# Analysis & validation code -- generic, reads the names left by the strategy code
# (symbols, start_date, end_date, init_equity, close, portfolio).

# %% Strategy vs. Benchmarks
#' The strategy against two passive benchmarks over the same window: SPY buy-and-hold and an
#' equal-weight buy-and-hold basket of the traded symbols.
import matplotlib.pyplot as plt

spy_data = vbt.YFData.download("SPY", start=start_date, end=end_date, missing_columns="nan")
spy = spy_data.get("Close")
spy = spy[spy.index.date >= pd.Timestamp(start_date).date()]
spy_eq = init_equity * spy / spy.iloc[0]
basket_eq = (init_equity / len(symbols)) * (close / close.iloc[0]).sum(axis=1)
comparison = pd.concat([equity.rename("Strategy"), spy_eq.rename("SPY"), basket_eq.rename("Equal-weight basket")], axis=1).dropna()

fig, ax = plt.subplots(figsize=(9, 4.5))
for col, color in zip(comparison.columns, ["#00E08F", "#8B5CF6", "#2563EB"]):
    ax.plot(comparison.index, comparison[col], label=col, color=color, lw=2)
ax.set_ylabel("Equity ($)"); ax.set_title("Strategy vs. Benchmark Equity Curves"); ax.legend(loc="upper left", frameon=False)
plt.show()
print(pd.DataFrame({"Final Equity": comparison.iloc[-1].round(0), "Total Return %": ((comparison.iloc[-1] / init_equity - 1) * 100).round(2)}))

# %% Drawdown
dd = (equity / equity.cummax() - 1) * 100
fig, ax = plt.subplots(figsize=(9, 3.5))
ax.fill_between(dd.index, dd.values, 0, color="#FF4D6A", alpha=0.35); ax.plot(dd.index, dd.values, color="#FF4D6A", lw=1.2)
ax.set_ylabel("Drawdown (%)"); ax.set_title("Strategy Drawdown")
plt.show()

# %% Portfolio Exposure Over Time
#' Mark-to-market share of equity held in positions.
exposure_pct = 100 * portfolio.asset_value(group_by=True) / equity
fig, ax = plt.subplots(figsize=(9, 3.5))
ax.plot(exposure_pct.index, exposure_pct.values, color="#2563EB", lw=1.4)
ax.set_ylabel("% of Equity Invested"); ax.set_title("Portfolio Exposure Over Time")
plt.show()

# %% Rolling 3-Month Sharpe
roll = returns.rolling(63).apply(lambda r: r.mean() / r.std() * np.sqrt(252), raw=True)
fig, ax = plt.subplots(figsize=(9, 3.5))
ax.plot(roll.index, roll.values, color="#8B5CF6", lw=1.4); ax.axhline(0, color="gray", ls="--", lw=1)
ax.set_ylabel("Annualized Sharpe"); ax.set_title("Rolling 3-Month Sharpe")
plt.show()
