如何优化pandas从雅虎获取股票报价的性能

1 投票
1 回答
599 浏览
提问于 2025-04-17 21:02

我的代码是用来循环处理1200多个股票代码,从雅虎获取历史报价(大约160到200天)。因为这个过程需要时间,所以我把这些报价存储在csv文件里,这样可以方便下载在时间范围内的报价,也就是任何日期之间的报价,或者缺失的报价csv文件。我使用了pandas库里的一个函数,叫做get_data_yahoo(stocknum,start,end)。

不过,我发现整个过程所需的时间没有什么变化,下载一天的报价和下载200天的报价似乎所花的时间是一样的……pandas是怎么处理雅虎的股票报价的?有没有更好的数据源?我可以做些什么来加快这个过程吗?

下面是我用来获取股票报价的函数调用。

def readStockPrice(stock,period=200,delay=1):

#define the period for stock filtering
now=dt.date.today()
end=now.strftime("%Y-%m-%d")
#start=(now-dt.timedelta(days=period)).strftime("%Y-%m-%d")

if os.path.isfile('cache/'+stock+'.csv'):
    df=pd.read_csv('cache/'+stock+'.csv',index_col=0,parse_dates=True)
    lastrecorddate=df.index.to_pydatetime()[-1].date()
    delta=(now-lastrecorddate).days
    if delta>delay:

        #print("retrieving "+stock+" quotes from the web")
        start=(lastrecorddate+dt.timedelta(days=1)).strftime("%Y-%m-%d")
        try:
            df_delta=web.get_data_yahoo(stock,start,end)
            df=df.append(df_delta)
            df_delta.to_csv('cache/'+stock+'.csv',header=False,mode='a')
        except IOError:
            return pd.DataFrame()
else:
    #print("retrieving "+stock+" quotes from the web")
    start=(now-dt.timedelta(days=period)).strftime("%Y-%m-%d")
    try:
        df=web.get_data_yahoo(stock,start,end)
        if not df.empty:
            df.to_csv('cache/'+stock+'.csv')
    except IOError:
        return pd.DataFrame()

return df

1 个回答

0

Pandas使用一个叫做_get_hist_yahoo的功能来获取数据,这个功能在pandas/io/data.py文件里,下面是个例子:

def _get_hist_yahoo(sym, start, end, retry_count, pause):
"""
Get historical data for the given name from yahoo.
Date format is datetime

Returns a DataFrame.
"""
start, end = _sanitize_dates(start, end)
url = (_HISTORICAL_YAHOO_URL + 's=%s' % sym +
       '&a=%s' % (start.month - 1) +
       '&b=%s' % start.day +
       '&c=%s' % start.year +
       '&d=%s' % (end.month - 1) +
       '&e=%s' % end.day +
       '&f=%s' % end.year +
       '&g=d' +
       '&ignore=.csv')
return _retry_read_url(url, retry_count, pause, 'Yahoo!')

我觉得这个数据会从网址转成一个SQL查询,像这样:

where date between START_TIME and END_TIME

如果Yahoo在日期这一列上建立了索引,那么它就可以利用这个索引,这样响应时间就和时间段的长短没有关系了。

撰写回答