Vectorized Backtesting¶
Tip
This is a Jupyter Notebook, to accesss/download the ipynb
file, please click the github/download icon button in the top right corner.
import pfund as pf
from IPython.display import display
pf.__version__
'0.0.2'
Create backtest() in Strategy¶
backtest() in strategy is only used for vectorized backtesting, which is for strategy prototyping.
class DemoStrategy(pf.Strategy):
def backtest(self):
# NOTE: in the future, this dataframe will change depending on your chosen data tool, e.g. pandas, polars, pyspark etc.
# a dataframe with added data is prepared for you automatically
print(f'Printing dataframe of Strategy "{self.name}":\n')
display(self.df.head())
# TODO: fill in strategy logic
# TODO: show metrics using pyfolio
Workflow: engine -> strategy -> data -> run()¶
# Step 1. initialize backtest engine
engine = pf.BacktestEngine(mode='vectorized')
# Step 2. add strategy to engine
strategy = engine.add_strategy(DemoStrategy(), name='demo_strategy')
# Step 3. add data to strategy
## add yfinance data
'''
IB = Interactive Brokers
AAPL = Stock ticker for Apple Inc.
USD = Quote currency
STK = Stock
1d = 1-day data
'''
strategy.add_data(
'IB', 'AAPL', 'USD', 'STK', resolutions=['1d'],
backtest={
# NOTE: since IB does not provide any historical data for backtesting purpose, use data from 'YAHOO_FINANCE'
'data_source': 'YAHOO_FINANCE',
'start_date': '2024-01-01',
'end_date': '2024-02-01',
}
)
## add crypto data
'''
BYBIT = Bybit Cryptocurrency Exchange
BTC = Bitcoin
USDT = Tether
PERP = Perpetual (a trading product)
2d = 2-day data
'''
strategy.add_data(
'BYBIT', 'BTC', 'USDT', 'PERP', resolutions=['2d'],
backtest={
# NOTE: since BYBIT does provide historical data, no need to specify 'data_source'
# since it will be downloading data on the fly from https://public.bybit.com/trading/, only get a few dates of data
'start_date': '2024-01-01',
'end_date': '2024-01-02',
}
)
# Step 4. run engine
engine.run()
Warning
You can’t run engine.run() again since all the raw data have been erased. For some reason, if you want to get the df of the strategy, you can:
df = strategy.get_df()
df