I apologize for the somewhat sloppyness of this program. I'm trying to sell when the if statement says to. The print statements all run, the counter resets, but it never sells. Can anyone help me with this?
Also, some of the comments won't make sense. I'd just changed this from an SPY/GLD algorithm - which worked fine.
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume
from quantopian.pipeline.data.quandl import yahoo_index_vix as cboe_vix
def initialize(context):
#Called once at the start of the algorithm.
# Rebalance every day, 1 hour after market open.
schedule_function(my_rebalance, date_rules.every_day())
context.counter = 0
context.trades = 0 #will track how many times a buy signal is executed
context.days_invested = 0
pipe = Pipeline()
attach_pipeline(pipe, name='VIX_pipeline')
pipe.add(cboe_vix.close.latest, 'vix')
#Called every day before market open.
def before_trading_start(context, data):
context.VIX = pipeline_output('VIX_pipeline')
context.spy = sid(8554)
#context.GLD = sid(26807)
context.VIXY = sid(40669)
def my_rebalance(context,data):
#Execute orders according to our schedule_function() timing.
#If vix rises to 25 and portfolio is all cash, allocate entire portfolio to SPY long
if context.VIX.iloc[0,0] >= 25 and context.portfolio.positions[context.VIXY].amount == 0:
order_percent(context.VIXY, 1.0)
context.counter = 0
print("counter reset on buy order")
if context.VIX.iloc[0,0] < 25 and context.portfolio.positions[context.VIXY].amount > 0 and context.counter >= 15:
order_percent(context.VIXY, 0.0)
context.counter = 0
print("counter reset on sell order")
if context.portfolio.positions[context.VIXY].amount > 0:
context.days_invested = context.days_invested + 1
print("Days invested: " + str(context.counter))
print("VIX: " + str(context.VIX.iloc[0,0]))
print("Current position in VIXY: " + str(context.portfolio.positions[context.VIXY].amount))
context.counter = context.counter + 1
def handle_data(context,data):
#Called every minute.
pass