OHLC 指 open,high,low,close,老外的網(wǎng)站數(shù)據(jù)規(guī)范,相比從國內的網(wǎng)站獲取股票、場內基金的數(shù)據(jù),yahoo更可靠,JSON的數(shù)據(jù)結構也使得獲取數(shù)據(jù)更方便、準確。
Yahoo API
過去python的pandas中直接提供了yahoo、google等數(shù)據(jù)的接口,pandas.io.data, 在《Python金融大數(shù)據(jù)分析》中有詳細介紹,現(xiàn)在該接口已經(jīng)移除,網(wǎng)上也有一些第三方的API,但也已經(jīng)很久沒有維護,失效了。
如果數(shù)據(jù)量不大,對頻率要求不高,可以考慮直接從Yahoo網(wǎng)頁直接提取數(shù)據(jù)。
API 接口
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數(shù)據(jù)
# 從網(wǎng)頁上獲取JSON數(shù)據(jù)
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')

image.png