"""120日均线状态与下一开盘成交;合成现金多头。""" import json from math import isclose closes = [100] * 119 + [102, 104, 90, 89] opens = [100] * 120 + [103, 105, 88] signals = [int(i >= 119 and p > sum(closes[i - 119:i + 1]) / 120) for i, p in enumerate(closes)] cash, quantity, orders = 1000, 0, [] for i, opening in enumerate(opens): target = signals[i - 1] if i else 0 if target and not quantity: quantity = int((cash - 1) // opening) cash -= quantity * opening + 1 orders.append({'index': i, 'side': 'buy', 'quantity': quantity, 'price': opening}) elif not target and quantity: cash += quantity * opening - 1 orders.append({'index': i, 'side': 'sell', 'quantity': quantity, 'price': opening}) quantity = 0 assert signals[:119] == [0] * 119 assert signals[119:] == [1, 1, 0, 0] assert [o['index'] for o in orders] == [120, 122] assert orders[0]['quantity'] == 9 and isclose(cash, 863) blocked_cash, blocked_quantity, blocked_orders = 1000, 0, [] for i, opening in enumerate(opens): if i == 120: continue # 缺开盘只能跳过,下一日重新按持续状态判断 target = signals[i - 1] if i else 0 if target and not blocked_quantity: blocked_quantity = int((blocked_cash - 1) // opening) blocked_cash -= blocked_quantity * opening + 1 blocked_orders.append([i, 'buy', blocked_quantity, opening]) elif not target and blocked_quantity: blocked_cash += blocked_quantity * opening - 1 blocked_orders.append([i, 'sell', blocked_quantity, opening]) blocked_quantity = 0 assert blocked_orders == [[121, 'buy', 9, 105], [122, 'sell', 9, 88]] assert blocked_cash == 845 print(json.dumps({'signal_tail': signals[119:], 'orders': orders, 'ending_cash': cash, 'fees': 2, 'missing_open_orders': blocked_orders, 'missing_open_ending_cash': blocked_cash}))