AI-Powered Stock Analyzer with Python

Fetch real stock data, process it, and get AI-generated analysis reports.

Introduction

30 Second Summary

You have probably checked a stock price before and wondered whether that number is good or bad. Professionals use software tools that pull data and interpret it instantly, but those tools cost hundreds of dollars a month.

In this project, you will build your own stock analysis tool in Python. It fetches real market data from the internet, crunches the numbers, sends them to Google's AI for a plain-English explanation, and saves a formatted report you can open and share.

What You'll Build

You run a single command, real stock prices fill your terminal, and an AI-written analysis appears below them explaining exactly what those numbers mean. A polished report file lands in your project folder, ready to open or send to someone.

By the end of this project, you'll have:

  • A working Python tool that fetches live stock data from the internet and prints real prices to your terminal on demand.
  • An AI-powered analysis step where Gemini reads your data and writes a beginner-friendly explanation of what is happening with the stock.
  • A formatted report file generated automatically with both the raw numbers and the AI insights, ready to share.
  • Secret Mission: Upgrade your analyzer to compare multiple stocks side-by-side with an AI-generated comparison report.

Are there any prerequisites?

You should be comfortable with basic Python concepts like variables, loops, conditionals, and functions. You also need a Google account to get a free Gemini API key.

Before We Start

Before we dive in, let's lock in what you're about to build and why it matters.

Set Up Your Developer Environment

Python can run basic scripts on its own, but building real tools requires external libraries. These are packages of code that other developers have written and shared so you do not have to build everything from scratch.

In this step, you will install two libraries using pip, Python's package manager. You will also create your project folder and confirm everything works together.

In this step, get ready to:
  • Create a project folder and open it in VS Code.
  • Install the requests and google-genai libraries with pip.
  • Verify both libraries import successfully.
Open VS Code and create your project folder
  • Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
  • Type VS Code and press Enter to open it.
  • Open the integrated terminal by clicking Terminal in the top menu bar, then New Terminal.
  • Move to your Desktop by running this command:
cd ~/Desktop
  • Create your project folder and move into it by running these commands:
mkdir stock-analyzer
cd stock-analyzer
  • Now open this folder in VS Code by clicking File in the top menu bar.
  • Click Open Folder.
  • Navigate to your Desktop, select the stock-analyzer folder, and click Open.

You should see stock-analyzer appear in the Explorer sidebar on the left, confirming VS Code is now working inside your project folder.

  • Open a fresh terminal inside this folder by clicking Terminal in the top menu bar, then New Terminal.

Terminal opened in the wrong folder?

If your terminal prompt does not show stock-analyzer, the terminal may have opened in a parent folder. Close the terminal panel, make sure the stock-analyzer folder is the one open in VS Code's Explorer sidebar, then open a new terminal again.

Help me fix my VS Code terminal path

Install the libraries your project needs

Your stock analyzer needs two external libraries to work. requests lets Python make HTTP calls to websites and APIs. google-genai lets Python talk to Google's Gemini AI.

  • Install the requests library by running this command:
pip install requests==2.34.2

You should see pip download and install the package, ending with a line that says Successfully installed.

  • Install the google-genai library by running this command:
pip install google-genai==2.18.0

You should see pip download and install this package along with its dependencies, ending with another Successfully installed line.

Why pin specific versions?

The ==2.34.2 and ==2.18.0 parts tell pip to install exact versions. This ensures your project behaves identically to this tutorial, even if newer versions release later.

Seeing a permission error or command not found?

If you see a permission error, try running pip install --user requests==2.34.2 instead. If pip is not recognized, try pip3 instead of pip.

Help me fix my pip install error

Create a test file and verify your setup

Now that both libraries are installed, you will create your main Python file and confirm everything imports correctly.

  • In the Explorer sidebar, hover over the stock-analyzer folder name and click the New File icon (a page with a plus sign).
  • Type stock_analyzer.py and press Enter.
  • Add this test code to your new file:
import requests
from google import genai

print("Setup complete! Both libraries are working.")

What does this code do?

import requests loads the HTTP library so Python can make web requests.

from google import genai loads the Gemini AI library so Python can communicate with Google's AI service.

