Stock Analysis With Moving Averages Crossover Strategy On Python

 The moving average is a technical indicator that helps to get the price trends. it helps to filter out noise from random short term price fluctuation. Technical traders find buy&sell signal when these moving averages cross each other. 

There are two types of averages - 
  • Simple Moving Average
  • Exponential Moving Average
These two do not have a major difference but the only difference they have is how they are calculated and what data is used in the calculation. 
SMA calculates the average price data whereas EMA gives more weight to current data.

So if Moving Averages helps in understanding the price fluctuation and one can get buy&sell signal seeing the crossover of the moving averages then we should try to make a python program that identifies the crossover automatically and gives the indicator to buy and sell.

The program which is listed below is not 100% accurate,  its just for analysis purposes. You can use it and get an idea about how moving average crossover works and gives you a buy&sell signal. Here down below I have used stock of CIPLA which is listed in NSE and the program has given some good signals for when to buy and when to sell, no doubt there are some wrong signals also but as I told this is not 100% accurate. If you have a good catch on stock analysis and prediction then you can use it to identify the correct signals otherwise just paper trade using this and build your catch. 

I have not Explained this program in this blog, there will be a separate blog where I'll explain the entire program.

So let's start with the code!


#Import the libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import pandas_datareader as dr

#Load the data
from google.colab import files
uploaded = files.upload()

#Store the data
df =pd.read_csv('CIPLA.NS.csv')
#Show the data
df

#Create a simple moving average with 30 day window
SMA30 = pd.DataFrame()
SMA30['Adj Close'] = df['Adj Close'].rolling(window=30).mean()

#Create a simple moving average with 100 day window
SMA100 = pd.DataFrame()
SMA100['Adj Close'] = df['Adj Close'].rolling(window=100).mean()

#Visualize the data to see the moving averages
plt.figure(figsize=(18.58.5))
plt.plot(df['Adj Close'], label = 'IBM', alpha = 0.35)
plt.plot(SMA30['Adj Close'], label = 'SMA30', alpha = 0.35)
plt.plot(SMA100['Adj Close'], label = 'SMA100', alpha = 0.35)
plt.title('Stock Price with moving Average')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend(loc='upper left')
plt.show()




#Create a new DataFrame to store all the data 
alldata = pd.DataFrame()
alldata['YESBANK'] = df['Adj Close']
alldata['SMA30'] = SMA30['Adj Close']
alldata['SMA100'] = SMA100['Adj Close']
#show the new DataFrame
alldata

#Create the function to signal when to buy and sell
def buy_sell(alldata):
  buy = []
  sell = []
  flag = -1

  for i in range(len(alldata)):
    if alldata['SMA30'][i] > alldata['SMA100'][i]:
      if flag != 1:
        buy.append(alldata['YESBANK'][i])
        sell.append(np.nan)
        flag = 1
      else:
        buy.append(np.nan)
        sell.append(np.nan)
    elif alldata['SMA30'][i] < alldata['SMA100'][i]:
      if flag != 0:
        buy.append(np.nan)
        sell.append(alldata['YESBANK'][i])
        flag = 0
      else:
        buy.append(np.nan)
        sell.append(np.nan)
    else:
      buy.append(np.nan)
      sell.append(np.nan)

  return (buy, sell)

#Store the buy and sell data into a variable
buy_sell = buy_sell(alldata)
alldata['buy_signal_price'] = buy_sell[0]
alldata['sell_signal_price'] = buy_sell[1]

#Visualize the data and function to get the buy and sell signal.
plt.figure(figsize=(18.58.5))
plt.plot(df['Adj Close'], label = 'IBM', alpha = 0.35)
plt.plot(SMA30['Adj Close'], label = 'SMA30', alpha = 0.35)
plt.plot(SMA100['Adj Close'], label = 'SMA100', alpha = 0.35)
plt.scatter(alldata.index, alldata['buy_signal_price'], label = 'buy', marker = '^', color = 'green')
plt.scatter(alldata.index, alldata['sell_signal_price'], label = 'sell', marker = 'v', color = 'red')
plt.title('Stock Price with moving Average')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend(loc='upper left')
plt.show()



 Okay so here what we can see is when the price was around 510 we got a sell signal on the chart and soon after that the price of the stock falls, that means it was a right signal and we should have earn profit through short selling at that time. And after that when the price of the share was around 600 then also we got a buy signal on the chart and after that the stock price increases, that was also a correct signal and here also we would have booked a good profit.

So this is how I predict stock movement, I don't entirely depend on this program instead I use it as a confirmatory aid. I personally follow the trend to predict the price plus I use this program to help only.

You can copy this code and find for yourself how crossover moving average strategy works

Comments

Popular posts from this blog

Net Present Value (NPV) On Python Using Numpy

Commodity Channel Index ( CCI ) Using Python

SMA Trading Strategy Using Python