Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Live trading - initialize run daily - issues

If initialize is run daily, but I have a number of storage variables I declare in initialize that are initially empty and are filled from a monthly run function and used throughout the month by daily functions, won't the running of initialize wipe the storage variables?

How can I get around this?

Example:

def initialize(context):  
    # general parameters for portfolio  
    context.max_perc_holding = .1 # maximum % of portfolio to be allocated to any one position  
    context.stop_loss_open = -0.1 # % loss before stop loss is triggered  
    context.stop_loss_windowed = -0.05 # % loss before stop loss is triggered based on windowed return  
    context.hist_price = 5 # in calculating windowed stop loss, the number of days prior to the current day to use for % change in price  
    context.min_share_price = 10 # minimum dollar value of share price to be held (to avoid trading penny stocks)  
    context.months_before_buy = 6 # number of months to buy stock before event  
    context.months_before_sell = 2 # number of months to sell stock before event  
    context.to_buy = set() # set to hold equity objects to buy for portfolio  
    context.to_sell = set() # set to hold equity objects to sell for portfolio  
    context.do_not_buy = set() # once a stop loss is triggered the equity is added to the do not buy list for the subsequent month  
    # in live trading initialize is run daily  
    fetch_csv("XXX",  
        pre_func = reformat_post,  
        date_column = 'date')  
    schedule_function(get_data, date_rules.every_day(), time_rules.market_open(minutes = 80))  
    schedule_function(get_buy_sell_equities, date_rules.month_start(), time_rules.market_open(minutes = 85))  
    schedule_function(trade_rebalance, date_rules.every_day(),time_rules.market_open(minutes = 90))  

now won't the following be reset daily?

context.to_buy = set() # set to hold equity objects to buy for portfolio
context.to_sell = set() # set to hold equity objects to sell for portfolio
context.do_not_buy = set() # once a stop loss is triggered the equity is added to the do not buy list for the subsequent month

This is problematic because "get_buy_sell_equities" populates to_buy and to_sell monthly and adjusts them monthly.

"trade_rebalance" is run daily to ensure that any orders that were not complete the day before are re-submitted

1 response

Ok I fixed by declaring the "set" variables in the actual scheduled functions and by adding a few conditionals to the other dependent daily functions as shown below:

if "key" in context:
execute code

Would be nice if fetch_csv could be run outside of initialize, and initialize were truly run once as in the back tester - would make algos a bit easier to deploy.