Skip to content

Instantly share code, notes, and snippets.

@LaurentiuGabriel
Created January 14, 2026 05:12
Show Gist options
  • Select an option

  • Save LaurentiuGabriel/7e850d082e407c6cc5187779ab2adf98 to your computer and use it in GitHub Desktop.

Select an option

Save LaurentiuGabriel/7e850d082e407c6cc5187779ab2adf98 to your computer and use it in GitHub Desktop.
News sentiment analysis with GPT-5.2
import os
import json
from typing import List, Literal
from pydantic import BaseModel
from openai import OpenAI
NEWSAPI_KEY = "NEWSAPI_KEY"
class AnalysisResult(BaseModel):
article: str
sentiment: Literal["Positive", "Negative"]
signal: Literal["Buy", "Sell"]
impact: Literal["low", "medium", "high"]
class NewsResponse(BaseModel):
results: List[AnalysisResult]
client = OpenAI(api_key="OPENAI_KEY")
def analyze_articles(article_texts: List[str]):
combined_content = "\n\n".join(article_texts)
response = client.beta.chat.completions.parse(
model="gpt-5.2"
messages=[
{"role": "system", "content": "You are a financial analyst. Analyze the following articles and provide a structured sentiment analysis."},
{"role": "user", "content": f"Analyze these articles:\n{combined_content}"}
],
response_format=NewsResponse,
)
return response.choices[0].message.parsed
if __name__ == "__main__":
url = f"https://newsapi.org/v2/everything?q={ticker}&from={from_date}&to={to_date}&sortBy=publishedAt&language=en&apiKey={NEWSAPI_KEY}"
response = requests.get(url)
response.raise_for_status()
data = response.json()
if data['status'] != 'ok' or data['totalResults'] == 0:
return pd.DataFrame()
articles = []
for article in data['articles']:
articles.append({
'title': article['title'],
'source': article['source']['name'],
'published_at': datetime.strptime(article['publishedAt'], '%Y-%m-%dT%H:%M:%SZ'),
'url': article['url'],
'description': article['description'][:200] + "..." if article['description'] and len(article['description']) > 200 else article['description']
})
structured_data = analyze_articles(articles)
print(json.dumps(structured_data.dict(), indent=2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment