Reputation: 51
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:
Thank You for your help with this!
Upvotes: 2
Views: 1643
Reputation: 5704
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)
Upvotes: 2
Reputation: 51
@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)
Upvotes: 3