def plot_dragonpoint(ax1,_dfquotes,beginindex,targetprices,_imulti=40): """ plot k graph with line of targetprices Args: _dfquotes (dataframe): the seurity dataframe which include'openPrice''closePrice''highestPrice''lowestPrice''tradeDate' ax1 : matplotlib ax object beginindex : the index of first k bar, _dfquotes[begin:] will be plot _locatormulti (int): adjust the axis's ticker display interval Returns: none Examples: >> """ global gdfquotes gdfquotes = _dfquotes plot_security_k(ax1,gdfquotes,beginindex,_locatormulti=_imulti) ax2 = ax1.twinx() ax2.set_ylim(ax1.get_ylim()) ax2.yaxis.set_major_formatter(ticker.FuncFormatter(format_percentage)) _zero = gdfquotes['closePrice'].iloc[-1] x1 = range(0,len(gdfquotes)-beginindex+1,len(gdfquotes)-beginindex) for _p in targetprices: y1 = [_p for n in x1] _percen = mymath.rod(_p/_zero-1,4)*100 if _percen < 0 and _percen > -11: ax1.plot(x1,y1,'m--') ax1.text(targetprices.index(_p)*3,_p,'%.2f(%.2f%%)'%(mymath.rod(_p,2),_percen),rotation=90,va='bottom',color='m') else: ax1.plot(x1,y1,'b-') ax1.text(targetprices.index(_p)*3,_p,'%.2f(%.2f%%)'%(mymath.rod(_p,2),_percen),rotation=90,va='bottom') plt.minorticks_on() pass
def ztnum(_his,s,_Divhis=[]): if len(_Divhis) == 0: _Divhis = DataAPI.EquDivGet(secID=s,eventProcessCD='6',field=['exDivDate','perShareDivRatio','perShareTransRatio','perCashDiv'],pandas="1") _Divdate = '0000-00-00' for _date in _Divhis.exDivDate: if _date >= _his['tradeDate'].iloc[0] and _date <= _his['tradeDate'].iloc[-1]: _Divdate = _date#只考虑区间内有一次除权 break i = 0 zt = 0 _closep = 0 while True: #除权单天的开盘价除权 if _his['tradeDate'].iloc[i+1] == _Divdate: _closep = msum.AdjP(_Divhis,_Divdate,_his['closePrice'].iloc[i]) else: _closep = _his['closePrice'].iloc[i] if _his['closePrice'].iloc[i+1] == mymath.rod(_closep*1.1,2): zt = zt + 1 #除权日前涨停价格除权 ''' if previousztdate < _Divdate and _his['tradeDate'].iloc[i+1] >= _Divdate: previouszt = msum.AdjP(_Divhis,_Divdate,previouszt) print '除权后 previouszt',previouszt if _his['closePrice'].iloc[i+1] >= previouszt: zt = zt + 1 previouszt = _his['closePrice'].iloc[i+1] previousztdate = _his['tradeDate'].iloc[i+1] ''' i = i + 1 if i > len(_his)-2: break return zt
def canbuy(_dayTran, _Divdate): #除权单天的开盘价除权 if _dayTran['tradeDate'] == _Divdate: _closep = AdjP(_Divhis, _Divdate, _dayTran['actPreClosePrice']) else: _closep = _dayTran['actPreClosePrice'] #T 天开盘价是否小于涨停价 if _dayTran['openPrice'] < mymath.rod(_closep * 1.1, 2): bcanbuy = True targetprice = _dayTran['openPrice'] * _dayTran['accumAdjFactor'] return bcanbuy, targetprice return False, 0
def ztcs(data): data = data.tolist() data = [round(e, 2) for e in data] if len(data) < 2: return 0 i = 0 zt = 0 previouszt = 0 while True: if (data[i + 1] == mymath.rod(data[i] * 1.1, 2) and data[i + 1] >= previouszt): zt = zt + 1 previouszt = data[i + 1] i = i + 1 if i > len(data) - 2: break return zt
def howmanyzt(_his, _Divdate, bzszt=False, turnrate=0.03): bzt_T = False #不除权历史数据 _his = _his.set_index('tradeDate') #计算区间内涨停情况 i = 0 zt = 0 previouszt = 0 _closep = 0 previousztdate = '0000-00-00' while True: #除权单天的开盘价除权 if _his.index[i + 1] == _Divdate: _closep = AdjP(_Divhis, _Divdate, _his['closePrice'].iloc[i]) else: _closep = _his['closePrice'].iloc[i] if _his['closePrice'].iloc[i + 1] == mymath.rod(_closep * 1.1, 2): #T 天是否涨停 if i == len(_his) - 2: if bzszt == False: bzt_T = True elif _his['turnoverRate'].iloc[ i + 1] >= turnrate or _his['openPrice'].iloc[ i + 1] != _his['closePrice'].iloc[i + 1]: bzt_T = True #除权日前涨停价格除权 if previousztdate < _Divdate and _his.index[i + 1] >= _Divdate: previouszt = AdjP(_Divhis, _Divdate, previouszt) if _his['closePrice'].iloc[i + 1] >= previouszt: zt = zt + 1 previouszt = _his['closePrice'].iloc[i + 1] previousztdate = _his.index[i + 1] i = i + 1 if i > len(_his) - 2: break return zt, bzt_T
print start,now for s in universe: #非复权历史数据 _his = DataAPI.MktEqudGet(beginDate=start,endDate=now,secID=s,isOpen=1,field=['tradeDate','closePrice','openPrice','highestPrice','lowestPrice','accumAdjFactor','actPreClosePrice','turnoverRate'],pandas='1') #历史除权信息 _Divhis = DataAPI.EquDivGet(secID=s,eventProcessCD='6',field=['exDivDate','perShareDivRatio','perShareTransRatio','perCashDiv'],pandas="1") value = [] #遍历历史数据 for id in range(20,len(_his)): g_currentdate = _his['tradeDate'].iloc[id] if g_currentdate < continueday: continue accumAdjFactor = _his['accumAdjFactor'].iloc[id] #买入 if len(value) > 0 and boughtbefore(s,g_currentdate,_his[id-20:id+1],g_imaxback+2): targetprice = mymath.rod(value[g_targetprice],2) _lowestprice = mymath.rod(_his['lowestPrice'].iloc[id]*accumAdjFactor,2) if targetprice >= _lowestprice: _openprice = mymath.rod(_his['openPrice'].iloc[id]*accumAdjFactor,2) _val =[g_currentdate,s,min(targetprice,_openprice)] i = len(g_security_return_value)*g_imaxback while i > 0: _val.append(0.) i = i - 1 g_security_history[len(g_security_history)] = _val #计算之前买入股票目前收益 #1.当天卖出的盈利概率 2.当天卖出的盈利百分比 i = len(g_security_history) - 1 while i >0: v = g_security_history[i] if v[0] == g_currentdate or v[1] != s:#ignore the current day and not the same stock
def format_percentage(y,pos=None): global dfquotes _ticklabel = mymath.rod(y/dfquotes['closePrice'].iloc[-1]-1,3) _per = '%.2f%%'%(_ticklabel*100) return _per
def lxztordt(gc, tradedate, zt=True, turnrate=0.03): """ 给定股票代码列表,计算连板数 Args: gc (list): 需要计算连板的股票代码列表 tradedate (string):计算时间 turnrate (float):一字板确认真实涨停换手率标准 zt (bool):计算涨停还是跌停 Returns: dict (dictionary):key是连板数量,value是[[ticker,turnoverrate],[ticker,turnoverrate]....] Examples: >> lxztordt(['000425','600307','002307','000877'],'20170210') >> lxztordt(['000425.XSHE','600307.XSHG','002307','000877'],'20170210') """ _his = [] _conbandict = {} for s in gc: _continuebang = 0 _continueturn = 0 if s.find('.') >= 0: _his = DataAPI.MktEqudGet(endDate=tradedate, secID=s, field=[ 'tradeDate', 'secShortName', 'lowestPrice', 'closePrice', 'turnoverRate' ], isOpen=1, pandas='1') else: _his = DataAPI.MktEqudGet(endDate=tradedate, ticker=s, field=[ 'tradeDate', 'secShortName', 'lowestPrice', 'closePrice', 'turnoverRate' ], isOpen=1, pandas='1') Divhis = DataAPI.EquDivGet(secID=s, eventProcessCD='6', field=[ 'exDivDate', 'perShareDivRatio', 'perShareTransRatio', 'perCashDiv' ], pandas="1") indexreverse = range(-1, -len(_his), -1) for ind in indexreverse: if (_his['secShortName'].iloc[ind].find('S') >= 0): if zt: maxinc = 1.05 else: maxinc = 0.95 else: if zt: maxinc = 1.1 else: maxinc = 0.9 if ind > indexreverse[-1]: _preclose = AdjP(Divhis, _his['tradeDate'].iloc[ind], _his['closePrice'].iloc[ind - 1]) if _his['closePrice'].iloc[ind] == mymath.rod( _preclose * maxinc, 2): _continuebang = _continuebang + 1 _continueturn = _continueturn + _his['turnoverRate'].iloc[ ind] #如果是统计涨停,则需要检查是不是真实涨停,如果不是就不统计连板数 if zt and _his['lowestPrice'].iloc[ind] == _his[ 'closePrice'].iloc[ind] and _his[ 'turnoverRate'].iloc[ind] < turnrate: _continuebang = _continuebang - 1 break else: break #next security if _continuebang == 0: continue #store to the dict if _continuebang in _conbandict: _conbandict[_continuebang].append([s, _continueturn]) else: _conbandict[_continuebang] = [[s, _continueturn]] return _conbandict
def handle_data(account): #在每个交易日开盘之前运行,用来执行策略,判断交易指令下达的时机和细节 global g_vardic global ticks global g_security_history global g_currentdate ticks = ticks % g_ifreq if ticks == 0: g_currentdate = account.current_date.strftime('%Y%m%d') for k, v in g_security_history.items(): if k == 0 or g_vardic[k]['checked']: continue if ticks == 0: df = DataAPI.MktEqudAdjGet( beginDate=v[0], endDate=g_currentdate, secID=v[1], field=['closePrice', 'highestPrice', 'lowestPrice'], isOpen='1', pandas='1') g_vardic[k]['before'] = len(df) if g_vardic[k]['before'] == 2: g_vardic[k]['closeprice'] = df['closePrice'].iloc[0] g_vardic[k]['highestprice'] = df['highestPrice'].iloc[-1] g_vardic[k]['lowestprice'] = df['lowestPrice'].iloc[-1] if g_vardic[k]['before'] != 2: continue #only T+1 day g_vardic[k]['fenshi'].append(account.reference_price[v[1]]) if ticks == 239: plt.title(v[1] + v[0]) plt.plot(g_vardic[k]['fenshi'] / g_vardic[k]['closeprice'] - 1, 'y-') lips = g_vardic[k]['soldpoint'] / g_vardic[k]['closeprice'] - 1 plt.plot(g_vardic[k]['soldticks'], lips, 'go') plt.grid() plt.xlim(0, 239) plt.xticks(range(0, 240, 30)) ymax = max( abs(g_vardic[k]['highestprice'] / g_vardic[k]['closeprice'] - 1), abs(g_vardic[k]['lowestprice'] / g_vardic[k]['closeprice'] - 1)) plt.ylim(-ymax, ymax) plt.show() g_vardic[k]['checked'] = True if g_vardic[k]['unit'] <= 0: continue if len(g_vardic[k]['fenshi']) <= 1: _price_1 = g_vardic[k]['fenshi'][0] else: _price_1 = g_vardic[k]['fenshi'][-2] if g_vardic[k]['fenshi'][0]/g_vardic[k]['closeprice']-1 >= jump\ and g_vardic[k]['fenshi'][-1] < _price_1: g_vardic[k]['soldpoint'].append(g_vardic[k]['fenshi'][-1]) g_vardic[k]['soldticks'].append(ticks) g_vardic[k]['unit'] = g_vardic[k]['unit'] - 1 if mymath.rod(g_vardic[k]['fenshi'][-1],2) == mymath.rod(g_vardic[k]['closeprice']*1.1,2)\ or ticks == 239: while g_vardic[k]['unit'] > 0: g_vardic[k]['soldpoint'].append(g_vardic[k]['fenshi'][-1]) g_vardic[k]['soldticks'].append(ticks) g_vardic[k]['unit'] = g_vardic[k]['unit'] - 1 ticks = ticks + 1 return