Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help with adding VIX price as a signal to not trade

This may come easy to some of you, but I am new and trying to learn by reading the tuts and editing code. I am trying to figure out how to import vix price and set it to not trade once vix hits a certain price. This is the original code that I am trying to add to. I might have a slight idea of it, but I don't want to screw it up and start of learning the wrong way. Any help or direction is appreciated, thanks!

Credit Peter Bakker for this original and Eric Tjossem edit.

import numpy as np  
import math  
from pytz import timezone  
import datetime  
from sqlalchemy import or_  
import scipy.stats as stats  
import talib as ta

def initialize(context):  
    set_symbol_lookup_date('2016-05-01')  
    log.info(get_environment('arena'))  
    if get_environment('arena') == 'backtest':  
        context.backtest_mode = True  
        log.info('We are backtesting.')  
    else:  
        context.backtest_mode = False  
    # Keeping track of the last sale that you have.  
    context.last_sale = None  
    context.stocks = ''  
    context.spy = symbol('SPY')  
    context.sh = symbol('SH')  
    context.assets = [context.spy]  
    context.history_close = None  
    context.history_max  = None  
    context.history_min  = None  
    context.lookback = 62  
    context.smoothing = 40 #40 is standard  
    context.holdtilpositive = False  
    context.holdtilnegative = False  
    context.buytomorrow = False  
    context.threshold = 0.0035 #5% is standard  
    context.hilo_index = []  
    context.hilo_MAindex = []  
    context.slope_index = []  
    context.spyslope_index = []  

    context.current_hilo = -10  
    context.m = len(context.stocks)  
    context.b_t = np.ones(context.m) / context.m  
    context.eps = 0.75 # change epsilon here  
    context.init = False  
    context.previous_datetime = None  
    #for making the history available in before trade start:  
    schedule_function(Algo_hilo, date_rule=date_rules.every_day(),  
                      time_rule=time_rules.market_close(minutes=5))

    # schedule_function(daily, date_rule=date_rules.week_start(2),  
    #                   time_rule=time_rules.market_open(minutes=30)  
    # Set a trading guard that will prevent any short positions  
    # from being placed. This is to insure that algorithms that  
    # depend on short positions are not accidently deployed.  
    set_long_only()  

def handle_data(context, data):  
    # Because most Robinhood accounts are cash accounts,  
    # trades(and most other brokerages) settle  
    # on a T+3 settlement date. This snippet of code prevents  
    # a trade from happening when you still have unsettled cash  
    # by checking if total cash (settled & unsettled) matches your  
    # settled cash amount.

    # [IMPORTANT] During backtests, `settled_cash` will always equal  
    # `cash`. In order to simulate a similar check, please also  
    # incorporate `simulate_cash_settlement` in handle data as you will  
    # see in this algorithm.  
    # For live trading only:  
    # if do_unsettled_funds_exist(context):  
        # return

    # `cash_settlement_date` simulates a T+3 settlement date. This  
    # should be used at the beginning of any handle_data or method  
    # used for schedule_function that places orders. At the end of  
    # of that method should be `check_last_sale`. Only for  
    # backtesting purposes!  
    # `check_last_sale` is what `cash_settlement_date` needs in  
    # order to work properly. Only for backtesting purposes!  
    pass

def do_unsettled_funds_exist(context):  
    """  
    For Robinhood users. In order to prevent you from attempting  
    to trade on unsettled cash (settlement dates are T+3) from  
    sale of proceeds. You can use this snippet of code which  
    checks for whether or not you currently have unsettled funds  
    To only be used for live trading!  
    """  
    if context.portfolio.cash != context.account.settled_cash:  
        return True

def check_last_sale(context):  
    """  
    To be used at the end of each bar. This checks if there were  
    any sales made and sets that to `context.last_sale`.  
    `context.last_sale` is then used in `cash_settlement_date` to  
    simulate a T+3 Cash Settlement date  
    To only be used for backtesting!  
    """  
    open_orders = get_open_orders()  
    most_recent_trade = []  
    # If there are open orders check for the most recent sale  
    if open_orders:  
        for sec, order in open_orders.iteritems():  
            for oo in order:  
                if oo.amount < 0:  
                    most_recent_trade.append(oo.created)  
    if len(most_recent_trade) > 0:  
        context.last_sale = max(most_recent_trade)  
def cash_settlement_date(context):  
    """  
    This will simulate Robinhood's T+3 cash settlement. If the  
    most recent sale is less than 3 trading days from the current  
    day, assume we have unsettled funds and exit  
    To only be used for backtesting!  
    """  
    if context.last_sale and (get_datetime() - context.last_sale).days < 3:  
        return True

