平台: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
视频: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
结果:
视频:https://www.bilibili.com/video/av55456917?p=22
1,市值中心化处理
防止得到的股票比较集中。(原因:默认大部分因子都包含了市值的影响。) 去除其他的因子存在的市值的影响。视频: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
未完待续