Vectorized Pandas Trading Backtests
Backtesting Steps
- Download the Price Data
- Calculate Indicators
- Calculate Theoretical Weights
- Run Weights in a Backtest
The code that pulls all the above pieces together is given
import backtest as bt
import yahoo as yo
import indicators as id
import trend as td
tickers = ['AAPL' ,'MSFT']
df = yo.history(' '.join(tickers), '2000-01-01', '2025-12-31')
#features
id.returns(df, tickers, [1,-1,5,10])
id.moving_averages(df, tickers, [1,2,3,5,10,20,50,100,150,200,300])
id.volatilities(df, tickers, [3,5,10,20,100])
#calculate weights
td.moving_average(df, 'trend1', 'AAPL', 3, 200, 1, 0)
#calculate the NAV of the hypothetical trades
nav = bt.backtest(df,{"trend1:1"})
recs = df.to_dict(orient='records')