def Algo_hilo(context, data):  
    cash = context.portfolio.cash  
    leverage = context.account.leverage  
    context.history_close = data.history(context.assets, 'price', 202, '1d')  
    #Calc spy slope  
    x1 = list(xrange(22))  
    spyslope, spyintercept, psyr_value, spyp_value, spystd_err = stats.linregress(x1,context.history_close[context.spy][-22:])  
    context.spyslope_index.append(spyslope)  
    #Calc zscore of spy slope  
    z_spyslope= stats.zscore(context.spyslope_index, axis=0, ddof=1)[-1]  
    accspyslope = 0  
    #Calc accelleration of spy  
    if len(context.spyslope_index) > 5:  
        x2 = list(xrange(5))  
        accspyslope, accspyintercept, accpsyr_value, accspyp_value, accspystd_err = stats.linregress(x2,context.spyslope_index[-5:])  
    #Calc long and short mavg spy  
    mavg_short = np.mean(context.history_close[context.spy][-22:])  
    mavg_med = np.mean(context.history_close[context.spy][-122:])  
    mavg_long = np.mean(context.history_close[context.spy][-200:])  
    current_price = context.history_close[context.spy][-1]  
    #get maxes and minimums  
    context.history_max = context.history_close.idxmax(axis=0, skipna=True)  
    context.history_min = context.history_close.idxmin(axis=0, skipna=True)  
    minctr = 0  
    maxctr = 0  
    stockctr = len(context.history_close.columns)  
    #find number of hi's and Lows  
    for stock in context.history_max.index:  
        datemax = context.history_max[stock]  
        if str(type(datemax))=="<class 'pandas.tslib.Timestamp'>" and datemax.date() == get_datetime().date(): maxctr += 1  
    for stock in context.history_min.index:  
         datemin = context.history_min[stock]  
         if str(type(datemin))=="<class 'pandas.tslib.Timestamp'>" and datemin.date() == get_datetime().date(): minctr += 1  
    hi = float(maxctr)/stockctr  
    lo = float(minctr)/stockctr  
    ratio = (float(maxctr - minctr))/stockctr  
    context.hilo_index.append(ratio)  
    #calc zscore of ratio  
    z_ratio= stats.zscore(context.hilo_index[-context.smoothing:], axis=0, ddof=1)[-1]  
    ma_ratio = np.mean(context.hilo_index[-context.smoothing:])  
    context.hilo_MAindex.append(ma_ratio)  
    context.current_hilo = ratio  
    #calc slope of MA HiLo index  
    if len(context.hilo_MAindex)> 7:  
        x = list(xrange(7))  
        slope, intercept, r_value, p_value, std_err = stats.linregress(x,context.hilo_MAindex[-7:])  
    else:  
        slope = 0  
        p_value =0  
    context.slope_index.append(slope)  
    if len(context.slope_index) > 7:  
        slope_ma = np.mean(context.slope_index[-7:])  
    else:  
        slope_ma = 0  


    if mavg_long > current_price:  
        record(mavg_long_vs_price=-1)  
    else:  
        record(mavg_long_vs_price=1)  
    if context.holdtilpositive:  
        record(holdtilpositive= 1)  
    elif context.holdtilnegative:  
        record(holdtilpositive= -1)  
    else:  
        record(holdtilpositive=0)  
    record(zspyslope = z_spyslope)  
    record(zratio_hi_lo = z_ratio)  
    record(slopespy = spyslope)  
    if (spyslope > 0 and slope_ma > 0) and context.holdtilpositive:  
        context.holdtilpositive = False  
    elif spyslope < 0 and context.holdtilnegative:  
        context.holdtilnegative = False  

    no_spys = context.portfolio.positions[context.spy].amount  
    if context.buytomorrow:  
        order_target_percent(context.sh, 0)  
        order_target_percent(context.spy, 1)  
        context.buytomorrow = False  
        return  
    if  z_spyslope > 0:  
        if no_spys==0: log.info('Buying: z score of the Slope of SPY over 22 days > 0: we are moving up')  
        context.buytomorrow = True #Buy with delay of 1 day  
        context.holdtilnegative = True  
        return  
    elif  z_spyslope < -.7:  
        if no_spys==0: log.info('Buying: z score of the Slope of SPY over 22 days < -0.7: mean reverting')  
        order_target_percent(context.sh, 0)  
        order_target_percent(context.spy, 1)  
        context.holdtilpositive = True  
        return  
    elif (z_spyslope < 0 and not context.holdtilpositive) or mavg_long > current_price or (z_spyslope > 1.0 or z_ratio > 1.5):  
        if no_spys>0:  
            if mavg_long > current_price:  
                log.info('Selling: price below Long mavg 122 days')  
                order_target_percent(context.sh, 1)  
            if z_spyslope > 1.0:  
                log.info('Selling: z score of the Slope of SPY over 22 days > 1.0')  
                order_target_percent(context.sh, 1)  
            if z_ratio > 1.5:  
                log.info('Selling: z score of the Ratio HILO of SPY over 22 days > 1.5')  
                order_target_percent(context.sh, 1)  
            if z_spyslope < 0 and not context.holdtilpositive: log.info('Selling: z score of the Slope of SPY over 22 days < -0.0 and not holding till positive')  
        order_target_percent(context.spy, 0)  
        return  
    return