The print() line confirms both imports succeeded. If either library was missing, Python would crash before reaching this line.

  • Save the file by pressing Cmd+S (macOS) or Ctrl+S (Windows).

Before you run this, what do you expect to see if both libraries installed correctly?

  • Run your file by entering this command in the terminal:
python stock_analyzer.py

You should see Setup complete! Both libraries are working. printed in your terminal. This confirms Python found both libraries and imported them without errors.

Seeing a ModuleNotFoundError?

If Python says it cannot find requests or google, the libraries may have installed to a different Python version than the one VS Code is using. Try running pip3 install requests==2.34.2 and pip3 install google-genai==2.18.0 to reinstall.

Help me fix my ModuleNotFoundError

✔️ Awesome, I've got everything!

Great. Double check you have saved stock_analyzer.py and you are ready for the next step.

ⓧ I'd like to double check the full code

Your stock_analyzer.py file should contain exactly this:

import requests
from google import genai

print("Setup complete! Both libraries are working.")

Your developer environment is locked in. Next up, you will use the requests library to fetch real stock market data from the internet and see it appear in your terminal.

Fetch Real Stock Data from the Internet

Your environment is locked in. Now it is time to make your Python script do something real.

The internet is full of data you can grab programmatically. Services called APIs let programs request data from other services over the web. In this step, you will call a free stock market API and watch real prices appear in your terminal from a single Python command.

In this step, get ready to:
  • Write a function that fetches stock data from a public API.
  • See real NVDA stock prices printed in your terminal.
  • Try fetching data for different stock tickers.
Write the stock data fetcher

The Fin-node API serves free stock market data as JSON. No API key or signup is needed. You just send a web request to a URL containing the stock ticker and get back structured data.

  • In VS Code, open stock_analyzer.py.
  • Select all the existing code and delete it.
  • Replace it with the following code that defines a function to fetch stock data from the internet:
import requests

# The stock ticker to look up
TICKER = "NVDA"

def fetch_stock_data(ticker):
    """Fetch stock data from the Fin-node API."""
    url = f"https://www.fin-node.net/api/{ticker}.json"
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Error: {response.status_code}")
        return None

# Call the function and display results
raw_data = fetch_stock_data(TICKER)
print(f"Got data for {TICKER}!")
print(f"Number of price days: {len(raw_data['prices'])}")
print(f"Latest day: {raw_data['prices'][-1]}")

What does this code do?

  • TICKER = "NVDA" sets which stock to look up. NVDA is NVIDIA's ticker symbol.
  • fetch_stock_data(ticker) builds a URL with the ticker, sends an HTTP request using requests, and returns the JSON response as a Python dictionary.
  • response.status_code == 200 checks that the request succeeded. 200 is the HTTP status code for "OK."
  • The bottom section calls the function and prints how many days of price data came back, plus the most recent day's full details.

Before you run this, what do you think will happen? Will you see stock prices, or will something go wrong?

  • Save stock_analyzer.py.
  • Run the script in your terminal by running this command:
python stock_analyzer.py

You should see real NVDA stock price data printed in your terminal. The output includes the number of price days and the latest day's data with dates, open, high, low, close, and volume values.

Seeing an error instead of data?

  • If you see ModuleNotFoundError: No module named 'requests', the library did not install into the same Python your terminal is using. Try running pip install requests==2.34.2 again.
  • If you see a connection error, check that you are connected to the internet.
  • If you see SyntaxError, check that the f-string quotes match. Each f"..." must use regular double quotes outside and single quotes inside the curly braces for dictionary keys.

Why isn't my stock data script working?

Try different stock tickers

Your function works for any ticker the API supports. You can swap in a different company to see different data.

  • In stock_analyzer.py, find the line that says TICKER = "NVDA".
  • Change "NVDA" to "AAPL" or "TSLA" and run the script again to see data for a different company.
  • Change TICKER back to "NVDA" before moving on.

What is an API?

An API (Application Programming Interface) is a way for one program to request data or actions from another service over the internet. You send a request to a specific URL, and the service sends back structured data your code can use.

The Fin-node API returns data in JSON format. JSON looks like Python dictionaries and lists, which is why response.json() converts it directly into a Python dictionary you can work with.

✔️ Awesome, I've got everything!

Great. Make sure you have saved your file with TICKER set back to "NVDA".

