I am trying to figure out the best way to get information on a "run" in pandas
The sample code below returns the following results:
import pandas as pd
import numpy as np
df2 = pd.DataFrame({'Price':[0.0, 3.6, 9.3, 4.5, 2.9, 3.2, 1.0, 6.7, 8.7, 9.8, 3.4, .7, 2.2, 6.5, 3.4, 1.7, 9.4, 10.0], 'PriceDate':['2023-10-01', '2023-10-02', '2023-10-03', '2023-10-04', '2023-10-05', '2023-10-06', '2023-10-07', '2023-10-08', '2023-10-09', '2023-10-10', '2023-10-11', '2023-10-12', '2023-10-13', '2023-10-14', '2023-10-15', '2023-10-16', '2023-10-17']})
df2['Trend']=np.where(df2['Price']>df2['Price'].shift(),"UPTREND","DOWNTREND")
Now ignore for a second that the first value shouldn't have a trend value. The trend value simply shows if the current price is greater than the prior price (uptrend) or less than the lower price (downtrend).
What I want to know is
- What is the first date of any uptrend/downtrend
- What is the last date of the uptrend/downtrend
- What is the first price of the uptrend/downtrend
- What is the last price of the uptrend/downtrend
So - the first uptrend starts on 10/2 and ends on 10/3, first price is 3.6, last price is 9.3 Another uptrend started on 10/8 ended on 10/10 with a first price of 6.7 and an end price on 9.8
I'd also like to get the last price of the prior trend, so for example - that 10/8 record looks like this
Any help will be greatly appreciated


One simple approach could be holding a variable to record the current state and the values associated with the start of a run, and iterate down the dataframe until that value changes. Record, and restart.
Pseudo code:
With this, you would then have a list
runsthat contains a dictionary with the info for each run that could be converted into a dataframe, matching your expected output.However, this is very much still pseudo code would absolutely need to be reviewed to account for how your data is structured, accounting for the run on the last row, runs that are only 1 entry long, etc etc --- but something like this should get you pretty close. Good luck!