Get Instant BSE Stock Alerts using PushBullet API

We all want to know what’s happening to the stocks in our portfolio so we can stay on top of things. Stock alerts are one of the ways by which we can keep an eye on our stocks of interest to keep abreast of latest happenings, be it financial results, board meeting outcomes, dividends, FDA warnings, material changes, debts etc.

At present, our options to get such stock related alerts is limited to checking stock exchange websites, business news channels & finance related websites, Twitter accounts, and paid stock alert websites.

Barring stock alerts websites & sometimes Twitter accounts of Business channels, the stock news relayed to us is always delayed by few minutes to few hours. The lag is mainly due to the processing of information, composing tweets or writing articles. The best place where such stock news is disseminated or relayed instantly is stock exchange websites.

National Stock Exchange (NSE) relays all stock related announcements here – NSE Announcements

Bombay Stock Exchange (BSE) disseminates all stock related announcements here – BSE Announcements

Though we get stock announcements immediately on NSE & BSE websites, we have to keep refreshing them and pour through all announcements to get relevant news on your stocks. It’s like trying to find a needle in a haystack. This task is not only menial but also time-consuming. What if, if we can automate all of these tasks and get the Stock alerts instantly on your mobile phone or desktop PC when some news or announcement related to your stocks get posted on the stock exchange websites. Is it possible? And how hard it is to do it?.

Yes, it is possible and it’s not very hard to do it. A few lines of code and some effort on a server or Linux station.

Steps to get BSE Stock Alerts

Here, I will guide you through the steps required to get BSE stock alerts using PushBullet API but need some amount of programming knowledge. For non-programming people, here is an alternative solution.

Announcements Website URL:

We need to get the right announcements website URL from which we can scrape the data. We are going to use BSE website because it is easier to scrape data from here. The URL that we are going to use to scrape the data is BSE Announcements webpage.

Scrape Data:

To scrape the data we need the right tools. Python programming language has the best tools out there to scrape website data. If you are able to get it done in any other programming language that you are familiar with, please do so.

Within the Python code, we are going to use the ‘requests’ python module to scrape the data and use ‘regular expression’ module to get structured data from the scraped data.

import requests, re

###Scraping the Website

