def df_eod_prices(timestr): w.start() w.isconnected() #timestr=input('tradedate') timey = timestr[0:4] timem = timestr[4:6] timed = timestr[6:8] date = datetime.datetime(int(timey), int(timem), int(timed)) windds1 = w.wset('SectorConstituent', 'date=' + timestr + ';sector=全部A股') datac = windds1.Data[1] #datat=['000001.SZ','000002.SZ'] windds2 = w.wss( datac, "pre_close,open,high,low,close,chg,pct_chg,volume,amt,adjfactor,vwap,trade_status", "tradeDate=" + timestr + ";priceAdj=U;cycle=D") dc1 = { 'Ticker': datac, 'Date': [timestr] * len(datac), 'PreClose': windds2.Data[0], 'Open': windds2.Data[1], 'High': windds2.Data[2], 'Low': windds2.Data[3], 'Close': windds2.Data[4], 'Change': windds2.Data[5], 'PctChg': windds2.Data[6], 'Volume': windds2.Data[7], 'Amount': windds2.Data[8], 'AdjFactor': windds2.Data[9], 'VWAP': windds2.Data[10], 'TradeStatus': windds2.Data[11] } df = pd.DataFrame(dc1) return (df)
def index_info(timestr): w.start() w.isconnected() #timestr=input('tradedate') timey=timestr[0:4] timem=timestr[4:6] timed=timestr[6:8] date= datetime.datetime(int(timey), int(timem), int(timed)) windds1=w.wset("indexhistory","startdate=2001-01-01;enddate="+timestr+";windcode=000300.SH;field=tradedate,tradecode,tradestatus") dc1={'tradedate':windds1.Data[0],'tradecode':windds1.Data[1],'tradestatus':windds1.Data[2]} df1=pd.DataFrame(dc1) df1=df1.sort_index(axis=0,by=['tradecode','tradedate'],ascending=True) df1=df1.reset_index(drop=True) i=0 df=pd.DataFrame({},columns=['Ticker','EntryDate','RemoveDate']) while(i<len(df1)): if(df1.loc[i,'tradecode']==df1.loc[i+1,'tradecode']): dc={'Ticker':df1.loc[i,'tradecode'],'EntryDate':str(df1.loc[i,'tradedate'])[0:4]+str(df1.loc[i,'tradedate'])[5:7]+str(df1.loc[i,'tradedate'])[8:10],'RemoveDate':str(df1.loc[i+1,'tradedate'])[0:4]+str(df1.loc[i+1,'tradedate'])[5:7]+str(df1.loc[i+1,'tradedate'])[8:10]} df=df.append(dc,ignore_index=True) i=i+2 else: dc={'Ticker':df1.loc[i,'tradecode'],'EntryDate':str(df1.loc[i,'tradedate'])[0:4]+str(df1.loc[i,'tradedate'])[5:7]+str(df1.loc[i,'tradedate'])[8:10],'RemoveDate':None} df=df.append(dc,ignore_index=True) i=i+1 return(df)
def st(timestr): w.start() w.isconnected() #timestr=input('tradedate') windds1 = w.wset( "carryoutspecialtreatment", "startdate=1998-04-28;enddate=" + timestr + ";field=wind_code,implementation_date") wcode = [] wdate = [] status = [] for i in range(len(windds1.Codes)): if (windds1.Data[0][i][7:9] != 'OC'): wcode.append(windds1.Data[0][i]) wdate.append(windds1.Data[1][i]) status.append(1) dc1 = {'codes': wcode, 'date': wdate, 'status': status} windds2 = w.wset( "cancelspecialtreatment", "startdate=1998-04-28;enddate=" + timestr + ";field=wind_code,implementation_date") wcode = [] wdate = [] status = [] for i in range(len(windds2.Codes)): if (windds1.Data[0][i][7:9] != 'OC'): wcode.append(windds2.Data[0][i]) wdate.append(windds2.Data[1][i]) status.append(2) dc2 = {'codes': wcode, 'date': wdate, 'status': status} df1 = pd.DataFrame(dc1) df2 = pd.DataFrame(dc2) df = pd.concat([df1, df2], ignore_index=True) df = df.sort_values(by=["codes", 'date']) code = [] entrydate = [] removedate = [] i = 0 while (i < len(df)): if (df.iloc[i][2] == 2): i += 1 elif (i < (len(df) - 1) and df.iloc[i][0] == df.iloc[i + 1][0]): code.append(df.iloc[i][0]) entrydate.append( str(df.iloc[i][1])[0:4] + str(df.iloc[i][1])[5:7] + str(df.iloc[i][1])[8:10]) removedate.append( str(df.iloc[i + 1][1])[0:4] + str(df.iloc[i + 1][1])[5:7] + str(df.iloc[i + 1][1])[8:10]) i += 2 else: code.append(df.iloc[i][0]) entrydate.append( str(df.iloc[i][1])[0:4] + str(df.iloc[i][1])[5:7] + str(df.iloc[i][1])[8:10]) removedate.append(None) i += 1 dc = {'Ticker': code, 'EntryDate': entrydate, 'RemoveDate': removedate} df = pd.DataFrame(dc) return (df)
def QA_fetch_get_stock_list(date): w.start() w.isconnected() if (is_valid_date(date) == False): print("wrong date") else: awgs = 'date=' + date + ';sectorid=a001010100000000' data = w.wset("sectorconstituent", awgs) return data.Data
def wConnect(): if w.isconnected(): print("w.isconnected: {}".format(w.isconnected())) #continue elif os.system('tasklist | find "wmain.exe"') == 0: _windPyStart() else: _startWindExe() _windPyStart()
def suspend1(timestr): w.start() w.isconnected() #timestr=input('tradedate') windds1 = w.wset( "pauselistsecurity", "startdate=1998-04-28;enddate=" + timestr + ";sectorid=a001010100000000;field=wind_code,susp_list_date") windds2 = w.wset( "resumelistsecurity", "startdate=1998-04-28;enddate=" + timestr + ";sectorid=a001010100000000;field=wind_code,resume_list_date") dc1 = { 'codes': windds1.Data[0], 'date': windds1.Data[1], 'status': [1 for i in range(len(windds1.Codes))] } dc2 = { 'codes': windds2.Data[0], 'date': windds2.Data[1], 'status': [2 for i in range(len(windds2.Codes))] } df1 = pd.DataFrame(dc1) df2 = pd.DataFrame(dc2) df = pd.concat([df1, df2], ignore_index=True) df = df.sort_values(by=["codes", 'date']) code = [] entrydate = [] removedate = [] i = 0 while (i < len(df)): if (df.iloc[i][2] == 2): i += 1 elif (i < (len(df) - 1) and df.iloc[i][0] == df.iloc[i + 1][0]): code.append(df.iloc[i][0]) entrydate.append( str(df.iloc[i][1])[0:4] + str(df.iloc[i][1])[5:7] + str(df.iloc[i][1])[8:10]) removedate.append( str(df.iloc[i + 1][1])[0:4] + str(df.iloc[i + 1][1])[5:7] + str(df.iloc[i + 1][1])[8:10]) i += 2 else: code.append(df.iloc[i][0]) entrydate.append( str(df.iloc[i][1])[0:4] + str(df.iloc[i][1])[5:7] + str(df.iloc[i][1])[8:10]) removedate.append(None) i += 1 dc = {'Ticker': code, 'EntryDate': entrydate, 'RemoveDate': removedate} df = pd.DataFrame(dc) code = [] for i in range(len(df)): if (df.iloc[i][2] == None): code.append(df.iloc[i][0]) dc = {'Ticker': code, 'Date': [timestr for i in range(len(code))]} df = pd.DataFrame(dc) return (df)
def QA_fetch_get_stock_risk(name, startDate, endDate): from WindPy import w w.start() w.isconnected() if(is_valid_date(endDate)==False): print ("wrong date") else : data=w.wsd(name, "annualyeild_100w,annualyeild_24m,annualyeild_60m,annualstdevr_100w,annualstdevr_24m,annualstdevr_60m,beta_100w,beta_24m,beta_60m,avgreturn,avgreturny,stdevry,stdcof,risk_nonsysrisk1,r2,alpha2,beta,sharpe,treynor,jensen,jenseny,betadf", startDate, endDate, "period=2;returnType=1;index=000001.SH;yield=1") if (data.ErrorCode==0): print ("Connent to Wind successfully") return data.Data
def QA_fetch_get_stock_list(date): from WindPy import w w.start() w.isconnected() if (is_valid_date(date) == False): print("wrong date") else: awgs = 'date=' + date + ';sectorid=a001010100000000' data = w.wset("sectorconstituent", awgs) return pd.DataFrame(np.asarray(data.Data).T, columns=data.Fields, index=data.Times)
def QA_fetch_get_stock_xueqiu(name, startDate, endDate): from WindPy import w #w.start() w.start() w.isconnected() if(is_valid_date(endDate)==False): print ("wrong date") else : data=w.wsd(name, "xq_accmfocus,xq_accmcomments,xq_accmshares,xq_focusadded,xq_commentsadded,xq_sharesadded,xq_WOW_focus,xq_WOW_comments,xq_WOW_shares", startDate, endDate, "") if (data.ErrorCode==0): print ("Connent to Wind successfully") return data.Data
def QA_fetch_get_stock_shape(name, startDate, endDate): from WindPy import w #w.start() w.start() w.isconnected() if(is_valid_date(endDate)==False): print ("wrong date") else : #history_low近期创历史新低,stage_high近期创阶段新高,history_high近期创历史新高,stage_low近期创阶段新高,up_days连涨天数,down_days连跌天数,breakout_ma向上有效突破均线,breakdown_ma向下有效突破均线,bull_bear_ma均线多空排列看涨看跌 data=w.wsd(name, "history_low,stage_high,history_high,stage_low,up_days,down_days,breakout_ma,breakdown_ma,bull_bear_ma", startDate, endDate, "n=3;m=60;meanLine=60;N1=5;N2=10;N3=20;N4=30;upOrLow=1") if (data.ErrorCode==0): print ("Connent to Wind successfully") return data.Data
def QA_fetch_get_stock_indicator(name, startDate, endDate): from WindPy import w #w.start() w.start() w.isconnected() if(is_valid_date(endDate)==False): print ("wrong date") else : #ADTM动态买卖气指标,ATR真实波幅,BBI多空指数,BBIBOLL多空布林线,BIAS乖离率,BOLL布林带,CCI顺势指标,CDP逆势操作,DMA平均线差,DMI趋向标准,DPO区间震荡线,ENV,EXPMA指数平滑移动平均,KDJ随机指标,slowKD慢速kd,MA简单移动平均,MACD指数平滑移动平均,MIKE麦克指数,MTM动力指标,PRICEOSC价格震荡指标,PVT量价趋势指标,RC变化率指数,ROC变动速率,RSI相对强弱指标,SAR抛物转向,SI摆动指标,SOBV能量潮,SRMI MI修正指标,STD 标准差,TAPI 加权指数成交值,TRIX 三重指数平滑平均,VHF纵横指标,VMA量简单移动平均,VMACD量指数平滑移动平均,VOSC成交量震荡,WVAD威廉变异离散量,vol_ratio量比 data=w.wsd(name, "ADTM,ATR,BBI,BBIBOLL,BIAS,BOLL,CCI,CDP,DMA,DMI,DPO,ENV,EXPMA,KDJ,slowKD,MA,MACD,MIKE,MTM,PRICEOSC,PVT,RC,ROC,RSI,SAR,SI,SOBV,SRMI,STD,TAPI,TRIX,VHF,VMA,VMACD,VOSC,WVAD,vol_ratio", startDate,endDate, "ADTM_N1=23;ADTM_N2=8;ADTM_IO=1;ATR_N=14;ATR_IO=1;BBI_N1=3;BBI_N2=6;BBI_N3=12;BBI_N4=24;BBIBOLL_N=10;BBIBOLL_Width=3;BBIBOLL_IO=1;BIAS_N=12;BOLL_N=26;BOLL_Width=2;BOLL_IO=1;CCI_N=14;CDP_IO=1;DMA_S=10;DMA_L=50;DMA_N=10;DMA_IO=1;DMI_N=14;DMI_N1=6;DMI_IO=1;DPO_N=20;DPO_M=6;DPO_IO=1;ENV_N=14;ENV_IO=1;EXPMA_N=12;KDJ_N=9;KDJ_M1=3;KDJ_M2=3;KDJ_IO=1;SlowKD_N1=9;SlowKD_N2=3;SlowKD_N3=3;SlowKD_N4=5;SlowKD_IO=1;MA_N=5;MACD_L=26;MACD_S=12;MACD_N=9;MACD_IO=1;MIKE_N=12;MIKE_IO=1;MTM_interDay=6;MTM_N=6;MTM_IO=1;PRICEOSC_L=26;PRICEOSC_S=12;RC_N=50;ROC_interDay=12;ROC_N=6;ROC_IO=1;RSI_N=6;SAR_N=4;SAR_SP=2;SAR_MP=20;SR MI_N=9;STD_N=26;TAPI_N=6;TAPI_IO=1;TRIX_N1=12;TRIX_N2=20;TRIX_IO=1;VHF_N=28;VMA_N=5;VMACD_S=12;VMACD_L=26;VMACD_N=9;VMACD_IO=1;VOSC_S=12;VOSC_L=26;WVAD_N1=24;WVAD_N2=6;WVAD_IO=1;VolumeRatio_N=5") if (data.ErrorCode==0): print ("Connent to Wind successfully") return data.Data
def suspend1(timestr): w.start() w.isconnected() #timestr=input('tradedate') windds1 = w.wset( "tradesuspend", "startdate=" + timestr + ";enddate=" + timestr + ";field=date,wind_code") dc1 = { 'Ticker': windds1.Data[1], 'Date': [timestr for i in range(len(windds1.Data[1]))] } df = pd.DataFrame(dc1) return (df)
def QA_fetch_get_stock_list_special(date,id): from WindPy import w #w.start() w.start() w.isconnected() if(is_valid_date(date)==False): print ("wrong date") else : # # if id in ['big','small','cixin','yujing','rzrq','rq','yj','st','sst']: awgs='date='+date+';sectorid='+data_list.wind_stock_list_special_id[id] data=w.wset("sectorconstituent",awgs) return data.Data
def QA_fetch_get_stock_day_simple(name, startDate, endDate): from WindPy import w #w.start w.start() w.isconnected() if(is_valid_date(endDate)==False): print ("wrong date") else : data=w.wsd(name,"sec_name,preclose,open,high,low,close,volume",startDate,endDate, "Fill=Previous;PriceAdj=F") #data=w.wsd("000002.SZ", "open,high,low,close,volume", "2017-03-03", "2017-04-01", "PriceAdj=B") print(data.ErrorCode) if (data.ErrorCode==0): print ("Connent to Wind successfully") return data.Data
def download_data_wind(start_date, end_date, var_list): if w.isconnected() == False: w.start() raw = w.wsd(var_list, "open, high, low, close", start_date, end_date, "") raw_df = pd.DataFrame(raw.Data, index=raw.Fields, columns=raw.Times) raw_df = raw_df.T return raw_df
def start_service(): if w.isconnected(): w.start() try: app.run(host="0.0.0.0", debug=True) finally: w.close()
def get_seq_w(self, start, end): """ 根据开始时间和结束时间,返回频率为“W"的回测任务确定新仓位时间list. :param start: str, 开始时间. :param end: str, 结束时间. :return: list, 计算下期仓位各时点list。 """ if not w.isconnected(): w.start() sleep(3) # wind的w.tdays函数准确性较差,需要严格检验 # seq = w.tdays(start, end, f"Period=W;TradingCalendar={self.calendar}").Data[0] # 转换为工作日 seq = w.tdays(start, end, "Period=W;Days=Weekdays").Data[0] if seq[-1].weekday() != 4: seq.pop() seq = [dd.strftime("%Y-%m-%d") for dd in seq] month = [] seq_ = [] for ss in seq: if ss[0:7] not in month: # 只有在新月份出现时才可能出现更新 month.append(ss[0:7]) seq_.append((ss, len(month) - 1)) else: seq_.append((ss, 0.5)) return seq_
def __init__(self, spec, basic_indices, ics_indices, ics, ics_fv, ics_rank, mode="run", check_w=False): self._date = "" self._spec = spec self.basic_indices = basic_indices self.ics_indices = ics_indices self.ics = ics self.ics_fv = ics_fv self.ics_rank = ics_rank self._codes = [] self._fields = None self._spec_id = [] self._names = [] self.df_all = None self.df_filter = None self.pool_codes = None self.print_obj = PrintOnce() if mode == "test": self._flag = True else: self._flag = False if check_w: if not w.isconnected(): w.start() self.check_spec_id()
def set_universe(code, refDate=None): if Settings.data_source == DataSource.WIND: from WindPy import w if not w.isconnected(): w.start() if not refDate: rawData = w.wset('IndexConstituent', 'windcode=' + convert2WindSymbol(code), 'field=wind_code') else: rawData = w.wset('IndexConstituent', 'date=' + refDate, 'windcode=' + convert2WindSymbol(code), 'field=wind_code') if len(rawData.Data) == 0: return # convert to .xshg/.xshe suffix idx = [s.replace('SH', 'xshg') for s in rawData.Data[0]] idx = [s.replace('SZ', 'xshe') for s in idx] return idx elif Settings.data_source != DataSource.DXDataCenter: import os import tushare as ts try: ts.set_token(os.environ['DATAYES_TOKEN']) except KeyError: raise idx = ts.Idx() return list(idx.IdxCons(secID=code, field='consID')['consID']) else: from DataAPI import api data = api.GetIndexConstitutionInfo( code, refDate=refDate).sort_values('conSecurityID') return list(data.conSecurityID)
def download_data_wind(start_date, end_date, var_list): if w.isconnected() == False: w.start() raw = w.edb(var_list, start_date, end_date) raw_df = pd.DataFrame(raw.Data, index=raw.Codes, columns=raw.Times) raw_df = raw_df.T return raw_df
def get_sec_return_on_date(cls, start_date, end_date, sec_ids, freq=FreqType.EOD, field=['close'], return_type=DfReturnType.DateIndexAndSecIDCol, is_cumul=False): """ :param start_date: str, start date of the query period :param end_date: str, end date of the query period :param sec_ids: list of str, sec IDs :param field: str, filed of data to be queried :param freq: FreqType :param return_type :param is_cumul: return is cumul or not :return: pd.DataFrame, index = date, col = sec ID """ if not w.isconnected(): w.start() ret = WindMarketDataHandler.get_sec_price_on_date( start_date, end_date, sec_ids, freq, field, return_type) ret = ret.pct_change() if is_cumul: ret = ret.fillna(0) ret = cum_returns(ret, starting_value=1.0) else: ret = ret.dropna() return ret
def get_sec_price_on_date(cls, start_date, end_date, sec_ids, freq=FreqType.EOD, field=['close'], return_type=DfReturnType.DateIndexAndSecIDCol): """ :param start_date: str, start date of the query period :param end_date: str, end date of the query period :param sec_ids: list of str, sec IDs :param freq: FreqType :param field: str, filed of data to be queried :param return_type: dfReturnType :return: pd.DataFrame, index = date, col = sec ID """ if not w.isconnected(): w.start() pyFinAssert( freq == FreqType.EOD, ValueError, "for the moment the function only accepts freq type = EOD") start_date = str(start_date) if not isinstance( start_date, basestring) else start_date end_date = str(end_date) if not isinstance(end_date, basestring) else end_date raw_data = w.wsd(sec_ids, field, start_date, end_date, 'PriceAdj=F', 'Fill=Previous') ret = format_raw_data(raw_data, sec_ids, freq, field, return_type) return ret
def get_seq_d(self, start, end): """ 根据开始时间和结束时间,返回频率为“D"的回测任务确定新仓位时间list. :param start: str, 开始时间. :param end: str, 结束时间. :return: list, 计算下期仓位各时点list。 """ if not w.isconnected(): w.start() sleep(3) # 日频级别暂时不变更为工作日日历,对于假期造成的不交易,当天仓位无法变更 seq = w.tdays(start, end, f"TradingCalendar={self.calendar}").Data[0] seq = [dd.strftime("%Y-%m-%d") for dd in seq] month = [] seq_ = [] for ss in seq: if ss[0:7] not in month: # 只有在新月份出现时才可能出现更新 month.append(ss[0:7]) seq_.append((ss, len(month) - 1)) else: seq_.append((ss, 0.5)) return seq_
def wss(cls, codes, paras): """多代码多维信息序列 :param codes:(list) or (str) :param paras:(list) or (str) :return:(DataFrame); """ try: if not w.isconnected(): w.start() if type(codes) is not list: codes = codes.split(",") # 全部转换为list格式 codes = [cls.mapper[x] if x in cls.mapper else x for x in codes] if type(paras) is not list: paras = paras.split(",") paras.insert(0, "windcode") windData = w.wss(codes, paras, options=None) if len(windData.Data) == 0: return None if len(windData.Data[0]) == 0: return None dataDict = {} for i in range(len(windData.Data)): dataDict[windData.Fields[i].lower()] = windData.Data[i] df = pd.DataFrame(dataDict) df = df[paras] df.rename(columns={"windcode": "code"}, inplace=True) return df except BaseException as e: print(format(e)) raise
def post(self): """ json str:{"offset": "1", "begin_time": "2017-3-31", "options": ""} :return: 返回万得返回数据dict """ data_dic = request.json logger.info('/tdaysoffset/ data_dic:%s', data_dic) offset = int(data_dic['offset']) begin_time = data_dic['begin_time'] options = data_dic['options'] if not w.isconnected(): w.start() if options == "": options = None ret_data = w.tdaysoffset(offset, begin_time, options) error_code = ret_data.ErrorCode if error_code != 0: msg = ERROR_CODE_MSG_DIC.setdefault(error_code, "") logger.error('tdaysoffset("%s", "%s", "%s") ErrorCode=%d %s' % (offset, begin_time, options, error_code, msg)) return {'error_code': ret_data.ErrorCode, 'message': msg}, 404 # if ret_data.ErrorCode != 0: # logger.error( # 'tdaysoffset("%s", "%s", "%s") ErrorCode=%d' % (offset, begin_time, options, ret_data.ErrorCode)) # return {'error_code': ret_data.ErrorCode}, 404 # 将 Data数据中所有 datetime date 类型的数据转换为 string if len(ret_data.Data) > 0 and len(ret_data.Data[0]) > 0: date_str = format_2_date_str(ret_data.Data[0][0]) else: logger.warning('tdaysoffset(%s, %s, %s) No value return' % (offset, begin_time, options)) date_str = '' ret_dic = {'Date': date_str} # print('offset:\n', ret_dic) return ret_dic
def QA_fetch_get_trade_date(endDate, exchange): from WindPy import w # w.start() w.start() w.isconnected() supportExchanges = ["SSE", "SZSE", "CFFEX", "SHFE", "DCE", "CZCE"] if (exchange in supportExchanges): #"SSE","SZSE","CFFEX","SHFE","DCE","CZCE" # 上海股票交易所,深圳股票交易所,中国金融期货交易所,上海期货交易所,大连商品交易所,郑州期货交易所 exchanges = "TradingCalendar=" + exchange data = w.tdays("1990-01-01", endDate, exchanges) # print(data.Data) dates = data.Data else: print("exchange name problem") return dates
def get_cons_maxUpOrDown(self, beginDate, endDate): '''利用wind获得列表中每个股票在特定日期的涨跌停情况 Args: self.consTicker: Series, 交易代码序列 self.tradeDate: str, 交易时间 Returns: self.consMaxUpOrDown: dict, 交易代码对应是否涨跌停 ''' # w.start() exchange = '.SH' if (w.isconnected()): length = len(self.consTicker) for i in range(length): Ticker = str(self.consTicker.values[i]) wind = w.wsd(Ticker + exchange, "maxupordown", beginDate, endDate, usedf=True) maxUpOrDown = wind[1] self.consMaxUpOrDown[Ticker] = maxUpOrDown # print("NO. %d, Ticker = %s"%(i,Ticker)) print(" %.2d " % i, sep=">", end='') print("get_cons_maxUpOrDown ...... Done!") print("\n") else: print("Wind Starting Error!")
def post(self): """ json str:{"codes": "XT1522613.XT", "fields": "fund_setupdate,fund_maturitydate,fund_mgrcomp,fund_existingyear,fund_fundmanager", "options": ""} :return: 返回万得返回数据dict """ args = receive_wss_parser.parse_args() logger.info('/wss/ args:%s', args) # codes = args['codes'] # fields = args['fields'] # options = args['options'] if args['options'] == "": args['options'] = None if not w.isconnected(): w.start() ret_data = None for nth in range(2): ret_data = w.wss(**args) error_code = ret_data.ErrorCode if error_code != 0: if nth == 0 and error_code == -40521010: w.stop() w.start() logger.warning('尝试重新登陆成功,再次调用函数') continue msg = ERROR_CODE_MSG_DIC.setdefault(error_code, "") logger.error('wss(%s) ErrorCode=%d %s' % (args, error_code, msg)) raise RequestError(msg, None, error_code) else: break else: if ret_data is None: msg = 'wst(%s) ret_data is None' % args logger.error(msg) raise RequestError(msg, None, 0) # 将 Data数据中所有 datetime date 类型的数据转换为 string data_len = len(ret_data.Data) logger.debug('ret_data.Data len:%d', data_len) logger.debug('ret_data.Codes : %s', ret_data.Codes) for n_data in range(data_len): data = ret_data.Data[n_data] data_len2 = len(data) if data_len2 > 0: if type(data[0]) in (datetime, date): ret_data.Data[n_data] = [ format_2_date_str(dt) for dt in data ] logger.info('%d column["%s"] date to str', n_data, ret_data.Fields[n_data]) # print('ret_data.Data:\n', ret_data.Data) # 组成 DataFrame ret_df = pd.DataFrame(ret_data.Data, index=ret_data.Fields, columns=ret_data.Codes) ret_dic = ret_df.to_dict() # print('ret_dic:\n', ret_dic) return ret_dic
def QA_fetch_get_stock_info(name, startDate, endDate): from WindPy import w #w.start() w.start() w.isconnected() #get the all stock list on the endDate # judge the vaild date if(is_valid_date(endDate)==False): print ("wrong date") else : #tempStr='date='+endDate+";sectorid=a001010100000000" #data=w.wset("sectorconstituent",tempStr) data=w.wsd(name, "sec_name,sec_englishname,ipo_date,exch_city,mkt,sec_status,delist_date,issuecurrencycode,curr,RO,parvalue,lotsize,tunit,exch_eng,country,concept,marginornot,SHSC,parallelcode,sec_type,backdoor,backdoordate,windtype", startDate, endDate) #print(data) if (data.ErrorCode!=0): print ("Connent to Wind successfully") return data.Data
def login(is_quiet=False): if not WDServer.isconnected(): login = WDServer.start() if not is_quiet: print(colored("WDServer is connected successfully!", "green")) else: if not is_quiet: print(colored("WDServer is already connected!", "green"))
def start(self): '''the main function to perform all operations''' print('开始程序') w.start(60) #if cannot connect to wind, just stop if not w.isconnected(): print('无法连接万德') print('程序结束') w.stop() return #otherwise print('万德已连接') print('开始处理数据') #期货行情 today = datetime.now() print('今天是', today.strftime('%Y-%m-%d')) loop = asyncio.get_event_loop() exchanges = self.config['futures']['exchanges'] for eid in dict.keys(exchanges): instruments = exchanges[eid] instrument = None for instrument in instruments: print('处理品种 ' + instrument + ' 交易所 ' + eid) items = [] i = 0 for i in range(today.month, today.month + 13, 1): iid = instrument if i > 12: iid = iid + self.fix_instrument(str(today.year + 1)[2:] + \ pad_month(i % 12), eid) else: iid = iid + self.fix_instrument(str(today.year)[2:] + \ pad_month(i), eid) iid = iid + '.' + eid items.append(iid) tasks = [] for item in items: tasks.append(asyncio.ensure_future(self.process_item(w, item))) try: loop.run_until_complete(asyncio.wait(tasks)) except: print('循环产生异常:处理品种' + instrument + '期货价格数据') finally: print('完成品种 ' + instrument + ' 交易所 ' + eid) loop.close() print('程序结束') w.stop()
import datetime import sqlite3 import numpy conn=sqlite3.connect("stockr.db3") cur=conn.cursor() #get data for one year numdays=150 #clear the table and keep only data a year from now cur.execute("delete from dp") #start connection with Wind w.start() # if connected to Wind if w.isconnected(): #fetch data # personal version allows 600000-600120 stockStartIndex=600000 for j in range(0,100): stockIndex=stockStartIndex+j print ("j="+str(j)) stock=str(stockIndex)+".sh" oneday=datetime.timedelta(days=1) totaldays=datetime.timedelta(days=numdays) dateEnd=datetime.date.today() dateStr=dateEnd-totaldays strdateStr=str(dateStr).replace("-","").split(" ")[0]
######## coding=gbk __author__ = 'henry' import site import sys reload(sys) sys.setdefaultencoding( "utf-8" ) from WindPy import w from Utility import str1D from Utility import str2D if (w.isconnected() != True): w.start(); #pwd:607387 stock_code = sys.argv[1] start_date = sys.argv[2] end_date = sys.argv[3] # res= w.wset("TradeSuspend","startdate=20150122;enddate=20150122") fields = "sec_name,trade_status,susp_reason" res = w.wsd(stock_code, fields, start_date, end_date, "Fill=Previous") #1.List getStocks print "WindStockReuslt:" print res
#_*_coding:utf-8 _*_ from WindPy import w from _datetime import date import pymysql from math import isnan w.start() print('connection wind success', w.isconnected()) db = pymysql.connect(host="localhost", user="******", passwd="A123123123", db="fund", charset="utf8") cursor = db.cursor() def GetSWexponent(ExponentID=None,BeginTime=None,EndTime=None): if(ExponentID==None): print("沒有传入申万之一指数代码,数据将返回所有申万一级指数的数据") ExponentID = '801010.SI,801020.SI,801030.SI,\ 801040.SI,801050.SI,801080.SI,801110.SI,\ 801120.SI,801130.SI,801140.SI,801150.SI,\ 801160.SI,801170.SI,801180.SI,801200.SI,\ 801210.SI,801230.SI,801710.SI,801720.SI,\ 801730.SI,801740.SI,801750.SI,801760.SI,\ 801770.SI,801780.SI,801790.SI,801880.SI,\ 801890.SI' if(BeginTime==None): BeginTime = '2010-01-01' if(EndTime==None): EndTime=date.today(); tmp = (ExponentID,'close',BeginTime,EndTime,'Fill=Previous') data = w.wsd(*tmp)
# coding: utf-8 # In[1]: from WindPy import w from datetime import * from pandas import * import numpy as np import pandas as pd import matplotlib.pyplot as plt import csv import math import glob plt.style.use('ggplot'); w.start(); w.isconnected(); #set some dates today = datetime.today() yesterday = today-timedelta(4) d = yesterday.strftime('%Y%m%d') #set index for stock s = '000905.SH' import mdapi.stock from math import * import random # In[2]: def tradedate(startDate,endDate):
# from spotimporter import SpotImporter # from indeximporter import IndexImporter # from volumeimporter import VolumeImporter if __name__ == '__main__': '''main function''' print('开始程序') config = None with open('config.json', encoding='utf-8') as config_file: config = json.load(config_file, encoding='utf-8') if config is None: print('无法读取配置文件config.json') #move on to perform the actual job w.start(60) if not w.isconnected(): print('无法连接万德') else: print('万德已连接') print('开始处理数据') #grab the main loop loop = asyncio.get_event_loop() #future quotes upload future_importer = FutureImporter(loop, w, config) future_importer.run() # spot_importer = SpotImporter(loop, w, config) # spot_importer.run() # index_importer = IndexImporter(loop, w, config)