TL;DR: I used backtrader boilerplate code with small adjustments to prepare a prototype that shows me the dates on which an indicator was triggered but it's not working. Please help!
Hi all,
Hope everyone is safe and healthy here. I am trying to build a backtest that makes trades based on how many days have passed since an indicator was triggered. In order to build this, I began by creating a simple prototype to ensure I am capturing these dates in the next()
method thats part of the strategy class.
Below you can find my code. I am just trying to get the Cerebro instance to print out the dates on which the indicator was triggered but am not getting the relevant output. I include my code below along with the output. I use python version 3.7.4 for this. Most of this was prepared using boilerplate code in the backtrader documentation.
Code:
#Import libraries
import numpy as np
import pandas as pd
import backtrader as bt
import backtrader.analyzers as btanalyzers
import matplotlib
from IPython.display import display, Image
from datetime import datetime
import yfinance as yf
import sys
#We instantiate a class used to inform QQQ call buying and selling
class LocalPeakStrategy(bt.Strategy):
#Hoping to log date in which local peaks are triggered
#We use this data to inform our actual buying
def log(self, dt=None):
dt = dt or self.datas[0].datetime.date(0)
print('%s' % (dt.isoformat()))
#We calculate different indicators/signals that inform buying/selling
def __init__(self):
local_peak_threshold = 0.08
one_day_rate_of_change =\
bt.ind.RateOfChange(period = 1)
two_day_rate_of_change =\
bt.ind.RateOfChange(period = 2)
three_day_rate_of_change =\
bt.ind.RateOfChange(period = 3)
if one_day_rate_of_change >= local_peak_threshold:
self.local_peak = one_day_rate_of_change
elif two_day_rate_of_change >= local_peak_threshold:
self.local_peak = two_day_rate_of_change
elif three_day_rate_of_change >= local_peak_threshold:
self.local_peak = three_day_rate_of_change
else:
self.local_peak = 0
#We tell backtrader when to buy and sell
def next(self):
#Testing to see if I can at least get the dates of when local peaks are set
if self.local_peak > 0:
self.log()
#Instantiate Cerebro object
cerebro = bt.Cerebro()
#Important relevant data
qqq = yf.Ticker("QQQ")
columns_to_use = ['Open', 'High', 'Low', 'Close', 'Volume']
df_qqq = qqq.history(period = 'max')[columns_to_use]
df_qqq['Open Interest'] = -1 #We are missing this data
#Add data feed
feed = bt.feeds.PandasData(dataname = df_qqq)
cerebro.adddata(feed)
#Set cash position and run
cerebro.broker.setcash(5000)
display(cerebro.run())
Output:
[<backtrader.strategy.Strategy at 0x7fdd236e5450>]
Any feedback deeply appreciated. Thanks for making this far.