Creating a Stock Market Analyser in Python

We shall be using Streamlit.

Prateek Majumder
Apr 19 · 5 min read

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

Read More-

Stock Codes

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 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

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

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 :

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 is a community of Analytics and Data…

Sign up for Analytics Vidhya News Bytes

By Analytics Vidhya

Latest news from Analytics Vidhya on our Hackathons and some of our best articles! Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Analytics Vidhya

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

Prateek Majumder

Written by

Electrical Engineering | IEM Kolkata | Varied Interests | Trying to understand the World.

Analytics Vidhya

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

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store