I am fairly new to both python and Quantopian, but decided to try an algorithm centered on the RSI. Any suggestions on improving the algorithm, or corrections to any errors are much appreciated.
# Put any initialization logic here. The context object will be passed to
# the other methods in your algorithm.
import talib
import numpy as np
import math
def initialize(context):
context.security = symbol('SWKS')
context.LOW_RSI = 45
context.HIGH_RSI = 70
# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
price = data[context.security].price
prices = history(15, '1d', 'price')
# Use pandas dataframe.apply to get the last RSI value
rsi_data = prices.apply(talib.RSI, timeperiod=14,).iloc[-1]
sec_rsi = rsi_data[context.security]
cash = context.portfolio.cash
#RSI over 70 indicates overbought, time to sell
if sec_rsi<context.LOW_RSI and cash>price:
shares_bought = int(cash/price)
order(context.security, +shares_bought)
log.info('Buying %s shares of %s' %(shares_bought, context.security.symbol))
#RSI under 30 indicates oversold, time to buy
elif sec_rsi>context.HIGH_RSI:
order_target(context.security, 0)
log.info('Selling %s' %(context.security.symbol))
record(secRSI=sec_rsi, secPRICE=data[context.security].close_price)
log.info(cash)