-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
303 lines (234 loc) · 8.16 KB
/
Copy pathutils.py
File metadata and controls
303 lines (234 loc) · 8.16 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
"""
Utility functions for Stock Sentiment Analytics
"""
import re
import pandas as pd
from datetime import datetime, timedelta
import sqlite3
from typing import List, Dict, Any, Optional
import logging
logger = logging.getLogger(__name__)
def extract_tickers(text: str) -> List[str]:
"""
Extract stock tickers from text using regex patterns.
Args:
text: Input text to search for tickers
Returns:
List of found ticker symbols
"""
# Common words that might be mistaken for tickers
common_words = {
'THE', 'AND', 'FOR', 'ARE', 'YOU', 'ALL', 'NEW', 'TOP', 'BEST', 'GOOD', 'BIG',
'ONE', 'TWO', 'GET', 'SEE', 'NOW', 'DAY', 'WAY', 'MAY', 'CAN', 'WILL', 'HAS',
'HAD', 'HER', 'HIS', 'ITS', 'OUR', 'THEY', 'THEM', 'THIS', 'THAT', 'WITH',
'FROM', 'INTO', 'DURING', 'BEFORE', 'AFTER', 'ABOVE', 'BELOW', 'BETWEEN',
'AMONG', 'AGAINST', 'TOWARD', 'TOWARDS', 'UPON', 'WITHIN', 'WITHOUT'
}
# Pattern for stock tickers (1-5 capital letters)
ticker_pattern = r'\b[A-Z]{1,5}\b'
tickers = re.findall(ticker_pattern, text)
# Filter out common words and duplicates
tickers = [ticker for ticker in tickers if ticker not in common_words]
return list(set(tickers))
def clean_text(text: str) -> str:
"""
Clean and normalize text for sentiment analysis.
Args:
text: Raw text to clean
Returns:
Cleaned text
"""
if not text:
return ""
# Remove URLs
text = re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', '', text)
# Remove special characters but keep basic punctuation
text = re.sub(r'[^\w\s\.\,\!\?\-\:]', '', text)
# Normalize whitespace
text = re.sub(r'\s+', ' ', text)
return text.strip()
def calculate_sentiment_metrics(df: pd.DataFrame) -> Dict[str, Any]:
"""
Calculate sentiment metrics from a DataFrame.
Args:
df: DataFrame with sentiment data
Returns:
Dictionary with calculated metrics
"""
if df.empty:
return {
'total_mentions': 0,
'avg_sentiment': 0.0,
'positive_pct': 0.0,
'negative_pct': 0.0,
'neutral_pct': 0.0,
'sentiment_trend': 'neutral'
}
metrics = {
'total_mentions': len(df),
'avg_sentiment': df['sentiment_score'].mean(),
'positive_pct': (df['sentiment_label'] == 'positive').mean() * 100,
'negative_pct': (df['sentiment_label'] == 'negative').mean() * 100,
'neutral_pct': (df['sentiment_label'] == 'neutral').mean() * 100
}
# Determine sentiment trend
if metrics['positive_pct'] > metrics['negative_pct']:
metrics['sentiment_trend'] = 'positive'
elif metrics['negative_pct'] > metrics['positive_pct']:
metrics['sentiment_trend'] = 'negative'
else:
metrics['sentiment_trend'] = 'neutral'
return metrics
def get_time_based_data(df: pd.DataFrame, hours: int = 24) -> pd.DataFrame:
"""
Filter data to last N hours.
Args:
df: DataFrame with timestamp column
hours: Number of hours to look back
Returns:
Filtered DataFrame
"""
if df.empty:
return df
cutoff_time = datetime.now() - timedelta(hours=hours)
return df[df['timestamp'] >= cutoff_time]
def aggregate_sentiment_by_ticker(df: pd.DataFrame) -> pd.DataFrame:
"""
Aggregate sentiment data by ticker.
Args:
df: DataFrame with sentiment data
Returns:
Aggregated DataFrame
"""
if df.empty:
return pd.DataFrame()
agg_data = df.groupby('ticker').agg({
'sentiment_score': ['mean', 'count', 'std'],
'sentiment_label': lambda x: x.value_counts().to_dict()
}).reset_index()
# Flatten column names
agg_data.columns = ['ticker', 'avg_sentiment', 'mention_count', 'sentiment_std', 'sentiment_distribution']
return agg_data
def get_database_connection(db_path: str = 'data/sentiment_data.db') -> sqlite3.Connection:
"""
Get a database connection.
Args:
db_path: Path to SQLite database
Returns:
SQLite connection
"""
return sqlite3.connect(db_path)
def load_sentiment_data(db_path: str = 'data/sentiment_data.db',
ticker: Optional[str] = None,
hours: Optional[int] = None) -> pd.DataFrame:
"""
Load sentiment data from database.
Args:
db_path: Path to database
ticker: Filter by specific ticker
hours: Filter by time range (last N hours)
Returns:
DataFrame with sentiment data
"""
try:
conn = get_database_connection(db_path)
query = "SELECT * FROM sentiment_data"
conditions = []
if ticker:
conditions.append(f"ticker = '{ticker}'")
if hours:
cutoff_time = datetime.now() - timedelta(hours=hours)
conditions.append(f"timestamp >= '{cutoff_time.isoformat()}'")
if conditions:
query += " WHERE " + " AND ".join(conditions)
query += " ORDER BY timestamp DESC"
df = pd.read_sql_query(query, conn)
conn.close()
# Convert timestamp column
if not df.empty and 'timestamp' in df.columns:
df['timestamp'] = pd.to_datetime(df['timestamp'])
return df
except Exception as e:
logger.error(f"Error loading sentiment data: {e}")
return pd.DataFrame()
def load_stock_data(db_path: str = 'data/sentiment_data.db',
ticker: Optional[str] = None,
hours: Optional[int] = None) -> pd.DataFrame:
"""
Load stock price data from database.
Args:
db_path: Path to database
ticker: Filter by specific ticker
hours: Filter by time range (last N hours)
Returns:
DataFrame with stock data
"""
try:
conn = get_database_connection(db_path)
query = "SELECT * FROM stock_data"
conditions = []
if ticker:
conditions.append(f"ticker = '{ticker}'")
if hours:
cutoff_time = datetime.now() - timedelta(hours=hours)
conditions.append(f"timestamp >= '{cutoff_time.isoformat()}'")
if conditions:
query += " WHERE " + " AND ".join(conditions)
query += " ORDER BY timestamp DESC"
df = pd.read_sql_query(query, conn)
conn.close()
# Convert timestamp column
if not df.empty and 'timestamp' in df.columns:
df['timestamp'] = pd.to_datetime(df['timestamp'])
return df
except Exception as e:
logger.error(f"Error loading stock data: {e}")
return pd.DataFrame()
def format_sentiment_score(score: float) -> str:
"""
Format sentiment score for display.
Args:
score: Sentiment score (0-1)
Returns:
Formatted string
"""
return f"{score:.3f}"
def get_sentiment_color(label: str) -> str:
"""
Get color for sentiment label.
Args:
label: Sentiment label
Returns:
CSS color string
"""
colors = {
'positive': '#28a745',
'negative': '#dc3545',
'neutral': '#6c757d'
}
return colors.get(label, '#6c757d')
def validate_ticker(ticker: str) -> bool:
"""
Validate if a string is a valid stock ticker.
Args:
ticker: Ticker symbol to validate
Returns:
True if valid, False otherwise
"""
# Basic validation: 1-5 capital letters
pattern = r'^[A-Z]{1,5}$'
return bool(re.match(pattern, ticker))
def get_trend_arrow(trend: str) -> str:
"""
Get arrow emoji for trend direction.
Args:
trend: Trend direction ('positive', 'negative', 'neutral')
Returns:
Arrow emoji
"""
arrows = {
'positive': '📈',
'negative': '📉',
'neutral': '➡️'
}
return arrows.get(trend, '➡️')