You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌套循环重构:DataFrame仓位开平仓遍历的无break实现咨询

连续仓位开平仓模拟的优化方案

核心需求

实现连续开平仓逻辑:从validLongLimits中取元素开多仓,找到其后续第一个validShortLimits元素平仓,再从该平仓位置之后的validLongLimits元素开始下一轮开平仓;同时基于前一次平仓价格更新余额,且不使用break语句。

方案选择:带锚点的while循环是最优解

这种依赖上一轮结果定位下一轮起始点的连续迭代场景,用带锚点指针的while循环完全替代嵌套for+break的写法,逻辑更清晰,不会遗漏数据,效率也更高。

具体实现代码

import pandas as pd
from tqdm import tqdm

# 预先将开仓、平仓信号的索引转为有序列表(保证与sim_df的时间顺序一致)
long_indices = sorted(validLongLimits.index.tolist())
short_indices = sorted(validShortLimits.index.tolist())

orders = {}
order_index = 0
amount = 1000  # 仓位数量,根据实际场景调整
current_balance = 165000  # 初始账户余额

# 锚点指针:分别跟踪当前处理的开仓、平仓信号位置
long_ptr = 0
short_ptr = 0

# 主循环:匹配开仓-平仓对
while long_ptr < len(long_indices) and short_ptr < len(short_indices):
    # 获取当前开仓信号的行数据
    long_idx = long_indices[long_ptr]
    long_row = sim_df_ha_rsi.loc[long_idx]
    
    # 移动平仓指针到当前开仓信号之后的第一个有效位置
    while short_ptr < len(short_indices) and short_indices[short_ptr] <= long_idx:
        short_ptr += 1
    
    # 没有后续平仓信号,标记为未平仓订单
    if short_ptr >= len(short_indices):
        orders[order_index] = {
            'Type': 'LONG',
            'Open': long_row['Open'],
            'DateOpen': long_row['Date'],
            'Commission_open': long_row['Open'] * 0.0001 * amount,
            'Commission_close': None,
            'Close': None,
            'DateClose': None,
            'Profit': None,
            'Balance': current_balance,
            'IsOpen': True
        }
        long_ptr += 1
        order_index += 1
        continue
    
    # 获取有效平仓信号的行数据
    short_idx = short_indices[short_ptr]
    short_row = sim_df_ha_rsi.loc[short_idx]
    
    # 计算本次交易利润及更新账户余额
    profit = (short_row['Close'] - long_row['Open']) * amount - \
             (long_row['Open'] * 0.0001 * amount + short_row['Close'] * 0.0001 * amount)
    current_balance += profit
    
    # 记录完整的开平仓订单
    orders[order_index] = {
        'Type': 'LONG',
        'Open': long_row['Open'],
        'DateOpen': long_row['Date'],
        'Commission_open': long_row['Open'] * 0.0001 * amount,
        'Commission_close': short_row['Close'] * 0.0001 * amount,
        'Close': short_row['Close'],
        'DateClose': short_row['Date'],
        'Profit': round(profit, 2),
        'Balance': round(current_balance, 2),
        'IsOpen': False
    }
    
    # 移动开仓指针,准备下一轮交易(平仓指针无需重置,下一轮开仓必须在当前平仓之后)
    long_ptr += 1
    order_index += 1

# 处理剩余未找到平仓信号的开仓订单
while long_ptr < len(long_indices):
    long_idx = long_indices[long_ptr]
    long_row = sim_df_ha_rsi.loc[long_idx]
    orders[order_index] = {
        'Type': 'LONG',
        'Open': long_row['Open'],
        'DateOpen': long_row['Date'],
        'Commission_open': long_row['Open'] * 0.0001 * amount,
        'Commission_close': None,
        'Close': None,
        'DateClose': None,
        'Profit': None,
        'Balance': current_balance,
        'IsOpen': True
    }
    long_ptr += 1
    order_index += 1

# 转换为DataFrame查看结果
orders_df = pd.DataFrame.from_dict(orders, orient='index')
print(orders_df)

方案优势

  • 全程无break语句,通过锚点指针移动控制迭代流程,逻辑清晰、易维护
  • 开仓、平仓信号仅遍历一次,时间复杂度为O(n+m),远优于嵌套for循环的O(n*m)
  • 严格遵循“平仓后再开下一轮仓”的规则,不会遗漏任何符合条件的交易信号
  • 自动处理剩余未平仓订单,避免数据丢失

内容的提问来源于stack exchange,提问作者bugrahaskan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 11:56:45