Back to Community
Problem: Using history function with alternating universe


We are currently trying to utilize the history function to get previous trading day's close price. However, our universe of SID's changes daily from a load using fetcher, and hence the same SID will NOT be in the universe two days in a row, which seems to make the history function fail miserably.

With a simple handle_data function doing nothing but


our algorithm fails if we do not have a fixed universe, e.g. by loading SID's using context.appl = sid(24) in our initialization.

How can we solve the problem?

1 response

If the fetcher has been properly setup then the stocks will have been loaded into your universe. You can then access it as:

    price_history = history(bar_count=2, frequency='1d', field='price', ffill=True)  
    for st in data:  
        prev_bar = price_history[st][-2]  
        curr_bar = price_history[st][-1]  

If you can't get it to work, check so that the stocks have been properly loaded into your universe, i.e:
for st in data: print st or something like that.

EDIT: Another really common mistake is to try to access data that doesn't exist. That will cause an error. Every stock doesn't trade every minute, that means that for some bars there's no price data. If you've only tried large stocks like appl manually and then import obscure companies you're bound to encounter such errors. Always check that the price data you try to grab actually exists. Example:
if 'price' in data[stock]: # Ok, it exists... Call history. That's not really related to the history function but perhaps you are comparing your historic values to the current value. What do I know.