AI_Stock_Prediction / tools /news_tool.py
dure-waseem's picture
initial code
a189e3e
# from crewai.tools import tool
# from langchain_community.tools.yahoo_finance_news import YahooFinanceNewsTool
# import json
# @tool("get_stock_news")
# def get_stock_news(company_ticker: str) -> str:
# """
# Retrieves the latest news and market sentiment for a given stock ticker
# from Yahoo Finance News.
# Args:
# company_ticker: str -> the ticker symbol of the company (e.g., 'AAPL', 'GOOGL')
# """
# try:
# # Initialize Yahoo Finance News tool
# yahoo_news_tool = YahooFinanceNewsTool()
# # Get news for the company
# news_result = yahoo_news_tool.run(company_ticker)
# if not news_result:
# return f"No news found for ticker: {company_ticker}"
# # If the result is already a string, return it
# if isinstance(news_result, str):
# return news_result
# # If it's a dict or list, format it as JSON
# return json.dumps(news_result, indent=2, ensure_ascii=False)
# except Exception as e:
# return f"Error retrieving news for {company_ticker}: {str(e)}"
from crewai.tools import tool
import finnhub
import os
import json
from datetime import datetime, timedelta
@tool("get_stock_news")
def get_stock_news(company_ticker: str) -> str:
"""
Retrieves the latest company news for a given stock ticker from Finnhub.
Gets news from the last 30 days to capture recent developments and market sentiment.
Args:
company_ticker: str -> the ticker symbol of the company (e.g., 'AAPL', 'GOOGL')
"""
try:
# Initialize Finnhub client
finnhub_client = finnhub.Client(api_key=os.getenv("FINNHUB_API_KEY"))
# Calculate date range (last 30 days)
end_date = datetime.now()
start_date = end_date - timedelta(days=30)
# Format dates as required by Finnhub API
from_date = start_date.strftime("%Y-%m-%d")
to_date = end_date.strftime("%Y-%m-%d")
# Get company news
news_data = finnhub_client.company_news(
symbol=company_ticker,
_from=from_date,
to=to_date
)
if not news_data:
return f"No recent news found for ticker: {company_ticker} in the last 30 days"
# Format the news data using all available Finnhub fields
formatted_news = []
for article in news_data[:20]: # Analyze top 15 most recent articles
formatted_article = {
"id": article.get("id", "unknown"),
"headline": article.get("headline", "No headline available"),
"summary": article.get("summary", "No summary available"),
"category": article.get("category", "General"),
"source": article.get("source", "Unknown source"),
"url": article.get("url", ""),
"image": article.get("image", ""),
"datetime": datetime.fromtimestamp(article.get("datetime", 0)).strftime("%Y-%m-%d %H:%M:%S") if article.get("datetime") else "Unknown date",
"unix_timestamp": article.get("datetime", 0),
"related_stocks": article.get("related", []) if article.get("related") else []
}
formatted_news.append(formatted_article)
# Sort by datetime (most recent first)
formatted_news.sort(key=lambda x: x["unix_timestamp"], reverse=True)
# Analyze news categories and sources
categories = {}
sources = {}
related_companies = set()
for article in formatted_news:
# Count categories
category = article["category"]
categories[category] = categories.get(category, 0) + 1
# Count sources
source = article["source"]
sources[source] = sources.get(source, 0) + 1
# Collect related companies/stocks
if article["related_stocks"]:
related_companies.update(article["related_stocks"])
# Create comprehensive news analysis
news_analysis = {
"company_ticker": company_ticker,
"analysis_period": {
"from_date": from_date,
"to_date": to_date,
"days_analyzed": 30
},
"news_metrics": {
"total_articles_found": len(news_data),
"articles_analyzed": len(formatted_news),
"average_articles_per_day": round(len(news_data) / 30, 2)
},
"news_breakdown": {
"categories": dict(sorted(categories.items(), key=lambda x: x[1], reverse=True)),
"top_sources": dict(sorted(sources.items(), key=lambda x: x[1], reverse=True)[:5]),
"related_companies_mentioned": list(related_companies)[:10] if related_companies else []
},
"recent_articles": formatted_news
}
return json.dumps(news_analysis, indent=2, ensure_ascii=False)
except Exception as e:
return f"Error retrieving news for {company_ticker}: {str(e)}\nPlease ensure FINNHUB_API_KEY is properly set in .env file"