How I made auto trading script — Part 2

Farhad Sanaei
5 min readSep 22, 2020

--

So let's see some codes

Before starting, it needs to be mentioned that all the codes that you will see here are written in python.

Download stock data:

First of all, what you need is to download stock data. There are many services to provide that, I found yahoo finance API as a very reliable and easy service to fetch this information.

Following is how you can fetch stock data via yfinance which is a python plugin for fetching yahoo finance API information.

yfinance.download(stockName, startDate, endDate, interval = ‘1m’)

I would recommend keeping the interval to 1 minute(1m) to have a more accurate MACD.

It also should be noted that with an interval of 1 minute you cannot query more than 7 days(the difference between startDate and endDate should not be more than 7 days)

Calculate MACD

Now based on the stock data that you have you need to calculate the MACD.

I went through understanding how MACD is calculated and in that way, an article helped a lot and I will share it with you in case you also want to understand how is this calculation happening. https://fairmontequities.com/how-to-calculate-the-macd/

There is always a plugin :)

After a lot of implementations, I found out that there is a python plugin called Talib and it can calculate MACD very easily.

You can calculate the MACD like following:

data[“macd”], data[“macd_signal”], data[“macd_hist”] = talib.MACD(data[‘Close’],fastperiod=12, slowperiod=26, signalperiod=9)

When to Buy/Sell?

Now that we have MACD information, we have to calculate and see when we have to buy or sell our stock.

There are 5 situations that might happen:

  1. MACD < Signal AND you did not buy yet -> In this case it means that stock price is decreasing. You need to do nothing and wait
  2. MACD < Signal AND you already bought a stock -> As stock price is decreasing, in this situation you have to sell your stocks
  3. MACD > Signal AND you did not buy yet -> As stock price is decreasing, and you still did not buy any stock, in this situation you should buy a new stock
  4. MACD >Signal AND you already bought a stock -> Stock price is increasing and you already bought a stock. In this situation, you just have to sit back and enjoy increasing the profits in your account :)
  5. MACD == Signal -> It means that MACD and SIGNAL are crossing each other. You will do nothing in this situation but right after this, you have to check very quickly again and see in which direction MACD and SIGNAL are going and decide about selling/buying.

Following is how I manage to calculate those situations in my script:

orderID = ''
if macd - macd_signal < 0 :
if len(orderID) == 0:
print 'Dont buy yet'
else:
print 'Sell'
orderID = ''
else:
if macd - macd_signal > 0:
if len(orderID) == 0:
print 'BUY'
orderID = '<order ID here>'
else:
print 'Dont sell yet'
else:
print 'Tie, Wait'

Let’s run it:

If you want to simply run your code for a date range then the complete code will be like following:

import yfinance
import talib
def downloadStockData(stockName= 'TL0.DE', startDate= '2020-9-22', endDate= '2020-9-23'):
return yfinance.download(stockName, startDate, endDate, interval = '1m')
def calculateMacd(data):
data["macd"], data["macd_signal"], data["macd_hist"] = talib.MACD(data['Close'],fastperiod=12, slowperiod=26, signalperiod=9)
return data
def calculateTheProfit(data):
orderID = ''
for i in range(len(data["macd"])):
# print(data.index[i], data["macd"][i] , data["macd_signal"][i], data["macd_hist"][i], data["Close"][i])
# print data.index[i], data["macd"][i] - data["macd_signal"][i]
if data["macd"][i] - data["macd_signal"][i] < 0 :
if len(orderID) == 0:
print data.index[i], 'Dont buy yet'#, ' MACD:', data["macd"][i], ' Signal:', data["macd_signal"][i]
else:
print data.index[i], 'Sell', ' Price:', data["Close"][i]
orderID = ''
else:
if data["macd"][i] - data["macd_signal"][i] > 0:
if len(orderID) == 0:
print data.index[i], 'BUY', ' Price:', data["Close"][i]
orderID = 'Dummy id'
else:
print data.index[i], 'Dont sell yet'#, ' MACD:', data["macd"][i], ' Signal:', data["macd_signal"][i]
else:
print data.index[i], 'Tie, Wait'
lastPrice = 0
if len(orderID) != 0:
lastPrice = data["Close"][len(data["Close"]) - 1]
stockData = downloadStockData()stockDataWithMacd = calculateMacd(stockData)calculateTheProfit(data= stockDataWithMacd)

Save the code above in a file(for instance name it macdtest.py) . To run this code you can simply run python macdtest.py in your terminal.

You can change the dates and stock name to see the results for different stocks and different dates. I would also suggest changing the interval to 1d and use different dates with the difference of (for instance) on year to see prices for every day instead of every minute.

The output would be something like the following:

2020-09-22 14:01:00+02:00 BUY  Price: 363.95001220703125
2020-09-22 14:02:00+02:00 Dont sell yet
2020-09-22 14:04:00+02:00 Dont sell yet
2020-09-22 14:05:00+02:00 Dont sell yet
2020-09-22 14:06:00+02:00 Dont sell yet
2020-09-22 14:08:00+02:00 Dont sell yet
2020-09-22 14:09:00+02:00 Dont sell yet
2020-09-22 14:10:00+02:00 Dont sell yet
2020-09-22 14:11:00+02:00 Dont sell yet
2020-09-22 14:12:00+02:00 Dont sell yet
2020-09-22 14:13:00+02:00 Dont sell yet
2020-09-22 14:14:00+02:00 Dont sell yet
2020-09-22 14:15:00+02:00 Dont sell yet
2020-09-22 14:16:00+02:00 Dont sell yet
2020-09-22 14:18:00+02:00 Dont sell yet
2020-09-22 14:19:00+02:00 Dont sell yet
2020-09-22 14:20:00+02:00 Dont sell yet
2020-09-22 14:24:00+02:00 Dont sell yet
2020-09-22 14:26:00+02:00 Dont sell yet
2020-09-22 14:28:00+02:00 Dont sell yet
2020-09-22 14:29:00+02:00 Dont sell yet
2020-09-22 14:30:00+02:00 Dont sell yet
2020-09-22 14:31:00+02:00 Dont sell yet
2020-09-22 14:32:00+02:00 Dont sell yet
2020-09-22 14:33:00+02:00 Dont sell yet
2020-09-22 14:34:00+02:00 Sell Price: 365.3500061035156
2020-09-22 14:35:00+02:00 Dont buy yet
2020-09-22 14:37:00+02:00 Dont buy yet

What is the next step?

From what I saw in the output I realized that in some stocks it is not always leading to having a profit if we buy and sell based on MACD.

So I decided to write some tests for this algorithm to make sure it is at least profitable for most of the time for the stocks that I am trying to buy.

In the next part, I am going to share my experience with how I tested my code and how I adjusted it based on my favorite stocks to have maximum profits.

Please Clap 👏 , subscribe and share if you liked it ☺️

--

--