Exemplo n.º 1
0
def GetLastTradeDate():
    end_date = date.today()
    count = w.tdayscount(end_date)
    if count.Data == 0 or datetime.now().hour <= 15:
        return w.tdaysoffset(-1, end_date).Data[0][0].date()

    return end_date
Exemplo n.º 2
0
def func11():
    yesterday = (datetime.datetime.now() - datetime.timedelta(days = 1)).strftime("%Y-%m-%d") 
    df_industry=pd.read_csv('industry.csv')
    last_date_industry = time.strftime("%Y-%m-%d",time.strptime(str(int(df_industry.iloc[-1,0])),"%Y%m%d"))
    day_gap_industry = w.tdayscount(last_date_industry, yesterday).Data[0][0]-1
    print 11
    w_wsd_data={}
    stock_ls=[]
    for stock in list(df_industry.columns.values)[1:]  :
        stock_ls.append(stock)
        w_wsd_data[stock] = w.wsd(stock, 'close',  (w.tdaysoffset(1,last_date_industry).Data[0][0]).strftime("%Y-%m-%d"),yesterday)
        print w_wsd_data
    f=open('industry.csv','a')   
    for i in xrange(day_gap_industry):
  
        this_day = w.tdaysoffset(i+1,last_date_industry)
        ls = []
        this_day_csv = (this_day.Data[0][0]).strftime("%Y%m%d")
        for stock in stock_ls:
            ls.append(w_wsd_data[stock].Data[0][i])  
            
        
        f.write(this_day_csv)
        for stock_data in ls:
            f.write(",")
            f.write(str(stock_data))
        f.write("\n")
    f.close()
        
    print 'finish'
Exemplo n.º 3
0
def func2():

    yesterday = (datetime.datetime.now() - datetime.timedelta(days = 1)).strftime("%Y-%m-%d") 
    df_openA=pd.read_csv('openA.csv')
    last_date_openA = time.strftime("%Y-%m-%d",time.strptime(str(int(df_openA.iloc[-1,0])),"%Y%m%d"))
    day_gap_openA = w.tdayscount(last_date_openA, yesterday).Data[0][0]-1
    print 2
    w_wsd_data={}
    stock_ls=[]
    for stock in universe:
        if stock[0]=='1':
            stock = stock + '.SZ'
        else:
            stock += '.SH'
        stock_ls.append(stock)
        w_wsd_data[stock] = w.wsd(stock, 'open',  (w.tdaysoffset(1,last_date_openA).Data[0][0]).strftime("%Y-%m-%d"),yesterday)
      
    for i in xrange(day_gap_openA):
        
        this_day = w.tdaysoffset(i+1,last_date_openA)
        ls = []
        this_day_csv = (this_day.Data[0][0]).strftime("%Y%m%d")

        for stock in stock_ls:
            ls.append(w_wsd_data[stock].Data[0][i])  
            
        f=open('openA.csv','a')
        f.write(this_day_csv)
        for stock_data in ls:
            f.write(",")
            f.write(str(stock_data))
        f.write("\n")
        f.close()
    print 'finish'
Exemplo n.º 4
0
def func9():
    yesterday = (datetime.datetime.now() - datetime.timedelta(days = 1)).strftime("%Y-%m-%d") 
    df_discount_ratio_M = pd.read_csv('discount_ratio_M.csv')
    last_date_discount_ratio_M = time.strftime("%Y-%m-%d",time.strptime(str(int(df_discount_ratio_M.iloc[-1,0])),"%Y%m%d"))
    day_gap_discount_ratio_M = w.tdayscount(last_date_discount_ratio_M, yesterday).Data[0][0]-1
    w_wsd_data={}
    print 9
    stock_ls=[]
    for stock in universe:
        if stock[0]=='1':
            stock = stock + '.SZ'
        else:
            stock = stock + '.SH'

        mA_code = w.wsd(stock, 'fund_smfcode', yesterday).Data[0][0]
        stock_ls.append(mA_code)
        w_wsd_data[mA_code] = w.wsd(mA_code, 'anal_tdiscountratio', (w.tdaysoffset(1,last_date_discount_ratio_M).Data[0][0]).strftime("%Y-%m-%d"),yesterday)  
    for i in xrange(day_gap_discount_ratio_M):
        this_day = w.tdaysoffset(i+1,last_date_discount_ratio_M)
        ls = []
        this_day_csv = (this_day.Data[0][0]).strftime("%Y%m%d")
        
        for stock in stock_ls:
            ls.append(w_wsd_data[stock].Data[0][i])  
        f=open('discount_ratio_M.csv','a') 
        f.write(this_day_csv)
        for stock_data in ls:
            f.write(",")
            f.write(str(stock_data))
        f.write("\n")
        f.close()
    print 'finish'
