Fork me on GitHub

金融数据分析| 因子选股策略

 

  因子选股策略

因子选股策略
因子:选择股票的某种标准
    增长率、 市值、 市盈率、 ROE(净资产收益率)
选股策略:
    对于某个因子,选取表现最好(因子最大或最小)的N支股票持仓
    每隔一段时间调仓一次
小市值策略:选取股票池中市值最小的N只股票持仓

 

def initialize(context):
    set_benchmark('000300.XSHG')
    set_option('use_real_price', True)
    set_order_cost(OrderCost(open_tax=0, 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.q = query(valuation).filter(valuation.code.in_(g.security))
    g.N = 20
    
    run_monthly(handle, 1)
    
def handle(context):
    df = get_fundamentals(g.q)[['code', 'market_cap']]
    df = df.sort_values('market_cap').iloc[:g.N,:] #sort   'DataFrame' object has no attribute 'sort'
    #print(df)
    to_hold = df['code'].values
    for stock in context.portfolio.positions:
        if stock not in to_hold:
            order_target(stock, 0)
    to_buy = [stock for stock in to_hold if stock not in context.portfolio.positions]
    
    if len(to_buy) > 0:
        cash_per_stock = context.portfolio.available_cash / len(to_buy)
        for stock in to_buy:
            order_value(stock, cash_per_stock)
            
    

  

 

 点击运行回测查看详情:

 

 多因子选股策略

def initialize(context):
    set_benchmark('000002.XSHG')
    set_option('use_real_price', True)
    set_order_cost(OrderCost(open_tax=0, close_tax=0.001,open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    g.security = get_index_stocks('000002.XSHG')
    
    g.q = query(valuation, indicator).filter(valuation.code.in_(g.security))
    g.N = 20
    
    run_monthly(handle, 1)
    
def handle(context):
    df = get_fundamentals(g.q)[['code', 'market_cap', 'roe']]
    #print(df)
    df['market_cap'] = (df['market_cap'] - df['market_cap'].min()) / (df['market_cap'].max() - df['market_cap'].min())
    df['roe'] = (df['roe'] - df['roe'].min()) / (df['roe'].max() - df['roe'].min())
    #print(df)
    df['score'] = df['roe'] - df['market_cap']
    
    df = df.sort_values('score').iloc[-g.N:,:] #sort AttributeError: 'DataFrame' object has no attribute 'sort'

    to_hold = df['code'].values

    for stock in context.portfolio.positions:
        if stock not in to_hold:
            order_target(stock, 0)
    to_buy = [stock for stock in to_hold if stock not in context.portfolio.positions]
    
    if len(to_buy) > 0:
        cash_per_stock = context.portfolio.available_cash / len(to_buy)
        for stock in to_buy:
            order_value(stock, cash_per_stock)
         

 

 

posted @ 2020-05-13 20:58  kris12  阅读(479)  评论(0)    收藏  举报
levels of contents