ekjotsingh commited on
Commit
0f6cbdf
·
verified ·
1 Parent(s): 98f3f06

Update backtest.py

Browse files
Files changed (1) hide show
  1. backtest.py +19 -6
backtest.py CHANGED
@@ -32,16 +32,27 @@ def backtest_engine():
32
  data = data.rename(columns=mapping)
33
  data = data.ffill().bfill()
34
 
35
- # Strategy: Monthly Momentum Rotation
36
- monthly_data = data.resample('M').last()
 
 
 
37
  momentum = monthly_data.pct_change(6) # 6-month momentum
38
 
39
  # Rank assets
40
  tradeable = ["NIFTY", "GOLD", "SILVER", "OIL"]
 
 
 
 
 
 
 
41
  ranks = momentum[tradeable].rank(axis=1)
42
 
43
  # Top 2 get 50% each
44
- target_weights = (ranks >= 3).astype(float) * 0.5
 
45
 
46
  # Shift to avoid look-ahead bias and align to daily
47
  daily_weights = target_weights.reindex(data.index).ffill().shift(1)
@@ -75,9 +86,11 @@ def backtest_engine():
75
  ax1.legend()
76
  ax1.set_title("Strategy vs Benchmark")
77
 
78
- ax2.stackplot(data.index, final_weights['NIFTY'], final_weights['GOLD'],
79
- final_weights['SILVER'], final_weights['OIL'], cash_weight,
80
- labels=['Nifty', 'Gold', 'Silver', 'Oil', 'Cash'], alpha=0.6)
 
 
81
  ax2.legend(loc='upper left', fontsize='small')
82
  ax2.set_title("Asset Allocation")
83
 
 
32
  data = data.rename(columns=mapping)
33
  data = data.ffill().bfill()
34
 
35
+ # --- FIX IS HERE ---
36
+ # Old: .resample('M') -> New: .resample('ME')
37
+ monthly_data = data.resample('ME').last()
38
+ # -------------------
39
+
40
  momentum = monthly_data.pct_change(6) # 6-month momentum
41
 
42
  # Rank assets
43
  tradeable = ["NIFTY", "GOLD", "SILVER", "OIL"]
44
+ # Ensure only existing columns are used (handling failed downloads)
45
+ tradeable = [t for t in tradeable if t in momentum.columns]
46
+
47
+ if not tradeable:
48
+ print("Error: No tradeable assets found.")
49
+ return None
50
+
51
  ranks = momentum[tradeable].rank(axis=1)
52
 
53
  # Top 2 get 50% each
54
+ # We check if rank is in top 2 (e.g. Rank 3 or 4 out of 4)
55
+ target_weights = (ranks >= (len(tradeable) - 1)).astype(float) * 0.5
56
 
57
  # Shift to avoid look-ahead bias and align to daily
58
  daily_weights = target_weights.reindex(data.index).ffill().shift(1)
 
86
  ax1.legend()
87
  ax1.set_title("Strategy vs Benchmark")
88
 
89
+ # Dynamic Stack Plot
90
+ ax2.stackplot(data.index,
91
+ *[final_weights[col] for col in tradeable],
92
+ cash_weight,
93
+ labels=tradeable + ['Cash'], alpha=0.6)
94
  ax2.legend(loc='upper left', fontsize='small')
95
  ax2.set_title("Asset Allocation")
96