Career Paths

The Stock Market Analyzer

Learn how to download and visualize financial data from the internet, creating stock price charts with the yfinance and matplotlib libraries.

Our Project: Stock Visualization Tool

We will create a script that allows the user to enter a stock ticker symbol, downloads its historical data for the last year, and generates a closing price chart.

Core Technologies We'll Use:

Python
yfinance
pandas
matplotlib
Step 1 / 4

Step 1: Environment and Library Setup

We prepare our workspace and install the necessary libraries for retrieving and visualizing financial data.

In this path, we will combine data retrieval from the internet with visualization. We will use three powerful libraries.

1. Create Virtual Environment

It's always good practice to start with a clean environment. Open your terminal:

# Create project folder
mkdir stock_analyzer
cd stock_analyzer

# Create and activate virtual environment
python -m venv venv
# For Windows: .\venv\Scripts\activate
# For macOS/Linux: source venv/bin/activate

2. Install Libraries

With the venv activated, we install the libraries:

  • yfinance: A convenient library for downloading historical market data from Yahoo Finance.
  • pandas: yfinance returns data as a Pandas DataFrame, so it's necessary.
  • matplotlib: For creating our charts.
  • requests: We will use it to send more reliable requests.
pip install yfinance pandas matplotlib requests

3. Create File

Create an empty Python file named stock_analyzer.py. This is where we will write all our code.

Step 2 / 4

Step 2: Retrieving Stock Data with yfinance

We write the code to connect to Yahoo Finance, sending a request that looks like a regular browser for greater reliability.

The yfinance library makes the data download process extremely simple. To avoid issues where our request is blocked, we will use the requests library to create a "session" that sends a User-Agent header, making our request look like that of a regular browser.

  1. Create session: We create a session object from the requests library and set the headers.
  2. Create Ticker object: The line yf.Ticker(ticker_symbol, session=session) creates an object representing the stock, using the session we created.
  3. Get history: The .history(period="1y") method downloads the historical data for the last year.

# stock_analyzer.py
import yfinance as yf
import pandas as pd
import requests # Import the requests library

