
寫量化策略時(shí)常用的技巧
1.善用panel保存數(shù)據(jù)
說明:pandas有三種數(shù)據(jù)結(jié)構(gòu),分別是Series(一維),DataFrame(二維),panel(三維)
例子:滬深300成分股所有股票[stock list]在某些特征指標(biāo)如成交量、收盤價(jià)[indicator list]上的某時(shí)間區(qū)間內(nèi)的歷史序列[time series],
[stock list] * [indicator list] * [time series]=3維
Q:如何通過Windpy接口來形成我們的三維面板數(shù)據(jù)呢?
A:按個(gè)股循環(huán),獲取每只股票的序列數(shù)據(jù)(二維);再把300只個(gè)股合并成三維。
例代碼1:獲取面板原始數(shù)據(jù)(daily),后期再在這張大的面板數(shù)據(jù)上計(jì)算月度的情況,再排序形成組合。再形成一個(gè)新的面板?!舅悸罚嚎?分-總】
ps1:缺點(diǎn)就是從總表中拆開按每個(gè)因子形成月度收益再concat合并,這個(gè)過程很麻煩,不如一開始就按因子分開處理好,再合并形成面板數(shù)據(jù)。
ps2:wind API每天12000條左右的記錄限制,意味著300只股票,每天只能他爸爸的獲取30天的數(shù)據(jù),10年的數(shù)據(jù)(120個(gè)月)得花120天來下載,這很坑啊。。??隙ㄊ且硗庀朕k法的,平時(shí)寫策略主要目的是訓(xùn)練思路和練手,對數(shù)據(jù)質(zhì)量要求不太高,目前看來,聚寬是最好的選擇,策略編寫平臺類似jupyter notebook,也支持python的所有package。
import pandas as pd
import copy
from WindPy import w
import datetime
w.start()
## 函數(shù)getAsharePanels(),獲取A股歷史面板數(shù)據(jù)
def getAsharePanels(stockcodes,start_date,end_date):
append_data=pd.DataFrame(columns=['trade_date','stock_code','open','high','low','close','volume']) #產(chǎn)生一個(gè)輔助數(shù)據(jù)集,幫助后面循環(huán)時(shí)匯總
individual_data=pd.DataFrame() #存放個(gè)股交易信息的數(shù)據(jù)集
result={} #result是一個(gè)三維的字典
for individual_stockcode in stockcodes:
# 依次生成個(gè)股數(shù)據(jù)集(變量包括:日期、代碼、開盤價(jià)、最高價(jià)、最低價(jià)、收盤價(jià)、成交量)
stock=w.wsd(individual_stockcode, "trade_code,open,high,low,close,volume",start_date,end_date)
individual_data['trade_date']=stock.Times
individual_data['stock_code']=stock.Data[0]
individual_data['open']=stock.Data[1]
individual_data['high']=stock.Data[2]
individual_data['low']=stock.Data[3]
individual_data['close']=stock.Data[4]
individual_data['volume']=stock.Data[5]
# 通過300次迭代,把300只股票的df格式的individual_data數(shù)據(jù)放到result里,形成3維的字典
result[+1]=individual_data
rawdata = pd.Panel(result) #獲取的滬深300成分股的3維數(shù)據(jù)保存在rawdata中
return rawdata
## 調(diào)用函數(shù)getAsharePanels(),獲取A股歷史面板數(shù)據(jù)
todayDate=datetime.datetime.strftime(datetime.date.today(),"%Y%m%d")
wsetdata=w.wset('SectorConstituent','date='+todayDate+';sectorId=1000000090000000;field=wind_code') #通過wset獲取滬深300成分股代碼
stockcodes=list(wsetdata.Data[0])
start_date='20120101' #樣本數(shù)據(jù)起始日期
end_date='20171231' #樣本數(shù)據(jù)結(jié)束日期
rawdata_panel=getAsharePanels(stockcodes,start_date,end_date)
例代碼2:
【先分后合】
step1:
一維:先寫好一系列函數(shù),分開處理好各因子的歷史序列數(shù)據(jù)(如:月度收益、排序形成portfolio等)
step2:寫個(gè)兩層的循環(huán),把一維變成二維,再變成三維
二維(內(nèi)層循環(huán)):再把一維按照因子類別作為二維的dataframe的列,以此思路來形成二維表,如:df[‘PE’]=seriesXXX
三維(外層循環(huán)):按monthly的時(shí)間來循環(huán),把二維的截面數(shù)據(jù)加上時(shí)間維度,變成三維的,形成一張panel
Q:分開處理好數(shù)據(jù)以后,如何形成我們的三維面板數(shù)據(jù)呢?
A:最外層循環(huán):按時(shí)間(換倉頻率一般是月度)
最內(nèi)層循環(huán):調(diào)用windpy接口獲取每只股票的所有因子的截面數(shù)據(jù),按股票代碼循環(huán)(成交等、價(jià)格等)
## 函數(shù)1:計(jì)算組合的月度收益率
def caculate_port_monthly_return(port,startdate,enddate,nextdate,CMV):
close1 = get_price(port, startdate, enddate, 'daily', ['close']) #三維面板數(shù)據(jù)
close2 = get_price(port, enddate, nextdate, 'daily',['close']) #面板數(shù)據(jù)
weighted_m_return = ((close2['close'].ix[0,:]/close1['close'].ix[0,:]-1)).mean() #等權(quán)加權(quán)
return weighted_m_return
## 函數(shù)2:計(jì)算benchmark組合的月度收益
def caculate_benchmark_monthly_return(startdate,enddate,nextdate):
close1 = get_price(['000001.XSHG'],startdate,enddate,'daily',['close'])['close']
#二維
close2 = get_price(['000001.XSHG'],enddate, nextdate, 'daily',['close'])['close']
benchmark_return = (close2.ix[0,:]/close1.ix[0,:]-1).sum()
print close1
return benchmark_return
## 核心策略:構(gòu)建因子組合并計(jì)算每月?lián)Q倉時(shí)不同組合的月收益率
# 得到結(jié)果monthly_return為panel數(shù)據(jù),儲存所有因子,在7×12個(gè)月內(nèi)5個(gè)組合及benchmark的月收益率
factors = ['B/M','EPS','PEG','ROE','ROA','GP/R','P/R','L/A','FAP','CMV']
#因?yàn)檠芯磕K取fundmental數(shù)據(jù)默認(rèn)date為研究日期的前一天。所以要自備時(shí)間序列。按月取
year = ['2011','2012','2013','2014','2015','2016','2017']
month = ['01','02','03','04','05','06','07','08','09','10','11','12']
result = {}
for i in range(7*12):
startdate = year[i/12] + '-' + month[i%12] + '-01'
try:
enddate = year[(i+1)/12] + '-' + month[(i+1)%12] + '-01'
except IndexError:
enddate = '2016-01-01'
try:
nextdate = year[(i+2)/12] + '-' + month[(i+2)%12] + '-01'
except IndexError:
if enddate == '2018-01-01':
nextdate = '2018-02-01'
else:
nextdate = '2018-01-01'
#print 'time %s'%startdate
fdf = get_factors(startdate,factors)
CMV = fdf['CMV']
#5個(gè)組合,10個(gè)因子
df = DataFrame(np.zeros(6*10).reshape(6,10),index = ['port1','port2','port3','port4','port5','benchmark'],columns = factors)
for fac in factors:
score = fdf[fac].order()
port1 = list(score.index)[: len(score)/5]
port2 = list(score.index)[ len(score)/5+1: 2*len(score)/5]
port3 = list(score.index)[ 2*len(score)/5+1: -2*len(score)/5]
port4 = list(score.index)[ -2*len(score)/5+1: -len(score)/5]
port5 = list(score.index)[ -len(score)/5+1: ]
df.ix['port1',fac] = caculate_port_monthly_return(port1,startdate,enddate,nextdate,CMV)
df.ix['port2',fac] = caculate_port_monthly_return(port2,startdate,enddate,nextdate,CMV)
df.ix['port3',fac] = caculate_port_monthly_return(port3,startdate,enddate,nextdate,CMV)
df.ix['port4',fac] = caculate_port_monthly_return(port4,startdate,enddate,nextdate,CMV)
df.ix['port5',fac] = caculate_port_monthly_return(port5,startdate,enddate,nextdate,CMV)
df.ix['benchmark',fac] = caculate_benchmark_monthly_return(startdate,enddate,nextdate)
#print 'factor %s'%faesult[i+1]=df
monthly_return = pd.Panel(result)
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
LSTM 模型輸入長度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報(bào)考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動決策的時(shí)代浪潮下,CDA 數(shù)據(jù)分析師認(rèn)證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計(jì)的實(shí)用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強(qiáng)大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實(shí)施重大更新。 此次更新旨在確保認(rèn) ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價(jià)值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡稱 BI)深度融合的時(shí)代,BI ...
2025-07-10SQL 在預(yù)測分析中的應(yīng)用:從數(shù)據(jù)查詢到趨勢預(yù)判? ? 在數(shù)據(jù)驅(qū)動決策的時(shí)代,預(yù)測分析作為挖掘數(shù)據(jù)潛在價(jià)值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價(jià)值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點(diǎn),而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報(bào)考到取證的全攻略? 在數(shù)字經(jīng)濟(jì)蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢性檢驗(yàn):捕捉數(shù)據(jù)背后的時(shí)間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢性檢驗(yàn)如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時(shí)間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時(shí)間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實(shí)戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認(rèn)證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗(yàn):數(shù)據(jù)趨勢與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢變化以及識別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認(rèn)證作為國內(nèi)權(quán)威的數(shù)據(jù)分析能力認(rèn)證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對策略? 長短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨(dú)特的門控機(jī)制,在 ...
2025-07-07統(tǒng)計(jì)學(xué)方法在市場調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場調(diào)研是企業(yè)洞察市場動態(tài)、了解消費(fèi)者需求的重要途徑,而統(tǒng)計(jì)學(xué)方法則是市場調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價(jià)值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03