根据财务指标的量化交易策略

#会在策略开始前触发一次,我们可以从get_fundamentals函数中更新我们的股票池
#并且保存查询获得的数据以作之后使用
def initialize(context):
    # 获取A股所有的股票
    Ashares = get_Ashares()
    # 获取A股所有股票的roe
    results_roe = get_fundamentals(Ashares, 'profit_ability', fields = 'roe')
    # 筛选roe在前100的股票
    results_roe = results_roe.sort(['roe'], ascending = False)[:100]
    # 将股票列表保存在stocks_roe变量中
    stocks_roe = results_roe.index.values.tolist()
    
    # 获取stocks_roe变量中所有股票的营业收入
    results_oper_profit_grow_rate = get_fundamentals(Ashares,'growth_ability','oper_profit_grow_rate')
    # 筛选营业收入在前100的股票   
    results_oper_profit_grow_rate = results_oper_profit_grow_rate.sort(['oper_profit_grow_rate'], ascending = False)[:100]
    # 将股票列表保存在stock_oper_profit_grow_rate中
    stock_oper_profit_grow_rate = results_oper_profit_grow_rate.index.values.tolist()
    
    # 取满足两个条件的股票并将最终筛选得到的股票保存在g.security变量中
    g.security = [val for val in stocks_roe if val in stock_oper_profit_grow_rate]

    
    # 计算平均买入比例
    if len(g.security) != 0:
        g.average_percent = 1.0 / len(g.security)
    else:
        g.average_percent = 0
    # 设置一个标识,用于判断是否已经买入
    g.flag = False
    # 打印下日志查看结果,会显示我们筛选得到的股票
    log.info(g.security)
    # 设置我们要操作的股票池
    set_universe(g.security)
    
# 程序运行第一天买入,等比例买入,并持有
def handle_data(context, data):
    if not g.flag and g.average_percent != 0:
        for stock in g.security:
            order_target_percent(stock, g.average_percent)
        g.flag = True

 

你可能感兴趣的:(量化交易)