'''
筛选出市值介于20-30亿的股票,选取其中市值最小的三只股票,
每天开盘买入,持有五个交易日,然后调仓。
'''
## 初始化函数,设定要操作的股票、基准等等
def initialize(context):
g.security = get_index_stocks('000300.XSHG')
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')
def handle_data(context,data):
# print(get_current_data()['601318.XSHG'].day_open) #当天开盘价
# print(attribute_history('601318.XSHG',5)) #历史数据
# order('601318.XSHG',100) #下单 买多少股
# order_value('601318.XSHG',10000)#买多少钱的股票
# order_target('601318.XSHG',200)#买到多少股 价值为0则是卖出
# order_target_value('601318.XSHG',10000)#买到价值为10000
#一般情况先卖后买
tobuy = []
for stock in g.security:
p = get_current_data()[stock].day_open#当天开盘价
amount = context.portfolio.positions[stock].total_amount#当前股票的仓位
cost=context.portfolio.positions[stock].avg_cost #平均持仓成本,当前持仓成本
if amount >0 and p > cost*1.25:
order_target(stock,0)#止盈
if amount>0 and p < cost*0.9:
order_target(stock,0)
if p <=10.0 and amount ==0:
tobuy.append(stock)
cash_per_stock = context.portfolio.available_cash / len(tobuy)#按策略筛选出的股票平均分配多少钱
for stocks in tobuy:
order_value(stocks,cash_per_stock)