Untitled
unknown
plain_text
9 months ago
900 B
5
Indexable
import pandas as pd
import numpy as np
import yfinance as yf
import backtrader as bt
# Data Collection
data = yf.download('AAPL', start='2020-01-01', end='2023-01-01')
# Define Strategy
class SmaCross(bt.Strategy):
params = (('short_period', 10), ('long_period', 30),)
def __init__(self):
self.sma_short = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.short_period)
self.sma_long = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.long_period)
def next(self):
if not self.position:
if self.sma_short > self.sma_long:
self.buy()
else:
if self.sma_short < self.sma_long:
self.sell()
# Backtesting
cerebro = bt.Cerebro()
data_feed = bt.feeds.PandasData(dataname=data)
cerebro.adddata(data_feed)
cerebro.addstrategy(SmaCross)
cerebro.run()
cerebro.plot()Editor is loading...
Leave a Comment