ⓧ I'd like to double check the full code

Here is the complete stock_analyzer.py at this point. Make sure yours matches:

import requests

TICKER = "NVDA"

def fetch_stock_data(ticker):
    url = f"https://www.fin-node.net/api/{ticker}.json"
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Error: {response.status_code}")
        return None

raw_data = fetch_stock_data(TICKER)
print(f"Got data for {TICKER}!")
print(f"Number of price days: {len(raw_data['prices'])}")
print(f"Latest day: {raw_data['prices'][-1]}")

You just pulled real financial data from the internet with a few lines of Python. Next up, you will crunch those raw numbers into a clean summary that highlights what actually matters.

Process Raw Data into Useful Numbers

The Fin-node API returns hundreds of data points for every stock. Dumping all of that raw data to the screen is overwhelming and useless.

Real developers filter and transform raw data into exactly what they need. In this step, you will build a processing function that extracts key metrics from the raw response. You will notice an important limitation at the end: numbers alone cannot tell you what they mean.

In this step, get ready to:
  • Build a function that processes raw API data into key stock metrics.
  • Display a clean formatted summary in the terminal.
  • Discover the limitation that raw numbers cannot interpret themselves.
Add the data processing function

The raw JSON from the API contains every trading day in its history. You only need the last 5 days to calculate recent performance.

  • In stock_analyzer.py, add the following function directly below the fetch_stock_data function (after its return None line):
def process_stock_data(data):
    # Extract the price history and company fundamentals
    prices = data["prices"]
    fundamentals = data["fundamentals"]
    # Take only the last 5 trading days
    recent_prices = prices[-5:]

    # Calculate price movement over the 5-day window
    latest_price = recent_prices[-1]["Close"]
    oldest_price = recent_prices[0]["Close"]
    price_change = latest_price - oldest_price
    price_change_percent = (price_change / oldest_price) * 100

    # Find the highest and lowest prices across those 5 days
    highs = [day["High"] for day in recent_prices]
    lows = [day["Low"] for day in recent_prices]

    # Package everything into a clean summary dictionary
    summary = {
        "ticker": TICKER,
        "latest_price": latest_price,
        "5_day_change": round(price_change, 2),
        "5_day_change_percent": round(price_change_percent, 2),
        "5_day_high": max(highs),
        "5_day_low": min(lows),
        "fundamentals": fundamentals,
        "recent_prices": recent_prices,
    }
    return summary

What does this code do?

  • prices[-5:] slices the last 5 entries from the price list. This gives you the most recent 5 trading days.
  • The price change calculation subtracts the oldest close from the latest close, then converts to a percentage.
  • List comprehensions ([day["High"] for day in recent_prices]) pull out just the high price from each day into a flat list so you can find the max and min.
  • The summary dictionary packages all the key numbers into one neat object your code can pass around.
  • Save stock_analyzer.py.
Replace the output with a processed summary

Now you need to call the new function and display its results instead of the raw data you printed in the previous step.

  • In stock_analyzer.py, find these lines at the bottom of your file:
raw_data = fetch_stock_data(TICKER)
print(f"Got data for {TICKER}!")
print(f"Number of price days: {len(raw_data['prices'])}")
print(f"Latest day: {raw_data['prices'][-1]}")
  • Select all four of those lines and replace them with the following code:
# Fetch and process, then display the summary
raw_data = fetch_stock_data(TICKER)
if raw_data:
    summary = process_stock_data(raw_data)
    print(f"\n--- Summary for {TICKER} ---")
    print(f"Latest Price: ${summary['latest_price']}")
    print(f"5-Day Change: ${summary['5_day_change']} ({summary['5_day_change_percent']}%)")
    print(f"5-Day High: ${summary['5_day_high']}")
    print(f"5-Day Low: ${summary['5_day_low']}")
    print("\nBut what does this actually mean? Is this good or bad?")

What does this code do?

  • if raw_data: is a safety check. If the API call failed and returned None, the script skips processing instead of crashing.
  • process_stock_data(raw_data) runs your new function and stores its result in summary.
  • The f-strings pull specific values from the summary dictionary and format them with dollar signs and percentages for readability.
  • The final print statement intentionally asks "But what does this actually mean?" to surface the limitation you will solve in the next step.
  • Save stock_analyzer.py.
