updated Hi! Help the teapot :) In the process of mastering Python and Pandas, I encountered the problem of applying my function to the Series. I am trying to make a function that will enumerate the values ​​of a predetermined set of numbers in the Series and, if one of several criteria is met, perform the operation with the number and enter it into the new Series, otherwise proceed 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 (the Close, High, Low columns), you need to get the following output (the trail column):

  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 to any help or advice where to dig. thank

  • Can you give an example of input (since np.random generate random data and we will not see your source DF) and output (resultant) DataFrame? - MaxU
  • Thanks for the comment. I realized that nothing is clear from the previous post. Remade and its function and made real data - Oleksii Lagoda
  • 1) the variable i affects the execution of the next line. I don’t think that it was required 2) describe how you see the exit from the branch: elif high.s[0] < trail and low.s[0] < stop_loss:

2 answers 2

Good day.

1) You have the ad run == True is inside the loop, and thus your loop goes around in a closed circle. Try to put it in the first line of the function, above the loop.

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

  • Clarifying questions to the author should not be asked in the form of an answer. - Pavel Mayorov
  • Buzu know. Thank. I will correct - Andrey Pushvincev

there is an if branch in your loop from which you will never exit, which is what happens with some data

  elif high.s[0] < trail and low.s[0] < stop_loss: i = i - 1