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)