File size: 13,481 Bytes
c3bf538 c6fb015 c3bf538 c6fb015 c3bf538 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 |
# # tasks/news_tasks.py - SIMPLIFIED VERSION THAT ALWAYS WORKS
# from celery_worker import celery
# from core.database import SessionLocal
# from models.analysis_job import AnalysisJob
# from uuid import UUID
# import logging
# from datetime import datetime
# import yfinance as yf
# logger = logging.getLogger(__name__)
# def get_stock_basic_info(ticker: str):
# """Get basic stock information to create realistic content"""
# try:
# stock = yf.Ticker(ticker)
# info = stock.info
# return {
# 'name': info.get('longName', ticker.replace('.NS', '')),
# 'sector': info.get('sector', 'Unknown'),
# 'industry': info.get('industry', 'Unknown'),
# 'current_price': info.get('currentPrice', 0),
# 'previous_close': info.get('previousClose', 0)
# }
# except Exception as e:
# logger.warning(f"Could not get stock info for {ticker}: {e}")
# return {
# 'name': ticker.replace('.NS', ''),
# 'sector': 'Unknown',
# 'industry': 'Unknown',
# 'current_price': 0,
# 'previous_close': 0
# }
# def create_realistic_articles(ticker: str, company_name: str, stock_info: dict):
# """Create realistic articles based on stock information"""
# # Calculate price movement for realistic sentiment
# current_price = stock_info.get('current_price', 0)
# previous_close = stock_info.get('previous_close', 0)
# price_change = 0
# if current_price and previous_close:
# price_change = ((current_price - previous_close) / previous_close) * 100
# # Generate articles based on actual stock performance
# articles = []
# if price_change > 2:
# articles.extend([
# {
# "title": f"{company_name} Shares Rally {price_change:.1f}% on Strong Market Sentiment",
# "url": f"https://finance.yahoo.com/quote/{ticker}",
# "source": "Market Analysis",
# "sentiment": "Positive",
# "sentiment_score": 0.8
# },
# {
# "title": f"Investors Show Confidence in {company_name} as Stock Gains Momentum",
# "url": f"https://www.moneycontrol.com/india/stockpricequote/{ticker}",
# "source": "Financial Express",
# "sentiment": "Positive",
# "sentiment_score": 0.7
# }
# ])
# elif price_change < -2:
# articles.extend([
# {
# "title": f"{company_name} Stock Declines {abs(price_change):.1f}% Amid Market Volatility",
# "url": f"https://finance.yahoo.com/quote/{ticker}",
# "source": "Market Watch",
# "sentiment": "Negative",
# "sentiment_score": 0.8
# },
# {
# "title": f"Market Correction Impacts {company_name} Share Price",
# "url": f"https://www.moneycontrol.com/india/stockpricequote/{ticker}",
# "source": "Economic Times",
# "sentiment": "Negative",
# "sentiment_score": 0.6
# }
# ])
# else:
# articles.extend([
# {
# "title": f"{company_name} Stock Shows Steady Performance in Current Market",
# "url": f"https://finance.yahoo.com/quote/{ticker}",
# "source": "Yahoo Finance",
# "sentiment": "Neutral",
# "sentiment_score": 0.5
# },
# {
# "title": f"Technical Analysis: {company_name} Maintains Stable Trading Range",
# "url": f"https://www.moneycontrol.com/india/stockpricequote/{ticker}",
# "source": "Market Analysis",
# "sentiment": "Neutral",
# "sentiment_score": 0.5
# }
# ])
# # Add sector-specific articles
# sector = stock_info.get('sector', 'Unknown')
# if sector != 'Unknown':
# articles.extend([
# {
# "title": f"{sector} Sector Update: Key Players Including {company_name} in Focus",
# "url": "https://example.com/sector-analysis",
# "source": "Sector Reports",
# "sentiment": "Neutral",
# "sentiment_score": 0.6
# },
# {
# "title": f"Industry Outlook: {stock_info.get('industry', 'Market')} Trends Affecting {company_name}",
# "url": "https://example.com/industry-outlook",
# "source": "Industry Analysis",
# "sentiment": "Positive",
# "sentiment_score": 0.6
# }
# ])
# # Add general market articles
# articles.extend([
# {
# "title": f"Quarterly Performance Review: {company_name} Financials and Market Position",
# "url": f"https://finance.yahoo.com/quote/{ticker}/financials",
# "source": "Financial Reports",
# "sentiment": "Neutral",
# "sentiment_score": 0.5
# },
# {
# "title": f"Analyst Coverage: Investment Recommendations for {company_name} Stock",
# "url": "https://example.com/analyst-coverage",
# "source": "Research Reports",
# "sentiment": "Positive",
# "sentiment_score": 0.7
# },
# {
# "title": f"Market Sentiment Analysis: Retail vs Institutional Interest in {company_name}",
# "url": "https://example.com/market-sentiment",
# "source": "Market Research",
# "sentiment": "Neutral",
# "sentiment_score": 0.5
# }
# ])
# return articles[:8] # Return top 8 articles
# def try_real_news_sources(ticker: str, company_name: str):
# """Attempt to get real news, but don't fail if it doesn't work"""
# real_articles = []
# try:
# # Try Yahoo Finance news (most reliable)
# logger.info(f"Attempting to fetch real Yahoo Finance news for {ticker}")
# stock = yf.Ticker(ticker)
# news = stock.news
# if news:
# logger.info(f"Found {len(news)} Yahoo Finance articles")
# for article in news[:5]: # Take first 5
# if article.get('title'):
# # Simple sentiment analysis
# title_lower = article['title'].lower()
# if any(word in title_lower for word in ['gain', 'rise', 'growth', 'profit', 'strong']):
# sentiment = 'Positive'
# score = 0.7
# elif any(word in title_lower for word in ['fall', 'decline', 'loss', 'weak', 'drop']):
# sentiment = 'Negative'
# score = 0.7
# else:
# sentiment = 'Neutral'
# score = 0.5
# real_articles.append({
# "title": article['title'].strip(),
# "url": article.get('link', ''),
# "source": article.get('publisher', 'Yahoo Finance'),
# "sentiment": sentiment,
# "sentiment_score": score,
# "is_real": True
# })
# logger.info(f"Successfully retrieved {len(real_articles)} real articles")
# except Exception as e:
# logger.warning(f"Could not fetch real news: {e}")
# return real_articles
# @celery.task
# def run_intelligence_analysis(job_id: str):
# """Simplified intelligence analysis that always provides results"""
# db = SessionLocal()
# job = None
# try:
# logger.info(f"Starting intelligence analysis for job {job_id}")
# # Get job
# job = db.query(AnalysisJob).filter(AnalysisJob.id == UUID(job_id)).first()
# if not job or not job.result:
# raise ValueError(f"Job {job_id} not found or has no initial data.")
# job.status = "INTELLIGENCE_GATHERING"
# db.commit()
# current_data = job.result
# ticker = current_data.get("ticker")
# company_name = current_data.get("company_name", ticker.replace('.NS', ''))
# logger.info(f"Analyzing {company_name} ({ticker})")
# # Get basic stock information
# stock_info = get_stock_basic_info(ticker)
# logger.info(f"Stock info: {stock_info['name']} - {stock_info['sector']}")
# # Try to get real news first
# real_articles = try_real_news_sources(ticker, company_name)
# # Create realistic articles
# realistic_articles = create_realistic_articles(ticker, company_name, stock_info)
# # Combine real and realistic articles
# all_articles = real_articles + realistic_articles
# # Remove duplicates and limit to 10 articles
# seen_titles = set()
# unique_articles = []
# for article in all_articles:
# if article['title'] not in seen_titles:
# seen_titles.add(article['title'])
# unique_articles.append(article)
# final_articles = unique_articles[:10]
# # Count sentiments
# sentiment_counts = {'Positive': 0, 'Negative': 0, 'Neutral': 0}
# for article in final_articles:
# sentiment_counts[article['sentiment']] += 1
# # Create intelligence briefing
# intelligence_briefing = {
# "articles": final_articles,
# "sentiment_summary": {
# "total_items": len(final_articles),
# "positive": sentiment_counts['Positive'],
# "negative": sentiment_counts['Negative'],
# "neutral": sentiment_counts['Neutral'],
# "real_articles": len(real_articles),
# "generated_articles": len(realistic_articles),
# "analysis_timestamp": datetime.now().isoformat()
# }
# }
# # Update job result
# new_result = current_data.copy()
# new_result['intelligence_briefing'] = intelligence_briefing
# job.result = new_result
# job.status = "INTELLIGENCE_COMPLETE"
# db.commit()
# logger.info(f"Intelligence analysis completed successfully:")
# logger.info(f"- Total articles: {len(final_articles)}")
# logger.info(f"- Real articles: {len(real_articles)}")
# logger.info(f"- Generated articles: {len(realistic_articles)}")
# logger.info(f"- Sentiment: {sentiment_counts}")
# return str(job.result)
# except Exception as e:
# logger.error(f"Intelligence analysis failed for job {job_id}: {e}")
# if job:
# job.status = "FAILED"
# error_data = job.result if job.result else {}
# error_data['error'] = f"Intelligence analysis failed: {str(e)}"
# job.result = error_data
# db.commit()
# return f"Error: {e}"
# finally:
# db.close()
# from celery_worker import celery
# from core.database import SessionLocal
# from models.analysis_job import AnalysisJob
# from tools.news_tools import get_combined_news_and_sentiment
# from uuid import UUID
# @celery.task
# def run_intelligence_analysis(job_id: str):
# with SessionLocal() as db:
# job = db.query(AnalysisJob).filter(AnalysisJob.id == UUID(job_id)).first()
# if not job or not job.result:
# print(f"Job {job_id} not found or has no data for intelligence.")
# return
# try:
# job.status = "INTELLIGENCE_GATHERING"
# db.commit()
# current_data = job.result
# ticker = current_data.get("ticker")
# company_name = current_data.get("company_name")
# intelligence_briefing = get_combined_news_and_sentiment(ticker, company_name)
# new_result = dict(current_data)
# new_result['intelligence_briefing'] = intelligence_briefing
# job.result = new_result
# db.commit()
# print(f"Intelligence analysis for job {job_id} completed successfully.")
# return "Intelligence gathering successful."
# except Exception as e:
# print(f"Error during intelligence analysis for job {job_id}: {e}")
# job.status = "FAILED"
# error_data = job.result if job.result else {}
# error_data['error'] = f"Intelligence analysis failed: {str(e)}"
# job.result = error_data
# db.commit()
# return f"Intelligence gathering failed: {e}"
from celery_worker import celery
from tools.news_tools import get_combined_news_and_sentiment
@celery.task
def get_intelligence_task(ticker: str, company_name: str):
print(f"Executing get_intelligence_task for {company_name}...")
# This task now depends on the company_name from the first task's result
return get_combined_news_and_sentiment(ticker, company_name) |