Im working with some data on stocks, and i wish to counter the number of times the stock price makes a higher high, e.g. how many consecutive times the stock price is higher than the previous price. The number of higher highs should then be counted in a column next to the stock price, and if the stock price does not manage to make a higher high, the value in the column should be "reset" to zero.
My desired result would look like this:
Stock Price | Number of higher highs |
---|---|
150 | 0 |
275 | 1 |
300 | 2 |
280 | 0 |
300 | 1 |
350 | 2 |
400 | 3 |
I've tried several solutions, but cannot make any on them work. I've tried using the if-statement, but im having trouble with coding the condition "if the value of the stock price is larger than the previous value, then column with number of higher highs should be equal to 1 + the previous value".
Working example:
import pandas as pd
data=[[150,0],[275,0],[300,0],[280,0],[300,0],[350,0],[400,0]]
df=pd.DataFrame(data,columns=['Stock Price','Number of higher highs'])
Appreciate all inputs and possible solutions!
I hope this solve your problem
import pandas as pd
data=[[150,0],[275,0],[300,0],[280,0],[300,0],[350,0],[400,0]]
tmp = -1
for indx in range (len( data)):
if tmp == -1:
tmp = data[indx][0]
data[indx][1] = 0
else:
if data[indx][0] > tmp:
data[indx][1]=data[indx-1][1] + 1
tmp = data[indx][0]
df=pd.DataFrame(data,columns=['Stock Price','Number of higher highs'])