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,close_today_commission=0, 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(by='market_cap').iloc[:g.N,:]
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)