0

I have following Pinescript statements that I'm trying to implement using python dataframes.

Hlv = float(na)
Hlv := close > sma_high ? 1 : close < sma_low ? -1 : Hlv[1]

Line 1 - Hlv - is basically a variable name which is a float

Line 2 - Assinging new value to variable , ternary operator (if-elseif-else). The assignment Hlv[1] means previous value (value of Hlv, 1 step(row) back)

Now Implementing this in Dataframe having following columns and data ->

Current ->

Close SMA_High SMA_Low 
 10      12      5
 12      14      6
 13      17      7

Now , I want to add another column called HLV storing Hlv values for each row , based on the condition we will compute as in pinescript line2.

Expected ->

Close SMA_High SMA_Low  Hlv
 10      9       5       1     // close > sma_high = 1
 5       14      6       -1    // close < sma_low = -1
 13      17      7       -1    // here no conditions are met , so previous value of Hlv is taken i.e -1

I am not able to figure out how to generate this new column with values deriving from other columns and even how to take previous value of the column.

I went through this answer and could see we could add values on condition as below -

df['Hlv'] = pd.NA
df.loc[df.Close>df.SMA_High,'Hlv'] = 1
df.loc[df.Close<df.SMA_Low,'Hlv'] = -1

But still not sure how can I populate with previous value if no conditions are met / default case . Thanks in advance.

devcodes
  • 1,038
  • 19
  • 38

1 Answers1

1
import numpy as np
df['Hlv'] = np.NaN
df.loc[df.Close>df.SMA_High,'Hlv'] = 1
df.loc[df.Close<df.SMA_Low,'Hlv'] = -1
df.fillna(method='ffill',inplace=True)
Deven Ramani
  • 751
  • 4
  • 10