Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
RSI and MA model

Hey guys, I am trying to make an RSI and MA model, using context world, to buy stocks that have an RSI under 20 and the price>MA. I am trying to use a loop to repeat the values looking for the RSI and MA. It is says my RSI is referenced before assignment. I do not believe I am finding the RSI correctly, or referencing it to my stocks in the universe.

How do I just share my code in Quantopian without a backtest?
here is my code:
import talib

def initialize(context):

set_universe(universe.DollarVolumeUniverse(floor_percentile=98.0, ceiling_percentile=100.0))

def handle_data(context, data):
buy=[]

for stock in data: #this represents a loop that will repeat looking for stocks.
prices = history(15, '1d', 'price') #using the price history of 15 days to find RSI
rsi= prices.apply(talib.RSI, timeperiod=14).iloc[-1] #trying to find RSI
rsi_significant=20
ma30=data[stock].mavg(30)
ma15=data[stock].mavg(15)

if ma15>ma30 and rsi<rsi_significant : #the MA15, is going to cross, while it is oversold.  
    buy.append(stock)  

count= len(buy) #this calculates the total number of securities that I can buy
if count == 0 : #if this equals 0, there are none I can buy.
for stock in data:
order_target_percent(stock,0.0) #buy nothing

else:
purchase=1/count # I am taking all the stocks that meet my requirements and dividing them up evenly.
for stock in data:
if stock in buy:
order_target_percent(stock,purchase)
log.info("buy the security" + str(stock))
else:
order_target_percent(stock,0)

6 responses

Could you try to format your code correctly in your post? You will have to highlight the code then click the "code sample" button ({}) in the editor. It's just a little tricky to get working with the lack of indentation here — then I can see if I can help you.

Disclaimer

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.

So my idea is too take the universe of stocks, upload the RSI from Talib, and use Moving Averages. When a stock is below the significant RSI and the moving averages cross it will buy a stock from the universe. That is what the count function is doing. I use a loop, I am unsure if that is necessary or not. The error is when I run it. " ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). There was a runtime error on line 18. "

There is an error on the previous backtest. View this code instead.

There is a better way to calculate RSI — see the example in our helps docs. The method you are using can work, but is less reliable. Good luck!

Oops! I checked the docs that Gus mentioned, and it shows the "prices.apply()" method that Quantdog is using.

This is what I use to get the most recent RSI value (I found it by copying others in these forums):

RSI = talib.RSI(prices[stock], 14)[-1]  

So it was killing it for the first year or so, and then it stopped making transactions. Is this algorithm performing no transactions during that period? I don't really believe that.