@ Blue sorry that is the wrong code. Correct code that Is not working shown below:
import numpy as np
import scipy
import pandas as pd
from pytz import timezone
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume, Returns
from quantopian.pipeline.filters.morningstar import Q500US, Q1500US
from quantopian.pipeline.classifiers.morningstar import Sector
import datetime
def initialize(context):
context.target_leverage = 2
context.mx_lvrg = 0
context.cash_low = 0
set_slippage(slippage.FixedSlippage(spread=0))
#set_commission(commission.PerShare(cost=0, min_trade_cost=0.00))
context.xly = sid(19662) #Consumer Discretionary 102
context.xlp = sid(19659) #Consumer Staples 205
context.xle = sid(19655) #Energy 309
context.xlf = sid(19656) #Financials 103
#context.xlv = sid(19661) #Health Care 306
context.xli = sid(19657) #Industrials 310
context.xlb = sid(19654) #Materials 101
#context.xlre = sid(49472) #Real estate 104
context.xlk = sid(19658) #Technology 311
context.xlu = sid(19660) #Utilities 207
context.sectors = [context.xly,
context.xlp,
context.xle,
context.xlf,
# context.xlv,
context.xli,
context.xlb,
#context.xlre,
context.xlk,
context.xlu
]
context.sector_id = [102,
205,
309,
103,
#306,
310,
101,
#104,
311,
207
]
context.stock_long = []
context.stock_short = []
schedule_function(func = liquidate, date_rule = date_rules.week_end(0), time_rule = time_rules.market_close(minutes = 1))
schedule_function(func = place_order, date_rule = date_rules.week_start(0), time_rule = time_rules.market_open())
schedule_function(count_positions, date_rules.every_day(), time_rules.market_close())
attach_pipeline(make_pipeline(context), 'mean_reversion')
#set_long_only()
context.enable_short_stock = True
context.today_wd = 0
context.today_month = 0
def make_pipeline(context):
mask = Q500US()
#lb_13 = -Returns(window_length=13, mask=mask)
weekly_return = Returns(window_length=6, mask=mask)
pipe = Pipeline(
columns={
'weekly_return': weekly_return,
'sector': Sector(),
},
# combined_alpha will be NaN for all stocks not in our universe,
# but we also want to make sure that we have a sector code for everything
# we trade.
screen=weekly_return.notnull() & Sector().notnull(),
)
return pipe
def before_trading_start(context, data):
print get_datetime('US/Eastern')
context.prev_day_wd = context.today_wd
context.today_wd = get_datetime('US/Eastern').weekday()
#context.prev_day_month = context.today_month
#context.today_month = get_datetime('US/Eastern').month
if context.today_wd > context.prev_day_wd: # used to see if today is the first business day of the week; do nothing and return if it is NOT the week start
#if context.today_month == context.prev_day_month:
return
else: # if it is the first trading day of the week
# week start
trackSectorPerformance(context, data)
if context.bullishSectorReturn > 0 and context.bearishSectorReturn < 0:
getBelowAverageStocksInBestPerformingSector(context, data)
def trackSectorPerformance(context, data):
log.info("in trackSectorPerformance.")
# Rank sectors based on weekly return
prices = data.history(context.sectors, 'price', 7, '1d')[:-1]
daily_ret = prices.pct_change(5)[1:].as_matrix(context.sectors)
weekly_ret = daily_ret[4]
bull = sorted(range(len(weekly_ret)), key=lambda i: weekly_ret[i])[-1] # lambda used to sort weekly returns
context.bullishSector = context.sector_id[bull] # identify bullish sectors by ID
context.bullishSectorReturn = weekly_ret[bull] # identify weekly return for each bullish sector
print context.bullishSectorReturn
log.info(context.bullishSector)
context.bearishSectorReturn = -99
if context.enable_short_stock:
bear = sorted(range(len(weekly_ret)), key=lambda i: weekly_ret[i])[0] # lambda used to sort weekly returns
context.bearishSector = context.sector_id[bear] # identify bearish sectors by ID
context.bearishSectorReturn = weekly_ret[bear] # identify weekly return for each bearish sector
print context.bullishSectorReturn
log.info("Done trackSectorPerformance.")
def getBelowAverageStocksInBestPerformingSector(context, data):
log.info("in getBelowAverageStocksInBestPerformingSector.")
pipeline_data = pipeline_output('mean_reversion')
bullish_data = pipeline_data[pipeline_data['sector'] == context.bullishSector]
#Filter out above average return stocks
below_average_bullish_data = bullish_data[bullish_data['weekly_return'] < context.bullishSectorReturn]
below_average_bullish_data = below_average_bullish_data.sort_values(by = 'weekly_return')
context.stock_to_long = below_average_bullish_data.index[:]
stock_to_long_returns = below_average_bullish_data['weekly_return']
#Calculate weights based on returns
context.stock_to_long_weights = context.bullishSectorReturn - stock_to_long_returns
context.stock_to_long_weights = context.stock_to_long_weights.div(context.stock_to_long_weights.sum())
print context.stock_to_long_weights.sum()
if context.enable_short_stock:
bearish_data = pipeline_data[pipeline_data['sector'] == context.bearishSector]
#context.stock_to_short = bearish_data.sort_values(by = 'weekly_return').index[-3:]
#Filter out above average return stocks
above_average_bearish_data = bearish_data[bearish_data['weekly_return'] > context.bearishSectorReturn]
above_average_bearish_data = above_average_bearish_data.sort_values(by = 'weekly_return')
context.stock_to_short = above_average_bearish_data.index[:]
stock_to_short_returns = above_average_bearish_data['weekly_return']
#Calculate weights based on returns
context.stock_to_short_weights = stock_to_short_returns - context.bearishSectorReturn
context.stock_to_short_weights = context.stock_to_short_weights.div(context.stock_to_short_weights.sum())
log.info("done getBelowAverageStocksInBestPerformingSector.")
def place_order(context, data):
log.info("in place order.")
try:
if len(context.stock_to_long)>0:
for i in range(len(c.stock_to_long)):
val = context.target_leverage * context.stock_to_long_weights[i] * context.portfolio.cash
if context.account.leverage > .7: # in part avoiding divide by zero
val /= context.account.leverage
order_value(context.stock_to_long[i], val)
order_target_percent(context.stock_to_long[i], context.stock_to_long_weights[i])
context.stock_long = context.stock_to_long
context.stock_to_long = []
if context.enable_short_stock:
if len(context.stock_to_short)>0:
for i in range(len(context.stock_to_short)):
val = context.target_leverage * (-context.stock_to_short_weights[i] * context.portfolio.cash * .5) / (context.account.leverage)
if context.account.leverage > .7:
val /= context.account.leverage
order_value(context.stock_to_short[i], val)
order_target_percent(context.stock_to_short[i], -context.stock_to_short_weights[i])
context.stock_short = context.stock_to_short
context.stock_to_short = []
track_orders(context, data)
def liquidate(context, data):
log.info("in liquidate.")
try:
if len(context.stock_long)>0:
log.info("Liquidating longs.")
for i in range(len(context.stock_long)):
order_target_percent(context.stock_long[i], 0)
if context.enable_short_stock:
if len(context.stock_short)>0:
for i in range(len(context.stock_short)):
order_target_percent(context.stock_short[i], 0)
except KeyError as k:
# so what exactly is update_universe doing that I'm ending up here?
print(k)
# KEEP TRACK OF LEVERAGE BY SCHEDULING FUNCTION ASSIGNED ABOVE AS count_positions
def count_positions(context,data):
longs = 0
for position in context.portfolio.positions.itervalues():
if position.amount > 0:
longs += 1
leverage=context.account.leverage
# asset=context.portfolio.portfolio_value
# record(asset=asset)
record(longs=longs)
record(leverage=leverage)