SMA Trading Strategy Using Python

This strategy works on the basic logic that whenever the 30 Day Simple Moving Average is greater than the closing price of the stock it gives a Buy signal and whenever the 30 Day SMA is smaller than the closing price then it gives a sell signal. This way we get a clear understanding of when to place a buy order and when to exit our position.

I've built this strategy using python and here is the program and logic for the strategy.

#import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
#Load data
from google.colab import files
files.upload()

#Store the data
df = pd.read_csv('HDFC.NS.csv')
#set date as index
df = df.set_index(pd.DatetimeIndex(df['Date'].values))
#show data
df




#visualize the close price
plt.figure(figsize=(16,8))
plt.title('Close Price')
plt.plot(df['Close'])
plt.xlabel('Date')
plt.ylabel('Close Price')


def SMA(dataperiod=30column='Close'):
  return data[column].rolling(window=period).mean()

df['SMA30'] = SMA(df)

#Show the data
df 



def strategy(df):
  buy = []
  sell = []
  flag = 0
  buy_price = 0

  for i in range(0, len(df)):

    if df['SMA30'][i] > df['Close'][i] and flag == 0:
      buy.append(df['Close'][i])
      sell.append(np.nan)
      buy_price = df['Close'][i]
      flag = 1
    elif df['SMA30'][i] < df['Close'][i] and flag == 1 and buy_price < df['Close'][i]:
      sell.append(df['Close'][i])
      buy.append(np.nan)
      buy_price = 0
      flag = 0
    else: 
      sell.append(np.nan)
      buy.append(np.nan)

  return (buy, sell)

Here in this function, the logic is whenever the SMA30 is greater than the Close price of the dataset and flag is equal to 0 then it will generate a buy signal and append the Buy list and change the flag to 1, and after that whenever the SMA30 is smaller than the Close price of the dataset and flag is already 1 then it will generate sell signal and append the sell list this way the flag will again be set back to 0 and this process will happen on repeat whenever this condition will ever happen again.


#get the buy and sell list
start = strategy(df)
df['Buy'] = start[0]
df['sell'] = start[1]


#visualize the close price and buy sell signal
plt.figure(figsize=(16,8))
plt.title('Close price buy sell signal')
plt.plot(df['Close'], alpha = 0.5, label = 'Close')
plt.plot(df['SMA30'], alpha = 0.5, label = 'SMA30')
plt.scatter(df.index, df['Buy'], color='green', label='Buy Signal', marker= '^', alpha = 1)
plt.scatter(df.index, df['sell'], color='red', label='sell Signal', marker= 'v', alpha = 1)
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.show()



Now here you can see we are getting consecutive buy & sell signals that are giving good opportunities for booking profit.

Comments