I tried making a "real-time stock price tracker" with Python [Web scraping]

programming

"I want to check stock prices whenever I want, but it's a pain to have to open the website every time."

"It would be so much easier if I could just see a list of the brands I want to see..."

For those of you who are worried about this, we recommendA real-time stock price tracker using Pythonis.

In this article,How to automatically retrieve and display stock price information of your choice using the power of Python and web scrapingWe will explain this in simple terms that even elementary school students can understand, with actual code included.

"I want to create a practical tool using Python"

For those of you who think so,Specific and immediately usable learningWe will deliver the following.

What is a stock price tracker? [What is a real-time stock price tracker?]

Explaining the basic functions of a stock price tracker

Conclusion: A stock tracker is a tool that displays a list of stock prices for each stock in real time.

Main features include:

• Get stock prices by specifying a specific company name or stock code

• Display of current price, previous day's change, volume, etc.

• Data updated every few minutes

• Notification feature will alert you when a certain price is exceeded

With these features,Get information at a glance that will help you make stock investment decisions and learncan.

In what situations can it be used?

Conclusion: Perfect for investment decisions and daily financial checks.

It is especially recommended for the following people:

• Beginners who have just started investing in stocks

• Intermediate investors who are following a particular stock for the long term

• People who want to record daily stock price fluctuations

• People who want to learn scraping and data processing

"I want to get stock prices in my own hands."

If you have that feeling,Anyone can make this tool.

Basics of Web Scraping [Introduction to Python Web Scraping]

What is Web Scraping? A simple explanation of how it works

Conclusion: It is a technology that automatically extracts only the necessary information from a web page.

For example, a stock price page of a brokerage firm has a lot of information,

Unlike a screen that humans see,It is structured in a system called HTML.

If you read HTML with Python and extract specific elements,

• Extract only stock prices

• Pick a specific code from the stock list

• Get only part of a page

You can do things like:This is the basics of web scrapingis.

Check the necessary preparations and precautions

Bottom line: three Python libraries make it easy to get started.

First, install the following:

1
pip install requests beautifulsoup4 lxml

• requests: Retrieving the contents of a web page

• BeautifulSoup: Make HTML easier to read

• lxml: A fast parsing engine

Also,It is important to follow the rules when scrapingis.

• Check whether the terms of use prohibit it.

• Limit the frequency of access (e.g. every 5 seconds)

• No personal information or copyrighted data

How to get stock prices [Python stock price scraping]

How to choose the target site and what to acquire

Conclusion: For personal use, Yahoo! Finance and other services are easy to use.

For example, there is a page for each stock with the following URL structure:

1
<a rel="noopener" href="https://finance.yahoo.co.jp/quote/7203.T" title="Toyota Motor Corporation [7203]: Stock Price and Stock Information - Yahoo! Finance" class="blogcard-wrap external-blogcard-wrap a-wrap cf" target="_blank"><div class="blogcard external-blogcard eb-left cf"><div class="blogcard-label external-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail external-blogcard-thumbnail"><img decoding="async" src="https://s.yimg.jp/images/finance/common/image/ogp.png" alt="" class="blogcard-thumb-image external-blogcard-thumb-image" width="160" height="90"></figure><div class="blogcard-content external-blogcard-content"><div class="blogcard-title external-blogcard-title">Toyota Motor Corporation [7203]: Stock Price and Stock Information - Yahoo! Finance</div><div class="blogcard-snippet external-blogcard-snippet">You can view the stock price, charts, latest related news, bulletin boards, and user reviews of Toyota Motor Corporation [7203]. You can view the previous day's closing price, high price, low price, as well as the year-to-date high/low price. Yahoo! Finance provides stock price updates, charts, rankings...</div></div><div class="blogcard-footer external-blogcard-footer cf"><div class="blogcard-site external-blogcard-site"><div class="blogcard-favicon external-blogcard-favicon"><img decoding="async" src="https://www.google.com/s2/favicons?domain=https://finance.yahoo.co.jp/quote/7203.T" alt="" class="blogcard-favicon-image external-blogcard-favicon-image" width="16" height="16"></div><div class="blogcard-domain external-blogcard-domain">finance.yahoo.co.jp</div></div></div></div></a>

