[B5]我的第一个量化策略

最近在学量化,刚学了一点点基础,这篇博客只作为一篇学习笔记,我想通过这种方式应该可以更好的激励自己去学习。

需求:
选股:获得市盈率大于50且小于65,营业总收入前10的股票
调仓:每日调仓,将所有资金平摊到10个股票的购买策略,卖出一次性卖出所有不符合条件的股票。

第1步:选股
不在init()处调用

def init(context):
    # 在context中保存全局变量
    #context.s1 = "000001.XSHE"
    # 实时打印日志
    #logger.info("RunInfo: {}".format(context.run_info))
    #定义一个选股的范围
    pass

在before_trading()处选股

#每日选股:获得市盈率大于50且小于65,营业收入前10的股票
# before_trading此函数会在每天策略交易开始前被调用,当天只会被调用一次
def before_trading(context):


    #选股
    q = query(
        fundamentals.eod_derivative_indicator.pe_ratio,
        fundamentals.income_statement.revenue
        ).filter(
            fundamentals.eod_derivative_indicator.pe_ratio >50,
            ).filter(
                fundamentals.eod_derivative_indicator.pe_ratio <65
                ).order_by(
                    fundamentals.income_statement.revenue.desc()
                    ).limit(10)

 

    fund = get_fundamentals(q)

    #print(fund.T)
    context.stock_list = fund.T.index

第2步:交易

#买卖:买入每天选出来的10只,卖出

# 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新
def handle_bar(context, bar_dict):
    # 开始编写你的主要的算法逻辑

    # bar_dict[order_book_id] 可以拿到某个证券的bar信息
    # context.portfolio 可以拿到现在的投资组合信息

    # 使用order_shares(id_or_ins, amount)方法进行落单

    # TODO: 开始编写你的算法吧!
    #order_shares(context.s1, 1000)
    


    #在此交易
    #先判断仓位是否有股票,如果有,卖出(判断不在新的股票池中)
    if len(context.portfolio.positions.keys()) != 0:

        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)
 
    pass

第3步:结束

# after_trading函数会在每天交易结束后被调用,当天只会被调用一次
def after_trading(context):
    pass

第4步:回测策略

在这里插入图片描述可以看出,这个策略还是不错的,回测年化收益率47.34%,最大回测8.46%,夏普比率1.58.
第一次做,还没用到因子分析和机器学习算法等,还存在许多缺陷。

发布了7 篇原创文章 · 获赞 0 · 访问量 457

猜你喜欢

转载自blog.csdn.net/weixin_45854207/article/details/103559937