Run the script and observe the limitation

Before you run this, think about what you expect to see. Will the output tell you whether this stock is performing well or poorly?

  • Run the script by entering this command in your terminal:
python stock_analyzer.py

You should see a clean summary with the latest price, a 5-day change in dollars and percentage, the 5-day high, and the 5-day low. Then the script prints: "But what does this actually mean? Is this good or bad?"

That question is the point. A 2% change could be normal fluctuation or a significant move. The numbers alone cannot tell you whether this is good news or bad news. You need intelligence to interpret data.

Not seeing the summary?

  • Make sure the process_stock_data function is placed after fetch_stock_data but before the raw_data = fetch_stock_data(TICKER) line at the bottom. Python reads top to bottom, so the function must be defined before it is called.
  • If you see KeyError: 'Close', check that you are using capital letters for the dictionary keys ("Close", "High", "Low"). The API returns them capitalized.
  • If you see NameError: name 'process_stock_data' is not defined, the function definition is placed below the line that calls it. Move it above.

Help me debug my stock summary output.

Try a different ticker

Change TICKER = "NVDA" at the top of your file to "AAPL" or "TSLA" and run again. You will see different numbers, but the same limitation: you still cannot tell what they mean without context.

Change it back to "NVDA" before moving on.

✔️ Awesome, I've got everything!

Great. Make sure you have saved stock_analyzer.py and the ticker is set back to "NVDA".

ⓧ I'd like to double check the full code

Your stock_analyzer.py should have these sections in order from top to bottom:

  • The import requests line and TICKER = "NVDA" at the very top.
  • The fetch_stock_data(ticker) function (from Step 2).
  • The process_stock_data(data) function you just added.
  • The bottom block starting with raw_data = fetch_stock_data(TICKER) that calls both functions, prints the summary, and ends with the "But what does this actually mean?" line.

Scroll up and confirm each chunk is present in order. If anything is missing, copy it from the relevant code block above.

You now have a program that fetches real data and crunches it into meaningful metrics. But the numbers alone leave you guessing. Next up, you will connect to Google's Gemini AI to interpret the data and explain what it all means in plain English.

Connect to Gemini AI for Intelligent Analysis

Your program fetches real stock data and crunches the numbers into a clean summary. But when you ran it, the output ended with a question: "What does this actually mean?"

Numbers alone cannot explain whether a 2% price change is normal volatility or a warning sign. This is exactly what AI excels at. In this step, you will send your processed data to Google's Gemini AI, which reads the numbers and writes a plain-English interpretation.

In this step, get ready to:
  • Connect your script to the Gemini AI service.
  • Build a structured prompt that feeds your stock data to the AI.
  • See an AI-generated explanation of NVDA's performance printed in your terminal.
Add the new imports and API key

Your script needs two new capabilities: converting Python dictionaries to formatted text (json), and talking to Google's AI (genai). You also need to store your API key so the AI service knows who is calling.

  • In stock_analyzer.py, find the first line at the top of your file:
import requests
  • Replace it with these four lines, which add the two new imports and set up your API key above the existing TICKER variable:
import requests
import json
from google import genai

API_KEY = "your-api-key-here"
TICKER = "NVDA"
  • Replace "your-api-key-here" with the actual Gemini API key from your Google AI Studio account.

What do these lines do?

  • import json gives Python the ability to convert dictionaries into neatly formatted text strings that the AI can read.
  • from google import genai loads the Google AI SDK you installed in Step 1.
  • API_KEY stores your personal key so Google's servers can verify your requests.

Keep your API key private

Never share your API key publicly or commit it to a shared repository. For this learning project, pasting it directly in the file is fine. In production code, developers store keys in environment variables instead.

Write the AI analysis function

This function takes your processed stock summary, packages it into a detailed prompt, and sends it to Gemini. The AI reads your data and returns a beginner-friendly explanation.

  • In stock_analyzer.py, scroll down to the end of the process_stock_data function (after its return summary line). Add this new function below it:
