For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
Check if ticker tradeable before all datafeeds are available
-
Hi, community,
I have a Buy&Hold strategy which keeps the same portfolio weight during the whole strategy life. However, I want to start a strategy before all data feeds available. For example:
Allocation SPY - 50% and TLT -50%- SPY is available on 01-01-1990
- TLT is available after 2004
So in this situation, before 2004, I want to adjust allocation to SPY - 100% and once TLT is available, then use target allocation: SPY - 50% and TLT -50%
Below is a strategy I refer to. Do you know how to check if ticker is available for a given date. I think the best option is to implement such check during
prenext
callimport strategies import logging import backtrader as bt from datetime import datetime import sys logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s/%(funcName)s - %(levelname)s - %(message)s', datefmt='%Y-%b-%d %H:%M:%S', stream=sys.stdout) logger = logging.getLogger(__name__) class BuyHold(bt.Strategy): params = dict(allocation=None, rebalance_frequency=None) def __init__(self): self.allocation = self.params._get('allocation') logger.info(f'Set portfolio allocation to {self.allocation}') print('Date during init', self.data.datetime.datetime().date()) for d in self.datas: print(f"stock: {d._name}, length: {len(d.array)}") def prenext(self): self.tradable_allocation() self.next() def tradable_allocation(self): tradable_alloc = dict() # for ticker in self.allocation: # if ticker is NOT tradable, then allocate asset weight to other ticker self.allocation = tradable_alloc def start(self): self.val_start = self.broker.get_cash() logger.info(f'Starting Portfolio Value: {self.broker.getvalue():.2f}') def next(self): for ticker in self.allocation: logger.debug(f'Execute Rebalance for {ticker} to {self.allocation[ticker]} allocation.') self.order_target_percent(ticker, target=self.allocation[ticker]) self.allocation = self.params._get('allocation') # Reset allocation on each step def stop(self): logger.info(f'Final Portfolio Value: {self.broker.getvalue():.2f}') START_CASH = 10000.0 START_DATE = datetime(year=1990, month=12, day=2) END_DATE = datetime(year=2005, month=12, day=31) weights = dict(SPY=0.5, TLT=0.5) if __name__ == '__main__': cerebro = bt.Cerebro() for ticker in weights: data = bt.feeds.YahooFinanceData(dataname=ticker, fromdate=START_DATE, todate=END_DATE) cerebro.adddata(data) cerebro.broker.setcash(START_CASH) # Run over everything cerebro.addstrategy(BuyHold, allocation=weights) results = cerebro.run()
-
I found a way to check if data is available for a given date.
data = self.getdatabyname(ticker) current_date = self.data.datetime.datetime().date() if date == bt.num2date(data.datetime[0]).date(): print(f'data is available for {ticker}')