• Toyota Motor Corp. stock code: 7203.T

• You can get other stocks by changing the URL in this format.

Example of elements to retrieve:

• Current price (specified by HTML class name, etc.)

• Change from previous day

• Name of stock

Actual code example and display of obtained results

Conclusion: You can get stock prices with 20-30 lines of code.

1
import requests from bs4 import BeautifulSoup url = "https://finance.yahoo.co.jp/quote/7203.T" res = requests.get(url) soup = BeautifulSoup(res.text, "lxml") price = soup.select_one(".stoksPrice").text name = soup.select_one("h1").text print(f"The current stock price of {name} is {price} yen.")

In this way, you can add the required HTML elements toSpecify by class name or tag nameBy doing so,

You can extract information accurately.

Formatting and displaying data [Python stock price formatting and display]

How to display it in a terminal

Conclusion: Displaying the data in a table format makes it easy to compare multiple stocks.

To handle multiple stocks, you can loop through a dictionary or list.

1
stocks = {"Toyota": "7203.T", "Nintendo": "7974.T", "Sony": "6758.T"} for name, code in stocks.items(): url = f"https://finance.yahoo.co.jp/quote/{code}" res = requests.get(url) soup = BeautifulSoup(res.text, "lxml") price = soup.select_one(".stoksPrice").text print(f"{name:<6}:{price} yen")

This way,Display each row as a neat tablecan.

Trying to visualize the data using graphs

Conclusion: You can also draw simple line graphs using matplotlib.

1
import matplotlib.pyplot as plt times = ["9:00", "10:00", "11:00"] prices = [1523, 1530, 1542] plt.plot(times, prices) plt.title("Toyota Motor stock price trends") plt.xlabel("Time") plt.ylabel("Stock price (yen)") plt.grid(True) plt.show()

By acquiring near real-time data and graphing it,You can visually grasp the changesIt will look like this.

Added automatic update and notification function [Real-time stock price automatic update]

Create a system for regular updates

Conclusion: You can use time.sleep() to update every 5 minutes, etc.

1
import time while True: get_stock_data() # Custom function time.sleep(300) # Every 5 minutes

In addition, if you plan to operate for a long period of time,We also recommend using cron or a scheduler.is.

How to implement LINE notifications and alerts

Conclusion: With LINE Notify, you can get notifications on your smartphone for a set price.

1. LINE Notify Issue a token with

2. Send with the following code

1
import requests message = "Toyota stock price fell below 1500 yen" token = "your access token" url = "https://notify-api.line.me/api/notify" headers = {"Authorization": f"Bearer {token}"} data = {"message": message} requests.post(url, headers=headers, data=data)

Being notified under certain conditions enhances real-time performance.

Application to practice and learning [Python stock price scraping application]

How to save logs and accumulate past data

Conclusion: You can manage history by saving it to a CSV file.

1
import csv from datetime import datetime with open("stock_log.csv", "a", newline="") as f: writer = csv.writer(f) now = datetime.now().strftime("%Y-%m-%d %H:%M") writer.writerow([now, "Toyota", 1530])

You can also load the data into Excel for analysis.

Can also be used for securities analysis and investment learning

Conclusion: The combination of Python and stock prices is a great introduction to data analysis.

• Calculate the moving average of a stock price

• Automatic high and low price capture

• Trend visualization

Many analyses can be performed using Python, such as:

👉Related articles:I tried making an "Automatic Exchange Rate Acquisition BOT" using Python [API usage]

Summary: A practical stock price acquisition tool [Python stock price tracker effectiveness]

Let's summarize the main points of this article.

Using Python and web scraping, you can create a tool that automatically obtains stock prices.

You can increase efficiency by displaying, recording, and notifying only the stocks you want to see.

It is also ideal for learning about investments and practicing data processing.

With the power of Python,The fun and convenience of having real-time information in your handsPlease come and experience it for yourself.

Copied title and URL