Automatic email notification on stock market share price change

For some days I was monitoring the share price in trading market. Generally I target share of a company (mostly from Nifty 50 as I am noob)…check the technical indicators…If indicator gives me green signal, I make a target that if the share reaches X amount then I buy/sell. I need a system where from I can be notified that price of a share reaches at X amount. There are multiple service available in internet. Most of them are either paid or complex. I needed a simple solution for the problem. I thought of automate this via Google App Script which has capability to do such thing easily.

What I need for developing such solution?

  1. Website where from live share price can be collected
  2. Method to extract the share price
  3. A place where share price limit can be stored and can be compared with current price.
  4. Email notification mechanism

1. Website where from live share price can be collected

There are some api (mostly paid) available from which live share price can be grabbed. There is another way around which can be done at no cost. Some website provides live share information (like moneycontrol). We can parse those website html data and extract share price.

2.  Method to extract the share price

We will use google script to parse website html data and extract exact share price data. Google Apps Script is a JavaScript cloud scripting language that provides easy ways to automate tasks across Google products and third party services and build web applications (definition copied from Google Apps Script official website).

3. A place where share price limit can be stored and can be compared with current price

For storing data we will use Google Sheet. Its a Google product and nicely compatible with Google App Script.

4. Email notification mechanism

Its none other than Google Mail aka GMail.

Let’s start coding…

First create a Google Sheet. You can copy my Demo Sheet. Rename the sheet name as MasterData. Create some column header like below

Tenco Trade Table Data
Stock ID : Stock code. You can use any id/name of the stock by which you can recognise the stock.

Current Price: Our script will extract the share current price from website and store here.

Lower Alert Price: We will keep some lower alert price. If the current price becomes lesser than lower alert price then it will send email notification and we can think of buying the stock.

Higher Alert Price: Similar as lower. We will keep higher price range here. If current price becomes more than higher price then we can sell the stock.

URL: Here we will keep the url of the website which will be parsed via script and extracted the current stock price data.

Last Updated Date: It is just used for logging purpose. We will store the date when the data got updated.

Now our database is almost ready… Oh! one more thing we need to keep: the email id… somewhere which will be get notified once the current price will cross the range. For that create another sheet/tab (down below). Name as Config. We can write some configuration related data here. Write Email ID as key and <your email id> as value.

Lets deep dive in coding part.

In Google sheet, click Tools -> Script Editor. It will open the Google Script editor where we can start wring our javascript code.

Please find below the full code at the end of the post. It self explanatory but let me just tell the key points.

In myFunction() first get all the existing value from Google Sheet and assign it some variable.

Create a function getHTML which will accept URL and get the HTML code from internet.

Create a function getCurrentPrice which will take the HTML code, parse it and find the stock price. In every website, there is a specific DOM structure where from specific data can be extracted. Here we have used parser library to parse the HTML code. To add the parser library click on Resources ->  Libraries… add the project key M1lugvAXKKtUxn_vdAG9JZleS6DrsjUUV

Parser Library

Thanks to Kutil for the idea of parser library

Create a sendEmail function which will use MailApp.sendEmail function to send email via Gmail.

So for every rows in the sheet, first it will get the complete HTML code from internet for specific URL. It parses the HTML code and extract the current price. It compares the current price with predefined lower or higher price range and send notification to certain email id. As simple as that.

For testing purpose select myFunction in dropdown in menu bar and run (play button). Initially it will ask for authorization (e.g. TencoTrade_Blue needs your permission to access your data on Google.) Click on Review Permissions, Sign in with you gmail id and allow. If it runs properly, you can see current price is changing and Last updated date column is updating.

To add a new stock data in watchlist, goto moneycontrol website. Find stock, copy the URL and fill your google sheet table with necessary information.

To run the script automatically, In the Google Script Editor click on Edit -> Current Project Trigger-> Click add new trigger and create trigger as per your requirement. I run the script in every hour. Do not run the script frequently (like every second) this will create unnecessary traffic in Moneycontrol website and your IP can be blocked/blacklisted for further service.

This can be customised more. Like Send Daily Status, Run the script only in Market hour, Send SMS etc… If you find more idea or features to be implemented, please let me know in comment section. The source code can be found below. Updated source code can be found in https://github.com/sonu041/TencoTrade. The code is opensource, You can contribute there in Github as well.

/*
* Stock Data Notification.
* Developed by: Shuvankar Sarkar
* GitHub: https://github.com/sonu041/TencoTrade
* DemoGoogleSheet: https://docs.google.com/spreadsheets/d/1fIfQh18F0CSko1UdPj4WXpfVONHgCbBeFzop_fzkrFE/edit?usp=sharing
* Date: 01-Aug-2018
*/

function myFunction() {
var lowerAlertPrice, higherAlertPrice, url, currentPrice, monConData;
var masterSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("MasterData");
var configSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Config");
var emailid = configSheet.getRange("B1").getValue();
var vals = masterSheet.getRange("A1:A").getValues();
var last = vals.filter(String).length;
var data = masterSheet.getDataRange().getValues();
for (var i = 1; i &amp;lt; last; i++) {
lowerAlertPrice = data[i][2];
higherAlertPrice = data[i][3];
url = data[i][4];
monConData = getHTML(url);
currentPrice = getCurrentPrice(monConData);
masterSheet.getRange("B"+(i+1)).setValue(currentPrice);
masterSheet.getRange("F"+(i+1)).setValue(Utilities.formatDate(new Date(), "GMT+5:30", "dd/MM/yyyy hh:mm:ss"));

//If current price reaches target price then send mail.
if (currentPrice &amp;lt;= lowerAlertPrice) { sendEmail(emailid,"Alert! Price reduced for "+data[i][0], "Price reduced for "+data[i][0]+": " + currentPrice); } if (currentPrice &amp;gt;= higherAlertPrice) {
sendEmail(emailid,"Alert! Price increased for "+data[i][0], "Price increased for "+data[i][0]+": " + currentPrice);
}
//Todo: If current price is 52 weeks lower then send mail.

//Pause for some moment to avoid DOS in Moneycontrol.
Utilities.sleep(1000);
}
}

function getCurrentPrice(content) {
var fromText = 'id="Nse_Prc_tick"&amp;gt;&amp;lt;strong&amp;gt;';
var toText = '&amp;lt;/strong&amp;gt;';

//Thanks to https://www.kutil.org/2016/01/easy-data-scrapping-with-google-apps.html for the Parser library.
var scraped = Parser
.data(content)
.from(fromText)
.to(toText)
.build();
//Logger.log(scraped);
return scraped;
}

function getHTML(url) {
var content = UrlFetchApp.fetch(url).getContentText();
return content;
}

function setHTML() {
}

function sendEmail(emailAddress, subject, message) {
MailApp.sendEmail(emailAddress, subject, message);
}

// TODO: Only send mail in market hours
function isMarketHour() {
}

// TODO: Send Daily Status mail
function sendDailyStatus() {
}

One response to “Automatic email notification on stock market share price change”

  1. Bikram says:

    A very useful post.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.