def analyze_with_ai(summary):
    # Create a connection to Google's AI service
    client = genai.Client(api_key=API_KEY)

    # Build a detailed prompt with all the stock data
    prompt = f"""Analyze this stock data and provide a brief, beginner-friendly summary:

Ticker: {summary['ticker']}
Latest Price: ${summary['latest_price']}
5-Day Price Change: ${summary['5_day_change']} ({summary['5_day_change_percent']}%)
5-Day High: ${summary['5_day_high']}
5-Day Low: ${summary['5_day_low']}

Fundamentals: {json.dumps(summary['fundamentals'], indent=2)}

Recent daily prices: {json.dumps(summary['recent_prices'], indent=2)}

Please provide:
1. A simple explanation of what these numbers mean
2. Key observations about the stock's recent performance
3. Important fundamentals to pay attention to

Keep it simple and educational. Explain any financial terms you use."""

    # Send the prompt to Gemini and get the response
    interaction = client.interactions.create(
        model="gemini-3.6-flash",
        input=prompt,
    )
    return interaction.output_text

What does this function do?

  • genai.Client(api_key=API_KEY) opens a connection to Google's AI service using your personal key.
  • The prompt variable is a formatted string that includes all your processed stock data. This gives the AI everything it needs to write an intelligent analysis.
  • client.interactions.create() sends your prompt to the gemini-3.6-flash model and waits for its response.
  • interaction.output_text contains the AI's written analysis as a plain string.
Call the AI and see the result

Now you need to update the bottom of your script to call the new AI function after processing the data.

  • Scroll to the bottom of stock_analyzer.py and find this block of code (everything below your functions):
raw_data = fetch_stock_data(TICKER)
if raw_data:
    summary = process_stock_data(raw_data)
    print(f"\n--- Summary for {TICKER} ---")
    print(f"Latest Price: ${summary['latest_price']}")
    print(f"5-Day Change: ${summary['5_day_change']} ({summary['5_day_change_percent']}%)")
    print(f"5-Day High: ${summary['5_day_high']}")
    print(f"5-Day Low: ${summary['5_day_low']}")
    print("\nBut what does this actually mean? Is this good or bad?")
  • Replace that entire block with this updated version that calls the AI after printing the summary:
raw_data = fetch_stock_data(TICKER)
if raw_data:
    summary = process_stock_data(raw_data)
    print(f"\n--- Summary for {TICKER} ---")
    print(f"Latest Price: ${summary['latest_price']}")
    print(f"5-Day Change: ${summary['5_day_change']} ({summary['5_day_change_percent']}%)")
    print(f"5-Day High: ${summary['5_day_high']}")
    print(f"5-Day Low: ${summary['5_day_low']}")

    print("\nAsking AI for analysis...")
    ai_analysis = analyze_with_ai(summary)
    print("\n--- AI Analysis ---")
    print(ai_analysis)

What changed?

The "But what does this actually mean?" line is gone. Instead, the script now calls analyze_with_ai(summary) and prints the AI's response below the numbers. The limitation from the previous step is now solved.

  • Save stock_analyzer.py.

Before you run this, what do you think will appear below the price summary? Will the AI take a long time to respond, or will it be fast?

  • Run your script to see the AI in action:
python stock_analyzer.py

You should see your familiar price summary for NVDA, followed by "Asking AI for analysis..." and then a full paragraph of AI-written insights explaining what the numbers mean.

Seeing an error about the API key?

  • Make sure you replaced "your-api-key-here" with your actual key from Google AI Studio. The key should be inside quotes.
  • Check that your key has no extra spaces before or after it.
  • If you see a "permission denied" or "invalid key" error, visit Google AI Studio and confirm your key is still active.

Help me fix my Gemini API key error in stock_analyzer.py

Seeing a timeout or connection error?

  • The AI call requires an internet connection. Check that you are online.
  • The Gemini API is free but can occasionally be slow during peak times. Wait a moment and try running the script again.

Help me fix a connection error when calling the Gemini API

✔️ Awesome, I've got everything!

Great. Double check you have saved stock_analyzer.py and your AI analysis is printing successfully.

ⓧ I'd like to double check the full code

