Yahoo! Finance財經數據PYTHON臨時讀取方法

本篇文章轉自簡書:http://www.jianshu.com/p/85d563d326a9web

這段時間在看量化策略,找到了一個比較不錯的開源項目,可是yahoo金融的數據源一直沒有找到,在網上找到了這篇文章,分享一下。文章最下方是原做者的微信號,有想打賞的自便~~瀏覽器

 

Yahoo! Finance提供國內外財經數據,PYTHON一般藉助於pandas或者matplotlib進行數據讀取。微信

因爲2017年5月16日Yahoo!單方面進行了API升級,原數據接口已下線。cookie

原URL格式:https://chart.yahoo.com/table.csv?s=IBM
現調整爲:https://query1.finance.yahoo.com/v7/finance/download/IBM?period1=1492611801&period2=1495203801&interval=1d&events=history&crumb=NMhMTCv7QpM3d


yahoo.jpg

在pandas及matplotlib yahoo finance補丁發佈前,可經過本文提供的臨時解決方法提取數據。unix

原數據提取方法一:code

import pandas.io.data as web
IBMStock = web.DataReader(name="IBM", data_source="yahoo",start="2000-1-1")

原數據提取方法二:blog

import requests

s = requests.Session()
r = s.get("https://chart.yahoo.com/table.csv?s=IBM",verify=False)

原數據提取方法三:接口

from matplotlib.finance import quotes_historical_yahoo_ochl

date1=(2013, 1, 1)
date2=(2013, 12,31)
price=quotes_historical_yahoo_ochl('IBM', date1, date2)

PYTHON臨時解決方案:
Step1. 經過瀏覽器獲取訪問yahoo時的cookie值ip

https://finance.yahoo.com/quote/IBM/history?p=IBM

Chrome


cookies.jpg

Step2. 右鍵點擊download,取得crumb值

https://query1.finance.yahoo.com/v7/finance/download/IBM?period1=1492611801&period2=1495203801&interval=1d&events=history&crumb=NMhMTCv7QpM


crumb.jpg

Step3. 使用unix time替換起止日期

代碼示例(Python 2.7.13 |Anaconda 4.3.1 (64-bit)):

# -*- coding: utf-8 -*-
"""
Created on Fri May 19 2017

@author: vincentqiao
"""

import requests
import time
import pandas as pd
import matplotlib.pyplot as plt

def datetime_timestamp(dt):
     time.strptime(dt, '%Y-%m-%d %H:%M:%S')
     s = time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S'))
     return str(int(s))

s = requests.Session()

#Replace B=xxxx
cookies = dict(B='c650m5hchrhii&b=3&s=tk')

#Replace crumb=yyyy
crumb = 'NMhMTCv7QpM'

begin = datetime_timestamp("2014-01-01 09:00:00")

end = datetime_timestamp("2017-04-30 09:00:00")

r = s.get("https://query1.finance.yahoo.com/v7/finance/download/IBM?period1="+begin+"&period2="+end+"&interval=1d&events=history&crumb="+crumb,cookies=cookies,verify=False)

f = open('IBM.csv', 'w')
f.write(r.text)
f.close()    


es = pd.read_csv('IBM.csv', index_col=0,parse_dates=True, sep=",", dayfirst=True)

data = pd.DataFrame({"IBM" : es["Adj Close"][:]}) 

print(data.info())

data.plot(subplots=True, grid=True, style="b", figsize=(8, 6))

plt.show()

運行結果:


 

做者微信公衆號


qrcode_small.jpg
相關文章
相關標籤/搜索