import random import time import uuid g.security = [] g.daycount = 0 stockstemp = get_index_stocks(‘000300.XBHS‘) total = len(stockstemp) g.holdstocks = [] while len(g.security) < 15 : stock = stockstemp[random.randint(0, total-1)] if stock not in g.security: g.security.append(stock) def initialize(context): context.universe = g.security def handle_data(context, data): # 最大持仓股票支数 maxhold = 5 totalsize = len(context.universe) print(totalsize) # 取得当前的现金 cash = context.portfolio.cash g.daycount = g.daycount + 1 if len(g.holdstocks) == 0 : #初始状态 count = maxhold singlemoney = cash / 5 while count > 0 : buystock = context.universe[random.randint(0, totalsize-1)] if buystock not in g.holdstocks and symbol(buystock) in data: g.holdstocks.append(buystock) # 用所有 singlemoney 买入股票 print(‘buystock=‘ + buystock) print(‘singlemoney=‘ + str(singlemoney)) order_value(symbol(buystock), singlemoney) # 记录这次买入 #log.info("Buying %s" % (buystock)) print("Buying %s" % (buystock)) count = count - 1 print(‘count=‘ + str(count)) elif g.daycount > 7 and g.daycount % 5 == 1 : #5 days change print(‘g.daycount=‘ + str(g.daycount)) #选择过去7天表现最差的股票卖出 weakstock = ‘‘ WeakReturns = 10000.0 #dfhis = history(7, unit=‘1d‘, field=‘price‘, security_list=g.holdstocks, df=False) dfhis = history(7, ‘1d‘, field=‘price‘) for stock in g.holdstocks : if symbol(stock) in data : #停牌票跳过 continue startprice = dfhis[symbol(stock)][0] endprice = dfhis[symbol(stock)][-1] curReturns = (endprice - startprice) / startprice print(‘curReturns=‘ + str(curReturns)) if curReturns < WeakReturns : WeakReturns = curReturns weakstock = stock if weakstock == ‘‘ : weakstock = g.holdstocks[0] sellstock = weakstock print(‘weakstock=‘ + weakstock) g.holdstocks.remove(weakstock) # 卖出所有股票,使这只股票的最终持有量为0 order_target(symbol(sellstock), 0) # 记录这次卖出 #log.info("selling %s" % (sellstock)) print("selling %s" % (sellstock)) while True: buystock = context.universe[random.randint(0, totalsize-1)] if buystock not in g.holdstocks and buystock != sellstock and symbol(buystock) in data: g.holdstocks.append(buystock) # 用所有 cash 买入股票 print(‘buystock=‘ + buystock) print(‘cash=‘ + str(cash)) order_value(symbol(buystock), cash) # 记录这次买入 #log.info("Buying %s" % (buystock)) print("Buying %s" % (buystock)) break
时间: 2024-10-03 16:10:57