diff --git a/weex/读取文件分析.py b/weex/读取文件分析.py index a3d6893..7cf0f3d 100644 --- a/weex/读取文件分析.py +++ b/weex/读取文件分析.py @@ -55,34 +55,51 @@ def check_signal(prev, curr): def simulate_trade(direction, entry_price, future_candles, take_profit_diff=30, stop_loss_diff=-10): """ 模拟交易(逐根K线回测) - 使用价差来控制止盈止损: - - 盈利达到 take_profit_diff 就止盈 - - 亏损达到 stop_loss_diff 就止损 - - direction:信号类型 - entry_price:开盘价格 - future_candles:未来的行情数据 - + 改进版:考虑开盘跳空触发止盈/止损的情况 """ - for candle in future_candles: - high, low, close = float(candle['high']), float(candle['low']), float(candle['close']) + open_p = float(candle['open']) + high = float(candle['high']) + low = float(candle['low']) + close = float(candle['close']) if direction == "long": - # 做多:检查最高价是否达到止盈,最低价是否触及止损 - if high >= entry_price + take_profit_diff: - return entry_price + take_profit_diff, take_profit_diff, candle['id'] # 止盈 - if low <= entry_price + stop_loss_diff: - return entry_price + stop_loss_diff, stop_loss_diff, candle['id'] # 止损 + tp_price = entry_price + take_profit_diff + sl_price = entry_price + stop_loss_diff + + # 🧩 开盘就跳空止盈 + if open_p >= tp_price: + return open_p, open_p - entry_price, candle['id'] + + # 🧩 开盘就跳空止损 + if open_p <= sl_price: + return open_p, open_p - entry_price, candle['id'] + + # 正常区间内触发止盈/止损 + if high >= tp_price: + return tp_price, take_profit_diff, candle['id'] + if low <= sl_price: + return sl_price, stop_loss_diff, candle['id'] elif direction == "short": - # 做空:检查最低价是否达到止盈,最高价是否触及止损 - if low <= entry_price - take_profit_diff: - return entry_price - take_profit_diff, take_profit_diff, candle['id'] # 止盈 - if high >= entry_price - stop_loss_diff: - return entry_price - stop_loss_diff, stop_loss_diff, candle['id'] # 止损 + tp_price = entry_price - take_profit_diff + sl_price = entry_price - stop_loss_diff - # 如果未来都没触发,最后一根收盘平仓 + # 🧩 开盘就跳空止盈 + if open_p <= tp_price: + return open_p, entry_price - open_p, candle['id'] + + # 🧩 开盘就跳空止损 + if open_p >= sl_price: + return open_p, entry_price - open_p, candle['id'] + + # 正常区间内触发止盈/止损 + if low <= tp_price: + return tp_price, take_profit_diff, candle['id'] + if high >= sl_price: + return sl_price, stop_loss_diff, candle['id'] + + # 未触发止盈止损,按最后收盘价平仓 final_price = float(future_candles[-1]['close']) if direction == "long": diff_money = final_price - entry_price @@ -92,6 +109,7 @@ def simulate_trade(direction, entry_price, future_candles, take_profit_diff=30, return final_price, diff_money, future_candles[-1]['id'] + def fetch_kline(day: int, year: int = 2025, month: int = 9, file_path: str = "stock_data.xlsx") -> list[dict]: """ 获取指定日期的分钟级 K 线数据。 @@ -140,7 +158,7 @@ def fetch_kline(day: int, year: int = 2025, month: int = 9, file_path: str = "st if __name__ == '__main__': datas = [] - for i in range(1, 31): + for i in range(1, 2): data = fetch_kline(year=2025, month=9, day=i) datas.extend(data)