Python, Pandas – iterate over elements with condition

Question:

updated Hello! Help the teapot 🙂 In the process of mastering Python and Pandas, I ran into the problem of applying my function to Series. I'm trying to make a function that will iterate over the values ​​of a predetermined set of numbers in a Series and, if one of several criteria is met, perform an operation with a number and add it to a new Series, otherwise move on to the next number.

I tried to build the following function on my understanding, but it does not work (Jupyter just goes into endless thoughts):

def trail_stop(high, low, close):
  for row in close:
    i = -1
    run = True  
    high.s = high.shift(i)
    low.s = low.shift(i)
    trail = (close + 0.0002)
    stop_loss = (close - 0.0002)
    while run == True:
      if high.s[0] > trail and low.s[0] < stop_loss:
        stop_loss = trail
        trail = trail + 0.0002
        i = i - 1
      elif low.s[0] > stop_loss:
        return stop_loss
        run = False
      elif high.s[0] < trail and low.s[0] < stop_loss:
        i = i - 1
      else:
        run = False

table['trail'] = table.apply(trail_stop(table.High, table.Low, table.Close), axis = 1) 

That is, with such outgoing data (columns Close, High, Low), you need to get the following output (column trail):

        High      Low    Close    trail
0    1.32396  1.32358  1.32391  1.32371
1    1.32392  1.32365  1.32365  1.32385 
2    1.32370  1.32364  1.32369  1.32389 
3    1.32378  1.32365  1.32371  1.32391 
4    1.32378  1.32360  1.32360  1.32380 
5    1.32390  1.32366  1.32370  1.32390 
6    1.32384  1.32370  1.32384  1.32364 
7    1.32386  1.32355  1.32380  1.32360 
8    1.32384  1.32358  1.32379  None
9    1.32389  1.32379  1.32387  None 
10   1.32386  1.32379  1.32383  1.32363 
11   1.32394  1.32360  1.32387  None 
12   1.32389  1.32370  1.32370  1.32390  
13   1.32390  1.32370  1.32390  1.32370 
14   1.32390  1.32364  1.32387  None  
15   1.32382  1.32373  1.32382  None 

I would be glad for any help or advice where to dig. Thank you

Answer:

Good afternoon.

1) You have the declaration run == True inside the cycle, and thus your cycle goes in a vicious circle. Try moving it to the first line of the function, above the loop.

2) I'm not sure that I understand the whole task correctly, but, as another option, try using if instead of while.

Scroll to Top