Financial Stock Price Web App

Data science is spread across our lives and we are surrounded by its applications. We unknowingly use the vast number of applications of data science and machine learning such as recommender systems, house price prediction, data monitoring and data analysis etc. We are in fact surrounded by data and probably have played around with it many a times (especially if you’re a math loving person). So here’s another web app in yet another vital application of data science.

This is a financial stock price web app. It shows the closing financial stock price values for S and P 500 companies. S and P 500 companies are 500 of the largest companies listed on stock exchanges in the US. The S and P 500 stock market index comprises of 505 common stocks issued by 500 large cap companies. The stocks of these companies trade either on the NYSE (New York Stock Exchange) or NASDAQ (National Association of Securities Dealers Automated Quotations). NYSE is an auction market whereas NASDAQ is a dealer’s market. Some of the S and P 500 companies included in the dataset are Alphabet, Apple, Amazon, Facebook, Microsoft etc. 

This web app displays information about the respective user input company (from the list of S and P 500 companies) and provides its stock chart along with other company share statistics. It displays information of the company such as its GICS sector, GICS sub-industry, headquarters location, CIK, etc. Users can analyze data over the past multiple years of the respective company.

Simple moving averages have also been provided so that users can compare the present value with the average value of stocks in a particular range. This helps to determine whether an asset price will continue or if it will reverse a bull or bear trend. Historical company shares along with company share data statistics have also been provided. 

Yahoo Finance and Yahoo Finance API was used to obtain the data. Users can also move their cursor over the stock charts to get the exact date and value of the stock price. Yahoo finance provides financial data, stock quotes, press releases etc. It alsooffers other tools for personal finance management.

Added feature: I added time series forecasting using fbprophet. Many people are unable to pip install that. This might be due to some reasons: fbprophet requires a C++ compiler, so if you’re operating on Windows, better use anaconda instead of VScode. Fbprophet also requires pystan so make sure that is working and check for the compatibility of those two versions. For any other build issues, contact us or drop a comment. You can also check out Stack Overflow for additional errors during installation of fbprophet: https://stackoverflow.com/questions/56701359/running-setup-py-install-for-fbprophet-error. Other solutions might also be available on Github.

Coming onto the update, yes I’ve finally added time series forecasting for the stocks and now the app can predict the opening and closing stock price values of companies over a period of 1 to 15 years. Time series data using rangeslider can also be seen to find out historical opening and closing stock values. The forecast plot and components have also been provided. Stock values and predictions can also be seen on a weekly basis apart from their yearly values and trends.  

We have deployed the app using Streamlit. It is an open source framework that allows data science teams to deploy web apps fairly easily. It’s one of the best hosting services I’ve used and it’s great for quick and easy deployment of web apps. The app is majorly coded in python. 

This web app helped me to improve my experience in Machine Learning and definitely helped in my future projects. Feel free to add onto this project and don’t hesitate to drop by any suggestions. Hope you enjoy the app!

Link of the app: https://share.streamlit.io/braxtonova/stockpred/main/app.py

Explanation of the Code and how you can make this yourself !

Here, I am going to go through the code in a very concise and simple manner so that people with even minimal experience in programming or data science can follow along and benefit it. This app has been coded in python and has been deployed on streamlit as mentioned before. I’ve also used the Random Forest Classifier Algorithm for this particular problem. 

Alright so lets finally get started. First up I’ve imported the python packages / libraries that I’ve used for this app. More information for them is available on the project template of SkillTools. 

import streamlit as st
from datetime import date

import yfinance as yf
from fbprophet import Prophet
from fbprophet.plot import plot_plotly
from plotly import graph_objs as go

from PIL import Image
import pandas as pd

After this, I’ve included an image of the usual perception of Finance in terms of mathematics (just to show you’ll something new). I’ve also included the description of the app early on. We also need to load the dataset (S and P 500 companies dataset in this case).

image = Image.open('stock.jpeg')

st.image(image, use_column_width=True)

st.markdown('''
# Fintech Stock Price App 
This app shows the closing financial stock price values for S and P 500 companies along with the timeline.  
- These are 500 of the largest companies listed on stock exchanges in the US.
- App built by Pranav Sawant and Anshuman Shukla of Team Skillocity.
- Dataset resource: Yahoo Finance
- Added feature: Time series forecasting with fbprophet that can predict the stock price values over 15 years.
- Note: User inputs for the company to be analysed are taken from the sidebar. It is located at the top left of the page (arrow symbol). Inputs for other features of data analysis can also be provided from the sidebar itself. 
''')
st.write('---')

