共计 2244 个字符,预计需要花费 6 分钟才能阅读完成。
能够本人 import 咱们平台反对的第三方 python 模块,比方 pandas、numpy 等。
1. 获取市值和市净率因子数据
因子: 极值, 标准化, 中性化解决
2. 选定股票池 (依据方向权重)
市净率小的某些股票
from sklearn.linear_model import LinearRegression
在这个办法中编写任何的初始化逻辑。context 对象将会在你的算法策略的任何办法之间做传递。
def init(context):
scheduler.run_weekly(get_data, tradingday=1) | |
scheduler.run_weekly(trade, tradingday=1) |
def get_data(context, bar_dict):
# 查问两个因子的整数后果 | |
q = query( | |
fundamentals.eod_derivative_indicator.pb_ratio, | |
fundamentals.eod_derivative_indicator.market_cap | |
).order_by(fundamentals.eod_derivative_indicator.pb_ratio) | |
fund = get_fundamentals(q) | |
# 转置 | |
context.fund = fund.T | |
# 查看 fund 格局 | |
# logger.info(fund.T) | |
# 进行因子数据的解决, 去极值, 标准化 | |
treat_data(context) | |
# 利用市净率进行选股 [PayPal](https://www.gendan5.com/wallet/PayPal.html)(市净率小的体现好) | |
context.stock_list = context.fund["pb_ratio"][context.fund["pb_ratio"] <= context.fund["pb_ratio"].quantile(0.05) # 取前 5% | |
].index | |
# 调试输入 | |
logger.info(context.stock_list) | |
logger.info(context.stock_list.shape) |
def treat_data(context):
"""因子数据的解决逻辑""" | |
# 去除 NaN | |
context.fund = context.fund.dropna() | |
# 对市净率去极极值标准化 | |
context.fund["pb_ratio"] = mad(context.fund["pb_ratio"]) | |
context.fund["pb_ratio"] = stand(context.fund["pb_ratio"]) | |
# 调试输入 | |
logger.info(context.fund.shape) | |
# 选股的解决, 对市净率进行市值中性化 | |
# 特征值: 市值 | |
# 目标值: 市净率因子 | |
x = context.fund["market_cap"].values.reshape(-1, 1) | |
y = context.fund["pb_ratio"] | |
# 建设线性回归, 中性化解决 | |
lr = LinearRegression() | |
lr.fit(x, y) | |
y_predict = lr.predict(x) | |
# 去除残差 | |
context.fund["pb_ratio"] = y - y_predict |
before_trading 此函数会在每天策略交易开始前被调用,当天只会被调用一次
def before_trading(context):
pass
你抉择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新
def handle_bar(context, bar_dict):
# TODO: 开始编写你的算法吧!pass
after_trading 函数会在每天交易完结后被调用,当天只会被调用一次
def after_trading(context):
pass
def trade(context, bar_dict):
# ---------------- 卖出 ---------------- | |
for stock in context.portfolio.positions.keys(): | |
# 判断是否还在股票池 | |
if stock not in context.stock_list: | |
order_target_percent(stock, 0) | |
# ---------------- 买入 ----------------- | |
weight = 1.0 / len(context.stock_list) | |
for stock in context.stock_list: | |
order_target_percent(stock, weight) |
相对偏差
import numpy as np
def mad(factor):
"""3 倍中位数去极值""" | |
# 求出因子值的中位数 | |
med = np.median(factor) | |
# 求出因子值与中位数的差值, 进行绝对值 | |
mad = np.median(abs(factor - med)) | |
# 定义几倍的中位数上上限 | |
high = med + (3 * 1.4826 * mad) | |
low = med - (3 * 1.4826 * mad) | |
# 替换上上限以外的值 | |
factor = np.where(factor > high, high, factor) | |
factor = np.where(factor < low, low, factor) | |
return factor |
标准化
def stand(factor):
"""自实现标准化""" | |
mean = factor.mean() | |
std = factor.std() | |
return (factor - mean) / std |
正文完