Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

relationship map

tilakpatel222085d839f6ad
diff --git a/fincept-terminal-desktop/src-tauri/capabilities/default.json b/fincept-terminal-desktop/src-tauri/capabilities/default.json
index c1b78d9da..b5e30a07f 100644
--- a/fincept-terminal-desktop/src-tauri/capabilities/default.json
+++ b/fincept-terminal-desktop/src-tauri/capabilities/default.json
@@ -6,6 +6,8 @@
"permissions": [
"core:default",
"opener:default",
+ "shell:default",
+ "shell:allow-open",
"http:default",
{
"identifier": "http:default",
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.py b/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.py
index 841168145..b96b791d3 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.py
@@ -271,6 +271,75 @@ class EdgarToolsWrapper:
except Exception as e:
return {"error": EdgarError("get_company_filings", str(e), traceback.format_exc()).to_dict()}
+ def get_corporate_events(self, ticker: str, limit: int = 20) -> Dict[str, Any]:
+ """
+ Get corporate events from 8-K filings
+
+ Args:
+ ticker: Stock ticker symbol
+ limit: Maximum number of 8-K filings to return
+
+ Returns:
+ List of corporate events with item descriptions
+ """
+ try:
+ company = Company(ticker)
+ filings = company.get_filings(form="8-K")
+
+ events = []
+ for i, filing in enumerate(filings):
+ if i >= limit:
+ break
+
+ try:
+ # Get the 8-K filing object to extract item information
+ form8k = filing.obj()
+
+ event_data = {
+ "filing_date": str(filing.filing_date) if hasattr(filing, 'filing_date') else None,
+ "period_of_report": str(filing.period_of_report) if hasattr(filing, 'period_of_report') else None,
+ "form": "8-K",
+ "filing_url": filing.filing_url if hasattr(filing, 'filing_url') else None,
+ "accession_number": filing.accession_number,
+ }
+
+ # Try to extract item information
+ if form8k and hasattr(form8k, 'items'):
+ event_data["items"] = form8k.items
+ elif form8k and hasattr(form8k, 'item'):
+ event_data["items"] = [form8k.item]
+
+ # Try to get text excerpt for event description
+ if form8k and hasattr(form8k, 'text'):
+ try:
+ text = form8k.text()
+ # Get first 500 chars as event description
+ event_data["description"] = text[:500] if text else None
+ except:
+ pass
+
+ events.append(event_data)
+
+ except Exception as e:
+ # If obj() fails, add basic filing info
+ events.append({
+ "filing_date": str(filing.filing_date) if hasattr(filing, 'filing_date') else None,
+ "period_of_report": str(filing.period_of_report) if hasattr(filing, 'period_of_report') else None,
+ "form": "8-K",
+ "filing_url": filing.filing_url if hasattr(filing, 'filing_url') else None,
+ "accession_number": filing.accession_number,
+ "error": str(e)
+ })
+
+ return {
+ "success": True,
+ "data": events,
+ "count": len(events),
+ "parameters": {"ticker": ticker, "limit": limit}
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_corporate_events", str(e), traceback.format_exc()).to_dict()}
+
def get_latest_filing(self, ticker: str, form: str, n: int = 1) -> Dict[str, Any]:
"""
Get latest filing(s) of specific form type
@@ -346,10 +415,10 @@ class EdgarToolsWrapper:
f"No financial data available for {ticker}").to_dict()
}
- # Get all three statements
- balance_sheet = financials.balance_sheet(periods=periods, annual=annual, as_dataframe=True)
- income_stmt = financials.income_statement(periods=periods, annual=annual, as_dataframe=True)
- cash_flow = financials.cash_flow(periods=periods, annual=annual, as_dataframe=True)
+ # Get all three statements (edgartools properties)
+ balance_sheet = financials.balance_sheet
+ income_stmt = financials.income_statement
+ cash_flow = financials.cashflow_statement # Note: cashflow_statement, not cash_flow
return {
"success": True,
@@ -370,7 +439,11 @@ class EdgarToolsWrapper:
"""Get balance sheet data"""
try:
company = Company(ticker)
- bs = company.balance_sheet(periods=periods, annual=annual, as_dataframe=as_json)
+ financials = company.get_financials() if annual else company.get_quarterly_financials()
+ if not financials:
+ return {"error": EdgarError("get_balance_sheet", f"No financials for {ticker}").to_dict()}
+
+ bs = financials.balance_sheet
return {
"success": True,
@@ -385,7 +458,11 @@ class EdgarToolsWrapper:
"""Get income statement data"""
try:
company = Company(ticker)
- inc = company.income_statement(periods=periods, annual=annual, as_dataframe=as_json)
+ financials = company.get_financials() if annual else company.get_quarterly_financials()
+ if not financials:
+ return {"error": EdgarError("get_income_statement", f"No financials for {ticker}").to_dict()}
+
+ inc = financials.income_statement
return {
"success": True,
@@ -400,7 +477,11 @@ class EdgarToolsWrapper:
"""Get cash flow statement data"""
try:
company = Company(ticker)
- cf = company.cash_flow(periods=periods, annual=annual, as_dataframe=as_json)
+ financials = company.get_financials() if annual else company.get_quarterly_financials()
+ if not financials:
+ return {"error": EdgarError("get_cash_flow", f"No financials for {ticker}").to_dict()}
+
+ cf = financials.cashflow_statement
return {
"success": True,
@@ -516,20 +597,39 @@ class EdgarToolsWrapper:
if thirteenf and hasattr(thirteenf, 'holdings'):
holdings_df = thirteenf.holdings
+
+ # Convert Decimal to float for JSON serialization
+ def convert_decimals(obj):
+ """Convert Decimal objects to float for JSON serialization"""
+ from decimal import Decimal
+ if isinstance(obj, Decimal):
+ return float(obj)
+ return obj
+
+ # Get holdings sample and convert to dict with Decimal handling
+ holdings_sample = None
+ if holdings_df is not None and hasattr(holdings_df, 'head'):
+ sample_df = holdings_df.head(10)
+ holdings_sample = sample_df.to_dict('records') if hasattr(sample_df, 'to_dict') else None
+ # Convert any Decimal values in the dict
+ if holdings_sample:
+ for record in holdings_sample:
+ for key, value in record.items():
+ record[key] = convert_decimals(value)
+
holdings_data.append({
"filing_date": str(filing.filing_date) if hasattr(filing, 'filing_date') else None,
"period_of_report": str(filing.period_of_report) if hasattr(filing, 'period_of_report') else None,
- "manager_name": thirteenf.manager_name if hasattr(thirteenf, 'manager_name') else None,
- "total_value": thirteenf.total_value if hasattr(thirteenf, 'total_value') else None,
- "total_holdings": thirteenf.total_holdings if hasattr(thirteenf, 'total_holdings') else None,
- "holdings_sample": holdings_df.head(10).to_dict() if holdings_df is not None else None,
+ "total_value": convert_decimals(thirteenf.total_value) if hasattr(thirteenf, 'total_value') else None,
+ "total_holdings": int(thirteenf.total_holdings) if hasattr(thirteenf, 'total_holdings') else None,
+ "holdings_sample": holdings_sample,
"accession_number": filing.accession_number,
})
- except:
+ except Exception as e:
holdings_data.append({
"filing_date": str(filing.filing_date) if hasattr(filing, 'filing_date') else None,
"accession_number": filing.accession_number,
- "note": "Unable to parse 13F data"
+ "note": f"Unable to parse 13F data: {str(e)}"
})
return {
@@ -587,26 +687,46 @@ class EdgarToolsWrapper:
"has_xbrl": proxy.has_xbrl if hasattr(proxy, 'has_xbrl') else False,
}
- # Executive compensation data
- if hasattr(proxy, 'executive_compensation') and proxy.executive_compensation:
+ # Executive compensation data (check if not None and not empty DataFrame)
+ if hasattr(proxy, 'executive_compensation'):
exec_comp = proxy.executive_compensation
- data["executive_compensation"] = {
- "peo_total_comp": exec_comp.peo_total_comp if hasattr(exec_comp, 'peo_total_comp') else None,
- "peo_actually_paid_comp": exec_comp.peo_actually_paid_comp if hasattr(exec_comp, 'peo_actually_paid_comp') else None,
- "neo_avg_total_comp": exec_comp.neo_avg_total_comp if hasattr(exec_comp, 'neo_avg_total_comp') else None,
- "neo_avg_actually_paid_comp": exec_comp.neo_avg_actually_paid_comp if hasattr(exec_comp, 'neo_avg_actually_paid_comp') else None,
- }
-
- # Named executives
- if hasattr(proxy, 'named_executives') and proxy.named_executives:
- data["named_executives"] = [
- {
- "name": ne.name if hasattr(ne, 'name') else None,
- "role": ne.role if hasattr(ne, 'role') else None,
- "total_comp": ne.total_comp if hasattr(ne, 'total_comp') else None,
- }
- for ne in proxy.named_executives[:10]
- ]
+ # Check if it's a DataFrame and not empty, or if it's another truthy object
+ if exec_comp is not None:
+ try:
+ # If it's a DataFrame, check if not empty
+ if hasattr(exec_comp, 'empty') and not exec_comp.empty:
+ data["executive_compensation"] = exec_comp.to_dict() if hasattr(exec_comp, 'to_dict') else str(exec_comp)
+ elif not hasattr(exec_comp, 'empty'):
+ # Not a DataFrame, handle as object
+ data["executive_compensation"] = {
+ "peo_total_comp": exec_comp.peo_total_comp if hasattr(exec_comp, 'peo_total_comp') else None,
+ "peo_actually_paid_comp": exec_comp.peo_actually_paid_comp if hasattr(exec_comp, 'peo_actually_paid_comp') else None,
+ "neo_avg_total_comp": exec_comp.neo_avg_total_comp if hasattr(exec_comp, 'neo_avg_total_comp') else None,
+ "neo_avg_actually_paid_comp": exec_comp.neo_avg_actually_paid_comp if hasattr(exec_comp, 'neo_avg_actually_paid_comp') else None,
+ }
+ except:
+ data["executive_compensation"] = "Unable to parse executive compensation"
+
+ # Named executives (check if not None and not empty)
+ if hasattr(proxy, 'named_executives'):
+ named_execs = proxy.named_executives
+ if named_execs is not None:
+ try:
+ # If it's a DataFrame, convert to list
+ if hasattr(named_execs, 'to_dict'):
+ data["named_executives"] = named_execs.to_dict('records')[:10] if hasattr(named_execs, 'empty') and not named_execs.empty else []
+ elif hasattr(named_execs, '__iter__'):
+ # It's an iterable (list, etc.)
+ data["named_executives"] = [
+ {
+ "name": ne.name if hasattr(ne, 'name') else str(ne.get('name')) if isinstance(ne, dict) else None,
+ "role": ne.role if hasattr(ne, 'role') else str(ne.get('role')) if isinstance(ne, dict) else None,
+ "total_comp": ne.total_comp if hasattr(ne, 'total_comp') else ne.get('total_comp') if isinstance(ne, dict) else None,
+ }
+ for ne in list(named_execs)[:10]
+ ]
+ except:
+ data["named_executives"] = "Unable to parse named executives"
return {
"success": True,
@@ -932,9 +1052,13 @@ class EdgarToolsWrapper:
return {"error": EdgarError("get_xbrl_data", str(e), traceback.format_exc()).to_dict()}
-def main():
- """Main CLI interface"""
- if len(sys.argv) < 2:
+def main(args=None):
+ """Main CLI interface - supports both PyO3 and subprocess execution"""
+ # Support both PyO3 (args parameter) and subprocess (sys.argv)
+ if args is None:
+ args = sys.argv[1:]
+
+ if len(args) < 1:
print(json.dumps({
"error": "Usage: python edgar_tools.py <command> [args...]",
"commands": {
@@ -948,6 +1072,7 @@ def main():
"company": [
"get_company <ticker>",
"get_company_filings <ticker> [form] [year] [quarter] [limit]",
+ "get_corporate_events <ticker> [limit]",
"get_latest_filing <ticker> <form> [n]",
"find_company <query> [top_n]",
"find <identifier>",
@@ -983,7 +1108,7 @@ def main():
}, indent=2))
sys.exit(1)
- command = sys.argv[1]
+ command = args[0]
# Initialize wrapper with default identity
try:
@@ -995,20 +1120,20 @@ def main():
try:
# Configuration commands
if command == "set_identity":
- identity = sys.argv[2] if len(sys.argv) > 2 else None
+ identity = args[1] if len(args) > 1 else None
result = wrapper.set_user_identity(identity)
elif command == "get_identity":
result = wrapper.get_user_identity()
elif command == "configure_connection":
- verify_ssl = sys.argv[2].lower() == "true" if len(sys.argv) > 2 else None
- proxy = sys.argv[3] if len(sys.argv) > 3 else None
- timeout = float(sys.argv[4]) if len(sys.argv) > 4 else None
+ verify_ssl = args[1].lower() == "true" if len(args) > 1 else None
+ proxy = args[2] if len(args) > 2 else None
+ timeout = float(args[3]) if len(args) > 3 else None
result = wrapper.configure_connection(verify_ssl, proxy, timeout)
elif command == "clear_cache":
- dry_run = sys.argv[2].lower() == "true" if len(sys.argv) > 2 else True
+ dry_run = args[1].lower() == "true" if len(args) > 1 else True
result = wrapper.clear_local_cache(dry_run)
elif command == "get_storage_info":
@@ -1016,120 +1141,145 @@ def main():
# Company commands
elif command == "get_company":
- ticker = sys.argv[2] if len(sys.argv) > 2 else None
- result = wrapper.get_company(ticker)
+ if len(args) < 2:
+ result = {"error": "Usage: edgar_tools.py get_company <ticker>"}
+ else:
+ ticker = args[1]
+ result = wrapper.get_company(ticker)
elif command == "get_company_filings":
- ticker = sys.argv[2] if len(sys.argv) > 2 else None
- form = sys.argv[3] if len(sys.argv) > 3 else None
- year = int(sys.argv[4]) if len(sys.argv) > 4 else None
- quarter = int(sys.argv[5]) if len(sys.argv) > 5 else None
- limit = int(sys.argv[6]) if len(sys.argv) > 6 else 20
- result = wrapper.get_company_filings(ticker, form, year, quarter, limit)
+ if len(args) < 2:
+ result = {"error": "Usage: edgar_tools.py get_company_filings <ticker> [form] [year] [quarter] [limit]"}
+ else:
+ ticker = args[1]
+ form = args[2] if len(args) > 2 else None
+ year = int(args[3]) if len(args) > 3 else None
+ quarter = int(args[4]) if len(args) > 4 else None
+ limit = int(args[5]) if len(args) > 5 else 20
+ result = wrapper.get_company_filings(ticker, form, year, quarter, limit)
+
+ elif command == "get_corporate_events":
+ if len(args) < 2:
+ result = {"error": "Usage: edgar_tools.py get_corporate_events <ticker> [limit]"}
+ else:
+ ticker = args[1]
+ limit = int(args[2]) if len(args) > 2 else 20
+ result = wrapper.get_corporate_events(ticker, limit)
elif command == "get_latest_filing":
- ticker = sys.argv[2] if len(sys.argv) > 2 else None
- form = sys.argv[3] if len(sys.argv) > 3 else "10-K"
- n = int(sys.argv[4]) if len(sys.argv) > 4 else 1
- result = wrapper.get_latest_filing(ticker, form, n)
+ if len(args) < 2:
+ result = {"error": "Usage: edgar_tools.py get_latest_filing <ticker> [form] [n]"}
+ else:
+ ticker = args[1]
+ form = args[2] if len(args) > 2 else "10-K"
+ n = int(args[3]) if len(args) > 3 else 1
+ result = wrapper.get_latest_filing(ticker, form, n)
# Financial commands
elif command == "get_financials":
- ticker = sys.argv[2] if len(sys.argv) > 2 else None
- periods = int(sys.argv[3]) if len(sys.argv) > 3 else 4
- annual = sys.argv[4].lower() != "false" if len(sys.argv) > 4 else True
+ ticker = args[1] if len(args) > 1 else None
+ periods = int(args[2]) if len(args) > 2 else 4
+ annual = args[3].lower() != "false" if len(args) > 3 else True
result = wrapper.get_financials(ticker, periods, annual)
elif command == "get_balance_sheet":
- ticker = sys.argv[2] if len(sys.argv) > 2 else None
- periods = int(sys.argv[3]) if len(sys.argv) > 3 else 4
- annual = sys.argv[4].lower() != "false" if len(sys.argv) > 4 else True
+ ticker = args[1] if len(args) > 1 else None
+ periods = int(args[2]) if len(args) > 2 else 4
+ annual = args[3].lower() != "false" if len(args) > 3 else True
result = wrapper.get_balance_sheet(ticker, periods, annual)
elif command == "get_income_statement":
- ticker = sys.argv[2] if len(sys.argv) > 2 else None
- periods = int(sys.argv[3]) if len(sys.argv) > 3 else 4
- annual = sys.argv[4].lower() != "false" if len(sys.argv) > 4 else True
+ ticker = args[1] if len(args) > 1 else None
+ periods = int(args[2]) if len(args) > 2 else 4
+ annual = args[3].lower() != "false" if len(args) > 3 else True
result = wrapper.get_income_statement(ticker, periods, annual)
elif command == "get_cash_flow":
- ticker = sys.argv[2] if len(sys.argv) > 2 else None
- periods = int(sys.argv[3]) if len(sys.argv) > 3 else 4
- annual = sys.argv[4].lower() != "false" if len(sys.argv) > 4 else True
+ ticker = args[1] if len(args) > 1 else None
+ periods = int(args[2]) if len(args) > 2 else 4
+ annual = args[3].lower() != "false" if len(args) > 3 else True
result = wrapper.get_cash_flow(ticker, periods, annual)
elif command == "get_company_facts":
- cik = sys.argv[2] if len(sys.argv) > 2 else None
+ cik = args[1] if len(args) > 1 else None
result = wrapper.get_company_facts(cik)
elif command == "get_xbrl_data":
- ticker = sys.argv[2] if len(sys.argv) > 2 else None
- form = sys.argv[3] if len(sys.argv) > 3 else "10-K"
+ ticker = args[1] if len(args) > 1 else None
+ form = args[2] if len(args) > 2 else "10-K"
result = wrapper.get_xbrl_data(ticker, form)
# Insider transactions
elif command == "get_insider_transactions":
- ticker = sys.argv[2] if len(sys.argv) > 2 else None
- limit = int(sys.argv[3]) if len(sys.argv) > 3 else 20
+ ticker = args[1] if len(args) > 1 else None
+ limit = int(args[2]) if len(args) > 2 else 20
result = wrapper.get_insider_transactions(ticker, limit)
# Fund holdings
elif command == "get_fund_holdings":
- ticker = sys.argv[2] if len(sys.argv) > 2 else None
- limit = int(sys.argv[3]) if len(sys.argv) > 3 else 5
+ ticker = args[1] if len(args) > 1 else None
+ limit = int(args[2]) if len(args) > 2 else 5
result = wrapper.get_fund_holdings(ticker, limit)
# Proxy statement
elif command == "get_proxy_statement":
- ticker = sys.argv[2] if len(sys.argv) > 2 else None
- result = wrapper.get_proxy_statement(ticker)
+ if len(args) < 2:
+ result = {"error": "Usage: edgar_tools.py get_proxy_statement <ticker>"}
+ else:
+ ticker = args[1]
+ result = wrapper.get_proxy_statement(ticker)
# Current filings
elif command == "get_current_filings" or command == "get_latest_filings":
- form = sys.argv[2] if len(sys.argv) > 2 else ""
- page_size = int(sys.argv[3]) if len(sys.argv) > 3 else 40
+ form = args[1] if len(args) > 1 else ""
+ page_size = int(args[2]) if len(args) > 2 else 40
result = wrapper.get_current_filings(form, page_size)
# Search commands
elif command == "find_company":
- query = sys.argv[2] if len(sys.argv) > 2 else None
- top_n = int(sys.argv[3]) if len(sys.argv) > 3 else 10
+ query = args[1] if len(args) > 1 else None
+ top_n = int(args[2]) if len(args) > 2 else 10
result = wrapper.find_company_by_name(query, top_n)
elif command == "find":
- identifier = sys.argv[2] if len(sys.argv) > 2 else None
+ identifier = args[1] if len(args) > 1 else None
result = wrapper.find_by_identifier(identifier)
elif command == "get_company_tickers":
- limit = int(sys.argv[2]) if len(sys.argv) > 2 else 100
+ limit = int(args[1]) if len(args) > 1 else 100
result = wrapper.get_company_tickers_list(limit)
# Filing operations
elif command == "get_filing_by_accession":
- accession = sys.argv[2] if len(sys.argv) > 2 else None
+ accession = args[1] if len(args) > 1 else None
result = wrapper.get_filing_by_accession(accession)
elif command == "get_filing_text":
- accession = sys.argv[2] if len(sys.argv) > 2 else None
- max_length = int(sys.argv[3]) if len(sys.argv) > 3 else 10000
+ accession = args[1] if len(args) > 1 else None
+ max_length = int(args[2]) if len(args) > 2 else 10000
result = wrapper.get_filing_text(accession, max_length)
elif command == "get_filings_by_date":
- year = int(sys.argv[2]) if len(sys.argv) > 2 else None
- quarter = int(sys.argv[3]) if len(sys.argv) > 3 else None
- form = sys.argv[4] if len(sys.argv) > 4 else None
- limit = int(sys.argv[5]) if len(sys.argv) > 5 else 50
+ year = int(args[1]) if len(args) > 1 else None
+ quarter = int(args[2]) if len(args) > 2 else None
+ form = args[3] if len(args) > 3 else None
+ limit = int(args[4]) if len(args) > 4 else 50
result = wrapper.get_filings_by_date(year, quarter, form, limit)
else:
result = {"error": EdgarError(command, f"Unknown command: {command}").to_dict()}
- print(json.dumps(result, indent=2))
+ # Return JSON for PyO3, print for subprocess
+ output = json.dumps(result, indent=2)
+ print(output)
+ return output
except Exception as e:
- print(json.dumps({
+ error_output = json.dumps({
"error": EdgarError(command, str(e), traceback.format_exc()).to_dict()
- }, indent=2))
+ }, indent=2)
+ print(error_output)
+ return error_output
if __name__ == "__main__":
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/edgar.rs b/fincept-terminal-desktop/src-tauri/src/commands/edgar.rs
new file mode 100644
index 000000000..d537b12b0
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/edgar.rs
@@ -0,0 +1,19 @@
+// Edgar (SEC filings) data commands using edgartools library
+use crate::utils::python::get_script_path;
+use crate::python_runtime;
+
+/// Execute Edgar Python script command with PyO3
+#[tauri::command]
+pub async fn execute_edgar_command(
+ app: tauri::AppHandle,
+ command: String,
+ args: Vec<String>,
+) -> Result<String, String> {
+ // Build command arguments
+ let mut cmd_args = vec![command];
+ cmd_args.extend(args);
+
+ // Execute Python script with PyO3
+ let script_path = get_script_path(&app, "edgar_tools.py")?;
+ python_runtime::execute_python_script(&script_path, cmd_args)
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
index e1a4a3abf..7aede9825 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
@@ -10,6 +10,7 @@ pub mod imf;
pub mod fmp;
pub mod federal_reserve;
pub mod sec;
+pub mod edgar;
pub mod cftc;
pub mod cboe;
pub mod bls;
diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rs
index 45cfbbdf9..8a30cb5f2 100644
--- a/fincept-terminal-desktop/src-tauri/src/lib.rs
+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs
@@ -364,6 +364,7 @@ pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
+ .plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_http::init())
.plugin(tauri_plugin_cors_fetch::init())
.plugin(tauri_plugin_dialog::init())
@@ -395,6 +396,7 @@ pub fn run() {
commands::market_data::get_financials,
commands::polygon::execute_polygon_command,
commands::yfinance::execute_yfinance_command,
+ commands::edgar::execute_edgar_command,
commands::alphavantage::execute_alphavantage_command,
commands::alphavantage::get_alphavantage_quote,
commands::alphavantage::get_alphavantage_daily,
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index 5b7f48a3e..1d658e4d4 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -31,6 +31,7 @@ import FyersTab from '@/components/tabs/fyers';
import SupportTicketTab from '@/components/tabs/SupportTicketTab';
import RecordedContextsManager from '@/components/common/RecordedContextsManager';
import AgentConfigTab from '@/components/tabs/AgentConfigTab';
+import RelationshipMapTab from '@/components/tabs/RelationshipMapTab';
import { useTranslation } from 'react-i18next';
// Lazy loaded tabs (heavy/Python-dependent)
@@ -541,6 +542,7 @@ function FinxeptTerminalContent() {
const marketsMenuItems = [
{ label: 'Live Markets', shortcut: 'F2', action: () => setActiveTab('markets') },
+ { label: 'Relationship Map', action: () => setActiveTab('relationship-map') },
{ label: 'Stock Screener', shortcut: 'F8', action: () => setActiveTab('screener') },
{ label: 'Polygon Data', action: () => setActiveTab('polygon'), separator: true },
{ label: 'Economics', action: () => setActiveTab('economics') },
@@ -997,6 +999,9 @@ function FinxeptTerminalContent() {
<TabsContent value="markets" className="h-full m-0 p-0">
<MarketsTab />
</TabsContent>
+ <TabsContent value="relationship-map" className="h-full m-0 p-0">
+ <RelationshipMapTab />
+ </TabsContent>
<TabsContent value="news" className="h-full m-0 p-0">
<NewsTab />
</TabsContent>
diff --git a/fincept-terminal-desktop/src/components/tabs/RelationshipMapTab.tsx b/fincept-terminal-desktop/src/components/tabs/RelationshipMapTab.tsx
new file mode 100644
index 000000000..3b2907bda
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/RelationshipMapTab.tsx
@@ -0,0 +1,665 @@
+import React, { useState, useCallback, useMemo, useEffect } from 'react';
+import ReactFlow, {
+ Node,
+ Edge,
+ Background,
+ Controls,
+ MiniMap,
+ useNodesState,
+ useEdgesState,
+ Handle,
+ Position,
+ MarkerType,
+} from 'reactflow';
+import 'reactflow/dist/style.css';
+import { Search, Building2, Users, TrendingUp, Calendar, BarChart3, Globe, DollarSign, FileText, Award, Activity, Briefcase, PieChart, ExternalLink } from 'lucide-react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
+import { TabFooter } from '@/components/common/TabFooter';
+import { relationshipMapService } from '@/services/relationshipMapService';
+import { open } from '@tauri-apps/plugin-shell';
+
+// ============================================================================
+// CUSTOM NODE COMPONENTS
+// ============================================================================
+
+const CompanyNode = ({ data }: any) => {
+ const { colors } = useTerminalTheme();
+
+ const formatMarketCap = (val: number) => {
+ if (!val) return 'N/A';
+ if (val >= 1e12) return `$${(val/1e12).toFixed(2)}T`;
+ if (val >= 1e9) return `$${(val/1e9).toFixed(2)}B`;
+ if (val >= 1e6) return `$${(val/1e6).toFixed(2)}M`;
+ return `$${val}`;
+ };
+
+ return (
+ <div
+ style={{
+ background: 'linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%)',
+ border: `3px solid ${colors.accent}`,
+ borderRadius: '12px',
+ padding: '24px',
+ minWidth: '320px',
+ maxWidth: '400px',
+ boxShadow: `0 0 40px ${colors.accent}80, 0 10px 30px rgba(0,0,0,0.7)`,
+ }}
+ >
+ <Handle type="target" position={Position.Top} style={{ opacity: 0 }} />
+ <div className="flex flex-col items-center text-center">
+ <Building2 className="w-12 h-12 mb-3" style={{ color: colors.accent }} />
+ <h2 className="text-2xl font-bold mb-1" style={{ color: colors.text }}>{data.name}</h2>
+ <div className="text-xl mb-2 font-mono" style={{ color: colors.accent }}>{data.ticker}</div>
+ <div className="text-sm mb-1" style={{ color: colors.textMuted }}>
+ {data.sector} • {data.industry}
+ </div>
+ <div className="text-sm font-semibold mt-2" style={{ color: colors.success }}>
+ Market Cap: {formatMarketCap(data.market_cap)}
+ </div>
+ <div className="text-xs mt-2 opacity-60">
+ CIK: {data.cik} | {data.exchange}
+ </div>
+ {data.employees && (
+ <div className="text-xs mt-1" style={{ color: colors.textMuted }}>
+ {data.employees.toLocaleString()} employees
+ </div>
+ )}
+ </div>
+ <Handle type="source" position={Position.Bottom} style={{ opacity: 0 }} />
+ <Handle type="source" position={Position.Left} style={{ opacity: 0 }} />
+ <Handle type="source" position={Position.Right} style={{ opacity: 0 }} />
+ </div>
+ );
+};
+
+const DataNode = ({ data }: any) => {
+ const { colors } = useTerminalTheme();
+ const [expanded, setExpanded] = useState(false);
+
+ const getIcon = () => {
+ switch (data.type) {
+ case 'events': return <Activity className="w-5 h-5" />;
+ case 'filings': return <Calendar className="w-5 h-5" />;
+ case 'financials': return <DollarSign className="w-5 h-5" />;
+ case 'balance': return <BarChart3 className="w-5 h-5" />;
+ case 'analysts': return <Award className="w-5 h-5" />;
+ case 'ownership': return <PieChart className="w-5 h-5" />;
+ case 'valuation': return <TrendingUp className="w-5 h-5" />;
+ case 'info': return <Briefcase className="w-5 h-5" />;
+ case 'executives': return <Users className="w-5 h-5" />;
+ default: return <FileText className="w-5 h-5" />;
+ }
+ };
+
+ const getColor = () => {
+ switch (data.type) {
+ case 'events': return '#ef4444';
+ case 'filings': return '#3b82f6';
+ case 'financials': return '#10b981';
+ case 'balance': return colors.accent;
+ case 'analysts': return '#8b5cf6';
+ case 'ownership': return '#f59e0b';
+ case 'valuation': return '#ec4899';
+ case 'info': return '#14b8a6';
+ case 'executives': return '#10b981';
+ default: return colors.textMuted;
+ }
+ };
+
+ const displayItems = expanded ? data.items : data.items?.slice(0, 4);
+ const hasClickableItems = data.type === 'events' || data.type === 'filings';
+
+ const handleItemClick = async (e: React.MouseEvent, item: any) => {
+ e.stopPropagation();
+ if (hasClickableItems && item.url) {
+ await open(item.url);
+ }
+ };
+
+ return (
+ <div
+ style={{
+ background: '#1a1a1a',
+ border: `2px solid ${getColor()}`,
+ borderRadius: '8px',
+ padding: '14px 18px',
+ minWidth: '260px',
+ maxWidth: '320px',
+ boxShadow: `0 0 20px ${getColor()}50, 0 4px 12px rgba(0,0,0,0.5)`,
+ cursor: 'pointer',
+ transition: 'all 0.2s',
+ }}
+ onClick={() => data.items?.length > 4 && setExpanded(!expanded)}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.transform = 'scale(1.02)';
+ e.currentTarget.style.boxShadow = `0 0 30px ${getColor()}70, 0 6px 16px rgba(0,0,0,0.6)`;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.transform = 'scale(1)';
+ e.currentTarget.style.boxShadow = `0 0 20px ${getColor()}50, 0 4px 12px rgba(0,0,0,0.5)`;
+ }}
+ >
+ <Handle type="target" position={Position.Top} style={{ background: getColor() }} />
+
+ <div className="flex items-center gap-2 mb-3">
+ <div style={{ color: getColor() }}>{getIcon()}</div>
+ <h4 className="font-semibold text-sm" style={{ color: colors.text }}>{data.title}</h4>
+ {data.items?.length > 4 && (
+ <span className="text-xs ml-auto px-1.5 py-0.5 rounded" style={{
+ backgroundColor: `${getColor()}20`,
+ color: getColor()
+ }}>
+ {data.items.length}
+ </span>
+ )}
+ </div>
+
+ <div className="space-y-1.5 text-xs">
+ {displayItems && displayItems.map((item: any, idx: number) => (
+ <div
+ key={idx}
+ className="flex justify-between gap-3 hover:bg-white/5 rounded px-1 py-0.5 transition-colors"
+ onClick={(e) => handleItemClick(e, item)}
+ style={{ cursor: hasClickableItems && item.url ? 'pointer' : 'default' }}
+ >
+ <span className="truncate" style={{ color: colors.textMuted }}>{item.label}</span>
+ <span className="font-medium text-right flex items-center gap-1" style={{ color: colors.text }}>
+ {item.value}
+ {hasClickableItems && item.url && <ExternalLink className="w-3 h-3 opacity-50" />}
+ </span>
+ </div>
+ ))}
+ {!expanded && data.items?.length > 4 && (
+ <div className="text-center pt-1 text-xs font-semibold" style={{ color: getColor() }}>
+ Click to see +{data.items.length - 4} more
+ </div>
+ )}
+ </div>
+
+ <Handle type="source" position={Position.Bottom} style={{ background: getColor(), opacity: 0 }} />
+ </div>
+ );
+};
+
+// ============================================================================
+// MAIN COMPONENT
+// ============================================================================
+
+// Define nodeTypes outside component to avoid re-creation on every render
+const nodeTypes = {
+ company: CompanyNode,
+ data: DataNode,
+};
+
+const RelationshipMapTab: React.FC = () => {
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
+ const [searchQuery, setSearchQuery] = useState('');
+ const [selectedSymbol, setSelectedSymbol] = useState('AAPL');
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const [nodes, setNodes, onNodesChange] = useNodesState([]);
+ const [edges, setEdges, onEdgesChange] = useEdgesState([]);
+
+ useEffect(() => {
+ fetchRelationshipData(selectedSymbol);
+ }, []);
+
+ const fetchRelationshipData = async (ticker: string) => {
+ setIsLoading(true);
+ setError(null);
+ try {
+ const data = await relationshipMapService.getRelationshipMap(ticker);
+ updateGraph(data);
+ } catch (err) {
+ console.error('[UI] Error:', err);
+ setError(`Failed to load data for ${ticker}`);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const updateGraph = (data: any) => {
+ const formatMoney = (val: number) => {
+ if (!val || val === 0) return '$0';
+ if (val >= 1e9) return `$${(val/1e9).toFixed(2)}B`;
+ if (val >= 1e6) return `$${(val/1e6).toFixed(2)}M`;
+ if (val >= 1e3) return `$${(val/1e3).toFixed(2)}K`;
+ return `$${val.toFixed(2)}`;
+ };
+
+ const formatPercent = (val: number) => {
+ if (!val && val !== 0) return 'N/A';
+ return `${(val * 100).toFixed(2)}%`;
+ };
+
+ const formatNumber = (val: number) => {
+ if (!val && val !== 0) return 'N/A';
+ if (val >= 1e9) return `${(val/1e9).toFixed(2)}B`;
+ if (val >= 1e6) return `${(val/1e6).toFixed(2)}M`;
+ return val.toFixed(2);
+ };
+
+ const newNodes: Node[] = [
+ // Center: Company
+ {
+ id: 'company',
+ type: 'company',
+ position: { x: 600, y: 350 },
+ data: {
+ name: data.company.name,
+ ticker: data.company.ticker,
+ industry: data.company.industry,
+ sector: data.company.sector,
+ cik: data.company.cik,
+ exchange: data.company.exchange,
+ employees: data.company.employees,
+ market_cap: data.company.market_cap,
+ },
+ },
+ ];
+
+ const newEdges: Edge[] = [];
+
+ // 1. Corporate Events (Top-Left) - 8-K Filings with Major Announcements
+ const corporateEventItems = data.corporate_events && data.corporate_events.length > 0
+ ? data.corporate_events.map((e: any) => {
+ const date = new Date(e.filing_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: '2-digit' });
+ // Get the first item code or use "Event"
+ const itemCode = e.items && e.items.length > 0 ? e.items[0] : 'Event';
+ return {
+ label: date,
+ value: itemCode,
+ description: e.description || 'Material corporate event filed with SEC',
+ url: e.filing_url,
+ allItems: e.items || []
+ };
+ })
+ : [{ label: 'No events available', value: 'Loading...' }];
+
+ newNodes.push({
+ id: 'events',
+ type: 'data',
+ position: { x: 50, y: 50 },
+ data: {
+ type: 'events',
+ title: 'Corporate Events',
+ items: corporateEventItems,
+ },
+ });
+ newEdges.push({
+ id: 'e-events',
+ source: 'company',
+ target: 'events',
+ type: 'smoothstep',
+ animated: true,
+ style: { stroke: '#ef4444', strokeWidth: 2 },
+ markerEnd: { type: MarkerType.ArrowClosed, color: '#ef4444' },
+ });
+
+ // 2. Recent SEC Filings (Top-Left-Center)
+ if (data.filings?.length > 0) {
+ newNodes.push({
+ id: 'filings',
+ type: 'data',
+ position: { x: 200, y: 80 },
+ data: {
+ type: 'filings',
+ title: 'Recent SEC Filings',
+ items: data.filings.map((f: any) => ({
+ label: `${f.form} (${f.description})`,
+ value: new Date(f.filing_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: '2-digit' }),
+ })),
+ },
+ });
+ newEdges.push({
+ id: 'e-filings',
+ source: 'company',
+ target: 'filings',
+ type: 'smoothstep',
+ animated: true,
+ style: { stroke: '#3b82f6', strokeWidth: 2 },
+ markerEnd: { type: MarkerType.ArrowClosed, color: '#3b82f6' },
+ });
+ }
+
+ // 3. Financials (Top-Center)
+ if (data.financials) {
+ newNodes.push({
+ id: 'financials',
+ type: 'data',
+ position: { x: 500, y: 50 },
+ data: {
+ type: 'financials',
+ title: 'Financial Metrics',
+ items: [
+ { label: 'Revenue', value: formatMoney(data.financials.revenue) },
+ { label: 'Gross Profit', value: formatMoney(data.financials.gross_profit) },
+ { label: 'Operating CF', value: formatMoney(data.financials.operating_cashflow) },
+ { label: 'Free CF', value: formatMoney(data.financials.free_cashflow) },
+ { label: 'EBITDA Margin', value: formatPercent(data.financials.ebitda_margins) },
+ { label: 'Profit Margin', value: formatPercent(data.financials.profit_margins) },
+ { label: 'Revenue Growth', value: formatPercent(data.financials.revenue_growth) },
+ { label: 'Earnings Growth', value: formatPercent(data.financials.earnings_growth) },
+ ],
+ },
+ });
+ newEdges.push({
+ id: 'e-financials',
+ source: 'company',
+ target: 'financials',
+ type: 'smoothstep',
+ animated: true,
+ style: { stroke: '#10b981', strokeWidth: 2 },
+ markerEnd: { type: MarkerType.ArrowClosed, color: '#10b981' },
+ });
+ }
+
+ // 4. Balance Sheet (Top-Right)
+ if (data.balance_sheet) {
+ newNodes.push({
+ id: 'balance',
+ type: 'data',
+ position: { x: 850, y: 80 },
+ data: {
+ type: 'balance',
+ title: 'Balance Sheet',
+ items: [
+ { label: 'Total Assets', value: formatMoney(data.balance_sheet.total_assets) },
+ { label: 'Total Liabilities', value: formatMoney(data.balance_sheet.total_liabilities) },
+ { label: 'Equity', value: formatMoney(data.balance_sheet.stockholders_equity) },
+ { label: 'Cash', value: formatMoney(data.balance_sheet.total_cash) },
+ { label: 'Debt', value: formatMoney(data.balance_sheet.total_debt) },
+ { label: 'Shares Out', value: formatNumber(data.balance_sheet.shares_outstanding) },
+ ],
+ },
+ });
+ newEdges.push({
+ id: 'e-balance',
+ source: 'company',
+ target: 'balance',
+ type: 'smoothstep',
+ animated: true,
+ style: { stroke: colors.accent, strokeWidth: 2 },
+ markerEnd: { type: MarkerType.ArrowClosed, color: colors.accent },
+ });
+ }
+
+ // 5. Analysts (Right)
+ if (data.analysts) {
+ newNodes.push({
+ id: 'analysts',
+ type: 'data',
+ position: { x: 1100, y: 350 },
+ data: {
+ type: 'analysts',
+ title: 'Analyst Coverage',
+ items: [
+ { label: 'Recommendation', value: data.analysts.recommendation.toUpperCase() },
+ { label: 'Rating Score', value: data.analysts.recommendation_mean ? data.analysts.recommendation_mean.toFixed(2) : 'N/A' },
+ { label: 'Target Price', value: formatMoney(data.analysts.target_price) },
+ { label: 'Target High', value: formatMoney(data.analysts.target_high) },
+ { label: 'Target Low', value: formatMoney(data.analysts.target_low) },
+ { label: 'Analysts', value: String(data.analysts.analyst_count) },
+ ],
+ },
+ });
+ newEdges.push({
+ id: 'e-analysts',
+ source: 'company',
+ target: 'analysts',
+ type: 'smoothstep',
+ animated: true,
+ style: { stroke: '#8b5cf6', strokeWidth: 2 },
+ markerEnd: { type: MarkerType.ArrowClosed, color: '#8b5cf6' },
+ });
+ }
+
+ // 6. Ownership (Bottom-Right)
+ if (data.ownership) {
+ newNodes.push({
+ id: 'ownership',
+ type: 'data',
+ position: { x: 850, y: 620 },
+ data: {
+ type: 'ownership',
+ title: 'Ownership Structure',
+ items: [
+ { label: 'Insider %', value: `${data.ownership.insider_percent.toFixed(2)}%` },
+ { label: 'Institutional %', value: `${data.ownership.institutional_percent.toFixed(2)}%` },
+ { label: 'Float Shares', value: formatNumber(data.ownership.float_shares) },
+ { label: 'Total Shares', value: formatNumber(data.ownership.shares_outstanding) },
+ ],
+ },
+ });
+ newEdges.push({
+ id: 'e-ownership',
+ source: 'company',
+ target: 'ownership',
+ type: 'smoothstep',
+ animated: true,
+ style: { stroke: '#f59e0b', strokeWidth: 2 },
+ markerEnd: { type: MarkerType.ArrowClosed, color: '#f59e0b' },
+ });
+ }
+
+ // 7. Valuation (Bottom-Center)
+ if (data.valuation) {
+ newNodes.push({
+ id: 'valuation',
+ type: 'data',
+ position: { x: 450, y: 650 },
+ data: {
+ type: 'valuation',
+ title: 'Valuation Metrics',
+ items: [
+ { label: 'P/E Ratio', value: data.valuation.pe_ratio.toFixed(2) },
+ { label: 'Forward P/E', value: data.valuation.forward_pe.toFixed(2) },
+ { label: 'Price/Book', value: data.valuation.price_to_book.toFixed(2) },
+ { label: 'Enterprise Value', value: formatMoney(data.valuation.enterprise_value) },
+ { label: 'EV/Revenue', value: data.valuation.enterprise_to_revenue.toFixed(2) },
+ { label: 'PEG Ratio', value: data.valuation.peg_ratio.toFixed(2) },
+ ],
+ },
+ });
+ newEdges.push({
+ id: 'e-valuation',
+ source: 'company',
+ target: 'valuation',
+ type: 'smoothstep',
+ animated: true,
+ style: { stroke: '#ec4899', strokeWidth: 2 },
+ markerEnd: { type: MarkerType.ArrowClosed, color: '#ec4899' },
+ });
+ }
+
+ // 8. Company Info (Bottom-Left)
+ newNodes.push({
+ id: 'info',
+ type: 'data',
+ position: { x: 100, y: 620 },
+ data: {
+ type: 'info',
+ title: 'Company Information',
+ items: [
+ { label: 'Exchange', value: data.company.exchange },
+ { label: 'Sector', value: data.company.sector },
+ { label: 'Industry', value: data.company.industry },
+ { label: 'Employees', value: data.company.employees ? data.company.employees.toLocaleString() : 'N/A' },
+ { label: 'SIC Code', value: data.company.sic },
+ ],
+ },
+ });
+ newEdges.push({
+ id: 'e-info',
+ source: 'company',
+ target: 'info',
+ type: 'smoothstep',
+ animated: true,
+ style: { stroke: '#14b8a6', strokeWidth: 2 },
+ markerEnd: { type: MarkerType.ArrowClosed, color: '#14b8a6' },
+ });
+
+ // 9. Executives (Left) - if available
+ if (data.executives?.length > 0) {
+ newNodes.push({
+ id: 'executives',
+ type: 'data',
+ position: { x: 50, y: 350 },
+ data: {
+ type: 'executives',
+ title: 'Executives',
+ items: data.executives.map((exec: any) => ({
+ label: exec.name,
+ value: exec.role,
+ })),
+ },
+ });
+ newEdges.push({
+ id: 'e-executives',
+ source: 'company',
+ target: 'executives',
+ type: 'smoothstep',
+ animated: true,
+ style: { stroke: '#10b981', strokeWidth: 2 },
+ markerEnd: { type: MarkerType.ArrowClosed, color: '#10b981' },
+ });
+ }
+
+ console.log('[UI] Generated nodes:', newNodes.length);
+ console.log('[UI] Generated edges:', newEdges.length);
+
+ setNodes(newNodes);
+ setEdges(newEdges);
+ };
+
+ const handleSearch = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!searchQuery.trim()) return;
+
+ const ticker = searchQuery.toUpperCase().trim();
+ setSelectedSymbol(ticker);
+ await fetchRelationshipData(ticker);
+ };
+
+ return (
+ <div
+ className="h-full flex flex-col"
+ style={{
+ fontFamily,
+ fontSize: `${fontSize}px`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ }}
+ >
+ {/* Header */}
+ <div
+ className="border-b px-4 py-3 flex items-center justify-between"
+ style={{ borderColor: colors.border }}
+ >
+ <div className="flex items-center gap-3">
+ <Globe className="w-5 h-5" style={{ color: colors.accent }} />
+ <h2 className="text-lg font-semibold">Relationship Map</h2>
+ <span className="text-xs px-2 py-1 rounded font-mono" style={{
+ backgroundColor: colors.surface,
+ color: colors.accent,
+ border: `1px solid ${colors.border}`
+ }}>
+ {selectedSymbol}
+ </span>
+ </div>
+
+ <form onSubmit={handleSearch} className="relative w-96">
+ <Search
+ className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4"
+ style={{ color: colors.textMuted }}
+ />
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ placeholder="Enter ticker (e.g., AAPL, TSLA, GOOGL)..."
+ className="w-full pl-10 pr-4 py-2 rounded border focus:outline-none focus:ring-1"
+ style={{
+ backgroundColor: colors.surface,
+ borderColor: colors.border,
+ color: colors.text,
+ }}
+ />
+ </form>
+ </div>
+
+ {/* Graph */}
+ <div className="flex-1" style={{ background: '#0a0a0a' }}>
+ {isLoading ? (
+ <div className="flex items-center justify-center h-full">
+ <div className="text-center">
+ <div
+ className="animate-spin rounded-full h-16 w-16 border-b-2 mx-auto mb-4"
+ style={{ borderColor: colors.accent }}
+ />
+ <p className="text-lg font-semibold" style={{ color: colors.text }}>
+ Loading {selectedSymbol}...
+ </p>
+ <p className="text-sm mt-2" style={{ color: colors.textMuted }}>
+ Fetching data from SEC Edgar + Yahoo Finance
+ </p>
+ </div>
+ </div>
+ ) : error ? (
+ <div className="flex items-center justify-center h-full">
+ <div className="text-center p-8 rounded border" style={{
+ backgroundColor: colors.surface,
+ borderColor: colors.error
+ }}>
+ <p className="text-lg font-semibold mb-2" style={{ color: colors.error }}>Error</p>
+ <p style={{ color: colors.textMuted }}>{error}</p>
+ </div>
+ </div>
+ ) : (
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ nodeTypes={nodeTypes}
+ fitView
+ minZoom={0.3}
+ maxZoom={2}
+ defaultViewport={{ x: 0, y: 0, zoom: 0.75 }}
+ style={{ background: '#0a0a0a' }}
+ >
+ <Background
+ gap={20}
+ size={1}
+ style={{ background: '#0a0a0a' }}
+ color="#1a1a1a"
+ />
+ <Controls
+ style={{
+ background: '#1a1a1a',
+ border: `1px solid ${colors.border}`,
+ borderRadius: '4px',
+ }}
+ />
+ <MiniMap
+ style={{
+ background: '#1a1a1a',
+ border: `1px solid ${colors.border}`,
+ }}
+ maskColor="#0a0a0a90"
+ nodeColor={(node) => {
+ if (node.id === 'company') return colors.accent;
+ return colors.textMuted;
+ }}
+ />
+ </ReactFlow>
+ )}
+ </div>
+
+ <TabFooter tabName="Relationship Map" />
+ </div>
+ );
+};
+
+export default RelationshipMapTab;
diff --git a/fincept-terminal-desktop/src/services/relationshipMapService.ts b/fincept-terminal-desktop/src/services/relationshipMapService.ts
new file mode 100644
index 000000000..39af3c5ff
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/relationshipMapService.ts
@@ -0,0 +1,435 @@
+// Relationship Map Service - Production-Level Implementation
+// Combines Edgar (SEC filings) + yfinance (market data) for comprehensive company intelligence
+
+import { invoke } from '@tauri-apps/api/core';
+
+// ============================================================================
+// TYPE DEFINITIONS
+// ============================================================================
+
+export interface CompanyInfo {
+ ticker: string;
+ name: string;
+ cik: string;
+ industry: string;
+ sic: string;
+ sector?: string;
+ address?: string;
+ exchange?: string;
+ employees?: number;
+ website?: string;
+ description?: string;
+ market_cap?: number;
+}
+
+export interface Executive {
+ name: string;
+ role: string;
+ compensation?: number;
+}
+
+export interface InstitutionalHolder {
+ name: string;
+ value: number;
+ shares?: number;
+ percentage?: number;
+}
+
+export interface Filing {
+ form: string;
+ filing_date: string;
+ description?: string;
+ url?: string;
+ period?: string;
+}
+
+export interface CorporateEvent {
+ filing_date: string;
+ period_of_report?: string;
+ form: string;
+ filing_url?: string;
+ accession_number: string;
+ items?: string[];
+ description?: string;
+}
+
+export interface BalanceSheetMetrics {
+ total_assets: number;
+ total_liabilities: number;
+ stockholders_equity: number;
+ shares_outstanding: number;
+ total_cash?: number;
+ total_debt?: number;
+}
+
+export interface FinancialMetrics {
+ revenue: number;
+ gross_profit: number;
+ operating_cashflow: number;
+ free_cashflow: number;
+ ebitda_margins: number;
+ profit_margins: number;
+ revenue_growth: number;
+ earnings_growth: number;
+}
+
+export interface AnalystData {
+ recommendation: string;
+ recommendation_mean?: number;
+ target_price: number;
+ target_high: number;
+ target_low: number;
+ analyst_count: number;
+}
+
+export interface OwnershipData {
+ insider_percent: number;
+ institutional_percent: number;
+ float_shares: number;
+ shares_outstanding: number;
+}
+
+export interface ValuationMetrics {
+ pe_ratio: number;
+ forward_pe: number;
+ price_to_book: number;
+ enterprise_value: number;
+ enterprise_to_revenue: number;
+ peg_ratio: number;
+}
+
+export interface RelationshipMapData {
+ company: CompanyInfo;
+ executives: Executive[];
+ holders: InstitutionalHolder[];
+ filings: Filing[];
+ corporate_events: CorporateEvent[];
+ balance_sheet: BalanceSheetMetrics;
+ financials: FinancialMetrics;
+ analysts: AnalystData;
+ ownership: OwnershipData;
+ valuation: ValuationMetrics;
+ timestamp: string;
+}
+
+// ============================================================================
+// SERVICE CLASS
+// ============================================================================
+
+class RelationshipMapService {
+
+ /**
+ * Get comprehensive relationship map data for a ticker
+ */
+ async getRelationshipMap(ticker: string): Promise<RelationshipMapData> {
+ try {
+ const [edgarCompany, edgarProxy, edgarFilings, edgarEvents, yfinanceInfo] = await Promise.allSettled([
+ this.getEdgarCompany(ticker),
+ this.getEdgarProxy(ticker),
+ this.getEdgarFilings(ticker),
+ this.getEdgarCorporateEvents(ticker),
+ this.getYFinanceInfo(ticker)
+ ]);
+
+ const companyData = edgarCompany.status === 'fulfilled' ? edgarCompany.value : null;
+ const proxyData = edgarProxy.status === 'fulfilled' ? edgarProxy.value : null;
+ const filingsData = edgarFilings.status === 'fulfilled' ? edgarFilings.value : null;
+ const eventsData = edgarEvents.status === 'fulfilled' ? edgarEvents.value : null;
+ const yfinanceData = yfinanceInfo.status === 'fulfilled' ? yfinanceInfo.value : null;
+
+ return this.combineData(ticker, companyData, proxyData, filingsData, eventsData, yfinanceData);
+ } catch (error) {
+ console.error('[RelationshipMapService] Error:', error);
+ throw error;
+ }
+ }
+
+ /**
+ * Fetch Edgar company info
+ */
+ private async getEdgarCompany(ticker: string) {
+ try {
+ const result = await invoke<string>('execute_edgar_command', {
+ command: 'get_company',
+ args: [ticker]
+ });
+ return JSON.parse(result);
+ } catch (error) {
+ console.error('[Edgar] Company error:', error);
+ return null;
+ }
+ }
+
+ /**
+ * Fetch Edgar proxy statement
+ */
+ private async getEdgarProxy(ticker: string) {
+ try {
+ const result = await invoke<string>('execute_edgar_command', {
+ command: 'get_proxy_statement',
+ args: [ticker]
+ });
+ return JSON.parse(result);
+ } catch (error) {
+ console.error('[Edgar] Proxy error:', error);
+ return null;
+ }
+ }
+
+ /**
+ * Fetch Edgar filings
+ */
+ private async getEdgarFilings(ticker: string) {
+ try {
+ const result = await invoke<string>('execute_edgar_command', {
+ command: 'get_company_filings',
+ args: [ticker]
+ });
+ return JSON.parse(result);
+ } catch (error) {
+ console.error('[Edgar] Filings error:', error);
+ return null;
+ }
+ }
+
+ /**
+ * Fetch Edgar corporate events (8-K filings)
+ */
+ private async getEdgarCorporateEvents(ticker: string) {
+ try {
+ const result = await invoke<string>('execute_edgar_command', {
+ command: 'get_corporate_events',
+ args: [ticker]
+ });
+ return JSON.parse(result);
+ } catch (error) {
+ console.error('[Edgar] Corporate Events error:', error);
+ return null;
+ }
+ }
+
+ /**
+ * Fetch yfinance data
+ */
+ private async getYFinanceInfo(ticker: string) {
+ try {
+ const result = await invoke<string>('execute_yfinance_command', {
+ command: 'info',
+ args: [ticker]
+ });
+ return JSON.parse(result);
+ } catch (error) {
+ console.error('[YFinance] Info error:', error);
+ return null;
+ }
+ }
+
+ /**
+ * Combine all data sources
+ */
+ private combineData(
+ ticker: string,
+ edgarCompany: any,
+ edgarProxy: any,
+ edgarFilings: any,
+ edgarEvents: any,
+ yfinanceData: any
+ ): RelationshipMapData {
+
+ // Extract company info
+ const company: CompanyInfo = {
+ ticker: ticker.toUpperCase(),
+ name: edgarCompany?.data?.name || yfinanceData?.company_name || ticker,
+ cik: edgarCompany?.data?.cik?.toString() || '',
+ industry: edgarCompany?.data?.industry || yfinanceData?.industry || 'N/A',
+ sic: edgarCompany?.data?.sic || '',
+ sector: yfinanceData?.sector || 'N/A',
+ address: edgarCompany?.data?.business_address || '',
+ exchange: yfinanceData?.exchange || 'N/A',
+ employees: yfinanceData?.employees,
+ website: yfinanceData?.website,
+ description: yfinanceData?.description,
+ market_cap: yfinanceData?.market_cap,
+ };
+
+ // Extract executives
+ const executives: Executive[] = this.extractExecutives(edgarProxy);
+
+ // Extract holders (placeholder - will implement when yfinance adds institutional_holders)
+ const holders: InstitutionalHolder[] = this.extractHolders(yfinanceData);
+
+ // Extract filings
+ const filings: Filing[] = this.extractFilings(edgarFilings);
+
+ // Extract corporate events
+ const corporate_events: CorporateEvent[] = this.extractCorporateEvents(edgarEvents);
+
+ // Extract balance sheet
+ const balance_sheet: BalanceSheetMetrics = {
+ total_assets: yfinanceData?.total_assets || 0,
+ total_liabilities: yfinanceData?.total_liabilities || 0,
+ stockholders_equity: (yfinanceData?.total_assets || 0) - (yfinanceData?.total_liabilities || 0),
+ shares_outstanding: yfinanceData?.shares_outstanding || 0,
+ total_cash: yfinanceData?.total_cash || 0,
+ total_debt: yfinanceData?.total_debt || 0,
+ };
+
+ // Extract financial metrics
+ const financials: FinancialMetrics = {
+ revenue: yfinanceData?.total_revenue || 0,
+ gross_profit: yfinanceData?.gross_profits || 0,
+ operating_cashflow: yfinanceData?.operating_cashflow || 0,
+ free_cashflow: yfinanceData?.free_cashflow || 0,
+ ebitda_margins: yfinanceData?.ebitda_margins || 0,
+ profit_margins: yfinanceData?.profit_margins || 0,
+ revenue_growth: yfinanceData?.revenue_growth || 0,
+ earnings_growth: yfinanceData?.earnings_growth || 0,
+ };
+
+ // Extract analyst data
+ const analysts: AnalystData = {
+ recommendation: yfinanceData?.recommendation_key || 'N/A',
+ recommendation_mean: yfinanceData?.recommendation_mean,
+ target_price: yfinanceData?.target_mean_price || 0,
+ target_high: yfinanceData?.target_high_price || 0,
+ target_low: yfinanceData?.target_low_price || 0,
+ analyst_count: yfinanceData?.number_of_analyst_opinions || 0,
+ };
+
+ // Extract ownership
+ const ownership: OwnershipData = {
+ insider_percent: (yfinanceData?.held_percent_insiders || 0) * 100,
+ institutional_percent: (yfinanceData?.held_percent_institutions || 0) * 100,
+ float_shares: yfinanceData?.float_shares || 0,
+ shares_outstanding: yfinanceData?.shares_outstanding || 0,
+ };
+
+ // Extract valuation
+ const valuation: ValuationMetrics = {
+ pe_ratio: yfinanceData?.pe_ratio || 0,
+ forward_pe: yfinanceData?.forward_pe || 0,
+ price_to_book: yfinanceData?.price_to_book || 0,
+ enterprise_value: yfinanceData?.enterprise_value || 0,
+ enterprise_to_revenue: yfinanceData?.enterprise_to_revenue || 0,
+ peg_ratio: yfinanceData?.peg_ratio || 0,
+ };
+
+ return {
+ company,
+ executives,
+ holders,
+ filings,
+ corporate_events,
+ balance_sheet,
+ financials,
+ analysts,
+ ownership,
+ valuation,
+ timestamp: new Date().toISOString()
+ };
+ }
+
+ /**
+ * Extract corporate events from Edgar data
+ */
+ private extractCorporateEvents(eventsData: any): CorporateEvent[] {
+ if (!eventsData?.data) {
+ return [];
+ }
+
+ return eventsData.data.slice(0, 15).map((event: any) => ({
+ filing_date: event.filing_date || '',
+ period_of_report: event.period_of_report || '',
+ form: event.form || '8-K',
+ filing_url: event.filing_url || '',
+ accession_number: event.accession_number || '',
+ items: event.items || [],
+ description: event.description || '',
+ }));
+ }
+
+ /**
+ * Extract executives from proxy data
+ */
+ private extractExecutives(proxyData: any): Executive[] {
+ if (!proxyData?.data?.named_executives || proxyData.data.named_executives.length === 0) {
+ return [];
+ }
+
+ const executives: Executive[] = [];
+ const seen = new Set<string>();
+
+ for (const exec of proxyData.data.named_executives) {
+ const name = exec.name;
+ if (name && !seen.has(name)) {
+ seen.add(name);
+ executives.push({
+ name,
+ role: this.parseRole(exec.role),
+ compensation: exec.total_comp
+ });
+ }
+ }
+
+ return executives.slice(0, 20);
+ }
+
+ /**
+ * Parse executive role
+ */
+ private parseRole(role: string): string {
+ if (!role) return 'Executive';
+ if (role.includes('Peo') || role.includes('CEO')) return 'CEO';
+ if (role.includes('CFO')) return 'CFO';
+ if (role.includes('Neo')) return 'Executive Officer';
+ if (role.includes('COO')) return 'COO';
+ if (role.includes('CTO')) return 'CTO';
+ return role;
+ }
+
+ /**
+ * Extract institutional holders (placeholder)
+ */
+ private extractHolders(yfinanceData: any): InstitutionalHolder[] {
+ // TODO: Implement when yfinance_data.py adds institutional_holders method
+ return [];
+ }
+
+ /**
+ * Extract recent filings
+ */
+ private extractFilings(filingsData: any): Filing[] {
+ if (!filingsData?.data) {
+ return [];
+ }
+
+ return filingsData.data.slice(0, 20).map((filing: any) => ({
+ form: filing.form || '',
+ filing_date: filing.filing_date || '',
+ description: this.getFilingDescription(filing.form),
+ url: filing.filing_url || '',
+ period: filing.period_of_report || ''
+ }));
+ }
+
+ /**
+ * Get filing description
+ */
+ private getFilingDescription(form: string): string {
+ const descriptions: Record<string, string> = {
+ '10-K': 'Annual Report',
+ '10-Q': 'Quarterly Report',
+ '8-K': 'Current Event',
+ '4': 'Insider Trading',
+ 'DEF 14A': 'Proxy Statement',
+ '13F-HR': 'Institutional Holdings',
+ 'S-8': 'Employee Stock Plan',
+ 'SCHEDULE 13G/A': '5%+ Ownership Amendment',
+ 'DEFA14A': 'Proxy Additional Materials',
+ '144': 'Insider Sale Notice'
+ };
+ return descriptions[form] || form;
+ }
+}
+
+export const relationshipMapService = new RelationshipMapService();