110|PYTHON – Automated Stock Information Email

BYU Student Author: @Mike_Paulsin
Reviewers: @Mark, @Hyrum
Estimated Time to Solve: 75 Minutes

We provide the solution to this challenge using:

  • Python

Need a program? Click here.

Overview
You are a young and ambitious stock trader who is always on the lookout for the next big investment opportunity. One day, you realize that you are spending too much time checking the stock prices for your favorite companies manually. You decide to build a Python program that can scrape the stock information from Yahoo Finance for a specific ticker and send it to you in an email, saving you time and effort.

The challenge requires you to create a Python script that can web scrape Yahoo Finance to find the stock information for a specific ticker. Specifically, you need to get the open, close, dividend yield, price to earnings ratio, and market cap. You then need to send this information in an email to yourself, all through Python.

Requirements

  • The program should allow the user to input the ticker symbol for the stock they want to monitor.
  • The program should web scrape Yahoo Finance to retrieve the latest stock information for the specified ticker.
  • The program should extract the open, close, dividend yield, price to earnings ratio, and market cap data from the web scraped data.
  • The program should format the extracted data into a user-friendly email template.
  • The program should send the formatted email to the user’s email address using a Python email library such as smtplib and/or EmailMessage.
  • The program should be well-documented with clear instructions on how to run and configure the program.

With this challenge, you can enhance your Python skills while also improving your ability to monitor stock information and potentially make better investment decisions. Leverage tools like Google and ChatGPT to navigate the different challenges of sending an email within python code.

Suggestions and Hints
  • Use the following modules in your code!
    from email.message import EmailMessage 
    import matplotlib.pyplot as plt 
    import smtplib 
    import requests 
    from bs4 import BeautifulSoup 
    
  • On your Gmail security settings, create an “app password” under your security settings. Use this password in your python code to avoid running into 2-step verification issues.
  • If you need further help on working with your gmail account to send emails automatically through python, click here.

Solution

Solution Code
from email.message import EmailMessage 
import matplotlib.pyplot as plt 
import smtplib 
import requests 
from bs4 import BeautifulSoup 

def getstockinfo(ticker): 
    # Send GET request to Yahoo Finance and parse HTML response 
    url = f"https://finance.yahoo.com/quote/{ticker}" 
    response = requests.get(url,headers=myheaders) 
    soup = BeautifulSoup(response.content, "html.parser") 
    soup = str(soup) 
    #print(soup) 

    # Extract financial data from HTML elements using text parsing 
    name = soup.split('<title>')[1].split('(')[0] 
    open = soup.split('OPEN-value">')[1].split('<')[0] 
    close = soup.split('PREV_CLOSE-value">')[1].split('<')[0] 
    marketcap = soup.split('MARKET_CAP-value">')[1].split('<')[0] 
    PEratio = soup.split('PE_RATIO-value">')[1].split('<')[0] 
    divyield = soup.split('DIVIDEND_AND_YIELD-value">')[1].split('<')[0] 

    return name,open,close,marketcap,PEratio,divyield 

def sendemail(): 
    #Enter gmail username and password 
    user_agent = 'Me' 
    myheaders = {'User-Agent': user_agent}  
    # Ask user for stock ticker symbol 
    tickerList = []  
    maxLengthList = 3 
    while len(tickerList) < maxLengthList: 
        ticker = input("Enter a stock ticker to get informtion on: ") 
        tickerList.append(ticker) 
    gmail_user = "youremail@gmail.com" 
    gmail_password = "****************" 
    for ticker in tickerList: 
        #run the getstockinfo function and define the respective variables 
        info = getstockinfo(ticker) 
        stockname = info[0] 
        open = info[1] 
        close = info[2] 
        marketcap = info[3] 
        PEratio = info[4] 
        divyield = info[5] 

        #create subject, name, and body of the email 
        subject = f'Daily Stock Information for {stockname}' 
        name = 'Mike' 
        body = f"""Hey {name}! 
 
            Here is your daily stock information for {stockname}! 

            Stock Ticker = {ticker} 
            Name: {stockname} 
            Open: {open} 
            Close: {close} 
            Market Cap: {marketcap} 
            P/E Ratio: {PEratio} 
            Dividend Yield: {divyield} 
            """ 

        #Initialize the email message 
        message = EmailMessage() 
        message['From'] = gmail_user 
        message['To'] = gmail_user 
        message['Subject'] = subject 
        message.set_content(body) 
        # Log in to the Gmail server 

        mail_server = smtplib.SMTP_SSL('smtp.gmail.com') 
        mail_server.login(gmail_user, gmail_password) 

        #Send the email 
        mail_server.send_message(message) 
        mail_server.quit() 
sendemail() 

Solution Video: Challenge 110|PYTHON – Automated Stock Information Email

Building a Python script to grab stock info from Yahoo Finance was a tricky ride through lots of complicated HTML and JavaScript stuff. I had to navigate through asynchronous loading and be extra careful to play by Yahoo Finance’s rules. The script wasn’t just about getting data; it used Python tools like BeautifulSoup and smtplib to smoothly send me the stock info via email. Understanding financial numbers, sorting through nested structures, and handling JavaScript-made things added more challenges. In the end, my Python script wasn’t just a tool; it was my guide through the web’s twists, ethical scraping, and understanding financial data, making coding feel like a cool adventure. It took me more an four hours to complete the python program. Here is my output for the website!
Screenshot 2024-01-16 at 1.32.04 PM