url = "http://www.bseindia.com/corporates/ann.aspx"
r = requests.get(url).text
stockannouncements = re.findall("

",r)

After that, we make a list of our stocks as a BSE security codes in a pickle (a computationally faster to read data format) and read from it.

import pickle
##List of Stocks we want to Screen( choose from nifty50,nifty100,nifty200,nifty500)
with open('nifty100.pkl','rb') as f:
nifty100 = pickle.load(f)

seclist = nifty100['Security Code'].values

Then we look for our stock in the announcements using the BSE stock’s security code. Once our stock is found, we structure the data of the announcement related to the stocks into a headline and body message, so that we can push the notification in a proper format.

###Looking for Our Stocks of Interest in the Announcements

for info in stockannouncements:
seccode = re.findall("- (\d{6}) -",info)
loc = [i for i,x in enumerate(seclist) if x == int(seccode[0])]
if len(loc)>0:
headline = re.findall(">([A-Z].*?)

<a class="tablebluelink" href="(.*?)" target="_blank">",info)</a>

##Structuring Head & Body of Notification
if len(headline)>0 and headline[0].replace('','') not in duplicates:
body = re.findall("\d{2}

(.*?$)",info)
try:
head = headline[0].replace('','')+'\n'
bodymessage = (body[0]+'\n\nLink to attachment:\n'+pdflink[0]+'\n')
ofile.write(head)
print (head,bodymessage)
##Pushing the Notification
push = pb.push_note(head,bodymessage)
except IndexError:
pass
time.sleep(2)

PushBullet API:

Since we have all the data required in a proper format after scraping the website, we need a way to push this information onto our mobiles and desktop PC. Here, we will use PushBullet API do that job of pushing the notifications.

First, we register on PushBullet website

PushBullet Website

After that follow the instructions on the site to set-up your mobile or desktop PC.

For the push notifications to work we need to use PushBullet API & can be accessed using the API Key. You can get the API key by going to “Settings” & then under “Access Tokens” click “Create Access Token”. It will create an API key for your account which will look like this

API Key: o.uvaVlngkt98QbvUZap8Y2kg5lJaSDHzx (this is just dummy API Key for demo purpose)

Push Notifications:

In order to push the notifications via PushBullet API, we will use PushBullet.py python library in our python code. Follow instructions on the PushBullet library’s webpage to install it.

Now we import the pushbullet library module and push the notifications using the following code. For this code to work, please replace the dummy API Key below with your own API Key.

from pushbullet import Pushbullet

##Pushbullet API Key

pb = Pushbullet('o.uvaVlngkt98QbvUZap8Y2kg5lJaSDHzx')

#Push Notification using headline & body message we got earlier

push = pb.push_note(head,bodymessage)

Final Code:

Here is the usable complete Python Code

import requests, re
from pushbullet import Pushbullet
import pandas as pd
import pickle, time

##List of Stocks we want to Screen( choose from nifty50,nifty100,nifty200,nifty500)
with open('nifty100.pkl','rb') as f:
nifty100 = pickle.load(f)

seclist = nifty100['Security Code'].values

##To Avoid Duplicates
ofile = open('Duplicates.txt','a+')
dupfile = open('Duplicates.txt','r').readlines()
duplicates = [s.rstrip() for s in dupfile]

##Pushbullet API Key
pb = Pushbullet('o.ElkAFoSmb3LcNuMIwP6VYNTsMzTwVsMU')

###Scraping the Website

url = "http://www.bseindia.com/corporates/ann.aspx"
r = requests.get(url).text
stockannouncements = re.findall("

 

",r)

###Looking for Our Stocks of Interest in the Announcements

for info in stockannouncements:
seccode = re.findall("- (\d{6}) -",info)
loc = [i for i,x in enumerate(seclist) if x == int(seccode[0])]
if len(loc)>0:
headline = re.findall(">([A-Z].*?)

<a class="tablebluelink" href="(.*?)" target="_blank">",info)</a>

##Structuring Head & Body of Notification
if len(headline)>0 and headline[0].replace('','') not in duplicates:
body = re.findall("\d{2}

(.*?$)",info)
try:
head = headline[0].replace('','').strip()+'\n'
bodymessage = (body[0]+'\n\nLink to attachment:\n'+pdflink[0]+'\n')
ofile.write(head)
print (head,bodymessage)
##Pushing the Notification
push = pb.push_note(head,bodymessage)
except IndexError:
pass
time.sleep(2)

ofile.close()

Set-up Cron Job:

According to Wikipedia, Cron is a time-based job scheduler in Unix-like computer operating systems. People who set up and maintain software environments use Cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals.

So, why we need to setup a Cron Job?.

Since the announcements information keeps flowing on the BSE website, we need our python script to check the website every few minutes & send us relevant stock alerts. This is especially important during the market hours when the stock swings wildly on the news flow, so that you can be prepared to take advantage of the good news or get our of stock on bad news or as you see fit.

A Cron job can be easily set-up on any Linux station like Ubuntu Desktop or on any Linux (or windows) based servers. Here I will show how we can set-up Cron job to run our python script every one minute on Ubuntu server (applied for desktop as well)

Type following command in the command line shell

sudo crontab -e

This will open the Cron job file. Add the following code to it

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
*/1 8-16 * * 1-5 /home/PATH TO YOUR FOLDER/myscript.py >/dev/null 2>&1

Replace “PATH TO YOUR FOLDER” on the second line with your path to the folder where the script is located. Change myscript.py to whatever name you are going to give the script. Then press “Escape”, followed by “:wq” and “Enter/Return” key to save the file.

What we are telling in the Cron Job file is to run the python script every 1 minute from 8 AM to 4 PM and from Monday to Friday. That will cover the pre-market, market & post-market hours.

Download the files & test

Finally, download all the files, including python script, in the zip folder and unpack it. Replace dummy API key with your API key in the python script. Run the script from the command line or your favorite IDE to see the result.

You will get an stock alert like this

Stock Alerts via PushBullet

Stock Alerts Notifications from BSE via PushBullet

Before running the script, please set-up at least one device (mobile or desktop PC) on the PushBullet site, so you can receive the notifications.

DOWNLOAD FILES

PS: I’m not a great coder and the code may not be very efficient, so fellow coders do drop in your suggestions in comments on how to make it even better.

Posted in Fundamental Analysis, Stocks.

9 Comments

  1. Pingback: Get Indian Stock Alerts via PushBullet | TradersLounge

  2. Hey This is super awesome work you have done. Though I faced one difficulty that when annonucement contain following text, your script fails to compare it from duplicates and gets into a loop to send this particular update plenty of times!
    Example headlines :
    DEWAN HOUSING FINANCE CORPORATION LTD. – 511072 – Allotment Of Secured Redeemable Non-Convertible Debentures (NCD’S).
    Indiabulls Housing Finance Ltd – 535789 – Allotment Of Secured, Redeemable, Non-Convertible Debentures On A Private Placement Basis – Intimation Under SEBI (Listing Obligations And Disclosure Requirements) Regulations, 2015.
    Can you help me rectify what changes will fix this?

  3. I did the same using beautiful soup but after a certain hits to the bse url from local host it blocked me .

    I haven’t used the headers for the request and neither you.

    Then how come it doesn’t block you .

    I had hit that url around 25 times in two hours.

  4. Thank for the help bro. It works..
    One thing I need to modify is I want all bse stocks not just nse50 or nse500. And I just want results updates.
    For url I have changed it to results url from announcements url.
    But I am stuck on stocks part.. I think I need to make a pkl file of all bse stocks. How to do that? Help will be appreciable.

  5. I couldn’t implement this to realize the awesomeness people have expressed here as I am stuck at the very first step figuring out where I have to try this code, “server or Linux station”? I have Windows 10 Professional installed on my machine. How do I get by implementing this on my machine? Please provide some guidance. Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *