avatarBee Guan Teo

Summary

This article provides a step-by-step guide on how to build a real-time stock alert messaging system using Python, which detects the price change percentage of a target instrument and sends an alert via Telegram.

Abstract

The article begins by introducing the concept of a stock alert messaging tool and its benefits, such as enabling prompt trading decisions without the need to constantly monitor a computer screen. The author then outlines the five stages involved in building a real-time stock alert messaging system using Python: acquiring real-time stock data, setting up a Telegram Bot, generating alert messages, sending alerts to the Telegram Bot, and scheduling stock alert messaging. The article provides detailed instructions and code snippets for each stage, using the Financial Modeling Prep (FMP) API to obtain real-time stock data and the Telepot library to interact with the Telegram Bot. The author also discusses the use of the Timeloop library to schedule stock alert messaging at specific time intervals. The article concludes by mentioning alternative libraries and tools that can be used for more advanced systems.

Bullet points

  • A stock alert messaging tool can be valuable for keeping up to date with the most recent changes in the stock market and enabling prompt trading decisions.
  • The article provides a step-by-step guide on how to build a real-time stock alert messaging system using Python.
  • The system will detect the price change percentage of a target instrument and send an alert via Telegram.
  • The five stages involved in building the system are: acquiring real-time stock data, setting up a Telegram Bot, generating alert messages, sending alerts to the Telegram Bot, and scheduling stock alert messaging.
  • The article provides detailed instructions and code snippets for each stage.
  • The Financial Modeling Prep (FMP) API is used to obtain real-time stock data.
  • The Telepot library is used to interact with the Telegram Bot.
  • The Timeloop library is used to schedule stock alert messaging at specific time intervals.
  • Alternative libraries and tools, such as Apache Airflow or Luigi, can be used for more advanced systems.

How to Build a Real-time Stock Alert Messaging System in Python

Photo by Christian Wiediger on Unsplash

A stock alert messaging tool can be valuable for us to keep up to date with the most recent changes of the stock market and enable us to make a prompt trading decision. Rather than staying in front of a computer screen for a long day, the alert system can directly detect the most recent change of market condition in real time and send us a notification via a messaging app such as Telegram.

In this article, we are going to use Python to build a real time stock alert messaging system. The alert messaging system will detect the price change percentage of a target instrument and send us an alert via Telegram.

Prerequisite Python Packages

  1. telepot — https://telepot.readthedocs.io/en/latest/
  2. timeloop — https://pypi.org/project/timeloop/

Github

The original full source codes presented in this article are available on my Github Repo. Feel free to download it (StockAlert.py) if you wish to use it to follow my article.

Building Real-time Stock Alert Messaging System

We can break down the process of building a real-time stock alert messaging system into five stages:

Stage 1: Acquiring real time stock data

Stage 2: Setting up Telegram Bot

Stage 3: Generating Alert Message

Stage 4: Sending Alert to Telegram Bot

Stage 5: Scheduling Stock Alert Messaging

The following sections will discuss each of the stages in detail.

Stage 1: Acquiring real time stock data

We are going to use Financial Modeling Prep (FMP) API to obtain the stock real time data. To do so, we will first need to sign up for a free API key. We can visit this FMP API site and log in using our Google account.

Image Prepared by the Author

Once we sign in the API page, we will be given 250 API free requests per day (which is sufficient for practice and testing purposes). We can get our API key from the dashboard page.

Image Prepared by the Author

Next, let’s go to the FMP Documentation Page and look for “Company Quote” endpoint from the “STOCK PRICE” section.

Image Prepared by the Author

When we click on the “Company Quote”, we shall see a sample of http request URL will appear at the right.

Image Prepared by the Author

We are going to use this URL along with the API key in our Python script to obtain the real time stock data. Now, we are ready to write a Python script to obtain the real time stock data via the FMP API.

Line 1–5: Import all the required libraries.

Line 7: Define a Python function to get real time stock data. This function will accept one input ticker as its parameter.

Line 8–10: Split the HTTP request URL into three parts so that we can build a dynamic API request URL based on the input ticker and individual API key.

Line 11–13: Use the Python requests module to get the real time stock data via the FMP API request URL and return the data in JSON format.

Line 15: Invoke the function to obtain the real time data of Amazon stock.

We shall get the real time stock data returned by the FMP API as below:

Image Prepared by the Author

Stage 2: Setting up Telegram Bot

At this stage, we have already obtained the real time stock data and now we need a Telegram Bot to deliver a stock alert. We will require a token and a receiver ID to send a stock alert via the Telegram Bot.