@st.cache
def load_data():
    components = pd.read_html(
        "https://en.wikipedia.org/wiki/List_of_S" "%26P_500_companies"
    )[0]
    return components.drop("SEC filings", axis=1).set_index("Symbol")


@st.cache(allow_output_mutation=True)
def load_quotes(asset):
    return yf.download(asset)

The next block of a code is a slightly long one but I’ll try to explain it in a simple manner. Would have been much easier in person but in the pandemic we’re all at home aren’t we. I have defined certain components and have listed the features upon which we can perform EDA and find more information about the particular stocks. Some of these are year founded, security, simple moving average etc. I have provided checkboxes / sliders so that users can change their inputs. (They have an option to choose the particular company but they can’t manipulate stocks within the app). I’ve included stock charts and other features into the app.

def main():
    components = load_data()
    
    st.sidebar.title("Options")

    if st.sidebar.checkbox("View companies list"):
        st.dataframe(
            components[["Security", "GICS Sector", "Date first added", "Founded"]]
        )
        
    title = st.empty()
        
    def label(symbol):
        a = components.loc[symbol]
        return symbol + " - " + a.Security

    st.sidebar.subheader("Select company")
    asset = st.sidebar.selectbox(
        "Click below to select a new company",
    components.index.sort_values(),
    index=3,
    format_func=label,
    )

    
    title.title(components.loc[asset].Security)
    if st.sidebar.checkbox("View company info", True):
        st.table(components.loc[asset])
    data0 = load_quotes(asset)
    data = data0.copy().dropna()
    data.index.name = None

    section = st.sidebar.slider(
        "Number of days for Data Analysis of stocks",
        min_value=30,
        max_value=min([5000, data.shape[0]]),
        value=1000,
        step=10,
    )

    data2 = data[-section:]["Adj Close"].to_frame("Adj Close")

    sma = st.sidebar.checkbox("Simple Moving Average")
    if sma:
        period = st.sidebar.slider(
            "Simple Moving Average period", min_value=5, max_value=500, value=20, step=1
        )
        data[f"SMA {period}"] = data["Adj Close"].rolling(period).mean()
        data2[f"SMA {period}"] = data[f"SMA {period}"].reindex(data2.index)

    sma2 = st.sidebar.checkbox("Simple Moving Average 2")
    if sma2:
        period2 = st.sidebar.slider(
            "Simple Moving Average 2 period", min_value=5, max_value=500, value=100, step=1
        )
        data[f"SMA2 {period2}"] = data["Adj Close"].rolling(period2).mean()
        data2[f"SMA2 {period2}"] = data[f"SMA2 {period2}"].reindex(data2.index)

    st.subheader("Stock Chart")
    st.line_chart(data2)

    
    st.subheader("Company Statistics")
    st.table(data2.describe())

    if st.sidebar.checkbox("View Historical Company Shares"):
        st.subheader(f"{asset} historical data")
        st.write(data2)

    
    


main()

My original app contained just this much itself. But then someone also suggested me to run time series forecasting using fbprophet. I did have certain issues while installing but I’ve already mentioned it earlier in this article. There were however some slight disadvantages of doing this. The app became slower and the compatibility of fbprophet and rangslider is not the best with streamlit. But regardless of that, I’ve put it in and here’s how you can do it too.

To prevent the app from significantly lagging, I’ve only used a few stocks for demonstrating time series forecasting. We can predict the stocks upto a period of 35 years.

def pre_dict():
    st.header('Stock prediction')

    START = "2010-01-01"
    TODAY = date.today().strftime("%Y-%m-%d")


    stocks = ('AAPL', 'GOOG', 'MSFT', 'GME')
    selected_stock = st.selectbox('Select company for prediction', stocks)

    n_years = st.slider('Years of prediction:', 1, 15)
    period = n_years * 365

