Skip to content

Instantly share code, notes, and snippets.

@alxfordy
Last active May 10, 2022 09:51
Show Gist options
  • Save alxfordy/f0c9394006701fbcc6175954095023ba to your computer and use it in GitHub Desktop.
Save alxfordy/f0c9394006701fbcc6175954095023ba to your computer and use it in GitHub Desktop.
Running Backtrader
import backtrader as bt
import yfinance as yf
def get_yf_data(ticker="BTC-USD", interval="1d", period="max", **kwargs):
"""
A function that returns a Backtrader data feed using Yahoo Finance API
Parameters
--------------------------------------
ticker - Yahoo Finance Ticket to fetch
interval - Interval defined by yfinance docs
period - Time period of return as defined by yfinance
kwargs - Further key word arguments for yfinance history interaction
"""
ticker_yf = yf.Ticker(ticker)
hist = ticker_yf.history(period=period, interval=interval, kwargs)
hist.ffill(inplace=True)
return bt.feeds.PandasData(dataname = hist)
class ComissionInfo(bt.CommissionInfo):
"""
Commission Object mainly used to define getsize
getsize allows for the buying or selling of fractional shares
"""
params = (
("commission", 0.00075),
("margin", None),
("commtype", None)
)
def getsize(self, price, cash):
"""Returns fractional size for cash operation @price"""
return self.p.leverage * (cash / price)
class CashMarket(bt.analyzers.Analyzer):
"""
Analyzer returning a dict of account value
"""
def create_analysis(self):
self.rets = {}
def notify_cashvalue(self, cash, value):
total = cash + value
self.rets[self.strategy.datetime.datetime()] = math.floor(total)
def get_analysis(self):
return self.rets
data = get_yf_data()
cerebro = bt.Cerebro()
# Add Data and Strategy to the bt instance
cerebro.adddata(data)
cerebro.addstrategy(DollarCostAverage)
# Add TimeReturn and our own Cash Market Analyser, cerbero returns these as a list
# results.analyzer[]
ankwargs = dict(timeframe=bt.TimeFrame.Years)
cerebro.addanalyzer(bt.analyzers.TimeReturn, fund=True, **ankwargs)
cerebro.addanalyzer(CashMarket)
## Add Comm for fractional shares
cerebro.broker.addcommissioninfo(ComissionInfo())
# Set our starting cash on the account
cerebro.broker.set_cash(1000)
results = cerebro.run()
cerebro.plot(iplot=False, style='candlestick')
return results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment