Home  >  Q&A  >  body text

怎样用python提取不同股票csv里特定时间段的数据

我有几千只股票的csv数据,需要算所有股票在特定时间段内的收益率。
但是数据里的日期信息并不统一,有的csv到2011年就没有了之后的信息了,有的csv仅有2012年1月后的数据。
所以用pandas读取数据后,希望筛选数据一个特定时间段里的数据(比如2012-07到2012-08两个月的数据)。
但是把时间作为索引后,根本无法将没有该时间段内数据的股票给跳过,总是报错,搜了各种pandas处理时间的方法也没能解决。

以下是csv数据截图/所有csv文件都是这样的形式

import os
import pandas as pd
import numpy as np
stdic=os.listdir(os.listdir(os.getcwd())[1])
del stdic[0]
date=['2012-07','2012-08']
#计算排序期J、持有期K内的对数收益率
def creturn(data,J,K):
    r=['','']
    r[0] = np.log(data[date[J-1]]['Adj Close'][0]/data[date[0]]['Adj Close'][-1])   #排序期收益率
    r[1] = np.log(data[date[J+K-1]]['Adj Close'][0]/data[date[J]]['Adj Close'][-1]) #持有期内收益率
    return r
rank=[]
#对每一个股票csv数据进行以上的计算并放入rank列表中
for item in stdic:
    fname = 'data/'+item
    data=pd.read_csv(fname)
    data=data.dropna()
    data['Date'] = pd.to_datetime(data['Date'])
    data = data[(data['Date'] >='20120701') & (data['Date'] <= '20120831')]
    data=data.set_index(['Date'])
    rank.append(creturn(data,1,1)[0])
报错的原因发现是,到了第10个csv文件的时候,csv里根本没有2012-07的数据,所以无法进行计算。
但是,就是无法把这种没有特定时段数据的文件跳过,不知道怎么筛选。。
希望各位大神能指点训斥一下。。。!
PHPzPHPz2741 days ago895

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:19:31

    It seems that the data['Date'] of pd.read_csv(fname) is not converted into date type,
    So your comparison is a string comparison, so it is wrong

    Provide a method:

    data['Date'] = pd.to_datetime(data['Date'])
    data = data[(data['Date'] >=pd.to_datetime('20120701')) & (data['Date'] <= pd.to_datetime('20120831'))]
    

    Reference:
    http://pandas.pydata.org/pand...

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:19:31

    I have also encountered a similar situation. When querying the row information in the database table, some rows have A field and some rows do not have A field. When there is no A field, an error will be reported when fetching the A field information. If the error is reported, this error will be captured and then stored. A default value for the variable in the A field information is OK, which can meet the skip requirement. You can try similar ideas

    reply
    0
  • Cancelreply