股票涨跌预测方法之二:股票技术指标计算
前一阵子在同学的鼓动下,花了一个多月研究了股票行情的预测方法,熟悉了常见的炒股术语及技术指标,现总结如下,纯属兴趣,如果想依照本文的方法来短线操作获利,请绕道。
研究的第二步就是了解常用的股票技术指标,如macd、rsi、ar等,由于前面已经下载了所有的股票数据。那么使用下面代码就可以获得指定股票的所有历史行情:
import pandas as pd import sqlite3 as db cxn = db.connect('all_tushare_data.db') m= pd.read_sql("select * from gp_record where code ='%s' % id, cxn) #id是股票代码
然后就可以计算各个指标,指标的含义及计算公式可自行百度,下面实现过程仅作参考:
if 1: #OBV线,称为成交量多空比率净额法 obv = m.volume*((m.close-m.low)-(m.high-m.close))/(m.high-m.low) obv = obv.fillna(0.0) obv.apply(np.cumsum) print 'obv', len(obv) if 1: #MACD指标 #ema12 = m.adjust_price.copy() #以后复权价为基础 ema12 = m.close.copy() ema26 = ema12.copy() for k in range(1,len(m)): ema12[k] = (ema12[k-1]*11 + ema12[k]*2)/13.0 for k in range(1,len(m)): ema26[k] = (ema26[k-1]*25 + ema26[k]*2)/27.0 dif = ema12-ema26 dea = dif.copy() for k in range(1,len(dea)): dea[k] = (dea[k-1]*8 + dea[k]*2)/10.0 macd = dif-dea print 'macd', len(ema12), len(ema26), len(macd) if 1:#rsi指标,统计近段时间收盘涨数和跌数来判断买卖意向 n=6 rsi = m.change.copy() rsi.apply(np.sign) rsi = rsi.rolling(center=False,window=n).mean() print 'rsi', len(rsi) if 1:#AR BR CR 指标 #第一天的计算数据没有,少一个 refVa = m.open[1:].values #Ar refVb = m.close[:-1].values #BR refVc = (2*m.close[:-1] + m.high[:-1] +m.low[:-1]).values /4 #CR ref = np.median([refVa, refVb, refVc]) a = m.high[1:] - ref b = ref - m.low[1:] c = pd.rolling_sum(a, 26) d = pd.rolling_sum(b, 26) cr = c/d print 'ar br cr', len(cr) if 1: #kdj 指标 n = 5 Ln = pd.rolling_min(m.low, n) Hn = pd.rolling_max(m.high, n) rsv = (m.close-Ln)/(Hn-Ln) #跟wr指标类似 para1 = para2 = 1.0/3 K = rsv.copy() #以后复权价为基础 K = K.fillna(0.0) for k in range(1,len(K)): K[k] = K[k-1]*(1-para1) + K[k]*para1 D = K.copy() for k in range(1,len(D)): D[k] = D[k-1]*(1-para2) + D[k]*para2 print 'KDJ', len(rsv), len(K), len(D) if 1: #cci 顺势指标 n= 10 ma = pd.rolling_mean(m.close, n) md = pd.rolling_mean((ma-m.close).abs(), n) #绝对偏差的平均值 cci = ((m.close+m.high+m.low)/3 -ma)/md/0.015 print 'cci', len(cci) if 1: #DMI指标 #第一天的计算数据没有,少一个 n=12 dm1 = pd.rolling_apply(m.high, 2, lambda d:max(d[1]-d[0],0.0))[1:] dm2 = pd.rolling_apply(m.low , 2, lambda d:max(d[0]-d[1],0.0))[1:] dm1[dm1<dm2] = 0 dm2[dm2<dm1] = 0 tr = (m.high-m.low).abs().values[1:], m.high[1:]-m.close[:-1].abs().values, m.low[1:]-m.close[:-1].abs().values tr = np.minimum(np.minimum(tr[0], tr[1]) ,tr[2]) dm1 = pd.rolling_mean(dm1, n) dm2 = pd.rolling_mean(dm2, n) tr = pd.rolling_mean(tr , n) di1 = dm1/tr di2 = dm2/tr dx = (di1-di2).abs()/(di1+di2) adx = pd.rolling_mean(dx , n) print 'dmi', len(adx) if 1: #boll指标 n=10 ma = pd.rolling_mean(m.close , n) md = np.sqrt( pd.rolling_mean((m.close-ma)**2 , n)) up = ma + 2*md dn = ma - 2*md print 'boll', len(ma), len(up), len(dn)