Home » Blog

The Best Stocks to Buy Right Now

Davis Keene·November 19, 2023

This post is not about stocks.

Sorry to disappoint you. As it turns out, I'm not a financial advisor, nor do I create personal finance content on this page. (Maybe I should? I don't know!)

I am, however, a computer scientist that likes to publish content, and it's a pet peeve of mine when I click on a web article and find that the information we're seeing just isn't up to date. It could be that Wikipedia maintainers haven't yet reacted to news, or that the article in question is just simply outdated. Whatever the reason, wouldn't it be nice to have one post, one URL, that automatically updates its content at a regular cadence without human intervention? More specifically, can we have a static page that always has up-to-date information on highly favored stocks?

Let's hack it together. I've included technical implementation details throughout this post, but I also tried my best to include relevant information for non-technical folks. Oh, and if you really are just interested in stocks to purchase, you can skip to the bottom of this post to see the list.

Generative AI for Content Refreshing

Generative AI has come a long way in recent years, and it is now possible to use it to create content that is self-updating. By exposing pre-trained language models to relevant, up-to-date information, we can apply this information to an existing article and have a GPT (General Purpose Transformer) update it for us. This means that we can create blog posts, news articles, and other types of content that automatically update themselves as new information becomes available. This is a powerful tool for content creators, as it allows them to focus on creating high-quality content without having to worry about maintaining it. With the help of generative AI, we can create a new era of content that is always fresh, relevant, and engaging.

Introducing the Content Refresh Pipeline

Imagine a workflow that constantly fetches the latest information and seamlessly integrates it into your web content. This is what we call a Content Refresh Pipeline. It's a systematic approach to keeping your blog posts as current as the ever-changing world of information. Here's how we can set this up:

  1. Define the Content to be Updated
    • Our first task is to identify the content that needs regular updates. For this demonstration, we're focusing on an article titled "Best Stocks To Buy Right Now", ensuring it always has the most current information.
  2. Crafting the Original Content
    • We start by writing the initial version of our article, incorporating the most up-to-date data available at the time of publishing.
  3. Establishing the Update Mechanism
    • This is where the magic happens. We set up a process that periodically (weekly or daily) executes the following steps:
      • Data Acquisition: Using web scraping, we perform a search for the latest information on top-performing stocks and compile the findings into a text format.
      • Content Integration: Next, we feed this freshly gathered data, along with our existing blog post, into an AI language model. This model then intelligently updates any outdated information in our article.
      • Publication: Finally, the revised content is saved, and a new version of the blog post is built and deployed to the web.

Now, let's delve into the specific technologies that make this pipeline possible:

  • AWS EC2: Our virtual machine in the cloud, perfect for running scripts consistently and handling the pipeline's automation.
  • Python's FastAPI Library: This serves as the backbone for our web server, hosting our content creation functions and managing the pipeline's workflow.
  • Python's Requests and BeautifulSoup4: These tools form our web scraping API, essential for extracting relevant text data from the web.
  • OpenAI's GPT-4 API: The cutting-edge language model that we'll use for intelligently updating our content based on the latest information.

We're all set to start creating content stays relevant and fresh. Let's give it a try!

Web Scraping

To get the latest information on high performing stocks, we can search google and scrape content into plain text. Let's write a script that can get us relevant, up-to-date text from Google about the best performing stocks of the month.

# web.py
import requests
from bs4 import BeautifulSoup
import datetime

def get_best_stocks():
    # Get current month and year
    now = datetime.datetime.now()
    current_month = now.strftime("%B")
    current_year = now.year

    # Perform web search
    search_query = f"best stocks to buy now {current_month} {current_year}"
    url = f"https://www.google.com/search?q={search_query}"
    response = requests.get(url)

    # Scrape top few results for text data
    soup = BeautifulSoup(response.text, "html.parser")
    results = soup.find_all("div", class_="BNeawe s3v9rd AP7Wnd")
    text_data = [result.get_text() for result in results]

    return text_data


if __name__ == "__main__":
    print(get_best_stocks())
