Creating a Stock Price Tracker with Python

Build a Python script to send you an email every time the price of your favourite stock goes down in price.

Jose Manu (CodingFun)
Analytics Vidhya

--

During this story, we are going to create a stock price tracker with Python. That is, a Python script that will send us an email every time the price of a particular stock goes below our valuation threshold.

Photo by Burak K on Pexels.com

Apple Stock Price Tracker

To build the stock price tracker with Python we will track the price of Apple. When the price is below a pre-defined threshold, the script will send us an email to our Gmail account letting us know about the price drop.

This is particularly useful in case we have fixed a target price for a stock and we want to be informed once the prices reaches down that level.

I will put the code below in one piece. The reason for this is that the code is rather simple. We will use financialmodelingprep in order to request real-time quote prices of the stock that we want to track. In this case, Apple. Note that you need to sign up to financialmodelingprep in order to get an API key with up to 250 API requests free per month.

Then, we compare the most current stock price to our price threshold. In this case, I have defined a stock price threshold of $140.

If the stock price of Apple is below $140, we will trigger the send email function that will send us an email to the given account. In the next section, I explain how to build such function.

Building the Send EmailFunction

The send email function is where we configure the code to send us an email. We will use the library smtplib in order to achieve this.

Using Smtplib we will:

  • Create a SMTP connection
  • Define our message, subject and recipient
  • And send the email

The code below follows the smtplib documentation to create a connection and start the server. Since it is a bit technical, I will not cover the details on how SMTP connection works in this story. You can have a look at the documentation for additional information.

What is important is to pass your Gmail account and Gmail password within the object server.login(‘your gmail’ , ‘your password’). In the code, my Gmail password is stored in the password variable.

Within server.sendmail, we pass the recipient of the email and the message (i.e. msg).

For the send email function to work, we need to go to Google and activate the Less secure app access in our account. Otherwise, Gmail will not let Python send an email on your behalf. To activate the less secure app access, google Less secure app access and open below link.

Then, ensure that below option is marked as ON:

To finalise the Python script, we simply include a while loop to ensure that the script runs uninterruptedly (you can stop the script by pressing ctrl/cmd + c). That will make sure that Python checks the stock prices of Apple every 10 minutes to see if the stock price has moved. This is achieved by the line time.sleep(600).

When we run the code and the stock price is below $140, we will get an email in our Gmail account:

To see the code in action, feel free to have a look at below video:

Wrapping Up

Just with a few lines of code, we have built a script to send us an email in case the price of our favourite stock moves down to a predefined level.

You can further improve the code. For instance, tracking the price of multiple stocks simultaneously. Or instead of sending an email based on price, you can send emails based on returns.

import requests
import smtplib
import time

api_key = 'asdfadsf adsf af'
password= 'tesasdfdsafads'

def send_mail(password):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login('codingandfun@gmail.com',password)
subject= 'test'
body = 'price down'

msg= f'subject: {subject} {body}'

server.sendmail(
'codingandfun@gmail.com',
'codingandfun@gmail.com',
msg
)
print('email is sent')
server.quit()


def price_tracker(api_key,password):
prices = requests.get(f'https://financialmodelingprep.com/api/v3/quote/AAPL?apikey={api_key}').json()
stockPrice = prices[0]['price']
print(stockPrice)
if stockPrice < 140:
send_mail(password)

#run evrey 10 minutes
while(True):
price_tracker(api_key,password)
time.sleep(600)

Note: All posts and videos are only intended for educational purposes. We do not offer financial advise. Also, we do not recommend you to buy or sell any stock. You are responsible to perform your own due diligence before investing or trading any security.

Originally published at https://codingandfun.com on January 2, 2021.

--

--

Jose Manu (CodingFun)
Analytics Vidhya

Python for Finance. Learn step by step how to automate cool financial analysis tools.