Intuitive explanation (Short Selling in Trading) Section 7, Unit 11

3. Perform adjustment

The method finds an extreme and will reset only after the number of set periods elapses. This means it can find a swing high that would be lower than the current price. This only happens with the latest swing. We, therefore, need to make a manual adjustment.

Can someone explain to me what exactly he is trying to do here above?

# Prepare for the Last swing adjustment, if the last_sign <0: swing high, if > 0 swing low

last_swing = np.sign(high_low['swing_high_low'][-1])

I understand he is trying to figure out if the last swing is a swing high or swing low via the np.sign method

# Instantiate last swing high and low dates
last_swing_low_dates = data[data['swing_low'] > 0].index.max()
last_swing_high_dates = data[data['swing_high'] > 0].index.max()

He uses the above code to find out the dates of the last swing low and last swing high

Test for extreme values:

# Swing_high_date is not equal to highest high date since swing_low

if (last_swing == -1) & (last_swing_high_dates != data[last_swing_low_dates:]['swing_high'].idxmax()):
   
# Reset swing_high to NaN
    data.loc[last_swing_high_dates, 'swing_high'] = np.nan

# Swing_high_date is not equal to highest high date since swing_low

elif (last_swing == 1) & (last_swing_low_dates != data[last_swing_high_dates:]['swing_low'].idxmax()):
   
# Reset swing_low to NaN
    data.loc[last_swing_low_dates, 'swing_low'] = np.nan

What is this code above supposed to do?

Thanks
 

# Swing_high_date is not equal to highest high date since swing_low



if (last_swing == -1) & (last_swing_high_dates != data[last_swing_low_dates:]['swing_high'].idxmax()):

   

# Reset swing_high to NaN

    data.loc[last_swing_high_dates, 'swing_high'] = np.nan



The above code checks two conditions. First, if the last swing is equal to -1 or not. That is, the last swing is equal to swing high or not. Second condition checks, the last swing high date is equal to the highest high date since swing low. If both conditions satisfy, it will fill the swing_high column with NaN values.



# Swing_high_date is not equal to highest high date since swing_low

elif (last_swing == 1) & (last_swing_low_dates != data[last_swing_high_dates:]['swing_low'].idxmax()):

   

# Reset swing_low to NaN

    data.loc[last_swing_low_dates, 'swing_low'] = np.nan



In this line of code, first, it checks the last swing is a swing low or not. And the last swing low date is equal to the highest low date since swing high. If both conditions satisfy, it will fill the swing_low column with NaN values.



Note: The comment above the elif condition is wrong. Will make the changes and update the notebook. Thanks!