Notifications on your stock performance? A guide to Telegram bots

Would you like to receive automatic updates on the performance of your investments? A Telegram bot can cope with this request and do much more.

The featured bot sends you updates on the performance of your stocks. The set-up is free and requires no coding skills, just 10 minutes of your time. In case you also know how to code some basic python, the bot can be readily tailored to your specific needs.

Specifically, our bot does the following:

  1. Each time you text the bot, it will send you an update on the current performance of your stock
  2. The bot will send you periodic updates on market performance
  3. The bot sends alarm messages when a certain high or low price threshold is reached

What is a Telegram Bot? 🤖

Before configuring the bot, it is worth understanding how the Telegram bot system works. A bot is a mere Telegram chat with a tiny artificial brain behind it.

Whenever the Telegram user calls the bot by sending it a message, the message is transmitted to the Telegram server, which communicates with the bot server, as showed in the scheme below . Your server will issue a response, send it to the Telegram server, which will forward it to the Telegram user.

Initialization of Telegram bot

Now let’s set up the Telegram bot and your server following the step-by-step instructions below.

  1. Open Telegram on your mobile phone.
  2. Click on search and search for BotFather. Search for the verified BotFather chat with a blue V on the left
  3. Text /newbot to BotFather to create a new bot
  4. BotFather will ask you to enter a bot name. Enter a name (e.g. My echo bot)
  5. BotFather will then ask you to enter a bot username. Enter a username that ends with the word bot (e.g. echo_bot)
  6. BotFather will send you a message with a token to access the HTTP API. Save this string for later and keep it stored safely.

You can also change the bot description (text /setdescription to BotFather), bot image (type /setuserpic) or other attributes (type/help for more information). This is just a prompt. Let’s move on.

Creation of the Python script for the bot

If you are an inquisitive programmer, download the Python API for the telegram bot at this link. The code you need is the python script echo_bot.py, which is located in the folder pyTelegramBotAPI/Examples.

If you wish to build the bot straight away, find the same file but tailored to out needs in the Appendix at the bottom of the page.

Follow these steps.

  1. Create a python script somewhere on your pc. To create a python script, a simple workaround is to create a text file and rename the file to any name that ends in .py (e.g. rename the file echo_bot.py)
  2. Copy the python script in the Appendix below inside the python file you just created
  3. In the file, change the text CHANGE_HERE with the name of the company (any name), the name of the shares (as for the stock exchange listing), the amount of the purchase (any rational number) , the share purchase price (any rational number). See the following example. You could add multiple stock if separated with the commas as in the example.
  4. Replace ADD_TOKEN_HERE with the text/token BotFather sent you before

You can add as many investments as you wish as long as they are separated with commas in the example. Be careful to respect the pattern (apostrophes, spaces, etc.)

An example of the fields filled is below.

df = pd.DataFrame({
'company': ["Amazon", "Apple", "Alphabet"],
'stock': ["AMZN", "AAPL", "GOOGL"],
'purchasePriceUSD': [100, 150, 45],
'purchaseSharePrice': [3295, 137.59, 1503.01]})
API_TOKEN = '13lsdkjf07:AAFE-tldskjfklsdjflskjfklsdjfksldYw'

Set up a server

If you have a Python compiler, you could already run the code and test the output on Telegram. However, let’s set up a server directly and run the code on it.

  1. Browser pythonanywhere, a website where you can set up a server for free
  2. Create an account. It is free
  3. Go to Files and Upload a file, specifically the python script you just created earlier (e.g. echo_bot.py)

Now you need to set up the console

  1. Again in pythonanywhere, go to Consoles.
  2. Click on bash to start a bash console.
  3. Copy the code below and run it
mkvirtualenv --python=/usr/bin/python3.7 mysite-virtualenv
pip install pyTelegramBotAPI
# Install the libraries used to scrape data from yahoo finance
pip install pandas
pip install pandas-datareader
# Run the code
python3 echo_bot.py

Well done. Search your bot using the bot name on Telegram and test it by sending it a message! You will receive an automatic response about the latest stock movements.

Appendix

#!/usr/bin/python

# This is a simple echo bot using the decorator mechanism.
# It echoes any incoming text messages.

import telebot

###################
###### NEW ########
###################
import pandas as pd
from pandas_datareader import data
import datetime


def investmentMovements():
today = datetime.date.today()
df = pd.DataFrame({
'company': ["CHANGE_HERE", "CHANGE_HERE"],
'stock': ["CHANGE_HERE","CHANGE_HERE"],
'purchasePriceUSD': [CHANGE_HERE, CHANGE_HERE],
'purchaseSharePrice': [CHANGE_HERE, CHANGE_HERE]})

#df['currentSharePrice'] = [data.get_data_yahoo('AMZN',today, today)['Close'][0] for x in df['stock']]
#df['percentageReturn'] = [(row[1]-row[0])/row[0] for row in df[['purchaseSharePrice',df'currentSharePrice']].to_numpy()]
#df['returnUSD'] = [(row[0]+row[0]*row[1]) for row in df[['purchasePriceUSD', 'percentageReturn']].to_numpy()]


text = ""

totReturnUSD = 0
totInvested = sum([x for x in df['purchasePriceUSD']])

for row in df.iterrows():
currentSharePrice = data.get_data_yahoo(row[1]['stock'],today, today)['Close'][0]
percentageReturn = 100*(currentSharePrice - row[1]['purchaseSharePrice'])/row[1]['purchaseSharePrice']
returnUSD = row[1]['purchasePriceUSD']*percentageReturn/100
totReturnUSD += returnUSD
text = (text + row[1]['company'] + " {0:.1f}% {1:.2f}$ ({2:.2f}$ -> {3:.2f}$)\n".format(
percentageReturn, returnUSD, row[1]['purchasePriceUSD'], (row[1]['purchasePriceUSD']+returnUSD)))


text = (text + "\nTOTAL {0:.1f}% {1:.2f}$ ({2:.2f}$ -> {3:.2f}$)\n".format(
(100*totReturnUSD/totInvested), totReturnUSD, totInvested, (totInvested+totReturnUSD)))


return text


API_TOKEN = 'ADD_TOKEN_HERE'

bot = telebot.TeleBot(API_TOKEN)


# Handle '/start' and '/help'
@bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
bot.reply_to(message, investmentMovements())





# Handle all other messages with content_type 'text' (content_types defaults to ['text'])
@bot.message_handler(func=lambda message: True)
def echo_message(message):
bot.reply_to(message, investmentMovements())

bot.polling()

Engineer by background, strategist by profession, computer scientist by vocation, dreamer by nature. In short, I’m Nebuly’s COO.