股票OHLC历史数据爬取——Yahoo

OHLC 指 open,high,low,close,老外的网站数据规范,相比从国内的网站获取股票、场内基金的数据,yahoo更可靠,JSON的数据结构也使得获取数据更方便、准确。

Yahoo API

过去python的pandas中直接提供了yahoo、google等数据的接口,pandas.io.data, 在《Python金融大数据分析》中有详细介绍,现在该接口已经移除,网上也有一些第三方的API,但也已经很久没有维护,失效了。

如果数据量不大,对频率要求不高,可以考虑直接从Yahoo网页直接提取数据。

API 接口

https://finance.yahoo.com/quote/510300.SS/history?period1=1511924498&period2=1543460498&interval=1d&filter=history&frequency=1d

510300.SS:股票代码
1511924498:起始日时间戳
1543460498:截止日时间戳
1d:频率,日

事先的处理

  • 日期转化为时间戳:
start_date = int(dt.datetime.strptime(start_date, "%Y-%m-%d").timestamp())
end_date = int(dt.datetime.strptime(end_date, "%Y-%m-%d").timestamp())
  • 代码转换
tick_suffix_dict = {'SH':'SS',
                    'SZ':'SZ',
                    'HK':'HK'}
  • freq 问题的处理
freq_dict = {"D":"1d", # 日
             "w":"1wk", # 周
             "m":"1mo" # 月}
  • url
 url = "https://finance.yahoo.com/quote/{}/history?period1={}&period2={}&interval={}&filter=history&frequency={}".\
format(tickCode,start_date,end_date,frequency,frequency)

获取JSON数据

 # 从网页上获取JSON数据
response = requests.get(url)
soup = BeautifulSoup(response.content,"lxml" )
    
script_json = json.loads(soup.find_all('script')[-3].text.split("\n")[5][16:-1])
prices_json = script_json['context']['dispatcher']['stores']['HistoricalPriceStore']['prices']

输出DataFrame

 prices = pd.DataFrame(prices_json)
 prices['date'] = prices['date'].apply(lambda x: dt.date.fromtimestamp(x))
 prices.set_index('date',inplace = True)
 prices.sort_index(inplace = True)

结果示例

ohlc_hist('510300.SH','2018-1-1','2018-11-27','m')
13903392-aaa5ce43d917a639.png
image.png

猜你喜欢

转载自blog.csdn.net/weixin_34014277/article/details/87237614