量化金融分析師AQF丨作為一個quant,無論是分析還交易,都要從數(shù)據(jù)開始。高質(zhì)量的結(jié)構(gòu)化數(shù)據(jù)可以為quant節(jié)約大量時間。tushare作為一個免費Python財經(jīng)數(shù)據(jù)接口,為想要探索量化領(lǐng)域的學習者打開了一扇方便的大門。今天我們就來介紹一下tushare中主要函數(shù)的用法。 >>>點擊咨詢python金融應用實戰(zhàn)
import tushare as tsimport pandas as pdimport time
1 交易數(shù)據(jù)
stocks = ['300631', '300605', '300576']dates = [('2017-09-04','2017-09-10'),('2017-09-11', '2017-09-17'),('2017-08-28','2017-09-03')]
1.1 歷史數(shù)據(jù)
# get_k_data 函數(shù)獲取歷史數(shù)據(jù)# 將多個時間段的數(shù)據(jù)拼接# 出于性能的考慮,一次性請求數(shù)據(jù)的時間長度較好不超過3年,需要獲取更長時間的歷史數(shù)據(jù)就需要將多個數(shù)據(jù)表拼接# ktype 的可用選項:D=日k線 W=周 M=月 5=5分鐘 15=15分鐘 30=30分鐘 60=60分鐘,默認為Ddata = [ts.get_k_data('300631', start, end, ktype='W') for (start, end) in dates]
df = pd.concat(data).set_index('date').sort_index()
df
1.2 實時數(shù)據(jù)
ts.get_today_all()
# 使用 get_today_all 函數(shù)獲取實時數(shù)據(jù)# 每30秒刷新一次數(shù)據(jù)while True:
df = ts.get_today_all()
print('\n', df.head())
time.sleep(30)
1.3 歷史分筆數(shù)據(jù)
# 獲取歷史分筆數(shù)據(jù)函數(shù)ts.get_tick_data(stocks[0], '2017-09-15')
import datetime as dt# 分筆數(shù)據(jù)只能逐日獲取# 需要獲取多日的歷史分筆數(shù)據(jù)需要再次用到 dataframe 拼接# 獲取工作日序列(start, end) = dates[0]
bdate_range = pd.bdate_range(start, end).tolist()
bdates = [datetime.strftime(date, '%Y-%m-%d') for date in bdate_range# 定義一個獲取 tick 數(shù)據(jù),并插入日期列的函數(shù)def get_tick(code, date):
df = ts.get_tick_data(code, date)
df['time'] = date + ' ' + df.time
df.set_index('time', inplace=True)
df.sort_index(inplace=True) return df# 獲取多日的 tick 數(shù)據(jù)并拼接成 dataframedata = [get_tick(stocks[0], date) for date in bdates]
tick_df = pd.concat(data)
tick_df
1.4 實時分筆數(shù)據(jù)
# 歷史分筆只能獲取當前交易日前一天及以前的數(shù)據(jù),當天的實時數(shù)據(jù)需要通過實時接口獲取while True:
tick = ts.get_realtime_quotes([stocks[0],'sh'])
print(tick[['time','code','name','price','bid','b1_v', 'ask','a1_v', 'volume']],'\n')
time.sleep(3)
1.5 指數(shù)行情列表
# 獲取指數(shù)行情數(shù)據(jù)index = ts.get_index()
index
1.6 大單數(shù)據(jù)
# 獲取單日大單數(shù)據(jù),僅對歷史日期有效# 通過 vol 參數(shù)設定大單門檻值,默認為400手df = ts.get_sina_dd(stocks[0], '2017-09-15', vol=1000)
df
附上GIF動圖版,讓你能更直觀了解Python的神奇之處~那么,祝大家學習愉快!
(2).jpg)
.jpg)
量化金融分析師AQF交流答疑群:737550026
完善下表,48小時內(nèi)查收全套AQF備考資料
聲明▎更多內(nèi)容請關(guān)注微信號量化金融分析師。原創(chuàng)文章,歡迎分享,若需引用或轉(zhuǎn)載請保留此處信息。


.jpg)


