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!

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:

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!

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
.envfile, 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
.envfile withpip install python-dotenv - Install SerpApi's Python library with
pip install serpapi - Create new
main.pyfile 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:


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 Days1M - 1 Month6M - 6 MonthsYTD - Year to Date1Y - 1 Year5Y - 5 YearsMAX - 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:NASDAQThe 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:
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.csvRun 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.
Scrape Market Trends
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
trendparameter
Here is the 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.

