HomeAPIFinancial Dashboard Using Streamlit and Alpha Vantage API – 2

Financial Dashboard Using Streamlit and Alpha Vantage API – 2

In this project, we build an interactive financial dashboard using Python, Streamlit, and the Alpha Vantage API. The application allows users to enter a stock ticker symbol and instantly view important financial metrics, company fundamentals, and currency exchange rates through a clean web-based interface.

The project is intentionally kept simple and consists of only two Python files.

financial-dashboard/
│
├── app.py
├── data.py

Project Overview

The dashboard retrieves real-time financial information from Alpha Vantage and presents it in an easy-to-understand format. Users simply enter their API key and a stock symbol (such as AAPL, MSFT, or TSLA) and click Load Data to generate the dashboard.

The application displays key financial indicators including:

  • Current stock price
  • Market capitalization
  • P/E Ratio
  • Earnings Per Share (EPS)
  • Dividend Yield
  • 52-week high and low prices
  • USD to INR exchange rate
  • USD to JOD exchange rate

The dashboard is designed for finance students, analysts, investors, and anyone interested in exploring company fundamentals through Python.

Technologies Used

  • Python
  • Streamlit
  • Pandas
  • Requests
  • Alpha Vantage API

How the Project Works

The project consists of two Python files:

app.py

This file creates the Streamlit user interface. It handles:

  • User input for API key and stock ticker
  • Dashboard layout and styling
  • Financial KPI cards
  • Summary data table
  • Error handling and validation

Example:

ticker = st.sidebar.text_input(
    "Ticker Symbol",
    value="AAPL"
)

The dashboard displays financial metrics using Streamlit’s metric components:

st.metric(
    "💲 Current Price",
    safe_price(data.get("current_price"))
)

data.py

This file is responsible for retrieving data from Alpha Vantage APIs.

It makes API calls to obtain:

  • Company overview information
  • Real-time stock quotes
  • Currency exchange rates

Example:

overview_url = (
    "https://www.alphavantage.co/query"
    f"?function=OVERVIEW"
    f"&symbol={ticker}"
    f"&apikey={api_key}"
)

The returned JSON data is processed and converted into a Python dictionary that is later displayed in the dashboard.

Features

  • Interactive financial dashboard
  • Real-time market data
  • Company fundamental analysis
  • Currency conversion rates
  • Clean and responsive Streamlit interface
  • Safe handling of missing data values
  • Financial KPI cards for quick analysis

Application Flow

User Input
     │
     ▼
 app.py
     │
     ▼
 data.py
     │
     ▼
 Alpha Vantage API
     │
     ▼
 Financial Data Returned
     │
     ▼
 Streamlit Dashboard

To run this application:

Assuming you are inside the project directory, run:

python -m streamlit run app.py

Educational Value

This project is an excellent example of combining finance and data science concepts. It demonstrates:

  • Working with REST APIs
  • JSON data processing
  • Financial data visualization
  • Streamlit web application development
  • Building interactive dashboards in Python

Compete code

The code for app.py is:

# app.py

import streamlit as st
import pandas as pd

from data import get_dashboard_data as get_dashboard_data
# from data import get_dashboard_data_test as get_dashboard_data # Use this for testing without API calls

# =====================================================
# SAFE DISPLAY FUNCTIONS
# =====================================================

def safe_text(value):
    """
    Return value as text or N/A
    """
    if value is None or value == "":
        return "N/A"
    return str(value)


def safe_price(value):
    """
    Format currency safely
    """
    try:
        return f"${float(value):,.2f}"
    except:
        return "N/A"


def safe_market_cap(value):
    """
    Convert market cap to trillions safely
    """
    try:
        return f"${float(value)/1e12:.2f} T"
    except:
        return "N/A"




# =====================================================
# PAGE CONFIG
# =====================================================

st.set_page_config(
    page_title="Financial Dashboard",
    page_icon="📈",
    layout="wide"
)


# =====================================================
# CUSTOM CSS
# =====================================================

