Ever wondered how to keep track of stock prices without constantly refreshing web pages? With Python, we can easily scrape stock price data and have all the information at our fingertips, all in real-time. Let’s dive into how you can do this with just a few lines of code!

Web scraping stock prices in Python

Scrape a Company’s Stock Data

If you need to monitor a company's stock, you can use this API: Google Finance API. It scrapes data from the Google Finance page. To get everything else on the page, like financial statements and news, read our tutorial:

Scrape Google Finance Ticker Quote Data in Python
Learn how to scrape Google Finance with Python. Get stock quotes, historical prices, financials, and news as JSON, find tickers with the new Autocomplete API, or build a DIY scraper.

Video Tutorial
If you prefer to watch a video, here it is

Step 1: Tools

We'll use the official Python library by SerpApi: serpapi-python .
That's the only tool that we need!

Python library from SerpApi, the tool we need to scrape Google SERP
As a side note: You can use this library to scrape search results from other search engines, not just Google Finance.

Usually, you'll write your DIY solution using something like BeautifulSoup, Selenium, Scrapy, Requests, etc., to scrape Google Finance results. You can relax now since we perform all these heavy tasks for you. So, you don't need to worry about all the problems you might've encountered while implementing your web scraping solution.

Step 2: Setup and preparation

  • Sign up for free at SerpApi. You can get 250 free searches per month.
  • Get your SerpApi API Key from your dashboard.
  • Create a new .env file, and assign a new env variable with value from API_KEY above.
    SERPAPI_API_KEY=$YOUR_SERPAPI_API_KEY_HERE
  • Install python-dotenv to read the .env file with
    pip install python-dotenv
  • Install SerpApi's Python library with
    pip install serpapi
  • Create new main.py file for the main program.

Your folder structure will look like this:

|_ .env
|_ main.py

Step 3: Write the code for scraping Google Finance results

Here is the code example for searching Tesla stock today:

import os
import serpapi

from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv('SERPAPI_API_KEY')

client = serpapi.Client(api_key=api_key)
result = client.search(
	engine="google_finance",
	q="TSLA:NASDAQ",
	hl="en",
)

print(result)

Scrape Tesla stock price with Python

Try to run this program with python main.py or python3 main.py from your terminal.

Let's compare the result from Google Finance page with the API response:

Result from Google finance page
Response sample result

As you can see, we've successfully gotten the data programmatically.

Q parameter
We need the company's ticker name as value for the q parameter. You can find this by searching on Google. Feel free to change the value of the q parameter a ticker's code of a company. If you only have the company name, see how to get the ticker name programmatically below.

Filter by time
You can filter the results by time using the window parameter. Here are the options:
1D - 1 Day(default)
5D - 5 Days
1M - 1 Month
6M - 6 Months
YTD - Year to Date
1Y - 1 Year
5Y - 5 Years
MAX - Maximum

How to get Ticker name programmatically

If you need to get the ticker name programmatically, use our Google Finance Autocomplete API. It returns the same suggestions you see when you type in the Google Finance search box.

company_name = "Nvidia"
result = client.search(
    engine="google_finance_autocomplete",
    q=company_name,
)

for stock in result["suggestions"]["stocks"]:
    print(stock["stock"], "|", stock["name"], "|", stock["country"])

ticker = result["suggestions"]["stocks"][0]["stock"]
print("Ticker:", ticker)

The output:

NVDA:NASDAQ | NVIDIA Corp | US
NVDA23:BKK | Nvidia Corporation INVX DR | TH
NVDC34:BVMF | Nvidia Corp BDR | BR
NVD:ETR | NVIDIA Corp | DE
NVD:FRA | NVIDIA Corp | DE
Ticker: NVDA:NASDAQ

The first result is usually the main listing. Pass ticker straight into the q parameter of the Google Finance API.

Interested in a no-code solution? Learn how to scrape Google Finance reports using Google Sheets:

Scrape Google Finance Reports with Google Sheets
How to scrape financial statements from Google Finance with Google Sheets using SerpApi’s Google Finance API.

Track multiple stock prices

To track several stocks, loop over a list of tickers and save each price with a timestamp. Each run adds new rows to the same CSV file, so you build a price history over time.

import csv
from datetime import datetime, timezone

tickers = ["TSLA:NASDAQ", "NVDA:NASDAQ", "AAPL:NASDAQ", "GOOGL:NASDAQ"]
max_tickers = 10  # each ticker is one search, so cap it

rows = []
for ticker in tickers[:max_tickers]:
    result = client.search(engine="google_finance", q=ticker, hl="en")
    summary = result.get("summary")
    if not summary:
        print(f"No price found for {ticker}")
        continue

    movement = summary.get("price_movement", {})
    row = {
        "checked_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "ticker": ticker,
        "name": summary.get("title"),
        "price": summary.get("extracted_price"),
        "currency": summary.get("currency"),
        "change_percent": round(movement.get("percentage", 0), 2),
        "movement": movement.get("movement", "Flat"),
    }
    rows.append(row)
    print(row["ticker"], row["price"], row["currency"], row["movement"], f'{row["change_percent"]}%')

file_exists = os.path.exists("stock_prices.csv")
with open("stock_prices.csv", "a", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()) if rows else ["ticker"])
    if not file_exists:
        writer.writeheader()
    writer.writerows(rows)

print(f"Saved {len(rows)} prices to stock_prices.csv")

The output:

TSLA:NASDAQ 385.19 USD Down 3.34%
NVDA:NASDAQ 200.13 USD Up 1.12%
AAPL:NASDAQ 339.5 USD Down 1.0%
GOOGL:NASDAQ 287.4 USD Up 0.53%
Saved 4 prices to stock_prices.csv

Run the script on a schedule (for example with cron or a GitHub Action) to collect prices every day. When the price doesn’t change, Google leaves out the movement field, so the code saves “Flat” instead.

SerpApi also provides the API for current market trends from this page: https://www.google.com/finance/markets/indexes?hl=en. We can use Google Finance Markets API for this.

Code sample
We can use the same setup as before with a few tweaks to some values:

result = client.search(
    engine="google_finance_markets",
    trend="indexes",
    hl="en"
)
  • Update engine to google_finance_markets
  • add trend parameter

Here is the result:

Google finance markets API result

Which represents this page:

Trend parameter
We can change the ranking factor using trend parameter. This parameter is used to retrieve different market trends. Available options:
- indexes - Market indexes
- most-active - Most active
- gainers - Gainers
- losers - Losers
- climate-leaders - Climate leaders
- cryptocurrencies - Crypto
- currencies - Currencies

I hope this is helpful! I hope it can be useful for your finance app project! If you have any questions, please feel free to contact us at contact@serpapi.com.