import jqdata
import math
import numpy as np
import pandas as pd
import datetime
def initialize(context):
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.benchmark = '000300.XSHG'
g.N = 10
set_benchmark(g.benchmark)
run_monthly(handle, 1)
def handle(context):
stocks = get_index_stocks('000300.XSHG')
# 这段时间的收盘价(attribu是选取一只股票多个时间的,history是选择多只股票)
# 转置,相当于将股票代码放在了表头上
df_close = history(30, field='close', security_list=list(stocks)).T
# 增加ret列,表示收益率(最后一天的价格-第一天的价格)/ 第一天的价格
df_close['ret'] = (df_close.iloc[:,-1]-df_close.iloc[:,0])/df_close.iloc[:,0]
# ascending = False 表示降序,即为动量策略,总选最好的
# ascending = True 反转策略
sorted_stocks = df_close.sort_values('ret', ascending = False).index
to_hold = sorted_stocks[:g.N]
# 手上可能有一些股票,有的留着,没有的卖掉,添加新的
for stock in context.portfolio.positions:
# 手上的股票没在to_hold中,买掉
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 to_buy:
cash_per_stock = context.portfolio.available_cash / len(to_buy)
for per in to_buy:
order_value(per,cash_per_stock)
2
import jqdata
import math
import numpy as np
import pandas as pd
import datetime
def initialize(context):
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.benchmark = '000300.XSHG'
g.N = 10
set_benchmark(g.benchmark)
run_monthly(handle, 1)
def handle(context):
stocks = get_index_stocks('000300.XSHG')
# 这段时间的收盘价(attribu是选取一只股票多个时间的,history是选择多只股票)
# 转置,相当于将股票代码放在了表头上
df_close = history(30, field='close', security_list=list(stocks)).T
# 增加ret列,表示收益率(最后一天的价格-第一天的价格)/ 第一天的价格
df_close['ret'] = (df_close.iloc[:,-1]-df_close.iloc[:,0])/df_close.iloc[:,0]
# ascending = False 表示降序,即为动量策略,总选最好的
# ascending = True 反转策略
sorted_stocks = df_close.sort_values('ret', ascending = False).index
to_hold = sorted_stocks[:g.N]
# 手上可能有一些股票,有的留着,没有的卖掉,添加新的
for stock in context.portfolio.positions:
# 手上的股票没在to_hold中,买掉
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 to_buy:
cash_per_stock = context.portfolio.available_cash / len(to_buy)
for per in to_buy:
order_value(per,cash_per_stock)



