- Import Libraries
We want two libraries for this mission — VectorBT and datetime
.
import vectorbt as vbt
import datetime as dt
2. Set the Backtesting Window
Use the datetime
library to outline a testing interval beginning two years earlier than at present.
current_date = dt.datetime.now()
start_date = current_date - dt.timedelta(days=730)
3. Fetch Market Knowledge
Make the most of VectorBT’s obtain
methodology to retrieve historic worth knowledge. Right here’s how one can get day by day closing costs for the SPY ETF beginning two years in the past:
knowledge = vbt.YFData.obtain('SPY', interval='1d', begin=start_date).get('Shut')
4. Calculate Transferring Averages
VectorBT makes it straightforward to calculate technical indicators like shifting averages. Use the .run()
methodology to generate a 50-day (quick) and 100-day (gradual) shifting common.
fast_ma = vbt.MA.run(knowledge, 50)
slow_ma = vbt.MA.run(knowledge, 100)
5. Outline Entry and Exit Circumstances
Create entry alerts when the fast-paced common crosses above the gradual one, and exit alerts when it crosses beneath.
buy_signals = fast_ma.ma_crossed_above(slow_ma)
sell_signals = fast_ma.ma_crossed_below(slow_ma)
6. Set Up the Backtest
Use the Portfolio
class to combine alerts and simulate efficiency.
portfolio = vbt.Portfolio.from_signals(
knowledge,
buy_signals,
sell_signals,
init_cash=100,
freq='1d',
sl_stop=0.05,
tp_stop=0.2
)
7. Show Outcomes
Lastly, print key metrics and visualize the portfolio’s efficiency with an in depth chart:
print(portfolio.total_profit())
print(portfolio.stats())
portfolio.plot().present()