def onInit(self):
"""????????????????"""
self.writeCtaLog(u'%s?????' %self.name)
# ???RSI????
self.rsiBuy = 50 + self.rsiEntry
self.rsiSell = 50 - self.rsiEntry
# ????????????????????????
initData = self.loadBar(self.initDays)
for bar in initData:
self.onBar(bar)
self.putEvent()
#----------------------------------------------------------------------
python类RSI的实例源码
def isBuy(context, analysis):
# Bullish SMA Crossover
if (getLast(analysis, 'sma_test') == 1):
# Bullish MACD
if (getLast(analysis, 'macd_test') == 1):
return True
# # Bullish Stochastics
# if(getLast(analysis, 'stoch_over_sold') == 1):
# return True
# # Bullish RSI
# if(getLast(analysis, 'rsi_over_sold') == 1):
# return True
return False
def isSell(context, analysis):
# Bearish SMA Crossover
if (getLast(analysis, 'sma_test') == 0):
# Bearish MACD
if (getLast(analysis, 'macd_test') == 0):
return True
# # Bearish Stochastics
# if(getLast(analysis, 'stoch_over_bought') == 0):
# return True
# # Bearish RSI
# if(getLast(analysis, 'rsi_over_bought') == 0):
# return True
return False
def getStrategy_RSI(start_trading_day,end_trading_day,_time,_close):
point = []
iday = _time.index(start_trading_day)
eday = _time.index(end_trading_day)
rsi = ta.RSI(np.array(_close,dtype='f8'),timeperiod=14)
rsi = rsi[iday:eday]
point.append(0)
for i in range(1,len(rsi)):
if (rsi[i] <= 30) and (rsi[i - 1] > 30):
point.append(1)
elif (rsi[i] >= 50) and (rsi[i - 1] < 50):
point.append(-1)
else:
point.append(0)
return point
def getStrategy_RSI(start_trading_day,end_trading_day,_time,_close):
point = []
iday = _time.index(start_trading_day)
eday = _time.index(end_trading_day)
rsi = ta.RSI(np.array(_close,dtype='f8'),timeperiod=14)
rsi = rsi[iday:eday]
point.append(0)
for i in range(1,len(rsi)):
if (rsi[i] <= 30) and (rsi[i - 1] > 30):
point.append(1)
elif (rsi[i] >= 50) and (rsi[i - 1] < 50):
point.append(-1)
else:
point.append(0)
return point
def KDJ_COM(high, low, close, fastk_period=9, slowk_period=3, slowd_period=3, fixpre=True) :
len1 = len(high)
len2 = len(low)
len3 = len(close)
if len1 != len2 or len1 != len3:
print (("KDJ_COM input invalid for len:%s %s %s " %(str(len1),str(len2),str(len3))))
return np.array([np.nan]),np.array([np.nan]),np.array([np.nan])
hValue = SecurityDataSrcBase.HHV_COM(high, fastk_period, fixpre)
lValue = SecurityDataSrcBase.LLV_COM(low, fastk_period, fixpre)
rsValue = (close - lValue) / (hValue - lValue) * 100
kValue = SecurityDataSrcBase.SMA_COM(rsValue, slowk_period)
dValue = SecurityDataSrcBase.SMA_COM(kValue, slowd_period)
jValue = 3 * kValue - 2 * dValue
return kValue, dValue, jValue
# RSI COMMON
def test_JiShuZhiBiao():
"""??????"""
pl = publish.Publish()
code = '002440'
code = '999999'
#?????????rsi
df = FenshiEx(code, '2014-10-8', '2014-10-8').df
#df = FENSHI_MA(df)
df = FENSHI_BIAS(df)
df['rsi'] = RSI(df['p'])
df1 = df.drop(['v','b','bias','rsi'], axis=1)
ui.drawDf(pl, df1)
df2 = df.drop(['v','b','p','avg', 'rsi'], axis=1)
ui.drawDf(pl, df2)
df2 = df.drop(['v','b','p','avg', 'bias'], axis=1)
ui.drawDf(pl, df2)
def __init__(self, selector):
self.selector = selector
self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"}
self.feature = []
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)
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)
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)
def handle_data(context, data):
print('handling bar: {}'.format(data.current_dt))
price = data.current(context.asset, 'close')
print('got price {price}'.format(price=price))
prices = data.history(
context.asset,
fields='price',
bar_count=20,
frequency='30T'
)
last_traded = prices.index[-1]
print('last candle date: {}'.format(last_traded))
rsi = talib.RSI(prices.values, timeperiod=14)[-1]
print('got rsi: {}'.format(rsi))
# If base_price is not set, we use the current value. This is the
# price at the first bar which we reference to calculate price_change.
if context.base_price is None:
context.base_price = price
price_change = (price - context.base_price) / context.base_price
cash = context.portfolio.cash
# Now that we've collected all current data for this frame, we use
# the record() method to save it. This data will be available as
# a parameter of the analyze() function for further analysis.
record(
price=price,
price_change=price_change,
cash=cash
)
def RSI(df, n, field='close'):
return pd.Series(talib.RSI(df[field].values, n), index = df.index, name='RSI%s' % str(n))
def rsi(df, n, field = 'close'):
RSI_key = 'RSI%s' % str(n)
df[RSI_key][-1] = talib.RSI(df[field][(-n-1):], n)[-1]
def RSI_F(df, n, field='close'):
UpMove = df[field] - df[field].shift(1)
DoMove = df[field].shift(1) - df[field]
UpD = pd.Series(UpMove)
DoD = pd.Series(DoMove)
UpD[(UpMove <= 0)] = 0
DoD[(DoMove <= 0)] = 0
PosDI = pd.Series(pd.ewma(UpD, com = n-1), name = "RSI"+str(n)+'_UP')
NegDI = pd.Series(pd.ewma(DoD, com = n-1), name = "RSI"+str(n)+'_DN')
RSI = pd.Series(PosDI / (PosDI + NegDI) * 100, name = 'RSI' + str(n))
return pd.concat([RSI, PosDI, NegDI], join='outer', axis=1)
def rsi_f(df, n, field = 'close'):
RSI_key = 'RSI%s' % str(n)
dx = df[field][-1] - df[field][-2]
alpha = 1.0/n
if dx > 0:
upx = dx
dnx = 0
else:
upx = 0
dnx = -dx
udi = df[RSI_key + '_UP'][-1] = df[RSI_key + '_UP'][-2] * (1 - alpha) + upx * alpha
ddi = df[RSI_key + '_DN'][-1] = df[RSI_key + '_DN'][-2] * (1 - alpha) + dnx * alpha
df[RSI_key][-1] = udi/(udi + ddi) * 100.0
#True Strength Index
def add_RSI(self, timeperiod=14,
type='line', color='secondary', **kwargs):
"""Relative Strength Index."""
if not self.has_close:
raise Exception()
utils.kwargs_check(kwargs, VALID_TA_KWARGS)
if 'kind' in kwargs:
type = kwargs['kind']
name = 'RSI({})'.format(str(timeperiod))
self.sec[name] = dict(type=type, color=color)
self.ind[name] = talib.RSI(self.df[self.cl].values,
timeperiod)
def __init__(self, selector):
self.selector = selector
self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"}
self.feature = []
prep_data_03_stock_02_OHLCV_arrays_2_features_targets_arrays.py 文件源码
项目:LIE
作者: EmbraceLife
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def __init__(self, selector):
self.selector = selector
self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"}
self.feature = []
def __init__(self, selector):
self.selector = selector
self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"}
self.feature = []
def __init__(self, selector):
self.selector = selector
self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"}
self.feature = []
def __init__(self, selector):
self.selector = selector
self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"}
self.feature = []
def RSI_CN(close, timeperiod=6):
return tl.RSI(close, timeperiod)
# MA
def rsi(self, n, array=False):
"""RSI??"""
result = talib.RSI(self.close, n)
if array:
return result
return result[-1]
# ----------------------------------------------------------------------
def RSI(self):
"""??????? 30????? 70????"""
closes = self.getCloses()
return talib.RSI(closes)
def RSI(closes, timeperiod=12):
"""??????? 30????? 70???? return: np.darray"""
closes = np.array(closes)
closes = closes[np.isnan(closes) == False]
return talib.RSI(closes, timeperiod)
def unittest_ma():
closes = Guider('600100').getCloses()
print(MA(closes))
fours = FOUR(closes)
print( len(closes), len(fours))
print(fours)
rsi = RSI(closes)
#rsi = rsi/100 - 0.5
rsi -= 50
fours *= 100
pl.figure
#pl.plot(closes)
pl.plot(fours,'r')
pl.plot(rsi)
pl.show()
def test_fenshi_rsi():
"""???????rsi??"""
code = '300059'
fenshi = CreateFenshiPd(code, '2015-8-6').resample('1min').mean().dropna()
print( fenshi)
closes = fenshi['p']
print(closes)
rsi = RSI(closes, 6)
print(rsi)
ui.DrawTs(pl, rsi)
def get_rsi_info(df):
"""
calculate rsi quotation.
:param df:
:return: rsi
"""
close = get_close_data(df)
rsi = ta.RSI(close, timeperiod=12)
return pd.DataFrame({u'rsi': rsi[-view_days:]})
def Get_TA(df_Code,Dist):
operate_array1=[]
operate_array2=[]
operate_array3=[]
count = 0
for code in df_Code.index:
# index,0 - 6 date??? open???? high???? close???? low???? volume???? price_change????? p_change????
# 7-12 ma5?5??? ma10?10??? ma20:20??? v_ma5:5???v_ma10:10??? v_ma20:20???
df = ts.get_hist_data(code,start='2014-11-20')
dflen = df.shape[0]
count = count + 1
if dflen>35:
try:
(df,operate1) = Get_MACD(df)
(df,operate2) = Get_KDJ(df)
(df,operate3) = Get_RSI(df)
except Exception, e:
Write_Blog(e,Dist)
pass
operate_array1.append(operate1) #round(df.iat[(dflen-1),16],2)
operate_array2.append(operate2)
operate_array3.append(operate3)
if count == 0:
Write_Blog(str(count),Dist)
df_Code['MACD']=pd.Series(operate_array1,index=df_Code.index)
df_Code['KDJ']=pd.Series(operate_array2,index=df_Code.index)
df_Code['RSI']=pd.Series(operate_array3,index=df_Code.index)
return df_Code
#??MACD??????