The output of this function will be something that looks like this... (click to view)
['The 3 Most Undervalued Hydrogen Stocks to Buy Now: November 2023', 'The 3 Most Undervalued AI Penny Stocks to Buy: November 2023', '3 of the Best Cheap Stocks Under $20 to Buy Now: November Edition', 'Top 10 Stocks to Buy and Hold in 2023', '3 Growth Stocks to Buy in November 2023', '3 Magnificent Growth Stocks to Buy on the Dip in November', '1 hour ago · Mattel (NYSE:MAT) is a mid-cap pick for cheap stocks under $20. The stock charged 30% upon the release of the Barbie movie in the summer.', '1 hour ago · Mattel (NYSE:MAT) is a mid-cap pick for cheap stocks under $20. The stock charged 30% upon the release of the Barbie movie in the summer.', '6 days ago · 3 Growth Stocks to Buy in November 2023 · Alphabet (GOOG, GOOGL) · Meta Platforms (META) · Zoom Video Communications (ZM) · Sponsored Headlines\xa0...', '6 days ago · 3 Growth Stocks to Buy in November 2023 · Alphabet (GOOG, GOOGL) · Meta Platforms (META) · Zoom Video Communications (ZM) · Sponsored Headlines\xa0...', '5 days ago · The 10 Best Stocks To Buy Now · Boeing (BA) · CSX (CSX) · Five Below (FIVE) · Kraft Heinz (KHC) · Occidental Petroleum (OXY) · Owens-Corning (OC).', '5 days ago · The 10 Best Stocks To Buy Now · Boeing (BA) · CSX (CSX) · Five Below (FIVE) · Kraft Heinz (KHC) · Occidental Petroleum (OXY) · Owens-Corning (OC).', 'Nov 1, 2023 · The top growth stocks for October include Solena Therapeutics Inc., American Coastal Insurance Corp., and Ambrx Biopharma Inc.,\xa0...', 'Nov 1, 2023 · The top growth stocks for October include Solena Therapeutics Inc., American Coastal Insurance Corp., and Ambrx Biopharma Inc.,\xa0...', '9 hours ago · Which stocks are best to buy now? According to Top Wall Street Analysts, the three stocks listed below are Strong Buys.', '9 hours ago · Which stocks are best to buy now? According to Top Wall Street Analysts, the three stocks listed below are Strong Buys.', 'Nov 6, 2023 · The Motley Fool has positions in and recommends Alphabet, Fortinet, PayPal, and Tesla. The Motley Fool recommends the following options: short\xa0...', 'Nov 6, 2023 · The Motley Fool has positions in and recommends Alphabet, Fortinet, PayPal, and Tesla. The Motley Fool recommends the following options: short\xa0...', '16 hours ago · The best Dow Jones stocks to buy and watch in November near buy points include Apple...

OpenAI API

To transform our web data into useful insights, we're going to use a tool from OpenAI called the GPT API. Imagine GPT as a sophisticated AI that we can communicate with using simple text. We send it text, and it replies back in text. It's like having a conversation with a really smart assistant that can summarize complex information.

For our project, we'll use the GPT API to convert all our collected web data into an easy-to-read, bulleted list. OpenAI offers several versions of this AI, each with different capabilities and costs. We've chosen to use the gpt-4-1106-preview model because it strikes a great balance between speed, intelligence, and cost.

To access this AI tool, we need something called an API token from OpenAI. This token acts like a special password, letting OpenAI know it's really us using their service. Once we sign up on OpenAI's website, we'll receive this token. We'll then securely store it in a .env file in our project. This way, we ensure our access is both authorized and protected:

OPENAI_API_KEY=<your-key-here>

We can read that value in Python and write a script that makes a valid API request to give us a human-readable summary of our web articles:

# ai.py

import os
import requests
from datetime import datetime
from dotenv import load_dotenv

from web import get_best_stocks

# Load environment variables from our .env file
load_dotenv()

def get_completion(prompt):
    url = "https://api.openai.com/v1/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}"
    }
    data = {
        "messages": [{"role": "user", "content": prompt}],
        "model": "gpt-4-1106-preview",
        "temperature": 0.7
    }
    response = requests.post(url, headers=headers, json=data)
    return response.json()

if __name__ == "__main__":
    # If we wanted to create a ChatBot, we could do so like this:
    # while True:
    #     prompt = input("You: ")
    #     response = get_completion(prompt)
    #     print("AI: " + response["choices"][0]["message"]["content"])

    # Instead, let's give our AI a prompt and see what it says
    prompt = f"""
    Below is recent data from the web about the top stocks to buy now. \n\n
    Your job is to summarize this information and return a list of the top 5 stocks to buy right now, and support your answer to each.

    Format your response using valid markdown. Do not provide any warnings about financial risk associated with buying stocks.

    Include a section at the end that says "Last updated at: <current_date>"\n\n
    <BEGIN_WEB_DATA>\n
    {" ".join(get_best_stocks())}\n
    <END_WEB_DATA>
    <START_CURRENT_DATE>
    {datetime.now()}
    <END_CURRENT_DATE>
    """
    # Get the prompt text from the resulting JSON
    print(get_completion(prompt)["choices"][0]["message"]["content"])

Analyzing the output of our script, we see that it actually did a pretty good job!

Based on the recent web data, here's a summarized list of the top 5 stocks to buy right now:

1. **Alphabet Inc. (GOOG, GOOGL)**
   - Alphabet, the parent company of Google, is recommended by multiple sources, including The Motley Fool. It's considered a growth stock and also one of the top tech stocks to buy in November 2023.

