-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrun.py
More file actions
201 lines (160 loc) · 7.18 KB
/
Copy pathrun.py
File metadata and controls
201 lines (160 loc) · 7.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#!/usr/bin/env python3
"""CLI entry point for the quant trading system."""
import argparse
import logging
import sys
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from quant.utils.config import load_config
from quant.strategy import MultiFactorStrategy
def setup_logging(verbose: bool = False):
level = logging.DEBUG if verbose else logging.INFO
logging.basicConfig(
level=level,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
def _plot_backtest_result(result, args, default_filename: str = "backtest_results.png"):
"""Shared plotting logic for all backtest commands."""
if not args.plot:
return
fig, axes = plt.subplots(3, 1, figsize=(14, 10), sharex=True)
# Equity curve
ax = axes[0]
result.equity_curve.plot(ax=ax, label="Strategy", linewidth=1.5)
if not result.benchmark_curve.empty:
result.benchmark_curve.plot(ax=ax, label="Benchmark (SPY)", linewidth=1.5, alpha=0.7)
ax.set_title("Equity Curve")
ax.set_ylabel("Portfolio Value ($)")
ax.legend()
ax.grid(True, alpha=0.3)
# Drawdown
ax = axes[1]
peak = result.equity_curve.cummax()
dd = (result.equity_curve - peak) / peak
dd.plot(ax=ax, color="red", linewidth=1)
ax.fill_between(dd.index, dd.values, 0, alpha=0.3, color="red")
ax.set_title("Drawdown")
ax.set_ylabel("Drawdown")
ax.grid(True, alpha=0.3)
# Rolling Sharpe
ax = axes[2]
rolling_ret = result.returns.rolling(63).mean() * 252
rolling_vol = result.returns.rolling(63).std() * (252 ** 0.5)
rolling_sharpe = rolling_ret / rolling_vol
rolling_sharpe.plot(ax=ax, linewidth=1)
ax.axhline(0, color="black", linewidth=0.5)
ax.set_title("Rolling 3-Month Sharpe Ratio")
ax.set_ylabel("Sharpe")
ax.grid(True, alpha=0.3)
plt.tight_layout()
outfile = args.plot_output or default_filename
plt.savefig(outfile, dpi=150)
print(f"\nPlot saved to {outfile}")
def cmd_backtest(args):
"""Run a historical backtest with the multi-factor strategy."""
config = load_config(args.config)
strategy = MultiFactorStrategy(config)
result = strategy.run_backtest(start=args.start, end=args.end)
print(result.summary())
_plot_backtest_result(result, args, "backtest_results.png")
def cmd_backtest_lgbm(args):
"""Run a historical backtest with the LightGBM strategy."""
from quant.signals.lgbm_strategy import LGBMStrategy
config = load_config(args.config)
lgbm_params = {}
if args.num_leaves != 31:
lgbm_params["num_leaves"] = args.num_leaves
if args.learning_rate != 0.05:
lgbm_params["learning_rate"] = args.learning_rate
if args.n_estimators != 200:
lgbm_params["n_estimators"] = args.n_estimators
strategy = LGBMStrategy(
config,
train_window=args.train_window,
val_window=args.val_window,
pred_horizon=args.pred_horizon,
retrain_every=args.retrain_every,
turnover_penalty=args.turnover_penalty,
lgbm_params=lgbm_params if lgbm_params else None,
)
result = strategy.run_backtest(start=args.start, end=args.end)
print(result.summary())
_plot_backtest_result(result, args, "backtest_lgbm_results.png")
def cmd_backtest_ensemble_lgbm(args):
"""Run a historical backtest with the factor + LightGBM ensemble."""
from quant.strategy_ensemble import StrategyEnsemble
config = load_config(args.config)
ensemble = StrategyEnsemble(
config,
strategy_a_weight=args.weight_a,
strategy_b_weight=1.0 - args.weight_a,
consensus_boost=args.consensus_boost,
)
result = ensemble.run_backtest(start=args.start, end=args.end)
print(result.summary())
_plot_backtest_result(result, args, "backtest_ensemble_lgbm_results.png")
def cmd_signal(args):
"""Show current alpha signals for the universe."""
config = load_config(args.config)
strategy = MultiFactorStrategy(config)
print("Fetching data and computing signals...")
signals = strategy.get_current_signal()
print("\n" + "=" * 50)
print("CURRENT COMPOSITE ALPHA SIGNALS")
print("=" * 50)
for sym, score in signals.items():
bar = "+" * max(0, int(score * 10)) if score > 0 else "-" * max(0, int(-score * 10))
print(f" {sym:6s} {score:+.4f} {bar}")
print("=" * 50)
def main():
parser = argparse.ArgumentParser(
description="Quant Trading System - Medium-Term US Equities"
)
parser.add_argument("-c", "--config", default="config.yaml",
help="Path to config file")
parser.add_argument("-v", "--verbose", action="store_true")
sub = parser.add_subparsers(dest="command", help="Command to run")
# Backtest
bt = sub.add_parser("backtest", help="Run historical backtest")
bt.add_argument("--start", help="Start date (YYYY-MM-DD)")
bt.add_argument("--end", help="End date (YYYY-MM-DD)")
bt.add_argument("--plot", action="store_true", help="Generate performance plots")
bt.add_argument("--plot-output", help="Plot output filename")
bt.set_defaults(func=cmd_backtest)
# Backtest LightGBM
bt_lgbm = sub.add_parser("backtest-lgbm", help="Run LightGBM strategy backtest")
bt_lgbm.add_argument("--start", help="Start date (YYYY-MM-DD)")
bt_lgbm.add_argument("--end", help="End date (YYYY-MM-DD)")
bt_lgbm.add_argument("--plot", action="store_true", help="Generate plots")
bt_lgbm.add_argument("--plot-output", help="Plot output filename")
bt_lgbm.add_argument("--train-window", type=int, default=504, help="Training window days")
bt_lgbm.add_argument("--val-window", type=int, default=63, help="Validation window days")
bt_lgbm.add_argument("--pred-horizon", type=int, default=21, help="Prediction horizon days")
bt_lgbm.add_argument("--retrain-every", type=int, default=1, help="Retrain every N rebalances")
bt_lgbm.add_argument("--turnover-penalty", type=float, default=0.1, help="Turnover penalty weight")
bt_lgbm.add_argument("--num-leaves", type=int, default=31)
bt_lgbm.add_argument("--learning-rate", type=float, default=0.05)
bt_lgbm.add_argument("--n-estimators", type=int, default=200)
bt_lgbm.set_defaults(func=cmd_backtest_lgbm)
# Backtest ensemble (Factor + LightGBM)
bt_ens = sub.add_parser("backtest-ensemble-lgbm", help="Run factor+LightGBM ensemble backtest")
bt_ens.add_argument("--start", help="Start date (YYYY-MM-DD)")
bt_ens.add_argument("--end", help="End date (YYYY-MM-DD)")
bt_ens.add_argument("--plot", action="store_true", help="Generate plots")
bt_ens.add_argument("--plot-output", help="Plot output filename")
bt_ens.add_argument("--weight-a", type=float, default=0.5, help="Factor strategy weight")
bt_ens.add_argument("--consensus-boost", type=float, default=1.3, help="Consensus boost multiplier")
bt_ens.set_defaults(func=cmd_backtest_ensemble_lgbm)
# Signals
sig = sub.add_parser("signal", help="Show current alpha signals")
sig.set_defaults(func=cmd_signal)
args = parser.parse_args()
setup_logging(args.verbose)
if not args.command:
parser.print_help()
sys.exit(1)
args.func(args)
if __name__ == "__main__":
main()