Firstly, let us start with generating the token by visiting the Telegram Web and search for “BobFather”.

Image Prepared by the Author

In the BotFather, type “/start”

Image Prepared by the Author

We shall see a list of bot commands and we just click or type the “/newbot”.

Image Prepared by the Author

A new bot is created now, and we shall name our bot. Here we may simply name it as “stock alert”.

Image Prepared by the Author

At last, we will need to create a username for our bot by following the specific naming convention. Here, I just name it as “Stockalert1439Bot”.

(Note: You need to create your own unique bot username as they cannot be duplicated. )

Image Prepared by the Author

Once the username is created successfully, we shall see a token is generated in the bot message. We can copy this token and paste it in a Notepad for further usage later.

Now, we will proceed to obtain the receiver ID. From the Telegram Web, we search for our created bot using the username created by us.

Image Prepared by the Author

Next, we can simply type any dummy message in our bot (e.g. Hello World).

Image Prepared by the Author

Open a new tab from our browser and copy and paste the following link.

https://api.telegram.org/bot/getUpdates

From the web page, we shall see an id appear in the “chat” property of JSON object.

Image Prepared by the Author

We shall use that id as our Receiver ID.

Stage 3: Generating Alert Message

Now we proceed to write a Python script to generate a stock alert message. Here we are just required to extract the relevant info from the real time stock data to serve our purpose.

Line 1: Define a Python function to generate stock alert message. This function will accept real time stock data as its input parameter.

Line 2–5: Extract the information of “symbol”, “price”, “changesPercentage” and “timestamp” and assign them to the relevant variables.

Line 7–10: Convert the timestamp to local date and time format using the datatime fromtimestamp method. Concatenate the current datetime, stock symbol and price into an alert message.

Line 12–13: Check if the drop of price is bigger than 2%, append a warning to the alert message.

Line 15: Return the alert message as output.

Line 17: Invoke the function to generate the stock alert message.

Image Prepared by the Author

Stage 4: Sending Alert to Telegram Bot

Here we are going to add the Telegram Token and the Receiver ID into our Python script to send the stock alert message to our Telegram Bot.

Line 1: Define a Python function to send alert message via our Telegram Bot. This function will accept one input text as its parameter.

Line 2–3: Copy and paste our own Telegram token and the Receiver ID here. Please note the Receiver ID is not a text but a number.

Line 4: Use the token to establish connection with our Telegram Bot.

Line 5: Send the input stock alert message to our Telegram Bot using the Receiver ID.

Line 7: Invoke the function to send the stock alert message to our Telegram Bot.

We shall observe a stock alert message sent to our Telegram Bot as below.

Image Prepared by the Author

Stage 5: Scheduling Stock Alert Messaging

At this stage, we have completed all the steps required to build a stock alert messaging system. However, we will still need a scheduler to automate the alert messaging process at a specific time interval without human intervention. This scheduler will automatically run the Python script to obtain the latest real time stock data, generate stock alert message and send the message to the Telegram Bot.

Here we will use a lightweight Python module, Timeloop, as our scheduler.

Line 1: Create a Timeloop object.

Line 3: Set the Timeloop job as a Python decorator. Specify the timedelta to 60 seconds so that the Python function beneath it (run_tasks) will be repeatedly invoked for every 60 seconds.

Line 4–8: Define a Python function that encapsulates the entire process of generating and sending stock alert message to our Telegram Bot.

Line 10: Start the scheduler to run the function, run_tasks(), for every 60 seconds.

Finally, we shall see a stock alert message is generated and delivered to our Telegram Bot every 1 minute.

(To terminate the scheduler, we can press “cltr” + “c”)

Image Prepared by the Author

Afterwords

We have just managed to create a stock alert messaging system using Python. The Timeloop module used in this work is a very lightweight scheduler. In a more advanced system, Apache Airflow or Luigi may become a more ideal choice.

Besides, the Telepot library has also no longer been supported and updated by its developer. However, Telepot still remained a particularly useful tool to connect Python to Telegram, due to its much easier code structure compared with another equivalent Python libraries. Another alternative library is pyTelegramBotAPI.

I hope you enjoy reading this article.

Subscribe to Medium

If you like my article and would like to read more similar articles from me or other authors, feel free to subscribe to Medium. Your subscription fee will partially go to me. This can be a great support for me to produce more articles that can benefit the community.

References

  1. https://site.financialmodelingprep.com/developer/docs
  2. https://telepot.readthedocs.io/en/latest/
  3. https://github.com/sankalpjonn/timeloop
Python
Finance
Programming
Data Science
Stocks
Recommended from ReadMedium