Creating a Stock Price Tracker with Python

In some of my previous posts, we learned how to value a company using multiples, the Discounted Cash Flow Method, etc. In this post, 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. In my next post, we will learn how to have the stock price alert Python script running continuously in a Raspberry Pi.

Creating a Stock Price Tracker with Python
Photo by Anna Nekrashevich 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 in this post. 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:

Send email with Python

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:

stock price alert with Python
stock price alert with Python

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

Stock Price Tracker with Python

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.

In addition, I would recommend you to have a look at the following post where we learn how to have the script continuously running in a Raspberry Pi.

If you like my blog about Python for Finance, I would appreciate if you can share it in your social media channels.

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('[email protected]',password)
  subject= 'test'
  body = 'price down'

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

  server.sendmail(
  '[email protected]',
  '[email protected]',
  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 in codingandfun.com 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.

3 thoughts on “Creating a Stock Price Tracker with Python

Comments are closed.