myrelaxsauna.com

Creating a Simple Stock Dashboard Using Flask and Python

Written on

Chapter 1: Introduction to Finance and Programming

Welcome to an engaging guide at the crossroads of finance and coding! If you've ever wanted to explore stock market trends or dreamt of building your own stock dashboard, you’ve come to the right place. In this article, we will embark on a journey to construct a straightforward yet effective stock dashboard utilizing Flask, a Python web framework, along with yfinance, a library that allows us to easily access financial data. No need for extensive programming or finance experience—just a desire to learn!

The Stock Market: A Data-Driven Landscape

The stock market is a dynamic environment, constantly influenced by global events, corporate decisions, and investor sentiment. For both experienced investors and those just starting out, keeping track of this ever-changing financial landscape is essential. Imagine leveraging programming to access a wealth of market data, turning raw figures into valuable insights. Our mission is to develop a Flask application that showcases stock information for specific companies over the last five business days, marking the beginning of your exploration into finance and web development.

The simplicity of this project is its charm, as it caters to your curiosity. With basic programming skills and some understanding of stock market principles, you can create tools that demystify the complexities of the market. The Flask app we are going to build serves not only as a project but also as proof of how coding can unlock financial insights. With just a few lines of Python code and the intuitive Flask framework, you can start developing personalized dashboards, analytical tools, or even automated trading systems.

Step-by-Step Guide: Building the Dashboard

Understanding Our Tools

  • Flask: A minimal web application framework for Python, providing essential tools and libraries to simplify web application development.
  • yfinance: A Python library that facilitates the download of historical market data from Yahoo Finance, granting access to a wealth of information. While more advanced and detailed data sources exist, yfinance is perfect for our current project.

Setting Up the Environment

Before diving into the code, ensure that you have Python installed. Then, install Flask and yfinance using pip, Python's package manager, with the command:

pip install Flask yfinance

Our project structure will resemble the following:

/your_project
/templates index.html

app.py

To create a new Flask project, you can use your preferred Integrated Development Environment (IDE) (like PyCharm), and navigate to File -> New Project.

Fetching Stock Data

Our objective is to display stock data, including opening, closing, high, and low prices for chosen stocks over the past five business days. We will use yfinance for data retrieval and Flask to present it on the web.

Crafting the Application

The heart of our application lies in the app.py file, where we will establish the Flask application and define how to gather and display stock data. This involves two primary components:

  1. A function to retrieve stock data for a given symbol and date using yfinance.
  2. Flask routes that dictate what content appears on our web page.

We also need an index.html file, which will serve as the template for our webpage, utilizing HTML and CSS for structure and styling, along with a bit of JavaScript for interactivity.

Initial Setup: Imports

from flask import Flask, render_template

import yfinance as yf

from datetime import datetime, timedelta, date

import pytz

  • Flask: Handles web server operations, routing, and HTML rendering.
  • render_template: Renders an HTML template file, allowing data from our Python code to be integrated into the web page.
  • yfinance: Essential for fetching financial data, providing access to a vast stock information repository.
  • datetime, timedelta, date: Manage dates and times, crucial for calculating time spans and specific dates.
  • pytz: Ensures accurate time zone localization for our dates.

Fetching Stock Data

app = Flask(__name__)

def get_stock_data(symbol, date):

stock = yf.Ticker(symbol)

tz = pytz.timezone('America/New_York')

start_date = datetime.strptime(date, '%Y-%m-%d')

start_date = tz.localize(start_date)

hist = stock.history(start=start_date, end=start_date + timedelta(days=1))

if not hist.empty:

last_row = hist.iloc[-1]

return {

'open': round(last_row['Open'], 2),

'high': round(last_row['High'], 2),

'low': round(last_row['Low'], 2),

'close': round(last_row['Close'], 2),

}

else:

return {'open': 'N/A', 'close': 'N/A', 'high': 'N/A', 'low': 'N/A'}

