How to beginner · 3 min read

Sentiment analysis for stock trading

Quick answer
Use a large language model (LLM) like gpt-4o to analyze news headlines or social media posts for sentiment related to stocks. By feeding relevant text to the model and interpreting its sentiment output, you can inform trading decisions with real-time market sentiment insights.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the openai Python package and set your API key as an environment variable for secure access.

bash
pip install openai
output
Collecting openai
  Downloading openai-1.7.0-py3-none-any.whl (70 kB)
Installing collected packages: openai
Successfully installed openai-1.7.0

Step by step

This example shows how to send stock-related news headlines to gpt-4o for sentiment analysis and interpret the response.

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

stock_news = "Tesla shares surge after strong quarterly earnings report"

messages = [
    {"role": "system", "content": "You are a financial sentiment analysis assistant."},
    {"role": "user", "content": f"Analyze the sentiment of this news headline for stock trading: '{stock_news}'"}
]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=messages
)

sentiment = response.choices[0].message.content
print("Sentiment analysis result:", sentiment)
output
Sentiment analysis result: The sentiment is positive, indicating optimism about Tesla's stock due to strong earnings.

Common variations

  • Use gpt-4o-mini for faster, cheaper inference with slightly less accuracy.
  • Process multiple headlines asynchronously using Python asyncio and the OpenAI async client.
  • Stream partial sentiment results for real-time UI updates by setting stream=True in the API call.
python
import asyncio
import os
from openai import OpenAI

async def analyze_sentiment_async(headline: str):
    client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
    messages = [
        {"role": "system", "content": "You are a financial sentiment analysis assistant."},
        {"role": "user", "content": f"Analyze the sentiment of this news headline for stock trading: '{headline}'"}
    ]
    response = await client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages
    )
    return response.choices[0].message.content

async def main():
    headlines = [
        "Apple stock falls amid supply chain concerns",
        "Amazon announces record-breaking sales this quarter"
    ]
    results = await asyncio.gather(*(analyze_sentiment_async(h) for h in headlines))
    for h, sentiment in zip(headlines, results):
        print(f"Headline: {h}\nSentiment: {sentiment}\n")

if __name__ == "__main__":
    asyncio.run(main())
output
Headline: Apple stock falls amid supply chain concerns
Sentiment: The sentiment is negative, reflecting concerns about Apple's stock due to supply chain issues.

Headline: Amazon announces record-breaking sales this quarter
Sentiment: The sentiment is positive, indicating strong confidence in Amazon's stock performance.

Troubleshooting

  • If you get AuthenticationError, verify your OPENAI_API_KEY environment variable is set correctly.
  • For RateLimitError, reduce request frequency or switch to a smaller model like gpt-4o-mini.
  • If sentiment output is unclear, refine the system prompt to specify the expected sentiment categories (e.g., positive, negative, neutral).

Key Takeaways

  • Use gpt-4o or gpt-4o-mini for accurate and cost-effective stock sentiment analysis.
  • Feed relevant financial news or social media text as input to the model with a clear system prompt.
  • Leverage async calls and streaming for scalable, real-time sentiment processing.
  • Always secure your API key via environment variables to avoid authentication errors.
  • Refine prompts to improve sentiment classification accuracy for trading decisions.
Verified 2026-04 · gpt-4o, gpt-4o-mini
Verify ↗