Your stock_analyzer.py should now have these sections in order. Scroll through your file and confirm each one is present:

  • Imports at the top: requests, json, and from google import genai.
  • Configuration: API_KEY set to your Gemini key, and TICKER = "NVDA".
  • The fetch_stock_data(ticker) function (unchanged from Step 2).
  • The process_stock_data(data) function (unchanged from Step 3).
  • The new analyze_with_ai(summary) function that creates a client, builds a prompt, and calls client.interactions.create().
  • The main code block at the bottom that fetches, processes, and calls the AI, printing everything to the terminal.

Your stock analyzer now does something remarkable. It pulls data from the internet, crunches it, and then asks an AI to explain what it all means. Next up, you will save this entire analysis to a file so you can keep and share it.

Save a Formatted Report to File

Your stock analyzer now fetches live data, crunches it into a summary, and sends it to Gemini for an intelligent breakdown. That is a complete pipeline.

There is one problem: the moment you close your terminal, all of that analysis disappears. A real developer tool produces output you can keep, share, or reference later. In this step, you will write the results to a file and wrap your script in a clean main() function so it runs like a professional program.

In this step, get ready to:
  • Add a function that writes a formatted report to a text file.
  • Wrap your entire pipeline in a main() function with proper error handling.
  • Run your script and find a shareable report file in your project folder.
Add a function that saves the report to a file

Python's built-in open() function lets you create and write to files on your computer. You will use an f-string to build a nicely formatted report, then write it to a .txt file.

  • In stock_analyzer.py, add this new function below your analyze_with_ai function (but above the loose code at the bottom):
def save_report(summary, ai_analysis):
    """Save the complete analysis to a text file."""
    report = f"""
====================================
  STOCK ANALYSIS REPORT: {summary['ticker']}
====================================

--- PRICE DATA ---
Latest Price: ${summary['latest_price']}
5-Day Change: ${summary['5_day_change']} ({summary['5_day_change_percent']}%)
5-Day High: ${summary['5_day_high']}
5-Day Low: ${summary['5_day_low']}

--- AI ANALYSIS ---
{ai_analysis}

====================================
  Report generated by Stock Analyzer
====================================
"""
    filename = f"{summary['ticker']}_report.txt"
    with open(filename, "w") as file:
        file.write(report)
    return filename

What does this code do?

This function builds a formatted string using an f-string with triple quotes (which lets you write multi-line text). The report includes both the price data and the AI analysis in a clean layout.

The with open(filename, "w") as file: line creates a new file in write mode. Python automatically closes the file when the with block ends, so you never leave files accidentally open.

Wrap everything in a main() function

Right now, the code at the bottom of your file runs immediately when Python loads the script. Professional Python programs wrap their execution logic in a main() function. This gives you a single entry point and makes the code easier to read.

  • Find the loose code at the bottom of your file. It starts with raw_data = fetch_stock_data(TICKER) and ends with print(ai_analysis).
  • Delete all of that loose code and replace it with this main() function:
def main():
    """Main function - runs the complete analysis pipeline."""
    print(f"Fetching stock data for {TICKER}...")
    raw_data = fetch_stock_data(TICKER)

    if raw_data is None:
        print("Failed to fetch data. Check your internet connection.")
        return

    print("Processing data...")
    summary = process_stock_data(raw_data)

    print(f"\n--- Summary for {TICKER} ---")
    print(f"Latest Price: ${summary['latest_price']}")
    print(f"5-Day Change: ${summary['5_day_change']} ({summary['5_day_change_percent']}%)")
    print(f"5-Day High: ${summary['5_day_high']}")
    print(f"5-Day Low: ${summary['5_day_low']}")

    print("\nAsking AI for analysis...")
    ai_analysis = analyze_with_ai(summary)

    print("\n--- AI Analysis ---")
    print(ai_analysis)

    filename = save_report(summary, ai_analysis)
    print(f"\nFull report saved to: {filename}")


if __name__ == "__main__":
    main()

What does this code do?

  • main() runs your entire pipeline in order: fetch, process, analyze, print, and save.
  • The if raw_data is None: check stops the program early if the API call failed, instead of crashing on bad data.
  • if __name__ == "__main__": is a Python pattern that means "only run this when the script is executed directly." It prevents the code from running if someone imports your file as a module.
  • Save stock_analyzer.py.

Before you run this, what do you expect to happen differently compared to last time? Think about it for a moment.

  • Run your completed script:
python stock_analyzer.py

