Making an Indian Stock market analysis dashboard using Streamlit

Soham Desai
4 min readJan 5, 2024

--

Howdy people! Today we will see how we can create an intuitive and advantageous stock market analysis dashboard using a library in python programming language called streamlit

The Indian stock market has grown quite a lot in these couple of years since the lockdown as more and more people have realized the importance of savings and investing. This is a tool that can help you track the stock market in your initial days.

This article explains the technical stuff even for non-coder friends and enthusiasts which includes :

  • Real-time market data of Sensex and Nifty.
  • Interactive charts and graphs
  • Powerful filtering and analysis tools help you drill down into the data.

Firstly if u are a programmer and know the basics skip to step 3 otherwise,

  1. Go to the official python installation page and click on Download Python <version>
Python official page

2. After installation u need a code editor to write the code and run it. The best code editor out there is VSCode. So head over to the download page and install it and now you are all set.

3. Now open VS Code and then create a file called dashboard.py, the .py is the python language extension.

4. Create a virtual environment by writing this command in the terminal

python -m venv venv
source venv/bin/activate

5. Now we make a requirements.txt file for installing the packages.

yfinance
plotly
streamlit

6. Here the yfinance is the Yahoo Finance package used to extract prices of stocks. Now we install these packages

pip install -r requirements.txt

7. Now import the libraries.

from math import floor
import streamlit as st
import pandas as pd
import datetime
import yfinance as yf
import plotly.graph_objects as go
from plotly.subplots import make_subplots

8. Now we write the remaining code for the dashboard.

st.title("Stock Price Screener and Analysis")
pd.set_option('max_colwidth', 400)
df = pd.DataFrame()

st.header("S&P BSE SENSEX")
today = datetime.date.today()
sensex = yf.download("^BSESN",start=today, interval="5m")
sensex_current = floor(sensex['Close'].iloc[-1])

if datetime.datetime.today().weekday()!=5 or datetime.datetime.today().weekday()!=6 :
if datetime.datetime.now().hour > 16:
st.write(f"Closing Price: {sensex_current}")
else:
st.write(f"Current Price: {sensex_current}")

if datetime.datetime.today().weekday() == 5 or datetime.datetime.today().weekday() == 6:
sensex_current = floor(sensex['Close'].iloc[-2])
st.write(f"Closing Price: {sensex_current}")
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights=[
0.7, 0.3], specs=[[{"type": "candlestick"}], [{"type": "bar"}]])
fig.update_xaxes(rangeslider_visible=False)
fig.add_trace(go.Candlestick(x=sensex.index, open=sensex['Open'], high=sensex['High'],
low=sensex['Low'], close=sensex['Close'], name='market data'), row=1, col=1)
st.plotly_chart(fig, use_container_width=True)


st.header("NIFTY 50")
nifty = yf.download("^NSEI",start=today, interval="5m")
nifty_current = floor(nifty['Close'].iloc[-1])

if datetime.datetime.today().weekday()!=5 or datetime.datetime.today().weekday()!=6 :
if datetime.datetime.now().hour > 16:
st.write(f"Closing Price: {nifty_current}")
else:
st.write(f"Current Price: {nifty_current}")

if datetime.datetime.today().weekday() == 5 or datetime.datetime.today().weekday() == 6:
nifty_current = floor(sensex['Close'].iloc[-2])
st.write(f"Closing Price: {nifty_current}")

fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights=[
0.7, 0.3], specs=[[{"type": "candlestick"}], [{"type": "bar"}]])
fig.update_xaxes(rangeslider_visible=False)
fig.add_trace(go.Candlestick(x=nifty.index, open=nifty['Open'], high=nifty['High'],
low=nifty['Low'], close=nifty['Close'], name='market data'), row=1, col=1)
st.plotly_chart(fig, use_container_width=True)

todays_stock, stocks, indicators = st.tabs(
["Stock price for Today ", "Historical Price of Stock", "Indicators"])

with todays_stock:
st.title("Today's Price of Stock")
stock = st.text_input("Enter a stock ticker symbol", "LT")
Today_stock = st.button("Get Today's Price")
today = datetime.date.today()
if Today_stock:
start_date = today
df = yf.download(f"{stock}.NS", start=start_date, interval="2m")
df['% Change'] = df['Close'].pct_change()*100
df['% Change'] = df['% Change'].round(2)
st.write(df)
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights=[
0.7, 0.3], specs=[[{"type": "candlestick"}], [{"type": "bar"}]])
fig.update_xaxes(rangeslider_visible=False)
fig.add_trace(go.Candlestick(x=df.index, open=df['Open'], high=df['High'],
low=df['Low'], close=df['Close'], name='market data'), row=1, col=1)
fig.add_trace(
go.Bar(x=df.index, y=df['Volume'], name='Volume'), row=2, col=1)

st.plotly_chart(fig, use_container_width=True)


with stocks:
st.title("Stocks")
stock_name = st.text_input("Enter a stock ticker symbol")
start_date = st.date_input("Start date")
goto_today = st.button("Get Price from start date till today")
end_date = st.date_input("End date")
get_stock = st.button("Get Stock Price")
today_date = datetime.date.today() + datetime.timedelta(days=1)
if end_date < start_date:
st.error("Error: End date must fall after start date.")
elif goto_today:
end_date = today_date
df = yf.download(f"{stock}.NS", start=start_date,
end=end_date, interval="15m")
df.style.set_properties(**{'text-align': 'left'})
st.write(df)
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights=[
0.7, 0.3], specs=[[{"type": "candlestick"}], [{"type": "bar"}]])
fig.update_xaxes(rangeslider_visible=False)
fig.update_xaxes(
rangebreaks=[
dict(bounds=["sat", "mon"]),
dict(pattern='hour', bounds=[16, 9])
]
)

fig.add_trace(go.Candlestick(x=df.index, open=df['Open'], high=df['High'],
low=df['Low'], close=df['Close'], name='market data'), row=1, col=1)
fig.add_trace(
go.Bar(x=df.index, y=df['Volume'], name='Volume'), row=2, col=1)

st.plotly_chart(fig, use_container_width=True)
elif get_stock:
df = yf.download(f"{stock}.NS", start=start_date,
end=end_date+datetime.timedelta(days=1), interval="15m")
df.style.set_properties(**{'text-align': 'left'})
st.write(df)
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights=[
0.7, 0.3], specs=[[{"type": "candlestick"}], [{"type": "bar"}]])
fig.update_xaxes(rangeslider_visible=False)
fig.update_xaxes(
rangebreaks=[
dict(bounds=["sat", "mon"]),
dict(pattern='hour', bounds=[16, 9])
]
)

fig.add_trace(go.Candlestick(x=df.index, open=df['Open'], high=df['High'],
low=df['Low'], close=df['Close'], name='market data'), row=1, col=1)
# bar chart
fig.add_trace(
go.Bar(x=df.index, y=df['Volume'], name='Volume'), row=2, col=1)

st.plotly_chart(fig, use_container_width=True)

9. Now in the terminal just run the command streamlit run dashboard.py and in the browser and new window should open for streamlit on port 8501.

The dashboard is essentially divided into 2 tabs, where the first tab is of the current today's stock prices and the other one is used to get the historical periodic data of a particular stock. Just keep in mind that while inputting the stock u need to input the correct symbol as the same listed on the NSE.

Thank you all for reading! Till next time.

--

--

Soham Desai
Soham Desai

Written by Soham Desai

IT Engineer from Xavier Institute of Engineering | Flutter App Dev | AI dev | Web 3 Enthusiast