Spaces:
Running
Running
File size: 11,779 Bytes
9df4cc0 3e4bf85 3778f9f 33a4549 9df4cc0 33a4549 9df4cc0 a9b1809 9df4cc0 33a4549 3778f9f 7cb8f2e be852d2 7cb8f2e be852d2 7cb8f2e be852d2 7cb8f2e be852d2 33a4549 48a2803 7cb8f2e be852d2 33a4549 0858d17 3778f9f be852d2 33a4549 c319a1e ff72975 1353a1f 33a4549 7cb8f2e 33a4549 7cb8f2e be852d2 33a4549 0858d17 c58a978 215f78a 0858d17 7cb8f2e c58a978 be852d2 33a4549 be852d2 7cb8f2e be852d2 7cb8f2e c58a978 0858d17 1353a1f 33a4549 0858d17 c58a978 0858d17 c58a978 33a4549 7cb8f2e 48a2803 7cb8f2e 48a2803 7cb8f2e 33a4549 0858d17 33a4549 7cb8f2e 0858d17 be852d2 0858d17 be852d2 0858d17 be852d2 c58a978 be852d2 c58a978 be852d2 c58a978 be852d2 c58a978 7cb8f2e 33a4549 4b24cc9 0858d17 33a4549 0858d17 33a4549 0858d17 9df4cc0 be852d2 9df4cc0 be852d2 9df4cc0 3778f9f 9df4cc0 3e4bf85 c58a978 3778f9f 9df4cc0 be852d2 c58a978 3e4bf85 c58a978 9df4cc0 3778f9f c58a978 9df4cc0 3778f9f c58a978 9df4cc0 be852d2 c58a978 be852d2 c58a978 be852d2 c58a978 be852d2 c58a978 be852d2 c58a978 be852d2 c58a978 9df4cc0 c58a978 9df4cc0 c58a978 9df4cc0 c58a978 3e4bf85 c58a978 be852d2 c58a978 9df4cc0 c58a978 3778f9f 9df4cc0 c58a978 9df4cc0 c58a978 9df4cc0 be852d2 c58a978 3e4bf85 |
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 |
import os
import pandas as pd
from datetime import datetime
from dotenv import load_dotenv
from md_html import convert_single_md_to_html as convert_md_to_html
from news_analysis import fetch_deep_news, generate_value_investor_report
from fin_interpreter import analyze_article
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DATA_DIR = os.path.join(BASE_DIR, "data")
HTML_DIR = os.path.join(BASE_DIR, "html")
os.makedirs(DATA_DIR, exist_ok=True)
os.makedirs(HTML_DIR, exist_ok=True)
load_dotenv()
# === Priority Logic ===
def derive_priority(sentiment, confidence):
sentiment = sentiment.lower()
if sentiment == "positive" and confidence > 0.7:
return "High"
if sentiment == "negative" and confidence > 0.6:
return "High"
if confidence > 0.5:
return "Medium"
return "Low"
# === Metrics Box ===
def build_metrics_box(topic, num_articles):
now = datetime.now().strftime("%Y-%m-%d %H:%M")
return f"""
> **Topic:** `{topic}`
> **Articles Collected:** `{num_articles}`
> **Generated:** `{now}`
---
"""
# === Main Analysis ===
def run_value_investing_analysis(csv_path, progress_callback=None):
current_df = pd.read_csv(csv_path)
all_articles = []
company_data = []
for _, row in current_df.iterrows():
topic = row.get("topic")
timespan = row.get("timespan_days", 7)
# if progress_callback:
# progress_callback(f"π Processing topic: {topic} ({timespan} days)")
# try:
# news = fetch_deep_news(topic, timespan)
# if progress_callback:
# progress_callback(f"[DEBUG] fetch_deep_news returned {len(news) if news else 0} articles.")
# except Exception as e:
# if progress_callback:
# progress_callback(f"[ERROR] fetch_deep_news failed: {e}")
# continue
try:
news = fetch_deep_news(topic, timespan)
except Exception as e:
if progress_callback:
progress_callback(f"[ERROR] fetch_deep_news failed: {e}")
continue
if not news:
if progress_callback:
progress_callback(f"β οΈ No news found for topic: {topic}")
continue
for article in news:
summary = article.get("summary", "") or article.get("content", "")
title = article.get("title", "Untitled")
url = article.get("url", "")
date = article.get("date", datetime.now().strftime("%Y-%m-%d"))
try:
result = analyze_article(summary)
sentiment = result.get("sentiment", "Neutral")
confidence = float(result.get("confidence", 0.0))
signal = result.get("investment_decision", "Watch")
#if progress_callback:
#progress_callback(f"π° [{title[:50]}...] β Sentiment: {sentiment}, Confidence: {confidence}, Signal: {signal}")
except Exception as e:
if progress_callback:
progress_callback(f"[FinBERT ERROR] {e}")
sentiment, confidence, signal = "Neutral", 0.0, "Watch"
priority = derive_priority(sentiment, confidence)
all_articles.append({
"Title": title,
"URL": url,
"Summary": summary[:300] + "..." if summary else "",
"Priority": priority,
"Sentiment": sentiment,
"Confidence": confidence,
"Signal": signal,
"Date": date
})
company_data.append({
"Company": topic,
"Sentiment": sentiment,
"Confidence": confidence,
"Signal": signal,
"Summary": summary,
"Priority": priority
})
try:
report_body = generate_value_investor_report(topic, news)
metrics_md = build_metrics_box(topic, len(news))
full_md = metrics_md + report_body
filename = f"{topic.replace(' ', '_').lower()}_{datetime.now().strftime('%Y-%m-%d')}.md"
filepath = os.path.join(DATA_DIR, filename)
with open(filepath, "w", encoding="utf-8") as f:
f.write(full_md)
except Exception as e:
if progress_callback:
progress_callback(f"[REPORT ERROR] {e}")
return all_articles, company_data
# === Insights Tab Data ===
def build_company_insights(company_data):
if not company_data:
return pd.DataFrame()
df = pd.DataFrame(company_data)
insights = []
for company, group in df.groupby("Company"):
mentions = len(group)
dominant_signal = group["Signal"].mode()[0] if not group["Signal"].mode().empty else "Watch"
avg_confidence = round(group["Confidence"].mean(), 2)
high_priority_ratio = round((group['Priority'] == 'High').sum() / len(group) * 100, 1)
highlights = " | ".join(group["Summary"].head(2).tolist())
insights.append({
"Company": company,
"Mentions": mentions,
"Dominant Signal": dominant_signal,
"Avg Confidence": avg_confidence,
"Interest % (High Priority)": f"{high_priority_ratio}%",
"Highlights": highlights
})
return pd.DataFrame(insights).sort_values(by="Avg Confidence", ascending=False).head(5)
# === Pipeline ===
def run_pipeline(csv_path, tavily_api_key, progress_callback=None):
os.environ["TAVILY_API_KEY"] = tavily_api_key
# === Clean old reports (MD and HTML) ===
for file in os.listdir(DATA_DIR):
if file.endswith(".md"):
os.remove(os.path.join(DATA_DIR, file))
for file in os.listdir(HTML_DIR):
if file.endswith(".html"):
os.remove(os.path.join(HTML_DIR, file))
# === Run the new analysis ===
all_articles, company_data = run_value_investing_analysis(csv_path, progress_callback)
html_paths = []
for md_file in os.listdir(DATA_DIR):
if md_file.endswith(".md"):
convert_md_to_html(os.path.join(DATA_DIR, md_file), HTML_DIR)
html_paths.append(os.path.join(HTML_DIR, md_file.replace(".md", ".html")))
articles_df = pd.DataFrame(all_articles)
insights_df = build_company_insights(company_data)
return html_paths, articles_df, insights_df
# import os
# import pandas as pd
# from datetime import datetime
# from dotenv import load_dotenv
# from md_html import convert_single_md_to_html as convert_md_to_html
# from news_analysis import fetch_deep_news, generate_value_investor_report
# from fin_interpreter import analyze_article
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# DATA_DIR = os.path.join(BASE_DIR, "data")
# HTML_DIR = os.path.join(BASE_DIR, "html")
# os.makedirs(DATA_DIR, exist_ok=True)
# os.makedirs(HTML_DIR, exist_ok=True)
# load_dotenv()
# # === Priority Logic ===
# def derive_priority(sentiment, confidence):
# sentiment = sentiment.lower()
# if sentiment == "positive" and confidence > 0.7:
# return "High"
# if sentiment == "negative" and confidence > 0.6:
# return "High"
# if confidence > 0.5:
# return "Medium"
# return "Low"
# # === Main Analysis ===
# def run_value_investing_analysis(csv_path, progress_callback=None):
# current_df = pd.read_csv(csv_path)
# all_articles = []
# company_data = []
# for _, row in current_df.iterrows():
# topic = row.get("topic")
# timespan = row.get("timespan_days", 7)
# if progress_callback:
# progress_callback(f"π Processing topic: {topic} ({timespan} days)")
# try:
# news = fetch_deep_news(topic, timespan)
# if progress_callback:
# progress_callback(f"[DEBUG] fetch_deep_news returned {len(news) if news else 0} articles.")
# except Exception as e:
# if progress_callback:
# progress_callback(f"[ERROR] fetch_deep_news failed: {e}")
# continue
# if not news:
# if progress_callback:
# progress_callback(f"β οΈ No news found for topic: {topic}")
# continue
# for article in news:
# summary = article.get("summary", "") or article.get("content", "")
# title = article.get("title", "Untitled")
# url = article.get("url", "")
# date = article.get("date", datetime.now().strftime("%Y-%m-%d"))
# try:
# result = analyze_article(summary)
# sentiment = result.get("sentiment", "Neutral")
# confidence = float(result.get("confidence", 0.0))
# if progress_callback:
# progress_callback(f"π° [{title[:50]}...] β Sentiment: {sentiment}, Confidence: {confidence}")
# except Exception as e:
# if progress_callback:
# progress_callback(f"[FinBERT ERROR] {e}")
# sentiment, confidence = "Neutral", 0.0
# priority = derive_priority(sentiment, confidence)
# all_articles.append({
# "Title": title,
# "URL": url,
# "Summary": summary[:300] + "..." if summary else "",
# "Priority": priority,
# "Date": date,
# "Sentiment": sentiment,
# "Confidence": confidence
# })
# company_data.append({
# "Company": topic,
# "Sentiment": sentiment,
# "Confidence": confidence,
# "Summary": summary,
# })
# try:
# report_body = generate_value_investor_report(topic, news)
# filename = f"{topic.replace(' ', '_').lower()}_{datetime.now().strftime('%Y-%m-%d')}.md"
# filepath = os.path.join(DATA_DIR, filename)
# with open(filepath, "w", encoding="utf-8") as f:
# f.write(report_body)
# except Exception as e:
# if progress_callback:
# progress_callback(f"[REPORT ERROR] {e}")
# return all_articles, company_data
# # === Insights Tab Data ===
# def build_company_insights(company_data):
# if not company_data:
# return pd.DataFrame()
# df = pd.DataFrame(company_data)
# insights = []
# for company, group in df.groupby("Company"):
# mentions = len(group)
# dominant_sentiment = group["Sentiment"].mode()[0] if not group["Sentiment"].mode().empty else "Neutral"
# avg_confidence = round(group["Confidence"].mean(), 2)
# highlights = " | ".join(group["Summary"].head(2).tolist())
# insights.append({
# "Company": company,
# "Mentions": mentions,
# "Sentiment": dominant_sentiment,
# "Confidence": avg_confidence,
# "Highlights": highlights
# })
# return pd.DataFrame(insights).sort_values(by="Confidence", ascending=False).head(5)
# # === Pipeline ===
# def run_pipeline(csv_path, tavily_api_key, progress_callback=None):
# os.environ["TAVILY_API_KEY"] = tavily_api_key
# all_articles, company_data = run_value_investing_analysis(csv_path, progress_callback)
# html_paths = []
# for md_file in os.listdir(DATA_DIR):
# if md_file.endswith(".md"):
# convert_md_to_html(os.path.join(DATA_DIR, md_file), HTML_DIR)
# html_paths.append(os.path.join(HTML_DIR, md_file.replace(".md", ".html")))
# articles_df = pd.DataFrame(all_articles)
# insights_df = build_company_insights(company_data)
# return html_paths, articles_df, insights_df
|