Back to Community
Error Thrown By Older RSI Algo...

Hi all,

I've been meaning to play around with an RSI algo attempt posted a while back:

I had to make a few changes (see source) as context/data usage became different as the platform was upgraded...but I'm still getting an error and I'm a little confused why...

Any ideas?


Clone Algorithm
Total Returns
Max Drawdown
Benchmark Returns
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
    #we're going to use the SPY ETF here, but feel free to initiate with 
    #other securities - just change the sid number
    context.spy = sid(8554)
    #set min and max portfolio notionals
    context.max_notional = 1000000.1
    context.min_notional = -1000000.0
    #the RSI is calculated based on the security's returns over a set number 
    #of preceding observations.  Here we're setting up an array to collect the 
    #preceding 6 ticks to allow us to calc the preceding 5 period returns
    context.tick_history = [0, 0, 0, 0, 0, 0]

# Will be called on every trade event for the securities you specify. 
def handle_data(context, data):
    #set price variable
    price = data[context.spy].price
    #on each new tick we will insert the latest price into the array, extending its 
    #lenght by 1.  We'll then remove the oldest tick to return the array to its 
    #original length
    preceding_prices = context.tick_history
    #if there are enough prices in the array, let's go!
    if preceding_prices[len(preceding_prices)-1] <> 0:
        #create and populate an array of returns from our prices
        returns = [(preceding_prices[i-1]-preceding_prices[i]) for i in range(1,len(preceding_prices))]
        #create two empty arrays, one for up moves, one for down moves
        up = []
        down = []
        #pass through the array of returns and place them in the corresponding up 
        #and down move arrays
        for i in range(len(returns)):
            if returns[i] > 0:
            elif returns[i] <= 0:
        #handle empty arrays - empty arrays mean no average of returns possible
        if len(up) == 0:
            rsi = 0
        elif len(down) == 0:
            rsi = 100
        #the meat of the RSI calculation
            av_up = sum(up) / len(up)
            av_down = sum(down) / len(down)
            #some extra, probably uneccessary error handling avoidance
            if av_down == 0:
                rsi = 100
            elif av_up == 0:
                rsi = 0
            #final RSI calculation, setting the statistic to be between 0 and 100
                rs = av_up / av_down
                rsi = 100 - (100 / (1 + rs))
    #set default RSI for when we dont yet have enough price history
        rsi = 50
    #determine current notional of positions
    notional = context.portfolio.positions[context.spy].amount * price
    #some local debugging to monitor RSI levels
    log.debug('RSI is')
    #very un-imaginative trading strategy based around the observed RSI level
    if (rsi > 50) and notional > context.min_notional:
    elif (rsi < 50) and notional > context.min_notional:
There was a runtime error.
3 responses

Hello Alex,

I'n sure there are better solutions but you could try  




The problem is that it's having problems changing your integer to a string for logging. It works if you do it explicitly. Change line 76 from




For more readable logs, I'd combine lines 75 and 76 like this:
log.debug('RSI is: ' + str(rsi))


The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Ah simple enough, thanks.

I didn't realize it was something that simple causing the problem... when run step by step in isolation, this line was giving me problem (basically never ending)

        returns = [(preceding_prices[i-1]-preceding_prices[i]) for i in range(1,len(preceding_prices))]

but it seems to be fine now...