Exemplo n.º 5
0
def volitility(code, T, numOfYearBefore):
    EndDay = datetime.date.today()
    BeginDay = EndDay - relativedelta(years=numOfYearBefore)
    LogRet = RevisedLogRet(code, BeginDay, EndDay)
    days = w.tdayscount(EndDay - relativedelta(months=T), EndDay,
                        "").Data[0][0]
    vol = (LogRet.rolling(window=days, center=False).std() *
           np.sqrt(252)).dropna().iloc[-1][0]

    return vol
Exemplo n.º 6
0
    def get_tdays_count(self, begin_date, end_date, style=""):
        """
			获取日期间的周期数
			输入参数:
				begin_date 	起始日期
				end_date 	截止日期
				style		日期类型
			函数返回:
				返回周期数N
				返回类型:int
		"""
        option = {"Days": style}
        td = w.tdayscount(begin_date, end_date, **option)
        return td.Data[0][0]
Exemplo n.º 7
0
def func6():

    yesterday = (datetime.datetime.now() - datetime.timedelta(days = 1)).strftime("%Y-%m-%d") 
    df_closeB=pd.read_csv('closeB.csv')
    last_date_closeB = time.strftime("%Y-%m-%d",time.strptime(str(int(df_closeB.iloc[-1,0])),"%Y%m%d"))
    day_gap_closeB = w.tdayscount(last_date_closeB, yesterday).Data[0][0]-1
    print 6
    w_wsd_data={}
    stock_ls=[]
    for stock in universe:
        if stock =='150073':
            stock='150075.SZ'
        else:
            if stock[0]=='1':
                stock = str(int(stock[:6])+1) + '.SZ'
            else:
                stock = str(int(stock[:6])+1) + '.SH'
        stock_ls.append(stock)

        w_wsd_data[stock] = w.wsd(stock, 'close',  (w.tdaysoffset(1,last_date_closeB).Data[0][0]).strftime("%Y-%m-%d"),yesterday)
       # print 1
        print stock
        #if w_wsd_data[stock].Data[0][0]==None:
    for i in xrange(day_gap_closeB):
  
        this_day = w.tdaysoffset(i+1,last_date_closeB)
        ls = []
        this_day_csv = (this_day.Data[0][0]).strftime("%Y%m%d")
        for stock in stock_ls:
            ls.append(w_wsd_data[stock].Data[0][i])  
            
        f=open('closeB.csv','a')   
        f.write(this_day_csv)
        for stock_data in ls:
            f.write(",")
            f.write(str(stock_data))
        f.write("\n")
        f.close()
        
    print 'finish'
Exemplo n.º 8
0
 def tdays_count(begin_date, end_date):
     w.start()
     result = w.tdayscount(begin_date.strftime("%Y-%m-%d"), end_date.strftime("%Y-%m-%d"), "").Data[0][0]
     return result
