1. Yahoo股票
Yahoo财經提供國内外的股票資料,其請求URL格式如下:
http://ichart.finance.yahoo.com/table.csv?a=&b=&c=&d=&e=&f=&s=AAPL
上URL是擷取2006/03/12到2015/12/31蘋果公司的股票資料
1.1 具體參數解析:
s – 股票名稱
a – 起始時間,月
b – 起始時間,日
c – 起始時間,年
d – 結束時間,月
e – 結束時間,日
f – 結束時間,年
g – 時間周期
Example: g=w, 表示周期是’周’。d->’日’(day),w->’周’(week),m->’月’(mouth),v->’dividendsonly’
一定注意月份參數,其值比真實資料-1。如需要9月資料,則寫為08。
1.2 各交易所字尾
說明:
如果要擷取滬深股市資訊股票名稱格式如下:
上海:股票代碼.SS
深圳:股票代碼.SZ
上海交易所=cn.finance.yahoo.com,.SS,Chinese
深圳交易所=cn.finance.yahoo.com,.SZ,Chinese
美國交易所=finance.yahoo.com,,United States
加拿大=ca.finance.yahoo.com,.TO,Toronto
紐西蘭=au.finance.yahoo.com,.NZ
新加坡=sg.finance.yahoo.com,.SI,Singapore
香港=hk.finance.yahoo.com,.HK,Hong Kong
台灣=tw.finance.yahoo.com,.TW,Taiwan
印度=in.finance.yahoo.com,.BO,Bombay
倫敦=uk.finance.yahoo.com,.L,London
澳洲=au.finance.yahoo.com,.AX,Sydney
巴西=br.finance.yahoo.com,.SA,Sao Paulo
瑞典=se.finance.yahoo.com,.ST,Stockholm
1.3 傳回資料
請求完成Yahoo傳回的資料是CVS格式,如下:
Date,Open,High,Low,Close,Volume,Adj Close
--,,,,,,
--,,,,,,
2. 擷取股票資料
下面是一段Python寫的代碼
def get_yahoo_data(stock):
start = time.time()
res = True
_now = datetime.datetime.now()
try:
if stock[] == '$':
stock = '^' + stock[:]
print 'get %s ...' % stock
f = open(data_path + '/' + stock + ".csv", 'w')
params = urllib.urlencode(
{'a': , 'b': , 'c': , 'd': _now.day, 'e': _now.month, 'f': _now.year, 's': stock})
url = "http://ichart.finance.yahoo.com/table.csv?%s" % params
url_get = urllib2.urlopen(url)
data = url_get.readline()
while(len(data) > ):
# print data
f.write(data)
data = url_get.readline()
f.close()
print "Fetch [%s] done, cost : %s." % (stock, (time.time() - start))
except urllib2.HTTPError:
res = False
print "Unable to fetch data for stock: {0} at {1}".format(stock, url)
except urllib2.URLError:
res = False
print "URL Error for stock: {0} at {1}".format(stock, url)
return res
實際上Python/Matlab都提供的有專門的API擷取Yahoo資料:
在Python中matplotlib提供的有專門處理金融資料的子產品——finance
import datetime
from matplotlib import finance, mlab
import numpy as np
def load_data(code, start_date, end_date ):
fh = finance.fetch_historical_yahoo(code, start_date, end_date)
data = mlab.csv2rec(fh)
fh.close()
# print data
data.sort()
close_data = data['close']
open_data = data['open']