Machine learning to generate buy/sell signals

How to Generate Buy & Sell Signals of Stock Trading

An example with Crude Oil daily data

Sarit Maitra
The Startup
Published in
7 min readSep 18, 2020

--

Image by Author

Buy and sell signals can be generated by two moving averages — a long-period and a short-period average. When the short moving average rises or falls below the long moving average, buy or sell signals can be generated based on set parameters.

Here, with a simple example, we have shown as how to generate report on buy/sell signals and visualize the chart.

Function to extract data:

def dataExtract(startDate,outputFile):
try:
data = pd.read_pickle(outputFile)
print('File data found...reading CrudeOil data')
except FileNotFoundError:
print('File not found...downloading CrudeOil data')
data = web.DataReader('CL=F', 'yahoo', startDate)
data.to_pickle(outputFile)
return data

data = dataExtract(startDate='2010-01-01', outputFile='CrudeOilPrice.pkl')
print(data.head())

Let us generate buy/sell signals by implementing short moving averages (20 days) and long moving averages (100 days) crossover strategy. In the code below, it can be noticed that, diff() is applied to restrict buy/sell signal.

Moving averages cross-over signals:

--

--