Untitled
unknown
plain_text
a month ago
1.3 kB
2
Indexable
Never
import backtrader as bt import datetime import yfinance as yf # Create a strategy class class SmaCross(bt.Strategy): params = ( ('short_period', 10), ('long_period', 30), ) def __init__(self): # Define the two SMAs self.short_sma = bt.indicators.SimpleMovingAverage( self.data.close, period=self.params.short_period) self.long_sma = bt.indicators.SimpleMovingAverage( self.data.close, period=self.params.long_period) def next(self): # Buy condition if self.short_sma > self.long_sma and not self.position: self.buy() # Sell condition elif self.short_sma < self.long_sma and self.position: self.sell() # Create a Cerebro engine instance cerebro = bt.Cerebro() # Fetch data from Yahoo Finance data = bt.feeds.PandasData( dataname=yf.download('AAPL', '2023-01-01', '2024-01-01')) # Add the data and strategy to Cerebro cerebro.adddata(data) cerebro.addstrategy(SmaCross) # Set the starting cash cerebro.broker.setcash(10000.0) # Run the strategy print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue()) cerebro.run() print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue()) # Plot the results cerebro.plot()
Leave a Comment