Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
339 lines (286 loc) · 12.4 KB
/
Copy pathmain.py
File metadata and controls
339 lines (286 loc) · 12.4 KB
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
"""
Main ETL pipeline for news sentiment analysis using Pathway.
"""
import logging
import time
import asyncio
from datetime import datetime
from typing import List, Optional
import os
import json
import pathway as pw
from config.settings import Settings
from src.data_sources.news_api import NewsAPIConnector, NewsArticle
from src.sentiment.analyzer import SentimentAnalyzer
from src.processors.article_processor import ArticleProcessor, ProcessedArticle
from src.outputs.output_handler import OutputManager
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def read_portfolio_tickers(filename="portfolio.txt"):
"""Read stock tickers from a file."""
if not os.path.exists(filename):
return []
with open(filename, "r") as f:
return [line.strip() for line in f if line.strip()]
class NewsSentimentPipeline:
"""Main ETL pipeline for news sentiment analysis."""
def __init__(self, settings: Optional[Settings] = None):
"""
Initialize the pipeline.
Args:
settings: Configuration settings (uses default if None)
"""
self.settings = settings or Settings()
self.settings.validate()
# Initialize components
self.news_connector = NewsAPIConnector(
api_key=self.settings.news_api_key,
base_url=self.settings.news_api_base_url
)
self.sentiment_analyzer = SentimentAnalyzer(
model_type=self.settings.sentiment_model,
model_name=self.settings.transformers_model_name
)
self.article_processor = ArticleProcessor()
self.output_manager = OutputManager(
output_format=self.settings.output_format,
output_path=self.settings.output_path,
database_url=self.settings.database_url
)
logger.info("News Sentiment Pipeline initialized")
logger.info(f"Model: {self.sentiment_analyzer.get_model_info()}")
def fetch_news_data(self) -> List[NewsArticle]:
"""
Fetch news articles from configured sources.
Returns:
List of NewsArticle objects
"""
try:
# Use portfolio tickers as keywords if file exists
tickers = read_portfolio_tickers()
keywords = tickers if tickers else self.settings.default_keywords
articles = self.news_connector.get_top_headlines(
sources=self.settings.default_sources,
keywords=keywords,
page_size=self.settings.max_articles_per_request
)
logger.info(f"Fetched {len(articles)} articles")
return articles
except Exception as e:
logger.error(f"Error fetching news data: {e}")
return []
def analyze_sentiment_batch(self, articles: List[NewsArticle]) -> List[ProcessedArticle]:
"""
Analyze sentiment for a batch of articles.
Args:
articles: List of NewsArticle objects
Returns:
List of ProcessedArticle objects
"""
if not articles:
return []
try:
# Prepare texts for sentiment analysis
texts = []
for article in articles:
combined_text = self.article_processor.combine_title_and_content(
article.title, article.content
)
texts.append(combined_text)
# Analyze sentiment
sentiment_results = self.sentiment_analyzer.analyze_batch(texts)
# Process articles with sentiment results
processed_articles = self.article_processor.process_batch(articles, sentiment_results)
logger.info(f"Analyzed sentiment for {len(processed_articles)} articles")
return processed_articles
except Exception as e:
logger.error(f"Error analyzing sentiment: {e}")
return []
def recommend_stocks(self, processed_articles: List[ProcessedArticle], tickers: list):
"""
For each ticker, aggregate sentiment and print buy/sell/hold recommendation.
"""
recommendations = {}
for ticker in tickers:
# Find articles mentioning the ticker (case-insensitive)
ticker_articles = [a for a in processed_articles if ticker.lower() in (a.title + ' ' + a.content).lower()]
if not ticker_articles:
recommendations[ticker] = ("No data", 0.0)
continue
avg_score = sum(a.sentiment_score for a in ticker_articles) / len(ticker_articles)
if avg_score > 0.1:
rec = "BUY"
elif avg_score < -0.1:
rec = "SELL"
else:
rec = "HOLD"
recommendations[ticker] = (rec, avg_score)
print("\nStock Recommendations:")
for ticker, (rec, score) in recommendations.items():
print(f"{ticker}: {rec} (avg sentiment: {score:.3f})")
return recommendations
def write_recommendation_sources(self, processed_articles: list, tickers: list, recommendations: dict):
"""
For each ticker, write a file with the recommendation and the news articles (title, url, published_at) that contributed, sorted by published_at descending.
"""
def to_naive(dt):
if dt.tzinfo is not None:
return dt.replace(tzinfo=None)
return dt
output = {}
for ticker in tickers:
ticker_articles = [a for a in processed_articles if ticker.lower() in (a.title + ' ' + a.content).lower()]
# Sort by published_at descending, making all datetimes naive
ticker_articles.sort(key=lambda a: to_naive(a.published_at), reverse=True)
output[ticker] = {
"recommendation": recommendations.get(ticker, ("No data", 0.0))[0],
"articles": [
{
"title": a.title,
"url": a.url,
"published_at": a.published_at.isoformat()
} for a in ticker_articles
]
}
# Write to file with timestamp
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
out_path = f"data/sentiment_results/recommendation_sources_{ts}.json"
with open(out_path, "w") as f:
json.dump(output, f, indent=2)
print(f"Wrote recommendation sources to {out_path}")
def run_batch_processing(self):
"""Run a single batch of processing."""
try:
articles = self.fetch_news_data()
if not articles:
logger.warning("No articles fetched")
return
processed_articles = self.analyze_sentiment_batch(articles)
if not processed_articles:
logger.warning("No articles processed")
return
success = self.output_manager.write(processed_articles)
if success:
logger.info(f"Successfully processed and stored {len(processed_articles)} articles")
stats = self.article_processor.get_statistics(processed_articles)
logger.info(f"Processing statistics: {stats}")
tickers = read_portfolio_tickers()
if tickers:
recommendations = self.recommend_stocks(processed_articles, tickers)
self.write_recommendation_sources(processed_articles, tickers, recommendations)
else:
logger.error("Failed to write results")
except Exception as e:
logger.error(f"Error in batch processing: {e}")
def run_pathway_streaming(self):
"""Run the pipeline using Pathway streaming."""
try:
# Create Pathway table for news data
news_table = pw.Table.empty(
article_id=pw.column(str),
title=pw.column(str),
content=pw.column(str),
source=pw.column(str),
published_at=pw.column(str),
url=pw.column(str),
author=pw.column(str),
url_to_image=pw.column(str)
)
# Define sentiment analysis function
def analyze_sentiment(row):
try:
combined_text = f"{row['title']}. {row['content']}"
result = self.sentiment_analyzer.analyze_text(combined_text)
return {
'sentiment_score': result.score,
'sentiment_label': result.label,
'confidence': result.confidence,
'model_used': result.model_used,
'processed_at': result.processed_at.isoformat()
}
except Exception as e:
logger.error(f"Error in sentiment analysis: {e}")
return {
'sentiment_score': 0.0,
'sentiment_label': 'neutral',
'confidence': 0.0,
'model_used': self.settings.sentiment_model,
'processed_at': datetime.now().isoformat()
}
# Apply sentiment analysis
sentiment_table = news_table.select(
*news_table,
**analyze_sentiment(news_table)
)
# Output results
if self.settings.output_format == "json":
pw.io.json.write(
sentiment_table,
self.settings.output_path + "/streaming_results.json"
)
elif self.settings.output_format == "csv":
pw.io.csv.write(
sentiment_table,
self.settings.output_path + "/streaming_results.csv"
)
# Run the pipeline
pw.run()
except Exception as e:
logger.error(f"Error in Pathway streaming: {e}")
def run_continuous(self, interval_seconds: Optional[int] = None):
"""
Run the pipeline continuously with periodic updates.
Args:
interval_seconds: Update interval in seconds (uses settings if None)
"""
interval = interval_seconds or self.settings.update_interval
logger.info(f"Starting continuous pipeline with {interval}s intervals")
try:
while True:
start_time = time.time()
# Run batch processing
self.run_batch_processing()
# Calculate sleep time
elapsed = time.time() - start_time
sleep_time = max(0, interval - elapsed)
logger.info(f"Batch completed in {elapsed:.2f}s. Sleeping for {sleep_time:.2f}s")
time.sleep(sleep_time)
except KeyboardInterrupt:
logger.info("Pipeline stopped by user")
except Exception as e:
logger.error(f"Error in continuous pipeline: {e}")
finally:
self.output_manager.close()
def run(self, mode: str = "batch", continuous: bool = False):
"""
Run the pipeline.
Args:
mode: Processing mode ("batch" or "streaming")
continuous: Whether to run continuously
"""
logger.info(f"Starting pipeline in {mode} mode")
if mode == "streaming":
self.run_pathway_streaming()
elif mode == "batch":
if continuous:
self.run_continuous()
else:
self.run_batch_processing()
else:
raise ValueError(f"Unsupported mode: {mode}")
def main():
"""Main entry point."""
try:
# Initialize pipeline
pipeline = NewsSentimentPipeline()
# Run pipeline in batch mode, continuous
pipeline.run(mode="batch", continuous=True)
except Exception as e:
logger.error(f"Pipeline failed: {e}")
raise
if __name__ == "__main__":
main()