
寫量化策略時常用的技巧
1.善用panel保存數(shù)據(jù)
說明:pandas有三種數(shù)據(jù)結(jié)構(gòu),分別是Series(一維),DataFrame(二維),panel(三維)
例子:滬深300成分股所有股票[stock list]在某些特征指標如成交量、收盤價[indicator list]上的某時間區(qū)間內(nèi)的歷史序列[time series],
[stock list] * [indicator list] * [time series]=3維
Q:如何通過Windpy接口來形成我們的三維面板數(shù)據(jù)呢?
A:按個股循環(huán),獲取每只股票的序列數(shù)據(jù)(二維);再把300只個股合并成三維。
例代碼1:獲取面板原始數(shù)據(jù)(daily),后期再在這張大的面板數(shù)據(jù)上計算月度的情況,再排序形成組合。再形成一個新的面板?!舅悸罚嚎?分-總】
ps1:缺點就是從總表中拆開按每個因子形成月度收益再concat合并,這個過程很麻煩,不如一開始就按因子分開處理好,再合并形成面板數(shù)據(jù)。
ps2:wind API每天12000條左右的記錄限制,意味著300只股票,每天只能他爸爸的獲取30天的數(shù)據(jù),10年的數(shù)據(jù)(120個月)得花120天來下載,這很坑啊。。??隙ㄊ且硗庀朕k法的,平時寫策略主要目的是訓練思路和練手,對數(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)生一個輔助數(shù)據(jù)集,幫助后面循環(huán)時匯總
individual_data=pd.DataFrame() #存放個股交易信息的數(shù)據(jù)集
result={} #result是一個三維的字典
for individual_stockcode in stockcodes:
# 依次生成個股數(shù)據(jù)集(變量包括:日期、代碼、開盤價、最高價、最低價、收盤價、成交量)
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:寫個兩層的循環(huán),把一維變成二維,再變成三維
二維(內(nèi)層循環(huán)):再把一維按照因子類別作為二維的dataframe的列,以此思路來形成二維表,如:df[‘PE’]=seriesXXX
三維(外層循環(huán)):按monthly的時間來循環(huán),把二維的截面數(shù)據(jù)加上時間維度,變成三維的,形成一張panel
Q:分開處理好數(shù)據(jù)以后,如何形成我們的三維面板數(shù)據(jù)呢?
A:最外層循環(huán):按時間(換倉頻率一般是月度)
最內(nèi)層循環(huán):調(diào)用windpy接口獲取每只股票的所有因子的截面數(shù)據(jù),按股票代碼循環(huán)(成交等、價格等)
## 函數(shù)1:計算組合的月度收益率
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:計算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)建因子組合并計算每月?lián)Q倉時不同組合的月收益率
# 得到結(jié)果monthly_return為panel數(shù)據(jù),儲存所有因子,在7×12個月內(nèi)5個組合及benchmark的月收益率
factors = ['B/M','EPS','PEG','ROE','ROA','GP/R','P/R','L/A','FAP','CMV']
#因為研究模塊取fundmental數(shù)據(jù)默認date為研究日期的前一天。所以要自備時間序列。按月取
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個組合,10個因子
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
SQL Server 中 CONVERT 函數(shù)的日期轉(zhuǎn)換:從基礎(chǔ)用法到實戰(zhàn)優(yōu)化 在 SQL Server 的數(shù)據(jù)處理中,日期格式轉(zhuǎn)換是高頻需求 —— 無論 ...
2025-09-18MySQL 大表拆分與關(guān)聯(lián)查詢效率:打破 “拆分必慢” 的認知誤區(qū) 在 MySQL 數(shù)據(jù)庫管理中,“大表” 始終是性能優(yōu)化繞不開的話題。 ...
2025-09-18CDA 數(shù)據(jù)分析師:表結(jié)構(gòu)數(shù)據(jù) “獲取 - 加工 - 使用” 全流程的賦能者 表結(jié)構(gòu)數(shù)據(jù)(如數(shù)據(jù)庫表、Excel 表、CSV 文件)是企業(yè)數(shù)字 ...
2025-09-18DSGE 模型中的 Et:理性預期算子的內(nèi)涵、作用與應用解析 動態(tài)隨機一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開始提取前,需先判斷 TIF 文件的類型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結(jié)構(gòu)數(shù)據(jù)特征價值的專業(yè)核心 表結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲的結(jié)構(gòu)化數(shù)據(jù),如數(shù)據(jù)庫表、Excel 表、 ...
2025-09-17Excel 導入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實戰(zhàn)應用 在用 Python(如 pandas 庫)處理 Excel 數(shù)據(jù)時,“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗與 t 檢驗:差異、適用場景與實踐應用 在數(shù)據(jù)分析與統(tǒng)計學領(lǐng)域,假設檢驗是驗證研究假設、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結(jié)構(gòu)數(shù)據(jù)全功能周期的專業(yè)操盤手 表格結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 存儲的結(jié)構(gòu)化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計劃中 rows 數(shù)量的準確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對象的 text 與 content:區(qū)別、場景與實踐指南 在 Python 進行 HTTP 網(wǎng)絡請求開發(fā)時(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結(jié)構(gòu)數(shù)據(jù)價值的核心操盤手 表格結(jié)構(gòu)數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫表)是企業(yè)最基礎(chǔ)、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請求工具對比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長浮點數(shù)據(jù)的科學計數(shù)法問題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長浮點數(shù)據(jù)時的科學計數(shù)法問題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務數(shù)據(jù)分析步驟的落地者與價值優(yōu)化者 業(yè)務數(shù)據(jù)分析是企業(yè)解決日常運營問題、提升執(zhí)行效率的核心手段,其價值 ...
2025-09-12用 SQL 驗證業(yè)務邏輯:從規(guī)則拆解到數(shù)據(jù)把關(guān)的實戰(zhàn)指南 在業(yè)務系統(tǒng)落地過程中,“業(yè)務邏輯” 是連接 “需求設計” 與 “用戶體驗 ...
2025-09-11塔吉特百貨孕婦營銷案例:數(shù)據(jù)驅(qū)動下的精準零售革命與啟示 在零售行業(yè) “流量紅利見頂” 的當下,精準營銷成為企業(yè)突圍的核心方 ...
2025-09-11CDA 數(shù)據(jù)分析師與戰(zhàn)略 / 業(yè)務數(shù)據(jù)分析:概念辨析與協(xié)同價值 在數(shù)據(jù)驅(qū)動決策的體系中,“戰(zhàn)略數(shù)據(jù)分析”“業(yè)務數(shù)據(jù)分析” 是企業(yè) ...
2025-09-11Excel 數(shù)據(jù)聚類分析:從操作實踐到業(yè)務價值挖掘 在數(shù)據(jù)分析場景中,聚類分析作為 “無監(jiān)督分組” 的核心工具,能從雜亂數(shù)據(jù)中挖 ...
2025-09-10統(tǒng)計模型的核心目的:從數(shù)據(jù)解讀到?jīng)Q策支撐的價值導向 統(tǒng)計模型作為數(shù)據(jù)分析的核心工具,并非簡單的 “公式堆砌”,而是圍繞特定 ...
2025-09-10