在Python DataFrame循环中进行交易管理计算

0 投票
0 回答
15 浏览
提问于 2025-04-12 01:17

我有一个循环,里面嵌套了if和else语句。我想做的是对我的数据表中的每一行进行以下操作:

  1. 检查是否有正在进行的交易,方法是查看是否已经设置了止盈(TP)或止损(SL)。如果已经设置了,就跳到下一行,因为我不想在已有交易的情况下再开一笔。

  2. 如果没有正在进行的交易,就判断这笔交易是买入还是卖出,然后相应地设置止盈和止损。同时,还要记录下进场价格。

  3. 如果交易已经开了,就检查当前价格是否达到了我们的止盈或止损水平。如果达到了,就通过用退出价格减去进场价格来计算利润或损失,并把结果记录在数据表中。

我一直得到一个负的利润列,而损失列根本没有显示,似乎没有计算出任何损失。我的逻辑哪里出了问题呢?

# Initialize TP and SL levels
TP_level = 0.0
SL_level = 0.0
entry = 0.0

# Iterate over rows in the DataFrame
for index, row in df_H1.iterrows():
    # Check if the trade is opened
    if row['IS_TRADE'] == 'NO':
        continue

    else:
        # If trade is already open, skip
        if TP_level != 0.0 or SL_level != 0.0:
            continue
        # Set TP and SL levels based on the trade type
        elif row['TRIGGER'] == 'BUY':
            TP_level = row['R2']  # Set TP level to R2
            SL_level = row['S1']  # Set SL level to S1
            entry = row['mid_c']
        elif row['TRIGGER'] == 'SELL':
            TP_level = row['S2']  # Set TP level to S2
            SL_level = row['R1']  # Set SL level to R1
            entry = row['mid_c']
    
        # Check if the price reaches TP level
        if row['mid_c'] >= TP_level:
            # Close the trade and calculate the profit
            profit = TP_level - entry
            # Reset TP and SL levels
            TP_level = 0.0
            SL_level = 0.0
            # Update the profit in the DataFrame
            df_H1.at[index, 'PROFIT'] = profit
        # Check if the price reaches SL level
        elif row['mid_c'] <= SL_level:
            # Close the trade and calculate the loss
            loss = SL_level - entry
            # Reset TP and SL levels
            TP_level = 0.0
            SL_level = 0.0
            entry = 0.0
            # Update the loss in the DataFrame
            df_H1.at[index, 'LOSS'] = loss

# Check for any remaining open trades and calculate their profits or losses
if TP_level != 0.0 or SL_level != 0.0:
    if row['TRIGGER'] == 'BUY':
        profit = TP_level - row['mid_c']
        df_H1.at[index, 'PROFIT'] = profit
    elif row['TRIGGER'] == 'SELL':
        loss = SL_level - row['mid_c']
        df_H1.at[index, 'LOSS'] = loss

# Check for any remaining open trades and calculate their profits or losses
for index, row in df_H1.iterrows():
    if row['IS_TRADE'] == 'YES':
        if TP_level != 0.0 or SL_level != 0.0:
            if row['TRIGGER'] == 'BUY':
                profit = TP_level - row['mid_c']
                df_H1.at[index, 'PROFIT'] = profit
            elif row['TRIGGER'] == 'SELL':
                loss = SL_level - row['mid_c']
                df_H1.at[index, 'LOSS'] = loss

0 个回答

暂无回答

撰写回答