This function initializes a Flask application and is designed to fetch historical stock data for a specific symbol on a designated date, utilizing yfinance to obtain open, high, low, and close prices. It also ensures that the date is localized to Eastern Time, which is vital since the New York Stock Exchange operates in this time zone.

Determining the Last Five Business Days

def get_last_5_business_days():

today = date.today()

last_5_days = [today - timedelta(days=x) for x in range(1, 8)]

business_days = [day for day in last_5_days if day.weekday() < 5][:5]

return business_days

This function identifies the last five business days, excluding weekends, to provide a timeframe for our stock data analysis.

Rendering the Home Page

@app.route('/')

def home():

dates = get_last_5_business_days()

date_strings = [date.strftime('%Y-%m-%d') for date in dates]

stocks_data = {}

for date_string in date_strings:

stocks_data[date_string] = {}

for symbol in ['AAPL', 'GOOGL', 'MSFT']:

stock_data = get_stock_data(symbol, date_string)

stocks_data[date_string][symbol] = stock_data

return render_template('index.html', stocks_data=stocks_data, dates=date_strings)

This segment of code outlines the main page of our web application. The @app.route('/') decorator indicates that this function should execute when the root URL is accessed. The function gathers stock data for the last five business days for specified stock symbols and renders the index.html template with the collected data.

Creating the HTML Template

To display the gathered data, we need to create an HTML page within the templates directory. Right-click on the folder and create a new HTML file (named index for simplicity).

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Stock Dashboard</title>

<style>

body { font-family: Arial, sans-serif; }

.tab-content { display: none; }

.tab-content.active { display: block; }

#tabs button.active { background-color: #4CAF50; color: white; }

#tabs button { background-color: #f1f1f1; color: black; padding: 10px 20px; border: none; cursor: pointer; }

#tabs button:hover { background-color: #ddd; }

table { width: 100%; border-collapse: collapse; }

th, td { text-align: left; padding: 8px; }

th { background-color: #f2f2f2; }

tr:nth-child(even) { background-color: #f9f9f9; }

.increase { background-color: #4CAF50; color: white; }

.decrease { background-color: #f44336; color: white; }

.same { background-color: #f9f9f9; color: black; }

</style>

</head>

<body>

<h1>Stock Dashboard</h1>

<div id="tabs">

<!-- Tab content will go here -->

</div>

<table>

<!-- Table data will be populated here -->

</table>

</body>

</html>

This basic HTML structure sets up the framework for our stock dashboard, including a responsive design and styling.

Chapter 2: Enhancing Your Dashboard

The first video titled "Build Your Own Financial Dashboard with Python" provides a comprehensive overview of creating a financial dashboard, offering insights and techniques to enhance your coding journey.

The second video, "Automating the CLI (Part 2): Building a Simple Web Dashboard with Flask & Bootstrap," delves into automation and the integration of Bootstrap for a more polished web interface.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Guidance from Veronica Speck: Insights for Aspiring Founders

Veronica Speck shares vital lessons learned as a founder, emphasizing intuition, understanding clients, and the importance of balance.

Unlocking the Power of Philosophy for a Better Life

Discover how studying philosophy can enhance your life and happiness.

Discovering the Joyful Wisdom of a 14-Pound Dog

Explore the uplifting lessons of happiness learned from Lila, a 14-pound dog, and understand the importance of embracing joy in our lives.

Navigating TikTok's Privacy Concerns: What You Need to Know

Explore TikTok's data collection practices and privacy concerns, plus tips to safeguard your information while using the app.

# Life Lessons Learned After 40: Insights and Reflections

Discover valuable insights and reflections on life after 40, including lessons on health, relationships, and personal growth.

Healing Old Wounds: Embracing Emotional Freedom

Explore the importance of addressing internal wounds and nurturing emotional well-being.

The Art of Part-Time Writing in a Busy World

Explore five essential guidelines for aspiring part-time writers to navigate their creative journey.

Embracing Growth: Celebrating Your Journey as an Entrepreneur

A reflection on personal growth, embracing where you are, and the importance of self-worth in entrepreneurship.