Analytics Vidhya

Analytics Vidhya is a community of Generative AI and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Creating a Stock Market Analyser in Python

Prateek Majumder
Analytics Vidhya
Published in
5 min readApr 19, 2021

--

Streamlit can be used to create simple and easy web apps in Python. Streamlit makes deveopment and deployment of Web Apps very easy. Check out the official streamlit website.

Understanding some Stock Market Terms

Before we dive into creating the application on Streamlit, we will understand some Stock Market terminology. Accoring to Investopedia, “The stock market refers to the collection of markets and exchanges where regular activities of buying, selling, and issuance of shares of publicly-held companies take place.”

Read More-

Stock Codes

A stock code definitionis an item of stock on a stock quotation scheme. Each unique code is made up of either numbers and letters or both. For example, Microsoft is listed as “MSFT” on NASDAQ and International Business Machines is listed as “IBM” on NYSE.

Sample Stock Market Data.

Then, the high and low refer to the maximum and minimum prices in a given time period. Open and close are the prices at which a stock began and ended trading in the same period. Volume is the total amount of trading activity. Adjusted values factor in corporate actions such as dividends, stock splits, and new share issuance.

Moving Averages

A moving average (MA) is a stock indicator that is commonly used in technical analysis. The reason for calculating the moving average of a stock is to help smooth out the price data over a specified period of time by creating a constantly updated average price.

A simple moving average (SMA) is a calculation that takes the arithmetic mean of a given set of prices over the specific number of days in the past; for example, over the previous 15, 30, 100, or 200 days.

OHLC Candle Stick Graph

Candlestick charts are used by traders to determine possible price movement based on past patterns. Candlesticks are useful when trading as they show four price points (open, close, high, and low) throughout the period of time the trader specifies.

Many algorithms are based on the same price information shown in candlestick charts. Trading is often dictated by emotion, which can be read in candlestick charts.

Getting into the Code

First, we import the necessary libraries. Do write the code in a .py file.

import warnings
warnings.filterwarnings('ignore') # Hide warnings
import datetime as dt
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader.data as web
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from PIL import Image
import os
from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates
import streamlit as st

Pandas datareader will be used to scrape the data. From mpl_finance, we shall be using the Candlestick charts.

Next, we will take the Stock code of the company, and also the starting date of the stock and the end date of the stock.

#title
st.title('Stock Market App')
'---------------------------------------------------------'
#text
st.write("Developed by Prateek Majumder")
image = Image.open(os.path.join('STOCK.png'))
st.image(image)
com = st.text_input("Enter the Stock Code of company","AAPL")'You Enterted the company code: ', comst_date= st.text_input("Enter Starting date as YYYY-MM-DD", "2000-01-10")'You Enterted the starting date: ', st_dateend_date= st.text_input("Enter Ending date as YYYY-MM-DD", "2000-01-20")'You Enterted the ending date: ', end_date

Next, we will use pandas_datareader.data to gather the stock market data from Yahoo Finance.

df = web.DataReader(com, 'yahoo', st_date, end_date)  # Collects data
df.reset_index(inplace=True)
df.set_index("Date", inplace=True)

Next, we will plot some of the data we got from yahoo finance.

#title
st.title('Stock Market Data')
'The Complete Stock Data as extracted from Yahoo Finance: '
df
'1. The Stock Open Values over time: '
st.line_chart(df["Open"])
'2. The Stock Close Values over time: '
st.line_chart(df["Close"])

Take note, that in the code, I had given AAPL (Apple) and sample dates, these can be modified in the app GUI.

GUI for data entry.
Data from Yahoo Finance.

Next, we code for displaying the moving averages.

mov_avg= st.text_input("Enter number of days Moving Average:", "50")'You Enterted the Moving Average: ', mov_avgdf["mov_avg_close"] = df['Close'].rolling(window=int(mov_avg),min_periods=0).mean()'1. Plot of Stock Closing Value for '+ mov_avg+ " Days of Moving Average"
' Actual Closing Value also Present'
st.line_chart(df[["mov_avg_close","Close"]])
df["mov_avg_open"] = df['Open'].rolling(window=int(mov_avg),min_periods=0).mean()'2. Plot of Stock Open Value for '+ mov_avg+ " Days of Moving Average"
' Actual Opening Value also Present'
st.line_chart(df[["mov_avg_open","Open"]])

It will look somewhat like this.

Moving Average.

Now, we do the code for the OHLC Candle Stick Graph.

ohlc_day= st.text_input("Enter number of days for Resampling for OHLC CandleStick Chart", "50")# Resample to get open-high-low-close (OHLC) on every n days of data
df_ohlc = df.Close.resample(ohlc_day+'D').ohlc()
df_volume = df.Volume.resample(ohlc_day+'D').sum()
df_ohlc.reset_index(inplace=True)
df_ohlc.Date = df_ohlc.Date.map(mdates.date2num)
# Create and visualize candlestick charts
plt.figure(figsize=(8,6))
'OHLC Candle Stick Graph for '+ ohlc_day+ " Days"ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1)
ax1.xaxis_date()
candlestick_ohlc(ax1, df_ohlc.values, width=2, colorup='g')
plt.xlabel('Time')
plt.ylabel('Stock Candle Sticks')
st.pyplot()

Other code and images can be added to the webapp for creating a better experience and better understanding.

Running the streamlit app.

streamlit run [filename]

Read More : https://docs.streamlit.io/en/stable/

App Deployed in Heroku :

The app can also be deployed as a live app on heroku. For that purpose, we need to add —

procfile, requirements.txt, runtime.txt, setup.sh.

Read More : https://devcenter.heroku.com/articles/python-pip

Check out the full project on my Github Page :

Do check out the live deployed Link :

Do connect with me on Linkedin :

Thank You.

--

--

Analytics Vidhya
Analytics Vidhya

Published in Analytics Vidhya

Analytics Vidhya is a community of Generative AI and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

No responses yet