'Python mplfinance addplot question. Add Entry Signal

does anyone know how to add an entry signal onto my graph so that I can see it visually? I want to see an entry signal on my graph when the SPY price hits $411.50.

I've read through everything I can find online regarding this topic including the mplfinance documentation and it seems like there's a way to do it by using addplot() scatter plot but I can't quite figure it out.

Here's what my code looks like so far:

# Libraries:
import pandas as pd
import mplfinance as mpf

# Pulling data:
data = pd.read_csv(r'C:\Users\Viktor\Documents\D2DT\Reformatted_Data\SPY_2021-04-12-2021-04-12.csv')

# Pre-processing data for mpf:
data['Date'] = pd.to_datetime(data['Date'])
data = data.set_index('Date')

# Plotting Data:
mpf.plot(data, type='candle', volume=True, style='yahoo', title="SP500 Data")

data.close()

Inside CSV: enter image description here Thank You for your help with this!



Solution 1:[1]

@r-beginners, I messed around with the documentation in the link you provided in the last comment and got it to work. Thank you. I'm posting the code below, hopefully this is helpful to somebody in the future!

import pandas as pd
import numpy as np
import mplfinance as mpf

day = '2021-04-12'
data = pd.read_csv(r'C:\Users\Viktor\Documents\D2DT\Reformatted_Data\SPY_' + str(day) + "-" + str(day) + '.csv')

data['Date'] = pd.to_datetime(data['Date'])
data = data.set_index('Date')

signal = []

for i in data['close']:
    if i > 411.50:
        signal.append(i)
    else:
        signal.append(np.nan)

apd = mpf.make_addplot(signal, type='scatter', markersize=200, marker='v', color='r')

mpf.plot(data[day], type='candle', volume=True, style='yahoo', title="SP500 Data", addplot=apd)

Solution 2:[2]

This single line replaces the for loop and is more efficient. It adds the required column (which we called signal) to the dataframe for plotting.

target = 411.50
df.loc[df['close'] >target, 'signal'] = True

For reference, use this site: https://datagy.io/pandas-conditional-column/

basically df.loc[df[‘column’] condition, ‘new column name’] = ‘value if condition is met’

So the full solution looks something like this:

import pandas as pd
import numpy as np
import mplfinance as mpf

day = '2021-04-12'
data = pd.read_csv(r'C:\Users\Viktor\Documents\D2DT\Reformatted_Data\SPY_' + str(day) + "-" + str(day) + '.csv')

data['Date'] = pd.to_datetime(data['Date'])
data = data.set_index('Date')


target = 411.50
df.loc[df['close'] >target, 'signal'] = True

apd = mpf.make_addplot(df['signal'], type='scatter', markersize=200, marker='v', color='r')

mpf.plot(data[day], type='candle', volume=True, style='yahoo', title="SP500 Data", addplot=apd)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sir_2727
Solution 2 D.L