Building a Personalized Stock Alert Automation System Using Python, News API, and LLM: Capturing Investment Opportunities Based on Real-time News Sentiment Analysis
While stock market volatility is difficult to predict, utilizing real-time news can increase the likelihood of capturing investment opportunities. This article introduces how to build a personalized stock alert automation system by combining Python, News API, and LLM (Large Language Model), and presents specific strategies to support investment decisions through news sentiment analysis.
1. The Challenge / Context
Individual investors spend a significant amount of time and effort manually checking and analyzing vast amounts of news information. Quickly identifying news that impacts the market and interpreting its meaning is crucial, but realistically not easy. Furthermore, it's difficult to determine whether a news item will have a positive or negative impact on investment based solely on its title. Therefore, what individual investors need is an automated system that can collect relevant news in real-time and analyze its content to assist in investment decisions.
2. Deep Dive: News API
News API is a powerful API that allows easy retrieval of news data from various news sources worldwide. By obtaining an API key, you can search for news related to specific keywords, company names, or industry sectors through simple HTTP requests. News API provides information such as news titles, content, publication dates, and sources in JSON format. It offers various filtering options, enabling you to extract only the desired news data, thereby filtering out unnecessary information and facilitating efficient analysis.
3. Step-by-Step Guide / Implementation
Now, let's take a detailed look at the steps to build a personalized stock alert automation system using Python, News API, and LLM.
Step 1: Obtaining a News API Key and Setting Up Python Environment
First, you need to obtain an API key from the News API website (https://newsapi.org/). A free plan is available, but it has request limits, so you might consider a paid plan if necessary. Next, set up your Python development environment and install the required libraries.
# Install required libraries
pip install requests transformers torch
Step 2: Collecting News Data Using News API
Below is the Python code for collecting news data related to a specific stock using News API.
import requests
def get_news(api_key, query, page_size=10):
url = f"https://newsapi.org/v2/everything?q={query}&apiKey={api_key}&pageSize={page_size}"
response = requests.get(url)
if response.status_code == 200:
return response.json()['articles']
else:
print(f"Error: {response.status_code}")
return None
# Set API key and query
api_key = "YOUR_NEWS_API_KEY" # Enter your issued API key here.
query = "삼성전자" # Stock ticker or keyword to search
# Get news data
news_data = get_news(api_key, query)
if news_data:
for article in news_data:
print(f"Title: {article['title']}")
print(f"Description: {article['description']}")
print(f"URL: {article['url']}")
print("-" * 20)
In the code above, replace YOUR_NEWS_API_KEY with your issued API key, and enter the desired stock ticker or keyword in the query variable. page_size sets the number of news articles to retrieve in a single API call. The code execution will output news titles, descriptions, and URLs.
Step 3: News Sentiment Analysis Using LLM
Based on the collected news data, sentiment analysis is performed to determine whether the news will have a positive or negative impact on investment. Here, we utilize a pre-trained sentiment analysis model from Hugging Face's Transformers library.
from transformers import pipeline
def analyze_sentiment(text):
sentiment_pipeline = pipeline("sentiment-analysis")
result = sentiment_pipeline(text)[0]
return result['label'], result['score']
if news_data:
for article in news_data:
title = article['title']
sentiment, score = analyze_sentiment(title)
print(f"Title: {title}")
print(f"Sentiment: {sentiment} (Score: {score:.4f})")
print("-" * 20)
The code above takes a news title as input, performs sentiment analysis, and returns a positive (POSITIVE) or negative (NEGATIVE) sentiment along with its score. The score is represented as a value between 0 and 1, where a value closer to 1 indicates a stronger intensity of that sentiment.
Step 4: Building a Personalized Notification System
Based on the sentiment analysis results, a personalized notification system is built. For example, you can set it to send notifications only when the sentiment score of positive news exceeds a certain threshold. Notifications can be sent via email, SMS, or messaging platforms like Slack.
import smtplib
from email.mime.text import MIMEText
def send_email(subject, body, recipient_email, sender_email, sender_password):
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = recipient_email
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465) # Use Gmail SMTP server
server.login(sender_email, sender_password)
server.sendmail(sender_email, recipient_email, msg.as_string())
server.quit()
print("Email sent successfully!")
except Exception as e:
print(f"Error sending email: {e}")
# Set notification threshold
positive_threshold = 0.8
if news_data:
for article in news_data:
title = article['title']
sentiment, score = analyze_sentiment(title)
if sentiment == "POSITIVE" and score >= positive_threshold:
subject = f"[Stock Alert] Positive News for {query}"
body = f"Title: {title}\nURL: {article['url']}\nSentiment Score: {score:.4f}"
recipient_email = "YOUR_EMAIL@gmail.com" # Recipient email address for notifications
sender_email = "YOUR_GMAIL@gmail.com" # Sender email address (Gmail)
sender_password = "YOUR_GMAIL_PASSWORD" # Sender email password (App password)
send_email(subject, body, recipient_email, sender_email, sender_password)
In the code above, email is sent only when the sentiment score is above positive_threshold. It uses the Gmail SMTP server to send emails. In Gmail account settings, you must allow "Less secure app access" or, if using 2-Step Verification, generate and use an app password. You need to replace YOUR_EMAIL@gmail.com, YOUR_GMAIL@gmail.com, and YOUR_GMAIL_PASSWORD with your actual email addresses and password.
4. Real-world Use Case / Example
I am using this system to predict stock price fluctuations for a specific pharmaceutical company. When positive news articles related to new drug development are published, the company's stock price is likely to rise. This system detects such news in real-time and sends me notifications. After receiving an alert, I check the detailed content of the news and make investment decisions. Previously, I spent over an hour a day manually checking this information, but now, thanks to the automated system, I can grasp all the information within 10 minutes and not miss investment opportunities.
5. Pros & Cons / Critical Analysis
- Pros:
- Real-time news-based investment opportunity capture
- Time-saving with automated alert system
- Personalized filtering and threshold settings
- News sentiment analysis using LLM
- Cons:
- News API usage limits (consider paid plan)
- Limitations in LLM sentiment analysis accuracy (potential for false positives/negatives)
- System maintenance and updates required
- Security management of API keys and email account information
6. FAQ
- Q: Can I use other news data sources instead of News API?
A: Yes, of course. You can collect news data using other news APIs or web scraping techniques. However, News API offers a relatively stable and easy-to-use interface, making it suitable for beginners. - Q: How can I improve the accuracy of LLM sentiment analysis?
A: You can fine-tune the sentiment analysis model or use an ensemble of multiple models. Additionally, adjusting the model to consider the characteristics of news data is a good approach. For example, you could use a model specialized in financial news or leverage a glossary of terms specific to a certain industry. - Q: Can I integrate the notification system with other messaging platforms like Slack?
A: Yes, it's possible. You can send notifications using the Slack API or other messaging platform APIs. Refer to the API documentation to write the appropriate code for that platform.
7. Conclusion
A personalized stock alert automation system utilizing Python, News API, and LLM is a highly useful tool for capturing investment opportunities through real-time news sentiment analysis. Follow the steps presented in this article to build the system and enhance your investment strategy by adding settings tailored to your needs. Get your News API key now and run the code to experience an automated investment alert system!