Exemplo n.º 9
0
def updatePal(palPath=None):
    start = time.time()

    md.init('18201141877', 'Wqxl7309')
    if not w.isconnected():
        w.start()

    palPath = r'E:\bqfcts\bqfcts\data\Paltest' if palPath is None else palPath
    tempFilePath = os.path.join(palPath,'temp_files')
    if not os.path.exists(tempFilePath):
        os.mkdir(tempFilePath)
    matName = 'data_20150701_now.mat'

    savedPal = h5py.File(os.path.join(palPath,matName))
    # print(read_cell(savedPal,'sec_names'))
    nextTrd = dt.datetime.strptime(str(int(savedPal['nexttrd'][0][0])),'%Y%m%d')
    nextTrdStr = nextTrd.strftime('%Y-%m-%d')
    updateTime = dt.datetime(nextTrd.year,nextTrd.month,nextTrd.day,15,30,0)
    if updateTime > dt.datetime.now():
        print('not update time yet')
        return
    else:
        availableDateStr = md.get_last_dailybars('SHSE.000001')[0].strtime[:10]
        if int(availableDateStr.replace('-','')) <= int(nextTrdStr.replace('-','')):
            print('new data not avaliable yet')
            return
        else:
            print('will update from {0} to {1}'.format(nextTrdStr,availableDateStr))

    betweenDays = [tdt.strtime[:10] for tdt in md.get_calendar('SHSE',nextTrdStr,availableDateStr)]
    if nextTrdStr!=availableDateStr:    # 避免同一日期重复
        betweenDays.append(availableDateStr)
    betweenDaysNumber = [int(tdt.replace('-','')) for tdt in betweenDays]
    newDateNum = len(betweenDaysNumber)

    # 更新前 先备份数据
    backupPath = os.path.join(palPath,'backup')
    cpResult = os.system(r'COPY {0} {1} /Y'.format(os.path.join(palPath,matName),os.path.join(backupPath,matName)))
    assert cpResult==0,'backup failed'

    gmDateFmt = 'yyyy-mm-dd'

    # update indice
    indiceNames = ['sh','hs300','zz500','sz50']
    indiceCodes = ['000001','000300','000905','000016']
    symbols = ','.join(['SHSE.{}'.format(sbl) for sbl in indiceCodes])
    indiceBars = md.get_dailybars(symbols,nextTrdStr,availableDateStr)
    for dumi,idx in enumerate(indiceNames):
        bars = indiceBars[dumi::4]
        idxret = np.array([bar.close for bar in bars])/np.array([bar.pre_close for bar in bars]) - 1
        idxArray = np.array([betweenDaysNumber,
                             [bar.open for bar in bars],
                             [bar.high for bar in bars],
                             [bar.low for bar in bars],
                             [bar.close for bar in bars],
                             [bar.volume for bar in bars],
                             [bar.amount for bar in bars],
                             idxret
                             ])
        # newIndex = np.column_stack([savedPal['index_{}'.format(idx)][:], idxArray])
        pd.DataFrame(np.transpose(idxArray)).to_csv(os.path.join(tempFilePath,'index_{}.csv'.format(idx)),index=False,header=False)

    # update stock info
    nCut = savedPal['N_cut'][0][0]    # 6000
    nEnd = savedPal['N_end'][0][0]    # last end date id ex.6732
    stockNames = read_cell(savedPal, 'stockname')
    savedStkcdsGM = ['.'.join([stk[-2:]+'SE',stk[:6]]) for stk in stockNames]
    savedStkNum = len(stockNames)
    listedStkcdsWind =  w.wset('sectorconstituent','date={};sectorid=a001010100000000'.format(availableDateStr)).Data[1]
    newStkcdsWind = sorted(list(set(listedStkcdsWind) - set(stockNames)))
    if newStkcdsWind:
        stockNames.extend( newStkcdsWind )
        newStkIpos = [int(tdt.strftime('%Y%m%d')) for tdt in w.wss(newStkcdsWind, 'ipo_date').Data[0]]
        newIpoIds = [(w.tdayscount(nextTrd,str(ipo)).Data[0][0]+nEnd) for ipo in newStkIpos]
        newStockip = pd.DataFrame([[int(newStkcdsWind[dumi][:6]), newStkIpos[dumi], newIpoIds[dumi],0,0,0,0,0] for dumi in range(len(newStkcdsWind))])
        newStockip.to_csv( os.path.join(tempFilePath,'stockip.csv'),index=False,header=False )
    else:
        pd.DataFrame([]).to_csv(os.path.join(tempFilePath, 'stockip.csv'), index=False, header=False)
    newStkcdsGm = ['.'.join([stk[-2:]+'SE',stk[:6]]) for stk in newStkcdsWind]
    allStkcdsGM = savedStkcdsGM + newStkcdsGm     # 全体股票包含已退市 与pal行数相同
    # allSecNames = pd.DataFrame(w.wss(stockNames,'sec_name').Data[0])
    allInstruments = md.get_instruments('SZSE', 1, 0) + md.get_instruments('SHSE', 1, 0)
    allInstrumentsDF = pd.DataFrame([[inds.symbol, inds.sec_name] for inds in allInstruments],columns=['symbol','sec_name']).set_index('symbol')
    allSecNames = allInstrumentsDF.loc[allStkcdsGM,'sec_name']
    allSecNames.to_csv( os.path.join(tempFilePath, 'sec_names.csv'), index=False, header=False )
    pd.DataFrame(newStkcdsWind).to_csv( os.path.join(tempFilePath, 'stockname.csv'), index=False, header=False )

    # update trade info
    pages = ['date','open','high','low','close','volume','amount','pctchg','flow_a_share','total_share','adjfct','adjprc','isst']
    newPal = {}
    for page in pages:
        newPal[page] = pd.DataFrame(np.zeros([len(allStkcdsGM), newDateNum]),index=allStkcdsGM,columns=betweenDays)
    lastPal = pd.DataFrame(savedPal['Pal'][:,-1,:],columns=savedStkcdsGM)
    barsDaily = md.get_dailybars(','.join(allStkcdsGM), nextTrdStr, availableDateStr)
    for bar in barsDaily:
        tdt = bar.strtime[:10]
        stk = '.'.join([bar.exchange,bar.sec_id])
        newPal['date'].loc[stk, tdt] = int(tdt.replace('-',''))
        newPal['open'].loc[stk, tdt] = bar.open
        newPal['high'].loc[stk, tdt] = bar.high
        newPal['low'].loc[stk, tdt] = bar.low
        newPal['close'].loc[stk, tdt] = bar.close
        newPal['volume'].loc[stk, tdt] = bar.volume
        newPal['amount'].loc[stk, tdt] = bar.amount
        newPal['pctchg'].loc[stk, tdt] = bar.close/bar.pre_close - 1
        # 计算自算复权因子 : 前一日收盘价*(1+当日收益率)/当日收盘价 s.t. (当日收盘价*当日复权因子)/前一日收盘价 = 1+ret
        # 若当日没有交易 : 沿用前一日 复权因子  循环外处理
        # 若前一日没有交易 前一日收盘价 特殊处理:
        #  当日有交易 : 取停牌前最后一个交易日的 收盘价
        #  当日没交易 没有退市 : 沿用前一日复权因子  循环外处理
        #  当日没交易 已经退市 : 沿用前一日复权因子  循环外处理
        # 若新股上市第一天 : 复权因子为1
        if stk in newStkcdsGm:
            newPal['adjfct'].loc[stk, tdt] = 1
        else:
            noTrdLast = (lastPal.loc[0, stk] == 0) if tdt == nextTrdStr else (newPal['date'].loc[stk, betweenDays[betweenDays.index(tdt) - 1]] == 0)
            if noTrdLast: # 前一日没交易 今日有交易(否则不应出现在bars里面)
                lastBar = md.get_last_n_dailybars(stk, 2, end_time=tdt)[-1]
                newPal['adjfct'].loc[stk, tdt] = lastPal.loc[15, stk] * lastBar.close * (1 + newPal['pctchg'].loc[stk, tdt]) / bar.close
            else:
                preClose = lastPal.loc[4,stk] if tdt==nextTrdStr else newPal['close'].loc[stk,betweenDays[betweenDays.index(tdt)-1]]
                newPal['adjfct'].loc[stk, tdt] = lastPal.loc[15, stk] * preClose * (1 + newPal['pctchg'].loc[stk, tdt]) / bar.close
    for dumi,tdt in enumerate(betweenDays):
        idx = newPal['adjfct'].loc[:,tdt]==0
        idx = idx.values
        if tdt==nextTrdStr:
            newPal['adjfct'].loc[idx[:savedStkNum], tdt] = lastPal.loc[15,:].values[idx[:savedStkNum]]
        else:
            newPal['adjfct'].loc[idx, tdt] = newPal['adjfct'].loc[idx, betweenDays[dumi-1]]
    newPal['adjprc'] = newPal['adjfct']*newPal['close']

    shareBar = md.get_share_index(','.join(allStkcdsGM), nextTrdStr, availableDateStr)
    for bar in shareBar:
        tdt = bar.pub_date
        stk = bar.symbol
        newPal['flow_a_share'].loc[stk, tdt] = bar.flow_a_share
        newPal['total_share'].loc[stk, tdt] = bar.total_share

    isST = np.array([int('ST' in sn) for sn in allSecNames.values])
    newPal['isst'] = pd.DataFrame(np.repeat(np.reshape(isST,(isST.shape[0],1)),len(betweenDays),axis=1), index=allStkcdsGM, columns=betweenDays)

    for page in newPal:
        newPal[page].to_csv(os.path.join(tempFilePath,'{}.csv'.format(page)),index=False,header=False )

    print('Pal temp files update finished with {0} stocks and {1} days in {2} seconds '.format(len(newStkcdsWind),len(betweenDays),time.time() - start))
