在聚宽平台上编写PEG策略---选股

def initialize(context):
    set_option('use_real_price', True)
    set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    set_benchmark('000300.XSHG')
    
    g.security = get_index_stocks('000300.XSHG')
    g.N = 20
    run_monthly(handle, 1)
    
def handle(context):
    df = get_fundamentals(query(valuation.code, valuation.pe_ratio, indicator.inc_net_profit_year_on_year).filter(valuation.code.in_(g.security)))
    df = df[(df['pe_ratio']>0) & (df['inc_net_profit_year_on_year']>0)]
    df['PEG'] = df['pe_ratio'] / df['inc_net_profit_year_on_year'] / 100
    df = df.sort(columns='PEG')[:g.N]
    tohold = df['code'].values
    
    for stock in context.portfolio.positions:
        if stock not in tohold:
            order_target_value(stock, 0)
    
    tobuy = [stock for stock in tohold if stock not in context.portfolio.positions]
    
    if len(tobuy)>0:
        print('Buying')
        cash = context.portfolio.available_cash
        cash_every_stock = cash / len(tobuy)
        
        for stock in tobuy:
            order_value(stock, cash_every_stock)

转载于:https://www.cnblogs.com/IQ-Python/p/7423863.html

你可能感兴趣的:(在聚宽平台上编写PEG策略---选股)