st.markdown(
    """
    <style>

    .main-title {
        font-size:40px;
        font-weight:bold;
        text-align:center;
        color:#00BFFF;
        margin-bottom:20px;
    }

    .sub-title {
        text-align:center;
        color:gray;
        margin-bottom:30px;
    }

    div[data-testid="metric-container"] {
        background-color: #1e1e1e;
        border: 1px solid #444;
        padding: 15px;
        border-radius: 12px;
        text-align:center;
        box-shadow: 2px 2px 8px rgba(0,0,0,0.2);
    }

    </style>
    """,
    unsafe_allow_html=True
)


# =====================================================
# HEADER
# =====================================================

st.markdown(
    "<div class='main-title'>📈 Financial Dashboard</div>",
    unsafe_allow_html=True
)

st.markdown(
    "<div class='sub-title'>Powered by Alpha Vantage</div>",
    unsafe_allow_html=True
)


# =====================================================
# SIDEBAR
# =====================================================

st.sidebar.header("Configuration")

api_key = st.sidebar.text_input(
    "Alpha Vantage API Key",
    type="password"
)

ticker = st.sidebar.text_input(
    "Ticker Symbol",
    value="AAPL"
)

load_button = st.sidebar.button(
    "Load Data"
)


# =====================================================
# MAIN
# =====================================================

if load_button:

    if not api_key:

        st.warning("Please enter an API key.")
        st.stop()

    with st.spinner("Fetching data..."):

        try:

            data = get_dashboard_data(
                api_key=api_key,
                ticker=ticker.upper()
            )

            st.success("Data Loaded Successfully")

            # ======================================
            # ROW 1
            # ======================================

            col1, col2, col3 = st.columns(3)

            with col1:
                st.metric(
                    "💲 Current Price",
                    safe_price(data.get("current_price"))
                )

            with col2:
                st.metric(
                    "📊 P/E Ratio",
                    safe_text(data.get("pe_ratio"))
                )

            with col3:
                st.metric(
                    "💰 EPS",
                    safe_text(data.get("eps"))
                )

            st.markdown("---")

            # ======================================
            # ROW 2
            # ======================================

            col1, col2, col3 = st.columns(3)

            with col1:
                st.metric(
                    "🏦 Market Cap",
                    safe_market_cap(data.get("market_cap"))
                )
                            
            
            with col2:
                st.metric(
                    "📈 52 Week High",
                    safe_text(data.get("52_week_high"))
                )

            with col3:
                st.metric(
                    "📉 52 Week Low",
                    safe_text(data.get("52_week_low"))
                )

            st.markdown("---")

            # ======================================
            # ROW 3
            # ======================================

            col1, col2, col3 = st.columns(3)

            with col1:
                st.metric(
                    "🎁 Dividend Yield",
                    safe_text(data.get("dividend_yield"))
                )

            with col2:
                st.metric(
                    "🇮🇳 USD → INR",
                    safe_text(data.get("usd_inr"))
                )

            with col3:
                st.metric(
                    "🇯🇴 USD → JOD",
                    safe_text(data.get("usd_jod"))
                )

            st.markdown("---")

            # ======================================
            # SUMMARY TABLE
            # ======================================

            st.subheader("Company Snapshot")

            summary_df = pd.DataFrame(
                {
                    "Metric": [
                        "Ticker",
                        "Current Price",
                        "Market Cap",
                        "PE Ratio",
                        "EPS",
                        "Dividend Yield",
                        "52 Week High",
                        "52 Week Low",
                        "USD -> INR",
                        "USD -> JOD",
                    ],
                    "Value": [
                        data["ticker"],
                        data["current_price"],
                        data["market_cap"],
                        data["pe_ratio"],
                        data["eps"],
                        data["dividend_yield"],
                        data["52_week_high"],
                        data["52_week_low"],
                        data["usd_inr"],
                        data["usd_jod"],
                    ]
                }
            )

            st.dataframe(
                summary_df,
                use_container_width=True
            )

            # ======================================
            # DASHBOARD FOOTER
            # ======================================

            st.markdown("---")

            st.info(
                f"""
                Ticker: {ticker.upper()}

                Dashboard generated using Alpha Vantage APIs.

                Demonstrates:
                - Financial Fundamentals
                - Market Data
                - Currency Exchange Rates
                - Streamlit KPI Cards
                """
            )

        except Exception as e:

            st.error(f"Error: {e}")

