Stock Market Analysis with Python
Pull real stock data and build a financial analysis dashboard.
Introduction
30 Second Summary
Stock prices are everywhere, from news headlines to phone notifications. But knowing a stock went up or down today tells you almost nothing about whether it is actually performing well.
In this project, you will build a Python script that pulls real Apple stock data and produces a professional analysis dashboard. You will calculate moving averages, daily returns, and rolling volatility to reveal the trends hidden in raw price data.
What You'll Build
Run your script once, and a multi-panel chart appears showing exactly how a stock has performed, where its trends shifted, and how risky it has been over time.
By the end of this project, you'll have:
- A working Python script that downloads live stock data and produces a complete financial analysis with one command.
- 20-day and 50-day moving average overlays on the real price chart, revealing whether a stock is trending up or down at any given moment.
- A multi-panel dashboard combining price trends, daily returns, and rolling volatility into a single publication-quality image you can save and share.
- Secret Mission: Compare two stocks side-by-side and calculate which delivers better risk-adjusted returns using the Sharpe Ratio.
Are there any prerequisites?
None. This guide includes full setup instructions for Python, VS Code, and every library you need. You do not need any prior Python experience to complete this project.
Before We Start
Before writing any code, let's get clear on what you're building and why.
This step locks in the stock you'll analyse and the question your dashboard will answer.
Set Up Your Python Environment
Every data science project starts with two essentials: a programming language and a code editor. Python is the industry standard for financial analysis, and VS Code is a professional editor that makes writing Python straightforward.
In this step, you'll install both tools and confirm they work together. Getting this right now means you won't debug setup issues when you're deep in stock data later.
In this step, get ready to:
- Install Python on your machine.
- Install VS Code with the Python extension.
- Confirm Python runs from your terminal.
Install Python
Python is the programming language you'll use to pull stock data and crunch financial numbers. You need to install it on your machine before you can write any code.
- Open your browser and go to https://www.python.org/downloads/.
- Click the large yellow download button for Windows.
- Once the file downloads, double-click it to run the installer.
- At the bottom of the first installer screen, check the box that says Add python.exe to PATH.
- Click Install Now.
- Wait for the installation to complete, then click Close.
Why does Add python.exe to PATH matter?
This checkbox lets your terminal find Python no matter which folder you're working in. Without it, your computer won't know where Python lives, and every command you try will fail.
If you accidentally skip this checkbox, you'll need to uninstall and reinstall Python with the box checked.
Install VS Code and the Python extension
VS Code is the editor where you'll write and run your Python scripts. A dedicated extension adds features like syntax highlighting and error detection for Python files.
- Open your browser and go to https://code.visualstudio.com/.
- Click the download button for Windows.
- Run the downloaded installer and accept the defaults.
- Once installation finishes, press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
- Type Visual Studio Code and press Enter to open it.
VS Code opens with a Welcome tab. Now install the Python extension.
- Click the Extensions icon in the left sidebar (it looks like four small squares).
- Type Python in the search bar at the top of the panel.
- Find the extension named Python by Microsoft (it should be the first result).
- Click Install.
What does the Python extension do?
It adds code highlighting, error detection, and a built-in way to run Python files directly from VS Code. Without it, VS Code treats your Python files as plain text.
Confirm Python works in your terminal
The terminal inside VS Code is where you'll run all your Python scripts. Confirming Python works here proves that your installation, PATH setting, and editor are all connected.
- In VS Code, click Terminal in the top menu bar.
- Click New Terminal.
A terminal panel appears at the bottom of VS Code. Before you run the next command, what do you expect to see if Python was installed correctly?
- Confirm Python is installed by running this command:
python --version
✔️ I see a version number
You see something like Python 3.x.x printed in the terminal. The exact version number does not matter for this project. Python is installed and your PATH is working correctly.
ⓧ Python isn't recognized or the Microsoft Store opened
This means your terminal cannot find the Python installation. Try these fixes in order.
- Close VS Code completely and reopen it. The terminal needs to reload your system PATH after a fresh install.
- If the Microsoft Store opened instead, close it. Open Windows Settings, search for Manage app execution aliases, and turn off the entries for App Installer - python.exe and App Installer - python3.exe. Then try the command again.
- If neither fix works, uninstall Python from Settings > Apps > Installed apps, then reinstall it from python.org. Make sure to check Add python.exe to PATH before clicking Install Now.
After fixing, close and reopen VS Code, open a new terminal, and run python --version again.
Still not working?
If you've tried all the fixes above and still can't get a version number, help me troubleshoot why Python isn't recognized in my VS Code terminal on Windows.
Your environment is locked in. Next up, you'll use Python to pull real Apple stock data from the internet and see it land in your terminal as a structured table.
Download Real Stock Data
Your Python environment is ready. Now you need the raw material for your analysis: real financial data.
In this step, you will install three data science libraries, connect to Yahoo Finance, and pull actual Apple stock prices straight into your terminal. Seeing real market data appear on your screen is your first proof that Python can do the heavy lifting.
In this step, get ready to:
- Install pandas, matplotlib, and yfinance.
- Download real AAPL stock data from Yahoo Finance.
- Display the data as a structured table in the terminal.
Install the data science libraries
Python on its own does not know how to download stock data or draw charts. You need three libraries that give Python those superpowers.
- Create a project folder on your Desktop by running these commands in your VS Code terminal:
cd ~/Desktop
mkdir stock-analysis
cd stock-analysis
- Confirm the folder exists by running:
ls
You should see the folder is empty (no output). That is expected.
- Install the three libraries by running this command:
pip install pandas matplotlib yfinance
You should see download progress bars followed by a "Successfully installed" message listing all three packages and their dependencies.
What are these libraries?
pandas organises data into tables (called DataFrames) so you can filter, calculate, and summarise numbers easily.
matplotlib draws charts and graphs. yfinance connects to Yahoo Finance and downloads real stock market data with no API key required.
Seeing 'pip is not recognized'?
This means Python was not added to your system PATH during installation. Close VS Code completely, reopen it, and try again. If it still fails, reinstall Python and make sure you check the "Add python.exe to PATH" box on the first installer screen.
Help me fix pip not being recognized on Windows.
Pull live stock data from Yahoo Finance
With your libraries installed, you can now write a script that reaches out to Yahoo Finance and downloads real Apple (AAPL) stock prices.
- In VS Code, click File in the top menu bar.
- Click Open Folder.
- Navigate to your Desktop, select the stock-analysis folder, and click Select Folder.
- If VS Code asks whether you trust the authors of this folder, click Yes, I trust the authors.
- Open a new terminal by clicking Terminal in the top menu bar, then New Terminal.
- In the Explorer sidebar on the left, hover over the folder name and click the new file icon (a page with a "+" symbol).
- Type stock_analysis.py and press Enter to create the file.
The file opens in the editor. This is where all your analysis code will live.
- Copy the following code into stock_analysis.py:
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
# Download stock data
ticker = "AAPL"
data = yf.download(ticker, start="2023-01-01", end="2024-12-31")
# Handle multi-level columns if present (depends on yfinance version)
if isinstance(data.columns, pd.MultiIndex):
data.columns = data.columns.droplevel(1)
What does this code do?
- The three import lines load the libraries you just installed so your script can use them.
- yf.download() reaches out to Yahoo Finance and pulls AAPL price data for 2023 through 2024.
- The MultiIndex check is a defensive fix. Some versions of yfinance return columns with extra nesting. This line flattens them so the rest of your code works the same regardless of which version got installed.
- Save the file by pressing Ctrl+S.
- Run the script by entering this command in your terminal:
python stock_analysis.py
You should see a download progress indicator as yfinance fetches the data from Yahoo Finance. The script then finishes without printing anything else. That is expected for now.
Seeing a ModuleNotFoundError?
This means the terminal cannot find the libraries you installed. Make sure your terminal is in the stock-analysis folder and that you ran pip install pandas matplotlib yfinance successfully earlier. Try running the install command again.
Help me fix ModuleNotFoundError in my Python script.
Display your stock data in the terminal
The data is downloading, but you cannot see it yet. Adding a few print statements turns invisible data into a structured table you can read.
- In stock_analysis.py, add the following code at the bottom of the file, below the MultiIndex handling block:
# Display basic info
print(f"Stock: {ticker}")
print(f"Data points: {len(data)}")
print(data.head(10))
print("\n--- Summary Statistics ---")
print(data.describe())
What does this code do?
- data.head(10) prints the first 10 rows of stock data as a table. Each row is one trading day with columns for Open, High, Low, Close, and Volume.
- data.describe() generates summary statistics (mean, min, max, standard deviation) across all columns. This gives you a quick snapshot of the stock's price range and trading volume.
- Save stock_analysis.py by pressing Ctrl+S.
Before you run this, what do you think the output will look like? Will it be a wall of numbers, or something more structured?
- Run the script again by entering this command in your terminal:
python stock_analysis.py
You should see a neatly formatted table of AAPL stock data with columns for Open, High, Low, Close, and Volume. Below that, a summary statistics section shows the mean, min, max, and standard deviation for each column.
What is a DataFrame?
The table you see is a DataFrame. Think of it as a spreadsheet inside Python. Each row is a trading day. Each column is a measurement (opening price, closing price, volume traded).
Everything you do in this project (calculating averages, measuring volatility, building charts) starts from this DataFrame.
Seeing an empty table or connection error?
Make sure you are connected to the internet. yfinance needs a live connection to reach Yahoo Finance. If you see a table with zero rows, double check that the ticker is spelled "AAPL" (all caps) and the dates are formatted exactly as shown.
Help me debug why my yfinance download returns no data.
✔️ Awesome, I've got everything!
Great. Double check you have saved stock_analysis.py and that your terminal shows the stock data table when you run it.
ⓧ I'd like to double check the full code
Here is the complete stock_analysis.py file so far. Make sure yours matches exactly:
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
# Download stock data
ticker = "AAPL"
data = yf.download(ticker, start="2023-01-01", end="2024-12-31")
# Handle multi-level columns if present (depends on yfinance version)
if isinstance(data.columns, pd.MultiIndex):
data.columns = data.columns.droplevel(1)
# Display basic info
print(f"Stock: {ticker}")
print(f"Data points: {len(data)}")
print(data.head(10))
print("\n--- Summary Statistics ---")
print(data.describe())
You have real Apple stock data flowing into Python. Next up, you will turn those numbers into a visual chart so you can actually see the stock's journey over time.
Plot the Stock Price
You have real Apple stock data printing to your terminal. That proves the download works, but a wall of numbers does not tell a story.
A line chart reveals patterns that raw numbers hide. In this step, you will plot the closing price over time to visualize AAPL's journey. Pay attention to whether you can easily identify trends from the chart alone.
In this step, get ready to:
- Add a matplotlib line chart of AAPL's closing price over time.
- Run the script and observe what the raw price reveals (and what it hides).
Add a line chart of the closing price
Your script already imports matplotlib but does not use it yet. You will add a chart that plots the closing price for every trading day in the dataset.
- In stock_analysis.py, scroll to the bottom of the file. Find this line:
print(data.describe())
- Add the following code below that line to create a line chart:
# Plot closing price
plt.figure(figsize=(12, 5))
plt.plot(data.index, data["Close"], label="Close Price", linewidth=1, color="black")
plt.title(f"{ticker} Closing Price")
plt.xlabel("Date")
plt.ylabel("Price ($)")
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
What does this code do?
- plt.figure(figsize=(12, 5)) creates a wide chart canvas (12 inches by 5 inches) so the price history is easy to read.
- plt.plot(data.index, data["Close"]) draws a line using dates on the x-axis and closing prices on the y-axis.
- plt.grid(True, alpha=0.3) adds a subtle grid to make price levels easier to judge by eye.
- plt.show() opens an interactive window displaying the chart.
Run the script and observe the chart
Before you run the script, think about this: with two years of daily closing prices plotted as a single line, do you think you will be able to clearly tell when the stock is trending up versus down?
- Save stock_analysis.py.
- Run the script by entering this command in your VS Code terminal:
python stock_analysis.py
A chart window opens showing AAPL's closing price from January 2023 through December 2024. You can see the general shape of the stock's journey.
Now look more closely. Can you pinpoint exactly when the stock shifted from a downtrend to an uptrend? Probably not. The day-to-day noise makes it difficult to identify clear trends or assess whether the stock is getting riskier. That is the limitation of raw price data.
Why is raw price hard to read?
Stock prices bounce around daily due to news, earnings reports, and market sentiment. These small fluctuations obscure the bigger picture. Professional analysts use smoothing techniques (like moving averages) to separate the signal from the noise.
You will add those techniques in the next step.
Chart window not appearing?
- Make sure you saved stock_analysis.py before running the command.
- Check that plt.show() is the last line in your script. If other code runs after it, the window may close immediately.
- On some systems, the chart window opens behind VS Code. Check your taskbar for a new window.
help me figure out why my matplotlib chart is not appearing
✔️ Awesome, I've got everything!
Great. Double check you have saved your file.
ⓧ I'd like to double check the full code
Here is what your complete stock_analysis.py should look like at this point:
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
# Download stock data
ticker = "AAPL"
data = yf.download(ticker, start="2023-01-01", end="2024-12-31")
# Handle multi-level columns if present (depends on yfinance version)
if isinstance(data.columns, pd.MultiIndex):
data.columns = data.columns.droplevel(1)
# Display basic info
print(f"Stock: {ticker}")
print(f"Data points: {len(data)}")
print(data.head(10))
print("\n--- Summary Statistics ---")
print(data.describe())
# Plot closing price
plt.figure(figsize=(12, 5))
plt.plot(data.index, data["Close"], label="Close Price", linewidth=1, color="black")
plt.title(f"{ticker} Closing Price")
plt.xlabel("Date")
plt.ylabel("Price ($)")
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
You have a working chart that visualizes real stock data. But you also experienced its biggest limitation: raw price is noisy and hides the underlying trend. Next up, you will add financial indicators that cut through the noise and reveal what the price is actually doing.
Reveal Trends with Financial Indicators
In the last step, you saw the raw closing price chart. It shows the general shape of AAPL's journey, but the day-to-day noise makes it hard to tell whether the stock is trending up or down at any given moment.
Financial analysts solve this with moving averages: smoothed lines that average out recent prices to reveal the underlying trend. In this step, you will calculate these indicators and overlay them on your chart so the trend pops out immediately.
In this step, get ready to:
- Calculate moving averages, daily returns, and volatility for AAPL stock data.
- Update the chart to overlay moving average lines on the raw price.
- Identify trends that were invisible in the raw price chart.
Calculate financial indicators
A moving average takes the mean of the last N days of prices, creating a smooth line that filters out daily noise. A short window (20 days) reacts quickly. A long window (50 days) shows the bigger trend.
- In stock_analysis.py, find the line that says print(data.describe()) near the bottom of the "Display basic info" section.
- Below that line, add the following code to calculate four financial metrics:
# Calculate financial metrics
data["Daily_Return"] = data["Close"].pct_change()
data["MA_20"] = data["Close"].rolling(window=20).mean()
data["MA_50"] = data["Close"].rolling(window=50).mean()
data["Volatility"] = data["Daily_Return"].rolling(window=20).std()
What does this code do?
- pct_change() calculates the percentage change between each day's closing price and the previous day. This gives you the daily return: how much the stock moved in one day.
- .rolling(window=20).mean() averages the last 20 closing prices into a single point. Each day gets its own 20-day average, creating the smooth MA_20 line.
- .rolling(window=50).mean() does the same over 50 days, producing a slower-moving trend line (MA_50).
- .rolling(window=20).std() measures volatility: how wildly the daily returns swing over the last 20 days. Higher volatility means more risk.
- Save stock_analysis.py.
Seeing a KeyError?
Make sure your column name matches exactly: data["Close"] with a capital C. Column names in pandas DataFrames are case-sensitive.
If you see KeyError: 'close', change it to "Close".
help me fix a KeyError in my pandas stock analysis code
Overlay moving averages on the chart
The metrics are calculated, but your chart still shows only the raw closing price. Time to overlay the moving average lines so you can actually see the trends.
- In stock_analysis.py, find the existing plot section that starts with the comment # Plot closing price.
- Replace that entire plot section (from the comment down to plt.show()) with the updated version below:
# Plot closing price with moving averages
plt.figure(figsize=(12, 5))
plt.plot(data.index, data["Close"], label="Close Price", linewidth=1, color="black")
plt.plot(data.index, data["MA_20"], label="20-Day MA", linewidth=1.5, color="blue")
plt.plot(data.index, data["MA_50"], label="50-Day MA", linewidth=1.5, color="orange")
plt.title(f"{ticker} Closing Price with Moving Averages")
plt.xlabel("Date")
plt.ylabel("Price ($)")
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
What changed in the chart code?
- Two new plt.plot() lines draw the 20-day moving average in blue and the 50-day moving average in orange on top of the black price line.
- The title now says "Closing Price with Moving Averages" so you know which version of the chart you are looking at.
- The label parameter on each line feeds into plt.legend(), which draws the colour key in the corner of the chart.
Before you run, predict: what do you think the moving average lines will look like compared to the raw price? Will they be above it, below it, or weaving through it?
- Save stock_analysis.py and run the script:
python stock_analysis.py
A chart window appears with three lines: the black closing price, a blue 20-day moving average, and an orange 50-day moving average. The moving averages weave smoothly through the noisy price, making trends obvious at a glance.
How do I read moving average crossovers?
When the blue 20-day line crosses above the orange 50-day line, the stock is gaining short-term momentum. When it crosses below, momentum is fading.
Look at your chart and find a spot where the blue line crosses the orange. Compare it to the price direction that follows. This is one of the most common signals traders watch.
Chart shows a gap at the start?
The first 20 days of the blue MA line and the first 50 days of the orange MA line will be missing. That is expected. A 50-day average needs 50 data points before it can produce its first value.
If the moving average lines are not appearing at all, check that your metric calculations sit between the print(data.describe()) line and the # Plot closing price with moving averages comment. The columns must exist before the plot tries to use them.
help me debug why my moving average lines are not showing on the matplotlib chart
✔️ Awesome, I've got everything!
Great. Double check you have saved stock_analysis.py and that you can see all three lines on your chart.
ⓧ I'd like to double check the full code
Your stock_analysis.py should have these sections in order. Scroll through your file and confirm each is present:
- The three imports (yfinance, pandas, matplotlib.pyplot).
- The download block (ticker = "AAPL", yf.download(...), multi-level column fix).
- The display block (print(f"Stock: {ticker}") through print(data.describe())).
- The financial metrics block (Daily_Return, MA_20, MA_50, Volatility).
- The updated plot block with three plt.plot() calls (Close in black, MA_20 in blue, MA_50 in orange) and the title "Closing Price with Moving Averages".
Your chart now tells a story the raw price never could. Those smooth lines reveal whether AAPL is trending up or cooling off at any point in time. Next up, you will build a multi-panel dashboard that combines price, returns, and volatility into a single professional analysis view.
Build Your Analysis Dashboard
Your chart now shows moving averages revealing the trends hidden in raw price data. That single chart, though, only tells part of the story.
A professional analyst needs to see price, returns, and risk in one view. In this step, you will build a multi-panel dashboard that combines all three dimensions into the format analysts actually use to brief stakeholders.
In this step, get ready to:
- Restructure the chart into a 3-panel figure showing price, returns, and volatility.
- Save the dashboard as a publication-quality PNG file.
- Print a statistical summary of the stock's performance to the terminal.
Replace the single chart with a multi-panel figure
Right now your script creates one chart with plt.figure(). To show multiple charts stacked vertically, you will switch to plt.subplots(), which creates a figure with multiple panels (called "axes") that share the same x-axis.
- In stock_analysis.py, find the old plotting section that starts with this comment:
# Plot closing price with moving averages
plt.figure(figsize=(12, 5))
- Select everything from that # Plot closing price with moving averages comment all the way down to and including plt.show() at the bottom of the file.
- Delete that entire block and replace it with this new multi-panel dashboard code:
# Build multi-panel analysis dashboard
fig, axes = plt.subplots(3, 1, figsize=(12, 10), sharex=True)
# Panel 1: Price with Moving Averages
axes[0].plot(data.index, data["Close"], label="Close Price", linewidth=1, color="black")
axes[0].plot(data.index, data["MA_20"], label="20-Day MA", linewidth=1.5, color="blue")
axes[0].plot(data.index, data["MA_50"], label="50-Day MA", linewidth=1.5, color="orange")
axes[0].set_title(f"{ticker} Stock Analysis Dashboard")
axes[0].set_ylabel("Price ($)")
axes[0].legend()
axes[0].grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
What does this code do?
- plt.subplots(3, 1) creates a figure with 3 rows and 1 column of panels. sharex=True makes all panels share the same date axis so they stay aligned.
- axes[0] targets the top panel. Instead of calling plt.plot() globally, you now plot to a specific panel using axes[0].plot().
- The top panel plots the same data as before: closing price with 20-day and 50-day moving averages.
- Save stock_analysis.py.
- Run the script by entering this command in your terminal:
python stock_analysis.py
A figure window appears with three stacked panels. The top panel shows your price and moving averages. The bottom two panels are empty for now.
Seeing a syntax error?
- Make sure you deleted ALL of the old plotting code including the plt.show() at the very end. Having two plt.show() calls can cause unexpected behaviour.
- Check that the f-string uses curly braces: f"{ticker} Stock Analysis Dashboard".
Help me fix a matplotlib subplots error in my stock analysis script.
Fill in the daily returns and volatility panels
The two empty panels will show daily returns as a bar chart and rolling volatility as a line. Together with the price panel, these three views give a complete picture of performance and risk.
- In stock_analysis.py, find the plt.tight_layout() line near the bottom of your file.
- Replace everything from plt.tight_layout() down to plt.show() with this code that adds both panels and saves the figure:
# Panel 2: Daily Returns
axes[1].bar(data.index, data["Daily_Return"], color="steelblue", alpha=0.7, width=1)
axes[1].axhline(y=0, color="black", linewidth=0.5)
axes[1].set_ylabel("Daily Return")
axes[1].set_title("Daily Returns")
axes[1].grid(True, alpha=0.3)
# Panel 3: Rolling Volatility
axes[2].plot(data.index, data["Volatility"], color="red", linewidth=1.5)
axes[2].set_ylabel("Volatility")
axes[2].set_title("20-Day Rolling Volatility")
axes[2].set_xlabel("Date")
axes[2].grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("stock_analysis.png", dpi=150, bbox_inches="tight")
plt.show()
What does this code do?
- axes[1].bar() draws daily returns as vertical bars in the middle panel. The zero line (axhline) makes it easy to spot positive vs negative days.
- axes[2].plot() draws rolling volatility as a red line in the bottom panel. Spikes in this line mean the stock had more day-to-day price swings during that period.
- plt.savefig("stock_analysis.png", dpi=150, bbox_inches="tight") saves the chart as a high-resolution PNG image file in your project folder.
- Save stock_analysis.py and run it again:
python stock_analysis.py
A three-panel figure appears. The top panel shows price with moving averages, the middle panel shows daily returns as blue bars above and below a zero line, and the bottom panel shows a red volatility line that spikes during turbulent periods.
- Close the chart window, then confirm the PNG was saved by running:
ls stock_analysis.png
You should see stock_analysis.png listed in the output. This is your publication-quality dashboard file.
Not seeing the PNG file?
- Make sure plt.savefig() comes BEFORE plt.show() in your code. Calling plt.show() first clears the figure, so there is nothing left to save.
- Check that your terminal is in the same folder as stock_analysis.py. The PNG saves to the directory where you run the command.
Help me figure out why plt.savefig is not creating a PNG file.
Print key statistics to the terminal
A chart tells the visual story, but stakeholders also want hard numbers. You will add a summary that prints the most important statistics: how much the stock returned on average, how volatile it was, and its best and worst days.
- At the very bottom of stock_analysis.py (after the plt.show() line), add the following code to print a performance summary:
# Print analysis summary
print(f"\n--- {ticker} Analysis Summary ---")
print(f"Average Daily Return: {data['Daily_Return'].mean():.4f} ({data['Daily_Return'].mean()*100:.2f}%)")
print(f"Average Volatility: {data['Volatility'].mean():.4f}")
print(f"Max Single-Day Gain: {data['Daily_Return'].max():.4f} ({data['Daily_Return'].max()*100:.2f}%)")
print(f"Max Single-Day Loss: {data['Daily_Return'].min():.4f} ({data['Daily_Return'].min()*100:.2f}%)")
total_return = ((data["Close"].iloc[-1] / data["Close"].iloc[0]) - 1) * 100
print(f"Total Return: {total_return:.2f}%")
What do these statistics mean?
- Average Daily Return tells you how much the stock moved on a typical day. A positive value means the stock trended upwards over the period.
- Average Volatility measures how much the stock's daily returns bounced around. Higher volatility means more risk.
- Total Return is the overall percentage gain or loss from the first day to the last day of your data range.
- Save stock_analysis.py.
Before you run the script, what do you expect to see in the terminal after the chart closes? Think about what statistics would appear for a stock that went up over two years.
- Run the script one final time:
python stock_analysis.py
Close the chart window. In your terminal you should see an analysis summary with values for average daily return, average volatility, max single-day gain, max single-day loss, and total return over the period.
Seeing a KeyError or missing data?
- Make sure the column names in the print statements match exactly: Daily_Return and Volatility (capital letters, underscore). These must match the column names you created earlier in the script.
- If you see nan for some values, that is normal. Rolling calculations produce empty values for the first few rows because they need a full window of data to compute.
Help me fix an error in my analysis summary print statements.
✔️ Awesome, I've got everything!
Great. Double check you have saved stock_analysis.py and that stock_analysis.png exists in your project folder.
ⓧ I'd like to double check the full code
Your file is longer than 30 lines now, so scroll through and confirm these sections appear in order:
- Imports (yfinance, pandas, matplotlib).
- Download stock data section with yf.download() and multi-level column handling.
- Display basic info section with print statements and data.describe().
- Calculate financial metrics section (Daily_Return, MA_20, MA_50, Volatility).
- Build multi-panel analysis dashboard with plt.subplots(3, 1) and all three panels filled.
- plt.savefig("stock_analysis.png", dpi=150, bbox_inches="tight") before plt.show().
- Print analysis summary section at the very end with all five statistics.
You now have a complete stock analysis tool. One script pulls live data, calculates the indicators analysts care about, and produces a dashboard you could hand to a stakeholder. You have also learned the exact workflow finance data scientists follow every day: pull data, compute metrics, visualise, summarise.
Secret mission
Compare Stocks with the Sharpe Ratio
Analysing one stock is useful, but portfolio managers compare multiple stocks on risk-adjusted returns. Can you refactor your script to download a second stock, calculate the Sharpe Ratio for both, and build a side-by-side comparison dashboard that reveals which stock gives you more return per unit of risk?
Clean Up Your Resources
Clean Up Your Resources
Decide whether to keep your resources running, pause them to come back later, or delete them entirely. This project runs entirely locally, so there are no ongoing costs.
Resources you used:
- stock_analysis.py (your Python analysis script).
- stock_analysis.png and stock_comparison.png (generated chart images).
- Python packages: pandas, matplotlib, yfinance.
- Python (installed via python.org).
- VS Code (installed via code.visualstudio.com).
Keep everything running
No action needed. Choose this if you plan to keep experimenting with your stock analysis script or want to try analysing different tickers.
- Your stock_analysis.py script stays on your machine, ready to run anytime.
- Python, VS Code, and the installed packages remain available for future projects.
- No storage or compute costs apply since everything is local.
Pause - I'll come back to this later
Since this project is entirely local, there is nothing to pause. Your files and installed tools sit idle with no ongoing resource usage.
- Your script and images remain in your project folder until you return.
- Python and VS Code stay installed but consume no resources when not actively running.
Delete - I don't want to use this again
Remove all project files and optionally uninstall the tools you set up.
- Delete your project files by running this in the VS Code terminal from the folder containing your script:
- On Windows:
del stock_analysis.py stock_analysis.png stock_comparison.png
- On macOS/Linux:
rm stock_analysis.py stock_analysis.png stock_comparison.png
- Uninstall the Python packages by running:
pip uninstall pandas matplotlib yfinance -y
- To uninstall Python: open Settings, select Apps, then Installed apps. Search for Python, click the three-dot menu, and select Uninstall.
- To uninstall VS Code: in the same Installed apps page, search for Visual Studio Code, click the three-dot menu, and select Uninstall.
Nice Work!
Nice Work!
You just built a stock market analysis tool from scratch. Starting with zero Python experience, you now have a script that pulls live financial data, computes the indicators analysts use daily, and produces a professional dashboard you can show off.
Here's what you accomplished:
- Pulled real stock market data programmatically using yfinance and calculated financial indicators that analysts rely on: moving averages, daily returns, and rolling volatility.
- Built a multi-panel analysis dashboard with matplotlib that tells a visual story about a stock's performance over time.
- Wrote a reusable script that can analyse any publicly traded stock. Change the ticker symbol and get a complete analysis instantly.
- Compared two stocks side-by-side using the Sharpe Ratio to identify which delivered better risk-adjusted returns.
Ready to quiz yourself?