# PSA: You can click on Matplotlib plots and append the points to a list.

Code to save points along x-axis:

``class PlotSelection(object): ''' Gets the points the user clicks on a plot. ''' def __init__(self,x,y): self.x = x self.y = y #self.click_type = [] self.points = [] def event_handler(self,event): self.points.append(np.round(event.xdata).astype(int)) #round based on task #self.click_type.append(int(event.button)) def get_points(self): fig,ax=plt.subplots() ax.plot(self.x,self.y) cid = fig.canvas.mpl_connect('button_press_event',self.event_handler) plt.show() #To run: #Some dataframe df y = df.Close.values x = np.arange(len(y)) ps = PlotSelection(x,y) ps.get_points() #opens plot; pick your points and close plot print(ps.points) #prints selected x-value of points ``

Useful for breaking apart data into trends, giving scipy's curve_fit an initial guess of coefficients, selecting peaks, etc.

Example: Selecting Peaks

AMD intraday data with peaks found through scipy find_peaks

The figure above is a KDE plot of AMD intraday data. Clearly, we don't want the center peak. We can try to create a function that only picks up peaks of a certain height, but depending on asset, length of time, etc. it is difficult to generalize and we might miss a peak. So, we can either click where we want our peaks or use scipy find_peaks and get the closest peaks to where we click. With oddly shaped peaks, it is better to use the first method.

Code:

``import numpy as np,matplotlib.pyplot as plt from scipy.stats import gaussian_kde,gmean,gstd from scipy.signal import find_peaks #not used in this example but helpful #df = dataframe of intraday data for last 90 days; OHLCV c = df.Close.values v = df.Volume.values wgt = abs(v-gmean(v))/gstd(v) #zscore of volume kde = gaussian_kde(c,weigths=v) #volume weighted kde of prices xr = np.linspace(c.min(),c.max(),20000) #smoother xrange for plot y = kde(xr) #get y values for xrange x = np.arange(len(y)) ps = PlotSelection(x,y) ps.get_points() plt.plot(xr,y) [plt.axvline(xr[x],color='r') for x in ps.points] ``

Picking Points Near Peak Centers

Submitted October 27, 2020 at 07:09AM by boolean_10
via https://ift.tt/35HKeBG 