def handle_bar(context, bar_dict):
# ?????????????
# bar_dict[order_book_id] ?????????bar??
# context.portfolio ???????????????
# ??order_shares(id_or_ins, amount)??????
# TODO: ??????????
# ????????????loop?????????RSI??
for stock in context.stocks:
# ??????
prices = history_bars(stock, context.TIME_PERIOD+1, '1d', 'close')
# ?Talib??RSI?
rsi_data = talib.RSI(prices, timeperiod=context.TIME_PERIOD)[-1]
cur_position = context.portfolio.positions[stock].quantity
# ??????30%???????
target_available_cash = context.portfolio.cash * context.ORDER_PERCENT
# ?RSI???????????????
if rsi_data > context.HIGH_RSI and cur_position > 0:
order_target_value(stock, 0)
# ?RSI?????????????cash?????????
if rsi_data < context.LOW_RSI:
logger.info("target available cash caled: " + str(target_available_cash))
# ??????????? - 100shares?????ricequant ?order management system reject?
order_value(stock, target_available_cash)
python类RSI的实例源码
def __recountRsi(self):
"""??K??RSI"""
if self.inputRsiLen <= 0: return
# 1?lineBar?????????
if len(self.lineBar) < self.inputRsiLen+2:
self.debugCtaLog(u'?????,??Bar?????{0}???RSI???{1}'.
format(len(self.lineBar), self.inputRsiLen+2))
return
# 3?inputRsiLen(????????????
listClose=[x.close for x in self.lineBar[-self.inputRsiLen - 2:]]
barRsi = ta.RSI(numpy.array(listClose, dtype=float), self.inputRsiLen)[-1]
barRsi = round(float(barRsi), 3)
l = len(self.lineRsi)
if l > self.inputRsiLen*8:
del self.lineRsi[0]
self.lineRsi.append(barRsi)
if l > 3:
# ?
if self.lineRsi[-1] < self.lineRsi[-2] and self.lineRsi[-3] < self.lineRsi[-2]:
t={}
t["Type"] = u'T'
t["RSI"] = self.lineRsi[-2]
t["Close"] = self.lineBar[-2].close
if len(self.lineRsiTop) > self.inputRsiLen:
del self.lineRsiTop[0]
self.lineRsiTop.append( t )
self.lastRsiTopButtom = self.lineRsiTop[-1]
# ?
elif self.lineRsi[-1] > self.lineRsi[-2] and self.lineRsi[-3] > self.lineRsi[-2]:
b={}
b["Type"] = u'B'
b["RSI"] = self.lineRsi[-2]
b["Close"] = self.lineBar[-2].close
if len(self.lineRsiButtom) > self.inputRsiLen:
del self.lineRsiButtom[0]
self.lineRsiButtom.append(b)
self.lastRsiTopButtom = self.lineRsiButtom[-1]
def _handle_data_rsi_only(context, data):
price = data.current(context.asset, 'close')
log.info('got price {price}'.format(price=price))
if price is np.nan:
log.warn('no pricing data')
return
if context.base_price is None:
context.base_price = price
try:
prices = data.history(
context.asset,
fields='price',
bar_count=20,
frequency='30T'
)
except Exception as e:
log.warn('historical data not available: '.format(e))
return
rsi = talib.RSI(prices.values, timeperiod=16)[-1]
log.info('got rsi {}'.format(rsi))
signal = None
if rsi < context.RSI_OVERSOLD:
signal = 'long'
# Making sure that the price is still current
price = data.current(context.asset, 'close')
cash = context.portfolio.cash
log.info(
'base currency available: {cash}, cap: {cap}'.format(
cash=cash,
cap=context.MAX_HOLDINGS
)
)
volume = data.current(context.asset, 'volume')
price_change = (price - context.base_price) / context.base_price
record(
price=price,
price_change=price_change,
rsi=rsi,
volume=volume,
cash=cash,
starting_cash=context.portfolio.starting_cash,
leverage=context.account.leverage,
)
_handle_buy_sell_decision(context, data, signal, price)
def calculate_features(df):
"""
Method which calculates and generates features
"""
close = df['close'].values
high = df['high'].values
low = df['low'].values
volume = df['volume'].values
last_row = df.tail(1).copy()
# ************** Calc EMAs
ema_periods = [2, 4, 8, 12, 16, 20]
for ema_period in ema_periods:
ema = talib.EMA(close[-ema_period:], timeperiod=ema_period)[-1]
last_row['ema' + str(ema_period)] = ema
# ************** Calc RSIs
rsi_periods = [5]
for rsi_period in rsi_periods:
rsi = talib.RSI(close[-rsi_period:], timeperiod=rsi_period-1)[-1]
last_row['rsi' + str(rsi_period)] = rsi
last_row['rsi_above_50' + str(rsi_period)] = int(rsi > 50.0)
# ************** Calc CCIs
cci_periods = [5]
for cci_period in cci_periods:
cci = talib.CCI(high[-cci_period:],
low[-cci_period:],
close[-cci_period:],
timeperiod=cci_period)[-1]
last_row['cci' + str(cci_period)] = cci
# ************** Calc MACD 1
macd_periods = [34]
for macd_period in macd_periods:
macd, macd_signal, _ = talib.MACD(close[-macd_period:],
fastperiod=12,
slowperiod=26,
signalperiod=9)
macd = macd[-1]
signal_line = macd_signal[-1]
last_row['macd_above_signal' + str(macd_period)] = int(macd > signal_line)
last_row['macd_above_zero' + str(macd_period)] = int(macd > 0.0)
# ************** Calc OBVs
obv_periods = [2, 4, 8, 12, 16, 20]
for obv_period in obv_periods:
obv = talib.OBV(close[-obv_period:], volume[-obv_period:])[-1]
last_row['obv' + str(obv_period)] = obv
return last_row
def calculate_features(df):
"""
Method which calculates and generates features
"""
close = df['close'].values
high = df['high'].values
low = df['low'].values
volume = df['volume'].values
last_row = df.tail(1).copy()
# ************** Calc EMAs
ema_periods = [2, 4, 8, 12, 16, 20]
for ema_period in ema_periods:
ema = talib.EMA(close[-ema_period:], timeperiod=ema_period)[-1]
last_row['ema' + str(ema_period)] = ema
# ************** Calc RSIs
rsi_periods = [5]
for rsi_period in rsi_periods:
rsi = talib.RSI(close[-rsi_period:], timeperiod=rsi_period-1)[-1]
last_row['rsi' + str(rsi_period)] = rsi
last_row['rsi_above_50' + str(rsi_period)] = int(rsi > 50.0)
# ************** Calc CCIs
cci_periods = [5]
for cci_period in cci_periods:
cci = talib.CCI(high[-cci_period:],
low[-cci_period:],
close[-cci_period:],
timeperiod=cci_period)[-1]
last_row['cci' + str(cci_period)] = cci
# ************** Calc MACD 1
macd_periods = [34]
for macd_period in macd_periods:
macd, macd_signal, _ = talib.MACD(close[-macd_period:],
fastperiod=12,
slowperiod=26,
signalperiod=9)
macd = macd[-1]
signal_line = macd_signal[-1]
last_row['macd_above_signal' + str(macd_period)] = int(macd > signal_line)
last_row['macd_above_zero' + str(macd_period)] = int(macd > 0.0)
# ************** Calc OBVs
obv_periods = [2, 4, 8, 12, 16, 20]
for obv_period in obv_periods:
obv = talib.OBV(close[-obv_period:], volume[-obv_period:])[-1]
last_row['obv' + str(obv_period)] = obv
return last_row
def oscillator2(data):
float_close = Data.toFloatArray(df['Close'])
float_high = Data.toFloatArray(df['High'])
float_low = Data.toFloatArray(df['Low'])
float_open = Data.toFloatArray(df['Open'])
adx_values = tl.ADX(np.array(float_high),np.array(float_low),np.array(float_close), timeperiod = 14)
dmi = tl.DX(np.array(float_high),np.array(float_low),np.array(float_close), timeperiod = 14)
mdmi = tl.MINUS_DI(np.array(float_high),np.array(float_low),np.array(float_close), timeperiod = 14)
rsi = tl.RSI(np.array(float_close),timeperiod = 4 )
signals = []
flag = 0
for i in xrange(40 , len(adx_values) - 2):
if flag ==0:
if adx_values[i]>20 and dmi[i]>mdmi[i] and df.loc[i+1, 'Open']> (df.loc[i, 'Close']+1.8) and rsi[i]<50:
signal = ['HSI', df.loc[i+1, 'Date'], 'Long', df.loc[i+1, 'Close']]
flag =1
signals.append(signal)
if adx_values[i]>20 and dmi[i]<mdmi[i] and df.loc[i+1, 'Open']< (df.loc[i, 'Close']-1.8) and rsi[i]<50:
signal = ['HSI', df.loc[i+1, 'Date'], 'Short', df.loc[i+1, 'Close']]
flag =2
signals.append(signal)
elif flag ==1:
if df.loc[i, 'Close']>= signal[3]*1.01 or df.loc[i, 'Close']<= signal[3]*0.90 or (df.loc[i, 'Date']-signal[1])>timedelta(days=5):
signal = ['HSI', df.loc[i, 'Date'], 'Short', df.loc[i+1, 'Open']]
flag = 0
signals.append(signal)
elif flag ==2:
if df.loc[i, 'Close']<= signal[3]*0.99 or df.loc[i, 'Close']>= signal[3]*1.10 or (df.loc[i, 'Date']-signal[1])>timedelta(days=5):
signal = ['HSI', df.loc[i+1, 'Date'], 'Long', df.loc[i+1, 'Close']]
flag = 0
signals.append(signal)
sig = pd.DataFrame(signals, columns=['Code', 'Time', 'Action', 'Price'])
print sig['Time'][10]-sig['Time'][0]
profits = []
print sig
for k in range(0,len(signals)/2):
if sig['Action'][k*2] == "Long":
profit = sig['Price'][k*2+1] - sig['Price'][k*2]
else:
profit = sig['Price'][k*2]- sig['Price'][k*2+1]
profits.append(profit)
print np.sum(profits)
print(profits)
###### PLOT #######
longSignals = sig[sig['Action'] == 'Long']
shortSignals = sig[sig['Action'] == 'Short']
plt.plot(df['Date'], df['Close'], longSignals['Time'], longSignals['Price'], 'r^', shortSignals['Time'],
shortSignals['Price'], 'gv', markersize=10)
red_patch = mpatches.Patch(color='red', label='Long')
green_patch = mpatches.Patch(color='green', label='Short')
plt.legend(handles=[red_patch, green_patch])
plt.grid()
plt.show()
###### PLOT #######
def Get_KDJ(df):
#??9,3,3
slowk, slowd = ta.STOCH(np.array(df['high']), np.array(df['low']), np.array(df['close']), fastk_period=9, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
slowkMA5 = ta.MA(slowk, timeperiod=5, matype=0)
slowkMA10 = ta.MA(slowk, timeperiod=10, matype=0)
slowkMA20 = ta.MA(slowk, timeperiod=20, matype=0)
slowdMA5 = ta.MA(slowd, timeperiod=5, matype=0)
slowdMA10 = ta.MA(slowd, timeperiod=10, matype=0)
slowdMA20 = ta.MA(slowd, timeperiod=20, matype=0)
#16-17 K,D
df['slowk']=pd.Series(slowk,index=df.index) #K
df['slowd']=pd.Series(slowd,index=df.index)#D
dflen = df.shape[0]
MAlen = len(slowkMA5)
operate = 0
#1.K???????——???90?????????10??????D??80???????????D??20???????????
if df.iat[(dflen-1),16]>=90:
operate = operate + 3
elif df.iat[(dflen-1),16]<=10:
operate = operate - 3
if df.iat[(dflen-1),17]>=80:
operate = operate + 3
elif df.iat[(dflen-1),17]<=20:
operate = operate - 3
#2.??????K???D??K?????D?????????#???
if df.iat[(dflen-1),16]> df.iat[(dflen-1),17] and df.iat[(dflen-2),16]<=df.iat[(dflen-2),17]:
operate = operate + 10
#??????K??D?K?????D?????????#???
elif df.iat[(dflen-1),16]< df.iat[(dflen-1),17] and df.iat[(dflen-2),16]>=df.iat[(dflen-2),17]:
operate = operate - 10
#3.???????????????????????
if df.iat[(dflen-1),7]>=df.iat[(dflen-1),8] and df.iat[(dflen-1),8]>=df.iat[(dflen-1),9]:#K???
if (slowkMA5[MAlen-1]<=slowkMA10[MAlen-1] and slowkMA10[MAlen-1]<=slowkMA20[MAlen-1]) or \
(slowdMA5[MAlen-1]<=slowdMA10[MAlen-1] and slowdMA10[MAlen-1]<=slowdMA20[MAlen-1]): #K,D??
operate = operate - 1
elif df.iat[(dflen-1),7]<=df.iat[(dflen-1),8] and df.iat[(dflen-1),8]<=df.iat[(dflen-1),9]:#K???
if (slowkMA5[MAlen-1]>=slowkMA10[MAlen-1] and slowkMA10[MAlen-1]>=slowkMA20[MAlen-1]) or \
(slowdMA5[MAlen-1]>=slowdMA10[MAlen-1] and slowdMA10[MAlen-1]>=slowdMA20[MAlen-1]): #K,D??
operate = operate + 1
return (df,operate)
#??RSI??????
def Get_RSI(df):
#??14,5
slowreal = ta.RSI(np.array(df['close']), timeperiod=14)
fastreal = ta.RSI(np.array(df['close']), timeperiod=5)
slowrealMA5 = ta.MA(slowreal, timeperiod=5, matype=0)
slowrealMA10 = ta.MA(slowreal, timeperiod=10, matype=0)
slowrealMA20 = ta.MA(slowreal, timeperiod=20, matype=0)
fastrealMA5 = ta.MA(fastreal, timeperiod=5, matype=0)
fastrealMA10 = ta.MA(fastreal, timeperiod=10, matype=0)
fastrealMA20 = ta.MA(fastreal, timeperiod=20, matype=0)
#18-19 ??real???real
df['slowreal']=pd.Series(slowreal,index=df.index) #??real 18
df['fastreal']=pd.Series(fastreal,index=df.index)#??real 19
dflen = df.shape[0]
MAlen = len(slowrealMA5)
operate = 0
#RSI>80?????RSI<20????
if df.iat[(dflen-1),18]>80 or df.iat[(dflen-1),19]>80:
operate = operate - 2
elif df.iat[(dflen-1),18]<20 or df.iat[(dflen-1),19]<20:
operate = operate + 2
#RSI??50???????????50????????
if (df.iat[(dflen-2),18]<=50 and df.iat[(dflen-1),18]>50) or (df.iat[(dflen-2),19]<=50 and df.iat[(dflen-1),19]>50):
operate = operate + 4
elif (df.iat[(dflen-2),18]>=50 and df.iat[(dflen-1),18]<50) or (df.iat[(dflen-2),19]>=50 and df.iat[(dflen-1),19]<50):
operate = operate - 4
#RSI??????????RSI?????????
if df.iat[(dflen-1),7]>=df.iat[(dflen-1),8] and df.iat[(dflen-1),8]>=df.iat[(dflen-1),9]:#K???
if (slowrealMA5[MAlen-1]<=slowrealMA10[MAlen-1] and slowrealMA10[MAlen-1]<=slowrealMA20[MAlen-1]) or \
(fastrealMA5[MAlen-1]<=fastrealMA10[MAlen-1] and fastrealMA10[MAlen-1]<=fastrealMA20[MAlen-1]): #RSI??
operate = operate - 1
elif df.iat[(dflen-1),7]<=df.iat[(dflen-1),8] and df.iat[(dflen-1),8]<=df.iat[(dflen-1),9]:#K???
if (slowrealMA5[MAlen-1]>=slowrealMA10[MAlen-1] and slowrealMA10[MAlen-1]>=slowrealMA20[MAlen-1]) or \
(fastrealMA5[MAlen-1]>=fastrealMA10[MAlen-1] and fastrealMA10[MAlen-1]>=fastrealMA20[MAlen-1]): #RSI??
operate = operate + 1
#?????????????????????????????????????????????????????????????????
if df.iat[(dflen-1),19]> df.iat[(dflen-1),18] and df.iat[(dflen-2),19]<=df.iat[(dflen-2),18]:
operate = operate + 10
elif df.iat[(dflen-1),19]< df.iat[(dflen-1),18] and df.iat[(dflen-2),19]>=df.iat[(dflen-2),18]:
operate = operate - 10
return (df,operate)