Stock Price Data - Counting Cycles in Python Pandas

Viewed 27

I am working with some stock data in pandas and would like to count the number of times (or cycles) where the price is within a certain entry and exit price point.

For example, I have set:

entry price = 136.3

exit price = 136.6

My entry price is $136.3 and my exit price is $136.6. I want to begin a cycle every time the value approaches $136.3 from below $136.3, and close that cycle when the price approaches $136.6 from below $136.6.

For example, using the dataframe in the screenshot below, we will have:

  • a cycle begins at Timestamp 1656682503 ($136.04) and ends at Timestamp 1656682802 ($137.15)
  • a cycle begins at Timestamp 1656682803 ($136.24) and ends at Timestamp 1656682804 ($136.65)

So, the cycle only begins if it crosses the entry price, and only ends if it crosses the exit price. The fluctuations in between are ignored since they never cross the entry and exit price points.

Basically, I want to be able to build a count to count the number of cycles. In this case, the count = 2.

I have thought of using .sum(), .cumsum() or .groupby(), but am honestly lost in the sauce. Any help would be appreciated.

enter image description here

1 Answers

a janky hack would be to write a function that sorts by timestamp, then iterates over the dataset, setting some variable 'switch' to indicate if you're in or out of a cycle, and adding 0.5 counts to another variable each time you switch, or adding 1 count per 2 switches

def counter(input, entry, exit, start_in_cycle=False):
    count = 0
    if start_in_cycle==False:
        cycle = False
    elif start_in_cycle==True:
        cycle = True
    temp = input.sort_values('Timestamp', ignore_index=True)
    
    for x in temp['value']:
        if cycle == False:
            if x >= entry:
                cycle == True
            else:
                pass
        if cycle == True:
            if x <= exit:
                cycle == False
                count += 1
            else:
                pass
    return count

count = counter(input_df, 136.3, 136.6, False)

Give this a try. This one only counts when a cycle is exited, and would count the first exit if the timeseries starts mid-cycle. Not sure if cycles would flip on >= and <= entry and exit, but you can adjust based on need.

Related