python量化羊驼法则

一、概念

这个有点玄学,遗传方法论和动量论,原理大概是,首先选择n只收益率高的股票,然后每月在n只里去掉m只最差的,然后再在大盘中选择m只收益率最差的进来

二、实现
选取沪深300,选择10只股票持有,2只作为调仓,最后回测效果一般(咩,cnm,笑脸),但在股灾区间表现却很亮眼

# 导入函数库
from jqdata import *

# 初始化函数,设定基准等等
def initialize(context):
    # 设定沪深300作为基准
    set_benchmark('000300.XSHG')
    # 开启动态复权模式(真实价格)
    set_option('use_real_price', True)
    # 股票类每笔交易时的手续费是:买入时佣金万分之三,卖出时佣金万分之三加千分之一印花税, 每笔交易佣金最低扣5块钱
    set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    
    g.security=get_index_stocks("000300.XSHG")
    g.period=3  
    g.N=10
    g.M=2
    run_monthly(handle,10)
    
    stocks=get_sorted(context,g.security)[-g.N:]
    cash=context.portfolio.available_cash/len(stocks)
    for stock in stocks:
        order_value(stock,cash)
    
def get_sorted(context,stocks):
    df=history(g.period, field="close", security_list=stocks).T
    df["ret"]=(df.iloc[:,-1]-df.iloc[:,0])/df.iloc[:,0]
    df=df.sort(columns="ret")
    return df.index.values
    
def handle(context):
    stocks=get_sorted(context,context.portfolio.positions.keys())
    for stock in stocks[:g.M]:
        order_target(stock,0)
        
    stocks=get_sorted(context,g.security)
    cash=context.portfolio.available_cash/g.M
    for stock in stocks:
        if len(context.portfolio.positions)>=10:
            break
        if stock not in context.portfolio.positions:
            order_target(stock,cash)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42357472/article/details/82954218