# %% Environment
#' Load Python packages. VectorBT records orders on the signal timestamp while using the next open as the execution price.
import numpy as np
import pandas as pd
import yfinance as yf
import vectorbt as vbt

# %% Universe & Parameters
#' Strategy specification implemented here: ADX(14), SMA(50), and SMA(200);
#' enter long when not held, ADX crosses above 20, close > SMA50, and SMA50 > SMA200;
#' exit when held and close < SMA50 or ADX crosses below 20.
symbols = ['SPY', 'QQQ', 'IWM', 'EFA', 'EEM', 'TLT', 'GLD', 'XLK', 'XLF', 'XLE']
start_date = '2021-10-07'
end_date = '2026-10-07'
init_equity = 100000.0
n_symbols = len(symbols)
slot_size = init_equity / n_symbols
adx_n = 14
sma_fast_n = 50
sma_slow_n = 200
transaction_cost_bps = 0.0005

parameter_table = pd.DataFrame({
    'parameter': ['symbols', 'start_date', 'end_date', 'init_equity', 'n_symbols', 'slot_size', 'adx_n', 'sma_fast_n', 'sma_slow_n', 'transaction_cost_bps'],
    'value': [', '.join(symbols), start_date, end_date, init_equity, n_symbols, slot_size, adx_n, sma_fast_n, sma_slow_n, transaction_cost_bps]
})
print(parameter_table)

# %% Data
#' Download each symbol individually, construct adjusted OHLC from Yahoo Adj Close, and stop if a split-like daily return remains.
end_download = (pd.Timestamp(end_date) + pd.Timedelta(days=1)).strftime('%Y-%m-%d')
frames = {}
for sym in symbols:
    raw = yf.download(sym, start=start_date, end=end_download, auto_adjust=False, progress=False)
    if raw.empty:
        raise ValueError(f'{sym} downloaded no rows')
    if isinstance(raw.columns, pd.MultiIndex):
        if 'Ticker' in raw.columns.names:
            raw = raw.xs(sym, axis=1, level='Ticker')
        else:
            raw = raw.droplevel(-1, axis=1)
    factor = raw['Adj Close'] / raw['Close']
    adj = pd.DataFrame(index=raw.index)
    adj['Open'] = raw['Open'] * factor
    adj['High'] = raw['High'] * factor
    adj['Low'] = raw['Low'] * factor
    adj['Close'] = raw['Adj Close']
    adj['Volume'] = raw['Volume']
    worst = adj['Close'].pct_change().abs().max()
    if worst > 0.40:
        raise ValueError(f'{sym} has a {worst * 100:.0f}% one-day move: likely an unadjusted split.')
    frames[sym] = adj

open_px = pd.DataFrame({sym: frames[sym]['Open'] for sym in symbols})
high_px = pd.DataFrame({sym: frames[sym]['High'] for sym in symbols})
low_px = pd.DataFrame({sym: frames[sym]['Low'] for sym in symbols})
close_px = pd.DataFrame({sym: frames[sym]['Close'] for sym in symbols})
close = close_px
volume = pd.DataFrame({sym: frames[sym]['Volume'] for sym in symbols})

# %% Portfolio Account & Strategy Setup
portfolio_st = 'adx_trend_emergence'
account_st = 'adx_trend_emergence_account'
strategy_st = 'adx_trend_emergence'

# %% Indicators
#' Compute ADX(14) using Wilder smoothing, along with SMA(50) and SMA(200).
def compute_adx(high, low, close, n=14):
    prev_close = close.shift(1)
    tr1 = high - low
    tr2 = (high - prev_close).abs()
    tr3 = (low - prev_close).abs()
    tr = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1)
    
    up_move = high - high.shift(1)
    down_move = low.shift(1) - low
    plus_dm = np.where((up_move > down_move) & (up_move > 0), up_move, 0.0)
    minus_dm = np.where((down_move > up_move) & (down_move > 0), down_move, 0.0)
    
    atr = tr.ewm(alpha=1.0/n, min_periods=n, adjust=False).mean()
    plus_di = 100.0 * pd.Series(plus_dm, index=close.index).ewm(alpha=1.0/n, min_periods=n, adjust=False).mean() / atr
    minus_di = 100.0 * pd.Series(minus_dm, index=close.index).ewm(alpha=1.0/n, min_periods=n, adjust=False).mean() / atr
    
    dx = 100.0 * (plus_di - minus_di).abs() / (plus_di + minus_di).replace(0, np.nan)
    adx = dx.ewm(alpha=1.0/n, min_periods=n, adjust=False).mean()
    return adx

