-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvolume_robustness_test.py
246 lines (210 loc) · 9.22 KB
/
volume_robustness_test.py
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""
volume_robustness_test.py
Tests the robustness of the Volume strategy vs. two benchmarks (Market Only, Risk-Managed Market).
We vary:
1) Subperiods (start_date, end_date)
2) Volume windows (for the Volume strategy).
We skip the other strategies (Flattened, Leader) to focus on Volume's performance
vs. simple benchmarks.
Constraints:
- Start date cannot be before 2008-12-26
- End date cannot be after 2024-12-06
- We aim for enough subperiods + windows to generate ~3x or more runs than before.
Outputs:
- A CSV storing each test scenario’s results:
[start_date, end_date, volume_window,
strategy_name,
final_value, total_return,
annualized_return, max_drawdown, sharpe_ratio]
- No equity curves or daily timeseries.
Example usage:
python volume_robustness_test.py
"""
import logging
import os
import csv
import pickle
import pandas as pd
from pathlib import Path
import numpy as np
from config.settings import (
DATA_DIR, INITIAL_FUNDS, REBALANCE_FREQUENCY, MARKET_PROXY,
REPORT_DIR
)
from utils.logging_utils import configure_logging
from data.data_loaders import load_proxies, load_top_stocks, load_financials
from utils.calendar_utils import get_rebalance_dates
from utils.metrics import compute_performance_metrics
from backtesting.backtester import run_backtest
# Only import the three strategies we want to test
from strategies.strategy_definitions import (
market_only_strategy,
risk_managed_market_strategy,
volume_spy_strategy
)
# Enrichment utilities
from utils.enrichment_utils import enrich_with_L_and_volume, calculate_m
logger = logging.getLogger(__name__)
def main():
configure_logging()
logger = logging.getLogger(__name__)
try:
# 1) Load data once
proxies_df = load_proxies()
top_stocks_df = load_top_stocks()
financials_df = load_financials()
logger.info("Enriching proxies with M for risk-managed strategy.")
proxies_df = calculate_m(proxies_df)
sp500_snapshot_path = DATA_DIR / "sp_500_historic_snapshot.feather"
if not sp500_snapshot_path.exists():
logger.error(f"Missing file: {sp500_snapshot_path}. Exiting.")
return
sp500_snapshot_df = pd.read_feather(sp500_snapshot_path)
sp500_snapshot_df.dropna(subset=["date"], inplace=True)
sp500_snapshot_df["date"] = pd.to_datetime(sp500_snapshot_df["date"]).dt.normalize()
sp500_snapshot_df.set_index("date", drop=True, inplace=True)
sp500_snapshot_df.sort_index(inplace=True)
# The CSV we’ll write scenario results to
robustness_csv = REPORT_DIR / "volume_robustness_results.csv"
if robustness_csv.exists():
os.remove(robustness_csv)
# Write headers
with open(robustness_csv, mode="w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow([
"start_date", "end_date", "volume_window",
"strategy_name",
"final_value", "total_return",
"annualized_return", "max_drawdown", "sharpe_ratio"
])
# We only test 3 strategies
strategy_funcs = {
"market": market_only_strategy,
"risk": risk_managed_market_strategy,
"volume": volume_spy_strategy
}
strategies = list(strategy_funcs.keys()) # ["market", "risk", "volume"]
# 2) Define subperiods & volume windows (expanded for ~3x runs)
# Must remain within [2008-12-26, 2024-12-06].
subperiods = [
# Some early expansions
("2008-12-26", "2010-12-31"),
("2008-12-26", "2011-12-31"),
("2008-12-26", "2012-12-31"),
("2008-12-26", "2013-12-31"),
("2008-12-26", "2014-12-31"),
("2008-12-26", "2016-12-31"),
("2008-12-26", "2018-12-31"),
("2008-12-26", "2020-12-31"),
("2008-12-26", "2022-12-31"),
("2008-12-26", "2024-12-06"),
# Shifting starts
("2010-01-01", "2014-12-31"),
("2010-01-01", "2016-12-31"),
("2010-01-01", "2018-12-31"),
("2010-01-01", "2020-12-31"),
("2010-01-01", "2022-12-31"),
("2012-01-01", "2016-12-31"),
("2012-01-01", "2018-12-31"),
("2012-01-01", "2020-12-31"),
("2012-01-01", "2022-12-31"),
("2012-01-01", "2024-12-06"),
# More combos with later start
("2014-01-01", "2018-12-31"),
("2014-01-01", "2020-12-31"),
("2014-01-01", "2022-12-31"),
("2014-01-01", "2024-12-06"),
("2016-01-01", "2020-12-31"),
("2016-01-01", "2022-12-31"),
("2016-01-01", "2024-12-06"),
]
# Volume windows
log_min = np.log(20)
log_max = np.log(252)
log_windows = np.linspace(log_min, log_max, 21)
volume_windows = np.exp(log_windows).round().astype(int).tolist()
# We'll compute total runs for logging progress
total_scenarios = len(subperiods) * len(volume_windows)
runs_per_scenario = len(strategies) # 3
total_runs = total_scenarios * runs_per_scenario
run_count = 0
logger.info(f"Starting volume robustness tests with {len(subperiods)} subperiods, "
f"{len(volume_windows)} volume windows => {total_scenarios} scenarios, "
f"{total_runs} total runs (3 strategies each).")
# 3) For each subperiod + volume_window
scenario_index = 0
for (start_date, end_date) in subperiods:
market_df = proxies_df[proxies_df["ticker"] == MARKET_PROXY].copy()
rebalance_dates = get_rebalance_dates(
market_df,
REBALANCE_FREQUENCY,
start_date=pd.to_datetime(start_date),
end_date=pd.to_datetime(end_date)
)
if not rebalance_dates:
logger.warning(f"No rebalance dates for {start_date}..{end_date}, skipping.")
continue
scenario_index += 1
logger.info(f"=== Scenario {scenario_index}/{len(subperiods)}: {start_date}->{end_date} "
f"({len(rebalance_dates)} rebalances) ===")
for vwin in volume_windows:
logger.info(f"-- volume_window={vwin} --")
top_stocks_enriched = enrich_with_L_and_volume(
top_stocks_df=top_stocks_df.copy(),
market_proxy_df=market_df.copy(),
l_window=20,
volume_window=vwin
)
data_dict = {
"proxies_df": proxies_df,
"top_stocks_df": top_stocks_enriched,
"sp500_snapshot_df": sp500_snapshot_df
}
for strat_name in strategies:
run_count += 1
logger.info(f"Run {run_count}/{total_runs}: {strat_name} {start_date}->{end_date}, vwin={vwin}")
strat_func = strategy_funcs[strat_name]
hist = run_backtest(
strategy_func=strat_func,
proxies_df=proxies_df,
top_stocks_df=top_stocks_enriched,
rebalance_dates=rebalance_dates,
initial_funds=INITIAL_FUNDS,
data_dict=data_dict
)
final_val = hist["portfolio_value"].iloc[-1]
total_ret = (final_val / INITIAL_FUNDS) - 1.0
daily_returns = hist["portfolio_value"].pct_change().dropna()
if daily_returns.empty:
ann_ret = None
max_dd = None
sharpe = None
else:
mean_daily = daily_returns.mean()
ann_ret = (1 + mean_daily)**252 - 1
running_max = hist["portfolio_value"].cummax()
drawdowns = (hist["portfolio_value"] - running_max) / running_max
max_dd = drawdowns.min()
std_daily = daily_returns.std()
if std_daily > 0:
sharpe = (mean_daily / std_daily) * (252**0.5)
else:
sharpe = None
# Write row
with open(robustness_csv, mode="a", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow([
start_date, end_date, vwin,
strat_name,
f"{final_val:.2f}",
f"{total_ret:.4f}",
f"{ann_ret:.4f}" if ann_ret is not None else "",
f"{max_dd:.4f}" if max_dd is not None else "",
f"{sharpe:.4f}" if sharpe is not None else ""
])
logger.info(f"All scenario testing complete after {run_count} runs. Results => {robustness_csv}")
except Exception as e:
logger.error(f"Error: {e}", exc_info=True)
raise
if __name__ == "__main__":
main()