Hi,
I'm struggling to figure out what I'm missing with the order_target_percent function. When I run the following code, it seems to work correctly, oscillating between investing 100% in the ETF and 100% in cash (allowing for small amounts of extra cash because of fractional share issues etc.).
However, when I run the code with the two securities below, it sometimes "blows up," ordering stocks well in excess of 100% of the portfolio value and generating losses of almost 2000%. I had thought that the function would basically allocate a certain % of the total portfolio value between a list of securities, so I could (in theory) say order_target_percent(sid1, 0.5) on one sid and order_target_percent(sid2, 0.5) on the other and it would split the total value 50/50 between the two stocks, or alternatively say order_target_percent(sid1, 1) to put all money into that stock, or order_target_percent(sid1, 0) to sell off all interest in sid1.
Anyone know what I'm missing?
Thanks,
Andy
import talib
# Put any initialization logic here. The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
context.stocks = [ sid(8554), sid(27102) ]
context.longs = { }
# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
prices = history(50, '1d', 'price') # 50-day lookback window
for stock in context.stocks:
if context.longs.get(stock) is None:
context.longs[stock] = 0.0
price = data[stock].price
upper, middle, lower = talib.BBANDS(prices[stock], timeperiod=50, nbdevup=2, nbdevdn=2, matype=0)
upper, middle, lower = upper[-1], middle[-1], lower[-1] # latest b-band value
mavg200 = data[stock].mavg(200)
if price <= lower and price <= mavg200:
context.longs[stock] = 1.0
if price >= upper and price >= mavg200:
context.longs[stock] = 0.0
total_longs = sum(context.longs.values())
if total_longs > 0:
log.debug("total longs is {tl}".format(tl=total_longs))
record(cash=context.portfolio.cash)
for stock in context.stocks:
if total_longs <= 0:
order_target_percent(stock, 0.0)
else:
order_target_percent(stock, context.longs[stock] / total_longs)
log.debug("adjusting {s} to {p} percent".format(s=stock, p=100.0*context.longs[stock] / total_longs))