Python script to check stock prices for nerds who invest

Programming in Python is great. By watching a few YouTube videos one can learn Python in a short amount of time. Python is versatile from scheduling an automated joke in Twitter, to hosting a website, to providing Air Traffic Management and Public Safety & Transport. Python is used in both personal and professional applications.

In this brief article I’ll demonstrate how to create a Python script that can check on stock prices and send an email alert when the price is at your choosing. I won’t talk about stocks or the benefits of investing in mutual funds but I will demonstrate everything that you will need in order to be alerted to a predetermined price.

Why is this post relevant? Because most investment sites require a paid subscription or buy-in with their firm in order to provide you with price alerts. My option: free.

To get started I assume you have Python installed (I’m using version 3.6). I’ll also be using a Google email server to send email. If you don’t have a Gmail account you can sign up for free via Gmail.

Finally, I’ll be using Tiingo.com to rely on daily closing prices. We’ll be using the Tiingo API so head over to Tiingo.com and create an account. Once the account is created select Account in the top-right corner:

Next, on the left-hand side click API and generate your unique token:

Next we’ll install the Tiingo client library for Python. Open up a Windows command prompt as admin (right-click command prompt and click Run as administrator) and type:

pip install tiingo

Once you have your Tiingo API token and Tiingo library for Python open IDLE for Python:

Create a new file and save to a location you can access later. Next, paste the code below:

from tiingo import TiingoClient
import smtplib


config = {}
me = 'your gmail email'
you = 'email to send to'
password = 'gmail password'

config['session'] = True

config['api_key'] = "Tiingo API token"

try:
    stock = 'your stock symbol here'
    client = TiingoClient(config)
    ticker_price = client.get_ticker_price(stock)
    close = ticker_price[0]['close']

    if ticker_price[0]['close'] > YOUR PRICE AS A NUMBER HERE:
       message = '{} is {}'.format(stock, close)
       s = smtplib.SMTP('smtp.gmail.com', 587)
       s.starttls()
       s.login(me, password)
       s.sendmail(me, you, message) 
       s.quit()
       print('Email sent.')
except:
    print('Something went wrong!')


That’s it! If the closing price of your investment is greater than the price you provided in the script then an email alert will be sent so that you can take action.

Leave a Reply

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

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