You will see all the familiar output (data summary and AI analysis), plus a new final line: Full report saved to: NVDA_report.txt. That file now exists in your project folder.

  • Confirm the report file was created by running:
ls

You should see NVDA_report.txt alongside your stock_analyzer.py file.

  • Open NVDA_report.txt by clicking on it in the VS Code Explorer sidebar.

You will see the full formatted report with the stock header, price data section, and AI analysis section all laid out cleanly.

Don't see NVDA_report.txt?

  • Check that you deleted ALL the old loose code (everything from raw_data = fetch_stock_data(TICKER) to the end). If both the old code and main() exist, the old code runs first and may hide errors.
  • Make sure if __name__ == "__main__": is at the very bottom of your file, not indented inside any function.
  • If you see an error about save_report not being defined, make sure your save_report function is above the main() function in the file.

Help me debug why my report file isn't being created.

✔️ Awesome, I've got everything!

Great. Double check you have saved stock_analyzer.py and confirmed that NVDA_report.txt exists in your project folder.

ⓧ I'd like to double check the full code

Your stock_analyzer.py should contain these sections in order. Scroll up and confirm each is present:

  • Imports: import requests, import json, from google import genai.
  • Configuration: API_KEY and TICKER variables.
  • Function: fetch_stock_data(ticker) that calls the Fin-node API.
  • Function: process_stock_data(data) that extracts the summary.
  • Function: analyze_with_ai(summary) that sends data to Gemini.
  • Function: save_report(summary, ai_analysis) that writes the report file.
  • Function: main() that runs the full pipeline.
  • Entry point: if __name__ == "__main__": main() at the very bottom.

Make sure there is NO loose code outside of functions (except the imports, config variables, and the if __name__ line).

Your stock analyzer is complete. You have a professional Python program that fetches live data, processes it, gets AI insights, and saves a polished report to a file. Next up, take on the Secret Mission and push your tool even further.

Secret mission

Multi-Stock Comparison

Your analyzer works great for a single stock. But real analysts never look at one stock in isolation. Can you upgrade your tool to fetch data for multiple tickers, compare them side-by-side, and have Gemini explain which one performed best?

Clean Up Your Resources

Clean Up Your Resources

This project runs entirely locally with a free-tier API, so there are no ongoing costs. Decide whether to keep your resources ready for future experiments, or delete them entirely.

Resources you used:

  • Python packages installed locally (requests and google-genai).
  • Gemini API key (free tier, no charges).
  • Project folder stock-analyzer with stock_analyzer.py, NVDA_report.txt, and comparison_report.txt.

Keep everything running

No action needed. Choose this if you plan to keep experimenting with your stock analyzer.

  • Your requests and google-genai libraries stay installed and ready for future Python projects.
  • Your Gemini API key remains active on the free tier indefinitely.
  • Your stock-analyzer folder and report files stay on your machine.

Pause - I'll come back to this later

Nothing to pause. There are no running servers, containers, or cloud resources consuming costs or memory.

  • Your project files stay where they are until you come back.
  • Your API key stays active on the free tier with no charges.

Delete - I don't want to use this again

Remove all project files and revoke your API key to start fresh.

  • Delete your project folder by running this command in your terminal:
rm -rf ~/Desktop/stock-analyzer

On Windows

If you are on Windows, run this in PowerShell instead:

Remove-Item -Recurse -Force "$HOME\Desktop\stock-analyzer"
  • Uninstall the Python packages by running:
pip uninstall requests google-genai
  • To revoke your Gemini API key, go to the AI Studio API Keys page at aistudio.google.com.
  • Find your key in the list and delete it.

Nice Work!

Nice Work!

You just built a real developer tool that pulls live data from the internet, crunches it into useful metrics, and sends it to an AI for intelligent analysis. That is a serious step up from practice scripts.

You've learned how to:

  • Make HTTP requests to a real API and transform raw JSON data into meaningful summaries with calculated metrics.
  • Connect to Google Gemini AI and send it structured prompts that turn numbers into beginner-friendly explanations.
  • Structure a complete Python tool with functions, file I/O, and a main() entry point that produces a shareable report.
  • Secret Mission: Built a multi-stock comparison tool that loops through multiple tickers and generates AI-powered side-by-side analysis.

Ready to quiz yourself?