需求:
代码:
import jqdata
def initialize(context):
# 定义一个全局变量, 保存要操作的股票
#g.security ='601318.XSHG'
g.security = get_index_stocks('000300.XSHG')
#print(g.security)
set_option('use_real_price', True)
# 股票类每笔交易时的手续费是:买入时佣金万分之三,卖出时佣金万分之三加千分之一印花税, 每笔交易佣金最低扣5块钱
set_order_cost(OrderCost(open_tax=0, 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)
# 一般情况下,先卖后买
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_strock = context.portfolio.available_cash / len(tobuy) # 每只股票分的钱
for stock in tobuy:
order_value(stock, cash_per_strock)