Spaces:
Running
Running
File size: 12,690 Bytes
97063b2 9df4cc0 97063b2 9df4cc0 97063b2 9df4cc0 97063b2 9df4cc0 97063b2 9df4cc0 97063b2 9df4cc0 97063b2 9df4cc0 373f148 9df4cc0 373f148 9df4cc0 373f148 9df4cc0 |
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 |
# import os
# import csv
# from datetime import datetime
# from langchain_openai import ChatOpenAI
# from langchain_core.prompts import PromptTemplate
# from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate
# import requests
# from dotenv import load_dotenv
# from fin_interpreter import analyze_article
# from tavily import TavilyClient
# # === Load environment or passed keys ===
# load_dotenv()
# OPENAI_KEY = os.environ.get("OPENAI_API_KEY") or os.getenv("OPENAI_KEY")
# TAVILY_KEY = os.environ.get("TAVILY_API_KEY") or os.getenv("TAVILY_KEY")
# # === Initialize Tavily Client ===
# tavily_client = TavilyClient(api_key=TAVILY_KEY)
# # === Get OpenAI client when needed ===
# def get_llm():
# openai_key = os.environ.get("OPENAI_API_KEY")
# if not openai_key:
# raise ValueError("OPENAI_API_KEY not found.")
# return ChatOpenAI(model_name="gpt-4.1", openai_api_key=openai_key)
# # === Related Terms ===
# def get_related_terms(topic):
# llm = get_llm()
# prompt = f"What are 5 closely related financial or industry terms to '{topic}'?"
# response = llm.invoke(prompt)
# return response.content.split(",")
# def tavily_search(query, days, max_results=10):
# api_key = os.getenv("TAVILY_KEY")
# url = "https://api.tavily.com/search"
# headers = {"Authorization": f"Bearer {api_key}"}
# payload = {
# "query": query,
# "search_depth": "advanced",
# "topic": "news",
# "days": int(days),
# "max_results": max_results,
# "include_answer": False,
# "include_raw_content": False
# }
# response = requests.post(url, json=payload, headers=headers)
# return response.json()
# # === Smart News Search ===
# def fetch_deep_news(topic, days):
# all_results = []
# seen_urls = set()
# base_queries = [
# topic,
# f"{topic} AND startup",
# f"{topic} AND acquisition OR merger OR funding",
# f"{topic} AND CEO OR executive OR leadership",
# f"{topic} AND venture capital OR Series A OR Series B",
# f"{topic} AND government grant OR approval OR contract",
# f"{topic} AND underrated OR small-cap OR micro-cap"
# ]
# investor_queries = [
# f"{topic} AND BlackRock OR Vanguard OR SoftBank",
# f"{topic} AND Elon Musk OR Sam Altman OR Peter Thiel",
# f"{topic} AND Berkshire Hathaway OR Warren Buffett",
# f"{topic} AND institutional investor OR hedge fund",
# ]
# related_terms = get_related_terms(topic)
# synonym_queries = [f"{term} AND {kw}" for term in related_terms for kw in ["startup", "funding", "merger", "acquisition"]]
# all_queries = base_queries + investor_queries + synonym_queries
# for query in all_queries:
# try:
# print(f"๐ Tavily query: {query}")
# response = requests.post(
# url="https://api.tavily.com/search",
# headers={
# "Authorization": f"Bearer {TAVILY_KEY}",
# "Content-Type": "application/json"
# },
# json={
# "query": query,
# "search_depth": "advanced",
# "topic": "news",
# "days": int(days),
# "max_results": 10,
# "include_answer": False,
# "include_raw_content": False
# }
# )
# if response.status_code != 200:
# print(f"โ ๏ธ Tavily API error: {response.status_code} - {response.text}")
# continue
# for item in response.json().get("results", []):
# url = item.get("url")
# content = item.get("content", "") or item.get("summary", "") or item.get("title", "")
# if url and url not in seen_urls and len(content) > 150:
# all_results.append({
# "title": item.get("title"),
# "url": url,
# "content": content
# })
# seen_urls.add(url)
# except Exception as e:
# print(f"โ ๏ธ Tavily request failed for query '{query}': {e}")
# print(f"๐ฐ Total articles collected: {len(all_results)}")
# return all_results
# # === Generate Markdown Report ===
# def generate_value_investor_report(topic, news_results, max_articles=20, max_chars_per_article=400):
# news_results = news_results[:max_articles]
# for item in news_results:
# result = analyze_article(item["content"])
# item["fin_sentiment"] = result.get("sentiment", "neutral")
# item["fin_confidence"] = result.get("confidence", 0.0)
# item["investment_decision"] = result.get("investment_decision", "Watch")
# article_summary = "".join(
# f"- **{item['title']}**: {item['content'][:max_chars_per_article]}... "
# f"(Sentiment: {item['fin_sentiment'].title()}, Confidence: {item['fin_confidence']:.2f}, "
# f"Decision: {item['investment_decision']}) [link]({item['url']})\n"
# for item in news_results
# )
# prompt = PromptTemplate.from_template("""
# You're a highly focused value investor. Analyze this week's news on "{Topic}".
# Your goal is to uncover:
# - Meaningful events (e.g., CEO joining a startup, insider buys, big-name partnerships)
# - Startups or small caps that may signal undervalued opportunity
# - Connections to key individuals or institutions (e.g., Elon Musk investing, Sam Altman joining)
# - Companies with strong fundamentals: low P/E, low P/B, high ROE, recent IPOs, moats, or high free cash flow
# ### News
# {ArticleSummaries}
# Write a markdown memo with:
# 1. **Key Value Signals**
# 2. **Stocks or Startups to Watch**
# 3. **What Smart Money Might Be Acting On**
# 4. **References**
# 5. **Investment Hypothesis**
# Include context and macroeconomic/regulatory angles. Add an intro on sentiment and market trends for the week.
# """)
# chat_prompt = ChatPromptTemplate.from_messages([
# SystemMessagePromptTemplate(prompt=prompt)
# ])
# prompt_value = chat_prompt.format_prompt(
# Topic=topic,
# ArticleSummaries=article_summary
# ).to_messages()
# llm = get_llm()
# result = llm.invoke(prompt_value)
# return result.content
import os
import csv
from datetime import datetime
from langchain_openai import ChatOpenAI
from langchain_core.prompts import PromptTemplate
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate
import requests
from dotenv import load_dotenv
from fin_interpreter import analyze_article
# === Load environment ===
load_dotenv()
OPENAI_KEY = os.environ.get("OPENAI_API_KEY") or os.getenv("OPENAI_KEY")
TAVILY_KEY = None # Will be accessed dynamically at runtime
# === Get OpenAI client when needed ===
def get_llm():
openai_key = os.environ.get("OPENAI_API_KEY")
if not openai_key:
raise ValueError("OPENAI_API_KEY not found.")
return ChatOpenAI(model_name="gpt-4.1", openai_api_key=openai_key)
# === Related Terms ===
def get_related_terms(topic):
llm = get_llm()
prompt = f"What are 5 closely related financial or industry terms to '{topic}'?"
response = llm.invoke(prompt)
return response.content.split(",")
# === Tavily Search ===
def tavily_search(query, days, max_results=10):
api_key = os.environ.get("TAVILY_API_KEY") or TAVILY_KEY
url = "https://api.tavily.com/search"
headers = {"Authorization": f"Bearer {api_key}"}
payload = {
"query": query,
"search_depth": "advanced",
"topic": "news",
"days": int(days),
"max_results": max_results,
"include_answer": False,
"include_raw_content": False
}
response = requests.post(url, json=payload, headers=headers)
return response.json()
# === Smart News Search ===
def fetch_deep_news(topic, days):
all_results = []
seen_urls = set()
base_queries = [
topic,
f"{topic} AND startup",
f"{topic} AND acquisition OR merger OR funding",
f"{topic} AND CEO OR executive OR leadership",
f"{topic} AND venture capital OR Series A OR Series B",
f"{topic} AND government grant OR approval OR contract",
f"{topic} AND underrated OR small-cap OR micro-cap"
]
investor_queries = [
f"{topic} AND BlackRock OR Vanguard OR SoftBank",
f"{topic} AND Elon Musk OR Sam Altman OR Peter Thiel",
f"{topic} AND Berkshire Hathaway OR Warren Buffett",
f"{topic} AND institutional investor OR hedge fund",
]
related_terms = get_related_terms(topic)
synonym_queries = [f"{term} AND {kw}" for term in related_terms for kw in ["startup", "funding", "merger", "acquisition"]]
all_queries = base_queries + investor_queries + synonym_queries
for query in all_queries:
try:
print(f"๐ Tavily query: {query}")
response = tavily_search(query, days)
if not isinstance(response, dict) or "results" not in response:
print(f"โ ๏ธ Tavily API response issue: {response}")
continue
for item in response.get("results", []):
url = item.get("url")
content = item.get("content", "") or item.get("summary", "") or item.get("title", "")
if url and url not in seen_urls and len(content) > 150:
all_results.append({
"title": item.get("title"),
"url": url,
"content": content
})
seen_urls.add(url)
except Exception as e:
print(f"โ ๏ธ Tavily request failed for query '{query}': {e}")
print(f"๐ฐ Total articles collected: {len(all_results)}")
return all_results
# === Generate Markdown Report ===
def generate_value_investor_report(topic, news_results, max_articles=20, max_chars_per_article=400):
news_results = news_results[:max_articles]
for item in news_results:
result = analyze_article(item["content"])
item["fin_sentiment"] = result.get("sentiment", "neutral")
item["fin_confidence"] = result.get("confidence", 0.0)
item["investment_decision"] = result.get("investment_decision", "Watch")
article_summary = "".join(
f"- **{item['title']}**: {item['content'][:max_chars_per_article]}... "
f"(Sentiment: {item['fin_sentiment'].title()}, Confidence: {item['fin_confidence']:.2f}, "
f"Decision: {item['investment_decision']}) [link]({item['url']})\n"
for item in news_results
)
prompt = PromptTemplate.from_template("""
You're a highly focused value investor. Analyze this week's news on "{Topic}".
Your goal is to uncover:
- Meaningful events (e.g., CEO joining a startup, insider buys, big-name partnerships)
- Startups or small caps that may signal undervalued opportunity
- Connections to key individuals or institutions (e.g., Elon Musk investing, Sam Altman joining)
- Companies with strong fundamentals: low P/E, low P/B, high ROE, recent IPOs, moats, or high free cash flow - THEY MUST INCLUDE THE LINK AS WELL and this is very important
### News
{ArticleSummaries}
Write a markdown memo with:
1. **Key Value Signals**
2. **Stocks or Startups to Watch**
3. **What Smart Money Might Be Acting On**
4. **References**
5. **Investment Hypothesis**
### ๐ Executive Summary
Summarize the topic's current investment environment in 3โ4 bullet points. Include sentiment, risks, and catalysts.
---
### ๐ Signals and Analysis (Include Sources)
For each important news item, write a short paragraph with:
- What happened
- Why it matters (financially)
- Embedded source as `[source title](url)`
- Bold any key financial terms (e.g., **Series A**, **merger**, **valuation**)
---
### ๐ง Investment Thesis
Give a reasoned conclusion:
- Is this a buy/sell/watch opportunity?
- Whatโs the risk/reward?
- What signals or themes matter most?
Include context and macroeconomic/regulatory angles. Add an intro on sentiment and market trends for the week.
""")
chat_prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate(prompt=prompt)
])
prompt_value = chat_prompt.format_prompt(
Topic=topic,
ArticleSummaries=article_summary
).to_messages()
llm = get_llm()
result = llm.invoke(prompt_value)
return result.content
|