# 导入函数库
import jqdata
import pandas as pd
def initialize(context):
set_benchmark('000300.XSHG')
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')
g.security = get_index_stocks('000300.XSHG')
g.N = 20
g.q = query(valuation.code, valuation.pe_ratio, indicator.inc_net_profit_year_on_year).filter(valuation.code.in_(g.security))
run_monthly(handle, 1)
def handle(context):
df = get_fundamentals(g.q)
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')
tohold = df['code'][:g.N].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:
cash = context.portfolio.available_cash / len(tobuy)
cash_every_stock = cash / len(tobuy)
for stock in tobuy:
order_value(stock, cash_every_stock)