import backtrader as bt
import yfinance as yf
# Download data from yfinance
data = yf.download("AAPL", period="max")
# Convert the data to a Pandas DataFrame
data = pd.DataFrame(data)
# Convert the DataFrame to a PandasData object
data = bt.feeds.PandasData(dataname=data)
# Instantiate Cerebro with the downloaded data
cerebro = bt.Cerebro()
cerebro.adddata(data)
# Add the SMA indicators to Cerebro
cerebro.addindicator(bt.indicators.SimpleMovingAverage, period=30, plotname="sma30")
cerebro.addindicator(bt.indicators.SimpleMovingAverage, period=50, plotname="sma50")
# Create the strategy
class MyStrategy(bt.Strategy):
def start(self):
# Access the indicator values using the `lines` attribute
if self.lines["sma30"][0] > self.lines["sma50"][0]:
# Buy if not already in a position
if not self.position:
self.buy()
else:
# Sell if in a position
if self.position:
self.sell()
# Add the strategy to Cerebro
cerebro.addstrategy(MyStrategy)
# Run the backtest
cerebro.run()
TypeError: list indices must be integers or slices, not str
I tried dropping the plot labels from the indicators but the lines.sma30 and lines.sma50 are always trouble. I fear backtrader doesn't have a good tutorial online as YahooFinanceCSVData doesn't work actually, so I used yfinance.
YahooFinanceCSVDatafor download data from Yahoo Finance! is depreciated. You can download the data and save it to a csv file and use the method to load the data to cerebro.strategy()method is the main logic that contain everything related to your trade. Example:This will help you to access the indicator data.
Here is my example strategy in full form:
Feel free to use this as a blueprint to write your strategies.