-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinsight.py
More file actions
2838 lines (2424 loc) · 122 KB
/
finsight.py
File metadata and controls
2838 lines (2424 loc) · 122 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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime
import json
import os
from typing import Dict, List, Any, TypedDict, Annotated, Sequence
import operator
from dotenv import load_dotenv
import yfinance as yf
import requests
from io import BytesIO
import PyPDF2
import time
from functools import lru_cache
import re
from dateutil.relativedelta import relativedelta
from datetime import datetime, timedelta
# LangGraph and LangChain imports
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_groq import ChatGroq
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langgraph.graph import StateGraph, END
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import FAISS
from langchain.schema import Document
from llm_evaluation import show_llm_evaluation_page, LLM_PROFILES
import numpy as np
# Load environment variables
load_dotenv()
def format_currency(amount: float, decimals: int = 2) -> str:
"""Format currency values properly with proper spacing"""
if amount is None or (isinstance(amount, float) and np.isnan(amount)):
return "N/A"
# Ensure amount is a number
try:
amount = float(amount)
except:
return "N/A"
if amount >= 1e9:
return f"${amount/1e9:.{decimals}f}B"
elif amount >= 1e6:
return f"${amount/1e6:.{decimals}f}M"
elif amount >= 1e3:
return f"${amount/1e3:.{decimals}f}K"
else:
return f"${amount:.{decimals}f}"
def clean_response_text(text: str) -> str:
"""Clean and format response text for proper display"""
if not text:
return text
import re
# Fix currency amount patterns: $107.0million -> $107.0 million
text = re.sub(r'\$(\d+(?:,\d{3})*(?:\.\d+)?)(million|billion|thousand|M|B|K)', r'$\1 \2', text, flags=re.IGNORECASE)
# First, fix the specific pattern causing issues: $numberText should be $number Text
# This regex looks for currency followed by numbers then letters without space
text = re.sub(r'\$(\d+(?:,\d{3})*(?:\.\d+)?[BMK]?)([A-Za-z])', r'$\1 \2', text)
# Fix merged bold markers: **word** should have spaces
# First, ensure spaces around bold markers
text = re.sub(r'(\S)\*\*(\S)', r'\1 **\2', text)
text = re.sub(r'(\S)\*\*', r'\1 **', text)
text = re.sub(r'\*\*(\S)', r'** \1', text)
# Fix percentage patterns: number% word should be number% word
text = re.sub(r'(\d+(?:\.\d+)?%)([A-Za-z])', r'\1 \2', text)
# Fix patterns like: of0.0 -> of 0.0
text = re.sub(r'([a-z])(\d+(?:\.\d+)?)', r'\1 \2', text, flags=re.IGNORECASE)
# Fix patterns like: marginof10.0 -> margin of 10.0
text = re.sub(r'([a-z])(of)(\d+)', r'\1 \2 \3', text, flags=re.IGNORECASE)
# Fix patterns like: 4,242Mwith -> 4,242M with
text = re.sub(r'(\d+(?:,\d{3})*(?:\.\d+)?[BMK])([a-z])', r'\1 \2', text)
# Fix merged words: millionand -> million and
text = re.sub(r'(million|billion|thousand)(and|with|or|for)', r'\1 \2', text, flags=re.IGNORECASE)
# Remove duplicate asterisks (e.g., ***** -> **)
text = re.sub(r'\*{3,}', '**', text)
# Clean up any remaining stray asterisks (single asterisks not part of bold)
text = re.sub(r'(?<!\*)\*(?!\*)', ' ', text)
# Ensure proper spacing after punctuation
text = re.sub(r'([.!?])([A-Z])', r'\1 \2', text)
# Fix line breaks
text = text.replace('\\n', '\n')
# Normalize whitespace
text = re.sub(r' +', ' ', text) # Multiple spaces to single space
text = re.sub(r'\n{3,}', '\n\n', text) # Multiple newlines to double
return text.strip()
def clean_list_item(text: str) -> str:
"""Clean individual list items, removing leading asterisks and formatting"""
if not text:
return text
import re
# Remove leading asterisks, numbers, periods, and whitespace
text = re.sub(r'^[\*\s\d\.]+', '', text.strip())
# Also clean using the main clean function
text = clean_response_text(text)
return text.strip()
def format_response_for_display(response_parts: List[str], response_mode: str, query_intent: str,
company: str, ticker: str, insights: Dict, kpis: Dict,
risk_assessment: Dict, market_data: Dict, parsed_data: Dict) -> str:
"""Format the complete response with proper styling"""
formatted_parts = []
if response_mode == "concise":
# CONCISE MODE - Clean, structured format
# Main answer with proper formatting
if insights.get("query_specific_answer"):
answer = clean_response_text(insights["query_specific_answer"])
formatted_parts.append(f"### 📌 {answer}\n")
# For earnings/financial analysis queries, show key metrics
elif query_intent in ["document_analysis", "general_analysis"] and "earnings" in query.lower():
# Format the earnings summary properly
revenue_val = parsed_data.get('revenue', 0)
revenue_str = format_currency(revenue_val)
net_margin_val = kpis.get('net_margin', 0)
pe_ratio_val = kpis.get('price_to_earnings', 0)
answer = f"{company}'s earnings in {period} show a revenue of {revenue_str} with a net margin of {net_margin_val:.1f}% and P/E ratio of {pe_ratio_val:.1f}."
formatted_parts.append(f"### 📌 {answer}\n")
# Investment decision
if insights.get("investment_decision") and query_intent == "investment_decision":
decision = insights["investment_decision"]
emoji = {"BUY": "🟢", "HOLD": "🟡", "SELL": "🔴", "WAIT": "⏸️"}.get(decision, "")
formatted_parts.append(f"Decision: {emoji} {decision}\n")
# Current price
if market_data.get('price') and query_intent == "investment_decision":
formatted_parts.append(f"Current Price: {format_currency(market_data['price'])}")
# Risk level
if query_intent in ["risk_assessment", "investment_decision"]:
risk_score = risk_assessment.get('overall_risk_score', 0)
risk_level = risk_assessment.get('risk_level', 'Unknown')
formatted_parts.append(f"**Risk Level:** {risk_level} ({risk_score:.0f}/100)\n")
# Key metrics in a clean table format
if query_intent in ["investment_decision", "general_analysis", "document_analysis"]:
formatted_parts.append("#### Key Metrics")
formatted_parts.append("| Metric | Value |")
formatted_parts.append("|--------|-------|")
# Safely format each metric
net_margin = kpis.get('net_margin', 0)
pe_ratio = kpis.get('price_to_earnings', 0)
formatted_parts.append(f"| Net Margin | {net_margin:.1f}% |")
formatted_parts.append(f"| P/E Ratio | {pe_ratio:.1f} |")
if market_data.get('52_week_high') and market_data.get('52_week_low'):
range_str = f"{format_currency(market_data['52_week_low'])} - {format_currency(market_data['52_week_high'])}"
formatted_parts.append(f"| 52-Week Range | {range_str} |")
formatted_parts.append("")
# Concerns with bullet points
if insights.get("key_concerns") and len(insights["key_concerns"]) > 0:
formatted_parts.append("#### ⚠️ Concerns")
for concern in insights["key_concerns"][:2]:
formatted_parts.append(f"- {concern}")
formatted_parts.append("")
# Recommendations
if insights.get("recommendations"):
formatted_parts.append("#### 💡 What to do")
for rec in insights["recommendations"][:2]:
formatted_parts.append(f"- {rec}")
formatted_parts.append("")
# Volatility warning
volatile_stocks = ['TSLA', 'GME', 'AMC', 'COIN', 'RIOT', 'MARA', 'PLTR', 'NIO', 'RIVN']
if ticker in volatile_stocks and query_intent == "investment_decision":
formatted_parts.append("*⚠️ Note: This stock is known for high volatility*\n")
else:
# DETAILED MODE - Professional format with sections
# Header
formatted_parts.append(f"# {company} ({ticker}) Financial Analysis\n")
# Investment Overview Box
if query_intent == "investment_decision":
formatted_parts.append("## 📊 Investment Overview")
formatted_parts.append("```")
if market_data.get('price'):
formatted_parts.append(f"Current Price: {format_currency(market_data['price'])}")
if market_data.get('market_cap'):
formatted_parts.append(f"Market Cap: {format_currency(market_data['market_cap'])}")
if market_data.get('52_week_high') and market_data.get('52_week_low'):
current = market_data.get('price', 0)
high = market_data['52_week_high']
low = market_data['52_week_low']
pct_from_high = ((current - high) / high * 100) if high > 0 else 0
formatted_parts.append(f"52-Week Range: {format_currency(low)} - {format_currency(high)}")
formatted_parts.append(f"From High: {pct_from_high:+.1f}%")
formatted_parts.append("```\n")
# Analysis section
if insights.get("query_specific_answer"):
formatted_parts.append("## 📈 Analysis")
# Clean the answer text before adding it
answer = insights["query_specific_answer"]
# Apply the same cleaning as in concise mode
answer = clean_response_text(answer)
# Additional cleaning for common patterns in financial text
import re
# Fix currency patterns: $107.0million -> $107.0 million
answer = re.sub(r'\$(\d+(?:\.\d+)?)(million|billion|thousand)', r'$\1 \2', answer, flags=re.IGNORECASE)
# Fix percentage patterns: of10.0% -> of 10.0%
answer = re.sub(r'of(\d+(?:\.\d+)?%)', r'of \1', answer)
# Fix merged words with numbers: margin10.0 -> margin 10.0
answer = re.sub(r'([a-z])(\d+(?:\.\d+)?)', r'\1 \2', answer, flags=re.IGNORECASE)
# Fix merged percentage with words: 10.0%and -> 10.0% and
answer = re.sub(r'(\d+(?:\.\d+)?%)([a-z])', r'\1 \2', answer, flags=re.IGNORECASE)
# Remove any stray asterisks
answer = re.sub(r'(?<!\*)\*(?!\*)', ' ', answer)
formatted_parts.append(f"{answer}\n")
# Investment Decision
if insights.get("investment_decision") and query_intent == "investment_decision":
decision = insights["investment_decision"]
emoji = {"BUY": "🟢", "HOLD": "🟡", "SELL": "🔴", "WAIT": "⏸️"}.get(decision, "")
formatted_parts.append(f"## {emoji} Investment Decision: {decision}")
# Add reasoning
if decision == "BUY":
formatted_parts.append("*Strong fundamentals support accumulation at current levels.*")
elif decision == "HOLD":
formatted_parts.append("*Mixed signals suggest maintaining current position while monitoring developments.*")
elif decision == "SELL":
formatted_parts.append("*Risk factors outweigh potential rewards at current valuation.*")
else:
formatted_parts.append("*Unclear trends warrant patience before taking a position.*")
formatted_parts.append("")
# Financial Metrics Table
if query_intent in ["investment_decision", "general_analysis"]:
formatted_parts.append("## 📊 Financial Metrics")
formatted_parts.append("| Metric | Value |")
formatted_parts.append("|--------|-------|")
formatted_parts.append(f"| Revenue | {format_currency(parsed_data.get('revenue', 0))} |")
formatted_parts.append(f"| Gross Margin | {kpis.get('gross_margin', 0):.1f}% |")
formatted_parts.append(f"| Net Margin | {kpis.get('net_margin', 0):.1f}% |")
formatted_parts.append(f"| P/E Ratio | {kpis.get('price_to_earnings', 0):.1f} |")
formatted_parts.append(f"| ROE | {kpis.get('return_on_equity', 0):.1f}% |")
formatted_parts.append(f"| Debt/Equity | {kpis.get('debt_to_equity', 0):.2f} |")
formatted_parts.append("")
# Strengths and Concerns in columns
if insights.get("key_strengths") or insights.get("key_concerns"):
formatted_parts.append("## 💪 Strengths vs ⚠️ Concerns")
formatted_parts.append("")
formatted_parts.append("### Strengths")
if insights.get("key_strengths"):
for strength in insights["key_strengths"]:
# Clean the strength text
clean_strength = clean_list_item(strength)
formatted_parts.append(f"- ✅ {clean_strength}")
formatted_parts.append("")
formatted_parts.append("### Concerns")
if insights.get("key_concerns"):
for concern in insights["key_concerns"]:
# Clean the concern text
clean_concern = clean_list_item(concern)
formatted_parts.append(f"- ⚠️ {clean_concern}")
formatted_parts.append("")
# Investment Strategy
if insights.get("recommendations"):
formatted_parts.append("## 🎯 Investment Strategy")
for i, rec in enumerate(insights["recommendations"], 1):
# Clean the recommendation text by removing any existing numbering and asterisks
clean_rec = rec.strip()
# Remove patterns like "** 1. **", "**1.**", "1.", "1)", etc. from the beginning
import re
clean_rec = re.sub(r'^[\*\s]*\d+[\.\)]\s*[\*\s]*', '', clean_rec)
# Remove any remaining leading/trailing asterisks
clean_rec = re.sub(r'^[\*\s]+|[\*\s]+$', '', clean_rec)
# Remove internal double asterisks that should be formatting
clean_rec = re.sub(r'\*\*\s*', '', clean_rec)
clean_rec = re.sub(r'\s*\*\*', '', clean_rec)
# Format as a clean numbered list
formatted_parts.append(f"{i}. {clean_rec}")
formatted_parts.append("")
# Outlook sections
if insights.get("market_position"):
formatted_parts.append("## 🏆 Market Position")
formatted_parts.append(f"{insights['market_position']}\n")
if insights.get("future_outlook"):
formatted_parts.append("## 🔮 Future Outlook")
formatted_parts.append(f"{insights['future_outlook']}\n")
return "\n".join(formatted_parts)
# Add this after your imports
class DateTimeEncoder(json.JSONEncoder):
"""JSON encoder that handles datetime and pandas Timestamp objects"""
def default(self, obj):
if isinstance(obj, (datetime, pd.Timestamp)):
return obj.strftime('%Y-%m-%d')
elif isinstance(obj, pd.Series):
return obj.tolist()
elif pd.isna(obj):
return None
return super().default(obj)
# SEC EDGAR API Configuration
SEC_HEADERS = {
'User-Agent': 'Your Company Name your.email@example.com'
}
SEC_BASE_URL = "https://data.sec.gov/api/xbrl/companyconcept/CIK{cik}/us-gaap/{concept}.json"
# Company discovery function using Yahoo Finance search
def discover_company_info(company_query: str):
"""
Discover company ticker and CIK using various methods
Returns: dict with ticker, full_name, cik, and confidence score
"""
# Common company name to ticker mappings
COMPANY_TICKER_MAP = {
# Banks and Financial Services
"state street": "STT",
"state street corporation": "STT",
"state street corp": "STT",
"jpmorgan": "JPM",
"jp morgan": "JPM",
"jpmorgan chase": "JPM",
"bank of america": "BAC",
"wells fargo": "WFC",
"goldman sachs": "GS",
"morgan stanley": "MS",
"charles schwab": "SCHW",
# Tech Companies
"snowflake": "SNOW",
"palantir": "PLTR",
"servicenow": "NOW",
"service now": "NOW",
"salesforce": "CRM",
"spotify": "SPOT",
"uber": "UBER",
"lyft": "LYFT",
"airbnb": "ABNB",
"coinbase": "COIN",
"robinhood": "HOOD",
# Big Tech
"apple": "AAPL",
"microsoft": "MSFT",
"google": "GOOGL",
"alphabet": "GOOGL",
"amazon": "AMZN",
"meta": "META",
"facebook": "META",
"netflix": "NFLX",
"tesla": "TSLA",
"nvidia": "NVDA",
# Other Major Companies
"walmart": "WMT",
"disney": "DIS",
"coca cola": "KO",
"coca-cola": "KO",
"pepsi": "PEP",
"pepsico": "PEP",
"mcdonald's": "MCD",
"mcdonalds": "MCD",
"starbucks": "SBUX",
"nike": "NKE",
"intel": "INTC",
"amd": "AMD",
"advanced micro devices": "AMD"
}
try:
# Clean the query
clean_query = company_query.lower().strip()
# Method 1: Check our mapping first
for company_name, ticker in COMPANY_TICKER_MAP.items():
if company_name in clean_query or clean_query in company_name:
# Verify with yfinance
try:
stock = yf.Ticker(ticker)
info = stock.info
if info and 'longName' in info:
return {
"ticker": ticker,
"full_name": info.get('longName', company_query),
"cik": None,
"confidence": 0.95,
"method": "known_mapping"
}
except:
pass
# Method 2: Try direct ticker lookup (if query is short and uppercase)
if len(company_query) <= 5 and company_query.isupper():
try:
stock = yf.Ticker(company_query)
info = stock.info
if info and 'longName' in info:
return {
"ticker": company_query,
"full_name": info.get('longName', company_query),
"cik": None,
"confidence": 0.9,
"method": "direct_ticker"
}
except:
pass
# Method 3: Try the query as a ticker (uppercase it)
ticker_test = company_query.upper().replace(" ", "")
if len(ticker_test) <= 5:
try:
stock = yf.Ticker(ticker_test)
info = stock.info
if info and 'longName' in info:
return {
"ticker": ticker_test,
"full_name": info.get('longName', company_query),
"cik": None,
"confidence": 0.8,
"method": "uppercase_ticker"
}
except:
pass
# Method 4: Remove common suffixes and try again
for suffix in [' inc', ' corp', ' corporation', ' limited', ' ltd', ' plc', ' sa', ' ag', ' nv', ' se', ' co', '.com']:
if clean_query.endswith(suffix):
base_name = clean_query[:-len(suffix)].strip()
# Check mapping again with base name
for company_name, ticker in COMPANY_TICKER_MAP.items():
if base_name in company_name or company_name in base_name:
try:
stock = yf.Ticker(ticker)
info = stock.info
if info and 'longName' in info:
return {
"ticker": ticker,
"full_name": info.get('longName', company_query),
"cik": None,
"confidence": 0.85,
"method": "suffix_removed_mapping"
}
except:
pass
# Method 5: Use SEC Edgar search API for CIK lookup
sec_search_url = f"https://www.sec.gov/cgi-bin/browse-edgar?company={company_query}&output=json"
try:
response = requests.get(sec_search_url, headers=SEC_HEADERS, timeout=5)
if response.status_code == 200:
data = response.json()
if 'companyMatch' in data and len(data['companyMatch']) > 0:
match = data['companyMatch'][0]
cik = str(match.get('cik', '')).zfill(10)
name = match.get('name', company_query)
# Try to find ticker from SEC data or use a mapping
ticker = None
# You could enhance this by maintaining a CIK-to-ticker mapping
return {
"ticker": ticker or company_query.upper()[:10], # Longer limit for unknown tickers
"full_name": name,
"cik": cik,
"confidence": 0.6,
"method": "sec_search"
}
except:
pass
# Method 6: Fallback - but don't truncate to 5 chars
# Instead, return the query as-is for the LLM to handle
return {
"ticker": company_query.upper().replace(" ", "")[:10], # Allow up to 10 chars
"full_name": company_query,
"cik": None,
"confidence": 0.2, # Very low confidence
"method": "fallback",
"needs_llm_help": True # Flag for LLM to help
}
except Exception as e:
return {
"ticker": "UNKNOWN",
"full_name": company_query,
"cik": None,
"confidence": 0.1,
"method": "error",
"error": str(e)
}
# Function to search for company CIK if not found
def search_company_cik(company_name: str, ticker: str = None):
"""Search for company CIK using SEC Edgar database"""
try:
# Try with company name
search_queries = [company_name]
if ticker:
search_queries.append(ticker)
for query in search_queries:
url = f"https://www.sec.gov/cgi-bin/browse-edgar?company={query}&output=json"
response = requests.get(url, headers=SEC_HEADERS, timeout=5)
if response.status_code == 200:
data = response.json()
if 'companyMatch' in data and len(data['companyMatch']) > 0:
# Return the first match
match = data['companyMatch'][0]
return str(match.get('cik', '')).zfill(10)
return None
except Exception:
return None
def extract_query_entities(query: str):
"""Extract company name and time period from natural language query"""
query_lower = query.lower()
# First, try to identify company from the query
company_name = None
# Common patterns for company mentions
# Pattern 1: "Company Name" (in quotes)
quote_pattern = r'"([^"]+)"'
quote_match = re.search(quote_pattern, query)
if quote_match:
company_name = quote_match.group(1)
# Pattern 2: Known company keywords followed by company name
company_keywords = ['invest in', 'analyze', 'buy', 'sell', 'about', 'is', 'how is', "what's", 'should i invest in', 'earnings of', 'financials of']
for keyword in company_keywords:
pattern = rf'{keyword}\s+([A-Z][A-Za-z0-9\s&\.\,\-]+?)(?:\s+(?:stock|shares|company|corp|inc|ltd|limited|good|bad|risky|safe|for|in|a\s|an\s|the\s|\?|$))'
match = re.search(pattern, query, re.IGNORECASE)
if match and not company_name:
potential_company = match.group(1).strip()
# Clean up the extracted name
for stop_word in ['for', 'in', 'a', 'an', 'the', 'good', 'bad', 'risky', 'safe']:
potential_company = re.sub(rf'\s+{stop_word}\s*$', '', potential_company, flags=re.IGNORECASE)
company_name = potential_company
break
# Pattern 3: Ticker symbols (usually uppercase, 1-5 letters)
if not company_name:
ticker_pattern = r'\b([A-Z]{1,5})\b'
ticker_matches = re.findall(ticker_pattern, query)
for potential_ticker in ticker_matches:
# Skip common words that might be mistaken for tickers
if potential_ticker not in ['I', 'A', 'Q', 'FY', 'CEO', 'CFO', 'IPO', 'EPS', 'PE']:
company_name = potential_ticker
break
# Pattern 4: Any capitalized phrase that might be a company
if not company_name:
# Look for capitalized words/phrases
cap_pattern = r'(?:^|(?<=\s))([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)'
cap_matches = re.findall(cap_pattern, query)
for match in cap_matches:
# Filter out common non-company words
if match.lower() not in ['should', 'what', 'how', 'when', 'where', 'why', 'quarter', 'fiscal', 'year', 'analyze', 'earnings']:
company_name = match
break
# Time period extraction - IMPROVED
detected_period = None
current_year = datetime.now().year
# Check for specific year mentions (e.g., "in 2024", "2024 earnings", "fiscal 2024")
year_pattern = r'(?:in\s+|for\s+|fiscal\s+|fy\s*)?(\d{4})(?:\s+earnings|\s+financials|\s+results)?'
year_match = re.search(year_pattern, query_lower)
if year_match:
year = year_match.group(1)
detected_period = f"FY {year}"
# Check for specific quarters
elif re.search(r'q(\d)\s*(\d{4})', query_lower):
quarter_match = re.search(r'q(\d)\s*(\d{4})', query_lower)
detected_period = f"Q{quarter_match.group(1)} {quarter_match.group(2)}"
# Check for year ranges
elif "past 5 years" in query_lower or "last 5 years" in query_lower:
detected_period = f"FY {current_year-5} to FY {current_year}"
elif "past 3 years" in query_lower or "last 3 years" in query_lower:
detected_period = f"FY {current_year-3} to FY {current_year}"
elif "past year" in query_lower or "last year" in query_lower:
detected_period = f"FY {current_year-1}"
elif "this year" in query_lower or "current year" in query_lower:
detected_period = f"FY {current_year}"
# Check for quarters without year
elif re.search(r'q(\d)(?:\s|$)', query_lower):
quarter_match = re.search(r'q(\d)(?:\s|$)', query_lower)
# Assume current year for quarter without year
detected_period = f"Q{quarter_match.group(1)} {current_year}"
# Check for fiscal year pattern
elif re.search(r'fy\s*(\d{4})', query_lower):
fy_match = re.search(r'fy\s*(\d{4})', query_lower)
detected_period = f"FY {fy_match.group(1)}"
return company_name, detected_period
# Company Discovery Agent Prompt
COMPANY_DISCOVERY_PROMPT = ChatPromptTemplate.from_messages([
("system", """You are a company discovery agent. Your job is to identify the company being discussed and find its trading information.
Given the user query: {query}
Extracted company name: {extracted_company}
Discovery results: {discovery_results}
Your task:
1. Confirm if the discovered company matches the user's intent
2. If multiple matches exist, choose the most likely one
3. Extract and validate the ticker symbol
4. Determine confidence in the match
Return a JSON response with:
- company_name: The official company name
- ticker: The stock ticker symbol
- cik: SEC CIK number (if available)
- confidence: 0-1 score of match accuracy
- alternative_matches: List of other possible companies if confidence < 0.8
- reasoning: Brief explanation of your choice
Be careful with ambiguous names. For example:
- "Apple" usually means Apple Inc. (AAPL)
- "Meta" means Meta Platforms Inc. (META), formerly Facebook
- "Google" means Alphabet Inc. (GOOGL/GOOG)
"""),
MessagesPlaceholder(variable_name="messages"),
])
# Updated Graph State to include company discovery
class FinancialAnalysisState(TypedDict):
messages: Annotated[Sequence[BaseMessage], operator.add]
query: str
extracted_company: str # Raw extracted company
company: str # Resolved company name
ticker: str # Resolved ticker
cik: str # Resolved CIK
period: str
parsed_data: Dict
kpis: Dict
risk_assessment: Dict
insights: Dict
current_agent: str
uploaded_content: str
market_data: Dict
data_sources: List[Dict]
period_validation: Dict
response_mode: str
company_confidence: float
# Enhanced company discovery agent that uses LLM when confidence is low
def create_company_discovery_agent(llm):
"""Agent to discover and validate company information"""
def company_discoverer(state: FinancialAnalysisState):
extracted_company = state.get("extracted_company", "")
if not extracted_company:
# If no company extracted, ask the LLM to identify it from the query
extract_prompt = f"Extract the company name from this query: '{state['query']}'. Return only the company name or ticker symbol."
response = llm.invoke([HumanMessage(content=extract_prompt)])
extracted_company = response.content.strip()
# Use discovery function
discovery_results = discover_company_info(extracted_company)
# If low confidence or needs LLM help, use LLM to improve
if discovery_results["confidence"] < 0.7 or discovery_results.get("needs_llm_help", False):
# Enhanced prompt for LLM
llm_prompt = f"""Identify the correct stock ticker for this company query: "{extracted_company}"
Common examples:
- "State Street" or "State Street Corporation" → STT (State Street Corp)
- "Snowflake" → SNOW (Snowflake Inc)
- "Palantir" → PLTR (Palantir Technologies)
- "ServiceNow" or "Service Now" → NOW (ServiceNow Inc)
If this is a well-known public company, provide the correct ticker symbol.
Return JSON with: {{"ticker": "XXX", "company_name": "Full Company Name", "confidence": 0.0-1.0}}
Query: {extracted_company}"""
response = llm.invoke([HumanMessage(content=llm_prompt)])
try:
import re
json_match = re.search(r'\{.*\}', response.content, re.DOTALL)
if json_match:
llm_result = json.loads(json_match.group())
# Verify the LLM's suggestion with yfinance
suggested_ticker = llm_result.get("ticker", "")
if suggested_ticker and suggested_ticker != "UNKNOWN":
try:
stock = yf.Ticker(suggested_ticker)
info = stock.info
if info and 'longName' in info:
discovery_results = {
"ticker": suggested_ticker,
"full_name": info.get('longName', llm_result.get("company_name", extracted_company)),
"cik": None,
"confidence": min(llm_result.get("confidence", 0.8), 0.9),
"method": "llm_assisted"
}
except:
# LLM suggestion didn't verify, keep original but with LLM's name
discovery_results["full_name"] = llm_result.get("company_name", discovery_results["full_name"])
discovery_results["confidence"] = min(discovery_results["confidence"], 0.5)
except:
pass
# Get CIK if not found
if not discovery_results.get("cik") and discovery_results.get("ticker"):
cik = search_company_cik(
discovery_results.get("full_name", extracted_company),
discovery_results.get("ticker")
)
discovery_results["cik"] = cik
# Final validation - if ticker is suspicious (like "STATE" or "SNOWF"), mark low confidence
suspicious_patterns = [
len(discovery_results["ticker"]) == 5 and discovery_results["ticker"] == extracted_company.upper()[:5],
discovery_results["ticker"] in ["STATE", "SNOWF", "UNKNOWN"],
discovery_results["method"] == "fallback"
]
if any(suspicious_patterns):
discovery_results["confidence"] = min(discovery_results["confidence"], 0.3)
# Update state with discovered information
return {
"messages": [AIMessage(content=f"Discovered company: {discovery_results['full_name']} ({discovery_results['ticker']}) with confidence {discovery_results['confidence']:.2f}")],
"company": discovery_results["full_name"],
"ticker": discovery_results["ticker"],
"cik": discovery_results["cik"],
"company_confidence": discovery_results["confidence"],
"current_agent": "parser"
}
return company_discoverer
# Update the detect_query_intent function (keep existing)
def detect_query_intent(query: str):
"""Detect the user's intent from their query"""
query_lower = query.lower()
# Investment decision queries
investment_keywords = ["invest", "buy", "sell", "hold", "should i", "good investment", "worth buying", "risky"]
# Analysis queries
analysis_keywords = ["analyze", "review", "summarize", "explain", "tell me about", "what are", "show me"]
# Risk queries
risk_keywords = ["risk", "risky", "safe", "dangerous", "volatility"]
# Comparison queries
comparison_keywords = ["compare", "versus", "vs", "better than", "difference between"]
# Document-specific queries
document_keywords = ["attached", "document", "pdf", "file", "earnings report", "10-k", "10-q"]
# Determine primary intent
if any(keyword in query_lower for keyword in investment_keywords):
return "investment_decision"
elif any(keyword in query_lower for keyword in risk_keywords):
return "risk_assessment"
elif any(keyword in query_lower for keyword in comparison_keywords):
return "comparison"
elif any(keyword in query_lower for keyword in document_keywords) and any(keyword in query_lower for keyword in analysis_keywords):
return "document_analysis"
elif any(keyword in query_lower for keyword in analysis_keywords):
return "general_analysis"
else:
return "general_query"
# Function to parse period to date with support for ranges
def parse_period_to_date(period: str):
"""Convert period string to date range"""
current_year = datetime.now().year
# Handle year ranges (e.g., "FY 2019 to FY 2024")
range_pattern = r'FY (\d{4}) to FY (\d{4})'
range_match = re.match(range_pattern, period)
if range_match:
start_year = int(range_match.group(1))
end_year = int(range_match.group(2))
return datetime(start_year, 1, 1), datetime(end_year, 12, 31)
# Handle fiscal year
if period.startswith("FY"):
year = int(period.replace("FY ", ""))
start_date = datetime(year, 1, 1)
end_date = datetime(year, 12, 31)
return start_date, end_date
# Handle quarters
quarter_match = re.match(r"Q(\d) (\d{4})", period)
if quarter_match:
quarter = int(quarter_match.group(1))
year = int(quarter_match.group(2))
# Quarter to month mapping
quarter_months = {
1: (1, 3), # Jan-Mar
2: (4, 6), # Apr-Jun
3: (7, 9), # Jul-Sep
4: (10, 12) # Oct-Dec
}
start_month, end_month = quarter_months[quarter]
start_date = datetime(year, start_month, 1)
# Get last day of end month
if end_month == 12:
end_date = datetime(year, 12, 31)
else:
end_date = datetime(year, end_month + 1, 1) - timedelta(days=1)
return start_date, end_date
# Default to current quarter if parsing fails
return None, None
def get_actual_data_period(data_date):
"""Convert a date to period string (Q1 2024, etc)"""
if not data_date:
return "Unknown"
month = data_date.month
year = data_date.year
if month <= 3:
return f"Q1 {year}"
elif month <= 6:
return f"Q2 {year}"
elif month <= 9:
return f"Q3 {year}"
else:
return f"Q4 {year}"
def clean_llm_text(text: str) -> str:
"""Clean text from LLM output while preserving word boundaries"""
if not text:
return text
import re
# Step 1: Normalize spacing around asterisks to avoid word merging
# Add spaces around asterisks first to protect word boundaries
text = re.sub(r'(\S)\*(\S)', r'\1 * \2', text) # e.g., "word*word" -> "word * word"
text = re.sub(r'\s*\*\s*', ' ', text) # Normalize all * to single space
# Step 2: Remove stray single asterisks (not double for bold markdown)
text = re.sub(r'(?<!\*)\*(?!\*)', '', text)
# Step 3: Remove strange unicode or leftover asterisk characters
text = text.replace('∗', '') # Unicode asterisk
text = text.replace('*', '') # Fallback, though most handled above
# Step 4: Unescape characters
text = text.replace('\\n', '\n')
text = text.replace('\\t', ' ')
# Step 5: Normalize whitespace
text = re.sub(r' +', ' ', text) # Reduce multiple spaces
text = re.sub(r'\n{3,}', '\n\n', text) # Reduce excessive newlines
return text.strip()
# Initialize LLMs
def get_llms():
"""Initialize all LLMs with API keys"""
llms = {}
# OpenAI GPT-4
if os.getenv("OPENAI_API_KEY"):
llms["gpt-4"] = ChatOpenAI(
model="gpt-4o",
temperature=0.7,
api_key=os.getenv("OPENAI_API_KEY")
)
# Groq (Fast inference with open models)
if os.getenv("GROQ_API_KEY"):
# Groq offers multiple models - using mistral for best quality
llms["groq-mixtral"] = ChatGroq(
model="mistral-saba-24b",
temperature=0.7,
api_key=os.getenv("GROQ_API_KEY")
)
# Also add Llama 2 70B as an option
llms["groq-llama3"] = ChatGroq(
model="llama3-70b-8192",
temperature=0.7,
api_key=os.getenv("GROQ_API_KEY")
)
# Google Gemini
if os.getenv("GOOGLE_API_KEY"):
llms["gemini-pro"] = ChatGoogleGenerativeAI(
model="gemini-1.5-flash",
temperature=0.7,
google_api_key=os.getenv("GOOGLE_API_KEY")
)
# Anthropic Claude (keeping as optional)
if os.getenv("ANTHROPIC_API_KEY"):
llms["claude-3"] = ChatAnthropic(
model="claude-3-sonnet-20240229",
temperature=0.7,
api_key=os.getenv("ANTHROPIC_API_KEY")
)
return llms
def fetch_yahoo_finance_data(ticker: str, period: str):
"""Fetch financial data from Yahoo Finance for specific period"""
# Check cache first
cache_key = f"{ticker}_{period}_{datetime.now().strftime('%Y-%m-%d')}"
if cache_key in st.session_state.yahoo_cache:
return st.session_state.yahoo_cache[cache_key]
# Rate limiting
current_time = time.time()
time_since_last = current_time - st.session_state.last_yahoo_request
if time_since_last < 2:
time.sleep(2 - time_since_last)
try:
st.session_state.last_yahoo_request = time.time()
stock = yf.Ticker(ticker)
# Parse the requested period
start_date, end_date = parse_period_to_date(period)
result = {
"requested_period": period,
"data_period": "Unknown",
"data_date": None,
"period_match": False,