else:

    st.info(
        "Enter your Alpha Vantage API key and a ticker symbol in the sidebar, then click 'Load Data'."
    )

The code for data.py is:

# data.py

import requests

def get_dashboard_data(api_key: str, ticker: str) -> dict:
    """
    Returns all dashboard data as a dictionary.
    """

    result = {}

    # ==========================================
    # COMPANY OVERVIEW
    # ==========================================

    overview_url = (
        "https://www.alphavantage.co/query"
        f"?function=OVERVIEW"
        f"&symbol={ticker}"
        f"&apikey={api_key}"
    )

    overview = requests.get(overview_url).json()

    # ==========================================
    # GLOBAL QUOTE
    # ==========================================

    quote_url = (
        "https://www.alphavantage.co/query"
        f"?function=GLOBAL_QUOTE"
        f"&symbol={ticker}"
        f"&apikey={api_key}"
    )

    quote = requests.get(quote_url).json()

    quote_data = quote.get("Global Quote", {})

    # ==========================================
    # USD -> INR
    # ==========================================

    inr_url = (
        "https://www.alphavantage.co/query"
        "?function=CURRENCY_EXCHANGE_RATE"
        "&from_currency=USD"
        "&to_currency=INR"
        f"&apikey={api_key}"
    )

    inr_data = requests.get(inr_url).json()

    # ==========================================
    # USD -> JOD
    # ==========================================

    jod_url = (
        "https://www.alphavantage.co/query"
        "?function=CURRENCY_EXCHANGE_RATE"
        "&from_currency=USD"
        "&to_currency=JOD"
        f"&apikey={api_key}"
    )

    jod_data = requests.get(jod_url).json()

    # ==========================================
    # BUILD DICTIONARY
    # ==========================================

    result = {
        "ticker": ticker,

        "current_price":
            quote_data.get("05. price"),

        "market_cap":
            overview.get("MarketCapitalization"),

        "pe_ratio":
            overview.get("PERatio"),

        "eps":
            overview.get("EPS"),

        "dividend_yield":
            overview.get("DividendYield"),

        "52_week_high":
            overview.get("52WeekHigh"),

        "52_week_low":
            overview.get("52WeekLow"),

        "usd_inr":
                inr_data.get(
                    "Realtime Currency Exchange Rate",
                    {}
                ).get("5. Exchange Rate"),

        "usd_jod":
                jod_data.get(
                    "Realtime Currency Exchange Rate",
                    {}
                ).get("5. Exchange Rate"),
    }

    return result

def get_dashboard_data_test(api_key: str, ticker: str) -> dict:
    data = {'ticker': 'AAPL',
            'current_price': None,
            'market_cap': '4629454651000',
            'pe_ratio': '38.16',
            'eps': '8.26',
            'dividend_yield': '0.0034',
            '52_week_high': '315.45',
            '52_week_low': '194.3',
            'usd_inr': '95.69577565',
            'usd_jod': None
    }
    
    return data
    
    
if __name__ == "__main__":
    import os

    # api_key = os.getenv("ALPHA_VANTAGE_API_KEY")
    api_key = ""
    ticker = "AAPL"
    data = get_dashboard_data(api_key, ticker)
    print(data)
    

Conclusion

The Financial Dashboard project provides a practical introduction to financial analytics using Python. By integrating Alpha Vantage APIs with Streamlit, the application delivers real-time stock market insights in a user-friendly interface. It serves as a strong beginner-t

Share: 

No comments yet! You be the first to comment.

Leave a Comment

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