adx_df = pd.DataFrame({sym: compute_adx(high_px[sym], low_px[sym], close_px[sym], adx_n) for sym in symbols})
sma50 = close_px.rolling(sma_fast_n, min_periods=sma_fast_n).mean()
sma200 = close_px.rolling(sma_slow_n, min_periods=sma_slow_n).mean()

# %% Signals
#' Build entry and exit signals from ADX crosses and moving average trend conditions.
adx_cross_up = (adx_df > 20.0) & (adx_df.shift(1) <= 20.0)
adx_cross_down = (adx_df < 20.0) & (adx_df.shift(1) >= 20.0)
close_above_sma50 = close_px > sma50
sma50_above_sma200 = sma50 > sma200
close_below_sma50 = close_px < sma50

entries = adx_cross_up & close_above_sma50 & sma50_above_sma200
exits = adx_cross_down | close_below_sma50

# %% Rules
#' Use next-open execution prices, one whole-share equal-dollar slot per symbol, long-only direction, no leverage, and transaction costs.
next_open = open_px.shift(-1)
entries = entries & next_open.notna()
exits = exits & next_open.notna()
entry_size = np.floor(slot_size / (next_open * (1.0 + transaction_cost_bps)))
entry_size = entry_size.where(entry_size >= 1, 0.0).fillna(0.0)

# %% Run the Backtest
#' Run the VectorBT portfolio with shared cash so the ten slots draw from one $100,000 account.
portfolio = vbt.Portfolio.from_signals(
    close=close_px,
    entries=entries,
    exits=exits,
    size=entry_size,
    size_type='amount',
    price=next_open,
    init_cash=init_equity,
    fees=transaction_cost_bps,
    direction='longonly',
    accumulate=False,
    cash_sharing=True,
    freq='1D'
)

# %% Idle Cash in Bonds
#' Cash not held in a position earns the return of the bond ETF (SHY).
bond_raw = yf.download('SHY', start=start_date, end=end_download, auto_adjust=False, progress=False)
if isinstance(bond_raw.columns, pd.MultiIndex):
    if 'Ticker' in bond_raw.columns.names:
        bond_raw = bond_raw.xs('SHY', axis=1, level='Ticker')
    else:
        bond_raw = bond_raw.droplevel(-1, axis=1)
bond_ret = (bond_raw['Adj Close'].pct_change()).reindex(portfolio.cash().index).fillna(0.0)

cash_series = portfolio.cash()
bond_value = max(cash_series.iloc[0], 0.0)
bond_earned = 0.0
bond_income = []
for i in range(1, len(cash_series)):
    inc = bond_value * bond_ret.iloc[i]
    bond_earned += inc
    bond_income.append(inc)
    bond_value = max(cash_series.iloc[i] + bond_earned, 0.0)

total_bond_earned = bond_earned
total_equity_with_bonds = portfolio.final_value() + total_bond_earned

cum_bond_inc = pd.Series([0.0] + bond_income, index=cash_series.index).cumsum()
equity = portfolio.value() + cum_bond_inc
returns = equity.pct_change().fillna(0.0)

print(f"Ending equity without bonds: ${portfolio.final_value():,.2f}")
print(f"Bond income on idle cash: ${total_bond_earned:,.2f}")
print(f"Ending equity with bonds: ${total_equity_with_bonds:,.2f}")
print(portfolio.stats())
