Bots Manage your Stock Portfolio

DeepBytes
4 min readMay 17, 2022

--

I work in the upstream sector of the Hydrocarbon Industry and I must confess, at times it is extremely engaging and exhaustive that I am completely cutoff from what happens in the outside world. Many times there is travel with some being remote locations completely cutoff from news. There are projects with short deadlines demanding complete attention during all working days endlessly for months. I am sure there are many like me working in different parts of the world in diverse avenues but can relate to the kind of work-life situation I am describing.

I had invested in the stock market just of millions of people around the world and as we all know the last 2–3 years has been extremely volatile when it comes to stock markets with plenty happening all around us and I found it very hard to keep track of my portfolio. That’s when I decided to create a bot which updates me everyday with what is happening to my portfolio so that I can make timely decisions and I am going to demonstrate how to do it. At the end you will create a program which will send periodic updates to the price changes happening in your portfolio via telegram. So let’s dig in then.

First create a ‘*.csv’ file having your shares listed as below using the naming convention present in Yahoo Finance as shown below. I have created a sample list called ‘Portfolio_shares.csv’.

Sample Portfolio Created for Reference

I am going to use Python and Telegram to create my program with my bot and we need to install the following libraries apart from the commonly used one's in Python.

pip install telethonpip install yfinancepip install telebot

Next we need to create a ‘bot’ on Telegram which is simple. Just type ‘@BotFather’ in the Telegram search box and select the @BotFather profile. Then type ‘/newbot’ which will prompt you to type the name of your bot. Choose a unique name and type it, viola its done. You have created your bot. Now each bot has an associated token to access which is unique and you need to keep it safely, perhaps take a screenshot and we will use this soon.

Now its time to activate your bot and just type your bot name in the search in telegram ‘@Botname’ and select it. Now type ‘/start’ to kickstart your bot into live action.

Next we need to register the Bot application with Telegram and in order to do that we need to login into telegram and go to the following URL and fill out the form in API development tools:

https://my.telegram.org/auth?to=apps

The important parameters controlling your Bot transactions are your ‘Bot’ or ‘Chat’ ID and Token ID. In order to find the Chat ID we need to go to the following URL where we replace <yourtoken> with the Bot token:

https://api.telegram.org/bot<yourtoken>/getUpdates

We should be getting something like the following, and if not we need to check if the Bot is started and the Bot Application form is filled out:

{"ok":true,"result":[{"update_id":76xxxxxxx,
"message":{"message_id":450,"from":{"id":24xxxxxxx,"is_bot":false,"first_name":"Name","last_name":"Name","username":"username","language_code":"en-US"}

In the above message do note down the Chat ID which usually ends with ID. This is a one time process and we don’t have to do this each time we run the application.

Now we are all set to launch the application which I created as follows with requisite libraries. I am running my program in Google Colab as I can access it easily and do not necessarily need a laptop to access:

import numpy as npimport pandas as pdimport yfinance as yfimport timefrom os import systemfrom datetime import datetimeimport requestsimport telebotfrom telethon.sync import TelegramClientfrom telethon.tl.types import InputPeerUser, InputPeerChannelfrom telethon import TelegramClient, sync, eventsimport iofrom google.colab import files

I create a function which monitors the rise or fall in my stock price and if it is above or below 2% (the threshold can be changed on convenience) I want a notification on my phone.

def wat(nam,bpri,dpri,cpri):     itr=0     tex=[]     if (cpri-dpri)/dpri<-0.02 or (cpri-dpri)/dpri>0.02:       itr+=1       per=((cpri-dpri)/dpri)*100.00       tex.append(nam+' for the day is '+str(per))return(tex)

Next I create a function which reads all my stocks from the ‘.csv’ file created earlier and tracks the latest price and volume from Yahoo Finance every 15 minutes. It sends information required to the function defined earlier to compute the share price changes and also to the bot for sending messages via telegram.

def job():     flag=0     dat=pd.read_csv(io.BytesIO(uploaded['Portfolio_shares.csv']))     shares=[]     for i in range(0,len(dat)):       data = yf.download(tickers=dat['Share'][i], period='1d', interval='15m')       if(data.empty):         flag+=1         shares.append(dat['Share'][i]+' not traded in session')       else:         b=float(dat['Invested'][i])         d=float(data['Open'][0])         c=float(data['Close'][-1])         shares.append(wat(dat['Share'][i],b,d,c))     test = telegram_bot_sendtext("===Portfolio Performance of Day===")     print(test)     for j in shares:       if len(j)>0:         str=" "         test = telegram_bot_sendtext(str.join(j))         print(test)         print('\n')

Next we create a function which defines the functionality of the bot to relay information into your telegram account.

def telegram_bot_sendtext(bot_message):     bot_token = '53xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'     bot_chatID = '5xxxxxxxxxxx'     send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message     response = requests.get(send_text)     return response.json()

The last step now is to call all your functions and let the program run until market closes by comparing the system time with the market closing time. I have kept it to 15:15 hrs and this can be changed as per user convenience.

trade_time=1while trade_time==1:     system('cls')     now=datetime.now()     current_hour = now.strftime("%H")     current_min=now.strftime("%M")     if int(current_hour)<15:       job()     else:       if int(current_hour)==15:        if int(current_min)<=15:           job()        else:           trade_time=0       else:         trade_time=0     time.sleep(900)

That’s it your program is ready and it sends periodic updates to your telegram account about the price changes in percentage happening in your portfolio every 15 minutes for the day. Feel free to add other suitable modifications to make this better. Thanks for reading!!!

Here’s a sample on how you will be receiving the updates.

Bot in action

--

--