Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to code for yesterday's value?

Hi,
I'm new so please go easy :) I've copied this code from the sample talib alogs using the stochastic indicator:

 # Iterate over our list of stocks  
    for stock in context.stocks:  
        current_position = context.portfolio.positions[stock].amount  
        slowk, slowd = talib.STOCH(hist['high'][stock],  
                                   hist['low'][stock],  
                                   hist['close'][stock],  
                                   fastk_period=5,  
                                   slowk_period=3,  
                                   slowk_matype=0,  
                                   slowd_period=3,  
                                   slowd_matype=0)

        # get most recent SSI value  
        slowk = slowk[-1]  
        slowd = slowd[-1]  

        # If either the slowk or slowd are less than 20, the stock is  
        # 'oversold,' a long position is opened if there are no shares  
        # in the portfolio.  
        if slowk < 20 and current_position <= 0 and data.can_trade(stock):  
            order_target_percent(stock, context.long_pct_per_stock)  

However, how can I call a previous day's value to compare to the current value? Thanks in advance!

7 responses
 slowk_yest = slowk[-2]  
 slowd_yest = slowd[-2]  

Thank you Vladimir. I did try that previously, but I got this error: IndexError: invalid index to scalar variable. I'm not sure how to fix it.

Santiago,

You may do this way.

Thank you once again. Any idea on why that error occurred when I tried your previous, simpler suggestion?

Just out of curiosity, for a leaner code, could I use something like this?

hist = data.history(context.spy, 'price', 20, '1d')  

Of course it would be for the stochasitcs indicator instead of price. But then could I call previous day's data like this?
slowk_yest = slowk[-2] slowd_yest = slowd[-2] I just don't know how to put it all together to ensure the syntax is correct.

Santiago,

You may use fast stochastic, it is working that way.

Or slow stochastic.