Code
import numpy as np
import pandas as pd
import yfinance as yf
import vectorbt as vbtPython / VectorBT Research Notebook
Get the code: Download Strategy Code (.py) | Download Analysis Code (.py)
This notebook is a complete, executable Python replication of the strategy published at quantstr.at, built on VectorBT. Every number, table and chart below is produced by the Python code in this document at render time.
The strategy, as specified:
Trade SPY, QQQ, IWM, EFA, EEM, TLT, GLD, XLK, XLF, and XLE from 2021-10-07 to 2026-10-07 using a long-only ADX trend-emergence strategy with daily bars, signals evaluated on the close, next-open execution, no leverage, no shorting, and one equal-dollar slot per symbol based on starting equity of $100,000 divided by 10, using whole shares and no adding to an existing position. For each symbol, compute ADX(14), SMA(50), and SMA(200). Enter long when the symbol is not already held, ADX(14) crosses above 20 from at or below 20, the close is above the SMA(50), and the SMA(50) is above the SMA(200). Exit when the symbol is held and either the close falls below the SMA(50) or ADX(14) crosses below 20 from at or above 20.
Differences from the R report. The two engines are independent implementations. Small differences in results are expected: VectorBT sizes orders in fractional shares where the R report uses whole shares, and the two data libraries apply price adjustments separately.
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 vbtStrategy 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) parameter value
0 symbols SPY, QQQ, IWM, EFA, EEM, TLT, GLD, XLK, XLF, XLE
1 start_date 2021-10-07
2 end_date 2026-10-07
3 init_equity 100000.0
4 n_symbols 10
5 slot_size 10000.0
6 adx_n 14
7 sma_fast_n 50
8 sma_slow_n 200
9 transaction_cost_bps 0.0005
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_st = 'adx_trend_emergence'
account_st = 'adx_trend_emergence_account'
strategy_st = 'adx_trend_emergence'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()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_sma50Use 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 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'
)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())Ending equity without bonds: $107,140.31
Bond income on idle cash: $7,401.17
Ending equity with bonds: $114,541.48
Start 2021-10-07 00:00:00
End 2026-10-07 00:00:00
Period 1255 days 00:00:00
Start Value 100000.0
End Value 107140.305009
Total Return [%] 7.140305
Benchmark Return [%] 83.493562
Max Gross Exposure [%] 88.646048
Total Fees Paid 885.803213
Max Drawdown [%] 6.92649
Max Drawdown Duration 384 days 00:00:00
Total Trades 89
Total Closed Trades 89
Total Open Trades 0
Open Trade PnL 0.0
Win Rate [%] 46.067416
Best Trade [%] 20.069467
Worst Trade [%] -9.974391
Avg Winning Trade [%] 4.648782
Avg Losing Trade [%] -2.461014
Avg Winning Trade Duration 35 days 00:35:07.317073
Avg Losing Trade Duration 10 days 03:30:00
Profit Factor 1.608789
Expectancy 80.228146
Sharpe Ratio 0.538649
Calmar Ratio 0.292518
Omega Ratio 1.115709
Sortino Ratio 0.733605
Name: group, dtype: object
This section continues in the same Python session, reusing the data and portfolio built above.
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.index = pd.to_datetime(spy.index.date)
equity.index = pd.to_datetime(equity.index.date)
close.index = pd.to_datetime(close.index.date)
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)
basket_eq.index = pd.to_datetime(basket_eq.index.date)
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)}))
Final Equity Total Return %
Strategy 114499.0 14.50
SPY 189892.0 89.89
Equal-weight basket 184861.0 84.86
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()
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()
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()