【量化】4天学会python机器学习与量化交易-笔记4(p21~p25)

Badia ·
更新时间:2024-09-21
· 614 次阅读

文章目录p21 因子数据的标准化处理p22 市值中心化处理介绍p23 案例:市值中性化实现以及回测选股结果p24 市值中心化结果总结分析p25 总结

平台:https://www.ricequant.com/quant
api1:https://www.ricequant.com/doc/rqdata-institutional#research-API-get_fundamentals
api2:https://www.ricequant.com/doc/api/python/chn#wizard-stock
rice quant ipynb

p21 因子数据的标准化处理

视频:https://www.bilibili.com/video/av55456917?p=21

# 2,标准化处理 from sklearn.preprocessing import StandardScaler std = StandardScaler() std.fit_transform(fund['pe_ratio_3md']) # (我的为什么报错。。) def stand(factor): '''自实现标准化''' mean = factor.mean() std = factor.std() return (factor - mean)/std fund['pe_ratio_stand'] = stand(fund['pe_ratio_3md']) fund

结果:
在这里插入图片描述

p22 市值中心化处理介绍

视频:https://www.bilibili.com/video/av55456917?p=22

1,市值中心化处理

防止得到的股票比较集中。(原因:默认大部分因子都包含了市值的影响。) 去除其他的因子存在的市值的影响。
2,回归法进行去除 建立某因子跟市值之间的一个回归方程,得出系数 最终预测的结果与因子之间的差值就是不受影响的那部分 p23 案例:市值中性化实现以及回测选股结果

视频:https://www.bilibili.com/video/av55456917?p=23

# 1,获取数据 q = query(fundamentals.eod_derivative_indicator.pb_ratio, fundamentals.eod_derivative_indicator.market_cap) fund = get_fundamentals(q, entry_date='2018-01-03')[:, '2018-01-03', :] #fund[:3] # 2,对因子数据进行处理,默认使用3倍中位数 fund['pb_ratio'] = mad(fund['pb_ratio']) fund['market_cap'] = mad(fund['market_cap']) # 对于市值因子可以选择处理 # 3,确定建立h回归方程特征值和目标值 # 传入特征值需要二维 x = fund['market_cap'].values.reshape(-1,1) # 注意加上.values y = fund['pb_ratio'] # 4,利用线性回归预测 from sklearn.linear_model import LinearRegression lr = LinearRegression() lr.fit(x, y) print(lr.coef_, lr.intercept_) # 5,得出每个预测值,让因子的真实值-预测值,得出的误差就是我们中性化处理之后的结果 y_predict = lr.predict(x) res = y - y_predict fund['pb_ratio'] = res

1,中心化处理:

原因:防止回测时选股集中 原理:建立回归关系

2,市值中心化选股对比

市值中心化处理:定期的分散到不同的股票 没有市值中心化处理:选股比较集中 p24 市值中心化结果总结分析

视频:https://www.bilibili.com/video/av55456917?p=24

p25 总结

完整代码:

from sklearn.linear_model import LinearRegression def init(context): scheduler.run_monthly(get_data, tradingday=1) def get_data(context, bar_dict): # 查询两个因子的数据结果 fund = get_fundamentals( query(fundamentals.eod_derivative_indicator.pb_ratio, fundamentals.eod_derivative_indicator.market_cap)) context.fund = fund.T # 进行因子数据的处理,去极值、标准化、市值中心化 treat_data(context) # 利用市净率进行选股(市净率小的好) # 选出20%的分位数,把小于它的股票保存下来 context.stock_list = context.fund['pb_ratio'][context.fund['pb_ratio'] up, up, factor) factor = np.where(factor<down, down, factor) return factor def stand(factor): '''自实现标准化''' mean = factor.mean() std = factor.std() return (factor - mean)/std

未完待续


作者:机智翔学长



p2 量化交易 学习 python机器学习 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号