After getting data of the SPY from Yahoo I create a channel of closing prices using, as you can see below, the Max and Min rolling window. The columns are HC and HL.
I need to create a column (which I have called flag) that shows 1 when the close price is equal to HC and this value continues until close will be equal to HL. At this point the value of Flag will be -1. As you can see it is very simple, the Flag can have just two values; 1 or -1.
The simple formula would be something like:
- if Close == HC then flag is 1
- if Close == HL then flag is -1
- if Close != HC and Close !=HL then flag is equal to the last value saved on the variable flag.
I have tried several things, including the code below, with no luck. The problem with this code is that the 0 value is shown. And I don't know how to make it disappear thru a conditional:
import pandas as pd
import pandas_datareader as dr
import numpy as np
from datetime import date
df = dr.data.get_data_yahoo('SPY',start='01-01-2019',end=date.today())
df['HC'] = df['Close'].rolling(20).max()
df['LC'] = df['Close'].rolling(20).min()
df['Flag'] = [1 if (df.loc[ei, 'Close'] == df.loc[ei, 'HC']) else
-1 if (df.loc[ei, 'Close'] == df.loc[ei, 'LC']) else
0 for ei in df.index]
Below you can see in blue the results of my code and in red the result that I need.
Is there a simple way to do this? I would appreciate if someone could help me with it. Thank you!