def get_stock_data(ticker_symbol):
    """
    Downloads historical data for a stock for the last year.
    """
    try:
        # We create a session with a User-Agent to avoid being blocked.
        session = requests.Session()
        session.headers['User-agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        
        stock = yf.Ticker(ticker_symbol, session=session)
        
        hist = stock.history(period="1y")
        
        if hist.empty:
            print(f"Error: No data found for symbol '{ticker_symbol}'.")
            return None, None
            
        print(f"Successfully downloaded data for stock '{stock.info.get('longName', ticker_symbol)}'.")
        return hist, stock.info

    except Exception as e:
        print(f"An error occurred: {e}")
        return None, None

if __name__ == '__main__':
    aapl_data, aapl_info = get_stock_data("AAPL")
    if aapl_data is not None:
        print("\n--- First 5 rows of Apple's data ---")
        print(aapl_data.head())
Step 3 / 4

Step 3: Data Visualization with Matplotlib

We use the Matplotlib library to create a line chart showing the stock's closing price over time.

Now that we have our data in a DataFrame, visualization is the next step. We will use Matplotlib to plot the closing price ('Close' column) against the date (which is the DataFrame's index).

  1. plt.figure(figsize=(...)): Creates a new "canvas" for our chart, defining its size.
  2. plt.plot(x, y): The main plotting function. On the X-axis, we put the DataFrame's index (hist.index, which are the dates) and on the Y-axis, the 'Close' column (hist['Close']).
  3. Adding labels and title: We use plt.title(), plt.xlabel(), and plt.ylabel() to make our chart understandable.
  4. plt.show(): Displays the window with the chart.

# (At the beginning of the file): import matplotlib.pyplot as plt
# (We will combine the logic into one function)

def plot_stock_price(ticker_symbol):
    """
    Combines data retrieval and visualization.
    """
    hist, info = get_stock_data(ticker_symbol) # Call the function we made
    
    if hist is None:
        return # If there's no data, we stop
        
    # --- Visualization ---
    plt.style.use('seaborn-v0_8-darkgrid') # A nice style for the charts
    plt.figure(figsize=(12, 6))
    
    plt.plot(hist.index, hist['Close'], label='Closing Price', color='cyan')
    
    plt.title(f"Historical Stock Price: {info.get('longName', ticker_symbol)}")
    plt.xlabel("Date")
    plt.ylabel("Price ($)")
    plt.legend()
    plt.grid(True)
    plt.tight_layout()
    plt.show()

# (We update the __main__ block to call the new function)
if __name__ == '__main__':
    plot_stock_price("MSFT") # Test for Microsoft
Step 4 / 4

Step 4: Interactivity and Improvements

We make our script interactive by asking the user to enter the stock symbol they are interested in.

To make our tool more useful, instead of having a fixed stock symbol in the code, we will ask the user which stock they want to analyze. This is done simply with the input() function.

With this change, the program becomes fully interactive, and the user can analyze any stock they wish by simply entering its symbol in the terminal.


# (Replace the old __main__ block)

if __name__ == '__main__':
    symbol = input("Enter a stock symbol (e.g., GOOGL, AAPL, MSFT): ")
    
    # Check if the user provided any input
    if symbol:
        # Convert to uppercase for compatibility
        plot_stock_price(symbol.upper())
    else:
        print("No symbol entered. Running example for Apple (AAPL).")
        plot_stock_price("AAPL")

Project Completion & Next Steps

Congratulations! You have completed the path and now have the full code for the project.

This is the final, complete code for the application. You can copy it, run it locally on your computer (after installing the necessary libraries with `pip`), and experiment by adding your own features!


# stock_analyzer.py
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd
import requests

def plot_stock_price(ticker_symbol):
    """
    Κατεβάζει τα δεδομένα μιας μετοχής και σχεδιάζει την τιμή κλεισίματος.
    """
    try:
        # Δημιουργία session με user-agent για να μοιάζει με browser
        session = requests.Session()
        session.headers['User-agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        
        stock = yf.Ticker(ticker_symbol, session=session)
        
        # Λήψη ιστορικών δεδομένων για τον τελευταίο χρόνο ('1y')
        hist = stock.history(period="1y")
        
        if hist.empty:
            print(f"Σφάλμα: Δεν βρέθηκαν δεδομένα για το σύμβολο '{ticker_symbol}'. Ελέγξτε το ticker.")
            return
            
        print(f"Λήφθηκαν δεδομένα για την {stock.info.get('longName', ticker_symbol)}.")
        
        # --- Οπτικοποίηση με Matplotlib ---
        plt.style.use('seaborn-v0_8-darkgrid')
        plt.figure(figsize=(12, 6))
        
        plt.plot(hist.index, hist['Close'], label='Τιμή Κλεισίματος', color='cyan')
        
        plt.title(f"Ιστορική Τιμή Μετοχής: {stock.info.get('longName', ticker_symbol)}")
        plt.xlabel("Ημερομηνία")
        plt.ylabel("Τιμή ($)")
        plt.legend()
        plt.grid(True)
        plt.tight_layout()
        plt.show()

    except Exception as e:
        print(f"Προέκυψε ένα απρόσμενο σφάλμα: {e}")

if __name__ == '__main__':
    # Ζητάμε από τον χρήστη το σύμβολο της μετοχής
    symbol = input("Εισάγετε το σύμβολο μιας μετοχής (π.χ., GOOGL, AAPL, MSFT): ")
    if symbol:
        plot_stock_price(symbol.upper())
    else:
        print("Δεν δόθηκε σύμβολο. Εκτελείται παράδειγμα για την Apple (AAPL).")
        plot_stock_price("AAPL")