Search code examples
pythonpandasfor-loopbreak

Nested loops turn in rounds


I am trying to loop over a DataFrame.

my code sample is the following:

for index1, long in tqdm(sim_df_ha_rsi.iterrows(), total=sim_df_ha_rsi.shape[0]):
    if index1 in validLongLimits.index:
        order_index += 1
        orders[index] = {
                'Type': 'LONG',
                'Open': open_price,
                'DateOpen': start_date,
                'Commission_open': open_price * 0.0001 * amount,
                'Commission_close': None,
                'Close': None,
                'DateClose': None,
                'Profit': None,
                'Balance': 165000,
                'IsOpen': True
        }
        
        for index2, short in sim_df_ha_rsi.iloc[index1:].iterrows():
            if index2 in validShortLimits.index:
                if long['Date'] < short['Date']:
                    orders[index]['IsOpen'] = False
                    orders[index]['DateClose'] = short['Date']
                    orders[index]['Close'] = short['Close']
                    orders[index]['Commission_close'] = short['Close'] * 0.0001 * amount
                    
                    for index3, stop in sim_df_ha_rsi.iloc[index2:].iterrows():
                        if index3 in validLongLimits.index:
                            open_price = validLongLimits.loc[ validLongLimits.index == index3 ]['Open'].values[0]
                            start_date = validLongLimits.loc[ validLongLimits.index == index3 ]['Date'].values[0]
                            index = index3
                        break
                    break

I fail to catch the following pattern:

let sim_df_ha_rsi be the data. validLongLimits and validShortLimits are sublists of the data. for a given value in validLongLimits, find the following value which belongs to validShortLimits, then reloop for the next value in validLongLimits which comes after the shorted one.

sim_df_ha_rsi is like:

    Date                Open        High        Low         Close RSI_14_1m   RSI_14_5m
0   2023-01-03 10:45:00 20.090000   20.180000   20.059999   20.115000   NaN NaN
1   2023-01-03 11:00:00 20.110001   20.100000   19.870001   19.990000   NaN NaN
2   2023-01-03 11:15:00 19.995000   19.950001   19.860001   19.897500   NaN NaN
3   2023-01-03 11:30:00 19.889999   19.889999   19.799999   19.852499   NaN NaN
4   2023-01-03 11:45:00 19.860000   19.850000   19.790001   19.817500   NaN NaN
... ... ... ... ... ... ... ...
313 2023-01-17 17:00:00 17.675000   17.750000   17.650000   17.700000   72.283634   62.390653
314 2023-01-17 17:15:00 17.700000   17.740000   17.629999   17.682499   70.135453   62.390653
315 2023-01-17 17:30:00 17.679999   17.660000   17.370001   17.547500   56.248421   55.891129
316 2023-01-17 17:45:00 17.580000   17.540001   17.410000   17.487500   51.379162   55.891129
317 2023-01-17 18:00:00 17.500000   17.520000   17.520000   17.520000   53.716387   55.891129

my output would be like:

    Type    Open    DateOpen    Commission_open Commission_close    Close   DateClose   Profit  Balance IsOpen

63  LONG    19.430000   2023-01-05 11:30:00 0.19430 None    None    None    None    165000  True
74  LONG    19.600000   2023-01-05 14:15:00 0.19600 None    None    None    None    165000  True
75  LONG    19.420000   2023-01-05 14:30:00 0.19420 None    None    None    None    165000  True
76  LONG    19.330000   2023-01-05 14:45:00 0.19330 None    None    None    None    165000  True

I want to open position and close position consecutively through data with specific conditions. Then, recalculate it with the price I closed the previous one.

my code seemingly works but shortcuts many gaps. It makes many calculations to return, say, 2 elements. breaks cause some fragility in the code. I don't want to use any break statement but don't know how to do.

Would a while loop with an anchor be more useful here?


Solution

  • Paraphase your inner for-loop line by line (but haven't tested with data):

    short_df = sim_df_ha_rsi.iloc[index1:].filter(items=validShortLimits.index, axis=0)
    short_df = short_df[short_df['Date'] > long['Date']]
    if len(short_df) > 0:
        short = short_df.iloc[0]
        index2 = short.name
        orders[index]['IsOpen'] = False
        orders[index]['DateClose'] = short['Date']
        orders[index]['Close'] = short['Close']
        orders[index]['Commission_close'] = short['Close'] * 0.0001 * amount
        long_df = sim_df_ha_rsi.iloc[index2:].filter(items=validLongLimits.index, axis=0)
        if len(long_df) > 0:
            open_price = long_df.iloc[0]['Open'].values[0]
            start_date = long_df.iloc[0]['Date'].values[0]
            index = long_df.iloc[0].name