How to add points to timeseries graph to show buy-sell signal – matplotlib

While doing time series analysis, you can show buy/sell signal on the ghraph itself.

Following is the script for doing the same.

While working on this code, I wasted quite a lot of time on below error.

Traceback (most recent call last):
File "", line 35, in <module>
plt.scatter(df.loc[df['SMA20'] >1400.0 , 'Date'],df.loc[df['SMA20'] >1400.0, 'Close Price'], label='skitscat', color='red', s=25, marker="<")
File "/usr/local/lib/python3.6/site-packages/matplotlib/", line 3378, in scatter
edgecolors=edgecolors, data=data, **kwargs)
File "/usr/local/lib/python3.6/site-packages/matplotlib/", line 1717, in inner
return func(ax, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/matplotlib/axes/", line 4023, in scatter
offsets = np.column_stack([x, y])
File "/usr/local/lib/python3.6/site-packages/numpy/lib/", line 369, in column_stack
return _nx.concatenate(arrays, 1)
TypeError: invalid type promotion

On further research I found that matplotlib scatter plot does not support pandas series and the scatter plot output needs to be converted into list so I had to use .values to make it work.

Output of my strategy using SMA 5 and SMAA12

As you can see, in range bound market it creates a lot of whipsaw, however, it was able to capture a very good bull run.

I tried using larger duration SMA to see another strategy. Second time, I tried with SAM20 and SMA100 and here is the output

As expected, longer duration SMA strategy provides lesser number of signals, lesser whipsaw’s.

This result does not mean you need to use higher duration SMA. I am planning to run this logic for approx 200 securities, will update this post with the feedabck later.


2 Replies to “How to add points to timeseries graph to show buy-sell signal – matplotlib”

    1. Hello Ochiauta,

      Below logic is correct
      df['Buy'] = np.where( (df['SMA5']> df['SMA20']), 1, 0)
      df['Sell'] = np.where( (df['SMA5']< df['SMA20']), 1, 0)

      Let me explain. If SMA5 is more than SMA20 = Short term its uptrend and I should buy. If SMA5 is lower than SMA20, stock is falling. Basically its momentum strategy.

      Please refer to this image

      SMA5 & SMA20 Strategy

      Green arrow is where you buy and red arrow is where you sell and you pocket the different (hopefully, you can keep the nerve and let system decide the signals)

Leave a Reply

Your email address will not be published. Required fields are marked *