# ========================================================================
# Core backtesting engine
# ========================================================================
def backtest_portfolio(prices, weights_func, rebal_freq='QS', name='Strategy',
start_date=None, end_date=None, drift=True):
"""Generic portfolio backtester.
Parameters
----------
prices : DataFrame
Daily adjusted close prices.
weights_func : callable(prices_history, current_date) -> dict
Returns target weights {ticker: weight}. Weights need not sum to 1;
residual goes to cash (return 0).
rebal_freq : str or None
Pandas offset alias for rebalancing dates: 'B' (every trading day),
'MS' (month start), 'QS' (quarter start), '6MS' (semi-annual), etc.
None = initial allocation only (buy-and-hold).
name : str
Strategy label for display.
start_date, end_date : str or None
Optional date filters.
drift : bool
True (default): between two rebalancing dates the weights follow the
prices, w_i <- w_i * (1 + r_i) / (1 + r_portfolio), as a portfolio
that holds shares does. False: the target weights are applied again
every day (the engine used before #24513, which rebalances daily
whatever rebal_freq says); kept as the non-regression witness.
Returns
-------
dict with keys: 'name', 'equity', 'returns', 'sharpe', 'cagr',
'max_dd', 'volatility', 'weights_history'
"""
p = prices.copy()
if start_date:
p = p[p.index >= start_date]
if end_date:
p = p[p.index <= end_date]
daily_ret = p.pct_change().fillna(0.0)
# Generate rebalancing dates (none after the initial allocation if rebal_freq is None)
if rebal_freq is None:
rebal_dates = pd.DatetimeIndex([])
else:
rebal_dates = pd.date_range(start=p.index[0], end=p.index[-1], freq=rebal_freq)
# Map to nearest trading days
rebal_dates = p.index[p.index.searchsorted(rebal_dates)]
rebal_dates = rebal_dates.unique()
# Track portfolio value
equity = pd.Series(index=p.index, dtype=float)
equity.iloc[0] = 1.0
current_weights = {}
weights_log = []
for i in range(1, len(p)):
date = p.index[i]
prev_date = p.index[i - 1]
day_ret = daily_ret.loc[date]
# Rebalance?
if date in rebal_dates or not current_weights:
history_up_to = p.loc[:prev_date]
new_w = weights_func(history_up_to, prev_date)
if new_w: # only update if function returns something
current_weights = dict(new_w)
weights_log.append((date, dict(current_weights)))
# Compute portfolio return for this day, with the weights held at the open
port_ret = 0.0
for ticker, w in current_weights.items():
if ticker in day_ret.index:
port_ret += w * day_ret[ticker]
# Cash portion earns 0 (simplification)
equity.iloc[i] = equity.iloc[i - 1] * (1.0 + port_ret)
# Drift: the weights follow the prices until the next rebalancing date
if drift and current_weights:
current_weights = {
ticker: w * (1.0 + (day_ret[ticker] if ticker in day_ret.index else 0.0))
/ (1.0 + port_ret)
for ticker, w in current_weights.items()
}
# Compute metrics
returns = equity.pct_change().dropna()
n_years = (p.index[-1] - p.index[0]).days / 365.25
cagr = (equity.iloc[-1] / equity.iloc[0]) ** (1.0 / n_years) - 1.0
vol = returns.std() * np.sqrt(252)
sharpe = (returns.mean() / returns.std()) * np.sqrt(252) if returns.std() > 0 else 0
drawdown = equity / equity.cummax() - 1.0
max_dd = drawdown.min()
return {
'name': name,
'equity': equity,
'returns': returns,
'sharpe': round(sharpe, 3),
'cagr': round(cagr * 100, 2),
'max_dd': round(max_dd * 100, 2),
'volatility': round(vol * 100, 2),
'weights_history': weights_log
}
def compare_results(results_list, show_best=True):
"""Print a comparison table of multiple backtest results."""
rows = []
for r in results_list:
rows.append({
'Strategy': r['name'],
'Sharpe': r['sharpe'],
'CAGR (%)': r['cagr'],
'MaxDD (%)': r['max_dd'],
'Vol (%)': r['volatility']
})
df = pd.DataFrame(rows).set_index('Strategy')
# Highlight best
print(df.to_string())
print()
if show_best:
best_sharpe = df['Sharpe'].idxmax()
print(f" >> Best Sharpe: {best_sharpe} ({df.loc[best_sharpe, 'Sharpe']})")
return df
def plot_equity_curves(results_list, title='Equity Curves'):
"""Plot equity curves for multiple strategies."""
fig, axes = plt.subplots(2, 1, figsize=(14, 10), gridspec_kw={'height_ratios': [3, 1]})
# Equity curves
ax1 = axes[0]
for r in results_list:
label = f"{r['name']} (S={r['sharpe']}, DD={r['max_dd']}%)"
ax1.plot(r['equity'], label=label, linewidth=1.2)
ax1.set_title(title, fontsize=14)
ax1.set_ylabel('Portfolio Value (normalized)')
ax1.legend(fontsize=9, loc='upper left')
ax1.grid(True, alpha=0.3)
# Drawdowns
ax2 = axes[1]
for r in results_list:
dd = r['equity'] / r['equity'].cummax() - 1.0
ax2.fill_between(dd.index, dd.values, alpha=0.3, label=r['name'])
ax2.set_title('Drawdowns', fontsize=12)
ax2.set_ylabel('Drawdown')
ax2.legend(fontsize=9, loc='lower left')
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
print("Backtesting engine loaded.")