• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

关于python:量化交易-实战之市值中性化选股

python 搞代码 4年前 (2022-02-20) 39次浏览 已收录 0个评论

能够本人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

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:关于python:量化交易-实战之市值中性化选股

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址