Exemplo n.º 10
0
    ]
    r = 0.038
    l = len(code)

    #    df = pd.DataFrame(columns = [u'公司名称',u'品种',u'品种代码',
    #                                 u'期权类型',u'行权价',u'到期日/交易期限',
    #                                 u'最小交易单位',u'买价',u'卖价',
    #                                 u'标的价格',u'报价日期'])
    df = pd.DataFrame(columns=[
        u'报价日期', u'品种', u'品种代码', u'期权类型', u'标的价格', u'行权价', u'到期日/交易期限',
        u'最小交易单位', u'买价', u'卖价', u'', u'25%分位波动率', u'50%分位波动率', u'75%分位波动率',
        u'今日波动率', u'买价波动率', u'卖价波动率', u'对冲成本波动率', u'设定卖价溢出波动率', u'设定买价溢出波动率'
    ])

    T = w.tdayscount(datetime.date.today(),
                     datetime.date.today() + relativedelta(months=1),
                     "").Data[0][0]
    for i in range(l):
        OriTickData = w.wss(code[i], "mfprice").Data[0][0]
        tick = float(re.search(r'\d+(\.\d+)?', OriTickData).group(0))

        S0 = w.wsq(code[i], "rt_last").Data[0][0]
        K = S0

        a = BidAsk(code[i], tick, T, r)

        df1 = a.QuoteOneSpecies(S0, K)
        df = df.append(df1)
        print(code[i])