Next, we need to load the data and plot it using a simple scatterplot.

 @st.cache
    def load_data(ticker):
        data = yf.download(ticker, START, TODAY)
        data.reset_index(inplace=True)
        return data

	
    #data_load_state = st.text('Loading data...')
    data = load_data(selected_stock)
    #data_load_state.text('Loading data... done!')

    st.subheader('Raw data')
    st.write(data.tail())

    # Plot raw data
    def runpls():
        fig = go.Figure()
        fig.add_trace(go.Scatter(x=data['Date'], y=data['Open'], name = "stock_open"))
        fig.add_trace(go.Scatter(x=data['Date'], y=data['Close'], name = "stock_close"))
        fig.layout.update(title_text='Time Series data with Rangeslider', xaxis_rangeslider_visible=True)
        st.plotly_chart(fig)
	
    runpls()

Now we simply need to predict the stock output, make necessary prediction data frames, and forecast the components.

df_train = data[['Date','Close']]
    df_train = df_train.rename(columns={"Date": "ds", "Close": "y"})

    m = Prophet()
    m.fit(df_train)
    future = m.make_future_dataframe(periods=period)
    forecast = m.predict(future)

    # Show and plot forecast
    st.subheader('Forecast data')
    st.write(forecast.tail())
    
    st.write(f'Forecast plot for {n_years} years')
    fig1 = plot_plotly(m, forecast)
    st.plotly_chart(fig1)

    st.write("Forecast components")
    fig2 = m.plot_components(forecast)
    st.write(fig2)

To finish up the code, I’ve added a stop button so that users can stop the forecasting as and when they like.

if st.button('Stock Prediction'): 
   if st.button('Stop Prediction'):
      st.title("Prediction Stopped")
   else:
       pre_dict()

So that’s all from this web app and I’ll soon be back with another cool application of machine learning and data science. Hasta Pronto !

Financial Stock Price Web App9 min read

193 thoughts on “Financial Stock Price Web App9 min read

  1. Clean and well displayed with good statistics. One suggestion : you can use time series forecasting using fbprophet package.

  2. Hi, thanks. Yeah I'll definitely add that. I originally tried doing that but unfortunately I couldn't pip install fbprophet as it requires a C++ compiler. I'll try using Anaconda and see how that goes.

  3. A secret weapon for anyone who needs content. I dont need to tell you how important it is to optimize every step in your SEO pipeline. But unfortunately, its nearly impossible to cut out time or money when it comes to getting good content. At least thats what I thought until I came across Article Forge. Built by a team of AI researchers from Stanford, MIT, Carnegie Mellon, Harvard, Article Forge is an AI content writer that uses deep learning models to research, plan out, and write entire articles about any topic with the click of a button. Their team trained AI models on millions of articles to teach Article Forge how to draw connections between topics so that each article it writes is relevant, interesting and useful. All their hard work means you just enter a few keywords and Article Forge will write a complete article from scratch making sure every thought flows naturally into the next, resulting in readable, high quality, and unique content. Put simply, this is a secret weapon for anyone who needs content. I get how impossible that sounds so you need to see how Article Forge writes a complete article with the Click Here:👉 https://stanford.io/3FXszd0

  4. Hmm it looks like your website ate my first comment (it was super long) so I guess I’ll just sum it up what I wrote and
    say, I’m thoroughly enjoying your blog. I as well am
    an aspiring blog blogger but I’m still new to everything.
    Do you have any tips and hints for first-time blog writers?
    I’d genuinely appreciate it. Life Experience Degrees

  5. Great blog here! Also your site loads up very fast! What web host are you using? Can I get your affiliate link to your host? I wish my website loaded up as fast as yours lol

  6. I found your blog through google and I must say, this is probably one of the best well prepared articles I have come across in a long time. I have bookmarked your site for more posts.

  7. Hello there, just became aware of your blog through Google, and found that it is truly informative. I am going to watch out for brussels. I will appreciate if you continue this in future. Lots of people will be benefited from your writing. Cheers!

  8. It is perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I want to suggest you some interesting things or suggestions. Perhaps you can write next articles referring to this article. I wish to read more things about it!

  9. I dont think Ive caught all the angles of this subject the way youve pointed them out. Youre a true star, a rock star man. Youve got so much to say and know so much about the subject that I think you should just teach a class about it

  10. Can I just say what a relief to seek out someone who actually knows what theyre speaking about on the internet. You positively know find out how to bring a problem to mild and make it important. Extra individuals have to read this and perceive this side of the story. I cant believe youre not more in style because you positively have the gift.

  11. Hello, I think your blog might be having browser compatibility issues. When I look at your website in Chrome, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other than that, awesome blog!

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top