Building an Automated Stock Analysis Dashboard with Streamlit, Yahoo Finance, and NewsAPI: Real-time Data-driven Investment Strategy

Tired of manual stock analysis? This guide introduces how to build an automated stock analysis dashboard based on real-time data by combining Streamlit, Yahoo Finance, and NewsAPI. This dashboard will help you make informed investment decisions and efficiently grasp market trends.

1. The Challenge / Context

The stock market is constantly changing, and successful investing requires rapid analysis and interpretation of vast amounts of data. Traditional stock analysis methods are time-consuming and pose challenges in collecting and integrating data from multiple sources. Especially for individual investors or small teams, limited access to advanced analytical tools makes it difficult to build real-time data-driven investment strategies. This can lead to missed investment opportunities or losses due to lack of information.

2. Deep Dive: Streamlit, Yahoo Finance, NewsAPI

This solution leverages three core technologies:

  • Streamlit: A Python-based web application framework that provides data visualization and analysis results through a user-friendly interface. Its advantage is the ability to quickly build dashboards without complex web development knowledge.
  • Yahoo Finance API (yfinance library): Provides various stock-related data such as historical stock prices, current stock prices, trading volumes, and dividend information. It is free to use and allows easy data retrieval through simple API calls.
  • NewsAPI: An API that provides news articles from around the world. It collects real-time economic news, corporate news, and political news that affect the stock market, providing crucial information for investment decisions.

Combining these three technologies allows you to build a powerful stock analysis dashboard that visually integrates real-time stock price data, relevant news articles, and technical indicators. Streamlit forms the frontend of the dashboard, the Yahoo Finance API fetches stock price data, and NewsAPI provides relevant news articles.

3. Step-by-Step Guide / Implementation

Here is a step-by-step guide to building an automated stock analysis dashboard using Streamlit, Yahoo Finance, and NewsAPI.

Step 1: Install Required Libraries

First, install the necessary Python libraries. Run the following command in your terminal or Anaconda Prompt:

pip install streamlit yfinance newsapi-python

Step 2: API Key Setup (NewsAPI)

To use NewsAPI, you need an API key. Create a free account on the NewsAPI website and obtain an API key. Store the issued API key in an environment variable or enter it directly into your code. Here's how to store it in an environment variable:

import os
os.environ["NEWSAPI_KEY"] = "YOUR_NEWSAPI_KEY" # Replace YOUR_NEWSAPI_KEY with your actual API key

Step 3: Write Streamlit Application Code

Below is the basic code for the Streamlit application. This code fetches stock price data from Yahoo Finance and relevant news articles from NewsAPI, then displays them on the dashboard.

import streamlit as st
import yfinance as yf
from newsapi import NewsApiClient
import os
import pandas as pd
import plotly.graph_objects as go

# NewsAPI 키 설정
newsapi_key = os.environ.get("NEWSAPI_KEY")
if not newsapi_key:
    st.error("NewsAPI 키가 설정되지 않았습니다. 환경 변수에 NEWSAPI_KEY를 설정하세요.")
    st.stop()

newsapi = NewsApiClient(api_key=newsapi_key)

# 주식 티커 입력 받기
ticker = st.text_input("주식 티커를 입력하세요 (예: AAPL, MSFT, TSLA)", "AAPL")

# 주가 데이터 가져오기
try:
    data = yf.Ticker(ticker)
    hist = data.history(period="1y")  # 1년치 주가 데이터 가져오기
    st.subheader(f"{ticker} 주가 데이터 (1년)")

    # Plotly를 사용한 캔들스틱 차트
    fig = go.Figure(data=[go.Candlestick(x=hist.index,
                                          open=hist['Open'],
                                          high=hist['High'],
                                          low=hist['Low'],
                                          close=hist['Close'])])
    fig.update_layout(xaxis_rangeslider_visible=False, title=f"{ticker} 캔들스틱 차트")
    st.plotly_chart(fig)

    # 최근 5일 종가 데이터 표시
    st.write("최근 5일 종가:")
    st.dataframe(hist['Close'].tail())

except Exception as e:
    st.error(f"주가 데이터를 가져오는 데 실패했습니다: {e}")
    st.stop()