#    bookname = u'场外期权报价-渤海融盛'
Exemplo n.º 11
0
def ttradedayscount(begt, endt):
    w.start()
    days = w.tdayscount(begt, endt).Data[0]
    return days[0]
Exemplo n.º 12
0
__author__ = 'aming.tao'
from WindPy import w
from datetime import *
w.start()
data=w.wsd("600000.SH","close,amt","2013-04-30", datetime.today()-timedelta(1))#取浦发银行收盘价等信
data=w.wsd("600000.SH","close,amt", datetime.today()-timedelta(100))#

data=w.wsi("600000.SH","close,amt","2015-10-01 9:00:00")#取浦发银行分钟收盘价等信息

data=w.wst("600000.SH","open", datetime.today()-timedelta(0,2*3600), datetime.now())#取浦发银行tick数据信息

data=w.wss("600000.SH,000001.SZ","eps_ttm,orps,surpluscapitalps","rptDate=20121231")#取浦发银行等财务数据信息


data=w.wset("SectorConstituent",u"date=20130608;sector=全部A股")#取全部A 股股票代码、名称信息
w.wset("IndexConstituent","date=20130608;windcode=000300.SH;field=wind_code,i_weight")#取沪深300 指数中股票代码和权重
w.wset("TradeSuspend","startdate=20130508;enddate=20130608;field=wind_code,sec_name,suspend_type,suspend_reason")#取停牌信息
w.wset("SectorConstituent",u"date=20130608;sector=风险警示股票;field=wind_code,sec_name")#取ST 股票等风险警示股票信息

w.tdays("2013-05-01","2013-06-08")#返回5 月1 日到6 月8 日之间的交易日序列
w.tdays("2013-05-01")#返回5 月1 日到当前时间的交易日序列
w.tdaysoffset(-5,"2013-05-01")#返回5 月1 日前推五个交易日的日期,返回2013-4-19
w.tdaysoffset(-5)#返回当前时间前推五个交易日的日期
w.tdayscount("2013-05-01","2013-06-08")#返回5 月1 日到6 月8 日之间的交易日序列长度,为27

w.stop()