the securities you get are quite excotic at times so you have to check their existence in data and if you want to be thorough wether price exists in data[stock]
This works for me
import pytz
import talib
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
def initialize(context):
context.stocks = []
set_universe(universe.DollarVolumeUniverse(floor_percentile=80.0 ,ceiling_percentile=82.5))
context.other_stocks = symbols('AET', 'AMGN', 'ADI', 'CSCO', 'IP', 'KMB', 'PRU', 'PEG', 'SLB', 'SYK', 'SPY')
context.nogo = ['SSO']
context.testStopday = None
context.StocksToOrder = 15.0
context.StocksToKeep = 30.0
context.rebalance_interval = 200
context.time_steps = 0
def handle_data(context, data):
priceHistory = history(90, '1d', 'price')
last_5_day_mean = priceHistory.tail(5).mean()
last_10_day_mean = priceHistory.tail(10).mean()
last_30_day_mean = priceHistory.tail(30).mean()
last_90_day_mean = priceHistory.tail(90).mean()
CurrentPrice = priceHistory.tail(1).mean()
diff_30_90 = (last_30_day_mean - last_90_day_mean)/ CurrentPrice
diff_10_30 = (last_10_day_mean - last_30_day_mean) / CurrentPrice
diff_5_30 = (last_5_day_mean - last_30_day_mean) / CurrentPrice
longs_30_90 = diff_30_90[diff_30_90 > 0.01]
longs_10_30 = diff_10_30[diff_10_30 > 0.01]
longs_5_30 = diff_5_30[diff_5_30 > 0.01]
if longs_30_90 is not None and longs_10_30 is not None:
longsIndex = longs_30_90.index.intersection(longs_10_30.index)
longsSeries = longs_10_30[longsIndex]
#eliminate stocks that are no longer traded...
for stock in longsSeries.index:
if stock.security_end_date < get_datetime():
if stock.symbol not in context.nogo:
context.nogo.append(stock.symbol)
longsSeries.sort(ascending=False) #
keepsSeries = longsSeries
longsSeries_length = min(context.StocksToOrder, len(longsSeries))
keepsSeries_length = min(context.StocksToKeep, len(keepsSeries))
longs_weight = 1.0 / longsSeries_length if longsSeries_length != 0 else 0
keeps_weight = 1.0 / keepsSeries_length if keepsSeries_length != 0 else 0
longsSeries = longsSeries.iloc[:longsSeries_length] if longs_weight != 0 else None
keepsSeries = keepsSeries.iloc[:keepsSeries_length] if keeps_weight != 0 else None
#----------------------------------------------------------------------------------------------------------------------
open_orders = get_open_orders()
Long_counter = 0.0
#print context.portfolio.positions[data].sid
if longsSeries is not None and not open_orders:
if len(context.portfolio.positions) != 0:
for stock in context.portfolio.positions:
if context.portfolio.positions[stock].amount > 0:
Long_counter = Long_counter + 1
#log.info( 'long {A}; Shares {B}; price {C}'.\
# format(A=stock, B =context.portfolio.positions[stock].amount, C=data[stock].price))
if stock not in longs_10_30:
if stock.symbol not in context.nogo:
order_target_percent(stock, 0)
Long_counter = Long_counter -1
currPrice = context.portfolio.positions[stock].last_sale_price
costBasis = context.portfolio.positions[stock].cost_basis
changePct = currPrice/costBasis - 1
if changePct < -0.05 and stock in data and 'price' in data[stock]:
order_target_percent(stock, 0)
Long_counter = Long_counter -1
context.nogo.append(stock.symbol)
for stock in longsSeries.index:
if stock not in context.portfolio.positions:
if Long_counter < context.StocksToOrder:
if stock is not symbol('SPY'):
if stock.symbol not in context.nogo and stock in data and 'price' in data[stock]:
order_target_percent(stock, 1.0/context.StocksToOrder)
Long_counter = Long_counter + 1
context.time_steps = context.time_steps + 1
if context.time_steps == context.rebalance_interval :
context.time_steps = 0
order_target_percent(symbol('SPY'), - Long_counter / context.StocksToOrder)
#----------------------------------------------------------------------------------------------------------------------
'''
this is a logic to have the algo to stop at a certain date.
'''
if context.testStopday == None:
context.testStopday = get_datetime()
# in case skipping holidays
if context.testStopday < get_datetime():
context.testStopday = get_datetime()
if get_datetime() == context.testStopday:
context.testStopday = context.testStopday + timedelta(days = 97)
'''
context.stocks = [str(sid.symbol) for sid in data]
print ', '.join(context.stocks)
'''
if context.testStopday.weekday()==4:
context.testStopday = context.testStopday + timedelta(days = 3)
else:
context.testStopday = context.testStopday + timedelta(days = 1)
#----------------------------------------------------------------------------------------------------------------------
#record(NXPI_diff_10_30 = diff_10_30[symbol('JUNO')])
#record(changePct = context.portfolio.positions[stock].last_sale_price/costBasis = context.portfolio.positions[stock].cost_basis - 1)
#----------------------------------------------------------------------------------------------------------------------
#this needs to executed at the very first time...
if len(context.portfolio.positions) == 0:
for stock in data:
# If the security instead exists in buys index, buy
if longsSeries is not None and stock in longsSeries.index:
if stock is not symbol('SPY'):
order_target_percent(stock, 1.0/context.StocksToOrder)