2. **Apple Inc. (AAPL)**
   - Apple is highlighted as one of the best Dow Jones stocks to watch and buy, as it is near buy points. It is also listed as one of the top tech stocks to invest in.

3. **Microsoft Corporation (MSFT)**
   - Microsoft is another top tech stock to buy, recommended by analysts. It is included in the list of Dow Jones stocks to watch and has a strong presence in the technology sector.

4. **Nvidia Corporation (NVDA)**
   - Nvidia is recognized as one of the best growth stocks as of November 2023, with a high rate of return. It is also one of the stocks listed as a Strong Buy by Wall Street Analysts.

5. **MercadoLibre, Inc. (MELI)**
   - MercadoLibre is noted for its significant growth potential, making it one of the best growth stocks in November 2023. It is also endorsed as a Strong Buy by analysts.

These stocks are chosen based on repeated mentions across different sources, their standing as strong buys or growth stocks, and their inclusion in lists of stocks to watch and buy.

Updating Existing Content

Now that we have a way to generate up-to-date content on what stocks to buy, we need to integrate this into our actual file, whether it be a blog post, website home page, etc.

My personal blog is a static website that is hosted on Github Pages, which uses react-static as a build tool. All of my blog posts are written in Markdown.

To automate the process of updating this content, I'm going to make a few changes to the code that we already have, to allow us to make changes to our blog posts given a relative file path.

# ai.py

def construct_new_content(path, new_content_snippet):
    # From a blog post (with clearly defined start and stop symbols),
    # put the new content in the correct place
    contents = read_file(path)
    # Grab the content before the new content snippet
    ai_content = contents.split(AI_DELIMITER)  # <- Delimiter (start/stop words) set elsewhere
    ai_content[1] = new_content_snippet
    return "".join(ai_content)

def get_updated_blog_post():
    prompt = ...  # Generates only the updated content that we need, with markdown formatting
    ai_content = get_completion(prompt)["choices"][0]["message"]["content"]
    new_content = construct_new_content("../Portfolio/public/blog/best-stocks.markdown", ai_content)
    return new_content

Let's now create a scheduled job that our web server will run at the same time each day. This job will run all the processes that we've defined earlier and update our blog's content automatically at midnight.


app = FastAPI()

scheduler = BackgroundScheduler()

def update_content_cron():
    # This script lives within the same root directory as my blog's source code
    print("Starting new blog post update...")
    updated_blog_post = get_updated_blog_post()
    # Update the content with the updated blog post and author a new commit
    # to trigger a new Github Pages build
    update_content("../Portfolio/public/blog/best-stocks.markdown", updated_blog_post)
    subprocess.call("./scripts/save_and_commit.sh")
    print("Finished updating blog post!")

@app.on_event("startup")
def startup():
    scheduler.add_job(
        func=update_content_cron,
        trigger="cron",
        hour="0",
        minute="0",
        second="0",
        timezone="EST",  # I live on Eastern Time, so I want this to update at 12am EST
        )
    scheduler.start()

And, voila! Below, you will find content that is entirely AI generated from prompt engineering and web scraping to deliver up-to-date content. In this case, we will present some good performing stocks that you can purchase, but there are so many other unique applications to having automatically updating content.

  • Your personal website could always have your current employer name & employment status based on LinkedIn data.
  • News headlines could dynamically change based on Twitter sentiment surrounding a particular current event.
  • Etc Etc Etc!
Quick note: AI generated content may be incorrect. In addition, purchasing these stocks at the discretion of AI generated content is not good financial advice. I am not a financial analyst, nor is this meant to be anything more than an experiment in auto-updating blog content.

The Best Stocks to Buy Right Now

Without further ado, here's a list of 5 high performing stocks to purchase right now, based on up-to-date information from the web. Check the bottom of this list to see when it was last updated, and click on any of the stock names to see its Yahoo Finance page.

  1. Planet Fitness, Inc. (PLNT)

    • With a robust growth profile, Planet Fitness is highlighted as one of the stand-out performers to consider for November 2023.
  2. Vita Coco Company, Inc. (COCO)

    • As a unique player in the beverage industry, Vita Coco has exhibited significant market potential and is a top pick for growth this month.
  3. New Fortress Energy Inc. (NFE)

    • With a focus on energy infrastructure, New Fortress Energy is a notable growth stock, grabbing the attention of investors in November 2023.
  4. Apple Inc. (AAPL)

    • Apple remains a solid choice according to the best Dow Jones stocks to buy and watch, showing strong performance in the stock market.
  5. Amazon.com, Inc. (AMZN)

    • Amazon's impressive year-to-date growth of 70.5% positions it as a prime pick for investors heading into the holiday season.

Last updated at: 2023-11-19