# 뉴스 기사 가져오기
try:
    top_headlines = newsapi.get_everything(q=ticker,
                                          language='ko',
                                          sort_by='relevancy')

    articles = top_headlines['articles']

    st.subheader(f"{ticker} 관련 최신 뉴스")
    if articles:
        for i, article in enumerate(articles):
            st.write(f"**{i+1}. {article['title']}**")
            st.write(f"Source: {article['source']['name']}")
            st.write(article['description'])
            st.write(f"[Read more]({article['url']})")
            st.write("---")
    else:
        st.write("관련 뉴스가 없습니다.")

except Exception as e:
    st.error(f"뉴스 기사를 가져오는 데 실패했습니다: {e}")
    st.stop()

Step 4: Run Streamlit Application

Save the Python file you wrote and run the Streamlit application by executing the following command in your terminal or Anaconda Prompt:

streamlit run your_file_name.py # Replace your_file_name.py with your actual file name

A web browser will automatically open, displaying the dashboard. When you enter a stock ticker, the stock's price data and related news articles will be displayed.

Step 5: Implement Additional Features (Optional)

Here are some features you can add to your dashboard:

  • Display Technical Indicators: Calculate and display technical indicators such as moving averages, MACD, and RSI alongside the stock price chart. You can use data provided by the yfinance library or technical analysis libraries like ta-lib.
  • Investment Strategy Simulation: Simulate the performance of various investment strategies using historical stock price data. For example, you can calculate the return of a strategy that buys when a specific moving average is crossed upwards and sells when another moving average is crossed downwards.
  • Sentiment Analysis: Analyze the content of news articles or social media posts to gauge investment sentiment for a particular stock. You can use sentiment analysis libraries like VADER Sentiment Analysis.
  • Notification Feature: Implement a feature to send email or SMS notifications when specific stock price conditions are met or important news articles are published.

4. Real-world Use Case / Example

As an individual investor, I use this dashboard every morning for 30 minutes to grasp stock market trends. In the past, it took me over an hour to visit multiple websites to collect and analyze stock price data and news articles. However, after building this dashboard, I can get the necessary information at a glance, saving time and enabling me to make better investment decisions. In particular, I was able to quickly respond to negative news related to specific stocks, minimizing losses.

5. Pros & Cons / Critical Analysis

  • Pros:
    • Automated Data Collection and Analysis: Automatically collects and analyzes real-time data through Yahoo Finance and NewsAPI, saving time and effort.
    • User-Friendly Interface: Streamlit allows you to build user-friendly dashboards without complex web development knowledge.
    • Customized Investment Strategies: You can develop your own customized investment strategies by adding various features such as technical indicators, sentiment analysis, and investment strategy simulations.
  • Cons:
    • Data Quality: The accuracy and reliability of data provided by Yahoo Finance and NewsAPI cannot be guaranteed. Data errors or delays may occur, which could lead to incorrect investment decisions.
    • API Usage Limits: While Yahoo Finance and NewsAPI offer free APIs, they have usage limits. Requesting large amounts of data or frequently calling the API may result in usage restrictions.
    • Technical Dependency: The dashboard is dependent on external libraries and APIs such as Streamlit, Yahoo Finance, and NewsAPI. Changes or discontinuation of these technologies could impair the dashboard's functionality.

6. FAQ

  • Q: Where can I get a NewsAPI key?
    A: You can create a free account and get an API key on the NewsAPI website (newsapi.org).
  • Q: How do I deploy a Streamlit dashboard to the web?
    A: You can deploy your Streamlit dashboard to the web using various platforms such as Streamlit Cloud, Heroku, or AWS. Streamlit Cloud is the simplest way to deploy Streamlit applications.
  • Q: Can I get stock data from other sources?
    A: Of course. You can use other stock data APIs such as Alpha Vantage or IEX Cloud. You will need to familiarize yourself with the usage of those APIs and modify the code accordingly.

7. Conclusion

Building an automated stock analysis dashboard using Streamlit, Yahoo Finance, and NewsAPI is a highly effective way to make informed investment decisions. Utilize the step-by-step instructions and code provided in this guide to build your own dashboard and develop real-time data-driven investment strategies. Copy and run the code now to maximize your investment efficiency!