How to code a Telegram Bot to get stock price updates in pure Python – Best Telegram

How to code a Telegram Bot to get stock price updates in pure Python

Create your own personal stock updates slave

The telegram bot I will be referring to in this article is Stock Updates Slave and source code can be found here on this GitHub repository).

Photo by Christian Wiediger on Unsplash

You might be thinking, why do we even need a service to update us of our portfolio holdings? Truth is, most of us are too busy with our daily lives and brokerage platforms that we are subscribed to provide such services but their push notifications come in the form of emails or mobile-app alerts that we are almost never inclined to click on or open. Telegram bot alerts are hence more useful because it is integrated into our day-to-day messaging application which we are a lot more likely to click on.

Demo of my telegram bot (GIF by author)

Before we start, here are some prerequisites to build this simple telegram bot:

  1. Basic to intermediate-level Python
  2. Basic understanding of how APIs work
  3. A Telegram account
  4. A Heroku account (for deployment)
  5. A GitHub account (for deployment)
  6. SQL Alchemy (optional, for database purposes) [NOT COVERED]
  7. AWS Account (optional, for serverless CRON jobs) [NOT COVERED

Without further ado, let’s get started!

First off, we will need an API to get the price changes for our stocks we have in mind. For simplicity, we will be using the yfinance, a library that is maintained after the Yahoo! Finance API was decommissioned. Its API is written in Python and we will also be using a Python-based library for the Telegram API known as python-telegram-bot.

We will first create a simple script based on the yfinance API to obtain price movements for an input ticker. Next, we will setup the Telegram handler to listen for requests made to the bot.

Step 1: Create a script to obtain price changes using yfinance

The script below takes in a ticker as input, with a lookback period as an optional argument, and returns a Tuple consisting of the percentage change in the first index and the list of closing values that contribute to the percentage change (mainly for extracting the exact prices if necessary) in the second.

Step 2: Create a telegram bot with Botfather

Follow the instructions on the bot to setup your bot (yes, you’re using a bot to create a bot —i.e., bot-ception). At the end of it, you’ll be given a bot token that is required to access the HTTP API. Take note of this token. We will use this in the next step.

Step 3: Export this token as an environment variable so our app can use it later.

From the command line, run:

export TELEGRAM_BOT_TOKEN=<YOUR_BOT_TOKEN_HERE>

Step 4: Create an telegram_bot_app.py that is our Telegram bot

This telegram bot only has a single command — get_px_change — which is initiated using the / command. On telegram, to get the price change for the AMZN ticker, run /get_px_change AMZN after serving the app locally via python -m telegram_bot_app.

Step 5: Register this command on Telegram so that it is more intuitive for users to know that this command exists

Go back to BotFather to register this command get_px_change via /setcommands. It might also be worth including a command like start to inform users how to use your bot.

FYI: Command handlers start with / and appear in the command list.

Note: Instead of command handlers, a conversation handler can also be used in conjunction with a keyboard markup (as seen in the above GIF). The latter may be more intuitive and convenient for users to navigate around.

More notes: It is best practice to have error handlers to handle unidentified commands.

Step 6: Place the scripts on a GitHub repository for easy deployment on Heroku

However, before we can deploy on Heroku, we need to define our environment. To do so, we need two new files:

a) Procfile — this tells Heroku the type of application and also the command to run after setting up the environment. It will consist of only this line:

web: python -m telegram_bot_app

b) requirements.txt — this defines the environment requirements of a typical Python-based application. It should look something like this:

pandas==1.0.1
numpy==1.18.1
yfinance==0.1.54
python-telegram-bot==13.1

The folder structure should look like this:

.
├── telegram_bot_app.py
├── ticker.py
├── Procfile
└── requirements.txt

Push these files to a GitHub repository on the main/master branch.

Step 7: Deploy this app on Heroku

If you don’t have an account with Heroku, create one and also install the Heroku command line interface (CLI).

a) Next, create a new project via the CLI:

heroku create <project_name>

b) Set the telegram bot token as an environment variable.

heroku config:set TELEGRAM_BOT_TOKEN=<YOUR_BOT_TOKEN_HERE>

c) Modify your telegram_bot_app.py to listen to webhook events.

d) Push your GitHub repo to the Heroku remote. Note that Heroku will only build if you push to the main or master branch. From your git repo, run the following:

git push heroku master

Voila! There you have it — your own Python-based Telegram Bot! You can of course extend the functionality of this bot by adding more functionalities and adding more command/message handlers.

Do check out my Stock Updates Slave if you’d like daily updates of your portfolio holdings!

For more advanced users, feel free to check out my git repository to find out how I set up a PostgreSQL database to keep track of the stocks in user’s portfolio and/or watchlist, and also his/her subscription status. My bot also supports bi-daily updates (push notifications) on your watchlist and/or portfolio if you’re subscribed to it. This is done via a serverless CRON job setup using AWS Lambda. Heroku also supports scheduled jobs so that could also be an option.

Closing Remarks

Finally, if you’ve enjoyed this article and would like to find out more, do consider giving this a clap (up to 50!) and leaving a comment if you’ve any feedback. Thank you!

If you like my content and are not subscribed to Medium, do consider supporting me and subscribing via my referral link here (NOTE: a portion of your membership fees will be apportioned to me as referral fees).

Ten articles before and after

How to create a Telegram-RAT (Remote Access Trojan)-2020 – Best Telegram

How hackers are getting access to 1000s of Telegram accounts – Best Telegram

ParaState — Telegram AMA — April 04 – Best Telegram

BlockBank — Telegram AMA — April 02 – Best Telegram

Crowdholding Telegram Airdrop Announcement – Best Telegram

How to build a Telegram BOT to suggest you pizza – Best Telegram

Crypto Trading Bots — Are They Good For Telegram Messenger? – Best Telegram

Migrating to Slack Community to Telegram – Best Telegram

Release – PooCoin Price Bot – Best Telegram

How to be safer while using Telegram in Russia and Ukraine – Best Telegram