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.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
update 3.2.1
tilakpatel228aeab0622a9c
diff --git a/.github/workflows/release-production.yml b/.github/workflows/release-production.ymlindex cdbf76f68..02c0c0748 100644--- a/.github/workflows/release-production.yml+++ b/.github/workflows/release-production.yml@@ -139,8 +139,14 @@ jobs:TAR_GZ=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle/macos -name "*.app.tar.gz" -type f 2>/dev/null | head -1)TAR_GZ_SIG=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle/macos -name "*.app.tar.gz.sig" -type f 2>/dev/null | head -1)- [ -f "$TAR_GZ" ] && cp "$TAR_GZ" "release-artifacts/" && echo "Found macOS tar.gz: $TAR_GZ"- [ -f "$TAR_GZ_SIG" ] && cp "$TAR_GZ_SIG" "release-artifacts/" && echo "Found macOS signature: $TAR_GZ_SIG"+ if [ -f "$TAR_GZ" ]; then+ cp "$TAR_GZ" "release-artifacts/FinceptTerminal-${{ matrix.arch }}-darwin.app.tar.gz"+ echo "Found macOS tar.gz: $TAR_GZ"+ fi+ if [ -f "$TAR_GZ_SIG" ]; then+ cp "$TAR_GZ_SIG" "release-artifacts/FinceptTerminal-${{ matrix.arch }}-darwin.app.tar.gz.sig"+ echo "Found macOS signature: $TAR_GZ_SIG"+ fielif [[ "${{ matrix.platform }}" == "ubuntu-22.04" ]]; thenSUFFIX="Linux-x64"@@ -151,8 +157,14 @@ jobs:APPIMAGE_TAR_GZ=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle/appimage -name "*.AppImage.tar.gz" -type f 2>/dev/null | head -1)APPIMAGE_TAR_GZ_SIG=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle/appimage -name "*.AppImage.tar.gz.sig" -type f 2>/dev/null | head -1)- [ -f "$APPIMAGE_TAR_GZ" ] && cp "$APPIMAGE_TAR_GZ" "release-artifacts/" && echo "Found Linux tar.gz: $APPIMAGE_TAR_GZ"- [ -f "$APPIMAGE_TAR_GZ_SIG" ] && cp "$APPIMAGE_TAR_GZ_SIG" "release-artifacts/" && echo "Found Linux signature: $APPIMAGE_TAR_GZ_SIG"+ if [ -f "$APPIMAGE_TAR_GZ" ]; then+ cp "$APPIMAGE_TAR_GZ" "release-artifacts/FinceptTerminal-x86_64-linux.AppImage.tar.gz"+ echo "Found Linux tar.gz: $APPIMAGE_TAR_GZ"+ fi+ if [ -f "$APPIMAGE_TAR_GZ_SIG" ]; then+ cp "$APPIMAGE_TAR_GZ_SIG" "release-artifacts/FinceptTerminal-x86_64-linux.AppImage.tar.gz.sig"+ echo "Found Linux signature: $APPIMAGE_TAR_GZ_SIG"+ fielif [[ "${{ matrix.platform }}" == "windows-2022" ]]; thenSUFFIX="Windows-x64"@@ -161,8 +173,14 @@ jobs:NSIS_ZIP=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle/nsis -name "*.nsis.zip" -type f 2>/dev/null | head -1)NSIS_ZIP_SIG=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle/nsis -name "*.nsis.zip.sig" -type f 2>/dev/null | head -1)- [ -f "$NSIS_ZIP" ] && cp "$NSIS_ZIP" "release-artifacts/" && echo "Found NSIS zip: $NSIS_ZIP"- [ -f "$NSIS_ZIP_SIG" ] && cp "$NSIS_ZIP_SIG" "release-artifacts/" && echo "Found Windows signature: $NSIS_ZIP_SIG"+ if [ -f "$NSIS_ZIP" ]; then+ cp "$NSIS_ZIP" "release-artifacts/FinceptTerminal-x86_64-windows.nsis.zip"+ echo "Found NSIS zip: $NSIS_ZIP"+ fi+ if [ -f "$NSIS_ZIP_SIG" ]; then+ cp "$NSIS_ZIP_SIG" "release-artifacts/FinceptTerminal-x86_64-windows.nsis.zip.sig"+ echo "Found Windows signature: $NSIS_ZIP_SIG"+ fifiLATEST_JSON=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle -name "latest.json" -type f 2>/dev/null | head -1)@@ -236,13 +254,9 @@ jobs:find all-artifacts -type f -name "*.AppImage" -exec cp {} release-files/ \;find all-artifacts -type f -name "*.deb" -exec cp {} release-files/ \;- # Copy updater archives and signatures- find all-artifacts -type f -name "*.app.tar.gz" -exec cp {} release-files/ \;- find all-artifacts -type f -name "*.app.tar.gz.sig" -exec cp {} release-files/ \;- find all-artifacts -type f -name "*.AppImage.tar.gz" -exec cp {} release-files/ \;- find all-artifacts -type f -name "*.AppImage.tar.gz.sig" -exec cp {} release-files/ \;- find all-artifacts -type f -name "*.nsis.zip" -exec cp {} release-files/ \;- find all-artifacts -type f -name "*.nsis.zip.sig" -exec cp {} release-files/ \;+ # Copy updater archives and signatures (with architecture-specific naming)+ find all-artifacts -type f \( -name "*-darwin.app.tar.gz" -o -name "*-linux.AppImage.tar.gz" -o -name "*-windows.nsis.zip" \) -exec cp {} release-files/ \;+ find all-artifacts -type f \( -name "*-darwin.app.tar.gz.sig" -o -name "*-linux.AppImage.tar.gz.sig" -o -name "*-windows.nsis.zip.sig" \) -exec cp {} release-files/ \;echo "=== Release files ==="ls -lh release-files/diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.jsonindex b64e86e15..0a44c4636 100644--- a/fincept-terminal-desktop/package.json+++ b/fincept-terminal-desktop/package.json@@ -1,7 +1,7 @@{"name": "fincept-terminal-desktop","private": true,- "version": "3.2.0",+ "version": "3.2.1","type": "module","license": "AGPL-3.0-or-later","scripts": {diff --git a/fincept-terminal-desktop/src-tauri/Cargo.lock b/fincept-terminal-desktop/src-tauri/Cargo.lockindex 3cf7f3e6d..1bf23dcfc 100644--- a/fincept-terminal-desktop/src-tauri/Cargo.lock+++ b/fincept-terminal-desktop/src-tauri/Cargo.lock@@ -1352,7 +1352,7 @@ dependencies = [[[package]]name = "fincept-terminal-desktop"-version = "3.2.0"+version = "3.2.1"dependencies = ["aes-gcm","ahash 0.8.12",diff --git a/fincept-terminal-desktop/src-tauri/Cargo.toml b/fincept-terminal-desktop/src-tauri/Cargo.tomlindex 9b2f793ba..c290e6ebb 100644--- a/fincept-terminal-desktop/src-tauri/Cargo.toml+++ b/fincept-terminal-desktop/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "fincept-terminal-desktop"-version = "3.2.0"+version = "3.2.1"description = "Professional-grade financial analysis platform with AI-powered insights and real-time market data"authors = ["Fincept Corporation <[email protected]>"]edition = "2021"diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/__init__.pynew file mode 100644index 000000000..948af8af7--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/__init__.py@@ -0,0 +1,8 @@+"""Corporate Finance & M&A Analysis Module"""+__version__ = "1.0.0"++from .deal_database.deal_tracker import MADealTracker+from .deal_database.deal_scanner import MADealScanner+from .deal_database.deal_parser import MADealParser++__all__ = ['MADealTracker', 'MADealScanner', 'MADealParser']diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/__init__.pynew file mode 100644index 000000000..a1763d409--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/__init__.py@@ -0,0 +1,9 @@+"""Advanced Analytics Module"""+from .monte_carlo_valuation import MonteCarloValuation+from .regression_analysis import MARegression, RegressionResult++__all__ = [+ 'MonteCarloValuation',+ 'MARegression',+ 'RegressionResult'+]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/monte_carlo_valuation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/monte_carlo_valuation.pynew file mode 100644index 000000000..102084349--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/monte_carlo_valuation.py@@ -0,0 +1,343 @@+"""Monte Carlo Simulation for M&A Valuation"""+from typing import Dict, Any, List, Optional, Callable+import numpy as np++class MonteCarloValuation:+ """Monte Carlo simulation for deal valuation under uncertainty"""++ def __init__(self, num_simulations: int = 10000, random_seed: Optional[int] = None):+ self.num_simulations = num_simulations+ if random_seed:+ np.random.seed(random_seed)++ def simulate_synergies(self, base_revenue_synergy: float,+ base_cost_synergy: float,+ revenue_std_dev_pct: float,+ cost_std_dev_pct: float,+ correlation: float = 0.3) -> Dict[str, Any]:+ """Simulate synergy outcomes with correlated uncertainties"""++ revenue_std = base_revenue_synergy * revenue_std_dev_pct+ cost_std = base_cost_synergy * cost_std_dev_pct++ mean = [base_revenue_synergy, base_cost_synergy]+ cov = [+ [revenue_std**2, correlation * revenue_std * cost_std],+ [correlation * revenue_std * cost_std, cost_std**2]+ ]++ simulated_synergies = np.random.multivariate_normal(mean, cov, self.num_simulations)++ revenue_synergies = simulated_synergies[:, 0]+ cost_synergies = simulated_synergies[:, 1]+ total_synergies = revenue_synergies + cost_synergies++ revenue_synergies = np.maximum(revenue_synergies, 0)+ cost_synergies = np.maximum(cost_synergies, 0)+ total_synergies = revenue_synergies + cost_synergies++ return {+ 'revenue_synergies': {+ 'mean': float(np.mean(revenue_synergies)),+ 'median': float(np.median(revenue_synergies)),+ 'std': float(np.std(revenue_synergies)),+ 'percentile_5': float(np.percentile(revenue_synergies, 5)),+ 'percentile_25': float(np.percentile(revenue_synergies, 25)),+ 'percentile_75': float(np.percentile(revenue_synergies, 75)),+ 'percentile_95': float(np.percentile(revenue_synergies, 95))+ },+ 'cost_synergies': {+ 'mean': float(np.mean(cost_synergies)),+ 'median': float(np.median(cost_synergies)),+ 'std': float(np.std(cost_synergies)),+ 'percentile_5': float(np.percentile(cost_synergies, 5)),+ 'percentile_25': float(np.percentile(cost_synergies, 25)),+ 'percentile_75': float(np.percentile(cost_synergies, 75)),+ 'percentile_95': float(np.percentile(cost_synergies, 95))+ },+ 'total_synergies': {+ 'mean': float(np.mean(total_synergies)),+ 'median': float(np.median(total_synergies)),+ 'std': float(np.std(total_synergies)),+ 'percentile_5': float(np.percentile(total_synergies, 5)),+ 'percentile_25': float(np.percentile(total_synergies, 25)),+ 'percentile_75': float(np.percentile(total_synergies, 75)),+ 'percentile_95': float(np.percentile(total_synergies, 95))+ },+ 'probability_positive': float(np.sum(total_synergies > 0) / self.num_simulations * 100),+ 'correlation': correlation,+ 'num_simulations': self.num_simulations+ }++ def simulate_dcf_valuation(self, base_fcf: List[float],+ fcf_growth_mean: float,+ fcf_growth_std: float,+ terminal_growth_mean: float,+ terminal_growth_std: float,+ wacc_mean: float,+ wacc_std: float) -> Dict[str, Any]:+ """Simulate DCF valuation with uncertain inputs"""++ valuations = []++ for _ in range(self.num_simulations):+ growth_rates = np.random.normal(fcf_growth_mean, fcf_growth_std, len(base_fcf))+ fcf_projection = [base_fcf[0] * np.prod(1 + growth_rates[:i+1]) for i in range(len(base_fcf))]++ terminal_growth = np.random.normal(terminal_growth_mean, terminal_growth_std)+ terminal_growth = np.clip(terminal_growth, 0, 0.06)++ wacc = np.random.normal(wacc_mean, wacc_std)+ wacc = np.clip(wacc, 0.05, 0.20)++ terminal_fcf = fcf_projection[-1] * (1 + terminal_growth)+ terminal_value = terminal_fcf / (wacc - terminal_growth)++ pv_fcf = sum(fcf / ((1 + wacc) ** (i + 1)) for i, fcf in enumerate(fcf_projection))+ pv_terminal = terminal_value / ((1 + wacc) ** len(base_fcf))++ valuation = pv_fcf + pv_terminal+ valuations.append(valuation)++ valuations = np.array(valuations)++ return {+ 'valuation_statistics': {+ 'mean': float(np.mean(valuations)),+ 'median': float(np.median(valuations)),+ 'std': float(np.std(valuations)),+ 'min': float(np.min(valuations)),+ 'max': float(np.max(valuations)),+ 'percentile_5': float(np.percentile(valuations, 5)),+ 'percentile_10': float(np.percentile(valuations, 10)),+ 'percentile_25': float(np.percentile(valuations, 25)),+ 'percentile_75': float(np.percentile(valuations, 75)),+ 'percentile_90': float(np.percentile(valuations, 90)),+ 'percentile_95': float(np.percentile(valuations, 95))+ },+ 'input_assumptions': {+ 'fcf_growth_mean': fcf_growth_mean * 100,+ 'fcf_growth_std': fcf_growth_std * 100,+ 'terminal_growth_mean': terminal_growth_mean * 100,+ 'terminal_growth_std': terminal_growth_std * 100,+ 'wacc_mean': wacc_mean * 100,+ 'wacc_std': wacc_std * 100+ },+ 'num_simulations': self.num_simulations+ }++ def simulate_deal_returns(self, purchase_price: float,+ synergy_mean: float,+ synergy_std: float,+ integration_cost_mean: float,+ integration_cost_std: float,+ years_to_realize: int = 3,+ discount_rate: float = 0.10) -> Dict[str, Any]:+ """Simulate deal returns considering synergies and integration costs"""++ npvs = []+ irrs = []++ for _ in range(self.num_simulations):+ annual_synergy = np.random.normal(synergy_mean, synergy_std)+ annual_synergy = max(0, annual_synergy)++ integration_cost = np.random.normal(integration_cost_mean, integration_cost_std)+ integration_cost = max(0, integration_cost)++ cash_flows = [-purchase_price - integration_cost]++ for year in range(1, years_to_realize + 6):+ if year <= years_to_realize:+ realized_synergy = annual_synergy * (year / years_to_realize)+ else:+ realized_synergy = annual_synergy++ cash_flows.append(realized_synergy)++ npv = sum(cf / ((1 + discount_rate) ** i) for i, cf in enumerate(cash_flows))+ npvs.append(npv)++ try:+ irr = np.irr(cash_flows)+ if not np.isnan(irr) and -1 < irr < 2:+ irrs.append(irr)+ except:+ pass++ npvs = np.array(npvs)+ irrs = np.array(irrs) if irrs else np.array([0])++ probability_positive_npv = float(np.sum(npvs > 0) / self.num_simulations * 100)++ return {+ 'npv_statistics': {+ 'mean': float(np.mean(npvs)),+ 'median': float(np.median(npvs)),+ 'std': float(np.std(npvs)),+ 'percentile_5': float(np.percentile(npvs, 5)),+ 'percentile_25': float(np.percentile(npvs, 25)),+ 'percentile_75': float(np.percentile(npvs, 75)),+ 'percentile_95': float(np.percentile(npvs, 95))+ },+ 'irr_statistics': {+ 'mean': float(np.mean(irrs)) * 100 if len(irrs) > 0 else None,+ 'median': float(np.median(irrs)) * 100 if len(irrs) > 0 else None,+ 'std': float(np.std(irrs)) * 100 if len(irrs) > 0 else None+ },+ 'probability_positive_npv': probability_positive_npv,+ 'probability_negative_npv': 100 - probability_positive_npv,+ 'value_at_risk_5pct': float(np.percentile(npvs, 5)),+ 'expected_shortfall_5pct': float(np.mean(npvs[npvs <= np.percentile(npvs, 5)])),+ 'purchase_price': purchase_price,+ 'num_simulations': self.num_simulations+ }++ def simulate_accretion_dilution(self, acquirer_eps: float,+ target_eps: float,+ purchase_price_mean: float,+ purchase_price_std: float,+ synergy_mean: float,+ synergy_std: float,+ acquirer_shares: float,+ target_shares: float,+ payment_stock_pct: float = 0.5) -> Dict[str, Any]:+ """Simulate EPS accretion/dilution"""++ accretion_pcts = []++ for _ in range(self.num_simulations):+ purchase_price = np.random.normal(purchase_price_mean, purchase_price_std)+ purchase_price = max(purchase_price_mean * 0.5, purchase_price)++ synergy = np.random.normal(synergy_mean, synergy_std)+ synergy = max(0, synergy)++ stock_consideration = purchase_price * payment_stock_pct+ acquirer_price = purchase_price / target_shares++ new_shares = (stock_consideration / acquirer_price) * (target_shares / acquirer_shares)++ combined_earnings = (acquirer_eps * acquirer_shares) + (target_eps * target_shares) + synergy+ pro_forma_shares = acquirer_shares + new_shares++ pro_forma_eps = combined_earnings / pro_forma_shares++ accretion_pct = ((pro_forma_eps - acquirer_eps) / acquirer_eps) * 100+ accretion_pcts.append(accretion_pct)++ accretion_pcts = np.array(accretion_pcts)++ probability_accretive = float(np.sum(accretion_pcts > 0) / self.num_simulations * 100)++ return {+ 'accretion_statistics': {+ 'mean': float(np.mean(accretion_pcts)),+ 'median': float(np.median(accretion_pcts)),+ 'std': float(np.std(accretion_pcts)),+ 'percentile_5': float(np.percentile(accretion_pcts, 5)),+ 'percentile_25': float(np.percentile(accretion_pcts, 25)),+ 'percentile_75': float(np.percentile(accretion_pcts, 75)),+ 'percentile_95': float(np.percentile(accretion_pcts, 95))+ },+ 'probability_accretive': probability_accretive,+ 'probability_dilutive': 100 - probability_accretive,+ 'expected_accretion_pct': float(np.mean(accretion_pcts)),+ 'downside_scenario_5pct': float(np.percentile(accretion_pcts, 5)),+ 'upside_scenario_95pct': float(np.percentile(accretion_pcts, 95)),+ 'num_simulations': self.num_simulations+ }++ def value_at_risk_analysis(self, deal_value: float,+ value_distribution: np.ndarray,+ confidence_level: float = 0.95) -> Dict[str, Any]:+ """Calculate Value at Risk metrics"""++ var_level = 1 - confidence_level+ var_value = float(np.percentile(value_distribution, var_level * 100))++ tail_values = value_distribution[value_distribution <= var_value]+ expected_shortfall = float(np.mean(tail_values)) if len(tail_values) > 0 else var_value++ return {+ 'confidence_level': confidence_level * 100,+ 'value_at_risk': var_value,+ 'expected_shortfall': expected_shortfall,+ 'potential_loss': deal_value - var_value,+ 'potential_loss_pct': ((deal_value - var_value) / deal_value * 100) if deal_value > 0 else 0+ }++if __name__ == '__main__':+ mc = MonteCarloValuation(num_simulations=10000, random_seed=42)++ synergies = mc.simulate_synergies(+ base_revenue_synergy=50_000_000,+ base_cost_synergy=30_000_000,+ revenue_std_dev_pct=0.30,+ cost_std_dev_pct=0.20,+ correlation=0.3+ )++ print("=== MONTE CARLO SYNERGY SIMULATION ===\n")+ print(f"Simulations: {synergies['num_simulations']:,}\n")++ print("Total Synergies:")+ total = synergies['total_synergies']+ print(f" Mean: ${total['mean']:,.0f}")+ print(f" Median: ${total['median']:,.0f}")+ print(f" Std Dev: ${total['std']:,.0f}")+ print(f" 5th Percentile: ${total['percentile_5']:,.0f}")+ print(f" 95th Percentile: ${total['percentile_95']:,.0f}")+ print(f" Probability Positive: {synergies['probability_positive']:.1f}%")++ print("\n\nRevenue Synergies:")+ rev = synergies['revenue_synergies']+ print(f" Mean: ${rev['mean']:,.0f}")+ print(f" Range (5th-95th): ${rev['percentile_5']:,.0f} - ${rev['percentile_95']:,.0f}")++ print("\nCost Synergies:")+ cost = synergies['cost_synergies']+ print(f" Mean: ${cost['mean']:,.0f}")+ print(f" Range (5th-95th): ${cost['percentile_5']:,.0f} - ${cost['percentile_95']:,.0f}")++ deal_returns = mc.simulate_deal_returns(+ purchase_price=500_000_000,+ synergy_mean=80_000_000,+ synergy_std=20_000_000,+ integration_cost_mean=50_000_000,+ integration_cost_std=15_000_000,+ years_to_realize=3,+ discount_rate=0.10+ )++ print("\n\n=== DEAL RETURNS SIMULATION ===")+ npv = deal_returns['npv_statistics']+ print(f"\nNPV Statistics:")+ print(f" Mean: ${npv['mean']:,.0f}")+ print(f" Median: ${npv['median']:,.0f}")+ print(f" Std Dev: ${npv['std']:,.0f}")+ print(f" 5th Percentile: ${npv['percentile_5']:,.0f}")+ print(f" 95th Percentile: ${npv['percentile_95']:,.0f}")+ print(f"\nProbability Positive NPV: {deal_returns['probability_positive_npv']:.1f}%")+ print(f"Value at Risk (5%): ${deal_returns['value_at_risk_5pct']:,.0f}")++ accretion = mc.simulate_accretion_dilution(+ acquirer_eps=5.00,+ target_eps=2.50,+ purchase_price_mean=800_000_000,+ purchase_price_std=100_000_000,+ synergy_mean=40_000_000,+ synergy_std=10_000_000,+ acquirer_shares=100_000_000,+ target_shares=50_000_000,+ payment_stock_pct=0.6+ )++ print("\n\n=== EPS ACCRETION/DILUTION SIMULATION ===")+ acc = accretion['accretion_statistics']+ print(f"\nAccretion/Dilution %:")+ print(f" Expected: {accretion['expected_accretion_pct']:+.2f}%")+ print(f" Median: {acc['median']:+.2f}%")+ print(f" 5th Percentile: {acc['percentile_5']:+.2f}%")+ print(f" 95th Percentile: {acc['percentile_95']:+.2f}%")+ print(f"\nProbability Accretive: {accretion['probability_accretive']:.1f}%")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/regression_analysis.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/regression_analysis.pynew file mode 100644index 000000000..bf1b4c6ca--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/advanced_analytics/regression_analysis.py@@ -0,0 +1,304 @@+"""Regression Analysis for M&A Valuation"""+from typing import Dict, Any, List, Optional, Tuple+import numpy as np+from dataclasses import dataclass++@dataclass+class RegressionResult:+ coefficients: np.ndarray+ intercept: float+ r_squared: float+ adjusted_r_squared: float+ std_errors: np.ndarray+ t_statistics: np.ndarray+ p_values: np.ndarray++class MARegression:+ """Regression analysis for M&A valuation and comps"""++ def linear_regression(self, X: np.ndarray, y: np.ndarray) -> RegressionResult:+ """Perform OLS linear regression"""++ n = len(y)+ k = X.shape[1]++ X_with_intercept = np.column_stack([np.ones(n), X])++ beta = np.linalg.lstsq(X_with_intercept, y, rcond=None)[0]++ intercept = beta[0]+ coefficients = beta[1:]++ y_pred = X_with_intercept @ beta+ residuals = y - y_pred++ ss_total = np.sum((y - np.mean(y)) ** 2)+ ss_residual = np.sum(residuals ** 2)++ r_squared = 1 - (ss_residual / ss_total) if ss_total > 0 else 0+ adjusted_r_squared = 1 - ((1 - r_squared) * (n - 1) / (n - k - 1)) if n > k + 1 else 0++ mse = ss_residual / (n - k - 1) if n > k + 1 else 0+ var_beta = mse * np.linalg.inv(X_with_intercept.T @ X_with_intercept)+ std_errors = np.sqrt(np.diag(var_beta))++ t_statistics = beta / std_errors+ from scipy import stats+ p_values = 2 * (1 - stats.t.cdf(np.abs(t_statistics), n - k - 1))++ return RegressionResult(+ coefficients=coefficients,+ intercept=intercept,+ r_squared=r_squared,+ adjusted_r_squared=adjusted_r_squared,+ std_errors=std_errors[1:],+ t_statistics=t_statistics[1:],+ p_values=p_values[1:]+ )++ def multiple_regression_valuation(self, comp_data: List[Dict[str, float]],+ subject_metrics: Dict[str, float]) -> Dict[str, Any]:+ """+ Perform multiple regression for comparable company valuation++ comp_data: [{'ev': X, 'revenue': Y, 'ebitda_margin': Z, 'growth': W}, ...]+ subject_metrics: {'revenue': A, 'ebitda_margin': B, 'growth': C}+ """++ if len(comp_data) < 3:+ raise ValueError("Need at least 3 comparable companies")++ y = np.array([comp['ev'] for comp in comp_data])++ feature_names = [k for k in comp_data[0].keys() if k != 'ev']+ X = np.array([[comp[feature] for feature in feature_names] for comp in comp_data])++ result = self.linear_regression(X, y)++ subject_features = np.array([subject_metrics[feature] for feature in feature_names])+ predicted_value = result.intercept + np.dot(result.coefficients, subject_features)++ residual_std = np.std(y - (result.intercept + X @ result.coefficients))+ prediction_interval_95 = 1.96 * residual_std++ return {+ 'predicted_value': float(predicted_value),+ 'prediction_interval': {+ 'lower': float(predicted_value - prediction_interval_95),+ 'upper': float(predicted_value + prediction_interval_95)+ },+ 'regression_statistics': {+ 'r_squared': result.r_squared,+ 'adjusted_r_squared': result.adjusted_r_squared,+ 'intercept': result.intercept+ },+ 'coefficients': {+ feature: {+ 'coefficient': float(result.coefficients[i]),+ 'std_error': float(result.std_errors[i]),+ 't_statistic': float(result.t_statistics[i]),+ 'p_value': float(result.p_values[i]),+ 'significant': result.p_values[i] < 0.05+ }+ for i, feature in enumerate(feature_names)+ },+ 'subject_metrics': subject_metrics,+ 'num_comparables': len(comp_data)+ }++ def premium_regression(self, deal_data: List[Dict[str, float]]) -> Dict[str, Any]:+ """+ Regression analysis of acquisition premiums++ deal_data: [{'premium': X, 'size': Y, 'leverage': Z, 'growth': W, 'multiple': M}, ...]+ """++ y = np.array([deal['premium'] for deal in deal_data])++ feature_names = [k for k in deal_data[0].keys() if k != 'premium']+ X = np.array([[deal[feature] for feature in feature_names] for deal in deal_data])++ result = self.linear_regression(X, y)++ return {+ 'regression_statistics': {+ 'r_squared': result.r_squared,+ 'adjusted_r_squared': result.adjusted_r_squared,+ 'intercept': result.intercept+ },+ 'premium_drivers': {+ feature: {+ 'coefficient': float(result.coefficients[i]),+ 'interpretation': f"1 unit increase in {feature} → {result.coefficients[i]:+.2f}% premium change",+ 't_statistic': float(result.t_statistics[i]),+ 'p_value': float(result.p_values[i]),+ 'significant': result.p_values[i] < 0.05+ }+ for i, feature in enumerate(feature_names)+ },+ 'num_observations': len(deal_data)+ }++ def multiple_expansion_analysis(self, historical_data: List[Dict[str, float]]) -> Dict[str, Any]:+ """+ Analyze relationship between company metrics and valuation multiples++ historical_data: [{'multiple': X, 'growth': Y, 'margin': Z, 'roe': W}, ...]+ """++ y = np.array([data['multiple'] for data in historical_data])++ feature_names = [k for k in historical_data[0].keys() if k != 'multiple']+ X = np.array([[data[feature] for feature in feature_names] for data in historical_data])++ result = self.linear_regression(X, y)++ return {+ 'base_multiple': result.intercept,+ 'multiple_drivers': {+ feature: {+ 'impact_per_unit': float(result.coefficients[i]),+ 'std_error': float(result.std_errors[i]),+ 'significance': 'significant' if result.p_values[i] < 0.05 else 'not significant',+ 'p_value': float(result.p_values[i])+ }+ for i, feature in enumerate(feature_names)+ },+ 'model_fit': {+ 'r_squared': result.r_squared,+ 'adjusted_r_squared': result.adjusted_r_squared+ }+ }++ def predict_synergies(self, historical_deals: List[Dict[str, float]],+ current_deal: Dict[str, float]) -> Dict[str, Any]:+ """+ Predict synergies based on historical deal characteristics++ historical_deals: [{'synergy_pct': X, 'overlap': Y, 'size_ratio': Z}, ...]+ current_deal: {'overlap': A, 'size_ratio': B, ...}+ """++ y = np.array([deal['synergy_pct'] for deal in historical_deals])++ feature_names = [k for k in historical_deals[0].keys() if k != 'synergy_pct']+ X = np.array([[deal[feature] for feature in feature_names] for deal in historical_deals])++ result = self.linear_regression(X, y)++ current_features = np.array([current_deal[feature] for feature in feature_names])+ predicted_synergy_pct = result.intercept + np.dot(result.coefficients, current_features)++ residual_std = np.std(y - (result.intercept + X @ result.coefficients))+ confidence_interval = 1.96 * residual_std++ return {+ 'predicted_synergy_pct': float(predicted_synergy_pct),+ 'confidence_interval_95': {+ 'lower': float(predicted_synergy_pct - confidence_interval),+ 'upper': float(predicted_synergy_pct + confidence_interval)+ },+ 'model_quality': {+ 'r_squared': result.r_squared,+ 'prediction_error_std': residual_std+ },+ 'synergy_drivers': {+ feature: {+ 'coefficient': float(result.coefficients[i]),+ 'current_value': current_deal[feature]+ }+ for i, feature in enumerate(feature_names)+ }+ }++ def transaction_multiple_regression(self, transactions: List[Dict[str, float]],+ metric_name: str = 'ebitda') -> Dict[str, Any]:+ """+ Regression to determine fair transaction multiple++ transactions: [{'ev_to_metric': X, 'growth': Y, 'margin': Z, 'size': W}, ...]+ """++ y = np.array([txn['ev_to_metric'] for txn in transactions])++ feature_names = [k for k in transactions[0].keys() if k != 'ev_to_metric']+ X = np.array([[txn[feature] for feature in feature_names] for txn in transactions])++ result = self.linear_regression(X, y)++ avg_growth = np.mean([txn['growth'] for txn in transactions])+ avg_margin = np.mean([txn['margin'] for txn in transactions])+ avg_size = np.mean([txn['size'] for txn in transactions])++ median_company = {+ 'growth': avg_growth,+ 'margin': avg_margin,+ 'size': avg_size+ }++ median_features = np.array([median_company.get(f, np.mean(X[:, i])) for i, f in enumerate(feature_names)])+ median_multiple = result.intercept + np.dot(result.coefficients, median_features)++ return {+ 'base_multiple': result.intercept,+ 'median_market_multiple': float(median_multiple),+ 'multiple_adjustments': {+ feature: {+ 'per_unit_change': float(result.coefficients[i]),+ 'example': f"1% higher {feature} → {result.coefficients[i]:+.2f}x multiple change"+ }+ for i, feature in enumerate(feature_names)+ },+ 'model_statistics': {+ 'r_squared': result.r_squared,+ 'num_transactions': len(transactions)+ }+ }++if __name__ == '__main__':+ analyzer = MARegression()++ comp_data = [+ {'ev': 5_000_000_000, 'revenue': 1_000_000_000, 'ebitda_margin': 25, 'growth': 15},+ {'ev': 8_000_000_000, 'revenue': 1_500_000_000, 'ebitda_margin': 30, 'growth': 20},+ {'ev': 3_500_000_000, 'revenue': 800_000_000, 'ebitda_margin': 20, 'growth': 12},+ {'ev': 6_500_000_000, 'revenue': 1_200_000_000, 'ebitda_margin': 28, 'growth': 18},+ {'ev': 4_000_000_000, 'revenue': 900_000_000, 'ebitda_margin': 22, 'growth': 14}+ ]++ subject = {'revenue': 1_100_000_000, 'ebitda_margin': 26, 'growth': 16}++ valuation = analyzer.multiple_regression_valuation(comp_data, subject)++ print("=== REGRESSION-BASED VALUATION ===\n")+ print(f"Predicted Value: ${valuation['predicted_value']:,.0f}")+ print(f"95% Prediction Interval:")+ print(f" Lower: ${valuation['prediction_interval']['lower']:,.0f}")+ print(f" Upper: ${valuation['prediction_interval']['upper']:,.0f}")+ print(f"\nR-Squared: {valuation['regression_statistics']['r_squared']:.3f}")+ print(f"Adjusted R-Squared: {valuation['regression_statistics']['adjusted_r_squared']:.3f}")++ print("\n\nCoefficients:")+ for feature, stats in valuation['coefficients'].items():+ sig = "***" if stats['significant'] else ""+ print(f" {feature}: {stats['coefficient']:,.0f} (t={stats['t_statistic']:.2f}, p={stats['p_value']:.4f}) {sig}")++ deal_data = [+ {'premium': 35, 'size': 500, 'leverage': 0.3, 'growth': 10, 'multiple': 8},+ {'premium': 42, 'size': 1000, 'leverage': 0.25, 'growth': 15, 'multiple': 10},+ {'premium': 28, 'size': 300, 'leverage': 0.4, 'growth': 8, 'multiple': 7},+ {'premium': 38, 'size': 750, 'leverage': 0.3, 'growth': 12, 'multiple': 9},+ {'premium': 45, 'size': 1200, 'leverage': 0.2, 'growth': 18, 'multiple': 11}+ ]++ premium_analysis = analyzer.premium_regression(deal_data)++ print("\n\n=== PREMIUM REGRESSION ANALYSIS ===")+ print(f"R-Squared: {premium_analysis['regression_statistics']['r_squared']:.3f}")+ print(f"Base Premium: {premium_analysis['regression_statistics']['intercept']:.1f}%\n")++ print("Premium Drivers:")+ for driver, stats in premium_analysis['premium_drivers'].items():+ sig = "***" if stats['significant'] else ""+ print(f" {driver}: {stats['coefficient']:+.2f}% {sig}")+ print(f" {stats['interpretation']}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/config.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/config.pynew file mode 100644index 000000000..1d744e4c6--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/config.py@@ -0,0 +1,26 @@+"""Configuration for Corporate Finance Module"""+from pathlib import Path++BASE_DIR = Path(__file__).parent+SCRIPTS_DIR = BASE_DIR.parent.parent+RESOURCES_DIR = SCRIPTS_DIR.parent+DATABASE_DIR = RESOURCES_DIR / "databases"+MA_DATABASE = DATABASE_DIR / "ma_deals.db"++DEFAULT_DISCOUNT_RATE = 0.10+DEFAULT_TERMINAL_GROWTH = 0.025+DEFAULT_TAX_RATE = 0.21+DEFAULT_RISK_FREE_RATE = 0.045++MA_FILING_FORMS = ['8-K', 'S-4', 'DEFM14A', 'SC 13D', 'SC 13G', '425', 'PREM14A']+MATERIAL_EVENT_ITEMS = ['1.01', '2.01', '8.01']++INDUSTRIES = [+ 'Technology', 'Healthcare', 'Financial Services', 'Industrials',+ 'Consumer Discretionary', 'Consumer Staples', 'Energy', 'Materials',+ 'Real Estate', 'Utilities', 'Telecommunications', 'Media'+]++DEAL_TYPES = ['Merger', 'Acquisition', 'Takeover', 'Joint Venture', 'Asset Purchase', 'Reverse Merger']+PAYMENT_METHODS = ['Cash', 'Stock', 'Mixed', 'Debt', 'Earnout']+DEAL_STATUS = ['Announced', 'Pending', 'Completed', 'Terminated', 'Withdrawn']diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_comparison/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_comparison/__init__.pynew file mode 100644index 000000000..3e2a5b96c--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_comparison/__init__.py@@ -0,0 +1,4 @@+"""Deal Comparison Module"""+from .deal_comparator import DealComparator, Deal++__all__ = ['DealComparator', 'Deal']diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_comparison/deal_comparator.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_comparison/deal_comparator.pynew file mode 100644index 000000000..8b8f9c102--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_comparison/deal_comparator.py@@ -0,0 +1,323 @@+"""Deal Comparison and Analysis Tool"""+from typing import Dict, Any, List, Optional+import numpy as np+from dataclasses import dataclass++@dataclass+class Deal:+ deal_id: str+ target_name: str+ acquirer_name: str+ deal_value: float+ offer_price_per_share: Optional[float]+ premium_1day: float+ payment_cash_pct: float+ payment_stock_pct: float+ ev_revenue: Optional[float]+ ev_ebitda: Optional[float]+ synergies: Optional[float]+ status: str+ industry: str+ announced_date: str++class DealComparator:+ """Compare multiple M&A deals side-by-side"""++ def compare_deals(self, deals: List[Deal]) -> Dict[str, Any]:+ """Compare multiple deals across key metrics"""++ if len(deals) < 2:+ raise ValueError("Need at least 2 deals to compare")++ comparison_table = []++ for deal in deals:+ comparison_table.append({+ 'deal_id': deal.deal_id,+ 'target': deal.target_name,+ 'acquirer': deal.acquirer_name,+ 'deal_value': deal.deal_value,+ 'offer_price': deal.offer_price_per_share,+ 'premium_1day': deal.premium_1day,+ 'payment_cash_pct': deal.payment_cash_pct,+ 'payment_stock_pct': deal.payment_stock_pct,+ 'ev_revenue': deal.ev_revenue,+ 'ev_ebitda': deal.ev_ebitda,+ 'synergies': deal.synergies,+ 'status': deal.status,+ 'industry': deal.industry,+ 'announced_date': deal.announced_date+ })++ deal_values = [d.deal_value for d in deals]+ premiums = [d.premium_1day for d in deals]+ ev_revenues = [d.ev_revenue for d in deals if d.ev_revenue is not None]+ ev_ebitdas = [d.ev_ebitda for d in deals if d.ev_ebitda is not None]++ statistics = {+ 'deal_value': {+ 'min': min(deal_values),+ 'max': max(deal_values),+ 'mean': np.mean(deal_values),+ 'median': np.median(deal_values)+ },+ 'premium_1day': {+ 'min': min(premiums),+ 'max': max(premiums),+ 'mean': np.mean(premiums),+ 'median': np.median(premiums)+ }+ }++ if ev_revenues:+ statistics['ev_revenue'] = {+ 'min': min(ev_revenues),+ 'max': max(ev_revenues),+ 'mean': np.mean(ev_revenues),+ 'median': np.median(ev_revenues)+ }++ if ev_ebitdas:+ statistics['ev_ebitda'] = {+ 'min': min(ev_ebitdas),+ 'max': max(ev_ebitdas),+ 'mean': np.mean(ev_ebitdas),+ 'median': np.median(ev_ebitdas)+ }++ return {+ 'num_deals': len(deals),+ 'comparison_table': comparison_table,+ 'statistics': statistics+ }++ def rank_deals(self, deals: List[Deal],+ criteria: str = 'premium') -> Dict[str, Any]:+ """Rank deals by specific criteria"""++ ranking_map = {+ 'premium': lambda d: d.premium_1day,+ 'deal_value': lambda d: d.deal_value,+ 'ev_revenue': lambda d: d.ev_revenue if d.ev_revenue else 0,+ 'ev_ebitda': lambda d: d.ev_ebitda if d.ev_ebitda else 0,+ 'synergies': lambda d: d.synergies if d.synergies else 0+ }++ if criteria not in ranking_map:+ raise ValueError(f"Invalid criteria. Choose from: {list(ranking_map.keys())}")++ sorted_deals = sorted(deals, key=ranking_map[criteria], reverse=True)++ rankings = []+ for rank, deal in enumerate(sorted_deals, 1):+ rankings.append({+ 'rank': rank,+ 'deal_id': deal.deal_id,+ 'target': deal.target_name,+ 'acquirer': deal.acquirer_name,+ 'metric_value': ranking_map[criteria](deal)+ })++ return {+ 'ranking_criteria': criteria,+ 'rankings': rankings+ }++ def payment_structure_analysis(self, deals: List[Deal]) -> Dict[str, Any]:+ """Analyze payment structures across deals"""++ all_cash_count = sum(1 for d in deals if d.payment_cash_pct == 100)+ all_stock_count = sum(1 for d in deals if d.payment_stock_pct == 100)+ mixed_count = len(deals) - all_cash_count - all_stock_count++ avg_cash_pct = np.mean([d.payment_cash_pct for d in deals])+ avg_stock_pct = np.mean([d.payment_stock_pct for d in deals])++ return {+ 'total_deals': len(deals),+ 'all_cash_deals': all_cash_count,+ 'all_stock_deals': all_stock_count,+ 'mixed_deals': mixed_count,+ 'average_cash_pct': avg_cash_pct,+ 'average_stock_pct': avg_stock_pct,+ 'distribution': {+ 'all_cash_pct': (all_cash_count / len(deals) * 100) if deals else 0,+ 'all_stock_pct': (all_stock_count / len(deals) * 100) if deals else 0,+ 'mixed_pct': (mixed_count / len(deals) * 100) if deals else 0+ }+ }++ def industry_analysis(self, deals: List[Deal]) -> Dict[str, Any]:+ """Analyze deals by industry"""++ industry_groups = {}++ for deal in deals:+ if deal.industry not in industry_groups:+ industry_groups[deal.industry] = []+ industry_groups[deal.industry].append(deal)++ industry_stats = {}++ for industry, industry_deals in industry_groups.items():+ deal_values = [d.deal_value for d in industry_deals]+ premiums = [d.premium_1day for d in industry_deals]++ industry_stats[industry] = {+ 'count': len(industry_deals),+ 'total_value': sum(deal_values),+ 'avg_deal_value': np.mean(deal_values),+ 'avg_premium': np.mean(premiums),+ 'median_premium': np.median(premiums)+ }++ return {+ 'industries': list(industry_groups.keys()),+ 'industry_statistics': industry_stats+ }++ def premium_benchmarking(self, target_deal: Deal,+ comparable_deals: List[Deal]) -> Dict[str, Any]:+ """Benchmark target deal premium against comparables"""++ comp_premiums = [d.premium_1day for d in comparable_deals]++ percentile_25 = np.percentile(comp_premiums, 25)+ percentile_50 = np.percentile(comp_premiums, 50)+ percentile_75 = np.percentile(comp_premiums, 75)++ target_premium = target_deal.premium_1day++ if target_premium < percentile_25:+ position = "below 25th percentile"+ elif target_premium < percentile_50:+ position = "between 25th and 50th percentile"+ elif target_premium < percentile_75:+ position = "between 50th and 75th percentile"+ else:+ position = "above 75th percentile"++ return {+ 'target_deal': {+ 'deal_id': target_deal.deal_id,+ 'target': target_deal.target_name,+ 'premium': target_premium+ },+ 'comparable_premiums': {+ '25th_percentile': percentile_25,+ 'median': percentile_50,+ '75th_percentile': percentile_75,+ 'mean': np.mean(comp_premiums),+ 'min': min(comp_premiums),+ 'max': max(comp_premiums)+ },+ 'target_position': position,+ 'above_median': target_premium > percentile_50,+ 'num_comparables': len(comparable_deals)+ }++ def valuation_multiple_comparison(self, deals: List[Deal],+ multiple_type: str = 'ev_ebitda') -> Dict[str, Any]:+ """Compare valuation multiples across deals"""++ if multiple_type == 'ev_ebitda':+ multiples = [(d.target_name, d.ev_ebitda) for d in deals if d.ev_ebitda is not None]+ elif multiple_type == 'ev_revenue':+ multiples = [(d.target_name, d.ev_revenue) for d in deals if d.ev_revenue is not None]+ else:+ raise ValueError("Invalid multiple_type. Use 'ev_ebitda' or 'ev_revenue'")++ if not multiples:+ return {'error': f'No {multiple_type} data available for deals'}++ companies, values = zip(*multiples)++ return {+ 'multiple_type': multiple_type,+ 'deals': [{'company': c, 'multiple': v} for c, v in multiples],+ 'statistics': {+ 'min': min(values),+ 'max': max(values),+ 'mean': np.mean(values),+ 'median': np.median(values),+ 'std': np.std(values)+ },+ 'num_deals_with_data': len(multiples)+ }++ def synergy_analysis(self, deals: List[Deal]) -> Dict[str, Any]:+ """Analyze synergies across deals"""++ deals_with_synergies = [d for d in deals if d.synergies is not None]++ if not deals_with_synergies:+ return {'error': 'No synergy data available'}++ synergies = [d.synergies for d in deals_with_synergies]+ synergy_pct = [(d.synergies / d.deal_value * 100) for d in deals_with_synergies]++ return {+ 'deals_with_synergy_data': len(deals_with_synergies),+ 'total_synergies': sum(synergies),+ 'synergy_statistics': {+ 'min': min(synergies),+ 'max': max(synergies),+ 'mean': np.mean(synergies),+ 'median': np.median(synergies)+ },+ 'synergy_as_pct_of_deal': {+ 'min': min(synergy_pct),+ 'max': max(synergy_pct),+ 'mean': np.mean(synergy_pct),+ 'median': np.median(synergy_pct)+ }+ }++if __name__ == '__main__':+ deals = [+ Deal("D001", "Target A", "Acquirer X", 1_000_000_000, 45.00, 35, 100, 0, 5.0, 12.0, 150_000_000, "Completed", "Technology", "2024-01-15"),+ Deal("D002", "Target B", "Acquirer Y", 2_500_000_000, 82.50, 42, 60, 40, 8.0, 15.0, 300_000_000, "Pending", "Technology", "2024-03-20"),+ Deal("D003", "Target C", "Acquirer Z", 750_000_000, 28.00, 28, 100, 0, 4.5, 10.0, 100_000_000, "Completed", "Healthcare", "2024-02-10"),+ Deal("D004", "Target D", "Acquirer W", 1_800_000_000, 65.00, 38, 50, 50, 6.5, 13.5, 250_000_000, "Announced", "Technology", "2024-04-05"),+ ]++ comparator = DealComparator()++ comparison = comparator.compare_deals(deals)++ print("=== DEAL COMPARISON ===\n")+ print(f"Number of Deals: {comparison['num_deals']}\n")++ print("Deal Value Statistics:")+ dv_stats = comparison['statistics']['deal_value']+ print(f" Min: ${dv_stats['min']:,.0f}")+ print(f" Max: ${dv_stats['max']:,.0f}")+ print(f" Mean: ${dv_stats['mean']:,.0f}")+ print(f" Median: ${dv_stats['median']:,.0f}")++ print("\nPremium Statistics:")+ prem_stats = comparison['statistics']['premium_1day']+ print(f" Min: {prem_stats['min']:.1f}%")+ print(f" Max: {prem_stats['max']:.1f}%")+ print(f" Mean: {prem_stats['mean']:.1f}%")+ print(f" Median: {prem_stats['median']:.1f}%")++ payment = comparator.payment_structure_analysis(deals)+ print("\n\n=== PAYMENT STRUCTURE ANALYSIS ===")+ print(f"All Cash: {payment['all_cash_deals']} ({payment['distribution']['all_cash_pct']:.0f}%)")+ print(f"All Stock: {payment['all_stock_deals']} ({payment['distribution']['all_stock_pct']:.0f}%)")+ print(f"Mixed: {payment['mixed_deals']} ({payment['distribution']['mixed_pct']:.0f}%)")++ industry = comparator.industry_analysis(deals)+ print("\n\n=== INDUSTRY ANALYSIS ===")+ for ind, stats in industry['industry_statistics'].items():+ print(f"\n{ind}:")+ print(f" Count: {stats['count']}")+ print(f" Total Value: ${stats['total_value']:,.0f}")+ print(f" Avg Premium: {stats['avg_premium']:.1f}%")++ benchmark = comparator.premium_benchmarking(deals[1], [deals[0], deals[2], deals[3]])+ print("\n\n=== PREMIUM BENCHMARKING ===")+ print(f"Target Deal: {benchmark['target_deal']['target']} ({benchmark['target_deal']['premium']:.1f}%)")+ print(f"Position: {benchmark['target_position']}")+ print(f"Median Premium: {benchmark['comparable_premiums']['median']:.1f}%")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/__init__.pynew file mode 100644index 000000000..8b6ab94f4--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/__init__.py@@ -0,0 +1,7 @@+"""M&A Deal Database Module"""+from .database_schema import MADatabase+from .deal_scanner import MADealScanner+from .deal_parser import MADealParser+from .deal_tracker import MADealTracker++__all__ = ['MADatabase', 'MADealScanner', 'MADealParser', 'MADealTracker']diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/database_schema.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/database_schema.pynew file mode 100644index 000000000..a2b8e6a5e--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/database_schema.py@@ -0,0 +1,444 @@+"""SQLite Database Schema for M&A Deals"""+import sqlite3+from pathlib import Path+from typing import Optional, Dict, Any, List+from datetime import datetime+import json++class MADatabase:+ def __init__(self, db_path: Optional[Path] = None):+ if db_path is None:+ from ..config import MA_DATABASE+ db_path = MA_DATABASE++ self.db_path = db_path+ self.db_path.parent.mkdir(parents=True, exist_ok=True)+ self.conn = None+ self._initialize_database()++ def _get_connection(self):+ if self.conn is None:+ self.conn = sqlite3.connect(str(self.db_path))+ self.conn.row_factory = sqlite3.Row+ return self.conn++ def _initialize_database(self):+ conn = self._get_connection()+ cursor = conn.cursor()++ cursor.execute("""+ CREATE TABLE IF NOT EXISTS ma_deals (+ deal_id TEXT PRIMARY KEY,+ announcement_date DATE NOT NULL,+ expected_close_date DATE,+ actual_close_date DATE,+ acquirer_name TEXT NOT NULL,+ acquirer_ticker TEXT,+ acquirer_cik TEXT,+ target_name TEXT NOT NULL,+ target_ticker TEXT,+ target_cik TEXT,+ deal_value REAL,+ deal_value_currency TEXT DEFAULT 'USD',+ enterprise_value REAL,+ equity_value REAL,+ deal_type TEXT NOT NULL,+ deal_status TEXT NOT NULL,+ payment_method TEXT,+ cash_percentage REAL,+ stock_percentage REAL,+ industry TEXT,+ sector TEXT,+ sub_sector TEXT,+ deal_rationale TEXT,+ strategic_fit_score REAL,+ synergies_disclosed REAL,+ synergy_type TEXT,+ integration_costs REAL,+ premium_1day REAL,+ premium_1week REAL,+ premium_4week REAL,+ premium_52week_high REAL,+ hostile_flag INTEGER DEFAULT 0,+ tender_offer_flag INTEGER DEFAULT 0,+ cross_border_flag INTEGER DEFAULT 0,+ acquirer_country TEXT,+ target_country TEXT,+ regulatory_concerns TEXT,+ antitrust_review_flag INTEGER DEFAULT 0,+ breakup_fee REAL,+ termination_conditions TEXT,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ data_source TEXT,+ filing_url TEXT,+ notes TEXT+ )""")++ cursor.execute("""+ CREATE TABLE IF NOT EXISTS deal_financials (+ financial_id INTEGER PRIMARY KEY AUTOINCREMENT,+ deal_id TEXT NOT NULL,+ period_type TEXT NOT NULL,+ fiscal_year INTEGER,+ fiscal_quarter INTEGER,+ party TEXT NOT NULL,+ revenue REAL,+ ebitda REAL,+ ebit REAL,+ net_income REAL,+ total_assets REAL,+ total_liabilities REAL,+ shareholders_equity REAL,+ cash_and_equivalents REAL,+ total_debt REAL,+ market_cap REAL,+ shares_outstanding REAL,+ book_value_per_share REAL,+ eps REAL,+ operating_cash_flow REAL,+ free_cash_flow REAL,+ capex REAL,+ revenue_growth REAL,+ ebitda_margin REAL,+ net_margin REAL,+ roe REAL,+ roa REAL,+ debt_to_equity REAL,+ current_ratio REAL,+ quick_ratio REAL,+ data_date DATE,+ FOREIGN KEY (deal_id) REFERENCES ma_deals(deal_id)+ )""")++ cursor.execute("""+ CREATE TABLE IF NOT EXISTS deal_multiples (+ multiple_id INTEGER PRIMARY KEY AUTOINCREMENT,+ deal_id TEXT NOT NULL,+ calculation_date DATE NOT NULL,+ ev_revenue REAL,+ ev_ebitda REAL,+ ev_ebit REAL,+ price_earnings REAL,+ price_book REAL,+ price_sales REAL,+ ev_fcf REAL,+ peg_ratio REAL,+ acquirer_ev_revenue REAL,+ acquirer_ev_ebitda REAL,+ acquirer_pe REAL,+ target_ev_revenue REAL,+ target_ev_ebitda REAL,+ target_pe REAL,+ implied_equity_value REAL,+ implied_enterprise_value REAL,+ multiple_type TEXT,+ ltm_or_ntm TEXT,+ FOREIGN KEY (deal_id) REFERENCES ma_deals(deal_id)+ )""")++ cursor.execute("""+ CREATE TABLE IF NOT EXISTS deal_advisors (+ advisor_id INTEGER PRIMARY KEY AUTOINCREMENT,+ deal_id TEXT NOT NULL,+ party TEXT NOT NULL,+ advisor_type TEXT NOT NULL,+ advisor_name TEXT NOT NULL,+ advisor_role TEXT,+ fee_disclosed REAL,+ FOREIGN KEY (deal_id) REFERENCES ma_deals(deal_id)+ )""")++ cursor.execute("""+ CREATE TABLE IF NOT EXISTS deal_timeline (+ timeline_id INTEGER PRIMARY KEY AUTOINCREMENT,+ deal_id TEXT NOT NULL,+ event_date DATE NOT NULL,+ event_type TEXT NOT NULL,+ event_description TEXT,+ milestone_status TEXT,+ FOREIGN KEY (deal_id) REFERENCES ma_deals(deal_id)+ )""")++ cursor.execute("""+ CREATE TABLE IF NOT EXISTS deal_synergies (+ synergy_id INTEGER PRIMARY KEY AUTOINCREMENT,+ deal_id TEXT NOT NULL,+ synergy_category TEXT NOT NULL,+ synergy_type TEXT NOT NULL,+ annual_value REAL,+ one_time_value REAL,+ realization_year INTEGER,+ realization_percentage REAL,+ description TEXT,+ confidence_level TEXT,+ FOREIGN KEY (deal_id) REFERENCES ma_deals(deal_id)+ )""")++ cursor.execute("""+ CREATE TABLE IF NOT EXISTS comparable_companies (+ comp_id INTEGER PRIMARY KEY AUTOINCREMENT,+ company_name TEXT NOT NULL,+ ticker TEXT,+ cik TEXT,+ industry TEXT,+ sector TEXT,+ market_cap REAL,+ enterprise_value REAL,+ revenue REAL,+ ebitda REAL,+ net_income REAL,+ ev_revenue REAL,+ ev_ebitda REAL,+ pe_ratio REAL,+ as_of_date DATE,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+ )""")++ cursor.execute("""+ CREATE TABLE IF NOT EXISTS industry_averages (+ avg_id INTEGER PRIMARY KEY AUTOINCREMENT,+ industry TEXT NOT NULL,+ sector TEXT,+ calculation_period TEXT,+ period_start DATE,+ period_end DATE,+ avg_ev_revenue REAL,+ median_ev_revenue REAL,+ avg_ev_ebitda REAL,+ median_ev_ebitda REAL,+ avg_pe REAL,+ median_pe REAL,+ avg_premium_1day REAL,+ median_premium_1day REAL,+ avg_premium_4week REAL,+ median_premium_4week REAL,+ deal_count INTEGER,+ total_deal_value REAL,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+ )""")++ cursor.execute("""+ CREATE TABLE IF NOT EXISTS sec_filings (+ filing_id INTEGER PRIMARY KEY AUTOINCREMENT,+ deal_id TEXT,+ accession_number TEXT UNIQUE NOT NULL,+ filing_type TEXT NOT NULL,+ filing_date DATE NOT NULL,+ company_name TEXT,+ cik TEXT,+ items TEXT,+ filing_url TEXT,+ html_url TEXT,+ parsed_flag INTEGER DEFAULT 0,+ contains_ma_flag INTEGER DEFAULT 0,+ confidence_score REAL,+ raw_text TEXT,+ extracted_data TEXT,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY (deal_id) REFERENCES ma_deals(deal_id)+ )""")++ cursor.execute("CREATE INDEX IF NOT EXISTS idx_deals_announcement ON ma_deals(announcement_date)")+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_deals_status ON ma_deals(deal_status)")+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_deals_industry ON ma_deals(industry)")+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_deals_acquirer ON ma_deals(acquirer_ticker)")+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_deals_target ON ma_deals(target_ticker)")+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_deals_value ON ma_deals(deal_value)")+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_financials_deal ON deal_financials(deal_id)")+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_multiples_deal ON deal_multiples(deal_id)")+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_timeline_deal ON deal_timeline(deal_id)")+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_filings_accession ON sec_filings(accession_number)")+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_filings_type ON sec_filings(filing_type)")+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_filings_date ON sec_filings(filing_date)")++ conn.commit()++ def insert_deal(self, deal_data: Dict[str, Any]) -> str:+ conn = self._get_connection()+ cursor = conn.cursor()++ deal_data['updated_at'] = datetime.now().isoformat()++ columns = ', '.join(deal_data.keys())+ placeholders = ', '.join(['?' for _ in deal_data])++ cursor.execute(f"""+ INSERT OR REPLACE INTO ma_deals ({columns})+ VALUES ({placeholders})+ """, list(deal_data.values()))++ conn.commit()+ return deal_data.get('deal_id')++ def insert_financials(self, financial_data: Dict[str, Any]) -> int:+ conn = self._get_connection()+ cursor = conn.cursor()++ columns = ', '.join(financial_data.keys())+ placeholders = ', '.join(['?' for _ in financial_data])++ cursor.execute(f"""+ INSERT INTO deal_financials ({columns})+ VALUES ({placeholders})+ """, list(financial_data.values()))++ conn.commit()+ return cursor.lastrowid++ def insert_multiples(self, multiples_data: Dict[str, Any]) -> int:+ conn = self._get_connection()+ cursor = conn.cursor()++ columns = ', '.join(multiples_data.keys())+ placeholders = ', '.join(['?' for _ in multiples_data])++ cursor.execute(f"""+ INSERT INTO deal_multiples ({columns})+ VALUES ({placeholders})+ """, list(multiples_data.values()))++ conn.commit()+ return cursor.lastrowid++ def insert_sec_filing(self, filing_data: Dict[str, Any]) -> int:+ conn = self._get_connection()+ cursor = conn.cursor()++ columns = ', '.join(filing_data.keys())+ placeholders = ', '.join(['?' for _ in filing_data])++ cursor.execute(f"""+ INSERT OR IGNORE INTO sec_filings ({columns})+ VALUES ({placeholders})+ """, list(filing_data.values()))++ conn.commit()+ return cursor.lastrowid++ def search_deals(self, filters: Dict[str, Any]) -> List[Dict[str, Any]]:+ conn = self._get_connection()+ cursor = conn.cursor()++ where_clauses = []+ params = []++ if 'industry' in filters:+ where_clauses.append("industry = ?")+ params.append(filters['industry'])++ if 'min_value' in filters:+ where_clauses.append("deal_value >= ?")+ params.append(filters['min_value'])++ if 'max_value' in filters:+ where_clauses.append("deal_value <= ?")+ params.append(filters['max_value'])++ if 'start_date' in filters:+ where_clauses.append("announcement_date >= ?")+ params.append(filters['start_date'])++ if 'end_date' in filters:+ where_clauses.append("announcement_date <= ?")+ params.append(filters['end_date'])++ if 'deal_status' in filters:+ where_clauses.append("deal_status = ?")+ params.append(filters['deal_status'])++ if 'acquirer_ticker' in filters:+ where_clauses.append("acquirer_ticker = ?")+ params.append(filters['acquirer_ticker'])++ if 'target_ticker' in filters:+ where_clauses.append("target_ticker = ?")+ params.append(filters['target_ticker'])++ where_sql = " AND ".join(where_clauses) if where_clauses else "1=1"++ query = f"""+ SELECT * FROM ma_deals+ WHERE {where_sql}+ ORDER BY announcement_date DESC+ """++ cursor.execute(query, params)+ return [dict(row) for row in cursor.fetchall()]++ def get_deal_by_id(self, deal_id: str) -> Optional[Dict[str, Any]]:+ conn = self._get_connection()+ cursor = conn.cursor()++ cursor.execute("SELECT * FROM ma_deals WHERE deal_id = ?", (deal_id,))+ row = cursor.fetchone()+ return dict(row) if row else None++ def get_deal_financials(self, deal_id: str) -> List[Dict[str, Any]]:+ conn = self._get_connection()+ cursor = conn.cursor()++ cursor.execute("""+ SELECT * FROM deal_financials+ WHERE deal_id = ?+ ORDER BY fiscal_year DESC, fiscal_quarter DESC+ """, (deal_id,))++ return [dict(row) for row in cursor.fetchall()]++ def get_deal_multiples(self, deal_id: str) -> List[Dict[str, Any]]:+ conn = self._get_connection()+ cursor = conn.cursor()++ cursor.execute("""+ SELECT * FROM deal_multiples+ WHERE deal_id = ?+ ORDER BY calculation_date DESC+ """, (deal_id,))++ return [dict(row) for row in cursor.fetchall()]++ def get_industry_stats(self, industry: str, start_date: str, end_date: str) -> Dict[str, Any]:+ conn = self._get_connection()+ cursor = conn.cursor()++ cursor.execute("""+ SELECT+ COUNT(*) as deal_count,+ SUM(deal_value) as total_value,+ AVG(deal_value) as avg_value,+ AVG(premium_1day) as avg_premium_1day,+ AVG(premium_4week) as avg_premium_4week+ FROM ma_deals+ WHERE industry = ?+ AND announcement_date BETWEEN ? AND ?+ AND deal_value IS NOT NULL+ """, (industry, start_date, end_date))++ row = cursor.fetchone()+ return dict(row) if row else {}++ def get_comparable_transactions(self, industry: str, min_value: float, max_value: float,+ start_date: str, end_date: str, limit: int = 20) -> List[Dict[str, Any]]:+ conn = self._get_connection()+ cursor = conn.cursor()++ cursor.execute("""+ SELECT d.*,+ m.ev_revenue, m.ev_ebitda, m.price_earnings+ FROM ma_deals d+ LEFT JOIN deal_multiples m ON d.deal_id = m.multiple_id+ WHERE d.industry = ?+ AND d.deal_value BETWEEN ? AND ?+ AND d.announcement_date BETWEEN ? AND ?+ AND d.deal_status = 'Completed'+ ORDER BY d.announcement_date DESC+ LIMIT ?+ """, (industry, min_value, max_value, start_date, end_date, limit))++ return [dict(row) for row in cursor.fetchall()]++ def close(self):+ if self.conn:+ self.conn.close()+ self.conn = Nonediff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_parser.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_parser.pynew file mode 100644index 000000000..dd623de36--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_parser.py@@ -0,0 +1,417 @@+"""M&A Deal Parser - Extract structured data from SEC filings"""+import sys+from pathlib import Path+from typing import Dict, Any, Optional, List, Tuple+import re+from datetime import datetime+import json++scripts_path = Path(__file__).parent.parent.parent.parent+sys.path.append(str(scripts_path))++try:+ from edgar_tools import Company, Filing+except ImportError:+ from edgartools import Company, Filing++from ..config import DEAL_TYPES, PAYMENT_METHODS, INDUSTRIES+from .database_schema import MADatabase++class MADealParser:+ def __init__(self, db: Optional[MADatabase] = None):+ self.db = db or MADatabase()++ self.value_patterns = [+ r'\$\s*(\d+(?:\.\d+)?)\s*(?:billion|bn)',+ r'\$\s*(\d+(?:\.\d+)?)\s*(?:million|mn|mm)',+ r'consideration\s+of\s+\$\s*([\d,]+(?:\.\d+)?)',+ r'purchase\s+price\s+of\s+\$\s*([\d,]+(?:\.\d+)?)',+ r'aggregate\s+(?:purchase\s+)?price\s+of\s+\$\s*([\d,]+(?:\.\d+)?)'+ ]++ self.date_patterns = [+ r'(?:dated|entered\s+into|effective)\s+(?:as\s+of\s+)?(\w+\s+\d{1,2},\s*\d{4})',+ r'(\d{1,2}/\d{1,2}/\d{4})',+ r'(\w+\s+\d{4})'+ ]++ self.payment_indicators = {+ 'cash': ['cash', 'cash consideration', 'cash payment', 'all cash'],+ 'stock': ['stock', 'shares', 'common stock', 'exchange ratio', 'stock consideration'],+ 'mixed': ['cash and stock', 'combination of cash and', 'mixed consideration']+ }++ def parse_filing(self, accession_number: str) -> Optional[Dict[str, Any]]:+ """Parse complete M&A deal from SEC filing"""+ try:+ conn = self.db._get_connection()+ cursor = conn.cursor()++ cursor.execute("""+ SELECT * FROM sec_filings+ WHERE accession_number = ?+ """, (accession_number,))++ filing_record = cursor.fetchone()+ if not filing_record:+ return None++ filing_record = dict(filing_record)++ text = self._get_filing_text(filing_record)+ if not text:+ return None++ deal_data = self._extract_deal_structure(text, filing_record)++ if deal_data:+ deal_id = self._generate_deal_id(deal_data)+ deal_data['deal_id'] = deal_id+ deal_data['data_source'] = 'SEC EDGAR'+ deal_data['filing_url'] = filing_record['filing_url']++ self.db.insert_deal(deal_data)++ cursor.execute("""+ UPDATE sec_filings+ SET parsed_flag = 1, deal_id = ?+ WHERE accession_number = ?+ """, (deal_id, accession_number))+ conn.commit()++ return deal_data++ except Exception as e:+ print(f"Error parsing {accession_number}: {e}")++ return None++ def _get_filing_text(self, filing_record: Dict[str, Any]) -> str:+ """Get filing text from record or fetch from SEC"""+ if filing_record.get('raw_text'):+ return filing_record['raw_text']++ try:+ cik = filing_record['cik']+ company = Company(cik)+ filings = company.get_filings(form=filing_record['filing_type'])++ for filing in filings:+ if filing.accession_number == filing_record['accession_number']:+ if hasattr(filing, 'text'):+ return filing.text()[:100000]+ elif hasattr(filing, 'html'):+ html = filing.html()+ return re.sub('<[^<]+?>', ' ', html)[:100000]+ except:+ pass++ return ""++ def _extract_deal_structure(self, text: str, filing_record: Dict[str, Any]) -> Dict[str, Any]:+ """Extract structured deal data from text"""+ deal_data = {}++ acquirer, target = self._extract_parties(text, filing_record)+ deal_data['acquirer_name'] = acquirer+ deal_data['target_name'] = target++ deal_value = self._extract_deal_value(text)+ if deal_value:+ deal_data['deal_value'] = deal_value+ deal_data['deal_value_currency'] = 'USD'++ announcement_date = self._extract_announcement_date(text, filing_record)+ if announcement_date:+ deal_data['announcement_date'] = announcement_date++ payment_method = self._extract_payment_method(text)+ deal_data['payment_method'] = payment_method++ deal_type = self._infer_deal_type(text)+ deal_data['deal_type'] = deal_type++ deal_data['deal_status'] = self._infer_status(text, filing_record)++ premiums = self._extract_premiums(text)+ deal_data.update(premiums)++ synergies = self._extract_synergies(text)+ if synergies:+ deal_data['synergies_disclosed'] = synergies++ rationale = self._extract_rationale(text)+ if rationale:+ deal_data['deal_rationale'] = rationale++ industry = self._infer_industry(text, filing_record)+ deal_data['industry'] = industry++ advisors = self._extract_advisors(text)++ if not deal_data.get('acquirer_name') or not deal_data.get('target_name'):+ return None++ return deal_data++ def _extract_parties(self, text: str, filing_record: Dict[str, Any]) -> Tuple[str, str]:+ """Extract acquirer and target names"""+ acquirer = filing_record['company_name']+ target = ""++ patterns = [+ r'acquire[ds]?\s+([A-Z][A-Za-z\s&]+(?:Inc\.|Corp\.|LLC|Ltd\.|Company|Corporation))',+ r'merger\s+(?:of|with)\s+([A-Z][A-Za-z\s&]+(?:Inc\.|Corp\.|LLC|Ltd\.))',+ r'purchase\s+(?:of|from)\s+([A-Z][A-Za-z\s&]+(?:Inc\.|Corp\.|LLC))',+ ]++ for pattern in patterns:+ match = re.search(pattern, text[:5000])+ if match:+ target = match.group(1).strip()+ break++ if not target:+ target = "Unknown Target"++ return acquirer, target++ def _extract_deal_value(self, text: str) -> Optional[float]:+ """Extract deal value from text"""+ for pattern in self.value_patterns:+ match = re.search(pattern, text, re.IGNORECASE)+ if match:+ value_str = match.group(1).replace(',', '')+ value = float(value_str)++ if 'billion' in match.group(0).lower() or 'bn' in match.group(0).lower():+ return value * 1_000_000_000+ elif 'million' in match.group(0).lower():+ return value * 1_000_000+ else:+ if value > 1_000_000:+ return value+ elif value > 1000:+ return value * 1_000_000+ else:+ return value * 1_000_000_000++ return None++ def _extract_announcement_date(self, text: str, filing_record: Dict[str, Any]) -> str:+ """Extract announcement date"""+ for pattern in self.date_patterns:+ match = re.search(pattern, text[:3000])+ if match:+ date_str = match.group(1)+ try:+ if '/' in date_str:+ date_obj = datetime.strptime(date_str, '%m/%d/%Y')+ else:+ date_obj = datetime.strptime(date_str, '%B %d, %Y')+ return date_obj.strftime('%Y-%m-%d')+ except:+ pass++ return filing_record['filing_date']++ def _extract_payment_method(self, text: str) -> str:+ """Extract payment method"""+ text_lower = text.lower()++ scores = {method: 0 for method in ['cash', 'stock', 'mixed']}++ for method, indicators in self.payment_indicators.items():+ for indicator in indicators:+ scores[method] += text_lower.count(indicator)++ if scores['mixed'] > 0 or (scores['cash'] > 0 and scores['stock'] > 0):+ return 'Mixed'+ elif scores['cash'] > scores['stock']:+ return 'Cash'+ elif scores['stock'] > 0:+ return 'Stock'++ return 'Cash'++ def _infer_deal_type(self, text: str) -> str:+ """Infer deal type from text"""+ text_lower = text.lower()++ if 'merger of equals' in text_lower or 'merger agreement' in text_lower:+ return 'Merger'+ elif 'tender offer' in text_lower:+ return 'Takeover'+ elif 'asset purchase' in text_lower or 'sale of assets' in text_lower:+ return 'Asset Purchase'+ elif 'joint venture' in text_lower:+ return 'Joint Venture'+ elif 'acquisition' in text_lower or 'acquire' in text_lower:+ return 'Acquisition'++ return 'Acquisition'++ def _infer_status(self, text: str, filing_record: Dict[str, Any]) -> str:+ """Infer deal status"""+ text_lower = text.lower()++ if filing_record['filing_type'] in ['DEFM14A', 'PREM14A']:+ return 'Pending'++ if 'closed' in text_lower or 'completed' in text_lower or 'consummated' in text_lower:+ return 'Completed'+ elif 'terminated' in text_lower or 'abandoned' in text_lower:+ return 'Terminated'+ elif 'pending' in text_lower or 'subject to' in text_lower:+ return 'Pending'++ return 'Announced'++ def _extract_premiums(self, text: str) -> Dict[str, float]:+ """Extract acquisition premiums"""+ premiums = {}++ patterns = {+ 'premium_1day': r'(\d+(?:\.\d+)?)\s*%\s*premium.*(?:prior|previous)\s+day',+ 'premium_1week': r'(\d+(?:\.\d+)?)\s*%\s*premium.*(?:prior|previous)\s+week',+ 'premium_4week': r'(\d+(?:\.\d+)?)\s*%\s*premium.*(?:prior|previous)\s+(?:four|4)\s+week'+ }++ for key, pattern in patterns.items():+ match = re.search(pattern, text, re.IGNORECASE)+ if match:+ premiums[key] = float(match.group(1))++ return premiums++ def _extract_synergies(self, text: str) -> Optional[float]:+ """Extract disclosed synergies"""+ patterns = [+ r'synergies?\s+of\s+\$\s*(\d+(?:\.\d+)?)\s*(?:billion|million)',+ r'cost\s+savings?\s+of\s+\$\s*(\d+(?:\.\d+)?)\s*(?:billion|million)',+ r'annual\s+(?:run-rate\s+)?synergies?\s+of\s+\$\s*(\d+(?:\.\d+)?)\s*(?:billion|million)'+ ]++ for pattern in patterns:+ match = re.search(pattern, text, re.IGNORECASE)+ if match:+ value = float(match.group(1))+ if 'billion' in match.group(0).lower():+ return value * 1_000_000_000+ else:+ return value * 1_000_000++ return None++ def _extract_rationale(self, text: str) -> str:+ """Extract deal rationale"""+ rationale_keywords = [+ 'strategic rationale', 'benefits of the transaction', 'reasons for the merger',+ 'transaction rationale', 'compelling strategic fit'+ ]++ for keyword in rationale_keywords:+ idx = text.lower().find(keyword)+ if idx != -1:+ snippet = text[idx:idx+500]+ return snippet.replace('\n', ' ')[:300]++ return ""++ def _infer_industry(self, text: str, filing_record: Dict[str, Any]) -> str:+ """Infer industry from text"""+ text_lower = text.lower()++ industry_keywords = {+ 'Technology': ['software', 'technology', 'cloud', 'saas', 'digital', 'platform'],+ 'Healthcare': ['healthcare', 'pharmaceutical', 'biotech', 'medical', 'health'],+ 'Financial Services': ['financial', 'banking', 'insurance', 'fintech', 'asset management'],+ 'Industrials': ['manufacturing', 'industrial', 'aerospace', 'defense'],+ 'Consumer Discretionary': ['retail', 'consumer', 'e-commerce', 'restaurant'],+ 'Energy': ['energy', 'oil', 'gas', 'renewable', 'power'],+ 'Real Estate': ['real estate', 'property', 'reit']+ }++ scores = {industry: 0 for industry in industry_keywords.keys()}++ for industry, keywords in industry_keywords.items():+ for keyword in keywords:+ scores[industry] += text_lower[:5000].count(keyword)++ if max(scores.values()) > 0:+ return max(scores, key=scores.get)++ return 'Diversified'++ def _extract_advisors(self, text: str) -> List[Dict[str, Any]]:+ """Extract financial and legal advisors"""+ advisors = []++ advisor_patterns = [+ r'([A-Z][A-Za-z\s&]+(?:LLC|LLP|Inc\.))\s+(?:is\s+)?(?:acting\s+as|served\s+as)\s+financial\s+advisor',+ r'financial\s+advisor[s]?[:\s]+([A-Z][A-Za-z\s&,]+(?:LLC|LLP|Inc\.))',+ r'([A-Z][A-Za-z\s&]+(?:LLC|LLP))\s+(?:is\s+)?(?:acting\s+as|served\s+as)\s+legal\s+counsel'+ ]++ for pattern in advisor_patterns:+ matches = re.findall(pattern, text[:10000])+ for match in matches:+ advisors.append({+ 'advisor_name': match.strip(),+ 'advisor_type': 'Financial' if 'financial' in pattern else 'Legal'+ })++ return advisors[:10]++ def _generate_deal_id(self, deal_data: Dict[str, Any]) -> str:+ """Generate unique deal ID"""+ acquirer = deal_data.get('acquirer_name', 'UNK')[:10].upper().replace(' ', '')+ target = deal_data.get('target_name', 'UNK')[:10].upper().replace(' ', '')+ date = deal_data.get('announcement_date', '').replace('-', '')[:8]++ return f"{acquirer}_{target}_{date}"++ def parse_batch(self, accession_numbers: List[str], max_workers: int = 5) -> Dict[str, Any]:+ """Parse multiple filings in batch"""+ from concurrent.futures import ThreadPoolExecutor, as_completed++ results = {+ 'parsed': [],+ 'failed': [],+ 'total': len(accession_numbers)+ }++ with ThreadPoolExecutor(max_workers=max_workers) as executor:+ futures = {executor.submit(self.parse_filing, acc): acc for acc in accession_numbers}++ for future in as_completed(futures):+ acc = futures[future]+ try:+ deal_data = future.result()+ if deal_data:+ results['parsed'].append(deal_data)+ else:+ results['failed'].append(acc)+ except Exception as e:+ results['failed'].append(acc)+ print(f"Error parsing {acc}: {e}")++ return results++if __name__ == '__main__':+ parser = MADealParser()++ db = MADatabase()+ high_conf_filings = db._get_connection().execute("""+ SELECT accession_number FROM sec_filings+ WHERE confidence_score > 0.75 AND parsed_flag = 0+ LIMIT 5+ """).fetchall()++ for filing in high_conf_filings:+ acc = filing[0]+ print(f"\nParsing {acc}...")+ deal = parser.parse_filing(acc)+ if deal:+ print(f" Deal: {deal['acquirer_name']} acquiring {deal['target_name']}")+ print(f" Value: ${deal.get('deal_value', 0):,.0f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_scanner.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_scanner.pynew file mode 100644index 000000000..a715483f3--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_scanner.py@@ -0,0 +1,299 @@+"""SEC Filing Scanner for M&A Deal Detection"""+import sys+from pathlib import Path+from typing import List, Dict, Any, Optional, Tuple+from datetime import datetime, timedelta+import re+from concurrent.futures import ThreadPoolExecutor, as_completed++scripts_path = Path(__file__).parent.parent.parent.parent+sys.path.append(str(scripts_path))++try:+ from edgar_tools import Company, get_filings, Filing+except ImportError:+ from edgartools import Company, get_filings, Filing++from ..config import MA_FILING_FORMS, MATERIAL_EVENT_ITEMS+from .database_schema import MADatabase++class MADealScanner:+ def __init__(self, db: Optional[MADatabase] = None):+ self.db = db or MADatabase()+ self.ma_keywords = [+ 'merger', 'acquisition', 'acquire', 'purchase', 'takeover',+ 'combination', 'consolidation', 'tender offer', 'definitive agreement',+ 'merger agreement', 'stock purchase', 'asset purchase', 'amalgamation'+ ]+ self.ma_patterns = [+ r'(?:definitive|merger)\s+agreement',+ r'acquire[ds]?\s+(?:all|substantially all)',+ r'tender\s+offer',+ r'cash\s+and\s+stock\s+(?:transaction|deal)',+ r'purchase\s+price\s+of\s+\$[\d,\.]+\s*(?:million|billion)',+ r'(?:merger|acquisition)\s+consideration'+ ]++ def scan_recent_filings(self, days_back: int = 30, max_workers: int = 5) -> List[Dict[str, Any]]:+ """Scan recent SEC filings for M&A activity"""+ end_date = datetime.now()+ start_date = end_date - timedelta(days=days_back)++ potential_deals = []++ with ThreadPoolExecutor(max_workers=max_workers) as executor:+ futures = []+ for form_type in MA_FILING_FORMS:+ future = executor.submit(self._scan_filing_type, form_type, start_date, end_date)+ futures.append(future)++ for future in as_completed(futures):+ try:+ results = future.result()+ potential_deals.extend(results)+ except Exception as e:+ print(f"Error scanning filings: {e}")++ return potential_deals++ def _scan_filing_type(self, form_type: str, start_date: datetime, end_date: datetime) -> List[Dict[str, Any]]:+ """Scan specific filing type for M&A deals"""+ potential_deals = []++ try:+ filings = get_filings(+ form=form_type,+ start_date=start_date.strftime('%Y-%m-%d'),+ end_date=end_date.strftime('%Y-%m-%d')+ )++ for filing in filings[:100]:+ deal_info = self._analyze_filing(filing)+ if deal_info and deal_info['confidence_score'] > 0.5:+ potential_deals.append(deal_info)+ self._store_filing(filing, deal_info)++ except Exception as e:+ print(f"Error scanning {form_type}: {e}")++ return potential_deals++ def _analyze_filing(self, filing) -> Optional[Dict[str, Any]]:+ """Analyze if filing contains M&A activity"""+ try:+ text = self._extract_filing_text(filing)+ if not text:+ return None++ text_lower = text.lower()+ confidence_score = 0.0+ deal_indicators = []++ for keyword in self.ma_keywords:+ if keyword in text_lower:+ confidence_score += 0.1+ deal_indicators.append(keyword)++ for pattern in self.ma_patterns:+ if re.search(pattern, text_lower):+ confidence_score += 0.2+ deal_indicators.append(pattern)++ if filing.form in ['S-4', 'DEFM14A', 'PREM14A']:+ confidence_score += 0.4++ if filing.form == '8-K':+ items = self._extract_8k_items(text)+ if any(item in ['1.01', '2.01'] for item in items):+ confidence_score += 0.3++ confidence_score = min(confidence_score, 1.0)++ if confidence_score > 0.5:+ return {+ 'accession_number': filing.accession_number,+ 'filing_type': filing.form,+ 'filing_date': filing.filing_date,+ 'company_name': filing.company,+ 'cik': filing.cik,+ 'filing_url': f"https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK={filing.cik}&type={filing.form}&dateb=&owner=exclude&count=100",+ 'confidence_score': confidence_score,+ 'contains_ma_flag': 1,+ 'deal_indicators': ','.join(deal_indicators[:5])+ }++ except Exception as e:+ print(f"Error analyzing filing {filing.accession_number}: {e}")++ return None++ def _extract_filing_text(self, filing) -> str:+ """Extract text from SEC filing"""+ try:+ if hasattr(filing, 'text'):+ return filing.text()[:50000]+ elif hasattr(filing, 'html'):+ html = filing.html()+ text = re.sub('<[^<]+?>', ' ', html)+ return text[:50000]+ return ""+ except Exception as e:+ print(f"Error extracting text: {e}")+ return ""++ def _extract_8k_items(self, text: str) -> List[str]:+ """Extract Item numbers from 8-K filing"""+ items = []+ pattern = r'Item\s+(\d+\.\d+)'+ matches = re.findall(pattern, text)+ return list(set(matches))++ def scan_company_ma_history(self, ticker: str, years_back: int = 5) -> List[Dict[str, Any]]:+ """Scan specific company's M&A history"""+ try:+ company = Company(ticker)+ end_date = datetime.now()+ start_date = end_date - timedelta(days=years_back*365)++ all_deals = []++ for form_type in MA_FILING_FORMS:+ try:+ filings = company.get_filings(+ form=form_type+ ).filter(+ date=f"{start_date.strftime('%Y-%m-%d')}:{end_date.strftime('%Y-%m-%d')}"+ )++ for filing in filings:+ deal_info = self._analyze_filing(filing)+ if deal_info and deal_info['confidence_score'] > 0.5:+ all_deals.append(deal_info)+ self._store_filing(filing, deal_info)++ except Exception as e:+ print(f"Error getting {form_type} for {ticker}: {e}")++ return all_deals++ except Exception as e:+ print(f"Error scanning company {ticker}: {e}")+ return []++ def scan_industry_ma_activity(self, industry_ciks: List[str], days_back: int = 90) -> List[Dict[str, Any]]:+ """Scan M&A activity for specific industry"""+ all_deals = []++ with ThreadPoolExecutor(max_workers=10) as executor:+ futures = {executor.submit(self._scan_cik, cik, days_back): cik for cik in industry_ciks}++ for future in as_completed(futures):+ try:+ deals = future.result()+ all_deals.extend(deals)+ except Exception as e:+ print(f"Error scanning CIK: {e}")++ return all_deals++ def _scan_cik(self, cik: str, days_back: int) -> List[Dict[str, Any]]:+ """Scan specific CIK for M&A filings"""+ try:+ company = Company(cik)+ end_date = datetime.now()+ start_date = end_date - timedelta(days=days_back)++ deals = []+ for form_type in ['8-K', 'S-4', 'DEFM14A']:+ try:+ filings = company.get_filings(form=form_type)+ for filing in filings[:10]:+ if filing.filing_date >= start_date.date():+ deal_info = self._analyze_filing(filing)+ if deal_info and deal_info['confidence_score'] > 0.6:+ deals.append(deal_info)+ except:+ continue++ return deals++ except Exception as e:+ return []++ def _store_filing(self, filing, deal_info: Dict[str, Any]):+ """Store filing information in database"""+ try:+ filing_data = {+ 'accession_number': deal_info['accession_number'],+ 'filing_type': deal_info['filing_type'],+ 'filing_date': deal_info['filing_date'],+ 'company_name': deal_info['company_name'],+ 'cik': deal_info['cik'],+ 'filing_url': deal_info['filing_url'],+ 'confidence_score': deal_info['confidence_score'],+ 'contains_ma_flag': deal_info['contains_ma_flag'],+ 'parsed_flag': 0+ }++ self.db.insert_sec_filing(filing_data)++ except Exception as e:+ print(f"Error storing filing: {e}")++ def get_high_confidence_deals(self, min_confidence: float = 0.75) -> List[Dict[str, Any]]:+ """Get high confidence M&A deals from database"""+ conn = self.db._get_connection()+ cursor = conn.cursor()++ cursor.execute("""+ SELECT * FROM sec_filings+ WHERE contains_ma_flag = 1+ AND confidence_score >= ?+ AND parsed_flag = 0+ ORDER BY filing_date DESC+ """, (min_confidence,))++ return [dict(row) for row in cursor.fetchall()]++ def batch_scan_sp500(self, days_back: int = 30) -> Dict[str, Any]:+ """Scan all S&P 500 companies for M&A activity"""+ sp500_tickers = self._get_sp500_tickers()++ total_deals = []+ successful_scans = 0+ failed_scans = 0++ with ThreadPoolExecutor(max_workers=10) as executor:+ futures = {executor.submit(self.scan_company_ma_history, ticker, days_back//365): ticker+ for ticker in sp500_tickers[:50]}++ for future in as_completed(futures):+ try:+ deals = future.result()+ total_deals.extend(deals)+ successful_scans += 1+ except:+ failed_scans += 1++ return {+ 'total_deals_found': len(total_deals),+ 'companies_scanned': successful_scans,+ 'failed_scans': failed_scans,+ 'deals': total_deals+ }++ def _get_sp500_tickers(self) -> List[str]:+ """Get S&P 500 tickers"""+ return [+ 'AAPL', 'MSFT', 'GOOGL', 'AMZN', 'NVDA', 'META', 'TSLA', 'BRK.B', 'UNH', 'JNJ',+ 'XOM', 'V', 'PG', 'JPM', 'MA', 'HD', 'CVX', 'MRK', 'ABBV', 'PEP', 'COST', 'AVGO',+ 'KO', 'LLY', 'WMT', 'MCD', 'TMO', 'ABT', 'ACN', 'CSCO', 'DHR', 'CRM', 'VZ', 'NEE'+ ]++if __name__ == '__main__':+ scanner = MADealScanner()+ print("Scanning recent M&A filings (last 7 days)...")+ deals = scanner.scan_recent_filings(days_back=7)+ print(f"Found {len(deals)} potential M&A deals")+ for deal in deals[:5]:+ print(f" - {deal['company_name']}: {deal['filing_type']} (Confidence: {deal['confidence_score']:.2f})")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_tracker.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_tracker.pynew file mode 100644index 000000000..cf8f125d5--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_database/deal_tracker.py@@ -0,0 +1,281 @@+"""M&A Deal Tracker - Main API for deal tracking and analysis"""+import sys+from pathlib import Path+from typing import Dict, Any, List, Optional+from datetime import datetime, timedelta+import json++from .database_schema import MADatabase+from .deal_scanner import MADealScanner+from .deal_parser import MADealParser++class MADealTracker:+ def __init__(self, db_path: Optional[Path] = None):+ self.db = MADatabase(db_path)+ self.scanner = MADealScanner(self.db)+ self.parser = MADealParser(self.db)++ def update_deal_database(self, days_back: int = 7, auto_parse: bool = True) -> Dict[str, Any]:+ """Update database with recent M&A deals"""+ print(f"Scanning SEC filings from last {days_back} days...")+ filings = self.scanner.scan_recent_filings(days_back=days_back)++ results = {+ 'filings_found': len(filings),+ 'deals_parsed': 0,+ 'parsing_failed': 0,+ 'timestamp': datetime.now().isoformat()+ }++ if auto_parse:+ high_confidence = [f for f in filings if f['confidence_score'] > 0.75]+ print(f"Parsing {len(high_confidence)} high-confidence filings...")++ for filing in high_confidence:+ try:+ deal = self.parser.parse_filing(filing['accession_number'])+ if deal:+ results['deals_parsed'] += 1+ except Exception as e:+ results['parsing_failed'] += 1+ print(f"Parse error: {e}")++ return results++ def search_deals(self, **filters) -> List[Dict[str, Any]]:+ """Search M&A deals with filters"""+ return self.db.search_deals(filters)++ def get_deal_details(self, deal_id: str) -> Optional[Dict[str, Any]]:+ """Get complete deal details including financials and multiples"""+ deal = self.db.get_deal_by_id(deal_id)+ if not deal:+ return None++ deal['financials'] = self.db.get_deal_financials(deal_id)+ deal['multiples'] = self.db.get_deal_multiples(deal_id)++ return deal++ def get_comparable_transactions(self, industry: str, target_value: float,+ date_range_years: int = 3, limit: int = 20) -> List[Dict[str, Any]]:+ """Get comparable M&A transactions"""+ end_date = datetime.now()+ start_date = end_date - timedelta(days=date_range_years*365)++ min_value = target_value * 0.5+ max_value = target_value * 2.0++ return self.db.get_comparable_transactions(+ industry=industry,+ min_value=min_value,+ max_value=max_value,+ start_date=start_date.strftime('%Y-%m-%d'),+ end_date=end_date.strftime('%Y-%m-%d'),+ limit=limit+ )++ def get_industry_statistics(self, industry: str, years_back: int = 3) -> Dict[str, Any]:+ """Get M&A statistics for industry"""+ end_date = datetime.now()+ start_date = end_date - timedelta(days=years_back*365)++ stats = self.db.get_industry_stats(+ industry=industry,+ start_date=start_date.strftime('%Y-%m-%d'),+ end_date=end_date.strftime('%Y-%m-%d')+ )++ deals = self.search_deals(+ industry=industry,+ start_date=start_date.strftime('%Y-%m-%d'),+ end_date=end_date.strftime('%Y-%m-%d')+ )++ if deals:+ values = [d['deal_value'] for d in deals if d.get('deal_value')]+ premiums_1day = [d['premium_1day'] for d in deals if d.get('premium_1day')]++ stats['median_deal_value'] = sorted(values)[len(values)//2] if values else 0+ stats['median_premium_1day'] = sorted(premiums_1day)[len(premiums_1day)//2] if premiums_1day else 0++ return stats++ def track_company(self, ticker: str, years_back: int = 5) -> Dict[str, Any]:+ """Track M&A activity for specific company"""+ print(f"Tracking M&A history for {ticker}...")++ filings = self.scanner.scan_company_ma_history(ticker, years_back)++ deals_as_acquirer = self.search_deals(acquirer_ticker=ticker)+ deals_as_target = self.search_deals(target_ticker=ticker)++ return {+ 'ticker': ticker,+ 'filings_found': len(filings),+ 'deals_as_acquirer': deals_as_acquirer,+ 'deals_as_target': deals_as_target,+ 'total_acquisitions': len(deals_as_acquirer),+ 'acquisition_history': deals_as_acquirer+ }++ def calculate_deal_statistics(self, deals: List[Dict[str, Any]]) -> Dict[str, Any]:+ """Calculate statistical metrics for deals"""+ if not deals:+ return {}++ values = [d['deal_value'] for d in deals if d.get('deal_value')]+ premiums_1day = [d['premium_1day'] for d in deals if d.get('premium_1day')]+ premiums_4week = [d['premium_4week'] for d in deals if d.get('premium_4week')]++ return {+ 'deal_count': len(deals),+ 'total_value': sum(values),+ 'avg_value': sum(values) / len(values) if values else 0,+ 'median_value': sorted(values)[len(values)//2] if values else 0,+ 'avg_premium_1day': sum(premiums_1day) / len(premiums_1day) if premiums_1day else 0,+ 'median_premium_1day': sorted(premiums_1day)[len(premiums_1day)//2] if premiums_1day else 0,+ 'avg_premium_4week': sum(premiums_4week) / len(premiums_4week) if premiums_4week else 0,+ 'median_premium_4week': sorted(premiums_4week)[len(premiums_4week)//2] if premiums_4week else 0,+ 'cash_deals': len([d for d in deals if d.get('payment_method') == 'Cash']),+ 'stock_deals': len([d for d in deals if d.get('payment_method') == 'Stock']),+ 'mixed_deals': len([d for d in deals if d.get('payment_method') == 'Mixed'])+ }++ def build_transaction_comp_table(self, industry: str, target_value: float,+ years_back: int = 3) -> Dict[str, Any]:+ """Build transaction comparable table"""+ comps = self.get_comparable_transactions(industry, target_value, years_back)++ if not comps:+ return {'error': 'No comparable transactions found'}++ stats = self.calculate_deal_statistics(comps)++ return {+ 'industry': industry,+ 'target_value': target_value,+ 'comparable_count': len(comps),+ 'comparables': comps,+ 'statistics': stats,+ 'valuation_multiples': {+ 'ev_revenue_median': self._calculate_median([c.get('ev_revenue') for c in comps if c.get('ev_revenue')]),+ 'ev_ebitda_median': self._calculate_median([c.get('ev_ebitda') for c in comps if c.get('ev_ebitda')]),+ 'premium_1day_median': stats.get('median_premium_1day', 0),+ 'premium_4week_median': stats.get('median_premium_4week', 0)+ }+ }++ def _calculate_median(self, values: List[float]) -> float:+ """Calculate median of list"""+ if not values:+ return 0.0+ sorted_vals = sorted(values)+ n = len(sorted_vals)+ if n % 2 == 0:+ return (sorted_vals[n//2-1] + sorted_vals[n//2]) / 2+ return sorted_vals[n//2]++ def export_deals_to_json(self, deals: List[Dict[str, Any]], output_path: str):+ """Export deals to JSON file"""+ with open(output_path, 'w') as f:+ json.dump(deals, f, indent=2, default=str)++ def get_recent_deals_summary(self, days: int = 30, min_value: float = 100_000_000) -> Dict[str, Any]:+ """Get summary of recent significant deals"""+ end_date = datetime.now()+ start_date = end_date - timedelta(days=days)++ deals = self.search_deals(+ start_date=start_date.strftime('%Y-%m-%d'),+ end_date=end_date.strftime('%Y-%m-%d'),+ min_value=min_value+ )++ by_industry = {}+ by_status = {}++ for deal in deals:+ industry = deal.get('industry', 'Unknown')+ status = deal.get('deal_status', 'Unknown')++ by_industry[industry] = by_industry.get(industry, 0) + 1+ by_status[status] = by_status.get(status, 0) + 1++ return {+ 'period_days': days,+ 'total_deals': len(deals),+ 'total_value': sum(d.get('deal_value', 0) for d in deals),+ 'by_industry': by_industry,+ 'by_status': by_status,+ 'top_deals': sorted(deals, key=lambda x: x.get('deal_value', 0), reverse=True)[:10],+ 'statistics': self.calculate_deal_statistics(deals)+ }++ def close(self):+ """Close database connection"""+ self.db.close()++def main():+ """CLI interface"""+ import argparse++ parser = argparse.ArgumentParser(description='M&A Deal Tracker')+ parser.add_argument('--update', action='store_true', help='Update deal database')+ parser.add_argument('--days', type=int, default=7, help='Days to scan back')+ parser.add_argument('--search', type=str, help='Search deals by industry')+ parser.add_argument('--track', type=str, help='Track company by ticker')+ parser.add_argument('--summary', action='store_true', help='Show recent deals summary')+ parser.add_argument('--comps', type=str, help='Build comp table for industry')+ parser.add_argument('--value', type=float, help='Target value for comps')++ args = parser.parse_args()++ tracker = MADealTracker()++ try:+ if args.update:+ result = tracker.update_deal_database(days_back=args.days)+ print(f"\nUpdate complete:")+ print(f" Filings found: {result['filings_found']}")+ print(f" Deals parsed: {result['deals_parsed']}")+ print(f" Failed: {result['parsing_failed']}")++ elif args.search:+ deals = tracker.search_deals(industry=args.search)+ print(f"\nFound {len(deals)} deals in {args.search}")+ for deal in deals[:10]:+ print(f" {deal['announcement_date']}: {deal['acquirer_name']} -> {deal['target_name']}")+ if deal.get('deal_value'):+ print(f" Value: ${deal['deal_value']:,.0f}")++ elif args.track:+ result = tracker.track_company(args.track)+ print(f"\nM&A Activity for {args.track}:")+ print(f" Total acquisitions: {result['total_acquisitions']}")+ print(f" Filings found: {result['filings_found']}")++ elif args.summary:+ summary = tracker.get_recent_deals_summary(days=30)+ print(f"\nRecent M&A Activity (Last 30 days):")+ print(f" Total deals: {summary['total_deals']}")+ print(f" Total value: ${summary['total_value']:,.0f}")+ print(f"\nBy Industry:")+ for industry, count in summary['by_industry'].items():+ print(f" {industry}: {count}")++ elif args.comps and args.value:+ comp_table = tracker.build_transaction_comp_table(args.comps, args.value)+ print(f"\nTransaction Comparables - {args.comps}")+ print(f" Found {comp_table['comparable_count']} comparable deals")+ print(f" Median EV/Revenue: {comp_table['valuation_multiples']['ev_revenue_median']:.2f}x")+ print(f" Median EV/EBITDA: {comp_table['valuation_multiples']['ev_ebitda_median']:.2f}x")++ else:+ parser.print_help()++ finally:+ tracker.close()++if __name__ == '__main__':+ main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/__init__.pynew file mode 100644index 000000000..351af3281--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/__init__.py@@ -0,0 +1,20 @@+"""Deal Structure Analysis Module"""+from .payment_structure import PaymentStructureAnalyzer, PaymentType+from .earnout_calculator import EarnoutCalculator, EarnoutTranche, EarnoutMetric+from .exchange_ratio import ExchangeRatioCalculator+from .collar_mechanisms import CollarMechanism, CollarType+from .cvr_valuation import CVRValuation, CVRTrigger, CVRType++__all__ = [+ 'PaymentStructureAnalyzer',+ 'PaymentType',+ 'EarnoutCalculator',+ 'EarnoutTranche',+ 'EarnoutMetric',+ 'ExchangeRatioCalculator',+ 'CollarMechanism',+ 'CollarType',+ 'CVRValuation',+ 'CVRTrigger',+ 'CVRType'+]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/collar_mechanisms.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/collar_mechanisms.pynew file mode 100644index 000000000..c5a638192--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/collar_mechanisms.py@@ -0,0 +1,368 @@+"""Collar Mechanisms for Stock Deal Protection"""+from typing import Dict, Any, List, Optional+import numpy as np++class CollarType:+ FIXED = "fixed"+ FLOATING = "floating"+ SYMMETRIC = "symmetric"+ ASYMMETRIC = "asymmetric"++class CollarMechanism:+ """Analyze collar structures in stock-for-stock M&A transactions"""++ def __init__(self, announcement_price: float,+ target_shares: float,+ base_exchange_ratio: float):+ self.announcement_price = announcement_price+ self.target_shares = target_shares+ self.base_exchange_ratio = base_exchange_ratio++ def fixed_collar(self, floor_price: float,+ cap_price: float,+ price_scenarios: Optional[List[float]] = None) -> Dict[str, Any]:+ """+ Fixed collar: Exchange ratio adjusts to maintain value within price band++ If acquirer price falls below floor: ratio increases (more shares)+ If acquirer price rises above cap: ratio decreases (fewer shares)+ """++ if price_scenarios is None:+ price_scenarios = np.linspace(+ self.announcement_price * 0.7,+ self.announcement_price * 1.3,+ 20+ ).tolist()++ scenarios = []+ base_value = self.base_exchange_ratio * self.announcement_price++ for price in price_scenarios:+ if price < floor_price:+ effective_ratio = base_value / floor_price+ value_per_share = floor_price+ protection_type = "floor_active"+ elif price > cap_price:+ effective_ratio = base_value / cap_price+ value_per_share = cap_price+ protection_type = "cap_active"+ else:+ effective_ratio = self.base_exchange_ratio+ value_per_share = price+ protection_type = "within_collar"++ actual_value = effective_ratio * price++ total_deal_value = actual_value * self.target_shares+ total_shares_issued = effective_ratio * self.target_shares++ scenarios.append({+ 'acquirer_price': price,+ 'effective_exchange_ratio': effective_ratio,+ 'value_per_target_share': actual_value,+ 'total_deal_value': total_deal_value,+ 'shares_issued': total_shares_issued,+ 'protection_active': protection_type,+ 'price_change_pct': ((price - self.announcement_price) / self.announcement_price) * 100+ })++ return {+ 'collar_type': 'fixed',+ 'announcement_price': self.announcement_price,+ 'base_exchange_ratio': self.base_exchange_ratio,+ 'floor_price': floor_price,+ 'cap_price': cap_price,+ 'floor_pct_below': ((self.announcement_price - floor_price) / self.announcement_price) * 100,+ 'cap_pct_above': ((cap_price - self.announcement_price) / self.announcement_price) * 100,+ 'scenarios': scenarios,+ 'value_range': {+ 'min': min(s['value_per_target_share'] for s in scenarios),+ 'max': max(s['value_per_target_share'] for s in scenarios),+ 'base': self.base_exchange_ratio * self.announcement_price+ }+ }++ def floating_collar(self, min_exchange_ratio: float,+ max_exchange_ratio: float,+ price_scenarios: Optional[List[float]] = None) -> Dict[str, Any]:+ """+ Floating collar: Exchange ratio bounded, value floats with stock price++ Min ratio: Floor on shares received (downside protection for target)+ Max ratio: Cap on shares issued (dilution protection for acquirer)+ """++ if price_scenarios is None:+ price_scenarios = np.linspace(+ self.announcement_price * 0.7,+ self.announcement_price * 1.3,+ 20+ ).tolist()++ scenarios = []++ for price in price_scenarios:+ if self.base_exchange_ratio < min_exchange_ratio:+ effective_ratio = min_exchange_ratio+ protection_type = "floor_active"+ elif self.base_exchange_ratio > max_exchange_ratio:+ effective_ratio = max_exchange_ratio+ protection_type = "cap_active"+ else:+ effective_ratio = self.base_exchange_ratio+ protection_type = "within_collar"++ value_per_share = effective_ratio * price+ total_deal_value = value_per_share * self.target_shares+ total_shares_issued = effective_ratio * self.target_shares++ scenarios.append({+ 'acquirer_price': price,+ 'effective_exchange_ratio': effective_ratio,+ 'value_per_target_share': value_per_share,+ 'total_deal_value': total_deal_value,+ 'shares_issued': total_shares_issued,+ 'protection_active': protection_type+ })++ return {+ 'collar_type': 'floating',+ 'base_exchange_ratio': self.base_exchange_ratio,+ 'min_exchange_ratio': min_exchange_ratio,+ 'max_exchange_ratio': max_exchange_ratio,+ 'scenarios': scenarios,+ 'ratio_range': {+ 'min': min_exchange_ratio,+ 'max': max_exchange_ratio,+ 'base': self.base_exchange_ratio+ }+ }++ def asymmetric_collar(self, floor_price: Optional[float] = None,+ cap_price: Optional[float] = None,+ price_scenarios: Optional[List[float]] = None) -> Dict[str, Any]:+ """+ Asymmetric collar: Only floor or only cap protection++ One-sided protection for target (floor only) or acquirer (cap only)+ """++ if floor_price is None and cap_price is None:+ raise ValueError("Must specify either floor_price or cap_price")++ if price_scenarios is None:+ price_scenarios = np.linspace(+ self.announcement_price * 0.7,+ self.announcement_price * 1.3,+ 20+ ).tolist()++ scenarios = []+ base_value = self.base_exchange_ratio * self.announcement_price++ for price in price_scenarios:+ protection_type = "no_protection"++ if floor_price and price < floor_price:+ effective_ratio = base_value / floor_price+ protection_type = "floor_active"+ elif cap_price and price > cap_price:+ effective_ratio = base_value / cap_price+ protection_type = "cap_active"+ else:+ effective_ratio = self.base_exchange_ratio++ value_per_share = effective_ratio * price+ total_deal_value = value_per_share * self.target_shares++ scenarios.append({+ 'acquirer_price': price,+ 'effective_exchange_ratio': effective_ratio,+ 'value_per_target_share': value_per_share,+ 'total_deal_value': total_deal_value,+ 'protection_active': protection_type+ })++ collar_structure = "floor_only" if floor_price and not cap_price else "cap_only"++ return {+ 'collar_type': 'asymmetric',+ 'collar_structure': collar_structure,+ 'floor_price': floor_price,+ 'cap_price': cap_price,+ 'base_exchange_ratio': self.base_exchange_ratio,+ 'scenarios': scenarios+ }++ def walk_away_collar(self, floor_price: float,+ cap_price: float,+ termination_fee: float,+ price_scenarios: Optional[List[float]] = None) -> Dict[str, Any]:+ """+ Collar with walk-away rights if price exceeds bounds++ Either party can terminate if price outside collar bounds+ """++ if price_scenarios is None:+ price_scenarios = np.linspace(+ self.announcement_price * 0.6,+ self.announcement_price * 1.4,+ 20+ ).tolist()++ scenarios = []++ for price in price_scenarios:+ if price < floor_price or price > cap_price:+ deal_proceeds = False+ value_per_share = 0+ termination_cost = termination_fee+ outcome = "walk_away_triggered"+ else:+ deal_proceeds = True+ value_per_share = self.base_exchange_ratio * price+ termination_cost = 0+ outcome = "deal_proceeds"++ scenarios.append({+ 'acquirer_price': price,+ 'deal_proceeds': deal_proceeds,+ 'value_per_target_share': value_per_share,+ 'termination_fee': termination_cost,+ 'outcome': outcome+ })++ return {+ 'collar_type': 'walk_away',+ 'floor_price': floor_price,+ 'cap_price': cap_price,+ 'termination_fee': termination_fee,+ 'base_exchange_ratio': self.base_exchange_ratio,+ 'scenarios': scenarios,+ 'deal_completion_rate': sum(1 for s in scenarios if s['deal_proceeds']) / len(scenarios) * 100+ }++ def collar_valuation_impact(self, collar_structure: Dict[str, Any],+ volatility: float,+ time_to_close: float) -> Dict[str, Any]:+ """Estimate collar impact on deal valuation using option pricing concepts"""++ base_value = self.base_exchange_ratio * self.announcement_price * self.target_shares++ scenarios = collar_structure.get('scenarios', [])+ if not scenarios:+ return {'error': 'No scenarios in collar structure'}++ price_changes = [s.get('price_change_pct', 0) for s in scenarios if 'price_change_pct' in s]+ values = [s['total_deal_value'] for s in scenarios]++ value_std = np.std(values)+ value_mean = np.mean(values)++ protection_scenarios = [s for s in scenarios if s.get('protection_active') not in ['within_collar', 'no_protection', None]]+ protection_value = value_mean - base_value if protection_scenarios else 0++ return {+ 'base_deal_value': base_value,+ 'expected_value_with_collar': value_mean,+ 'value_standard_deviation': value_std,+ 'collar_protection_value': protection_value,+ 'coefficient_of_variation': (value_std / value_mean * 100) if value_mean > 0 else 0,+ 'scenarios_with_protection': len(protection_scenarios),+ 'total_scenarios': len(scenarios)+ }++ def compare_collar_structures(self, price_scenarios: List[float]) -> Dict[str, Any]:+ """Compare different collar structures"""++ no_collar = {+ 'type': 'no_collar',+ 'scenarios': [+ {+ 'acquirer_price': price,+ 'value_per_target_share': self.base_exchange_ratio * price,+ 'total_deal_value': self.base_exchange_ratio * price * self.target_shares+ }+ for price in price_scenarios+ ]+ }++ fixed = self.fixed_collar(+ floor_price=self.announcement_price * 0.9,+ cap_price=self.announcement_price * 1.1,+ price_scenarios=price_scenarios+ )++ floating = self.floating_collar(+ min_exchange_ratio=self.base_exchange_ratio * 0.9,+ max_exchange_ratio=self.base_exchange_ratio * 1.1,+ price_scenarios=price_scenarios+ )++ floor_only = self.asymmetric_collar(+ floor_price=self.announcement_price * 0.9,+ price_scenarios=price_scenarios+ )++ structures = {+ 'no_collar': no_collar,+ 'fixed_collar': fixed,+ 'floating_collar': floating,+ 'floor_only': floor_only+ }++ comparison = []+ for name, structure in structures.items():+ scenarios = structure.get('scenarios', [])+ values = [s['total_deal_value'] for s in scenarios]++ comparison.append({+ 'structure': name,+ 'mean_value': np.mean(values),+ 'std_dev': np.std(values),+ 'min_value': min(values),+ 'max_value': max(values),+ 'coefficient_of_variation': (np.std(values) / np.mean(values) * 100) if np.mean(values) > 0 else 0+ })++ return {+ 'comparison': comparison,+ 'structures': structures+ }++if __name__ == '__main__':+ collar = CollarMechanism(+ announcement_price=100.00,+ target_shares=10_000_000,+ base_exchange_ratio=0.65+ )++ fixed = collar.fixed_collar(+ floor_price=90.00,+ cap_price=110.00+ )++ print("=== FIXED COLLAR ANALYSIS ===\n")+ print(f"Base Exchange Ratio: {fixed['base_exchange_ratio']:.4f}")+ print(f"Floor Price: ${fixed['floor_price']:.2f} ({fixed['floor_pct_below']:.1f}% below)")+ print(f"Cap Price: ${fixed['cap_price']:.2f} ({fixed['cap_pct_above']:.1f}% above)\n")++ print("Sample Scenarios:")+ for scenario in fixed['scenarios'][::4]:+ print(f"\nAcquirer @ ${scenario['acquirer_price']:.2f}:")+ print(f" Exchange Ratio: {scenario['effective_exchange_ratio']:.4f}")+ print(f" Value/Share: ${scenario['value_per_target_share']:.2f}")+ print(f" Protection: {scenario['protection_active']}")++ comparison = collar.compare_collar_structures(+ price_scenarios=[70, 80, 90, 100, 110, 120, 130]+ )++ print("\n\n=== COLLAR STRUCTURE COMPARISON ===")+ for comp in comparison['comparison']:+ print(f"\n{comp['structure'].replace('_', ' ').title()}:")+ print(f" Mean Value: ${comp['mean_value']:,.0f}")+ print(f" Std Dev: ${comp['std_dev']:,.0f}")+ print(f" Range: ${comp['min_value']:,.0f} - ${comp['max_value']:,.0f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/cvr_valuation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/cvr_valuation.pynew file mode 100644index 000000000..18c22afdb--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/cvr_valuation.py@@ -0,0 +1,340 @@+"""Contingent Value Rights (CVR) Valuation"""+from typing import Dict, Any, List, Optional+from dataclasses import dataclass+from enum import Enum+import numpy as np++class CVRType(Enum):+ MILESTONE = "milestone"+ EARNOUT = "earnout"+ REGULATORY = "regulatory"+ COMMODITY_PRICE = "commodity_price"+ LITIGATION = "litigation"++@dataclass+class CVRTrigger:+ trigger_type: CVRType+ description: str+ payment_if_triggered: float+ probability: float+ expected_timing_years: float++class CVRValuation:+ """Valuation of Contingent Value Rights in M&A transactions"""++ def __init__(self, discount_rate: float = 0.12,+ risk_free_rate: float = 0.04):+ self.discount_rate = discount_rate+ self.risk_free_rate = risk_free_rate++ def value_milestone_cvr(self, triggers: List[CVRTrigger]) -> Dict[str, Any]:+ """Value milestone-based CVR (FDA approval, product launch, etc.)"""++ trigger_analysis = []+ total_expected_pv = 0++ for trigger in triggers:+ pv = trigger.payment_if_triggered / ((1 + self.discount_rate) ** trigger.expected_timing_years)+ expected_value = pv * trigger.probability++ total_expected_pv += expected_value++ trigger_analysis.append({+ 'trigger_type': trigger.trigger_type.value,+ 'description': trigger.description,+ 'payment_if_triggered': trigger.payment_if_triggered,+ 'probability': trigger.probability * 100,+ 'expected_timing_years': trigger.expected_timing_years,+ 'present_value': pv,+ 'expected_value': expected_value+ })++ return {+ 'cvr_type': 'milestone',+ 'triggers': trigger_analysis,+ 'total_face_value': sum(t.payment_if_triggered for t in triggers),+ 'total_expected_value': total_expected_pv,+ 'discount_rate': self.discount_rate * 100,+ 'blended_probability': (total_expected_pv / sum(t['present_value'] for t in trigger_analysis) * 100) if trigger_analysis else 0+ }++ def value_regulatory_cvr(self, payment_if_approved: float,+ approval_probability: float,+ expected_decision_years: float,+ appeal_possible: bool = False,+ appeal_probability: float = 0,+ appeal_delay_years: float = 0) -> Dict[str, Any]:+ """Value regulatory approval CVR (common in pharma/biotech deals)"""++ base_pv = payment_if_approved / ((1 + self.discount_rate) ** expected_decision_years)+ base_expected = base_pv * approval_probability++ if appeal_possible and approval_probability < 1.0:+ rejection_prob = 1 - approval_probability+ appeal_success_prob = rejection_prob * appeal_probability++ appeal_timing = expected_decision_years + appeal_delay_years+ appeal_pv = payment_if_approved / ((1 + self.discount_rate) ** appeal_timing)+ appeal_expected = appeal_pv * appeal_success_prob++ total_expected = base_expected + appeal_expected+ blended_probability = approval_probability + appeal_success_prob+ else:+ appeal_expected = 0+ total_expected = base_expected+ blended_probability = approval_probability++ return {+ 'cvr_type': 'regulatory',+ 'payment_if_approved': payment_if_approved,+ 'base_approval_probability': approval_probability * 100,+ 'expected_decision_years': expected_decision_years,+ 'base_expected_value': base_expected,+ 'appeal_scenario': {+ 'appeal_possible': appeal_possible,+ 'appeal_probability': appeal_probability * 100 if appeal_possible else 0,+ 'appeal_expected_value': appeal_expected,+ 'appeal_delay_years': appeal_delay_years+ },+ 'total_expected_value': total_expected,+ 'blended_success_probability': blended_probability * 100,+ 'discount_rate': self.discount_rate * 100+ }++ def value_commodity_price_cvr(self, payment_schedule: List[Dict[str, float]],+ current_price: float,+ price_volatility: float,+ years_to_maturity: float) -> Dict[str, Any]:+ """+ Value commodity price-linked CVR++ payment_schedule: [{'threshold': price, 'payment': amount}, ...]+ Uses simplified option pricing logic+ """++ expected_payments = []+ total_expected_pv = 0++ for tier in payment_schedule:+ threshold = tier['threshold']+ payment = tier['payment']++ z_score = (np.log(threshold / current_price)) / (price_volatility * np.sqrt(years_to_maturity))++ from scipy.stats import norm+ probability = 1 - norm.cdf(z_score)++ pv = payment / ((1 + self.discount_rate) ** years_to_maturity)+ expected_value = pv * probability++ total_expected_pv += expected_value++ expected_payments.append({+ 'price_threshold': threshold,+ 'payment_if_reached': payment,+ 'probability': probability * 100,+ 'present_value': pv,+ 'expected_value': expected_value+ })++ return {+ 'cvr_type': 'commodity_price',+ 'current_price': current_price,+ 'price_volatility': price_volatility * 100,+ 'years_to_maturity': years_to_maturity,+ 'payment_tiers': expected_payments,+ 'total_expected_value': total_expected_pv,+ 'total_max_payment': sum(t['payment'] for t in payment_schedule)+ }++ def value_litigation_cvr(self, case_value: float,+ win_probability: float,+ expected_resolution_years: float,+ legal_costs: float = 0,+ settlement_probability: float = 0,+ settlement_amount: float = 0) -> Dict[str, Any]:+ """Value litigation outcome CVR"""++ win_pv = (case_value - legal_costs) / ((1 + self.discount_rate) ** expected_resolution_years)+ win_expected = win_pv * win_probability++ if settlement_probability > 0:+ settlement_timing = expected_resolution_years * 0.7+ settlement_pv = settlement_amount / ((1 + self.discount_rate) ** settlement_timing)+ settlement_expected = settlement_pv * settlement_probability++ no_settlement_prob = 1 - settlement_probability+ adjusted_win_expected = win_expected * no_settlement_prob+ total_expected = adjusted_win_expected + settlement_expected+ else:+ settlement_expected = 0+ total_expected = win_expected++ return {+ 'cvr_type': 'litigation',+ 'case_value': case_value,+ 'win_probability': win_probability * 100,+ 'expected_resolution_years': expected_resolution_years,+ 'legal_costs': legal_costs,+ 'win_scenario_expected_value': win_expected,+ 'settlement': {+ 'settlement_probability': settlement_probability * 100,+ 'settlement_amount': settlement_amount,+ 'settlement_expected_value': settlement_expected+ },+ 'total_expected_value': total_expected,+ 'discount_rate': self.discount_rate * 100+ }++ def value_earnout_cvr(self, base_earnout: float,+ stretch_earnout: float,+ base_probability: float,+ stretch_probability: float,+ years_to_measurement: int) -> Dict[str, Any]:+ """Value multi-tier earnout CVR"""++ base_pv = base_earnout / ((1 + self.discount_rate) ** years_to_measurement)+ base_expected = base_pv * base_probability++ stretch_pv = (base_earnout + stretch_earnout) / ((1 + self.discount_rate) ** years_to_measurement)+ stretch_expected = stretch_pv * stretch_probability++ neither_prob = 1 - base_probability - stretch_probability+ neither_expected = 0++ total_expected = base_expected + stretch_expected++ return {+ 'cvr_type': 'earnout',+ 'base_earnout': base_earnout,+ 'stretch_earnout': stretch_earnout,+ 'total_max_payment': base_earnout + stretch_earnout,+ 'years_to_measurement': years_to_measurement,+ 'scenarios': {+ 'base_achieved': {+ 'payment': base_earnout,+ 'probability': base_probability * 100,+ 'expected_value': base_expected+ },+ 'stretch_achieved': {+ 'payment': base_earnout + stretch_earnout,+ 'probability': stretch_probability * 100,+ 'expected_value': stretch_expected+ },+ 'neither_achieved': {+ 'payment': 0,+ 'probability': neither_prob * 100,+ 'expected_value': 0+ }+ },+ 'total_expected_value': total_expected,+ 'discount_rate': self.discount_rate * 100+ }++ def cvr_sensitivity_analysis(self, base_valuation: Dict[str, Any],+ probability_scenarios: List[float],+ timing_scenarios: List[float]) -> Dict[str, Any]:+ """Sensitivity analysis for CVR valuation"""++ base_payment = base_valuation.get('payment_if_approved') or base_valuation.get('case_value', 0)+ base_timing = base_valuation.get('expected_decision_years') or base_valuation.get('expected_resolution_years', 1)++ results = []++ for prob in probability_scenarios:+ for timing in timing_scenarios:+ pv = base_payment / ((1 + self.discount_rate) ** timing)+ expected = pv * prob++ results.append({+ 'probability': prob * 100,+ 'timing_years': timing,+ 'present_value': pv,+ 'expected_value': expected+ })++ return {+ 'base_valuation': base_valuation,+ 'sensitivity_matrix': results,+ 'value_range': {+ 'min': min(r['expected_value'] for r in results),+ 'max': max(r['expected_value'] for r in results),+ 'base': base_valuation.get('total_expected_value', 0)+ }+ }++ def compare_cvr_vs_cash(self, cash_alternative: float,+ cvr_expected_value: float,+ cvr_max_value: float,+ target_shareholder_discount_rate: float = 0.15) -> Dict[str, Any]:+ """Compare CVR to cash alternative from target shareholder perspective"""++ cvr_certainty_equivalent = cvr_expected_value / (1 + target_shareholder_discount_rate)++ cash_superiority = cash_alternative > cvr_certainty_equivalent++ upside_scenario = cvr_max_value - cash_alternative+ downside_risk = cash_alternative - cvr_expected_value++ return {+ 'cash_alternative': cash_alternative,+ 'cvr_expected_value': cvr_expected_value,+ 'cvr_max_value': cvr_max_value,+ 'cvr_certainty_equivalent': cvr_certainty_equivalent,+ 'cash_preferred': cash_superiority,+ 'upside_potential': upside_scenario,+ 'downside_risk': downside_risk,+ 'risk_reward_ratio': upside_scenario / downside_risk if downside_risk > 0 else float('inf')+ }++if __name__ == '__main__':+ cvr = CVRValuation(discount_rate=0.12)++ regulatory = cvr.value_regulatory_cvr(+ payment_if_approved=100_000_000,+ approval_probability=0.65,+ expected_decision_years=2.0,+ appeal_possible=True,+ appeal_probability=0.30,+ appeal_delay_years=1.5+ )++ print("=== REGULATORY CVR VALUATION ===\n")+ print(f"Payment if Approved: ${regulatory['payment_if_approved']:,.0f}")+ print(f"Base Approval Probability: {regulatory['base_approval_probability']:.1f}%")+ print(f"Expected Decision: {regulatory['expected_decision_years']:.1f} years")+ print(f"\nBase Expected Value: ${regulatory['base_expected_value']:,.0f}")+ print(f"Appeal Expected Value: ${regulatory['appeal_scenario']['appeal_expected_value']:,.0f}")+ print(f"Total Expected Value: ${regulatory['total_expected_value']:,.0f}")+ print(f"Blended Success Probability: {regulatory['blended_success_probability']:.1f}%")++ triggers = [+ CVRTrigger(CVRType.MILESTONE, "FDA Approval", 50_000_000, 0.70, 2.0),+ CVRTrigger(CVRType.MILESTONE, "EU Approval", 30_000_000, 0.60, 2.5),+ CVRTrigger(CVRType.MILESTONE, "Product Launch", 20_000_000, 0.80, 3.0)+ ]++ milestone = cvr.value_milestone_cvr(triggers)++ print("\n\n=== MILESTONE CVR VALUATION ===")+ print(f"Total Face Value: ${milestone['total_face_value']:,.0f}")+ print(f"Total Expected Value: ${milestone['total_expected_value']:,.0f}")+ print(f"\nMilestones:")+ for trigger in milestone['triggers']:+ print(f"\n {trigger['description']}:")+ print(f" Payment: ${trigger['payment_if_triggered']:,.0f}")+ print(f" Probability: {trigger['probability']:.0f}%")+ print(f" Expected Value: ${trigger['expected_value']:,.0f}")++ comparison = cvr.compare_cvr_vs_cash(+ cash_alternative=40_000_000,+ cvr_expected_value=milestone['total_expected_value'],+ cvr_max_value=milestone['total_face_value']+ )++ print("\n\n=== CVR vs CASH COMPARISON ===")+ print(f"Cash Alternative: ${comparison['cash_alternative']:,.0f}")+ print(f"CVR Expected Value: ${comparison['cvr_expected_value']:,.0f}")+ print(f"Cash Preferred: {comparison['cash_preferred']}")+ print(f"Upside Potential: ${comparison['upside_potential']:,.0f}")+ print(f"Downside Risk: ${comparison['downside_risk']:,.0f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/earnout_calculator.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/earnout_calculator.pynew file mode 100644index 000000000..458171169--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/earnout_calculator.py@@ -0,0 +1,322 @@+"""Earnout Calculator for Contingent Payments"""+from typing import Dict, Any, List, Optional+from dataclasses import dataclass+from enum import Enum+import numpy as np++class EarnoutMetric(Enum):+ REVENUE = "revenue"+ EBITDA = "ebitda"+ NET_INCOME = "net_income"+ USERS = "users"+ CUSTOM = "custom"++@dataclass+class EarnoutTranche:+ metric: EarnoutMetric+ threshold: float+ payment: float+ measurement_period_years: int+ description: str = ""++class EarnoutCalculator:+ """Calculate and value earnout provisions in M&A deals"""++ def __init__(self, discount_rate: float = 0.10):+ self.discount_rate = discount_rate++ def calculate_simple_earnout(self, base_price: float,+ earnout_tranches: List[EarnoutTranche],+ probability_weights: List[float]) -> Dict[str, Any]:+ """Calculate earnout value with probability weighting"""++ if len(earnout_tranches) != len(probability_weights):+ raise ValueError("Must provide probability for each tranche")++ if not abs(sum(probability_weights) - 1.0) < 0.01:+ raise ValueError(f"Probabilities must sum to 1.0, got {sum(probability_weights)}")++ tranche_details = []+ total_expected_earnout = 0++ for tranche, probability in zip(earnout_tranches, probability_weights):+ pv = tranche.payment / ((1 + self.discount_rate) ** tranche.measurement_period_years)+ expected_value = pv * probability++ total_expected_earnout += expected_value++ tranche_details.append({+ 'metric': tranche.metric.value,+ 'threshold': tranche.threshold,+ 'payment_if_achieved': tranche.payment,+ 'measurement_period': tranche.measurement_period_years,+ 'probability': probability * 100,+ 'present_value': pv,+ 'expected_value': expected_value,+ 'description': tranche.description+ })++ total_consideration = base_price + total_expected_earnout+ earnout_pct = (total_expected_earnout / total_consideration * 100) if total_consideration > 0 else 0++ return {+ 'base_price': base_price,+ 'earnout_tranches': tranche_details,+ 'total_earnout_face_value': sum(t.payment for t in earnout_tranches),+ 'total_earnout_pv': sum(t['present_value'] for t in tranche_details),+ 'total_earnout_expected_value': total_expected_earnout,+ 'total_consideration': total_consideration,+ 'earnout_as_pct_of_deal': earnout_pct,+ 'discount_rate': self.discount_rate * 100+ }++ def tiered_earnout(self, base_price: float,+ metric_name: str,+ tiers: List[Dict[str, float]],+ probability_distribution: List[float]) -> Dict[str, Any]:+ """+ Tiered earnout based on performance levels++ tiers: [{'threshold': value, 'payment': amount}, ...]+ probability_distribution: probability for each tier+ """++ if len(tiers) != len(probability_distribution):+ raise ValueError("Must provide probability for each tier")++ tier_analysis = []+ total_expected = 0++ for tier, prob in zip(tiers, probability_distribution):+ expected = tier['payment'] * prob++ tier_analysis.append({+ 'threshold': tier['threshold'],+ 'payment': tier['payment'],+ 'probability': prob * 100,+ 'expected_value': expected+ })++ total_expected += expected++ return {+ 'base_price': base_price,+ 'metric': metric_name,+ 'tiers': tier_analysis,+ 'max_earnout': max(t['payment'] for t in tiers),+ 'expected_earnout': total_expected,+ 'total_expected_consideration': base_price + total_expected+ }++ def continuous_earnout(self, base_price: float,+ metric_baseline: float,+ earnout_rate: float,+ cap: Optional[float] = None,+ measurement_years: int = 3,+ expected_metric_path: List[float] = None) -> Dict[str, Any]:+ """+ Continuous earnout (e.g., $X per revenue dollar above threshold)++ Args:+ earnout_rate: Payment per unit of metric above baseline+ expected_metric_path: Projected metric values for each year+ """++ if expected_metric_path is None or len(expected_metric_path) != measurement_years:+ raise ValueError(f"Must provide {measurement_years} years of metric projections")++ yearly_earnouts = []+ total_earnout_pv = 0++ for year, metric_value in enumerate(expected_metric_path, 1):+ excess = max(0, metric_value - metric_baseline)+ earnout_payment = excess * earnout_rate++ if cap:+ earnout_payment = min(earnout_payment, cap)++ pv = earnout_payment / ((1 + self.discount_rate) ** year)+ total_earnout_pv += pv++ yearly_earnouts.append({+ 'year': year,+ 'metric_value': metric_value,+ 'baseline': metric_baseline,+ 'excess': excess,+ 'earnout_payment': earnout_payment,+ 'present_value': pv+ })++ return {+ 'base_price': base_price,+ 'earnout_structure': 'continuous',+ 'baseline_metric': metric_baseline,+ 'earnout_rate': earnout_rate,+ 'cap': cap,+ 'measurement_years': measurement_years,+ 'yearly_details': yearly_earnouts,+ 'total_earnout_pv': total_earnout_pv,+ 'total_consideration': base_price + total_earnout_pv,+ 'discount_rate': self.discount_rate * 100+ }++ def revenue_milestone_earnout(self, base_price: float,+ milestones: List[Dict[str, float]],+ probabilities: List[float],+ timing: List[int]) -> Dict[str, Any]:+ """+ Revenue milestone-based earnout++ Args:+ milestones: [{'revenue_target': X, 'payment': Y}, ...]+ probabilities: Achievement probability for each+ timing: Years until each milestone+ """++ if not (len(milestones) == len(probabilities) == len(timing)):+ raise ValueError("Milestones, probabilities, and timing must have same length")++ milestone_analysis = []+ total_expected_pv = 0++ for milestone, prob, years in zip(milestones, probabilities, timing):+ pv = milestone['payment'] / ((1 + self.discount_rate) ** years)+ expected_pv = pv * prob++ total_expected_pv += expected_pv++ milestone_analysis.append({+ 'revenue_target': milestone['revenue_target'],+ 'payment_if_achieved': milestone['payment'],+ 'years_to_milestone': years,+ 'probability': prob * 100,+ 'present_value': pv,+ 'expected_value': expected_pv+ })++ return {+ 'base_price': base_price,+ 'milestones': milestone_analysis,+ 'total_milestone_payments': sum(m['payment'] for m in milestones),+ 'total_expected_earnout_pv': total_expected_pv,+ 'total_expected_consideration': base_price + total_expected_pv,+ 'discount_rate': self.discount_rate * 100+ }++ def earnout_sensitivity(self, base_earnout: Dict[str, Any],+ probability_scenarios: List[List[float]],+ scenario_names: List[str]) -> Dict[str, Any]:+ """Sensitivity analysis for earnout value under different probability assumptions"""++ if 'earnout_tranches' not in base_earnout:+ raise ValueError("Base earnout must have tranche structure")++ results = []++ for probs, name in zip(probability_scenarios, scenario_names):+ total_expected = 0+ for tranche, prob in zip(base_earnout['earnout_tranches'], probs):+ expected = tranche['present_value'] * prob+ total_expected += expected++ total_consideration = base_earnout['base_price'] + total_expected++ results.append({+ 'scenario': name,+ 'probabilities': [p * 100 for p in probs],+ 'expected_earnout': total_expected,+ 'total_consideration': total_consideration+ })++ return {+ 'base_case': base_earnout,+ 'sensitivity_scenarios': results,+ 'valuation_range': {+ 'min': min(r['total_consideration'] for r in results),+ 'max': max(r['total_consideration'] for r in results),+ 'base': base_earnout['total_consideration']+ }+ }++ def earnout_risk_adjustment(self, earnout_value: float,+ measurement_period: int,+ execution_risk: str = 'medium') -> Dict[str, Any]:+ """Apply risk adjustment to earnout valuation"""++ risk_discounts = {+ 'low': 0.10,+ 'medium': 0.25,+ 'high': 0.40,+ 'very_high': 0.60+ }++ discount = risk_discounts.get(execution_risk, 0.25)++ risk_adjusted_value = earnout_value * (1 - discount)++ return {+ 'unadjusted_earnout_value': earnout_value,+ 'execution_risk_level': execution_risk,+ 'risk_discount': discount * 100,+ 'risk_adjusted_value': risk_adjusted_value,+ 'value_haircut': earnout_value - risk_adjusted_value,+ 'measurement_period_years': measurement_period+ }++if __name__ == '__main__':+ calculator = EarnoutCalculator(discount_rate=0.12)++ tranches = [+ EarnoutTranche(+ metric=EarnoutMetric.REVENUE,+ threshold=100_000_000,+ payment=50_000_000,+ measurement_period_years=2,+ description="Year 2 revenue > $100M"+ ),+ EarnoutTranche(+ metric=EarnoutMetric.EBITDA,+ threshold=20_000_000,+ payment=30_000_000,+ measurement_period_years=3,+ description="Year 3 EBITDA > $20M"+ )+ ]++ probabilities = [0.60, 0.40]++ earnout = calculator.calculate_simple_earnout(+ base_price=300_000_000,+ earnout_tranches=tranches,+ probability_weights=probabilities+ )++ print("=== EARNOUT VALUATION ===\n")+ print(f"Base Purchase Price: ${earnout['base_price']:,.0f}")+ print(f"Total Earnout (Face Value): ${earnout['total_earnout_face_value']:,.0f}")+ print(f"Total Earnout (PV): ${earnout['total_earnout_pv']:,.0f}")+ print(f"Expected Earnout Value: ${earnout['total_earnout_expected_value']:,.0f}")+ print(f"Total Expected Consideration: ${earnout['total_consideration']:,.0f}")+ print(f"Earnout as % of Deal: {earnout['earnout_as_pct_of_deal']:.1f}%\n")++ print("Tranche Details:")+ for tranche in earnout['earnout_tranches']:+ print(f"\n {tranche['description']}")+ print(f" Payment if Achieved: ${tranche['payment_if_achieved']:,.0f}")+ print(f" Probability: {tranche['probability']:.0f}%")+ print(f" Expected Value: ${tranche['expected_value']:,.0f}")++ continuous = calculator.continuous_earnout(+ base_price=300_000_000,+ metric_baseline=80_000_000,+ earnout_rate=0.50,+ cap=60_000_000,+ measurement_years=3,+ expected_metric_path=[90_000_000, 105_000_000, 125_000_000]+ )++ print("\n\n=== CONTINUOUS EARNOUT ===")+ print(f"Earnout Rate: ${continuous['earnout_rate']:.2f} per revenue dollar above baseline")+ print(f"Cap: ${continuous['cap']:,.0f}")+ print(f"Total Earnout PV: ${continuous['total_earnout_pv']:,.0f}")+ print(f"Total Consideration: ${continuous['total_consideration']:,.0f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/exchange_ratio.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/exchange_ratio.pynew file mode 100644index 000000000..b364190a0--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/exchange_ratio.py@@ -0,0 +1,263 @@+"""Exchange Ratio Calculations for Stock Mergers"""+from typing import Dict, Any, Optional, List+import numpy as np++class ExchangeRatioCalculator:+ """Calculate and analyze exchange ratios for stock-based M&A"""++ def __init__(self, acquirer_price: float, target_price: float):+ self.acquirer_price = acquirer_price+ self.target_price = target_price++ def calculate_fixed_exchange_ratio(self, offer_price_per_share: float) -> Dict[str, Any]:+ """Calculate fixed exchange ratio based on offer price"""++ exchange_ratio = offer_price_per_share / self.acquirer_price++ premium = ((offer_price_per_share - self.target_price) / self.target_price) * 100++ return {+ 'exchange_ratio_type': 'fixed',+ 'exchange_ratio': exchange_ratio,+ 'acquirer_share_price': self.acquirer_price,+ 'target_share_price': self.target_price,+ 'offer_price_per_target_share': offer_price_per_share,+ 'premium_to_target': premium,+ 'shares_received_per_target_share': exchange_ratio+ }++ def calculate_fixed_value_exchange(self, offer_value_per_share: float,+ current_acquirer_price: float) -> Dict[str, Any]:+ """Calculate exchange ratio that maintains fixed value"""++ exchange_ratio = offer_value_per_share / current_acquirer_price++ original_ratio = offer_value_per_share / self.acquirer_price++ return {+ 'exchange_ratio_type': 'fixed_value',+ 'target_value': offer_value_per_share,+ 'original_acquirer_price': self.acquirer_price,+ 'current_acquirer_price': current_acquirer_price,+ 'original_exchange_ratio': original_ratio,+ 'current_exchange_ratio': exchange_ratio,+ 'ratio_adjustment': exchange_ratio - original_ratio,+ 'shares_received_per_target_share': exchange_ratio+ }++ def analyze_exchange_ratio_movement(self, exchange_ratio: float,+ acquirer_price_range: List[float],+ target_shares: float) -> Dict[str, Any]:+ """Analyze value movement across acquirer share price range"""++ analysis = []++ for price in acquirer_price_range:+ value_per_target_share = exchange_ratio * price+ total_value = value_per_target_share * target_shares+ premium = ((value_per_target_share - self.target_price) / self.target_price) * 100++ analysis.append({+ 'acquirer_price': price,+ 'value_per_target_share': value_per_target_share,+ 'total_deal_value': total_value,+ 'premium': premium,+ 'price_change_vs_announcement': ((price - self.acquirer_price) / self.acquirer_price) * 100+ })++ return {+ 'fixed_exchange_ratio': exchange_ratio,+ 'target_shares_outstanding': target_shares,+ 'price_scenarios': analysis,+ 'value_range': {+ 'min': min(s['total_deal_value'] for s in analysis),+ 'max': max(s['total_deal_value'] for s in analysis),+ 'at_announcement': exchange_ratio * self.acquirer_price * target_shares+ }+ }++ def relative_valuation_ratio(self, acquirer_eps: float, target_eps: float,+ target_shares: float,+ acquirer_shares: float) -> Dict[str, Any]:+ """Calculate exchange ratio based on relative valuations"""++ acquirer_pe = self.acquirer_price / acquirer_eps if acquirer_eps > 0 else 0+ target_pe = self.target_price / target_eps if target_eps > 0 else 0++ exchange_ratio_at_parity = (target_eps / acquirer_eps) if acquirer_eps > 0 else 0++ actual_ratio = self.target_price / self.acquirer_price++ new_shares_issued = exchange_ratio_at_parity * target_shares+ post_deal_shares = acquirer_shares + new_shares_issued+ post_deal_ownership_target = (new_shares_issued / post_deal_shares) * 100++ return {+ 'acquirer_pe': acquirer_pe,+ 'target_pe': target_pe,+ 'acquirer_eps': acquirer_eps,+ 'target_eps': target_eps,+ 'exchange_ratio_at_eps_parity': exchange_ratio_at_parity,+ 'current_market_ratio': actual_ratio,+ 'ratio_premium_to_parity': ((actual_ratio / exchange_ratio_at_parity - 1) * 100) if exchange_ratio_at_parity > 0 else 0,+ 'post_deal_target_ownership': post_deal_ownership_target+ }++ def contribution_based_ratio(self, acquirer_metrics: Dict[str, float],+ target_metrics: Dict[str, float],+ acquirer_shares: float,+ target_shares: float) -> Dict[str, Any]:+ """Calculate exchange ratio based on contribution analysis"""++ total_revenue = acquirer_metrics.get('revenue', 0) + target_metrics.get('revenue', 0)+ total_ebitda = acquirer_metrics.get('ebitda', 0) + target_metrics.get('ebitda', 0)+ total_net_income = acquirer_metrics.get('net_income', 0) + target_metrics.get('net_income', 0)++ contributions = {}++ if total_revenue > 0:+ contributions['revenue'] = {+ 'acquirer': (acquirer_metrics.get('revenue', 0) / total_revenue) * 100,+ 'target': (target_metrics.get('revenue', 0) / total_revenue) * 100+ }++ if total_ebitda > 0:+ contributions['ebitda'] = {+ 'acquirer': (acquirer_metrics.get('ebitda', 0) / total_ebitda) * 100,+ 'target': (target_metrics.get('ebitda', 0) / total_ebitda) * 100+ }++ if total_net_income > 0:+ contributions['net_income'] = {+ 'acquirer': (acquirer_metrics.get('net_income', 0) / total_net_income) * 100,+ 'target': (target_metrics.get('net_income', 0) / total_net_income) * 100+ }++ avg_target_contribution = np.mean([c['target'] for c in contributions.values()])++ implied_exchange_ratio = (avg_target_contribution / 100) * acquirer_shares / target_shares if target_shares > 0 else 0++ market_ratio = self.target_price / self.acquirer_price++ return {+ 'contributions': contributions,+ 'average_target_contribution': avg_target_contribution,+ 'implied_exchange_ratio': implied_exchange_ratio,+ 'market_exchange_ratio': market_ratio,+ 'ratio_premium_to_contribution': ((market_ratio / implied_exchange_ratio - 1) * 100) if implied_exchange_ratio > 0 else 0+ }++ def breakeven_exchange_ratio(self, acquirer_eps: float,+ target_eps: float,+ acquirer_shares: float,+ target_shares: float,+ synergies: float = 0) -> Dict[str, Any]:+ """Calculate exchange ratio that results in EPS breakeven"""++ acquirer_net_income = acquirer_eps * acquirer_shares+ target_net_income = target_eps * target_shares++ combined_ni = acquirer_net_income + target_net_income + synergies++ breakeven_ratio_results = []++ for ratio in np.linspace(0.5, 2.0, 50):+ new_shares = ratio * target_shares+ post_deal_shares = acquirer_shares + new_shares+ post_deal_eps = combined_ni / post_deal_shares++ accretion = ((post_deal_eps - acquirer_eps) / acquirer_eps) * 100++ breakeven_ratio_results.append({+ 'exchange_ratio': ratio,+ 'post_deal_eps': post_deal_eps,+ 'accretion_dilution': accretion+ })++ if abs(accretion) < 0.01:+ breakeven_ratio = ratio+ break+ else:+ breakeven_ratio = None++ return {+ 'breakeven_exchange_ratio': breakeven_ratio,+ 'acquirer_standalone_eps': acquirer_eps,+ 'sensitivity_analysis': breakeven_ratio_results,+ 'synergies_assumed': synergies+ }++ def collar_analysis(self, base_exchange_ratio: float,+ floor_price: float,+ cap_price: float,+ acquirer_price_scenarios: List[float]) -> Dict[str, Any]:+ """Analyze collar structure on exchange ratio"""++ scenarios = []++ for price in acquirer_price_scenarios:+ if price < floor_price:+ effective_ratio = base_exchange_ratio * (floor_price / self.acquirer_price)+ elif price > cap_price:+ effective_ratio = base_exchange_ratio * (cap_price / self.acquirer_price)+ else:+ effective_ratio = base_exchange_ratio++ value_per_share = effective_ratio * price++ scenarios.append({+ 'acquirer_price': price,+ 'effective_exchange_ratio': effective_ratio,+ 'value_per_target_share': value_per_share,+ 'collar_active': price < floor_price or price > cap_price+ })++ return {+ 'base_exchange_ratio': base_exchange_ratio,+ 'collar_floor': floor_price,+ 'collar_cap': cap_price,+ 'announcement_price': self.acquirer_price,+ 'scenarios': scenarios+ }++if __name__ == '__main__':+ calc = ExchangeRatioCalculator(+ acquirer_price=100.00,+ target_price=50.00+ )++ fixed = calc.calculate_fixed_exchange_ratio(offer_price_per_share=65.00)++ print("=== FIXED EXCHANGE RATIO ===\n")+ print(f"Exchange Ratio: {fixed['exchange_ratio']:.4f}")+ print(f"Acquirer Price: ${fixed['acquirer_share_price']:.2f}")+ print(f"Target Price: ${fixed['target_share_price']:.2f}")+ print(f"Offer Price: ${fixed['offer_price_per_target_share']:.2f}")+ print(f"Premium: {fixed['premium_to_target']:.2f}%")++ price_range = [80, 90, 100, 110, 120]+ movement = calc.analyze_exchange_ratio_movement(+ exchange_ratio=fixed['exchange_ratio'],+ acquirer_price_range=price_range,+ target_shares=10_000_000+ )++ print("\n\n=== VALUE MOVEMENT ANALYSIS ===")+ for scenario in movement['price_scenarios']:+ print(f"\nAcquirer @ ${scenario['acquirer_price']:.2f}:")+ print(f" Value per Target Share: ${scenario['value_per_target_share']:.2f}")+ print(f" Total Deal Value: ${scenario['total_deal_value']:,.0f}")+ print(f" Premium: {scenario['premium']:.1f}%")++ relative = calc.relative_valuation_ratio(+ acquirer_eps=5.00,+ target_eps=3.00,+ target_shares=10_000_000,+ acquirer_shares=50_000_000+ )++ print("\n\n=== RELATIVE VALUATION RATIO ===")+ print(f"Acquirer P/E: {relative['acquirer_pe']:.1f}x")+ print(f"Target P/E: {relative['target_pe']:.1f}x")+ print(f"Exchange Ratio at EPS Parity: {relative['exchange_ratio_at_eps_parity']:.4f}")+ print(f"Current Market Ratio: {relative['current_market_ratio']:.4f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/payment_structure.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/payment_structure.pynew file mode 100644index 000000000..9237d3045--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/deal_structure/payment_structure.py@@ -0,0 +1,288 @@+"""Payment Structure Analysis - Cash vs Stock"""+from typing import Dict, Any, Optional, List+from dataclasses import dataclass+from enum import Enum++class PaymentType(Enum):+ ALL_CASH = "all_cash"+ ALL_STOCK = "all_stock"+ MIXED = "mixed"+ CASH_AND_STOCK = "cash_and_stock"++@dataclass+class DealTerms:+ enterprise_value: float+ cash_portion: float = 0+ stock_portion: float = 0+ acquirer_share_price: float = 0+ target_shares_outstanding: float = 0++class PaymentStructureAnalyzer:+ """Analyzes payment structure implications for M&A deals"""++ def __init__(self, acquirer_shares_outstanding: float,+ acquirer_share_price: float,+ target_shares_outstanding: float,+ target_share_price: float):+ self.acquirer_shares = acquirer_shares_outstanding+ self.acquirer_price = acquirer_share_price+ self.target_shares = target_shares_outstanding+ self.target_price = target_share_price++ def analyze_all_cash(self, purchase_price: float,+ acquirer_cash: float,+ debt_capacity: float) -> Dict[str, Any]:+ """Analyze all-cash transaction"""++ cash_needed = purchase_price+ use_debt = max(0, cash_needed - acquirer_cash)++ post_deal_shares = self.acquirer_shares+ dilution_pct = 0++ return {+ 'payment_type': PaymentType.ALL_CASH.value,+ 'purchase_price': purchase_price,+ 'cash_required': cash_needed,+ 'acquirer_cash_used': min(acquirer_cash, cash_needed),+ 'debt_required': use_debt,+ 'debt_capacity_available': debt_capacity,+ 'debt_feasible': use_debt <= debt_capacity,+ 'post_deal_shares_outstanding': post_deal_shares,+ 'shareholder_dilution': dilution_pct,+ 'target_shareholders_receive': {+ 'cash': cash_needed,+ 'stock': 0,+ 'ownership_pct': 0+ }+ }++ def analyze_all_stock(self, purchase_price: float) -> Dict[str, Any]:+ """Analyze all-stock transaction"""++ new_shares_issued = purchase_price / self.acquirer_price+ post_deal_shares = self.acquirer_shares + new_shares_issued++ acquirer_ownership = (self.acquirer_shares / post_deal_shares) * 100+ target_ownership = (new_shares_issued / post_deal_shares) * 100+ dilution_pct = (new_shares_issued / self.acquirer_shares) * 100++ exchange_ratio = new_shares_issued / self.target_shares++ return {+ 'payment_type': PaymentType.ALL_STOCK.value,+ 'purchase_price': purchase_price,+ 'new_shares_issued': new_shares_issued,+ 'exchange_ratio': exchange_ratio,+ 'post_deal_shares_outstanding': post_deal_shares,+ 'shareholder_dilution': dilution_pct,+ 'ownership_split': {+ 'acquirer_shareholders': acquirer_ownership,+ 'target_shareholders': target_ownership+ },+ 'target_shareholders_receive': {+ 'cash': 0,+ 'shares': new_shares_issued,+ 'ownership_pct': target_ownership+ }+ }++ def analyze_mixed_payment(self, purchase_price: float,+ cash_percentage: float,+ acquirer_cash: float,+ debt_capacity: float) -> Dict[str, Any]:+ """Analyze mixed cash/stock transaction"""++ if not 0 <= cash_percentage <= 100:+ raise ValueError("Cash percentage must be between 0 and 100")++ cash_portion = purchase_price * (cash_percentage / 100)+ stock_portion = purchase_price * ((100 - cash_percentage) / 100)++ new_shares_issued = stock_portion / self.acquirer_price+ post_deal_shares = self.acquirer_shares + new_shares_issued++ acquirer_ownership = (self.acquirer_shares / post_deal_shares) * 100+ target_ownership = (new_shares_issued / post_deal_shares) * 100+ dilution_pct = (new_shares_issued / self.acquirer_shares) * 100++ use_debt = max(0, cash_portion - acquirer_cash)++ exchange_ratio = new_shares_issued / self.target_shares++ return {+ 'payment_type': PaymentType.MIXED.value,+ 'purchase_price': purchase_price,+ 'cash_portion': cash_portion,+ 'stock_portion': stock_portion,+ 'cash_percentage': cash_percentage,+ 'stock_percentage': 100 - cash_percentage,+ 'cash_required': cash_portion,+ 'acquirer_cash_used': min(acquirer_cash, cash_portion),+ 'debt_required': use_debt,+ 'debt_capacity_available': debt_capacity,+ 'debt_feasible': use_debt <= debt_capacity,+ 'new_shares_issued': new_shares_issued,+ 'exchange_ratio': exchange_ratio,+ 'post_deal_shares_outstanding': post_deal_shares,+ 'shareholder_dilution': dilution_pct,+ 'ownership_split': {+ 'acquirer_shareholders': acquirer_ownership,+ 'target_shareholders': target_ownership+ },+ 'target_shareholders_receive': {+ 'cash': cash_portion,+ 'shares': new_shares_issued,+ 'ownership_pct': target_ownership+ }+ }++ def compare_payment_structures(self, purchase_price: float,+ acquirer_cash: float,+ debt_capacity: float) -> Dict[str, Any]:+ """Compare all payment structure options"""++ all_cash = self.analyze_all_cash(purchase_price, acquirer_cash, debt_capacity)+ all_stock = self.analyze_all_stock(purchase_price)+ mixed_50_50 = self.analyze_mixed_payment(purchase_price, 50, acquirer_cash, debt_capacity)+ mixed_75_25 = self.analyze_mixed_payment(purchase_price, 75, acquirer_cash, debt_capacity)+ mixed_25_75 = self.analyze_mixed_payment(purchase_price, 25, acquirer_cash, debt_capacity)++ return {+ 'purchase_price': purchase_price,+ 'scenarios': {+ 'all_cash': all_cash,+ 'all_stock': all_stock,+ '50_cash_50_stock': mixed_50_50,+ '75_cash_25_stock': mixed_75_25,+ '25_cash_75_stock': mixed_25_75+ },+ 'summary': {+ 'min_dilution': all_cash['shareholder_dilution'],+ 'max_dilution': all_stock['shareholder_dilution'],+ 'min_cash_required': 0,+ 'max_cash_required': purchase_price+ }+ }++ def optimal_payment_mix(self, purchase_price: float,+ acquirer_cash: float,+ debt_capacity: float,+ max_acceptable_dilution: float,+ max_leverage_ratio: Optional[float] = None) -> Dict[str, Any]:+ """Find optimal payment mix given constraints"""++ results = []++ for cash_pct in range(0, 101, 5):+ analysis = self.analyze_mixed_payment(purchase_price, cash_pct,+ acquirer_cash, debt_capacity)++ if analysis['shareholder_dilution'] > max_acceptable_dilution:+ continue++ if not analysis['debt_feasible']:+ continue++ results.append({+ 'cash_percentage': cash_pct,+ 'stock_percentage': 100 - cash_pct,+ 'dilution': analysis['shareholder_dilution'],+ 'debt_required': analysis['debt_required'],+ 'target_ownership': analysis['ownership_split']['target_shareholders']+ })++ if not results:+ return {+ 'feasible': False,+ 'message': 'No feasible payment structure within constraints'+ }++ min_dilution = min(results, key=lambda x: x['dilution'])+ min_debt = min(results, key=lambda x: x['debt_required'])++ return {+ 'feasible': True,+ 'optimal_scenarios': {+ 'minimize_dilution': min_dilution,+ 'minimize_debt': min_debt+ },+ 'all_feasible_options': results,+ 'constraints': {+ 'max_dilution': max_acceptable_dilution,+ 'debt_capacity': debt_capacity,+ 'available_cash': acquirer_cash+ }+ }++ def tax_implications(self, payment_structure: Dict[str, Any],+ target_shareholder_basis: float,+ capital_gains_rate: float = 0.20) -> Dict[str, Any]:+ """Analyze tax implications for target shareholders"""++ cash_received = payment_structure['target_shareholders_receive']['cash']+ stock_received_value = payment_structure['target_shareholders_receive'].get('shares', 0) * self.acquirer_price++ total_consideration = cash_received + stock_received_value+ gain = total_consideration - target_shareholder_basis++ taxable_gain = min(cash_received, gain)++ current_tax = taxable_gain * capital_gains_rate++ deferred_gain = max(0, gain - taxable_gain)++ return {+ 'total_consideration': total_consideration,+ 'cost_basis': target_shareholder_basis,+ 'total_gain': gain,+ 'cash_received': cash_received,+ 'stock_received_value': stock_received_value,+ 'taxable_gain_current': taxable_gain,+ 'deferred_gain': deferred_gain,+ 'current_tax_liability': current_tax,+ 'after_tax_proceeds': cash_received - current_tax,+ 'effective_tax_rate': (current_tax / total_consideration * 100) if total_consideration > 0 else 0+ }++if __name__ == '__main__':+ analyzer = PaymentStructureAnalyzer(+ acquirer_shares_outstanding=100_000_000,+ acquirer_share_price=50.00,+ target_shares_outstanding=20_000_000,+ target_share_price=30.00+ )++ purchase_price = 800_000_000++ comparison = analyzer.compare_payment_structures(+ purchase_price=purchase_price,+ acquirer_cash=200_000_000,+ debt_capacity=400_000_000+ )++ print("=== PAYMENT STRUCTURE COMPARISON ===\n")+ print(f"Purchase Price: ${purchase_price:,.0f}\n")++ for scenario_name, scenario_data in comparison['scenarios'].items():+ print(f"\n{scenario_name.replace('_', ' ').title()}:")+ print(f" Dilution: {scenario_data['shareholder_dilution']:.2f}%")+ if 'cash_required' in scenario_data:+ print(f" Cash Required: ${scenario_data.get('cash_required', 0):,.0f}")+ if 'debt_required' in scenario_data:+ print(f" Debt Required: ${scenario_data.get('debt_required', 0):,.0f}")+ print(f" Target Ownership: {scenario_data['target_shareholders_receive']['ownership_pct']:.2f}%")++ optimal = analyzer.optimal_payment_mix(+ purchase_price=purchase_price,+ acquirer_cash=200_000_000,+ debt_capacity=400_000_000,+ max_acceptable_dilution=15.0+ )++ print("\n\n=== OPTIMAL PAYMENT MIX ===")+ if optimal['feasible']:+ print(f"\nMinimize Dilution: {optimal['optimal_scenarios']['minimize_dilution']['cash_percentage']}% cash")+ print(f" Dilution: {optimal['optimal_scenarios']['minimize_dilution']['dilution']:.2f}%")+ print(f"\nMinimize Debt: {optimal['optimal_scenarios']['minimize_debt']['cash_percentage']}% cash")+ print(f" Debt Required: ${optimal['optimal_scenarios']['minimize_debt']['debt_required']:,.0f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/__init__.pynew file mode 100644index 000000000..0f48cd507--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/__init__.py@@ -0,0 +1,15 @@+"""Fairness Opinion Framework Module"""+from .valuation_framework import FairnessOpinionFramework, ValuationMethod, ValuationRange+from .premium_analysis import PremiumAnalysis+from .process_quality import ProcessQualityAssessment, ProcessType, Bidder, BidderType++__all__ = [+ 'FairnessOpinionFramework',+ 'ValuationMethod',+ 'ValuationRange',+ 'PremiumAnalysis',+ 'ProcessQualityAssessment',+ 'ProcessType',+ 'Bidder',+ 'BidderType'+]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/premium_analysis.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/premium_analysis.pynew file mode 100644index 000000000..d00b257a9--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/premium_analysis.py@@ -0,0 +1,324 @@+"""Premium Analysis for Fairness Opinions"""+from typing import Dict, Any, List, Optional+from datetime import datetime, timedelta+import numpy as np++class PremiumAnalysis:+ """Analyze acquisition premiums for fairness opinion"""++ def __init__(self, offer_price_per_share: float,+ shares_outstanding: float):+ self.offer_price_per_share = offer_price_per_share+ self.shares_outstanding = shares_outstanding+ self.offer_value = offer_price_per_share * shares_outstanding++ def calculate_premiums(self, historical_prices: Dict[str, float]) -> Dict[str, Any]:+ """+ Calculate premiums to various historical prices++ historical_prices: {'1_day': price, '1_week': price, '1_month': price, ...}+ """++ premiums = {}++ for period, price in historical_prices.items():+ premium_pct = ((self.offer_price_per_share - price) / price * 100) if price > 0 else 0+ premium_dollar = self.offer_price_per_share - price++ premiums[period] = {+ 'historical_price': price,+ 'premium_pct': premium_pct,+ 'premium_dollar': premium_dollar+ }++ return {+ 'offer_price_per_share': self.offer_price_per_share,+ 'premiums': premiums,+ 'offer_value': self.offer_value+ }++ def unaffected_price_analysis(self, daily_prices: List[float],+ rumor_date: Optional[int] = None) -> Dict[str, Any]:+ """Determine unaffected stock price before deal rumors"""++ if rumor_date is None:+ rumor_date = len(daily_prices)++ unaffected_prices = daily_prices[:rumor_date]++ if not unaffected_prices:+ raise ValueError("No unaffected prices available")++ avg_1_day = unaffected_prices[-1] if len(unaffected_prices) >= 1 else 0+ avg_5_day = np.mean(unaffected_prices[-5:]) if len(unaffected_prices) >= 5 else avg_1_day+ avg_20_day = np.mean(unaffected_prices[-20:]) if len(unaffected_prices) >= 20 else avg_5_day+ avg_60_day = np.mean(unaffected_prices[-60:]) if len(unaffected_prices) >= 60 else avg_20_day++ premium_1_day = ((self.offer_price_per_share - avg_1_day) / avg_1_day * 100) if avg_1_day > 0 else 0+ premium_5_day = ((self.offer_price_per_share - avg_5_day) / avg_5_day * 100) if avg_5_day > 0 else 0+ premium_20_day = ((self.offer_price_per_share - avg_20_day) / avg_20_day * 100) if avg_20_day > 0 else 0+ premium_60_day = ((self.offer_price_per_share - avg_60_day) / avg_60_day * 100) if avg_60_day > 0 else 0++ return {+ 'unaffected_prices': {+ '1_day_prior': avg_1_day,+ '5_day_avg': avg_5_day,+ '20_day_avg': avg_20_day,+ '60_day_avg': avg_60_day+ },+ 'premiums_to_unaffected': {+ '1_day': premium_1_day,+ '5_day': premium_5_day,+ '20_day': premium_20_day,+ '60_day': premium_60_day+ },+ 'offer_price': self.offer_price_per_share,+ 'rumor_date_index': rumor_date+ }++ def benchmark_premiums(self, industry: str = 'general') -> Dict[str, Any]:+ """Provide benchmark acquisition premiums by industry"""++ industry_benchmarks = {+ 'general': {+ '1_day': {'25th': 15, 'median': 30, '75th': 45},+ '1_week': {'25th': 18, 'median': 33, '75th': 48},+ '4_week': {'25th': 22, 'median': 37, '75th': 52}+ },+ 'technology': {+ '1_day': {'25th': 20, 'median': 35, '75th': 50},+ '1_week': {'25th': 23, 'median': 38, '75th': 53},+ '4_week': {'25th': 27, 'median': 42, '75th': 57}+ },+ 'healthcare': {+ '1_day': {'25th': 25, 'median': 40, '75th': 55},+ '1_week': {'25th': 28, 'median': 43, '75th': 58},+ '4_week': {'25th': 32, 'median': 47, '75th': 62}+ },+ 'financial': {+ '1_day': {'25th': 12, 'median': 25, '75th': 38},+ '1_week': {'25th': 15, 'median': 28, '75th': 41},+ '4_week': {'25th': 19, 'median': 32, '75th': 45}+ },+ 'industrials': {+ '1_day': {'25th': 18, 'median': 32, '75th': 46},+ '1_week': {'25th': 21, 'median': 35, '75th': 49},+ '4_week': {'25th': 25, 'median': 39, '75th': 53}+ }+ }++ benchmarks = industry_benchmarks.get(industry.lower(), industry_benchmarks['general'])++ return {+ 'industry': industry,+ 'benchmark_premiums': benchmarks,+ 'source': 'Historical M&A transaction data'+ }++ def compare_to_benchmarks(self, actual_premium: float,+ period: str = '1_day',+ industry: str = 'general') -> Dict[str, Any]:+ """Compare actual premium to industry benchmarks"""++ benchmarks = self.benchmark_premiums(industry)+ period_benchmarks = benchmarks['benchmark_premiums'].get(period, benchmarks['benchmark_premiums']['1_day'])++ percentile_25 = period_benchmarks['25th']+ percentile_50 = period_benchmarks['median']+ percentile_75 = period_benchmarks['75th']++ if actual_premium < percentile_25:+ position = "below 25th percentile"+ elif actual_premium < percentile_50:+ position = "between 25th and 50th percentile"+ elif actual_premium < percentile_75:+ position = "between 50th and 75th percentile"+ else:+ position = "above 75th percentile"++ return {+ 'actual_premium': actual_premium,+ 'period': period,+ 'industry': industry,+ 'benchmarks': period_benchmarks,+ 'relative_position': position,+ 'above_median': actual_premium > percentile_50+ }++ def premium_adequacy_analysis(self, actual_premium: float,+ control_premium_justified: bool,+ synergy_value: Optional[float] = None,+ standalone_value: Optional[float] = None) -> Dict[str, Any]:+ """Analyze whether premium is adequate"""++ typical_control_premium = 30.0++ if control_premium_justified:+ min_expected_premium = typical_control_premium+ else:+ min_expected_premium = 15.0++ premium_adequate = actual_premium >= min_expected_premium++ if synergy_value and standalone_value:+ total_value = standalone_value + synergy_value+ premium_as_pct_of_synergies = ((self.offer_value - standalone_value) / synergy_value * 100) if synergy_value > 0 else 0+ synergy_capture_fair = 20 <= premium_as_pct_of_synergies <= 50+ else:+ premium_as_pct_of_synergies = None+ synergy_capture_fair = None++ return {+ 'actual_premium_pct': actual_premium,+ 'control_premium_expected': control_premium_justified,+ 'minimum_expected_premium': min_expected_premium,+ 'premium_adequate': premium_adequate,+ 'synergy_analysis': {+ 'synergy_value': synergy_value,+ 'premium_as_pct_of_synergies': premium_as_pct_of_synergies,+ 'synergy_split_reasonable': synergy_capture_fair+ } if synergy_value and standalone_value else None+ }++ def fifty_two_week_analysis(self, week_52_high: float,+ week_52_low: float,+ current_price: float) -> Dict[str, Any]:+ """Analyze offer relative to 52-week trading range"""++ premium_to_52w_high = ((self.offer_price_per_share - week_52_high) / week_52_high * 100) if week_52_high > 0 else 0+ premium_to_52w_low = ((self.offer_price_per_share - week_52_low) / week_52_low * 100) if week_52_low > 0 else 0++ range_position = ((self.offer_price_per_share - week_52_low) / (week_52_high - week_52_low) * 100) if (week_52_high - week_52_low) > 0 else 0++ above_52w_high = self.offer_price_per_share > week_52_high++ current_vs_52w_high = ((current_price - week_52_high) / week_52_high * 100) if week_52_high > 0 else 0++ return {+ '52_week_high': week_52_high,+ '52_week_low': week_52_low,+ 'current_price': current_price,+ 'offer_price': self.offer_price_per_share,+ 'premium_to_52w_high': premium_to_52w_high,+ 'premium_to_52w_low': premium_to_52w_low,+ 'position_in_52w_range_pct': range_position,+ 'above_52w_high': above_52w_high,+ 'current_vs_52w_high_pct': current_vs_52w_high,+ 'interpretation': 'strong offer' if above_52w_high else 'within historical range'+ }++ def volume_weighted_average_price(self, prices: List[float],+ volumes: List[int],+ days: int = 30) -> Dict[str, Any]:+ """Calculate VWAP and premium"""++ if len(prices) != len(volumes):+ raise ValueError("Prices and volumes must have same length")++ recent_prices = prices[-days:]+ recent_volumes = volumes[-days:]++ vwap = sum(p * v for p, v in zip(recent_prices, recent_volumes)) / sum(recent_volumes) if sum(recent_volumes) > 0 else 0++ premium_to_vwap = ((self.offer_price_per_share - vwap) / vwap * 100) if vwap > 0 else 0++ return {+ 'period_days': days,+ 'vwap': vwap,+ 'offer_price': self.offer_price_per_share,+ 'premium_to_vwap': premium_to_vwap,+ 'total_volume': sum(recent_volumes)+ }++ def analyst_target_comparison(self, analyst_targets: List[float]) -> Dict[str, Any]:+ """Compare offer to analyst price targets"""++ if not analyst_targets:+ return {'error': 'No analyst targets provided'}++ mean_target = np.mean(analyst_targets)+ median_target = np.median(analyst_targets)+ min_target = min(analyst_targets)+ max_target = max(analyst_targets)++ premium_to_mean = ((self.offer_price_per_share - mean_target) / mean_target * 100) if mean_target > 0 else 0+ premium_to_median = ((self.offer_price_per_share - median_target) / median_target * 100) if median_target > 0 else 0++ above_all_targets = self.offer_price_per_share > max_target+ below_all_targets = self.offer_price_per_share < min_target++ return {+ 'analyst_targets': {+ 'count': len(analyst_targets),+ 'mean': mean_target,+ 'median': median_target,+ 'min': min_target,+ 'max': max_target+ },+ 'offer_price': self.offer_price_per_share,+ 'premium_to_mean': premium_to_mean,+ 'premium_to_median': premium_to_median,+ 'above_all_targets': above_all_targets,+ 'below_all_targets': below_all_targets,+ 'within_analyst_range': min_target <= self.offer_price_per_share <= max_target+ }++if __name__ == '__main__':+ analyzer = PremiumAnalysis(+ offer_price_per_share=42.50,+ shares_outstanding=50_000_000+ )++ historical_prices = {+ '1_day': 32.50,+ '1_week': 31.80,+ '1_month': 30.20,+ '3_month': 28.50+ }++ premiums = analyzer.calculate_premiums(historical_prices)++ print("=== PREMIUM ANALYSIS ===\n")+ print(f"Offer Price: ${premiums['offer_price_per_share']:.2f}")+ print(f"Offer Value: ${premiums['offer_value']:,.0f}\n")++ print("Premiums to Historical Prices:")+ for period, data in premiums['premiums'].items():+ print(f" {period.replace('_', ' ').title()}: ${data['historical_price']:.2f} → {data['premium_pct']:.1f}% premium")++ daily_prices = [28.0, 28.5, 29.0, 29.5, 30.0, 30.5, 31.0, 31.5, 32.0, 32.5] + [33.0] * 5+ unaffected = analyzer.unaffected_price_analysis(daily_prices, rumor_date=10)++ print("\n\n=== UNAFFECTED PRICE ANALYSIS ===")+ print("\nUnaffected Prices:")+ for period, price in unaffected['unaffected_prices'].items():+ premium = unaffected['premiums_to_unaffected'][period.replace('_prior', '').replace('_avg', '')]+ print(f" {period.replace('_', ' ').title()}: ${price:.2f} → {premium:.1f}% premium")++ comparison = analyzer.compare_to_benchmarks(+ actual_premium=premiums['premiums']['1_day']['premium_pct'],+ period='1_day',+ industry='technology'+ )++ print("\n\n=== BENCHMARK COMPARISON ===")+ print(f"Industry: {comparison['industry'].title()}")+ print(f"Actual Premium: {comparison['actual_premium']:.1f}%")+ print(f"Position: {comparison['relative_position']}")+ print(f"\nIndustry Benchmarks:")+ print(f" 25th percentile: {comparison['benchmarks']['25th']:.0f}%")+ print(f" Median: {comparison['benchmarks']['median']:.0f}%")+ print(f" 75th percentile: {comparison['benchmarks']['75th']:.0f}%")++ week_52 = analyzer.fifty_two_week_analysis(+ week_52_high=35.00,+ week_52_low=24.00,+ current_price=32.50+ )++ print("\n\n=== 52-WEEK ANALYSIS ===")+ print(f"52-Week Range: ${week_52['52_week_low']:.2f} - ${week_52['52_week_high']:.2f}")+ print(f"Offer Price: ${week_52['offer_price']:.2f}")+ print(f"Premium to 52W High: {week_52['premium_to_52w_high']:.1f}%")+ print(f"Position in Range: {week_52['position_in_52w_range_pct']:.1f}%")+ print(f"Interpretation: {week_52['interpretation']}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/process_quality.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/process_quality.pynew file mode 100644index 000000000..04d63e2d2--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/process_quality.py@@ -0,0 +1,397 @@+"""M&A Process Quality Assessment"""+from typing import Dict, Any, List, Optional+from enum import Enum+from dataclasses import dataclass++class ProcessType(Enum):+ BROAD_AUCTION = "broad_auction"+ TARGETED_AUCTION = "targeted_auction"+ NEGOTIATED_SALE = "negotiated_sale"+ GO_SHOP = "go_shop"+ UNSOLICITED = "unsolicited"++class BidderType(Enum):+ STRATEGIC = "strategic"+ FINANCIAL_SPONSOR = "financial_sponsor"+ MANAGEMENT = "management"++@dataclass+class Bidder:+ name: str+ bidder_type: BidderType+ initial_indication: Optional[float]+ final_bid: Optional[float]+ selected: bool++class ProcessQualityAssessment:+ """Assess quality and fairness of M&A sale process"""++ def __init__(self, process_type: ProcessType):+ self.process_type = process_type++ def evaluate_market_check(self, parties_contacted: int,+ ndas_executed: int,+ management_presentations: int,+ bids_received: int,+ go_shop_period_days: Optional[int] = None) -> Dict[str, Any]:+ """Evaluate thoroughness of market check"""++ if self.process_type == ProcessType.BROAD_AUCTION:+ min_expected_contacts = 30+ min_expected_bids = 5+ elif self.process_type == ProcessType.TARGETED_AUCTION:+ min_expected_contacts = 15+ min_expected_bids = 3+ elif self.process_type == ProcessType.GO_SHOP:+ min_expected_contacts = 20+ min_expected_bids = 2+ else:+ min_expected_contacts = 5+ min_expected_bids = 1++ contact_rate = (ndas_executed / parties_contacted * 100) if parties_contacted > 0 else 0+ presentation_rate = (management_presentations / ndas_executed * 100) if ndas_executed > 0 else 0+ bid_rate = (bids_received / management_presentations * 100) if management_presentations > 0 else 0++ process_adequate = (+ parties_contacted >= min_expected_contacts and+ bids_received >= min_expected_bids+ )++ quality_score = 0+ if parties_contacted >= min_expected_contacts:+ quality_score += 25+ if ndas_executed >= min_expected_contacts * 0.5:+ quality_score += 25+ if management_presentations >= min_expected_contacts * 0.3:+ quality_score += 25+ if bids_received >= min_expected_bids:+ quality_score += 25++ return {+ 'process_type': self.process_type.value,+ 'parties_contacted': parties_contacted,+ 'ndas_executed': ndas_executed,+ 'management_presentations': management_presentations,+ 'bids_received': bids_received,+ 'conversion_rates': {+ 'contact_to_nda': contact_rate,+ 'nda_to_presentation': presentation_rate,+ 'presentation_to_bid': bid_rate+ },+ 'process_adequate': process_adequate,+ 'quality_score': quality_score,+ 'go_shop_period_days': go_shop_period_days,+ 'go_shop_adequate': go_shop_period_days >= 30 if go_shop_period_days else None+ }++ def analyze_competitive_tension(self, bidders: List[Bidder]) -> Dict[str, Any]:+ """Analyze competitive dynamics among bidders"""++ if not bidders:+ return {'error': 'No bidders provided'}++ strategic_bidders = [b for b in bidders if b.bidder_type == BidderType.STRATEGIC]+ financial_bidders = [b for b in bidders if b.bidder_type == BidderType.FINANCIAL_SPONSOR]++ bids_with_finals = [b for b in bidders if b.final_bid is not None]++ if len(bids_with_finals) >= 2:+ final_bids = sorted([b.final_bid for b in bids_with_finals], reverse=True)+ winning_bid = final_bids[0]+ second_bid = final_bids[1]++ bid_increment = winning_bid - second_bid+ bid_increment_pct = (bid_increment / second_bid * 100) if second_bid > 0 else 0++ competitive_tension = "high" if bid_increment_pct < 5 else "moderate" if bid_increment_pct < 10 else "low"+ else:+ bid_increment = None+ bid_increment_pct = None+ competitive_tension = "none"++ bidders_improved = sum(1 for b in bidders if b.initial_indication and b.final_bid and b.final_bid > b.initial_indication)+ improvement_rate = (bidders_improved / len(bids_with_finals) * 100) if bids_with_finals else 0++ return {+ 'total_bidders': len(bidders),+ 'strategic_bidders': len(strategic_bidders),+ 'financial_bidders': len(financial_bidders),+ 'bidders_with_final_bids': len(bids_with_finals),+ 'competitive_tension': competitive_tension,+ 'bid_increment_pct': bid_increment_pct,+ 'bidders_improved_offers': bidders_improved,+ 'improvement_rate': improvement_rate,+ 'multiple_rounds': improvement_rate > 0+ }++ def evaluate_board_process(self, board_meetings: int,+ special_committee: bool,+ independent_financial_advisor: bool,+ independent_legal_counsel: bool,+ management_conflicts: bool,+ fairness_opinion_obtained: bool) -> Dict[str, Any]:+ """Evaluate board's discharge of fiduciary duties"""++ governance_score = 0+ max_score = 100++ if board_meetings >= 3:+ governance_score += 15+ elif board_meetings >= 1:+ governance_score += 10++ if special_committee:+ governance_score += 25++ if independent_financial_advisor:+ governance_score += 20++ if independent_legal_counsel:+ governance_score += 15++ if fairness_opinion_obtained:+ governance_score += 25++ if management_conflicts and not special_committee:+ governance_score -= 30++ governance_rating = "excellent" if governance_score >= 85 else \+ "good" if governance_score >= 70 else \+ "adequate" if governance_score >= 50 else "deficient"++ best_practices_met = special_committee and independent_financial_advisor and fairness_opinion_obtained++ return {+ 'board_meetings_held': board_meetings,+ 'special_committee_formed': special_committee,+ 'independent_financial_advisor': independent_financial_advisor,+ 'independent_legal_counsel': independent_legal_counsel,+ 'management_conflicts_present': management_conflicts,+ 'fairness_opinion_obtained': fairness_opinion_obtained,+ 'governance_score': governance_score,+ 'governance_rating': governance_rating,+ 'best_practices_met': best_practices_met,+ 'process_defensible': governance_score >= 70+ }++ def timing_pressure_analysis(self, process_duration_days: int,+ termination_fee_pct: float,+ go_shop_allowed: bool,+ no_shop_period: bool,+ financing_contingency: bool) -> Dict[str, Any]:+ """Analyze timing pressures and deal protections"""++ adequate_duration = process_duration_days >= 60++ termination_fee_reasonable = 2.0 <= termination_fee_pct <= 4.0++ timing_pressure_score = 100++ if process_duration_days < 30:+ timing_pressure_score -= 40+ elif process_duration_days < 60:+ timing_pressure_score -= 20++ if termination_fee_pct > 4.0:+ timing_pressure_score -= 15++ if no_shop_period and not go_shop_allowed:+ timing_pressure_score -= 25++ pressure_level = "low" if timing_pressure_score >= 75 else \+ "moderate" if timing_pressure_score >= 50 else "high"++ return {+ 'process_duration_days': process_duration_days,+ 'adequate_duration': adequate_duration,+ 'termination_fee_pct': termination_fee_pct,+ 'termination_fee_reasonable': termination_fee_reasonable,+ 'go_shop_allowed': go_shop_allowed,+ 'no_shop_period': no_shop_period,+ 'financing_contingency': financing_contingency,+ 'timing_pressure_score': timing_pressure_score,+ 'pressure_level': pressure_level,+ 'deal_protections_reasonable': termination_fee_reasonable and (go_shop_allowed or not no_shop_period)+ }++ def alternative_transactions_considered(self, alternatives: List[Dict[str, Any]]) -> Dict[str, Any]:+ """Evaluate alternatives to sale transaction"""++ alternative_types = {}++ for alt in alternatives:+ alt_type = alt['type']+ if alt_type not in alternative_types:+ alternative_types[alt_type] = []+ alternative_types[alt_type].append(alt)++ strategic_alternatives = [+ 'remain_independent',+ 'strategic_acquisition',+ 'asset_sale',+ 'spin_off',+ 'recapitalization',+ 'liquidation'+ ]++ alternatives_considered = set(alt['type'] for alt in alternatives)+ comprehensive = len(alternatives_considered) >= 3++ return {+ 'alternatives_evaluated': len(alternatives),+ 'alternative_types': list(alternatives_considered),+ 'alternatives_by_type': alternative_types,+ 'comprehensive_analysis': comprehensive,+ 'remain_independent_considered': 'remain_independent' in alternatives_considered,+ 'strategic_alternatives_considered': len(alternatives_considered.intersection(strategic_alternatives))+ }++ def shareholder_approval_analysis(self, approval_required: bool,+ majority_threshold: float,+ unaffiliated_shareholder_vote: bool,+ anticipated_approval_pct: Optional[float] = None) -> Dict[str, Any]:+ """Analyze shareholder approval requirements"""++ if not approval_required:+ return {+ 'approval_required': False,+ 'reason': 'Statutory exemption or other exception'+ }++ vote_protection = "strong" if unaffiliated_shareholder_vote else "standard"++ expected_approval = None+ if anticipated_approval_pct:+ expected_approval = anticipated_approval_pct >= majority_threshold++ return {+ 'approval_required': approval_required,+ 'majority_threshold_pct': majority_threshold,+ 'unaffiliated_shareholder_vote': unaffiliated_shareholder_vote,+ 'anticipated_approval_pct': anticipated_approval_pct,+ 'expected_to_pass': expected_approval,+ 'vote_protection_level': vote_protection+ }++ def comprehensive_process_evaluation(self, market_check: Dict[str, Any],+ competitive_tension: Dict[str, Any],+ board_process: Dict[str, Any],+ timing_analysis: Dict[str, Any]) -> Dict[str, Any]:+ """Comprehensive evaluation of entire M&A process"""++ components = {+ 'market_check': market_check.get('quality_score', 0) * 0.30,+ 'competitive_tension': (100 if competitive_tension.get('competitive_tension') == 'high' else+ 70 if competitive_tension.get('competitive_tension') == 'moderate' else+ 40 if competitive_tension.get('competitive_tension') == 'low' else 0) * 0.25,+ 'board_governance': board_process.get('governance_score', 0) * 0.30,+ 'timing_process': timing_analysis.get('timing_pressure_score', 0) * 0.15+ }++ overall_score = sum(components.values())++ process_quality = "excellent" if overall_score >= 85 else \+ "good" if overall_score >= 70 else \+ "adequate" if overall_score >= 50 else "deficient"++ supports_fairness = overall_score >= 60++ return {+ 'overall_process_score': overall_score,+ 'process_quality_rating': process_quality,+ 'component_scores': components,+ 'supports_fairness_conclusion': supports_fairness,+ 'key_strengths': self._identify_strengths(market_check, competitive_tension, board_process, timing_analysis),+ 'key_weaknesses': self._identify_weaknesses(market_check, competitive_tension, board_process, timing_analysis)+ }++ def _identify_strengths(self, market_check, competitive_tension, board_process, timing_analysis) -> List[str]:+ strengths = []++ if market_check.get('quality_score', 0) >= 75:+ strengths.append("Thorough market check with broad outreach")++ if competitive_tension.get('competitive_tension') in ['high', 'moderate']:+ strengths.append("Competitive bidding process")++ if board_process.get('special_committee_formed'):+ strengths.append("Independent special committee formed")++ if board_process.get('governance_score', 0) >= 80:+ strengths.append("Strong governance and board process")++ if timing_analysis.get('go_shop_allowed'):+ strengths.append("Go-shop period allowed")++ return strengths++ def _identify_weaknesses(self, market_check, competitive_tension, board_process, timing_analysis) -> List[str]:+ weaknesses = []++ if market_check.get('quality_score', 0) < 50:+ weaknesses.append("Limited market check")++ if competitive_tension.get('competitive_tension') == 'none':+ weaknesses.append("No competitive tension")++ if not board_process.get('special_committee_formed') and board_process.get('management_conflicts_present'):+ weaknesses.append("Management conflicts without special committee")++ if timing_analysis.get('timing_pressure_score', 0) < 50:+ weaknesses.append("Significant timing pressure")++ if timing_analysis.get('termination_fee_pct', 0) > 4.0:+ weaknesses.append("High termination fee")++ return weaknesses++if __name__ == '__main__':+ assessment = ProcessQualityAssessment(ProcessType.TARGETED_AUCTION)++ market_check = assessment.evaluate_market_check(+ parties_contacted=25,+ ndas_executed=18,+ management_presentations=12,+ bids_received=5+ )++ print("=== MARKET CHECK EVALUATION ===\n")+ print(f"Process Type: {market_check['process_type'].replace('_', ' ').title()}")+ print(f"Parties Contacted: {market_check['parties_contacted']}")+ print(f"NDAs Executed: {market_check['ndas_executed']}")+ print(f"Management Presentations: {market_check['management_presentations']}")+ print(f"Bids Received: {market_check['bids_received']}")+ print(f"Quality Score: {market_check['quality_score']}/100")+ print(f"Process Adequate: {market_check['process_adequate']}")++ bidders = [+ Bidder("Strategic A", BidderType.STRATEGIC, 2_000_000_000, 2_400_000_000, False),+ Bidder("Strategic B", BidderType.STRATEGIC, 2_100_000_000, 2_500_000_000, True),+ Bidder("PE Firm A", BidderType.FINANCIAL_SPONSOR, 1_900_000_000, 2_300_000_000, False),+ Bidder("Strategic C", BidderType.STRATEGIC, 1_800_000_000, 2_200_000_000, False),+ ]++ competition = assessment.analyze_competitive_tension(bidders)++ print("\n\n=== COMPETITIVE TENSION ANALYSIS ===")+ print(f"Total Bidders: {competition['total_bidders']}")+ print(f"Strategic: {competition['strategic_bidders']}, Financial: {competition['financial_bidders']}")+ print(f"Competitive Tension: {competition['competitive_tension'].title()}")+ print(f"Bid Increment: {competition['bid_increment_pct']:.1f}%")+ print(f"Bidders Improved: {competition['bidders_improved_offers']}/{competition['bidders_with_final_bids']}")++ board = assessment.evaluate_board_process(+ board_meetings=5,+ special_committee=True,+ independent_financial_advisor=True,+ independent_legal_counsel=True,+ management_conflicts=False,+ fairness_opinion_obtained=True+ )++ print("\n\n=== BOARD PROCESS EVALUATION ===")+ print(f"Governance Score: {board['governance_score']}/100")+ print(f"Rating: {board['governance_rating'].title()}")+ print(f"Best Practices Met: {board['best_practices_met']}")+ print(f"Process Defensible: {board['process_defensible']}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/valuation_framework.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/valuation_framework.pynew file mode 100644index 000000000..0debcdd00--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/fairness_opinion/valuation_framework.py@@ -0,0 +1,403 @@+"""Fairness Opinion Valuation Framework"""+from typing import Dict, Any, List, Optional+from dataclasses import dataclass+from enum import Enum+import numpy as np++class ValuationMethod(Enum):+ DCF = "dcf"+ PRECEDENT_TRANSACTIONS = "precedent_transactions"+ TRADING_COMPS = "trading_comps"+ LBO_ANALYSIS = "lbo_analysis"+ PREMIUMS_PAID = "premiums_paid"+ REPLACEMENT_COST = "replacement_cost"++@dataclass+class ValuationRange:+ method: ValuationMethod+ low: float+ high: float+ midpoint: float+ weight: float++class FairnessOpinionFramework:+ """Framework for investment banking fairness opinions"""++ def __init__(self, company_name: str, offer_price: float):+ self.company_name = company_name+ self.offer_price = offer_price++ def calculate_dcf_valuation(self, free_cash_flows: List[float],+ terminal_value: float,+ wacc_low: float,+ wacc_high: float) -> Dict[str, Any]:+ """Calculate DCF valuation range"""++ def npv(fcf: List[float], tv: float, discount_rate: float) -> float:+ pv_fcf = sum(cf / ((1 + discount_rate) ** (i + 1)) for i, cf in enumerate(fcf))+ pv_tv = tv / ((1 + discount_rate) ** len(fcf))+ return pv_fcf + pv_tv++ low_value = npv(free_cash_flows, terminal_value, wacc_high)+ high_value = npv(free_cash_flows, terminal_value, wacc_low)+ mid_value = npv(free_cash_flows, terminal_value, (wacc_low + wacc_high) / 2)++ return {+ 'method': ValuationMethod.DCF.value,+ 'valuation_range': {+ 'low': low_value,+ 'high': high_value,+ 'midpoint': mid_value+ },+ 'assumptions': {+ 'wacc_low': wacc_low * 100,+ 'wacc_high': wacc_high * 100,+ 'terminal_value': terminal_value,+ 'projection_years': len(free_cash_flows)+ },+ 'fcf_projections': free_cash_flows+ }++ def calculate_trading_comps_valuation(self, subject_metric: float,+ multiples_low: float,+ multiples_high: float,+ metric_name: str = "EBITDA") -> Dict[str, Any]:+ """Calculate trading comparables valuation range"""++ low_value = subject_metric * multiples_low+ high_value = subject_metric * multiples_high+ mid_value = subject_metric * ((multiples_low + multiples_high) / 2)++ return {+ 'method': ValuationMethod.TRADING_COMPS.value,+ 'valuation_range': {+ 'low': low_value,+ 'high': high_value,+ 'midpoint': mid_value+ },+ 'assumptions': {+ 'metric_name': metric_name,+ 'subject_metric': subject_metric,+ 'multiple_range_low': multiples_low,+ 'multiple_range_high': multiples_high+ }+ }++ def calculate_precedent_transactions_valuation(self, subject_metric: float,+ multiples_low: float,+ multiples_high: float,+ metric_name: str = "EBITDA") -> Dict[str, Any]:+ """Calculate precedent transactions valuation range"""++ low_value = subject_metric * multiples_low+ high_value = subject_metric * multiples_high+ mid_value = subject_metric * ((multiples_low + multiples_high) / 2)++ return {+ 'method': ValuationMethod.PRECEDENT_TRANSACTIONS.value,+ 'valuation_range': {+ 'low': low_value,+ 'high': high_value,+ 'midpoint': mid_value+ },+ 'assumptions': {+ 'metric_name': metric_name,+ 'subject_metric': subject_metric,+ 'multiple_range_low': multiples_low,+ 'multiple_range_high': multiples_high+ }+ }++ def calculate_lbo_analysis(self, entry_price: float,+ exit_multiple_low: float,+ exit_multiple_high: float,+ ebitda_at_exit: float,+ years_to_exit: int = 5,+ target_irr: float = 0.20) -> Dict[str, Any]:+ """Calculate implied valuation from LBO analysis"""++ exit_value_low = ebitda_at_exit * exit_multiple_low+ exit_value_high = ebitda_at_exit * exit_multiple_high++ implied_value_low = exit_value_low / ((1 + target_irr) ** years_to_exit)+ implied_value_high = exit_value_high / ((1 + target_irr) ** years_to_exit)+ implied_value_mid = (implied_value_low + implied_value_high) / 2++ return {+ 'method': ValuationMethod.LBO_ANALYSIS.value,+ 'valuation_range': {+ 'low': implied_value_low,+ 'high': implied_value_high,+ 'midpoint': implied_value_mid+ },+ 'assumptions': {+ 'exit_multiple_low': exit_multiple_low,+ 'exit_multiple_high': exit_multiple_high,+ 'ebitda_at_exit': ebitda_at_exit,+ 'years_to_exit': years_to_exit,+ 'target_irr': target_irr * 100+ }+ }++ def calculate_premiums_analysis(self, unaffected_price: float,+ premium_low: float,+ premium_high: float) -> Dict[str, Any]:+ """Calculate valuation based on acquisition premiums"""++ low_value = unaffected_price * (1 + premium_low)+ high_value = unaffected_price * (1 + premium_high)+ mid_value = unaffected_price * (1 + (premium_low + premium_high) / 2)++ return {+ 'method': ValuationMethod.PREMIUMS_PAID.value,+ 'valuation_range': {+ 'low': low_value,+ 'high': high_value,+ 'midpoint': mid_value+ },+ 'assumptions': {+ 'unaffected_price': unaffected_price,+ 'premium_low': premium_low * 100,+ 'premium_high': premium_high * 100+ }+ }++ def weighted_valuation_summary(self, valuation_ranges: List[ValuationRange]) -> Dict[str, Any]:+ """Create weighted valuation summary across all methods"""++ total_weight = sum(v.weight for v in valuation_ranges)++ if abs(total_weight - 1.0) > 0.01:+ raise ValueError(f"Weights must sum to 1.0, got {total_weight}")++ weighted_low = sum(v.low * v.weight for v in valuation_ranges)+ weighted_high = sum(v.high * v.weight for v in valuation_ranges)+ weighted_mid = sum(v.midpoint * v.weight for v in valuation_ranges)++ method_details = []+ for v in valuation_ranges:+ method_details.append({+ 'method': v.method.value,+ 'low': v.low,+ 'high': v.high,+ 'midpoint': v.midpoint,+ 'weight': v.weight * 100,+ 'contribution_to_weighted_mid': v.midpoint * v.weight+ })++ implied_premium_low = ((self.offer_price - weighted_low) / weighted_low * 100) if weighted_low > 0 else 0+ implied_premium_high = ((self.offer_price - weighted_high) / weighted_high * 100) if weighted_high > 0 else 0+ implied_premium_mid = ((self.offer_price - weighted_mid) / weighted_mid * 100) if weighted_mid > 0 else 0++ within_range = weighted_low <= self.offer_price <= weighted_high++ return {+ 'company_name': self.company_name,+ 'offer_price': self.offer_price,+ 'weighted_valuation_range': {+ 'low': weighted_low,+ 'high': weighted_high,+ 'midpoint': weighted_mid+ },+ 'implied_premium': {+ 'to_low': implied_premium_low,+ 'to_high': implied_premium_high,+ 'to_midpoint': implied_premium_mid+ },+ 'offer_within_range': within_range,+ 'methods_used': method_details,+ 'position_in_range': ((self.offer_price - weighted_low) / (weighted_high - weighted_low) * 100) if (weighted_high - weighted_low) > 0 else 0+ }++ def football_field_analysis(self, valuation_ranges: List[ValuationRange]) -> Dict[str, Any]:+ """Create football field valuation chart data"""++ sorted_ranges = sorted(valuation_ranges, key=lambda x: x.midpoint)++ overall_low = min(v.low for v in valuation_ranges)+ overall_high = max(v.high for v in valuation_ranges)++ range_data = []+ for v in sorted_ranges:+ range_data.append({+ 'method': v.method.value,+ 'low': v.low,+ 'high': v.high,+ 'midpoint': v.midpoint,+ 'range_width': v.high - v.low,+ 'offer_within': v.low <= self.offer_price <= v.high+ })++ return {+ 'valuation_ranges': range_data,+ 'overall_range': {+ 'low': overall_low,+ 'high': overall_high+ },+ 'offer_price': self.offer_price,+ 'offer_position': {+ 'below_all_ranges': self.offer_price < overall_low,+ 'above_all_ranges': self.offer_price > overall_high,+ 'within_at_least_one': any(r['offer_within'] for r in range_data)+ }+ }++ def sensitivity_analysis(self, base_valuation: float,+ key_assumptions: List[Dict[str, Any]]) -> Dict[str, Any]:+ """Perform sensitivity analysis on key valuation assumptions"""++ sensitivity_results = []++ for assumption in key_assumptions:+ param_name = assumption['parameter']+ base_value = assumption['base_value']+ scenarios = assumption['scenarios']++ scenario_results = []+ for scenario in scenarios:+ variance_pct = scenario['variance_pct']+ adjusted_value = base_value * (1 + variance_pct / 100)++ valuation_impact_pct = scenario.get('valuation_impact_pct', variance_pct)+ adjusted_valuation = base_valuation * (1 + valuation_impact_pct / 100)++ scenario_results.append({+ 'scenario': scenario['name'],+ 'parameter_value': adjusted_value,+ 'variance_pct': variance_pct,+ 'valuation': adjusted_valuation,+ 'valuation_change_pct': valuation_impact_pct+ })++ sensitivity_results.append({+ 'parameter': param_name,+ 'base_value': base_value,+ 'scenarios': scenario_results+ })++ return {+ 'base_valuation': base_valuation,+ 'sensitivity_analysis': sensitivity_results+ }++ def fairness_determination(self, weighted_valuation: Dict[str, Any],+ qualitative_factors: List[str]) -> Dict[str, Any]:+ """Make fairness determination based on quantitative and qualitative analysis"""++ offer_price = weighted_valuation['offer_price']+ low = weighted_valuation['weighted_valuation_range']['low']+ high = weighted_valuation['weighted_valuation_range']['high']+ mid = weighted_valuation['weighted_valuation_range']['midpoint']++ within_range = weighted_valuation['offer_within_range']+ position = weighted_valuation['position_in_range']++ if within_range:+ if position >= 40 and position <= 60:+ quantitative_conclusion = "fair"+ elif position < 40:+ quantitative_conclusion = "fair_low_end"+ else:+ quantitative_conclusion = "fair_high_end"+ elif offer_price < low:+ shortfall_pct = ((low - offer_price) / low * 100)+ if shortfall_pct < 10:+ quantitative_conclusion = "marginally_below_range"+ else:+ quantitative_conclusion = "materially_below_range"+ else:+ premium_pct = ((offer_price - high) / high * 100)+ if premium_pct < 10:+ quantitative_conclusion = "marginally_above_range"+ else:+ quantitative_conclusion = "materially_above_range"++ is_fair = quantitative_conclusion in ["fair", "fair_low_end", "fair_high_end", "marginally_below_range", "marginally_above_range"]++ return {+ 'offer_price': offer_price,+ 'valuation_range': {+ 'low': low,+ 'high': high,+ 'midpoint': mid+ },+ 'quantitative_analysis': {+ 'within_range': within_range,+ 'position_in_range_pct': position,+ 'conclusion': quantitative_conclusion+ },+ 'qualitative_factors_considered': qualitative_factors,+ 'fairness_conclusion': {+ 'is_fair': is_fair,+ 'conclusion': "fair from a financial point of view" if is_fair else "not fair from a financial point of view"+ }+ }++if __name__ == '__main__':+ framework = FairnessOpinionFramework(+ company_name="Target Corp",+ offer_price=2_500_000_000+ )++ dcf = framework.calculate_dcf_valuation(+ free_cash_flows=[150_000_000, 175_000_000, 200_000_000, 225_000_000, 250_000_000],+ terminal_value=3_500_000_000,+ wacc_low=0.08,+ wacc_high=0.10+ )++ trading_comps = framework.calculate_trading_comps_valuation(+ subject_metric=300_000_000,+ multiples_low=7.5,+ multiples_high=9.5,+ metric_name="EBITDA"+ )++ precedent = framework.calculate_precedent_transactions_valuation(+ subject_metric=300_000_000,+ multiples_low=8.0,+ multiples_high=10.0,+ metric_name="EBITDA"+ )++ valuation_ranges = [+ ValuationRange(ValuationMethod.DCF, dcf['valuation_range']['low'],+ dcf['valuation_range']['high'], dcf['valuation_range']['midpoint'], 0.40),+ ValuationRange(ValuationMethod.TRADING_COMPS, trading_comps['valuation_range']['low'],+ trading_comps['valuation_range']['high'], trading_comps['valuation_range']['midpoint'], 0.30),+ ValuationRange(ValuationMethod.PRECEDENT_TRANSACTIONS, precedent['valuation_range']['low'],+ precedent['valuation_range']['high'], precedent['valuation_range']['midpoint'], 0.30)+ ]++ summary = framework.weighted_valuation_summary(valuation_ranges)++ print("=== FAIRNESS OPINION VALUATION SUMMARY ===\n")+ print(f"Company: {summary['company_name']}")+ print(f"Offer Price: ${summary['offer_price']:,.0f}\n")+ print(f"Weighted Valuation Range:")+ print(f" Low: ${summary['weighted_valuation_range']['low']:,.0f}")+ print(f" Midpoint: ${summary['weighted_valuation_range']['midpoint']:,.0f}")+ print(f" High: ${summary['weighted_valuation_range']['high']:,.0f}\n")+ print(f"Offer Within Range: {summary['offer_within_range']}")+ print(f"Position in Range: {summary['position_in_range']:.1f}%\n")++ print("Valuation Methods:")+ for method in summary['methods_used']:+ print(f"\n {method['method'].upper()} ({method['weight']:.0f}% weight):")+ print(f" Range: ${method['low']:,.0f} - ${method['high']:,.0f}")+ print(f" Midpoint: ${method['midpoint']:,.0f}")++ qualitative_factors = [+ "Strategic rationale and synergies",+ "Market conditions and timing",+ "Process and alternatives considered",+ "Premium to unaffected price",+ "Board and management evaluation"+ ]++ fairness = framework.fairness_determination(summary, qualitative_factors)++ print("\n\n=== FAIRNESS CONCLUSION ===")+ print(f"Quantitative Conclusion: {fairness['quantitative_analysis']['conclusion']}")+ print(f"\nFairness Opinion: The offer price of ${fairness['offer_price']:,.0f} is")+ print(f"{fairness['fairness_conclusion']['conclusion']}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/__init__.pynew file mode 100644index 000000000..3e6383e0b--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/__init__.py@@ -0,0 +1,12 @@+"""Industry-Specific M&A Metrics Module"""+from .technology import TechnologyMetrics, TechBusinessModel+from .healthcare import HealthcareMetrics, HealthcareSegment+from .financial_services import FinancialServicesMetrics++__all__ = [+ 'TechnologyMetrics',+ 'TechBusinessModel',+ 'HealthcareMetrics',+ 'HealthcareSegment',+ 'FinancialServicesMetrics'+]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/financial_services.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/financial_services.pynew file mode 100644index 000000000..9931098fb--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/financial_services.py@@ -0,0 +1,418 @@+"""Financial Services Industry M&A Metrics"""+from typing import Dict, Any, List, Optional++class FinancialServicesMetrics:+ """Financial services sector M&A metrics"""++ def calculate_bank_metrics(self, total_assets: float,+ deposits: float,+ loans: float,+ net_interest_margin: float,+ efficiency_ratio: float,+ npa_ratio: float,+ tier1_capital_ratio: float,+ roe: float) -> Dict[str, Any]:+ """Calculate banking metrics for M&A"""++ loan_to_deposit_ratio = (loans / deposits) if deposits > 0 else 0++ tangible_book_multiple = self._bank_price_to_tangible_book(roe, efficiency_ratio, npa_ratio)++ asset_quality_score = 100 - (npa_ratio * 1000)++ profitability_score = 0+ if roe >= 15:+ profitability_score += 30+ elif roe >= 12:+ profitability_score += 20++ if net_interest_margin >= 3.5:+ profitability_score += 25+ elif net_interest_margin >= 3.0:+ profitability_score += 15++ if efficiency_ratio <= 50:+ profitability_score += 25+ elif efficiency_ratio <= 60:+ profitability_score += 15++ if npa_ratio <= 1.0:+ profitability_score += 20+ elif npa_ratio <= 2.0:+ profitability_score += 10++ return {+ 'total_assets': total_assets,+ 'deposits': deposits,+ 'loans': loans,+ 'loan_to_deposit_ratio': loan_to_deposit_ratio * 100,+ 'net_interest_margin': net_interest_margin,+ 'efficiency_ratio': efficiency_ratio,+ 'npa_ratio': npa_ratio,+ 'tier1_capital_ratio': tier1_capital_ratio,+ 'roe': roe,+ 'asset_quality_score': max(0, asset_quality_score),+ 'profitability_score': profitability_score,+ 'price_to_tangible_book_range': tangible_book_multiple,+ 'core_deposit_premium': self._calculate_deposit_premium(deposits, profitability_score)+ }++ def _bank_price_to_tangible_book(self, roe: float, efficiency: float, npa: float) -> Dict[str, float]:+ """Calculate P/TBV multiple range for banks"""++ base = 1.0++ if roe >= 15:+ base = 1.8+ elif roe >= 12:+ base = 1.4+ elif roe >= 10:+ base = 1.1++ if efficiency <= 50:+ base *= 1.2+ elif efficiency <= 60:+ base *= 1.1++ if npa <= 1.0:+ base *= 1.15+ elif npa >= 3.0:+ base *= 0.85++ return {+ 'low': base * 0.85,+ 'mid': base,+ 'high': base * 1.15+ }++ def _calculate_deposit_premium(self, deposits: float, quality_score: int) -> float:+ """Calculate core deposit intangible premium"""++ base_premium = 0.03++ if quality_score >= 80:+ base_premium = 0.06+ elif quality_score >= 60:+ base_premium = 0.045++ return deposits * base_premium++ def calculate_insurance_metrics(self, gross_written_premium: float,+ combined_ratio: float,+ investment_yield: float,+ loss_ratio: float,+ expense_ratio: float,+ roe: float,+ book_value: float) -> Dict[str, Any]:+ """Calculate insurance company metrics"""++ underwriting_profit_margin = 100 - combined_ratio++ insurance_quality = 0++ if combined_ratio <= 95:+ insurance_quality += 30+ elif combined_ratio <= 100:+ insurance_quality += 20++ if loss_ratio <= 60:+ insurance_quality += 25+ elif loss_ratio <= 70:+ insurance_quality += 15++ if expense_ratio <= 25:+ insurance_quality += 20+ elif expense_ratio <= 30:+ insurance_quality += 10++ if roe >= 12:+ insurance_quality += 25+ elif roe >= 10:+ insurance_quality += 15++ price_to_book = self._insurance_price_to_book(roe, combined_ratio)++ return {+ 'gross_written_premium': gross_written_premium,+ 'combined_ratio': combined_ratio,+ 'underwriting_profit_margin': underwriting_profit_margin,+ 'loss_ratio': loss_ratio,+ 'expense_ratio': expense_ratio,+ 'investment_yield': investment_yield,+ 'roe': roe,+ 'book_value': book_value,+ 'insurance_quality_score': insurance_quality,+ 'price_to_book_range': price_to_book,+ 'premium_multiple': self._premium_multiple(insurance_quality)+ }++ def _insurance_price_to_book(self, roe: float, combined_ratio: float) -> Dict[str, float]:+ """P/B multiple for insurance companies"""++ base = 1.0++ if roe >= 15:+ base = 1.6+ elif roe >= 12:+ base = 1.3+ elif roe >= 10:+ base = 1.1++ if combined_ratio <= 95:+ base *= 1.2+ elif combined_ratio > 100:+ base *= 0.85++ return {+ 'low': base * 0.85,+ 'mid': base,+ 'high': base * 1.15+ }++ def _premium_multiple(self, quality: int) -> Dict[str, float]:+ """Premium revenue multiple"""++ if quality >= 80:+ base = 1.5+ elif quality >= 60:+ base = 1.2+ else:+ base = 0.9++ return {+ 'low': base * 0.85,+ 'mid': base,+ 'high': base * 1.15+ }++ def calculate_wealth_management_metrics(self, aum: float,+ net_flows: float,+ advisory_fee_rate: float,+ client_retention: float,+ advisor_productivity: float,+ operating_margin: float) -> Dict[str, Any]:+ """Calculate wealth/asset management metrics"""++ organic_growth_rate = (net_flows / aum * 100) if aum > 0 else 0++ revenue = aum * advisory_fee_rate++ wealth_quality = 0++ if advisory_fee_rate >= 0.75:+ wealth_quality += 25+ elif advisory_fee_rate >= 0.60:+ wealth_quality += 15++ if client_retention >= 95:+ wealth_quality += 25+ elif client_retention >= 90:+ wealth_quality += 15++ if organic_growth_rate >= 5:+ wealth_quality += 20+ elif organic_growth_rate >= 3:+ wealth_quality += 10++ if operating_margin >= 25:+ wealth_quality += 20+ elif operating_margin >= 20:+ wealth_quality += 10++ if advisor_productivity >= 150_000_000:+ wealth_quality += 10++ aum_multiple = self._aum_multiple(wealth_quality, advisory_fee_rate)++ return {+ 'aum': aum,+ 'net_flows': net_flows,+ 'organic_growth_rate': organic_growth_rate,+ 'advisory_fee_rate': advisory_fee_rate,+ 'estimated_revenue': revenue,+ 'client_retention': client_retention,+ 'advisor_productivity': advisor_productivity,+ 'operating_margin': operating_margin,+ 'wealth_quality_score': wealth_quality,+ 'aum_multiple_range': aum_multiple,+ 'revenue_multiple_range': self._wealth_revenue_multiple(wealth_quality)+ }++ def _aum_multiple(self, quality: int, fee_rate: float) -> Dict[str, float]:+ """AUM-based multiple"""++ base = 0.02++ if quality >= 80:+ base = 0.04+ elif quality >= 60:+ base = 0.03++ if fee_rate >= 0.75:+ base *= 1.2++ return {+ 'low': base * 0.85,+ 'mid': base,+ 'high': base * 1.15+ }++ def _wealth_revenue_multiple(self, quality: int) -> Dict[str, float]:+ """Revenue multiple for wealth management"""++ if quality >= 80:+ base = 4.5+ elif quality >= 60:+ base = 3.5+ else:+ base = 2.5++ return {+ 'low': base * 0.85,+ 'mid': base,+ 'high': base * 1.15+ }++ def calculate_fintech_metrics(self, transaction_volume: float,+ take_rate: float,+ user_growth: float,+ ltv_cac: float,+ revenue_growth: float,+ regulatory_licenses: List[str]) -> Dict[str, Any]:+ """Calculate fintech metrics"""++ revenue = transaction_volume * take_rate++ fintech_quality = 0++ if revenue_growth >= 100:+ fintech_quality += 30+ elif revenue_growth >= 50:+ fintech_quality += 20++ if ltv_cac >= 3:+ fintech_quality += 25+ elif ltv_cac >= 2:+ fintech_quality += 15++ if user_growth >= 50:+ fintech_quality += 20+ elif user_growth >= 30:+ fintech_quality += 10++ if take_rate >= 2.5:+ fintech_quality += 15+ elif take_rate >= 1.5:+ fintech_quality += 10++ fintech_quality += min(len(regulatory_licenses) * 5, 10)++ revenue_multiple = self._fintech_multiple(fintech_quality, revenue_growth)++ return {+ 'transaction_volume': transaction_volume,+ 'take_rate': take_rate,+ 'revenue': revenue,+ 'user_growth': user_growth,+ 'ltv_cac': ltv_cac,+ 'revenue_growth': revenue_growth,+ 'regulatory_licenses': regulatory_licenses,+ 'fintech_quality_score': fintech_quality,+ 'revenue_multiple_range': revenue_multiple,+ 'gmv_multiple': (revenue_multiple['mid'] * take_rate / 100)+ }++ def _fintech_multiple(self, quality: int, growth: float) -> Dict[str, float]:+ """Fintech revenue multiple"""++ if quality >= 80:+ base = 10.0+ elif quality >= 60:+ base = 7.0+ else:+ base = 4.0++ if growth >= 100:+ base *= 1.3++ return {+ 'low': base * 0.8,+ 'mid': base,+ 'high': base * 1.2+ }++ def financial_services_benchmarks(self) -> Dict[str, Any]:+ """Financial services M&A benchmarks"""++ return {+ 'banks': {+ 'price_to_tangible_book': {'25th': 1.1, 'median': 1.4, '75th': 1.8},+ 'price_to_earnings': {'25th': 10, 'median': 13, '75th': 16},+ 'key_drivers': 'ROE, efficiency ratio, asset quality'+ },+ 'insurance': {+ 'price_to_book': {'25th': 0.9, 'median': 1.2, '75th': 1.5},+ 'price_to_earnings': {'25th': 8, 'median': 11, '75th': 14},+ 'key_drivers': 'Combined ratio, underwriting discipline, ROE'+ },+ 'wealth_management': {+ 'aum_multiple_pct': {'25th': 2.0, 'median': 3.0, '75th': 4.5},+ 'revenue_multiple': {'25th': 2.5, 'median': 3.5, '75th': 5.0},+ 'key_drivers': 'Fee rates, client retention, organic growth'+ },+ 'fintech': {+ 'revenue_multiple': {'25th': 5.0, 'median': 8.0, '75th': 12.0},+ 'key_drivers': 'Growth rate, unit economics, regulatory moat'+ }+ }++if __name__ == '__main__':+ analyzer = FinancialServicesMetrics()++ bank = analyzer.calculate_bank_metrics(+ total_assets=50_000_000_000,+ deposits=40_000_000_000,+ loans=35_000_000_000,+ net_interest_margin=3.2,+ efficiency_ratio=58,+ npa_ratio=1.2,+ tier1_capital_ratio=12.5,+ roe=13.5+ )++ print("=== BANK M&A METRICS ===\n")+ print(f"Total Assets: ${bank['total_assets']:,.0f}")+ print(f"Loan/Deposit Ratio: {bank['loan_to_deposit_ratio']:.1f}%")+ print(f"ROE: {bank['roe']:.1f}%")+ print(f"Efficiency Ratio: {bank['efficiency_ratio']:.1f}%")+ print(f"NPA Ratio: {bank['npa_ratio']:.1f}%")+ print(f"\nProfitability Score: {bank['profitability_score']}/100")+ print(f"Asset Quality Score: {bank['asset_quality_score']:.0f}/100")+ print(f"\nPrice/Tangible Book Range:")+ ptbv = bank['price_to_tangible_book_range']+ print(f" {ptbv['low']:.2f}x - {ptbv['high']:.2f}x (Mid: {ptbv['mid']:.2f}x)")+ print(f"Core Deposit Premium: ${bank['core_deposit_premium']:,.0f}")++ wealth = analyzer.calculate_wealth_management_metrics(+ aum=75_000_000_000,+ net_flows=3_000_000_000,+ advisory_fee_rate=0.70,+ client_retention=93,+ advisor_productivity=125_000_000,+ operating_margin=22+ )++ print("\n\n=== WEALTH MANAGEMENT METRICS ===")+ print(f"AUM: ${wealth['aum']:,.0f}")+ print(f"Organic Growth: {wealth['organic_growth_rate']:.1f}%")+ print(f"Advisory Fee Rate: {wealth['advisory_fee_rate']:.2f}%")+ print(f"Quality Score: {wealth['wealth_quality_score']}/100")+ print(f"\nAUM Multiple Range:")+ aum_mult = wealth['aum_multiple_range']+ print(f" {aum_mult['low']:.2f}% - {aum_mult['high']:.2f}%")++ benchmarks = analyzer.financial_services_benchmarks()+ print("\n\n=== FINANCIAL SERVICES M&A BENCHMARKS ===")+ for sector, data in benchmarks.items():+ print(f"\n{sector.upper()}:")+ print(f" Key Drivers: {data['key_drivers']}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/healthcare.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/healthcare.pynew file mode 100644index 000000000..9779a1420--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/healthcare.py@@ -0,0 +1,406 @@+"""Healthcare Industry-Specific M&A Metrics"""+from typing import Dict, Any, List, Optional+from enum import Enum++class HealthcareSegment(Enum):+ BIOTECH = "biotech"+ PHARMA = "pharma"+ MEDICAL_DEVICES = "medical_devices"+ HEALTHCARE_SERVICES = "healthcare_services"+ HEALTHTECH = "healthtech"++class HealthcareMetrics:+ """Healthcare sector-specific M&A metrics"""++ def __init__(self, segment: HealthcareSegment):+ self.segment = segment++ def calculate_pharma_biotech_metrics(self, pipeline_value: Dict[str, Any],+ marketed_products_revenue: float,+ r_and_d_expense: float,+ patent_expiry_schedule: List[Dict[str, Any]]) -> Dict[str, Any]:+ """Calculate pharma/biotech valuation metrics"""++ total_pipeline_npv = sum(asset['npv'] for asset in pipeline_value.get('assets', []))++ marketed_value = marketed_products_revenue * 4.0++ patent_cliff_risk = self._assess_patent_cliff(patent_expiry_schedule, marketed_products_revenue)++ total_value = marketed_value + total_pipeline_npv++ pipeline_contribution = (total_pipeline_npv / total_value * 100) if total_value > 0 else 0++ r_and_d_efficiency = (total_pipeline_npv / r_and_d_expense) if r_and_d_expense > 0 else 0++ return {+ 'marketed_products_revenue': marketed_products_revenue,+ 'marketed_products_value': marketed_value,+ 'pipeline_npv': total_pipeline_npv,+ 'total_enterprise_value': total_value,+ 'pipeline_contribution_pct': pipeline_contribution,+ 'r_and_d_efficiency': r_and_d_efficiency,+ 'patent_cliff_assessment': patent_cliff_risk,+ 'valuation_breakdown': {+ 'marketed_products': marketed_value,+ 'pipeline': total_pipeline_npv+ }+ }++ def _assess_patent_cliff(self, schedule: List[Dict[str, Any]], revenue: float) -> Dict[str, Any]:+ """Assess patent expiry risk"""++ near_term_expiries = [p for p in schedule if p.get('years_to_expiry', 10) <= 3]++ at_risk_revenue = sum(p.get('revenue', 0) for p in near_term_expiries)+ at_risk_pct = (at_risk_revenue / revenue * 100) if revenue > 0 else 0++ risk_level = "high" if at_risk_pct > 30 else "moderate" if at_risk_pct > 15 else "low"++ return {+ 'products_expiring_3_years': len(near_term_expiries),+ 'revenue_at_risk': at_risk_revenue,+ 'revenue_at_risk_pct': at_risk_pct,+ 'risk_level': risk_level+ }++ def value_drug_candidate(self, peak_sales: float,+ years_to_peak: int,+ patent_life_remaining: int,+ probability_of_success: float,+ development_costs_remaining: float,+ discount_rate: float = 0.12) -> Dict[str, Any]:+ """Value individual drug candidate using rNPV"""++ cash_flows = []++ for year in range(1, patent_life_remaining + 1):+ if year <= years_to_peak:+ sales = peak_sales * (year / years_to_peak)+ else:+ decline_years = year - years_to_peak+ sales = peak_sales * (0.85 ** decline_years)++ profit_margin = 0.75+ cash_flow = sales * profit_margin++ pv = cash_flow / ((1 + discount_rate) ** year)+ cash_flows.append({+ 'year': year,+ 'sales': sales,+ 'cash_flow': cash_flow,+ 'present_value': pv+ })++ npv = sum(cf['present_value'] for cf in cash_flows)++ rnpv = (npv - development_costs_remaining) * probability_of_success++ return {+ 'peak_sales': peak_sales,+ 'years_to_peak': years_to_peak,+ 'patent_life_remaining': patent_life_remaining,+ 'probability_of_success': probability_of_success * 100,+ 'development_costs_remaining': development_costs_remaining,+ 'npv_unrisked': npv,+ 'rnpv': rnpv,+ 'discount_rate': discount_rate * 100,+ 'cash_flow_projections': cash_flows[:10]+ }++ def calculate_medical_device_metrics(self, revenue: float,+ gross_margin: float,+ clinical_evidence_strength: int,+ regulatory_approvals: List[str],+ reimbursement_coverage: float,+ installed_base: Optional[int] = None,+ recurring_revenue_pct: Optional[float] = None) -> Dict[str, Any]:+ """Calculate medical device company metrics"""++ regulatory_score = len(regulatory_approvals) * 20+ if 'FDA' in regulatory_approvals:+ regulatory_score += 20+ if 'CE_Mark' in regulatory_approvals:+ regulatory_score += 15++ device_quality_score = 0++ if gross_margin >= 0.70:+ device_quality_score += 25+ elif gross_margin >= 0.60:+ device_quality_score += 15++ if clinical_evidence_strength >= 80:+ device_quality_score += 25+ elif clinical_evidence_strength >= 60:+ device_quality_score += 15++ if reimbursement_coverage >= 80:+ device_quality_score += 25+ elif reimbursement_coverage >= 60:+ device_quality_score += 15++ device_quality_score += min(regulatory_score, 25)++ if recurring_revenue_pct and recurring_revenue_pct >= 40:+ device_quality_score += 10++ revenue_multiple = self._device_revenue_multiple(device_quality_score, gross_margin, recurring_revenue_pct)++ return {+ 'revenue': revenue,+ 'gross_margin': gross_margin * 100,+ 'clinical_evidence_strength': clinical_evidence_strength,+ 'regulatory_approvals': regulatory_approvals,+ 'reimbursement_coverage': reimbursement_coverage,+ 'installed_base': installed_base,+ 'recurring_revenue_pct': recurring_revenue_pct * 100 if recurring_revenue_pct else None,+ 'device_quality_score': device_quality_score,+ 'regulatory_score': min(regulatory_score, 100),+ 'revenue_multiple_range': revenue_multiple+ }++ def _device_revenue_multiple(self, quality: int, margin: float, recurring_pct: Optional[float]) -> Dict[str, float]:+ """Determine medical device revenue multiple"""++ base = 3.0++ if quality >= 80:+ base = 5.5+ elif quality >= 60:+ base = 4.5++ if margin >= 0.70:+ base *= 1.2++ if recurring_pct and recurring_pct >= 40:+ base *= 1.3++ return {+ 'low': base * 0.85,+ 'mid': base,+ 'high': base * 1.15+ }++ def calculate_healthcare_services_metrics(self, revenue: float,+ ebitda: float,+ same_store_growth: float,+ payor_mix: Dict[str, float],+ quality_scores: Dict[str, float],+ regulatory_compliance_score: int) -> Dict[str, Any]:+ """Calculate healthcare services metrics"""++ ebitda_margin = (ebitda / revenue) if revenue > 0 else 0++ medicare_pct = payor_mix.get('medicare', 0)+ commercial_pct = payor_mix.get('commercial', 0)+ medicaid_pct = payor_mix.get('medicaid', 0)++ payor_quality_score = (commercial_pct * 1.0 + medicare_pct * 0.7 + medicaid_pct * 0.5)++ avg_quality_score = sum(quality_scores.values()) / len(quality_scores) if quality_scores else 0++ services_quality = 0++ if ebitda_margin >= 0.20:+ services_quality += 25+ elif ebitda_margin >= 0.15:+ services_quality += 15++ if same_store_growth >= 5:+ services_quality += 25+ elif same_store_growth >= 3:+ services_quality += 15++ if payor_quality_score >= 0.75:+ services_quality += 20+ elif payor_quality_score >= 0.60:+ services_quality += 10++ if avg_quality_score >= 4.5:+ services_quality += 15+ elif avg_quality_score >= 4.0:+ services_quality += 10++ if regulatory_compliance_score >= 90:+ services_quality += 15+ elif regulatory_compliance_score >= 80:+ services_quality += 10++ ebitda_multiple = self._services_ebitda_multiple(services_quality, ebitda_margin)++ return {+ 'revenue': revenue,+ 'ebitda': ebitda,+ 'ebitda_margin': ebitda_margin * 100,+ 'same_store_growth': same_store_growth,+ 'payor_mix': {k: v * 100 for k, v in payor_mix.items()},+ 'payor_quality_score': payor_quality_score * 100,+ 'average_quality_score': avg_quality_score,+ 'regulatory_compliance': regulatory_compliance_score,+ 'services_quality_score': services_quality,+ 'ebitda_multiple_range': ebitda_multiple+ }++ def _services_ebitda_multiple(self, quality: int, margin: float) -> Dict[str, float]:+ """Healthcare services EBITDA multiple range"""++ base = 8.0++ if quality >= 80:+ base = 12.0+ elif quality >= 60:+ base = 10.0++ if margin >= 0.20:+ base *= 1.15++ return {+ 'low': base * 0.85,+ 'mid': base,+ 'high': base * 1.15+ }++ def calculate_healthtech_metrics(self, revenue: float,+ revenue_growth: float,+ clinical_integration_depth: int,+ provider_customers: int,+ patient_lives_covered: int,+ data_assets_value: Optional[float] = None) -> Dict[str, Any]:+ """Calculate healthtech/digital health metrics"""++ revenue_per_provider = revenue / provider_customers if provider_customers > 0 else 0+ revenue_per_life = revenue / patient_lives_covered if patient_lives_covered > 0 else 0++ healthtech_quality = 0++ if revenue_growth >= 100:+ healthtech_quality += 30+ elif revenue_growth >= 50:+ healthtech_quality += 20++ if clinical_integration_depth >= 80:+ healthtech_quality += 25+ elif clinical_integration_depth >= 60:+ healthtech_quality += 15++ if patient_lives_covered >= 1_000_000:+ healthtech_quality += 25+ elif patient_lives_covered >= 500_000:+ healthtech_quality += 15++ if revenue_per_provider >= 50_000:+ healthtech_quality += 20+ elif revenue_per_provider >= 25_000:+ healthtech_quality += 10++ revenue_multiple = self._healthtech_multiple(healthtech_quality, revenue_growth)++ return {+ 'revenue': revenue,+ 'revenue_growth': revenue_growth,+ 'clinical_integration_depth': clinical_integration_depth,+ 'provider_customers': provider_customers,+ 'patient_lives_covered': patient_lives_covered,+ 'revenue_per_provider': revenue_per_provider,+ 'revenue_per_life': revenue_per_life,+ 'data_assets_value': data_assets_value,+ 'healthtech_quality_score': healthtech_quality,+ 'revenue_multiple_range': revenue_multiple+ }++ def _healthtech_multiple(self, quality: int, growth: float) -> Dict[str, float]:+ """Healthtech revenue multiple"""++ base = 4.0++ if quality >= 80:+ base = 8.0+ elif quality >= 60:+ base = 6.0++ if growth >= 100:+ base *= 1.4+ elif growth >= 50:+ base *= 1.2++ return {+ 'low': base * 0.8,+ 'mid': base,+ 'high': base * 1.2+ }++ def healthcare_ma_benchmarks(self) -> Dict[str, Any]:+ """Healthcare M&A benchmark multiples"""++ return {+ 'pharma': {+ 'revenue_multiple': {'25th': 3.5, 'median': 5.0, '75th': 7.0},+ 'ebitda_multiple': {'25th': 14, 'median': 18, '75th': 24},+ 'key_drivers': 'Pipeline strength, patent life, R&D productivity'+ },+ 'biotech': {+ 'market_cap_to_pipeline_npv': {'25th': 0.4, 'median': 0.6, '75th': 0.9},+ 'key_drivers': 'Clinical stage, indication, probability of success'+ },+ 'medical_devices': {+ 'revenue_multiple': {'25th': 3.0, 'median': 4.5, '75th': 6.5},+ 'ebitda_multiple': {'25th': 12, 'median': 16, '75th': 22},+ 'key_drivers': 'Regulatory status, reimbursement, clinical evidence'+ },+ 'healthcare_services': {+ 'revenue_multiple': {'25th': 0.8, 'median': 1.2, '75th': 1.8},+ 'ebitda_multiple': {'25th': 8, 'median': 11, '75th': 14},+ 'key_drivers': 'Payor mix, quality scores, same-store growth'+ },+ 'healthtech': {+ 'revenue_multiple': {'25th': 4.0, 'median': 6.0, '75th': 9.0},+ 'key_drivers': 'Growth rate, clinical integration, covered lives'+ }+ }++if __name__ == '__main__':+ pharma = HealthcareMetrics(HealthcareSegment.PHARMA)++ drug = pharma.value_drug_candidate(+ peak_sales=2_000_000_000,+ years_to_peak=5,+ patent_life_remaining=12,+ probability_of_success=0.35,+ development_costs_remaining=500_000_000,+ discount_rate=0.12+ )++ print("=== DRUG CANDIDATE VALUATION ===\n")+ print(f"Peak Sales: ${drug['peak_sales']:,.0f}")+ print(f"Probability of Success: {drug['probability_of_success']:.0f}%")+ print(f"NPV (Unrisked): ${drug['npv_unrisked']:,.0f}")+ print(f"rNPV: ${drug['rnpv']:,.0f}")+ print(f"Development Costs Remaining: ${drug['development_costs_remaining']:,.0f}")++ device = HealthcareMetrics(HealthcareSegment.MEDICAL_DEVICES)++ device_metrics = device.calculate_medical_device_metrics(+ revenue=150_000_000,+ gross_margin=0.72,+ clinical_evidence_strength=85,+ regulatory_approvals=['FDA', 'CE_Mark'],+ reimbursement_coverage=90,+ installed_base=5_000,+ recurring_revenue_pct=0.45+ )++ print("\n\n=== MEDICAL DEVICE METRICS ===")+ print(f"Revenue: ${device_metrics['revenue']:,.0f}")+ print(f"Gross Margin: {device_metrics['gross_margin']:.1f}%")+ print(f"Quality Score: {device_metrics['device_quality_score']}/100")+ print(f"Regulatory Score: {device_metrics['regulatory_score']}/100")+ print(f"\nRevenue Multiple Range:")+ mult = device_metrics['revenue_multiple_range']+ print(f" {mult['low']:.1f}x - {mult['high']:.1f}x (Mid: {mult['mid']:.1f}x)")++ benchmarks = pharma.healthcare_ma_benchmarks()+ print("\n\n=== HEALTHCARE M&A BENCHMARKS ===")+ for sector, data in benchmarks.items():+ print(f"\n{sector.upper().replace('_', ' ')}:")+ print(f" Key Drivers: {data['key_drivers']}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/technology.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/technology.pynew file mode 100644index 000000000..a74bed927--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/industry_metrics/technology.py@@ -0,0 +1,408 @@+"""Technology Industry-Specific M&A Metrics"""+from typing import Dict, Any, List, Optional+from enum import Enum++class TechBusinessModel(Enum):+ SAAS = "saas"+ ENTERPRISE_SOFTWARE = "enterprise_software"+ CONSUMER_SOFTWARE = "consumer_software"+ SEMICONDUCTOR = "semiconductor"+ HARDWARE = "hardware"+ MARKETPLACE = "marketplace"+ ADTECH = "adtech"++class TechnologyMetrics:+ """Technology sector-specific M&A metrics and multiples"""++ def __init__(self, business_model: TechBusinessModel):+ self.business_model = business_model++ def calculate_saas_metrics(self, arr: float,+ revenue_growth_rate: float,+ gross_margin: float,+ net_retention_rate: float,+ cac: float,+ ltv: float,+ burn_multiple: Optional[float] = None) -> Dict[str, Any]:+ """Calculate SaaS-specific metrics"""++ rule_of_40 = revenue_growth_rate + (gross_margin - 0.80) * 100++ ltv_cac_ratio = ltv / cac if cac > 0 else 0++ cac_payback_months = (cac / (arr / 12)) if arr > 0 else 0++ magic_number = (arr * 0.25) / (arr * 0.20) if arr > 0 else revenue_growth_rate / 100++ arr_per_employee = None++ efficiency_score = 0+ if rule_of_40 >= 40:+ efficiency_score += 30+ elif rule_of_40 >= 30:+ efficiency_score += 20++ if ltv_cac_ratio >= 3:+ efficiency_score += 25+ elif ltv_cac_ratio >= 2:+ efficiency_score += 15++ if net_retention_rate >= 120:+ efficiency_score += 25+ elif net_retention_rate >= 110:+ efficiency_score += 15++ if gross_margin >= 0.75:+ efficiency_score += 20+ elif gross_margin >= 0.70:+ efficiency_score += 10++ return {+ 'business_model': 'saas',+ 'arr': arr,+ 'revenue_growth_rate': revenue_growth_rate,+ 'gross_margin': gross_margin * 100,+ 'net_retention_rate': net_retention_rate,+ 'key_metrics': {+ 'rule_of_40': rule_of_40,+ 'ltv_cac_ratio': ltv_cac_ratio,+ 'cac_payback_months': cac_payback_months,+ 'magic_number': magic_number,+ 'burn_multiple': burn_multiple+ },+ 'efficiency_score': efficiency_score,+ 'valuation_implications': {+ 'premium_multiple_justified': efficiency_score >= 70,+ 'suggested_multiple_range': self._saas_multiple_range(rule_of_40, revenue_growth_rate, net_retention_rate)+ }+ }++ def _saas_multiple_range(self, rule_of_40: float, growth: float, nrr: float) -> Dict[str, float]:+ """Determine appropriate ARR multiple range for SaaS"""++ base_multiple = 5.0++ if rule_of_40 >= 50:+ base_multiple = 12.0+ elif rule_of_40 >= 40:+ base_multiple = 9.0+ elif rule_of_40 >= 30:+ base_multiple = 7.0++ if growth > 50:+ base_multiple *= 1.3+ elif growth > 30:+ base_multiple *= 1.15++ if nrr >= 130:+ base_multiple *= 1.2+ elif nrr >= 120:+ base_multiple *= 1.1++ return {+ 'low': base_multiple * 0.8,+ 'mid': base_multiple,+ 'high': base_multiple * 1.2+ }++ def calculate_user_metrics(self, mau: int,+ dau: int,+ revenue: float,+ user_growth_rate: float,+ arpu: float,+ engagement_rate: float) -> Dict[str, Any]:+ """Calculate user-based metrics for consumer tech"""++ dau_mau_ratio = (dau / mau) if mau > 0 else 0++ revenue_per_mau = revenue / mau if mau > 0 else 0+ revenue_per_dau = revenue / dau if dau > 0 else 0++ user_quality_score = 0+ if dau_mau_ratio >= 0.5:+ user_quality_score += 30+ elif dau_mau_ratio >= 0.3:+ user_quality_score += 20++ if user_growth_rate >= 50:+ user_quality_score += 25+ elif user_growth_rate >= 30:+ user_quality_score += 15++ if engagement_rate >= 60:+ user_quality_score += 25+ elif engagement_rate >= 40:+ user_quality_score += 15++ if arpu >= 10:+ user_quality_score += 20+ elif arpu >= 5:+ user_quality_score += 10++ return {+ 'mau': mau,+ 'dau': dau,+ 'dau_mau_ratio': dau_mau_ratio * 100,+ 'arpu': arpu,+ 'revenue_per_mau': revenue_per_mau,+ 'revenue_per_dau': revenue_per_dau,+ 'user_growth_rate': user_growth_rate,+ 'engagement_rate': engagement_rate,+ 'user_quality_score': user_quality_score,+ 'valuation_approach': 'user_based',+ 'implied_value_per_user': self._value_per_user(user_quality_score, arpu, engagement_rate)+ }++ def _value_per_user(self, quality_score: int, arpu: float, engagement: float) -> Dict[str, float]:+ """Estimate value per user for M&A"""++ base_value = arpu * 36++ if quality_score >= 70:+ base_value *= 1.5+ elif quality_score >= 50:+ base_value *= 1.2++ if engagement >= 60:+ base_value *= 1.3++ return {+ 'value_per_mau': base_value,+ 'value_per_dau': base_value * 2.5+ }++ def calculate_marketplace_metrics(self, gmv: float,+ take_rate: float,+ revenue: float,+ liquidity_score: float,+ supply_side_retention: float,+ demand_side_retention: float) -> Dict[str, Any]:+ """Calculate marketplace-specific metrics"""++ implied_take_rate = (revenue / gmv) if gmv > 0 else take_rate++ network_strength = (supply_side_retention + demand_side_retention) / 2++ marketplace_quality = 0+ if liquidity_score >= 80:+ marketplace_quality += 30+ elif liquidity_score >= 60:+ marketplace_quality += 20++ if take_rate >= 20:+ marketplace_quality += 25+ elif take_rate >= 15:+ marketplace_quality += 15++ if network_strength >= 85:+ marketplace_quality += 25+ elif network_strength >= 75:+ marketplace_quality += 15++ if supply_side_retention >= 80 and demand_side_retention >= 80:+ marketplace_quality += 20++ gmv_multiple = self._gmv_multiple_range(marketplace_quality, take_rate, network_strength)++ return {+ 'gmv': gmv,+ 'revenue': revenue,+ 'take_rate': take_rate,+ 'implied_take_rate': implied_take_rate * 100,+ 'liquidity_score': liquidity_score,+ 'supply_side_retention': supply_side_retention,+ 'demand_side_retention': demand_side_retention,+ 'network_strength': network_strength,+ 'marketplace_quality_score': marketplace_quality,+ 'gmv_multiple_range': gmv_multiple+ }++ def _gmv_multiple_range(self, quality: int, take_rate: float, network: float) -> Dict[str, float]:+ """Determine GMV multiple range"""++ base = 0.5++ if quality >= 70:+ base = 1.2+ elif quality >= 50:+ base = 0.8++ if take_rate >= 20:+ base *= 1.3++ if network >= 85:+ base *= 1.2++ return {+ 'low': base * 0.8,+ 'mid': base,+ 'high': base * 1.2+ }++ def calculate_semiconductor_metrics(self, revenue: float,+ r_and_d_pct: float,+ gross_margin: float,+ design_win_backlog: float,+ process_node: int,+ fabless: bool) -> Dict[str, Any]:+ """Calculate semiconductor-specific metrics"""++ r_and_d_intensity = r_and_d_pct++ technology_leadership_score = 0+ if process_node <= 5:+ technology_leadership_score = 100+ elif process_node <= 7:+ technology_leadership_score = 85+ elif process_node <= 10:+ technology_leadership_score = 70+ elif process_node <= 14:+ technology_leadership_score = 55+ else:+ technology_leadership_score = 40++ design_win_coverage = (design_win_backlog / revenue) if revenue > 0 else 0++ semiconductor_quality = 0+ if gross_margin >= 60:+ semiconductor_quality += 30+ elif gross_margin >= 50:+ semiconductor_quality += 20++ if technology_leadership_score >= 85:+ semiconductor_quality += 30+ elif technology_leadership_score >= 70:+ semiconductor_quality += 20++ if design_win_coverage >= 2.0:+ semiconductor_quality += 20+ elif design_win_coverage >= 1.5:+ semiconductor_quality += 15++ if fabless:+ semiconductor_quality += 20++ return {+ 'revenue': revenue,+ 'r_and_d_pct': r_and_d_pct * 100,+ 'gross_margin': gross_margin * 100,+ 'process_node_nm': process_node,+ 'fabless': fabless,+ 'design_win_backlog': design_win_backlog,+ 'design_win_coverage_years': design_win_coverage,+ 'technology_leadership_score': technology_leadership_score,+ 'semiconductor_quality_score': semiconductor_quality,+ 'typical_revenue_multiple': self._semiconductor_multiple(semiconductor_quality, gross_margin)+ }++ def _semiconductor_multiple(self, quality: int, margin: float) -> Dict[str, float]:+ """Semiconductor revenue multiple range"""++ if quality >= 80:+ base = 6.0+ elif quality >= 60:+ base = 4.5+ else:+ base = 3.0++ if margin >= 0.60:+ base *= 1.2++ return {+ 'low': base * 0.85,+ 'mid': base,+ 'high': base * 1.15+ }++ def tech_acquisition_multiples_benchmark(self) -> Dict[str, Any]:+ """Industry benchmark multiples for tech M&A"""++ return {+ 'saas': {+ 'arr_multiple': {'25th': 6.0, 'median': 9.0, '75th': 13.0},+ 'revenue_multiple': {'25th': 5.0, 'median': 8.0, '75th': 12.0},+ 'key_driver': 'Rule of 40, NRR, growth rate'+ },+ 'enterprise_software': {+ 'revenue_multiple': {'25th': 4.0, 'median': 6.5, '75th': 10.0},+ 'ebitda_multiple': {'25th': 18.0, 'median': 24.0, '75th': 32.0},+ 'key_driver': 'Recurring revenue %, customer concentration'+ },+ 'consumer_software': {+ 'revenue_multiple': {'25th': 2.5, 'median': 4.5, '75th': 7.0},+ 'mau_value': {'25th': 25, 'median': 50, '75th': 100},+ 'key_driver': 'User engagement, monetization, growth'+ },+ 'semiconductor': {+ 'revenue_multiple': {'25th': 2.5, 'median': 4.0, '75th': 6.0},+ 'ebitda_multiple': {'25th': 12.0, 'median': 16.0, '75th': 22.0},+ 'key_driver': 'Process technology, gross margin, design wins'+ },+ 'marketplace': {+ 'gmv_multiple': {'25th': 0.4, 'median': 0.8, '75th': 1.5},+ 'revenue_multiple': {'25th': 3.0, 'median': 5.0, '75th': 8.0},+ 'key_driver': 'Take rate, liquidity, network effects'+ }+ }++if __name__ == '__main__':+ saas_analyzer = TechnologyMetrics(TechBusinessModel.SAAS)++ saas_metrics = saas_analyzer.calculate_saas_metrics(+ arr=100_000_000,+ revenue_growth_rate=60,+ gross_margin=0.78,+ net_retention_rate=125,+ cac=10_000,+ ltv=35_000,+ burn_multiple=1.2+ )++ print("=== SAAS METRICS ANALYSIS ===\n")+ print(f"ARR: ${saas_metrics['arr']:,.0f}")+ print(f"Growth Rate: {saas_metrics['revenue_growth_rate']:.0f}%")+ print(f"Gross Margin: {saas_metrics['gross_margin']:.1f}%")+ print(f"Net Retention Rate: {saas_metrics['net_retention_rate']:.0f}%\n")++ print("Key Metrics:")+ print(f" Rule of 40: {saas_metrics['key_metrics']['rule_of_40']:.1f}")+ print(f" LTV/CAC Ratio: {saas_metrics['key_metrics']['ltv_cac_ratio']:.1f}x")+ print(f" CAC Payback: {saas_metrics['key_metrics']['cac_payback_months']:.1f} months")+ print(f" Magic Number: {saas_metrics['key_metrics']['magic_number']:.2f}")+ print(f"\nEfficiency Score: {saas_metrics['efficiency_score']}/100")+ print(f"Premium Multiple Justified: {saas_metrics['valuation_implications']['premium_multiple_justified']}")+ print(f"\nSuggested ARR Multiple Range:")+ mult = saas_metrics['valuation_implications']['suggested_multiple_range']+ print(f" Low: {mult['low']:.1f}x")+ print(f" Mid: {mult['mid']:.1f}x")+ print(f" High: {mult['high']:.1f}x")++ marketplace_analyzer = TechnologyMetrics(TechBusinessModel.MARKETPLACE)++ marketplace = marketplace_analyzer.calculate_marketplace_metrics(+ gmv=500_000_000,+ take_rate=18.0,+ revenue=90_000_000,+ liquidity_score=75,+ supply_side_retention=82,+ demand_side_retention=88+ )++ print("\n\n=== MARKETPLACE METRICS ===")+ print(f"GMV: ${marketplace['gmv']:,.0f}")+ print(f"Revenue: ${marketplace['revenue']:,.0f}")+ print(f"Take Rate: {marketplace['take_rate']:.1f}%")+ print(f"Network Strength: {marketplace['network_strength']:.1f}%")+ print(f"Quality Score: {marketplace['marketplace_quality_score']}/100")+ print(f"\nGMV Multiple Range:")+ gmv_mult = marketplace['gmv_multiple_range']+ print(f" {gmv_mult['low']:.2f}x - {gmv_mult['high']:.2f}x")++ benchmarks = saas_analyzer.tech_acquisition_multiples_benchmark()+ print("\n\n=== TECH M&A MULTIPLES BENCHMARKS ===")+ for sector, data in benchmarks.items():+ print(f"\n{sector.upper().replace('_', ' ')}:")+ print(f" Key Driver: {data['key_driver']}")+ for metric, values in data.items():+ if metric != 'key_driver':+ print(f" {metric.replace('_', ' ').title()}: {values['median']:.1f}x median")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/__init__.pynew file mode 100644index 000000000..547ab9778--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/__init__.py@@ -0,0 +1,8 @@+"""LBO Module - Leveraged Buyout Models"""+from .lbo_model import LBOModel+from .capital_structure import CapitalStructureBuilder+from .debt_schedule import DebtSchedule+from .returns_calculator import ReturnsCalculator+from .exit_analysis import ExitAnalyzer++__all__ = ['LBOModel', 'CapitalStructureBuilder', 'DebtSchedule', 'ReturnsCalculator', 'ExitAnalyzer']diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/capital_structure.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/capital_structure.pynew file mode 100644index 000000000..3cbee9642--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/capital_structure.py@@ -0,0 +1,199 @@+"""Capital Structure Builder for LBO"""+from typing import Dict, Any, List, Optional+from dataclasses import dataclass++@dataclass+class DebtTranche:+ """Debt tranche structure"""+ name: str+ amount: float+ interest_rate: float+ amortization_years: float+ type: str # 'Revolver', 'Term Loan A', 'Term Loan B', 'Senior Notes', 'Subordinated', 'Mezzanine'+ mandatory_amortization: float = 0+ sweep_percentage: float = 0++class CapitalStructureBuilder:+ """Build and analyze LBO capital structure"""++ def __init__(self, entry_enterprise_value: float, entry_ebitda: float):+ self.entry_ev = entry_enterprise_value+ self.entry_ebitda = entry_ebitda+ self.debt_tranches: List[DebtTranche] = []+ self.sponsor_equity = 0+ self.rollover_equity = 0+ self.management_equity = 0++ def add_debt_tranche(self, name: str, amount: float, interest_rate: float,+ amortization_years: float, debt_type: str,+ mandatory_amortization: float = 0,+ sweep_percentage: float = 0) -> DebtTranche:+ """Add debt tranche to capital structure"""++ tranche = DebtTranche(+ name=name,+ amount=amount,+ interest_rate=interest_rate,+ amortization_years=amortization_years,+ type=debt_type,+ mandatory_amortization=mandatory_amortization,+ sweep_percentage=sweep_percentage+ )++ self.debt_tranches.append(tranche)+ return tranche++ def set_equity(self, sponsor_equity: float, rollover_equity: float = 0,+ management_equity: float = 0):+ """Set equity components"""+ self.sponsor_equity = sponsor_equity+ self.rollover_equity = rollover_equity+ self.management_equity = management_equity++ def calculate_leverage_metrics(self) -> Dict[str, float]:+ """Calculate leverage and coverage metrics"""++ total_debt = sum(t.amount for t in self.debt_tranches)+ total_equity = self.sponsor_equity + self.rollover_equity + self.management_equity++ senior_debt = sum(t.amount for t in self.debt_tranches+ if t.type in ['Revolver', 'Term Loan A', 'Term Loan B', 'Senior Notes'])+ subordinated_debt = total_debt - senior_debt++ return {+ 'total_debt': total_debt,+ 'total_equity': total_equity,+ 'total_capital': total_debt + total_equity,+ 'debt_to_ebitda': total_debt / self.entry_ebitda if self.entry_ebitda else 0,+ 'senior_debt_to_ebitda': senior_debt / self.entry_ebitda if self.entry_ebitda else 0,+ 'total_debt_to_capital': (total_debt / (total_debt + total_equity) * 100) if (total_debt + total_equity) else 0,+ 'equity_to_capital': (total_equity / (total_debt + total_equity) * 100) if (total_debt + total_equity) else 0,+ 'sponsor_equity_contribution': self.sponsor_equity,+ 'rollover_equity': self.rollover_equity,+ 'management_equity': self.management_equity+ }++ def build_capital_structure_table(self) -> Dict[str, Any]:+ """Build detailed capital structure table"""++ leverage_metrics = self.calculate_leverage_metrics()++ debt_details = []+ for tranche in self.debt_tranches:+ debt_details.append({+ 'name': tranche.name,+ 'type': tranche.type,+ 'amount': tranche.amount,+ 'percentage_of_total': (tranche.amount / leverage_metrics['total_capital'] * 100),+ 'interest_rate': tranche.interest_rate * 100,+ 'amortization_years': tranche.amortization_years+ })++ equity_details = [+ {+ 'name': 'Sponsor Equity',+ 'amount': self.sponsor_equity,+ 'percentage_of_total': (self.sponsor_equity / leverage_metrics['total_capital'] * 100)+ },+ {+ 'name': 'Rollover Equity',+ 'amount': self.rollover_equity,+ 'percentage_of_total': (self.rollover_equity / leverage_metrics['total_capital'] * 100)+ },+ {+ 'name': 'Management Equity',+ 'amount': self.management_equity,+ 'percentage_of_total': (self.management_equity / leverage_metrics['total_capital'] * 100)+ }+ ]++ return {+ 'entry_enterprise_value': self.entry_ev,+ 'entry_ebitda': self.entry_ebitda,+ 'entry_multiple': self.entry_ev / self.entry_ebitda if self.entry_ebitda else 0,+ 'debt_tranches': debt_details,+ 'equity_components': equity_details,+ 'leverage_metrics': leverage_metrics,+ 'total_sources': leverage_metrics['total_capital']+ }++ def calculate_annual_interest_expense(self, year: int = 1) -> float:+ """Calculate annual interest expense"""++ total_interest = 0+ for tranche in self.debt_tranches:+ outstanding_balance = tranche.amount++ if year > 1 and tranche.mandatory_amortization > 0:+ years_elapsed = min(year - 1, tranche.amortization_years)+ amortized = tranche.amount * tranche.mandatory_amortization * years_elapsed+ outstanding_balance = max(0, tranche.amount - amortized)++ total_interest += outstanding_balance * tranche.interest_rate++ return total_interest++ def optimize_capital_structure(self, target_leverage: float,+ max_leverage: float = 7.0) -> Dict[str, Any]:+ """Optimize capital structure for target leverage"""++ target_debt = target_leverage * self.entry_ebitda+ target_debt = min(target_debt, max_leverage * self.entry_ebitda)++ equity_needed = self.entry_ev - target_debt++ typical_structure = {+ 'Revolver': 0.05,+ 'Term Loan A': 0.20,+ 'Term Loan B': 0.50,+ 'Senior Notes': 0.15,+ 'Subordinated': 0.10+ }++ self.debt_tranches = []++ for debt_type, allocation in typical_structure.items():+ amount = target_debt * allocation++ if debt_type == 'Revolver':+ interest_rate = 0.04+ amort = 5+ elif debt_type == 'Term Loan A':+ interest_rate = 0.045+ amort = 5+ elif debt_type == 'Term Loan B':+ interest_rate = 0.055+ amort = 7+ elif debt_type == 'Senior Notes':+ interest_rate = 0.060+ amort = 10+ else:+ interest_rate = 0.085+ amort = 10++ self.add_debt_tranche(+ name=debt_type,+ amount=amount,+ interest_rate=interest_rate,+ amortization_years=amort,+ debt_type=debt_type+ )++ self.set_equity(sponsor_equity=equity_needed * 0.85,+ rollover_equity=equity_needed * 0.10,+ management_equity=equity_needed * 0.05)++ return self.build_capital_structure_table()++if __name__ == '__main__':+ builder = CapitalStructureBuilder(+ entry_enterprise_value=5_000_000_000,+ entry_ebitda=625_000_000+ )++ optimized = builder.optimize_capital_structure(target_leverage=5.5)++ print(f"Entry Multiple: {optimized['entry_multiple']:.2f}x")+ print(f"Total Debt/EBITDA: {optimized['leverage_metrics']['debt_to_ebitda']:.2f}x")+ print(f"Debt %: {optimized['leverage_metrics']['total_debt_to_capital']:.1f}%")+ print(f"Equity %: {optimized['leverage_metrics']['equity_to_capital']:.1f}%")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/debt_schedule.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/debt_schedule.pynew file mode 100644index 000000000..6def14335--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/debt_schedule.py@@ -0,0 +1,149 @@+"""Debt Schedule and Amortization Calculator"""+from typing import Dict, Any, List+from .capital_structure import DebtTranche++class DebtSchedule:+ """Calculate debt amortization schedule"""++ def __init__(self, debt_tranches: List[DebtTranche]):+ self.tranches = debt_tranches++ def calculate_annual_schedule(self, fcf_projection: List[float],+ years: int = 7) -> Dict[str, Any]:+ """Calculate annual debt schedule with cash flow sweep"""++ schedule = {year: {} for year in range(1, years + 1)}++ tranche_balances = {t.name: t.amount for t in self.tranches}++ for year in range(1, years + 1):+ year_data = {}++ beginning_balances = {name: bal for name, bal in tranche_balances.items()}++ total_mandatory_amort = 0+ for tranche in self.tranches:+ if year <= tranche.amortization_years:+ mandatory = tranche.amount * tranche.mandatory_amortization+ total_mandatory_amort += mandatory+ else:+ mandatory = 0++ year_data[f'{tranche.name}_mandatory_amort'] = mandatory++ total_interest = 0+ for tranche in self.tranches:+ outstanding = tranche_balances[tranche.name]+ interest = outstanding * tranche.interest_rate+ total_interest += interest+ year_data[f'{tranche.name}_interest'] = interest++ fcf_available = fcf_projection[year - 1] if year <= len(fcf_projection) else 0+ cash_available_for_sweep = max(0, fcf_available - total_mandatory_amort)++ total_sweep = 0+ for tranche in self.tranches:+ if tranche.sweep_percentage > 0:+ sweep_amount = min(+ cash_available_for_sweep * tranche.sweep_percentage,+ tranche_balances[tranche.name]+ )+ total_sweep += sweep_amount+ year_data[f'{tranche.name}_sweep'] = sweep_amount+ else:+ year_data[f'{tranche.name}_sweep'] = 0++ for tranche in self.tranches:+ mandatory = year_data[f'{tranche.name}_mandatory_amort']+ sweep = year_data[f'{tranche.name}_sweep']+ total_paydown = mandatory + sweep++ new_balance = max(0, tranche_balances[tranche.name] - total_paydown)+ tranche_balances[tranche.name] = new_balance++ year_data[f'{tranche.name}_beginning'] = beginning_balances[tranche.name]+ year_data[f'{tranche.name}_ending'] = new_balance+ year_data[f'{tranche.name}_total_paydown'] = total_paydown++ year_data['total_debt_beginning'] = sum(beginning_balances.values())+ year_data['total_debt_ending'] = sum(tranche_balances.values())+ year_data['total_interest_expense'] = total_interest+ year_data['total_mandatory_amort'] = total_mandatory_amort+ year_data['total_sweep'] = total_sweep+ year_data['total_debt_paydown'] = total_mandatory_amort + total_sweep++ schedule[year] = year_data++ return schedule++ def calculate_interest_coverage(self, ebitda_projection: List[float],+ schedule: Dict[int, Dict[str, Any]]) -> Dict[int, float]:+ """Calculate interest coverage ratios"""++ coverage_ratios = {}++ for year, data in schedule.items():+ if year <= len(ebitda_projection):+ ebitda = ebitda_projection[year - 1]+ interest = data['total_interest_expense']++ coverage = ebitda / interest if interest > 0 else float('inf')+ coverage_ratios[year] = coverage++ return coverage_ratios++ def calculate_leverage_progression(self, ebitda_projection: List[float],+ schedule: Dict[int, Dict[str, Any]]) -> Dict[int, float]:+ """Calculate Debt/EBITDA progression"""++ leverage_ratios = {}++ for year, data in schedule.items():+ if year <= len(ebitda_projection):+ ebitda = ebitda_projection[year - 1]+ debt = data['total_debt_ending']++ leverage = debt / ebitda if ebitda > 0 else float('inf')+ leverage_ratios[year] = leverage++ return leverage_ratios++ def summarize_debt_paydown(self, schedule: Dict[int, Dict[str, Any]]) -> Dict[str, Any]:+ """Summarize total debt paydown"""++ initial_debt = schedule[1]['total_debt_beginning']+ final_debt = schedule[max(schedule.keys())]['total_debt_ending']++ total_paydown = initial_debt - final_debt+ paydown_pct = (total_paydown / initial_debt * 100) if initial_debt else 0++ total_interest_paid = sum(data['total_interest_expense'] for data in schedule.values())++ return {+ 'initial_debt': initial_debt,+ 'final_debt': final_debt,+ 'total_paydown': total_paydown,+ 'paydown_percentage': paydown_pct,+ 'total_interest_paid': total_interest_paid+ }++if __name__ == '__main__':+ from capital_structure import DebtTranche++ tranches = [+ DebtTranche('Revolver', 250_000_000, 0.04, 5, 'Revolver', 0, 0),+ DebtTranche('Term Loan A', 1_000_000_000, 0.045, 5, 'Term Loan A', 0.20, 0.5),+ DebtTranche('Term Loan B', 2_500_000_000, 0.055, 7, 'Term Loan B', 0.01, 0.75),+ ]++ fcf_projection = [400_000_000, 450_000_000, 500_000_000, 550_000_000,+ 600_000_000, 650_000_000, 700_000_000]++ debt_schedule = DebtSchedule(tranches)+ schedule = debt_schedule.calculate_annual_schedule(fcf_projection, years=7)++ summary = debt_schedule.summarize_debt_paydown(schedule)+ print(f"Initial Debt: ${summary['initial_debt']:,.0f}")+ print(f"Final Debt: ${summary['final_debt']:,.0f}")+ print(f"Paydown: ${summary['total_paydown']:,.0f} ({summary['paydown_percentage']:.1f}%)")+ print(f"Total Interest: ${summary['total_interest_paid']:,.0f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/exit_analysis.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/exit_analysis.pynew file mode 100644index 000000000..1f209d7a6--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/exit_analysis.py@@ -0,0 +1,107 @@+"""Exit Analysis for LBO"""+from typing import Dict, Any, List+import numpy as np++class ExitAnalyzer:+ """Analyze exit scenarios and valuations"""++ def __init__(self, exit_year_ebitda: float):+ self.exit_ebitda = exit_year_ebitda++ def calculate_exit_enterprise_value(self, exit_multiple: float) -> float:+ """Calculate exit enterprise value"""+ return self.exit_ebitda * exit_multiple++ def calculate_exit_equity_value(self, exit_ev: float, exit_year_debt: float) -> float:+ """Calculate exit equity value"""+ return max(0, exit_ev - exit_year_debt)++ def multiples_exit_analysis(self, exit_multiples: List[float],+ exit_year_debt: float) -> Dict[float, Dict[str, float]]:+ """Analyze exit values across multiple exit multiples"""++ exit_scenarios = {}++ for multiple in exit_multiples:+ exit_ev = self.calculate_exit_enterprise_value(multiple)+ exit_equity = self.calculate_exit_equity_value(exit_ev, exit_year_debt)++ exit_scenarios[multiple] = {+ 'exit_multiple': multiple,+ 'exit_ebitda': self.exit_ebitda,+ 'exit_enterprise_value': exit_ev,+ 'exit_debt': exit_year_debt,+ 'exit_equity_value': exit_equity+ }++ return exit_scenarios++ def calculate_implied_exit_multiple(self, target_irr: float, initial_equity: float,+ holding_period: int, exit_year_debt: float) -> float:+ """Calculate exit multiple needed for target IRR"""++ target_exit_equity = initial_equity * ((1 + target_irr) ** holding_period)++ required_ev = target_exit_equity + exit_year_debt++ implied_multiple = required_ev / self.exit_ebitda if self.exit_ebitda else 0++ return implied_multiple++ def sensitivity_table(self, ebitda_range: List[float], multiple_range: List[float],+ exit_year_debt: float) -> Dict[str, Any]:+ """Two-way sensitivity: Exit EBITDA vs Exit Multiple"""++ matrix = []++ for ebitda in ebitda_range:+ row = []+ for multiple in multiple_range:+ exit_ev = ebitda * multiple+ exit_equity = max(0, exit_ev - exit_year_debt)+ row.append(exit_equity)+ matrix.append(row)++ return {+ 'matrix': matrix,+ 'ebitda_range': ebitda_range,+ 'multiple_range': multiple_range,+ 'base_ebitda': self.exit_ebitda,+ 'exit_debt': exit_year_debt+ }++ def comparable_exit_multiples(self, industry: str) -> Dict[str, float]:+ """Historical exit multiples by industry"""++ typical_multiples = {+ 'Technology': {'low': 8.0, 'median': 12.0, 'high': 16.0},+ 'Healthcare': {'low': 9.0, 'median': 12.5, 'high': 16.0},+ 'Industrials': {'low': 7.0, 'median': 10.0, 'high': 13.0},+ 'Consumer': {'low': 8.0, 'median': 11.0, 'high': 14.0},+ 'Financial Services': {'low': 9.0, 'median': 11.5, 'high': 14.0}+ }++ return typical_multiples.get(industry, {'low': 7.0, 'median': 10.0, 'high': 13.0})++if __name__ == '__main__':+ analyzer = ExitAnalyzer(exit_year_ebitda=850_000_000)++ exit_multiples = [8.0, 10.0, 12.0, 14.0]+ exit_debt = 1_200_000_000++ scenarios = analyzer.multiples_exit_analysis(exit_multiples, exit_debt)++ print("Exit Scenarios:\n")+ for multiple, data in scenarios.items():+ print(f"{multiple:.1f}x EBITDA:")+ print(f" EV: ${data['exit_enterprise_value']:,.0f}")+ print(f" Equity Value: ${data['exit_equity_value']:,.0f}\n")++ implied_multiple = analyzer.calculate_implied_exit_multiple(+ target_irr=0.25,+ initial_equity=1_500_000_000,+ holding_period=5,+ exit_year_debt=exit_debt+ )++ print(f"Implied Multiple for 25% IRR: {implied_multiple:.2f}x")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/lbo_model.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/lbo_model.pynew file mode 100644index 000000000..f83012573--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/lbo_model.py@@ -0,0 +1,234 @@+"""Complete LBO Model"""+from typing import Dict, Any, List, Optional+from .capital_structure import CapitalStructureBuilder+from .debt_schedule import DebtSchedule+from .returns_calculator import ReturnsCalculator+from .exit_analysis import ExitAnalyzer++class LBOModel:+ """Complete Leveraged Buyout Model"""++ def __init__(self, target_data: Dict[str, Any], transaction_assumptions: Dict[str, Any]):+ self.target = target_data+ self.assumptions = transaction_assumptions++ self.entry_ebitda = target_data.get('ebitda')+ self.entry_multiple = transaction_assumptions.get('entry_multiple', 10.0)+ self.entry_ev = self.entry_ebitda * self.entry_multiple++ self.capital_structure = None+ self.debt_schedule = None+ self.returns_calc = ReturnsCalculator()+ self.exit_analyzer = None++ def build_complete_model(self, projection_years: int = 5) -> Dict[str, Any]:+ """Build complete LBO model"""++ target_leverage = self.assumptions.get('target_leverage', 5.5)++ self.capital_structure = CapitalStructureBuilder(self.entry_ev, self.entry_ebitda)+ cap_structure = self.capital_structure.optimize_capital_structure(target_leverage)++ revenue_growth = self.assumptions.get('revenue_growth', [0.05] * projection_years)+ ebitda_margin = self.assumptions.get('ebitda_margin', 0.15)+ capex_pct = self.assumptions.get('capex_pct_revenue', 0.03)+ nwc_pct = self.assumptions.get('nwc_pct_revenue', 0.05)+ tax_rate = self.assumptions.get('tax_rate', 0.21)++ financials = self._project_financials(+ revenue_growth, ebitda_margin, capex_pct, nwc_pct, tax_rate, projection_years+ )++ fcf_projection = [fin['free_cash_flow'] for fin in financials.values()]++ self.debt_schedule = DebtSchedule(self.capital_structure.debt_tranches)+ debt_schedule = self.debt_schedule.calculate_annual_schedule(fcf_projection, projection_years)++ ebitda_projection = [fin['ebitda'] for fin in financials.values()]+ interest_coverage = self.debt_schedule.calculate_interest_coverage(ebitda_projection, debt_schedule)+ leverage_progression = self.debt_schedule.calculate_leverage_progression(ebitda_projection, debt_schedule)+ debt_summary = self.debt_schedule.summarize_debt_paydown(debt_schedule)++ exit_year = self.assumptions.get('exit_year', 5)+ exit_ebitda = financials[exit_year]['ebitda']+ exit_multiples = self.assumptions.get('exit_multiples', [8.0, 10.0, 12.0])++ self.exit_analyzer = ExitAnalyzer(exit_ebitda)++ exit_year_debt = debt_schedule[exit_year]['total_debt_ending']+ exit_scenarios = self.exit_analyzer.multiples_exit_analysis(exit_multiples, exit_year_debt)++ returns_analysis = {}+ initial_equity = cap_structure['leverage_metrics']['sponsor_equity_contribution']++ for multiple, scenario in exit_scenarios.items():+ exit_equity = scenario['exit_equity_value']+ returns = self.returns_calc.comprehensive_returns(initial_equity, exit_equity, exit_year)+ hurdle_metrics = self.returns_calc.calculate_hurdle_metrics(returns, self.assumptions.get('hurdle_irr', 0.20))++ returns_analysis[multiple] = {+ **returns,+ 'hurdle_metrics': hurdle_metrics+ }++ sensitivity = self._build_sensitivity_analysis(+ initial_equity, exit_year, ebitda_projection, debt_schedule+ )++ return {+ 'transaction_summary': {+ 'target_company': self.target.get('company_name', 'Target'),+ 'entry_ebitda': self.entry_ebitda,+ 'entry_multiple': self.entry_multiple,+ 'entry_enterprise_value': self.entry_ev,+ 'holding_period': exit_year,+ 'exit_year': exit_year+ },+ 'capital_structure': cap_structure,+ 'financial_projections': financials,+ 'debt_schedule': debt_schedule,+ 'debt_summary': debt_summary,+ 'credit_metrics': {+ 'interest_coverage': interest_coverage,+ 'leverage_progression': leverage_progression+ },+ 'exit_scenarios': exit_scenarios,+ 'returns_analysis': returns_analysis,+ 'sensitivity_analysis': sensitivity+ }++ def _project_financials(self, revenue_growth: List[float], ebitda_margin: float,+ capex_pct: float, nwc_pct: float, tax_rate: float,+ years: int) -> Dict[int, Dict[str, float]]:+ """Project financial statements"""++ base_revenue = self.target.get('revenue', self.entry_ebitda / ebitda_margin)++ financials = {}++ for year in range(1, years + 1):+ growth = revenue_growth[year - 1] if year <= len(revenue_growth) else revenue_growth[-1]++ if year == 1:+ revenue = base_revenue * (1 + growth)+ else:+ revenue = financials[year - 1]['revenue'] * (1 + growth)++ ebitda = revenue * ebitda_margin++ depreciation = revenue * 0.03++ ebit = ebitda - depreciation++ interest = self.capital_structure.calculate_annual_interest_expense(year) if self.capital_structure else 0++ ebt = ebit - interest++ taxes = max(0, ebt * tax_rate)++ net_income = ebt - taxes++ capex = revenue * capex_pct++ if year == 1:+ nwc_change = revenue * nwc_pct+ else:+ nwc_change = (revenue - financials[year - 1]['revenue']) * nwc_pct++ fcf = ebitda - taxes - capex - nwc_change - interest++ financials[year] = {+ 'year': year,+ 'revenue': revenue,+ 'revenue_growth': growth * 100,+ 'ebitda': ebitda,+ 'ebitda_margin': ebitda_margin * 100,+ 'depreciation': depreciation,+ 'ebit': ebit,+ 'interest_expense': interest,+ 'ebt': ebt,+ 'taxes': taxes,+ 'net_income': net_income,+ 'capex': capex,+ 'nwc_change': nwc_change,+ 'free_cash_flow': fcf+ }++ return financials++ def _build_sensitivity_analysis(self, initial_equity: float, exit_year: int,+ ebitda_projection: List[float],+ debt_schedule: Dict[int, Dict[str, Any]]) -> Dict[str, Any]:+ """Build IRR sensitivity tables"""++ exit_ebitda_base = ebitda_projection[exit_year - 1]+ exit_debt = debt_schedule[exit_year]['total_debt_ending']++ ebitda_variations = [exit_ebitda_base * (1 + delta) for delta in [-0.20, -0.10, 0, 0.10, 0.20]]+ multiple_variations = [8.0, 9.0, 10.0, 11.0, 12.0, 13.0]++ irr_matrix = []+ moic_matrix = []++ for ebitda in ebitda_variations:+ irr_row = []+ moic_row = []++ for multiple in multiple_variations:+ exit_ev = ebitda * multiple+ exit_equity = max(0, exit_ev - exit_debt)++ returns = self.returns_calc.comprehensive_returns(initial_equity, exit_equity, exit_year)++ irr_row.append(returns['irr'])+ moic_row.append(returns['moic'])++ irr_matrix.append(irr_row)+ moic_matrix.append(moic_row)++ return {+ 'irr_sensitivity': {+ 'matrix': irr_matrix,+ 'ebitda_variations': ebitda_variations,+ 'multiple_variations': multiple_variations+ },+ 'moic_sensitivity': {+ 'matrix': moic_matrix,+ 'ebitda_variations': ebitda_variations,+ 'multiple_variations': multiple_variations+ }+ }++if __name__ == '__main__':+ target_company = {+ 'company_name': 'Target LBO Co',+ 'revenue': 3_000_000_000,+ 'ebitda': 625_000_000+ }++ assumptions = {+ 'entry_multiple': 8.0,+ 'target_leverage': 5.5,+ 'revenue_growth': [0.05, 0.06, 0.07, 0.07, 0.08],+ 'ebitda_margin': 0.25,+ 'capex_pct_revenue': 0.03,+ 'nwc_pct_revenue': 0.05,+ 'tax_rate': 0.21,+ 'exit_year': 5,+ 'exit_multiples': [9.0, 10.0, 11.0, 12.0],+ 'hurdle_irr': 0.20+ }++ model = LBOModel(target_company, assumptions)+ results = model.build_complete_model(projection_years=5)++ print("=== LBO MODEL RESULTS ===\n")+ print(f"Entry EV: ${results['transaction_summary']['entry_enterprise_value']:,.0f}")+ print(f"Entry Multiple: {results['transaction_summary']['entry_multiple']:.1f}x")+ print(f"Total Leverage: {results['capital_structure']['leverage_metrics']['debt_to_ebitda']:.2f}x\n")++ print("Returns by Exit Multiple:")+ for multiple, returns in results['returns_analysis'].items():+ print(f" {multiple:.1f}x: IRR {returns['irr']:.1f}% | MOIC {returns['moic']:.2f}x")++ print(f"\nDebt Paydown: ${results['debt_summary']['total_paydown']:,.0f} ({results['debt_summary']['paydown_percentage']:.1f}%)")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/returns_calculator.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/returns_calculator.pynew file mode 100644index 000000000..4b13f097b--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/lbo/returns_calculator.py@@ -0,0 +1,109 @@+"""Returns Calculator - IRR and MOIC"""+from typing import List, Dict, Any+import numpy as np++class ReturnsCalculator:+ """Calculate LBO returns metrics"""++ @staticmethod+ def calculate_irr(cash_flows: List[float]) -> float:+ """Calculate Internal Rate of Return"""+ try:+ irr = np.irr(cash_flows)+ return irr if not np.isnan(irr) else 0+ except:+ return 0++ @staticmethod+ def calculate_moic(initial_investment: float, exit_proceeds: float) -> float:+ """Calculate Multiple on Invested Capital"""+ if initial_investment <= 0:+ return 0+ return exit_proceeds / initial_investment++ @staticmethod+ def calculate_cash_on_cash(initial_equity: float, exit_equity_value: float,+ interim_distributions: float = 0) -> float:+ """Calculate cash-on-cash return"""+ if initial_equity <= 0:+ return 0++ total_cash_received = exit_equity_value + interim_distributions+ return total_cash_received / initial_equity++ def comprehensive_returns(self, initial_equity: float, exit_equity_value: float,+ holding_period_years: int,+ interim_distributions: List[float] = None) -> Dict[str, Any]:+ """Calculate comprehensive return metrics"""++ if interim_distributions is None:+ interim_distributions = []++ cash_flows = [-initial_equity] + interim_distributions + [exit_equity_value]++ irr = self.calculate_irr(cash_flows)+ moic = self.calculate_moic(initial_equity, exit_equity_value)+ coc = self.calculate_cash_on_cash(initial_equity, exit_equity_value, sum(interim_distributions))++ annualized_return = ((moic ** (1 / holding_period_years)) - 1) if holding_period_years > 0 else 0++ return {+ 'initial_equity_investment': initial_equity,+ 'exit_equity_value': exit_equity_value,+ 'holding_period_years': holding_period_years,+ 'irr': irr * 100,+ 'moic': moic,+ 'cash_on_cash_multiple': coc,+ 'annualized_return': annualized_return * 100,+ 'absolute_gain': exit_equity_value - initial_equity,+ 'absolute_gain_pct': ((exit_equity_value - initial_equity) / initial_equity * 100) if initial_equity else 0+ }++ def returns_by_exit_year(self, initial_equity: float, exit_values: Dict[int, float]) -> Dict[int, Dict[str, float]]:+ """Calculate returns for multiple exit scenarios"""++ returns_by_year = {}++ for year, exit_value in exit_values.items():+ returns = self.comprehensive_returns(initial_equity, exit_value, year)+ returns_by_year[year] = returns++ return returns_by_year++ def calculate_hurdle_metrics(self, returns: Dict[str, Any],+ hurdle_irr: float = 0.20) -> Dict[str, Any]:+ """Calculate excess returns vs hurdle rate"""++ actual_irr = returns['irr'] / 100+ excess_irr = actual_irr - hurdle_irr++ return {+ 'hurdle_irr': hurdle_irr * 100,+ 'actual_irr': returns['irr'],+ 'excess_irr': excess_irr * 100,+ 'meets_hurdle': actual_irr >= hurdle_irr,+ 'hurdle_moic': (1 + hurdle_irr) ** returns['holding_period_years'],+ 'actual_moic': returns['moic'],+ 'excess_moic': returns['moic'] - ((1 + hurdle_irr) ** returns['holding_period_years'])+ }++if __name__ == '__main__':+ calc = ReturnsCalculator()++ initial_equity = 1_500_000_000+ exit_equity = 4_200_000_000+ holding_period = 5++ returns = calc.comprehensive_returns(initial_equity, exit_equity, holding_period)++ print(f"Initial Investment: ${returns['initial_equity_investment']:,.0f}")+ print(f"Exit Value: ${returns['exit_equity_value']:,.0f}")+ print(f"Holding Period: {returns['holding_period_years']} years")+ print(f"\nIRR: {returns['irr']:.1f}%")+ print(f"MOIC: {returns['moic']:.2f}x")+ print(f"Absolute Gain: ${returns['absolute_gain']:,.0f} ({returns['absolute_gain_pct']:.1f}%)")++ hurdle = calc.calculate_hurdle_metrics(returns, hurdle_irr=0.20)+ print(f"\nHurdle IRR: {hurdle['hurdle_irr']:.1f}%")+ print(f"Excess IRR: {hurdle['excess_irr']:.1f}%")+ print(f"Meets Hurdle: {hurdle['meets_hurdle']}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/__init__.pynew file mode 100644index 000000000..880cb7549--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/__init__.py@@ -0,0 +1,8 @@+"""Merger Models Module - Accretion/Dilution Analysis"""+from .merger_model import MergerModel+from .sources_uses import SourcesUsesBuilder+from .pro_forma_builder import ProFormaBuilder+from .contribution_analysis import ContributionAnalyzer+from .sensitivity_analysis import SensitivityAnalyzer++__all__ = ['MergerModel', 'SourcesUsesBuilder', 'ProFormaBuilder', 'ContributionAnalyzer', 'SensitivityAnalyzer']diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/contribution_analysis.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/contribution_analysis.pynew file mode 100644index 000000000..96210e7fa--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/contribution_analysis.py@@ -0,0 +1,46 @@+"""Contribution Analysis for M&A"""+from typing import Dict, Any+from .pro_forma_builder import CompanyFinancials++class ContributionAnalyzer:+ """Analyze contributions from each party to combined entity"""++ def __init__(self, acquirer: CompanyFinancials, target: CompanyFinancials):+ self.acquirer = acquirer+ self.target = target++ def analyze_contributions(self, acquirer_shares: float,+ new_shares_issued: float) -> Dict[str, Any]:+ """Analyze financial and ownership contributions"""++ total_shares = acquirer_shares + new_shares_issued+ acquirer_ownership = acquirer_shares / total_shares * 100+ target_ownership = new_shares_issued / total_shares * 100++ combined_revenue = self.acquirer.revenue + self.target.revenue+ combined_ebitda = self.acquirer.ebitda + self.target.ebitda+ combined_net_income = self.acquirer.net_income + self.target.net_income+ combined_assets = self.acquirer.total_assets + self.target.total_assets++ return {+ 'ownership': {+ 'acquirer_pct': acquirer_ownership,+ 'target_pct': target_ownership+ },+ 'revenue_contribution': {+ 'acquirer_pct': (self.acquirer.revenue / combined_revenue * 100) if combined_revenue else 0,+ 'target_pct': (self.target.revenue / combined_revenue * 100) if combined_revenue else 0+ },+ 'ebitda_contribution': {+ 'acquirer_pct': (self.acquirer.ebitda / combined_ebitda * 100) if combined_ebitda else 0,+ 'target_pct': (self.target.ebitda / combined_ebitda * 100) if combined_ebitda else 0+ },+ 'net_income_contribution': {+ 'acquirer_pct': (self.acquirer.net_income / combined_net_income * 100) if combined_net_income else 0,+ 'target_pct': (self.target.net_income / combined_net_income * 100) if combined_net_income else 0+ },+ 'assets_contribution': {+ 'acquirer_pct': (self.acquirer.total_assets / combined_assets * 100) if combined_assets else 0,+ 'target_pct': (self.target.total_assets / combined_assets * 100) if combined_assets else 0+ }+ }diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/merger_model.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/merger_model.pynew file mode 100644index 000000000..4d7e70c2a--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/merger_model.py@@ -0,0 +1,252 @@+"""Complete Merger Model - Accretion/Dilution Analysis"""+from typing import Dict, Any, Optional+from .sources_uses import SourcesUsesBuilder+from .pro_forma_builder import ProFormaBuilder, CompanyFinancials+from .contribution_analysis import ContributionAnalyzer+from .sensitivity_analysis import SensitivityAnalyzer++class MergerModel:+ """Complete M&A merger model with accretion/dilution analysis"""++ def __init__(self, acquirer_data: Dict[str, Any], target_data: Dict[str, Any],+ deal_terms: Dict[str, Any]):++ self.acquirer_data = acquirer_data+ self.target_data = target_data+ self.deal_terms = deal_terms++ self.acquirer_financials = self._build_company_financials(acquirer_data)+ self.target_financials = self._build_company_financials(target_data)++ self.sources_uses = None+ self.pro_forma_builder = None+ self.contribution_analyzer = None+ self.sensitivity_analyzer = None++ def _build_company_financials(self, data: Dict[str, Any]) -> CompanyFinancials:+ """Build CompanyFinancials from dict"""++ return CompanyFinancials(+ revenue=data.get('revenue', 0),+ cogs=data.get('cogs', data.get('revenue', 0) * 0.6),+ gross_profit=data.get('gross_profit', data.get('revenue', 0) * 0.4),+ sg_a=data.get('sg_a', data.get('revenue', 0) * 0.2),+ r_d=data.get('r_d', 0),+ depreciation=data.get('depreciation', data.get('revenue', 0) * 0.03),+ ebitda=data.get('ebitda', 0),+ ebit=data.get('ebit', 0),+ interest_expense=data.get('interest_expense', 0),+ ebt=data.get('ebt', 0),+ taxes=data.get('taxes', 0),+ net_income=data.get('net_income', 0),+ shares_outstanding=data.get('shares_outstanding', 0),+ eps=data.get('eps', 0),+ total_assets=data.get('total_assets', 0),+ total_liabilities=data.get('total_liabilities', 0),+ shareholders_equity=data.get('shareholders_equity', 0),+ cash=data.get('cash', 0),+ debt=data.get('debt', 0)+ )++ def build_complete_model(self) -> Dict[str, Any]:+ """Build complete merger model"""++ purchase_price = self.deal_terms.get('purchase_price', 0)+ cash_consideration = self.deal_terms.get('cash_consideration', 0)+ stock_consideration = self.deal_terms.get('stock_consideration', 0)+ acquirer_stock_price = self.deal_terms.get('acquirer_stock_price', 0)++ cash_from_balance_sheet = min(cash_consideration, self.acquirer_financials.cash)+ new_debt_needed = max(0, cash_consideration - cash_from_balance_sheet)++ self.sources_uses = SourcesUsesBuilder(+ purchase_price=purchase_price,+ target_debt_refinanced=self.target_financials.debt,+ acquirer_cash=cash_from_balance_sheet,+ new_debt=new_debt_needed,+ new_equity=stock_consideration+ )++ self.sources_uses.estimate_transaction_fees(purchase_price)+ self.sources_uses.estimate_financing_fees(new_debt_needed)++ sources_uses_table = self.sources_uses.auto_balance()++ deal_structure = {+ 'new_debt': new_debt_needed,+ 'synergies': self.deal_terms.get('synergies', 0),+ 'integration_costs': self.deal_terms.get('integration_costs', 0),+ 'tax_rate': self.deal_terms.get('tax_rate', 0.21),+ 'acquirer_stock_price': acquirer_stock_price,+ 'stock_consideration': stock_consideration,+ 'debt_interest_rate': self.deal_terms.get('debt_interest_rate', 0.05),+ 'synergy_schedule': self.deal_terms.get('synergy_schedule', {+ 1: 0.25, 2: 0.50, 3: 0.75, 4: 1.00, 5: 1.00+ })+ }++ self.pro_forma_builder = ProFormaBuilder(+ self.acquirer_financials,+ self.target_financials,+ deal_structure+ )++ new_shares = self.pro_forma_builder.calculate_new_shares_issued(+ stock_consideration,+ acquirer_stock_price+ )++ goodwill = self.pro_forma_builder.calculate_goodwill(+ purchase_price,+ self.target_financials.shareholders_equity+ )++ accretion_dilution = self.pro_forma_builder.calculate_accretion_dilution()++ pf_year1 = self.pro_forma_builder.build_pro_forma_income_statement(year=1)+ pf_balance_sheet = self.pro_forma_builder.build_pro_forma_balance_sheet()++ multi_year_projections = self.pro_forma_builder.build_multi_year_projections(years=5)++ standalone_vs_pf = self.pro_forma_builder.compare_standalone_vs_proforma()++ breakeven_synergies = self.pro_forma_builder.calculate_breakeven_synergies()++ self.contribution_analyzer = ContributionAnalyzer(+ self.acquirer_financials,+ self.target_financials+ )++ contribution_analysis = self.contribution_analyzer.analyze_contributions(+ self.acquirer_financials.shares_outstanding,+ new_shares+ )++ self.sensitivity_analyzer = SensitivityAnalyzer(self.pro_forma_builder)++ synergy_sensitivity = self.sensitivity_analyzer.synergy_sensitivity(+ min_synergies=0,+ max_synergies=self.deal_terms.get('synergies', 0) * 2,+ steps=11+ )++ price_sensitivity = self.sensitivity_analyzer.purchase_price_sensitivity(+ base_price=purchase_price,+ price_range_pct=0.20,+ steps=11+ )++ return {+ 'deal_overview': {+ 'acquirer': self.acquirer_data.get('company_name', 'Acquirer'),+ 'target': self.target_data.get('company_name', 'Target'),+ 'purchase_price': purchase_price,+ 'cash_consideration': cash_consideration,+ 'stock_consideration': stock_consideration,+ 'payment_mix': {+ 'cash_pct': (cash_consideration / purchase_price * 100) if purchase_price else 0,+ 'stock_pct': (stock_consideration / purchase_price * 100) if purchase_price else 0+ }+ },+ 'sources_uses': sources_uses_table,+ 'new_shares_issued': new_shares,+ 'goodwill': goodwill,+ 'accretion_dilution': accretion_dilution,+ 'pro_forma_year1': pf_year1,+ 'pro_forma_balance_sheet': pf_balance_sheet,+ 'multi_year_projections': multi_year_projections,+ 'standalone_vs_proforma': standalone_vs_pf,+ 'breakeven_synergies': breakeven_synergies,+ 'contribution_analysis': contribution_analysis,+ 'sensitivity_analysis': {+ 'synergies': synergy_sensitivity,+ 'purchase_price': price_sensitivity+ }+ }++ def generate_executive_summary(self) -> Dict[str, Any]:+ """Generate executive summary of merger model"""++ model_results = self.build_complete_model()++ ad = model_results['accretion_dilution']+ pf_y1 = model_results['pro_forma_year1']++ summary = {+ 'deal_snapshot': {+ 'acquirer': model_results['deal_overview']['acquirer'],+ 'target': model_results['deal_overview']['target'],+ 'purchase_price': model_results['deal_overview']['purchase_price'],+ 'payment_structure': model_results['deal_overview']['payment_mix']+ },+ 'financial_impact': {+ 'eps_impact': f"{ad['accretion_dilution_pct']:.1f}% {ad['status']}",+ 'standalone_eps': ad['standalone_eps'],+ 'pro_forma_eps': ad['pro_forma_eps'],+ 'pro_forma_revenue': pf_y1['revenue'],+ 'pro_forma_ebitda': pf_y1['ebitda'],+ 'pro_forma_net_income': pf_y1['net_income']+ },+ 'key_assumptions': {+ 'synergies': self.deal_terms.get('synergies', 0),+ 'integration_costs': self.deal_terms.get('integration_costs', 0),+ 'new_debt': model_results['sources_uses']['sources']['sources_breakdown']['new_debt']['amount'],+ 'new_shares_issued': model_results['new_shares_issued']+ },+ 'breakeven_analysis': {+ 'breakeven_synergies': model_results['breakeven_synergies'],+ 'synergies_cushion': self.deal_terms.get('synergies', 0) - model_results['breakeven_synergies']+ }+ }++ return summary++if __name__ == '__main__':+ acquirer = {+ 'company_name': 'Acquirer Corp',+ 'revenue': 10_000_000_000,+ 'ebitda': 1_500_000_000,+ 'net_income': 869_000_000,+ 'shares_outstanding': 500_000_000,+ 'eps': 1.738,+ 'cash': 2_000_000_000,+ 'debt': 3_000_000_000+ }++ target = {+ 'company_name': 'Target Inc',+ 'revenue': 2_000_000_000,+ 'ebitda': 300_000_000,+ 'net_income': 173_800_000,+ 'shares_outstanding': 100_000_000,+ 'eps': 1.738,+ 'cash': 300_000_000,+ 'debt': 500_000_000+ }++ deal_terms = {+ 'purchase_price': 3_000_000_000,+ 'cash_consideration': 1_500_000_000,+ 'stock_consideration': 1_500_000_000,+ 'acquirer_stock_price': 50.0,+ 'synergies': 150_000_000,+ 'integration_costs': 75_000_000,+ 'debt_interest_rate': 0.045+ }++ model = MergerModel(acquirer, target, deal_terms)+ results = model.build_complete_model()++ print("=== MERGER MODEL RESULTS ===\n")+ print(f"Purchase Price: ${results['deal_overview']['purchase_price']:,.0f}")+ print(f"Payment Mix: {results['deal_overview']['payment_mix']['cash_pct']:.0f}% Cash / "+ f"{results['deal_overview']['payment_mix']['stock_pct']:.0f}% Stock\n")++ ad = results['accretion_dilution']+ print(f"EPS Impact: {ad['accretion_dilution_pct']:.2f}% {ad['status']}")+ print(f" Standalone EPS: ${ad['standalone_eps']:.2f}")+ print(f" Pro Forma EPS: ${ad['pro_forma_eps']:.2f}\n")++ print(f"Breakeven Synergies: ${results['breakeven_synergies']:,.0f}")+ print(f"Assumed Synergies: ${deal_terms['synergies']:,.0f}")+ print(f"Cushion: ${deal_terms['synergies'] - results['breakeven_synergies']:,.0f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/pro_forma_builder.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/pro_forma_builder.pynew file mode 100644index 000000000..258a91b30--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/pro_forma_builder.py@@ -0,0 +1,322 @@+"""Pro Forma Financial Statement Builder"""+from typing import Dict, Any, List, Optional+from dataclasses import dataclass+import numpy as np++@dataclass+class CompanyFinancials:+ """Company financial data structure"""+ revenue: float+ cogs: float+ gross_profit: float+ sg_a: float+ r_d: float+ depreciation: float+ ebitda: float+ ebit: float+ interest_expense: float+ ebt: float+ taxes: float+ net_income: float+ shares_outstanding: float+ eps: float++ total_assets: float = 0+ total_liabilities: float = 0+ shareholders_equity: float = 0+ cash: float = 0+ debt: float = 0++class ProFormaBuilder:+ """Build pro forma combined financial statements"""++ def __init__(self, acquirer_financials: CompanyFinancials,+ target_financials: CompanyFinancials,+ deal_structure: Dict[str, Any]):++ self.acquirer = acquirer_financials+ self.target = target_financials+ self.deal_structure = deal_structure++ self.new_shares_issued = 0+ self.new_debt = deal_structure.get('new_debt', 0)+ self.synergies = deal_structure.get('synergies', 0)+ self.integration_costs = deal_structure.get('integration_costs', 0)+ self.goodwill = 0+ self.purchase_price_allocation = {}++ def calculate_new_shares_issued(self, stock_consideration: float,+ acquirer_stock_price: float) -> float:+ """Calculate new shares to be issued"""++ self.new_shares_issued = stock_consideration / acquirer_stock_price+ return self.new_shares_issued++ def calculate_goodwill(self, purchase_price: float,+ target_book_value: float,+ fair_value_adjustments: float = 0) -> float:+ """Calculate goodwill from acquisition"""++ fair_value_net_assets = target_book_value + fair_value_adjustments+ self.goodwill = purchase_price - fair_value_net_assets++ return self.goodwill++ def build_pro_forma_income_statement(self, year: int = 1) -> Dict[str, float]:+ """Build pro forma income statement"""++ synergy_realization = self._get_synergy_realization(year)+ integration_cost_impact = self._get_integration_cost(year)++ pf_revenue = self.acquirer.revenue + self.target.revenue+ pf_cogs = self.acquirer.cogs + self.target.cogs+ pf_gross_profit = pf_revenue - pf_cogs++ pf_sg_a = self.acquirer.sg_a + self.target.sg_a - (synergies * synergy_realization * 0.6)+ pf_r_d = self.acquirer.r_d + self.target.r_d+ pf_depreciation = self.acquirer.depreciation + self.target.depreciation++ pf_ebitda = pf_gross_profit - pf_sg_a - pf_r_d + integration_cost_impact+ pf_ebit = pf_ebitda - pf_depreciation++ incremental_interest = self._calculate_incremental_interest()+ pf_interest_expense = self.acquirer.interest_expense + self.target.interest_expense + incremental_interest++ pf_ebt = pf_ebit - pf_interest_expense++ tax_rate = self.deal_structure.get('tax_rate', 0.21)+ pf_taxes = pf_ebt * tax_rate if pf_ebt > 0 else 0++ pf_net_income = pf_ebt - pf_taxes++ pf_shares = self.acquirer.shares_outstanding + self.new_shares_issued+ pf_eps = pf_net_income / pf_shares if pf_shares else 0++ return {+ 'revenue': pf_revenue,+ 'cogs': pf_cogs,+ 'gross_profit': pf_gross_profit,+ 'gross_margin': (pf_gross_profit / pf_revenue * 100) if pf_revenue else 0,+ 'sg_a': pf_sg_a,+ 'r_d': pf_r_d,+ 'depreciation': pf_depreciation,+ 'ebitda': pf_ebitda,+ 'ebitda_margin': (pf_ebitda / pf_revenue * 100) if pf_revenue else 0,+ 'ebit': pf_ebit,+ 'interest_expense': pf_interest_expense,+ 'ebt': pf_ebt,+ 'taxes': pf_taxes,+ 'effective_tax_rate': (pf_taxes / pf_ebt * 100) if pf_ebt else 0,+ 'net_income': pf_net_income,+ 'net_margin': (pf_net_income / pf_revenue * 100) if pf_revenue else 0,+ 'shares_outstanding': pf_shares,+ 'eps': pf_eps,+ 'synergies_realized': synergies * synergy_realization,+ 'integration_costs': integration_cost_impact+ }++ def build_pro_forma_balance_sheet(self) -> Dict[str, float]:+ """Build pro forma balance sheet"""++ pf_cash = self.acquirer.cash + self.target.cash - self.deal_structure.get('cash_used', 0)+ pf_total_assets = self.acquirer.total_assets + self.target.total_assets + self.goodwill++ pf_debt = self.acquirer.debt + self.target.debt + self.new_debt+ pf_total_liabilities = self.acquirer.total_liabilities + self.target.total_liabilities + self.new_debt++ equity_issuance = self.new_shares_issued * self.deal_structure.get('acquirer_stock_price', 0)+ pf_shareholders_equity = (self.acquirer.shareholders_equity ++ equity_issuance ++ self.target.shareholders_equity)++ return {+ 'cash': pf_cash,+ 'total_assets': pf_total_assets,+ 'goodwill': self.goodwill,+ 'total_debt': pf_debt,+ 'total_liabilities': pf_total_liabilities,+ 'shareholders_equity': pf_shareholders_equity,+ 'debt_to_equity': pf_debt / pf_shareholders_equity if pf_shareholders_equity else 0,+ 'equity_to_assets': pf_shareholders_equity / pf_total_assets if pf_total_assets else 0+ }++ def build_multi_year_projections(self, years: int = 5) -> Dict[int, Dict[str, float]]:+ """Build multi-year pro forma projections"""++ projections = {}++ for year in range(1, years + 1):+ projections[year] = self.build_pro_forma_income_statement(year)++ return projections++ def _get_synergy_realization(self, year: int) -> float:+ """Get synergy realization percentage by year"""++ realization_schedule = self.deal_structure.get('synergy_schedule', {+ 1: 0.25,+ 2: 0.50,+ 3: 0.75,+ 4: 1.00,+ 5: 1.00+ })++ return realization_schedule.get(year, 1.0)++ def _get_integration_cost(self, year: int) -> float:+ """Get integration cost impact by year"""++ if year == 1:+ return -self.integration_costs+ elif year == 2:+ return -self.integration_costs * 0.5+ else:+ return 0++ def _calculate_incremental_interest(self) -> float:+ """Calculate incremental interest expense from new debt"""++ interest_rate = self.deal_structure.get('debt_interest_rate', 0.05)+ return self.new_debt * interest_rate++ def calculate_accretion_dilution(self) -> Dict[str, Any]:+ """Calculate EPS accretion/dilution"""++ standalone_acquirer_eps = self.acquirer.eps++ pf_year1 = self.build_pro_forma_income_statement(year=1)+ pf_eps = pf_year1['eps']++ eps_change = pf_eps - standalone_acquirer_eps+ accretion_dilution_pct = (eps_change / standalone_acquirer_eps * 100) if standalone_acquirer_eps else 0++ is_accretive = eps_change > 0++ return {+ 'standalone_eps': standalone_acquirer_eps,+ 'pro_forma_eps': pf_eps,+ 'eps_change': eps_change,+ 'accretion_dilution_pct': accretion_dilution_pct,+ 'is_accretive': is_accretive,+ 'status': 'Accretive' if is_accretive else 'Dilutive'+ }++ def calculate_breakeven_synergies(self) -> float:+ """Calculate synergies needed for EPS neutral deal"""++ original_synergies = self.synergies+ low, high = 0, original_synergies * 5++ while high - low > 0.01e6:+ mid = (low + high) / 2+ self.synergies = mid++ result = self.calculate_accretion_dilution()++ if result['eps_change'] < 0:+ low = mid+ else:+ high = mid++ breakeven = (low + high) / 2+ self.synergies = original_synergies++ return breakeven++ def compare_standalone_vs_proforma(self) -> Dict[str, Any]:+ """Compare standalone vs pro forma metrics"""++ pf_is = self.build_pro_forma_income_statement()++ combined_standalone_revenue = self.acquirer.revenue + self.target.revenue+ combined_standalone_ni = self.acquirer.net_income + self.target.net_income+ combined_standalone_ebitda = self.acquirer.ebitda + self.target.ebitda++ return {+ 'revenue': {+ 'standalone_combined': combined_standalone_revenue,+ 'pro_forma': pf_is['revenue'],+ 'difference': pf_is['revenue'] - combined_standalone_revenue,+ 'difference_pct': ((pf_is['revenue'] - combined_standalone_revenue) /+ combined_standalone_revenue * 100) if combined_standalone_revenue else 0+ },+ 'net_income': {+ 'standalone_combined': combined_standalone_ni,+ 'pro_forma': pf_is['net_income'],+ 'difference': pf_is['net_income'] - combined_standalone_ni,+ 'difference_pct': ((pf_is['net_income'] - combined_standalone_ni) /+ combined_standalone_ni * 100) if combined_standalone_ni else 0+ },+ 'ebitda': {+ 'standalone_combined': combined_standalone_ebitda,+ 'pro_forma': pf_is['ebitda'],+ 'difference': pf_is['ebitda'] - combined_standalone_ebitda,+ 'difference_pct': ((pf_is['ebitda'] - combined_standalone_ebitda) /+ combined_standalone_ebitda * 100) if combined_standalone_ebitda else 0+ }+ }++if __name__ == '__main__':+ acquirer = CompanyFinancials(+ revenue=10_000_000_000,+ cogs=6_000_000_000,+ gross_profit=4_000_000_000,+ sg_a=2_000_000_000,+ r_d=500_000_000,+ depreciation=300_000_000,+ ebitda=1_500_000_000,+ ebit=1_200_000_000,+ interest_expense=100_000_000,+ ebt=1_100_000_000,+ taxes=231_000_000,+ net_income=869_000_000,+ shares_outstanding=500_000_000,+ eps=1.738,+ total_assets=15_000_000_000,+ total_liabilities=8_000_000_000,+ shareholders_equity=7_000_000_000,+ cash=2_000_000_000,+ debt=3_000_000_000+ )++ target = CompanyFinancials(+ revenue=2_000_000_000,+ cogs=1_200_000_000,+ gross_profit=800_000_000,+ sg_a=400_000_000,+ r_d=100_000_000,+ depreciation=60_000_000,+ ebitda=300_000_000,+ ebit=240_000_000,+ interest_expense=20_000_000,+ ebt=220_000_000,+ taxes=46_200_000,+ net_income=173_800_000,+ shares_outstanding=100_000_000,+ eps=1.738,+ total_assets=3_000_000_000,+ total_liabilities=1_500_000_000,+ shareholders_equity=1_500_000_000,+ cash=300_000_000,+ debt=500_000_000+ )++ deal_structure = {+ 'new_debt': 2_000_000_000,+ 'synergies': 100_000_000,+ 'integration_costs': 50_000_000,+ 'tax_rate': 0.21,+ 'acquirer_stock_price': 50.0,+ 'stock_consideration': 1_000_000_000+ }++ builder = ProFormaBuilder(acquirer, target, deal_structure)+ builder.calculate_new_shares_issued(1_000_000_000, 50.0)++ result = builder.calculate_accretion_dilution()+ print(f"Standalone EPS: ${result['standalone_eps']:.2f}")+ print(f"Pro Forma EPS: ${result['pro_forma_eps']:.2f}")+ print(f"Impact: {result['accretion_dilution_pct']:.1f}% {result['status']}")++ breakeven = builder.calculate_breakeven_synergies()+ print(f"\nBreakeven Synergies: ${breakeven:,.0f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/sensitivity_analysis.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/sensitivity_analysis.pynew file mode 100644index 000000000..3d3df0f15--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/sensitivity_analysis.py@@ -0,0 +1,98 @@+"""Sensitivity Analysis for Merger Models"""+from typing import Dict, Any, List+import numpy as np+from .pro_forma_builder import ProFormaBuilder++class SensitivityAnalyzer:+ """Perform sensitivity analysis on merger model assumptions"""++ def __init__(self, pro_forma_builder: ProFormaBuilder):+ self.builder = pro_forma_builder+ self.original_synergies = pro_forma_builder.synergies+ self.original_integration_costs = pro_forma_builder.integration_costs++ def synergy_sensitivity(self, min_synergies: float, max_synergies: float,+ steps: int = 11) -> Dict[str, Any]:+ """Analyze EPS sensitivity to synergy assumptions"""++ synergy_values = np.linspace(min_synergies, max_synergies, steps)+ results = []++ for synergy in synergy_values:+ self.builder.synergies = synergy+ ad_result = self.builder.calculate_accretion_dilution()++ results.append({+ 'synergies': synergy,+ 'pro_forma_eps': ad_result['pro_forma_eps'],+ 'accretion_dilution_pct': ad_result['accretion_dilution_pct']+ })++ self.builder.synergies = self.original_synergies++ return {+ 'sensitivity_data': results,+ 'synergy_range': [min_synergies, max_synergies],+ 'base_case': self.original_synergies+ }++ def purchase_price_sensitivity(self, base_price: float, price_range_pct: float = 0.20,+ steps: int = 11) -> Dict[str, Any]:+ """Analyze EPS sensitivity to purchase price"""++ min_price = base_price * (1 - price_range_pct)+ max_price = base_price * (1 + price_range_pct)+ prices = np.linspace(min_price, max_price, steps)++ results = []++ for price in prices:+ goodwill_adjustment = price - base_price+ original_goodwill = self.builder.goodwill++ self.builder.goodwill = original_goodwill + goodwill_adjustment++ ad_result = self.builder.calculate_accretion_dilution()++ results.append({+ 'purchase_price': price,+ 'pro_forma_eps': ad_result['pro_forma_eps'],+ 'accretion_dilution_pct': ad_result['accretion_dilution_pct']+ })++ self.builder.goodwill = original_goodwill++ return {+ 'sensitivity_data': results,+ 'price_range': [min_price, max_price],+ 'base_case': base_price+ }++ def two_way_sensitivity(self, var1_name: str, var1_range: List[float],+ var2_name: str, var2_range: List[float]) -> Dict[str, Any]:+ """Two-way sensitivity table"""++ matrix = []++ for v1 in var1_range:+ row = []+ for v2 in var2_range:+ if var1_name == 'synergies':+ self.builder.synergies = v1+ if var2_name == 'synergies':+ self.builder.synergies = v2++ ad_result = self.builder.calculate_accretion_dilution()+ row.append(ad_result['accretion_dilution_pct'])++ matrix.append(row)++ self.builder.synergies = self.original_synergies++ return {+ 'matrix': matrix,+ 'var1_name': var1_name,+ 'var1_range': var1_range,+ 'var2_name': var2_name,+ 'var2_range': var2_range+ }diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/sources_uses.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/sources_uses.pynew file mode 100644index 000000000..1d4cabc11--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/merger_models/sources_uses.py@@ -0,0 +1,236 @@+"""Sources & Uses of Funds Analysis"""+from typing import Dict, Any, List, Optional+from dataclasses import dataclass, field++@dataclass+class SourcesUsesBuilder:+ """Build sources and uses of funds for M&A transaction"""++ purchase_price: float+ target_debt_refinanced: float = 0+ transaction_fees: float = 0+ financing_fees: float = 0+ other_uses: float = 0++ acquirer_cash: float = 0+ new_debt: float = 0+ new_equity: float = 0+ rollover_equity: float = 0+ other_sources: float = 0++ def calculate_uses(self) -> Dict[str, Any]:+ """Calculate total uses of funds"""++ uses = {+ 'purchase_price': self.purchase_price,+ 'target_debt_refinanced': self.target_debt_refinanced,+ 'transaction_fees': self.transaction_fees,+ 'financing_fees': self.financing_fees,+ 'other_uses': self.other_uses+ }++ total_uses = sum(uses.values())++ uses_breakdown = {+ item: {+ 'amount': amount,+ 'percentage': (amount / total_uses * 100) if total_uses else 0+ }+ for item, amount in uses.items()+ }++ return {+ 'uses_breakdown': uses_breakdown,+ 'total_uses': total_uses+ }++ def calculate_sources(self) -> Dict[str, Any]:+ """Calculate total sources of funds"""++ sources = {+ 'acquirer_cash': self.acquirer_cash,+ 'new_debt': self.new_debt,+ 'new_equity': self.new_equity,+ 'rollover_equity': self.rollover_equity,+ 'other_sources': self.other_sources+ }++ total_sources = sum(sources.values())++ sources_breakdown = {+ item: {+ 'amount': amount,+ 'percentage': (amount / total_sources * 100) if total_sources else 0+ }+ for item, amount in sources.items()+ }++ return {+ 'sources_breakdown': sources_breakdown,+ 'total_sources': total_sources+ }++ def build_sources_uses_table(self) -> Dict[str, Any]:+ """Build complete sources & uses table"""++ uses = self.calculate_uses()+ sources = self.calculate_sources()++ imbalance = sources['total_sources'] - uses['total_uses']+ balanced = abs(imbalance) < 0.01++ return {+ 'uses': uses,+ 'sources': sources,+ 'balanced': balanced,+ 'imbalance': imbalance+ }++ def auto_balance(self, method: str = 'cash') -> Dict[str, Any]:+ """Auto-balance sources and uses"""++ uses = self.calculate_uses()+ sources = self.calculate_sources()++ imbalance = sources['total_sources'] - uses['total_uses']++ if abs(imbalance) < 0.01:+ return self.build_sources_uses_table()++ if imbalance < 0:+ shortfall = abs(imbalance)+ if method == 'cash':+ self.acquirer_cash += shortfall+ elif method == 'debt':+ self.new_debt += shortfall+ elif method == 'equity':+ self.new_equity += shortfall+ else:+ excess = imbalance+ if method == 'cash' and self.acquirer_cash >= excess:+ self.acquirer_cash -= excess+ elif method == 'debt' and self.new_debt >= excess:+ self.new_debt -= excess++ return self.build_sources_uses_table()++ def calculate_financing_mix(self) -> Dict[str, float]:+ """Calculate debt/equity financing mix"""++ total_financing = self.new_debt + self.new_equity++ if total_financing == 0:+ return {+ 'debt_percentage': 0,+ 'equity_percentage': 0,+ 'cash_percentage': 100,+ 'debt_to_equity': 0+ }++ debt_pct = (self.new_debt / total_financing) * 100+ equity_pct = (self.new_equity / total_financing) * 100+ cash_pct = (self.acquirer_cash / (total_financing + self.acquirer_cash)) * 100++ debt_to_equity = self.new_debt / self.new_equity if self.new_equity else float('inf')++ return {+ 'debt_percentage': debt_pct,+ 'equity_percentage': equity_pct,+ 'cash_percentage': cash_pct,+ 'debt_to_equity': debt_to_equity,+ 'total_financing': total_financing+ }++ def estimate_transaction_fees(self, deal_value: float, fee_structure: Optional[Dict[str, float]] = None) -> float:+ """Estimate transaction fees"""++ if fee_structure is None:+ fee_structure = {+ 'financial_advisory': 0.01,+ 'legal': 0.003,+ 'accounting': 0.001,+ 'other': 0.001+ }++ total_fees = sum(+ deal_value * rate+ for rate in fee_structure.values()+ )++ self.transaction_fees = total_fees+ return total_fees++ def estimate_financing_fees(self, debt_amount: float, fee_rate: float = 0.02) -> float:+ """Estimate debt financing fees"""++ financing_fees = debt_amount * fee_rate+ self.financing_fees = financing_fees+ return financing_fees++@dataclass+class DetailedSourcesUses(SourcesUsesBuilder):+ """Extended sources & uses with detailed breakdown"""++ advisory_fees: Dict[str, float] = field(default_factory=dict)+ legal_fees: Dict[str, float] = field(default_factory=dict)+ debt_tranches: Dict[str, float] = field(default_factory=dict)+ equity_issuances: Dict[str, float] = field(default_factory=dict)++ def add_advisory_fee(self, advisor: str, fee: float):+ """Add financial advisory fee"""+ self.advisory_fees[advisor] = fee+ self.transaction_fees = sum(self.advisory_fees.values())++ def add_debt_tranche(self, tranche_name: str, amount: float):+ """Add debt tranche"""+ self.debt_tranches[tranche_name] = amount+ self.new_debt = sum(self.debt_tranches.values())++ def add_equity_issuance(self, issuance_type: str, amount: float):+ """Add equity issuance"""+ self.equity_issuances[issuance_type] = amount+ self.new_equity = sum(self.equity_issuances.values())++ def detailed_breakdown(self) -> Dict[str, Any]:+ """Get detailed breakdown of all items"""++ base_table = self.build_sources_uses_table()++ base_table['detailed_fees'] = {+ 'advisory': self.advisory_fees,+ 'legal': self.legal_fees,+ 'total_transaction_fees': self.transaction_fees+ }++ base_table['detailed_financing'] = {+ 'debt_tranches': self.debt_tranches,+ 'equity_issuances': self.equity_issuances,+ 'total_debt': self.new_debt,+ 'total_equity': self.new_equity+ }++ return base_table++if __name__ == '__main__':+ builder = SourcesUsesBuilder(+ purchase_price=5_000_000_000,+ target_debt_refinanced=500_000_000,+ acquirer_cash=2_000_000_000,+ new_debt=2_500_000_000,+ new_equity=1_000_000_000+ )++ builder.estimate_transaction_fees(5_000_000_000)+ builder.estimate_financing_fees(2_500_000_000)++ table = builder.auto_balance()++ print(f"Total Uses: ${table['uses']['total_uses']:,.0f}")+ print(f"Total Sources: ${table['sources']['total_sources']:,.0f}")+ print(f"Balanced: {table['balanced']}")++ financing_mix = builder.calculate_financing_mix()+ print(f"\nFinancing Mix:")+ print(f" Debt: {financing_mix['debt_percentage']:.1f}%")+ print(f" Equity: {financing_mix['equity_percentage']:.1f}%")+ print(f" Cash: {financing_mix['cash_percentage']:.1f}%")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/__init__.pynew file mode 100644index 000000000..219328b86--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/__init__.py@@ -0,0 +1,8 @@+"""Startup Valuation Module"""+from .berkus_method import BerkusMethod+from .scorecard_method import ScorecardMethod+from .vc_method import VCMethod+from .first_chicago_method import FirstChicagoMethod+from .risk_factor_summation import RiskFactorSummation++__all__ = ['BerkusMethod', 'ScorecardMethod', 'VCMethod', 'FirstChicagoMethod', 'RiskFactorSummation']diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/berkus_method.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/berkus_method.pynew file mode 100644index 000000000..350ac2ea2--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/berkus_method.py@@ -0,0 +1,152 @@+"""Berkus Method - Pre-Revenue Startup Valuation"""+from typing import Dict, Any+from enum import Enum++class BerkusFactor(Enum):+ """Five key value factors in Berkus Method"""+ SOUND_IDEA = "sound_idea"+ PROTOTYPE = "prototype"+ QUALITY_MANAGEMENT = "quality_management"+ STRATEGIC_RELATIONSHIPS = "strategic_relationships"+ PRODUCT_ROLLOUT = "product_rollout"++class BerkusMethod:+ """Berkus Method for pre-revenue startup valuation"""++ def __init__(self, max_value_per_factor: float = 500_000):+ self.max_value = max_value_per_factor+ self.max_total_valuation = max_value_per_factor * 5++ self.factor_descriptions = {+ BerkusFactor.SOUND_IDEA: "Basic value, viable idea with significant market opportunity",+ BerkusFactor.PROTOTYPE: "Technology risk reduced through working prototype/product",+ BerkusFactor.QUALITY_MANAGEMENT: "Strong management team with relevant experience",+ BerkusFactor.STRATEGIC_RELATIONSHIPS: "Strategic alliances, partnerships, or customer commitments",+ BerkusFactor.PRODUCT_ROLLOUT: "Evidence of market acceptance, initial sales or validation"+ }++ def assess_factor(self, factor: BerkusFactor, score: float) -> float:+ """+ Assess single factor value++ Args:+ factor: BerkusFactor enum+ score: 0-1 score (0 = none, 0.5 = moderate, 1 = excellent)++ Returns:+ Dollar value for this factor+ """+ if not 0 <= score <= 1:+ raise ValueError("Score must be between 0 and 1")++ return self.max_value * score++ def calculate_valuation(self, factor_scores: Dict[BerkusFactor, float]) -> Dict[str, Any]:+ """+ Calculate total startup valuation using Berkus Method++ Args:+ factor_scores: Dict mapping BerkusFactor to score (0-1)++ Returns:+ Valuation breakdown and total+ """++ factor_values = {}+ total_valuation = 0++ for factor in BerkusFactor:+ score = factor_scores.get(factor, 0)+ value = self.assess_factor(factor, score)+ factor_values[factor.value] = {+ 'score': score,+ 'value': value,+ 'max_value': self.max_value,+ 'description': self.factor_descriptions[factor]+ }+ total_valuation += value++ return {+ 'method': 'Berkus Method',+ 'factor_assessments': factor_values,+ 'total_valuation': total_valuation,+ 'max_possible_valuation': self.max_total_valuation,+ 'valuation_percentage': (total_valuation / self.max_total_valuation * 100)+ }++ def quick_assessment(self, idea_score: float, prototype_score: float,+ team_score: float, relationships_score: float,+ rollout_score: float) -> Dict[str, Any]:+ """Quick valuation with direct scores"""++ factor_scores = {+ BerkusFactor.SOUND_IDEA: idea_score,+ BerkusFactor.PROTOTYPE: prototype_score,+ BerkusFactor.QUALITY_MANAGEMENT: team_score,+ BerkusFactor.STRATEGIC_RELATIONSHIPS: relationships_score,+ BerkusFactor.PRODUCT_ROLLOUT: rollout_score+ }++ return self.calculate_valuation(factor_scores)++ def guided_assessment(self) -> Dict[str, Any]:+ """Interactive guided assessment with questions"""++ assessment_questions = {+ BerkusFactor.SOUND_IDEA: [+ "Is the market opportunity large (>$1B)?",+ "Is the problem clearly defined and significant?",+ "Is the solution innovative and defensible?"+ ],+ BerkusFactor.PROTOTYPE: [+ "Does a working prototype exist?",+ "Has the technology been validated?",+ "Are key technical risks mitigated?"+ ],+ BerkusFactor.QUALITY_MANAGEMENT: [+ "Does the team have relevant industry experience?",+ "Have founders successfully built companies before?",+ "Is the team complete with necessary skills?"+ ],+ BerkusFactor.STRATEGIC_RELATIONSHIPS: [+ "Are there signed LOIs or partnerships?",+ "Does the startup have strategic investors?",+ "Are there channel partners committed?"+ ],+ BerkusFactor.PRODUCT_ROLLOUT: [+ "Is there evidence of product-market fit?",+ "Are there paying customers or users?",+ "Is there positive market feedback?"+ ]+ }++ return {+ 'method': 'Berkus Method - Guided Assessment',+ 'assessment_framework': assessment_questions,+ 'scoring_guide': {+ '0.0-0.2': 'None/Minimal',+ '0.2-0.4': 'Weak',+ '0.4-0.6': 'Moderate',+ '0.6-0.8': 'Strong',+ '0.8-1.0': 'Excellent'+ }+ }++if __name__ == '__main__':+ berkus = BerkusMethod(max_value_per_factor=500_000)++ valuation = berkus.quick_assessment(+ idea_score=0.8,+ prototype_score=0.6,+ team_score=0.9,+ relationships_score=0.4,+ rollout_score=0.3+ )++ print(f"=== BERKUS METHOD VALUATION ===\n")+ print(f"Total Valuation: ${valuation['total_valuation']:,.0f}")+ print(f"Percentage of Max: {valuation['valuation_percentage']:.1f}%\n")++ print("Factor Breakdown:")+ for factor, data in valuation['factor_assessments'].items():+ print(f" {factor.replace('_', ' ').title()}: ${data['value']:,.0f} (score: {data['score']:.1f})")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/first_chicago_method.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/first_chicago_method.pynew file mode 100644index 000000000..955d2460f--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/first_chicago_method.py@@ -0,0 +1,227 @@+"""First Chicago Method - Scenario-Based Valuation"""+from typing import Dict, Any, List+from dataclasses import dataclass++@dataclass+class Scenario:+ """Valuation scenario"""+ name: str+ probability: float+ exit_year: int+ exit_value: float+ description: str++class FirstChicagoMethod:+ """First Chicago Method for scenario-based startup valuation"""++ def __init__(self):+ self.discount_rate = 0.40++ def create_scenario(self, name: str, probability: float,+ exit_year: int, exit_value: float,+ description: str = "") -> Scenario:+ """Create valuation scenario"""++ if not 0 <= probability <= 1:+ raise ValueError("Probability must be between 0 and 1")++ return Scenario(name, probability, exit_year, exit_value, description)++ def discount_to_present(self, future_value: float, years: int,+ discount_rate: Optional[float] = None) -> float:+ """Discount future value to present"""++ rate = discount_rate or self.discount_rate+ return future_value / ((1 + rate) ** years)++ def calculate_expected_value(self, scenarios: List[Scenario],+ discount_rate: Optional[float] = None) -> Dict[str, Any]:+ """Calculate probability-weighted expected value"""++ rate = discount_rate or self.discount_rate++ total_probability = sum(s.probability for s in scenarios)+ if abs(total_probability - 1.0) > 0.01:+ raise ValueError(f"Probabilities must sum to 1.0, got {total_probability}")++ scenario_details = []+ weighted_pv_sum = 0++ for scenario in scenarios:+ pv = self.discount_to_present(scenario.exit_value, scenario.exit_year, rate)+ weighted_pv = pv * scenario.probability++ weighted_pv_sum += weighted_pv++ scenario_details.append({+ 'name': scenario.name,+ 'probability': scenario.probability * 100,+ 'exit_year': scenario.exit_year,+ 'exit_value': scenario.exit_value,+ 'present_value': pv,+ 'weighted_present_value': weighted_pv,+ 'description': scenario.description+ })++ return {+ 'method': 'First Chicago Method',+ 'scenarios': scenario_details,+ 'discount_rate': rate * 100,+ 'expected_present_value': weighted_pv_sum,+ 'valuation': weighted_pv_sum+ }++ def three_scenario_valuation(self, best_case: Dict[str, Any],+ base_case: Dict[str, Any],+ worst_case: Dict[str, Any],+ probabilities: Optional[Dict[str, float]] = None) -> Dict[str, Any]:+ """+ Standard three-scenario valuation++ Args:+ best_case: {'exit_value': float, 'exit_year': int, 'description': str}+ base_case: {...}+ worst_case: {...}+ probabilities: Optional custom probabilities (default: 20%, 50%, 30%)++ Returns:+ Expected valuation+ """++ if probabilities is None:+ probabilities = {'best': 0.20, 'base': 0.50, 'worst': 0.30}++ scenarios = [+ self.create_scenario(+ 'Best Case',+ probabilities['best'],+ best_case['exit_year'],+ best_case['exit_value'],+ best_case.get('description', '')+ ),+ self.create_scenario(+ 'Base Case',+ probabilities['base'],+ base_case['exit_year'],+ base_case['exit_value'],+ base_case.get('description', '')+ ),+ self.create_scenario(+ 'Worst Case',+ probabilities['worst'],+ worst_case['exit_year'],+ worst_case['exit_value'],+ worst_case.get('description', '')+ )+ ]++ return self.calculate_expected_value(scenarios)++ def sensitivity_to_probabilities(self, scenarios: List[Scenario],+ variable_scenario_index: int) -> Dict[str, Any]:+ """Analyze sensitivity to scenario probabilities"""++ results = []++ for prob in [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]:+ adjusted_scenarios = scenarios.copy()++ remaining_prob = 1.0 - prob+ other_scenarios = [i for i in range(len(scenarios)) if i != variable_scenario_index]++ original_other_total = sum(scenarios[i].probability for i in other_scenarios)++ adjusted_scenarios[variable_scenario_index] = Scenario(+ scenarios[variable_scenario_index].name,+ prob,+ scenarios[variable_scenario_index].exit_year,+ scenarios[variable_scenario_index].exit_value,+ scenarios[variable_scenario_index].description+ )++ for i in other_scenarios:+ new_prob = (scenarios[i].probability / original_other_total) * remaining_prob+ adjusted_scenarios[i] = Scenario(+ scenarios[i].name,+ new_prob,+ scenarios[i].exit_year,+ scenarios[i].exit_value,+ scenarios[i].description+ )++ valuation = self.calculate_expected_value(adjusted_scenarios)++ results.append({+ 'variable_probability': prob * 100,+ 'valuation': valuation['expected_present_value']+ })++ return {+ 'variable_scenario': scenarios[variable_scenario_index].name,+ 'sensitivity_data': results+ }++ def calculate_breakeven_probability(self, scenarios: List[Scenario],+ current_investment: float,+ success_scenario_index: int = 0) -> float:+ """Calculate probability needed for scenario to break even on investment"""++ success_scenario = scenarios[success_scenario_index]+ other_scenarios = [s for i, s in enumerate(scenarios) if i != success_scenario_index]++ success_pv = self.discount_to_present(success_scenario.exit_value, success_scenario.exit_year)++ other_weighted_pv = sum(+ self.discount_to_present(s.exit_value, s.exit_year) * s.probability+ for s in other_scenarios+ )++ other_total_prob = sum(s.probability for s in other_scenarios)++ if success_pv <= 0:+ return 1.0++ breakeven_prob = (current_investment - other_weighted_pv) / success_pv++ return max(0, min(1, breakeven_prob))++if __name__ == '__main__':+ fc = FirstChicagoMethod()++ valuation = fc.three_scenario_valuation(+ best_case={+ 'exit_value': 500_000_000,+ 'exit_year': 4,+ 'description': 'IPO or strategic acquisition at premium'+ },+ base_case={+ 'exit_value': 150_000_000,+ 'exit_year': 5,+ 'description': 'Moderate success, trade sale'+ },+ worst_case={+ 'exit_value': 20_000_000,+ 'exit_year': 6,+ 'description': 'Acqui-hire or distressed sale'+ }+ )++ print("=== FIRST CHICAGO METHOD VALUATION ===\n")+ print(f"Expected Valuation: ${valuation['expected_present_value']:,.0f}")+ print(f"Discount Rate: {valuation['discount_rate']:.0f}%\n")++ print("Scenario Analysis:")+ for scenario in valuation['scenarios']:+ print(f"\n{scenario['name']} ({scenario['probability']:.0f}% probability):")+ print(f" Exit Value (Year {scenario['exit_year']}): ${scenario['exit_value']:,.0f}")+ print(f" Present Value: ${scenario['present_value']:,.0f}")+ print(f" Weighted PV: ${scenario['weighted_present_value']:,.0f}")++ scenarios = [+ fc.create_scenario('Best', 0.20, 4, 500_000_000),+ fc.create_scenario('Base', 0.50, 5, 150_000_000),+ fc.create_scenario('Worst', 0.30, 6, 20_000_000)+ ]++ breakeven = fc.calculate_breakeven_probability(scenarios, 15_000_000, success_scenario_index=0)+ print(f"\nBreakeven Best Case Probability: {breakeven * 100:.1f}%")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/risk_factor_summation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/risk_factor_summation.pynew file mode 100644index 000000000..b570f3771--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/risk_factor_summation.py@@ -0,0 +1,206 @@+"""Risk Factor Summation Method"""+from typing import Dict, Any+from enum import Enum++class RiskFactor(Enum):+ """12 standard risk factors"""+ MANAGEMENT = "management"+ STAGE_OF_BUSINESS = "stage_of_business"+ LEGISLATION_POLITICAL = "legislation_political"+ MANUFACTURING = "manufacturing"+ SALES_MARKETING = "sales_marketing"+ FUNDING_CAPITAL = "funding_capital"+ COMPETITION = "competition"+ TECHNOLOGY = "technology"+ LITIGATION = "litigation"+ INTERNATIONAL = "international"+ REPUTATION = "reputation"+ LUCRATIVE_EXIT = "lucrative_exit"++class RiskFactorSummation:+ """Risk Factor Summation Method for startup valuation"""++ def __init__(self, base_valuation: float, adjustment_per_factor: float = 250_000):+ self.base_valuation = base_valuation+ self.adjustment_per_factor = adjustment_per_factor++ self.risk_descriptions = {+ RiskFactor.MANAGEMENT: "Quality and experience of management team",+ RiskFactor.STAGE_OF_BUSINESS: "Development stage and operational maturity",+ RiskFactor.LEGISLATION_POLITICAL: "Regulatory and political risk exposure",+ RiskFactor.MANUFACTURING: "Production and supply chain risk",+ RiskFactor.SALES_MARKETING: "Go-to-market and customer acquisition risk",+ RiskFactor.FUNDING_CAPITAL: "Future financing and capital needs risk",+ RiskFactor.COMPETITION: "Competitive intensity and market dynamics",+ RiskFactor.TECHNOLOGY: "Technical execution and IP protection risk",+ RiskFactor.LITIGATION: "Legal disputes and liability exposure",+ RiskFactor.INTERNATIONAL: "Cross-border and currency risk",+ RiskFactor.REPUTATION: "Brand and reputational risk",+ RiskFactor.LUCRATIVE_EXIT: "Exit opportunity and liquidity risk"+ }++ def assess_risk_factor(self, factor: RiskFactor, risk_level: int) -> float:+ """+ Assess single risk factor++ Args:+ factor: RiskFactor enum+ risk_level: -2 (very high risk) to +2 (very low risk, adds value)+ 0 = neutral/average risk++ Returns:+ Valuation adjustment for this factor+ """++ if not -2 <= risk_level <= 2:+ raise ValueError("Risk level must be between -2 and +2")++ return risk_level * self.adjustment_per_factor++ def calculate_valuation(self, risk_assessments: Dict[RiskFactor, int]) -> Dict[str, Any]:+ """+ Calculate valuation using risk factor summation++ Args:+ risk_assessments: Dict mapping RiskFactor to risk_level (-2 to +2)++ Returns:+ Complete valuation breakdown+ """++ factor_adjustments = {}+ total_adjustment = 0++ for factor in RiskFactor:+ risk_level = risk_assessments.get(factor, 0)+ adjustment = self.assess_risk_factor(factor, risk_level)++ factor_adjustments[factor.value] = {+ 'risk_level': risk_level,+ 'adjustment': adjustment,+ 'description': self.risk_descriptions[factor]+ }++ total_adjustment += adjustment++ final_valuation = self.base_valuation + total_adjustment++ return {+ 'method': 'Risk Factor Summation',+ 'base_valuation': self.base_valuation,+ 'risk_assessments': factor_adjustments,+ 'total_adjustment': total_adjustment,+ 'final_valuation': max(0, final_valuation),+ 'adjustment_pct': (total_adjustment / self.base_valuation * 100) if self.base_valuation else 0+ }++ def quick_assessment(self, base_valuation: float,+ management_risk: int, stage_risk: int, technology_risk: int,+ competition_risk: int, market_risk: int, funding_risk: int) -> Dict[str, Any]:+ """Quick assessment with key risk factors"""++ assessments = {+ RiskFactor.MANAGEMENT: management_risk,+ RiskFactor.STAGE_OF_BUSINESS: stage_risk,+ RiskFactor.TECHNOLOGY: technology_risk,+ RiskFactor.COMPETITION: competition_risk,+ RiskFactor.SALES_MARKETING: market_risk,+ RiskFactor.FUNDING_CAPITAL: funding_risk,+ RiskFactor.LEGISLATION_POLITICAL: 0,+ RiskFactor.MANUFACTURING: 0,+ RiskFactor.LITIGATION: 0,+ RiskFactor.INTERNATIONAL: 0,+ RiskFactor.REPUTATION: 0,+ RiskFactor.LUCRATIVE_EXIT: 0+ }++ self.base_valuation = base_valuation+ return self.calculate_valuation(assessments)++ def risk_scoring_guide(self) -> Dict[str, Any]:+ """Get risk scoring guidelines"""++ return {+ 'risk_levels': {+ '+2': 'Very Low Risk / Significant Positive (+$500K)',+ '+1': 'Below Average Risk / Positive (+$250K)',+ '0': 'Average Risk / Neutral ($0)',+ '-1': 'Above Average Risk / Negative (-$250K)',+ '-2': 'Very High Risk / Significant Negative (-$500K)'+ },+ 'factor_guidelines': {+ 'Management': {+ '+2': 'Serial successful entrepreneurs, complete A-team',+ '+1': 'Strong relevant experience, mostly complete team',+ '0': 'Some relevant experience, gaps in team',+ '-1': 'Limited experience, significant gaps',+ '-2': 'First-time founders, incomplete team'+ },+ 'Technology': {+ '+2': 'Proven technology, strong IP protection',+ '+1': 'Working prototype, some IP',+ '0': 'Early-stage technology, uncertain IP',+ '-1': 'Unproven technology, weak IP',+ '-2': 'Technology risk very high, no IP'+ },+ 'Competition': {+ '+2': 'Clear differentiation, high barriers',+ '+1': 'Good positioning, some barriers',+ '0': 'Competitive market, moderate barriers',+ '-1': 'Intense competition, low barriers',+ '-2': 'Dominated by incumbents, no barriers'+ }+ }+ }++ def sensitivity_analysis(self, base_assessments: Dict[RiskFactor, int],+ variable_factor: RiskFactor) -> Dict[str, Any]:+ """Analyze valuation sensitivity to single risk factor"""++ results = []++ for risk_level in [-2, -1, 0, 1, 2]:+ test_assessments = base_assessments.copy()+ test_assessments[variable_factor] = risk_level++ valuation = self.calculate_valuation(test_assessments)++ results.append({+ 'risk_level': risk_level,+ 'valuation': valuation['final_valuation'],+ 'adjustment': valuation['total_adjustment']+ })++ return {+ 'variable_factor': variable_factor.value,+ 'sensitivity_data': results,+ 'base_valuation': self.base_valuation+ }++if __name__ == '__main__':+ rfs = RiskFactorSummation(base_valuation=2_000_000, adjustment_per_factor=250_000)++ valuation = rfs.quick_assessment(+ base_valuation=2_000_000,+ management_risk=1,+ stage_risk=-1,+ technology_risk=0,+ competition_risk=-1,+ market_risk=0,+ funding_risk=-1+ )++ print("=== RISK FACTOR SUMMATION VALUATION ===\n")+ print(f"Base Valuation: ${valuation['base_valuation']:,.0f}")+ print(f"Total Adjustment: ${valuation['total_adjustment']:,} ({valuation['adjustment_pct']:+.1f}%)")+ print(f"Final Valuation: ${valuation['final_valuation']:,.0f}\n")++ print("Risk Factor Assessments:")+ for factor, data in valuation['risk_assessments'].items():+ if data['adjustment'] != 0:+ print(f" {factor.replace('_', ' ').title()}: {data['risk_level']:+d} (${data['adjustment']:+,})")++ guide = rfs.risk_scoring_guide()+ print("\n=== RISK SCORING GUIDE ===")+ for level, desc in guide['risk_levels'].items():+ print(f"{level}: {desc}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/scorecard_method.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/scorecard_method.pynew file mode 100644index 000000000..d167fb1ba--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/scorecard_method.py@@ -0,0 +1,173 @@+"""Scorecard Valuation Method"""+from typing import Dict, Any++class ScorecardMethod:+ """Scorecard (or Payne) Method for startup valuation"""++ def __init__(self, region: str = 'US'):+ self.region = region++ self.typical_pre_money_valuations = {+ 'US': {'seed': 2_000_000, 'series_a': 5_000_000},+ 'Europe': {'seed': 1_500_000, 'series_a': 4_000_000},+ 'Asia': {'seed': 1_800_000, 'series_a': 4_500_000}+ }++ self.factor_weights = {+ 'management_team': 0.30,+ 'size_of_opportunity': 0.25,+ 'product_technology': 0.15,+ 'competitive_environment': 0.10,+ 'marketing_sales_channels': 0.10,+ 'need_for_additional_investment': 0.05,+ 'other_factors': 0.05+ }++ def get_baseline_valuation(self, stage: str = 'seed') -> float:+ """Get baseline valuation for region and stage"""++ region_valuations = self.typical_pre_money_valuations.get(self.region, self.typical_pre_money_valuations['US'])+ return region_valuations.get(stage, region_valuations['seed'])++ def assess_factor(self, factor_name: str, comparison_score: float) -> float:+ """+ Assess factor relative to average startup++ Args:+ factor_name: Name of factor being assessed+ comparison_score: -0.5 to +0.5 (0 = average, +0.5 = way above, -0.5 = way below)++ Returns:+ Adjustment multiplier (e.g., 1.3 for 30% above average)+ """++ if factor_name not in self.factor_weights:+ raise ValueError(f"Unknown factor: {factor_name}")++ weight = self.factor_weights[factor_name]++ adjustment = 1 + (comparison_score * weight / 0.30)++ return max(0.5, min(1.5, adjustment))++ def calculate_valuation(self, stage: str, factor_assessments: Dict[str, float],+ custom_baseline: float = None) -> Dict[str, Any]:+ """+ Calculate valuation using scorecard method++ Args:+ stage: Funding stage ('seed', 'series_a')+ factor_assessments: Dict of factor_name -> comparison_score (-0.5 to +0.5)+ custom_baseline: Optional custom baseline instead of regional average++ Returns:+ Detailed valuation breakdown+ """++ baseline = custom_baseline or self.get_baseline_valuation(stage)++ factor_multipliers = {}+ cumulative_multiplier = 1.0++ for factor, comparison_score in factor_assessments.items():+ multiplier = self.assess_factor(factor, comparison_score)+ factor_multipliers[factor] = {+ 'comparison_score': comparison_score,+ 'weight': self.factor_weights[factor],+ 'multiplier': multiplier+ }++ weight = self.factor_weights[factor]+ cumulative_multiplier *= (1 + (multiplier - 1) * weight / sum(self.factor_weights.values()))++ final_valuation = baseline * cumulative_multiplier++ return {+ 'method': 'Scorecard Method',+ 'baseline_valuation': baseline,+ 'region': self.region,+ 'stage': stage,+ 'factor_assessments': factor_multipliers,+ 'cumulative_multiplier': cumulative_multiplier,+ 'final_valuation': final_valuation,+ 'adjustment_pct': (cumulative_multiplier - 1) * 100+ }++ def comprehensive_assessment(self, stage: str, team_strength: str, market_size: str,+ product_strength: str, competition: str,+ sales_traction: str) -> Dict[str, Any]:+ """+ Comprehensive assessment with simplified inputs++ Args:+ All parameters: 'weak', 'average', 'strong', 'excellent'++ Returns:+ Valuation result+ """++ strength_to_score = {+ 'weak': -0.4,+ 'below_average': -0.2,+ 'average': 0.0,+ 'above_average': 0.2,+ 'strong': 0.35,+ 'excellent': 0.5+ }++ assessments = {+ 'management_team': strength_to_score.get(team_strength, 0),+ 'size_of_opportunity': strength_to_score.get(market_size, 0),+ 'product_technology': strength_to_score.get(product_strength, 0),+ 'competitive_environment': strength_to_score.get(competition, 0),+ 'marketing_sales_channels': strength_to_score.get(sales_traction, 0),+ 'need_for_additional_investment': 0.0,+ 'other_factors': 0.0+ }++ return self.calculate_valuation(stage, assessments)++ def sensitivity_analysis(self, stage: str, base_assessments: Dict[str, float],+ variable_factor: str) -> Dict[str, Any]:+ """Run sensitivity analysis on single factor"""++ results = []++ for score in [-0.5, -0.3, -0.1, 0, 0.1, 0.3, 0.5]:+ test_assessments = base_assessments.copy()+ test_assessments[variable_factor] = score++ valuation_result = self.calculate_valuation(stage, test_assessments)++ results.append({+ 'factor_score': score,+ 'valuation': valuation_result['final_valuation'],+ 'multiplier': valuation_result['cumulative_multiplier']+ })++ return {+ 'variable_factor': variable_factor,+ 'sensitivity_data': results,+ 'baseline_valuation': self.get_baseline_valuation(stage)+ }++if __name__ == '__main__':+ scorecard = ScorecardMethod(region='US')++ valuation = scorecard.comprehensive_assessment(+ stage='seed',+ team_strength='excellent',+ market_size='strong',+ product_strength='above_average',+ competition='average',+ sales_traction='below_average'+ )++ print(f"=== SCORECARD METHOD VALUATION ===\n")+ print(f"Baseline ({valuation['region']} {valuation['stage']}): ${valuation['baseline_valuation']:,.0f}")+ print(f"Adjustment: {valuation['adjustment_pct']:+.1f}%")+ print(f"Final Valuation: ${valuation['final_valuation']:,.0f}\n")++ print("Factor Assessments:")+ for factor, data in valuation['factor_assessments'].items():+ print(f" {factor.replace('_', ' ').title()}: {data['comparison_score']:+.2f} (weight: {data['weight']:.0%})")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/startup_summary.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/startup_summary.pynew file mode 100644index 000000000..7b19876d4--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/startup_summary.py@@ -0,0 +1,263 @@+"""Comprehensive Startup Valuation Summary"""+from typing import Dict, Any, List, Optional+from .berkus_method import BerkusMethod, BerkusFactor+from .scorecard_method import ScorecardMethod+from .vc_method import VCMethod+from .first_chicago_method import FirstChicagoMethod, Scenario+from .risk_factor_summation import RiskFactorSummation, RiskFactor++class StartupValuationSummary:+ """Aggregate all startup valuation methods into comprehensive summary"""++ def __init__(self, startup_name: str):+ self.startup_name = startup_name++ def comprehensive_valuation(self,+ berkus_scores: Optional[Dict[BerkusFactor, float]] = None,+ scorecard_inputs: Optional[Dict[str, Any]] = None,+ vc_inputs: Optional[Dict[str, Any]] = None,+ first_chicago_scenarios: Optional[List[Scenario]] = None,+ risk_factor_assessments: Optional[Dict[RiskFactor, int]] = None) -> Dict[str, Any]:+ """+ Generate comprehensive startup valuation using all applicable methods++ Returns summary with all methods, weighted average, and range+ """++ valuations = {}++ # Berkus Method (pre-revenue)+ if berkus_scores:+ berkus = BerkusMethod()+ berkus_result = berkus.calculate_valuation(berkus_scores)+ valuations['berkus'] = {+ 'method': 'Berkus Method',+ 'valuation': berkus_result['total_valuation'],+ 'applicability': 'pre_revenue',+ 'details': berkus_result+ }++ # Scorecard Method+ if scorecard_inputs:+ scorecard = ScorecardMethod(region=scorecard_inputs.get('region', 'US'))+ scorecard_result = scorecard.calculate_valuation(+ stage=scorecard_inputs['stage'],+ factor_assessments=scorecard_inputs['assessments']+ )+ valuations['scorecard'] = {+ 'method': 'Scorecard Method',+ 'valuation': scorecard_result['final_valuation'],+ 'applicability': 'early_stage',+ 'details': scorecard_result+ }++ # VC Method+ if vc_inputs:+ vc = VCMethod()+ vc_result = vc.comprehensive_valuation(**vc_inputs)+ valuations['vc_method'] = {+ 'method': 'VC Method',+ 'valuation': vc_result['pre_money_valuation'],+ 'applicability': 'all_stages',+ 'details': vc_result+ }++ # First Chicago Method+ if first_chicago_scenarios:+ fc = FirstChicagoMethod()+ fc_result = fc.calculate_expected_value(first_chicago_scenarios)+ valuations['first_chicago'] = {+ 'method': 'First Chicago Method',+ 'valuation': fc_result['expected_present_value'],+ 'applicability': 'all_stages',+ 'details': fc_result+ }++ # Risk Factor Summation+ if risk_factor_assessments:+ rfs = RiskFactorSummation(base_valuation=2_000_000)+ rfs_result = rfs.calculate_valuation(risk_factor_assessments)+ valuations['risk_factor'] = {+ 'method': 'Risk Factor Summation',+ 'valuation': rfs_result['final_valuation'],+ 'applicability': 'early_stage',+ 'details': rfs_result+ }++ if not valuations:+ return {'error': 'No valuation methods provided'}++ # Calculate statistics+ valuation_values = [v['valuation'] for v in valuations.values()]++ min_val = min(valuation_values)+ max_val = max(valuation_values)+ mean_val = sum(valuation_values) / len(valuation_values)+ median_val = sorted(valuation_values)[len(valuation_values) // 2]++ # Weighted average (give more weight to methods with higher applicability)+ weights = {+ 'berkus': 0.15,+ 'scorecard': 0.20,+ 'vc_method': 0.30,+ 'first_chicago': 0.25,+ 'risk_factor': 0.10+ }++ total_weight = sum(weights.get(k, 0.2) for k in valuations.keys())+ weighted_valuation = sum(+ v['valuation'] * weights.get(k, 0.2)+ for k, v in valuations.items()+ ) / total_weight++ return {+ 'startup_name': self.startup_name,+ 'valuations_by_method': valuations,+ 'valuation_summary': {+ 'min': min_val,+ 'max': max_val,+ 'mean': mean_val,+ 'median': median_val,+ 'weighted_average': weighted_valuation,+ 'range': max_val - min_val,+ 'coefficient_of_variation': (+ (max_val - min_val) / mean_val * 100+ ) if mean_val > 0 else 0+ },+ 'methods_used': list(valuations.keys()),+ 'num_methods': len(valuations),+ 'recommendation': {+ 'suggested_valuation': weighted_valuation,+ 'valuation_range': f"${min_val:,.0f} - ${max_val:,.0f}",+ 'confidence': 'high' if len(valuations) >= 3 else 'moderate'+ }+ }++ def quick_pre_revenue_valuation(self,+ idea_quality: int,+ team_quality: int,+ prototype_status: int,+ market_size: int) -> Dict[str, Any]:+ """+ Quick pre-revenue valuation using Berkus and Risk Factor++ All inputs: 0-100 scale+ """++ # Convert to Berkus scores (0-1)+ berkus_scores = {+ BerkusFactor.SOUND_IDEA: idea_quality / 100,+ BerkusFactor.QUALITY_MANAGEMENT: team_quality / 100,+ BerkusFactor.PROTOTYPE: prototype_status / 100,+ BerkusFactor.STRATEGIC_RELATIONSHIPS: 0.3,+ BerkusFactor.PRODUCT_ROLLOUT: 0.2+ }++ # Convert to risk factor scores (-2 to +2)+ def scale_to_risk(score: int) -> int:+ if score >= 80:+ return 2+ elif score >= 60:+ return 1+ elif score >= 40:+ return 0+ elif score >= 20:+ return -1+ else:+ return -2++ risk_assessments = {+ RiskFactor.MANAGEMENT: scale_to_risk(team_quality),+ RiskFactor.STAGE_OF_BUSINESS: -1,+ RiskFactor.TECHNOLOGY: scale_to_risk(prototype_status),+ RiskFactor.COMPETITION: 0,+ RiskFactor.SALES_MARKETING: scale_to_risk(market_size),+ RiskFactor.FUNDING_CAPITAL: -1+ }++ return self.comprehensive_valuation(+ berkus_scores=berkus_scores,+ risk_factor_assessments=risk_assessments+ )++ def series_a_valuation(self,+ revenue: float,+ revenue_growth: float,+ exit_year: int = 5,+ exit_multiple: float = 8.0,+ investment_amount: float = 10_000_000) -> Dict[str, Any]:+ """Series A stage valuation using VC and First Chicago methods"""++ # VC Method inputs+ vc_inputs = {+ 'exit_year_metric': revenue * (1 + revenue_growth) ** exit_year,+ 'exit_multiple': exit_multiple,+ 'years_to_exit': exit_year,+ 'investment_amount': investment_amount,+ 'stage': 'series_a'+ }++ # First Chicago scenarios+ exit_revenue = revenue * (1 + revenue_growth) ** exit_year+ scenarios = [+ Scenario('Bear Case', 0.25, exit_year + 1, exit_revenue * 0.6 * 6.0, 'Conservative exit'),+ Scenario('Base Case', 0.50, exit_year, exit_revenue * exit_multiple, 'Expected outcome'),+ Scenario('Bull Case', 0.25, exit_year - 1, exit_revenue * 1.4 * 10.0, 'Strong exit')+ ]++ return self.comprehensive_valuation(+ vc_inputs=vc_inputs,+ first_chicago_scenarios=scenarios+ )++if __name__ == '__main__':+ startup = StartupValuationSummary("TechStartup Inc")++ # Pre-revenue example+ pre_revenue = startup.quick_pre_revenue_valuation(+ idea_quality=85,+ team_quality=90,+ prototype_status=70,+ market_size=80+ )++ print("=== PRE-REVENUE STARTUP VALUATION ===\n")+ print(f"Startup: {pre_revenue['startup_name']}")+ print(f"Methods Used: {pre_revenue['num_methods']}\n")++ print("Valuation Summary:")+ summary = pre_revenue['valuation_summary']+ print(f" Min: ${summary['min']:,.0f}")+ print(f" Max: ${summary['max']:,.0f}")+ print(f" Weighted Average: ${summary['weighted_average']:,.0f}")+ print(f" Median: ${summary['median']:,.0f}")++ print(f"\nRecommendation:")+ rec = pre_revenue['recommendation']+ print(f" Suggested Valuation: ${rec['suggested_valuation']:,.0f}")+ print(f" Range: {rec['valuation_range']}")+ print(f" Confidence: {rec['confidence'].title()}")++ print("\n\nValuations by Method:")+ for method, data in pre_revenue['valuations_by_method'].items():+ print(f" {data['method']}: ${data['valuation']:,.0f}")++ # Series A example+ series_a = startup.series_a_valuation(+ revenue=5_000_000,+ revenue_growth=1.0,+ exit_year=5,+ exit_multiple=8.0,+ investment_amount=15_000_000+ )++ print("\n\n=== SERIES A VALUATION ===")+ print(f"Methods Used: {series_a['num_methods']}\n")++ summary_a = series_a['valuation_summary']+ print("Valuation Summary:")+ print(f" Weighted Average: ${summary_a['weighted_average']:,.0f}")+ print(f" Range: ${summary_a['min']:,.0f} - ${summary_a['max']:,.0f}")++ rec_a = series_a['recommendation']+ print(f"\nSuggested Pre-Money: ${rec_a['suggested_valuation']:,.0f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/vc_method.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/vc_method.pynew file mode 100644index 000000000..cab67c8f5--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/startup_valuation/vc_method.py@@ -0,0 +1,191 @@+"""Venture Capital (VC) Method of Valuation"""+from typing import Dict, Any, Optional++class VCMethod:+ """Venture Capital Method for startup valuation"""++ def __init__(self):+ self.typical_ror_by_stage = {+ 'seed': 0.60,+ 'series_a': 0.50,+ 'series_b': 0.40,+ 'series_c': 0.30,+ 'late_stage': 0.25+ }++ self.typical_exit_multiples = {+ 'revenue': {'saas': 8.0, 'ecommerce': 1.5, 'marketplace': 3.0, 'fintech': 5.0},+ 'ebitda': {'default': 12.0},+ 'pe': {'default': 20.0}+ }++ def calculate_terminal_value(self, exit_year_metric: float,+ exit_multiple: float) -> float:+ """Calculate terminal/exit value"""+ return exit_year_metric * exit_multiple++ def calculate_present_value(self, terminal_value: float,+ required_ror: float, years_to_exit: int) -> float:+ """Discount terminal value to present"""+ return terminal_value / ((1 + required_ror) ** years_to_exit)++ def calculate_post_money_valuation(self, terminal_value: float,+ required_ror: float, years_to_exit: int) -> float:+ """Calculate post-money valuation (before financing)"""+ return self.calculate_present_value(terminal_value, required_ror, years_to_exit)++ def calculate_pre_money_valuation(self, post_money: float,+ investment_amount: float) -> float:+ """Calculate pre-money valuation"""+ return post_money - investment_amount++ def calculate_ownership_percentage(self, investment_amount: float,+ post_money: float) -> float:+ """Calculate investor ownership percentage"""+ return (investment_amount / post_money) * 100++ def comprehensive_valuation(self, exit_year_metric: float,+ exit_multiple: float,+ years_to_exit: int,+ investment_amount: float,+ stage: str = 'series_a',+ custom_ror: Optional[float] = None) -> Dict[str, Any]:+ """+ Complete VC method valuation++ Args:+ exit_year_metric: Projected revenue/EBITDA at exit+ exit_multiple: Exit valuation multiple+ years_to_exit: Years until liquidity event+ investment_amount: Amount being invested+ stage: Funding stage+ custom_ror: Custom required rate of return++ Returns:+ Complete valuation analysis+ """++ required_ror = custom_ror or self.typical_ror_by_stage.get(stage, 0.40)++ terminal_value = self.calculate_terminal_value(exit_year_metric, exit_multiple)++ post_money = self.calculate_post_money_valuation(terminal_value, required_ror, years_to_exit)++ pre_money = self.calculate_pre_money_valuation(post_money, investment_amount)++ ownership_pct = self.calculate_ownership_percentage(investment_amount, post_money)++ investor_exit_value = terminal_value * (ownership_pct / 100)++ investor_return = investor_exit_value / investment_amount++ return {+ 'method': 'VC Method',+ 'inputs': {+ 'exit_year_metric': exit_year_metric,+ 'exit_multiple': exit_multiple,+ 'years_to_exit': years_to_exit,+ 'investment_amount': investment_amount,+ 'required_ror': required_ror * 100,+ 'stage': stage+ },+ 'terminal_value': terminal_value,+ 'post_money_valuation': post_money,+ 'pre_money_valuation': pre_money,+ 'investor_ownership_pct': ownership_pct,+ 'investor_exit_value': investor_exit_value,+ 'investor_return_multiple': investor_return,+ 'investor_irr': required_ror * 100+ }++ def reverse_engineer_valuation(self, investment_amount: float,+ target_ownership_pct: float) -> Dict[str, Any]:+ """Calculate implied valuation from desired ownership"""++ post_money = investment_amount / (target_ownership_pct / 100)+ pre_money = post_money - investment_amount++ return {+ 'investment_amount': investment_amount,+ 'target_ownership_pct': target_ownership_pct,+ 'implied_post_money': post_money,+ 'implied_pre_money': pre_money+ }++ def scenario_analysis(self, base_case: Dict[str, float],+ bear_case: Dict[str, float],+ bull_case: Dict[str, float],+ investment_amount: float,+ stage: str = 'series_a') -> Dict[str, Any]:+ """Run scenario analysis with three cases"""++ scenarios = {}++ for case_name, case_data in [('bear', bear_case), ('base', base_case), ('bull', bull_case)]:+ valuation = self.comprehensive_valuation(+ exit_year_metric=case_data['exit_metric'],+ exit_multiple=case_data['exit_multiple'],+ years_to_exit=case_data['years_to_exit'],+ investment_amount=investment_amount,+ stage=stage+ )++ scenarios[case_name] = valuation++ return {+ 'scenarios': scenarios,+ 'valuation_range': {+ 'low': scenarios['bear']['pre_money_valuation'],+ 'base': scenarios['base']['pre_money_valuation'],+ 'high': scenarios['bull']['pre_money_valuation']+ }+ }++ def calculate_required_exit_multiple(self, current_valuation: float,+ investment_amount: float,+ target_return: float,+ years_to_exit: int,+ exit_year_metric: float) -> float:+ """Calculate exit multiple needed for target return"""++ post_money = current_valuation + investment_amount+ ownership_pct = investment_amount / post_money++ required_exit_value = investment_amount * target_return++ required_company_value = required_exit_value / ownership_pct++ required_multiple = required_company_value / exit_year_metric++ return required_multiple++if __name__ == '__main__':+ vc = VCMethod()++ valuation = vc.comprehensive_valuation(+ exit_year_metric=100_000_000,+ exit_multiple=8.0,+ years_to_exit=5,+ investment_amount=10_000_000,+ stage='series_a'+ )++ print("=== VC METHOD VALUATION ===\n")+ print(f"Exit Value (Year 5): ${valuation['terminal_value']:,.0f}")+ print(f"Required ROR: {valuation['inputs']['required_ror']:.0f}%")+ print(f"\nPre-Money Valuation: ${valuation['pre_money_valuation']:,.0f}")+ print(f"Post-Money Valuation: ${valuation['post_money_valuation']:,.0f}")+ print(f"\nInvestor Ownership: {valuation['investor_ownership_pct']:.1f}%")+ print(f"Investor Return: {valuation['investor_return_multiple']:.2f}x")++ scenarios = vc.scenario_analysis(+ base_case={'exit_metric': 100_000_000, 'exit_multiple': 8.0, 'years_to_exit': 5},+ bear_case={'exit_metric': 60_000_000, 'exit_multiple': 6.0, 'years_to_exit': 6},+ bull_case={'exit_metric': 150_000_000, 'exit_multiple': 10.0, 'years_to_exit': 4},+ investment_amount=10_000_000+ )++ print(f"\nValuation Range:")+ print(f" Bear: ${scenarios['valuation_range']['low']:,.0f}")+ print(f" Base: ${scenarios['valuation_range']['base']:,.0f}")+ print(f" Bull: ${scenarios['valuation_range']['high']:,.0f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/__init__.pynew file mode 100644index 000000000..a442b2c65--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/__init__.py@@ -0,0 +1,18 @@+"""Synergy Analysis Module"""+from .revenue_synergies import RevenueSynergyAnalyzer, RevenueSynergyType, SynergyOpportunity+from .cost_synergies import CostSynergyAnalyzer, CostSynergyType, CostReduction+from .integration_costs import IntegrationCostAnalyzer, IntegrationCategory, IntegrationCost+from .synergy_valuation import SynergyValuation++__all__ = [+ 'RevenueSynergyAnalyzer',+ 'RevenueSynergyType',+ 'SynergyOpportunity',+ 'CostSynergyAnalyzer',+ 'CostSynergyType',+ 'CostReduction',+ 'IntegrationCostAnalyzer',+ 'IntegrationCategory',+ 'IntegrationCost',+ 'SynergyValuation'+]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/cost_synergies.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/cost_synergies.pynew file mode 100644index 000000000..ff983a4a8--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/cost_synergies.py@@ -0,0 +1,464 @@+"""Cost Synergy Analysis"""+from typing import Dict, Any, List, Optional+from dataclasses import dataclass+from enum import Enum+import numpy as np++class CostSynergyType(Enum):+ HEADCOUNT_REDUCTION = "headcount_reduction"+ FACILITIES_CONSOLIDATION = "facilities_consolidation"+ PROCUREMENT = "procurement"+ IT_SYSTEMS = "it_systems"+ VENDOR_RATIONALIZATION = "vendor_rationalization"+ SHARED_SERVICES = "shared_services"+ MANUFACTURING = "manufacturing"+ R_AND_D = "r_and_d"++@dataclass+class CostReduction:+ category: CostSynergyType+ description: str+ annual_savings: float+ one_time_cost: float+ ramp_years: int++class CostSynergyAnalyzer:+ """Analyze and quantify cost synergies in M&A transactions"""++ def __init__(self, tax_rate: float = 0.25,+ cost_of_capital: float = 0.10):+ self.tax_rate = tax_rate+ self.cost_of_capital = cost_of_capital++ def calculate_headcount_synergy(self, duplicate_roles: int,+ average_loaded_cost: float,+ severance_multiple: float = 1.5,+ ramp_years: int = 2) -> Dict[str, Any]:+ """Calculate headcount reduction synergy"""++ annual_savings = duplicate_roles * average_loaded_cost++ one_time_cost = duplicate_roles * average_loaded_cost * severance_multiple++ yearly_cash_flows = []+ for year in range(0, 7):+ if year == 0:+ cash_flow = -one_time_cost+ elif year <= ramp_years:+ realization = year / ramp_years+ savings = annual_savings * realization+ cash_flow = savings * (1 - self.tax_rate)+ else:+ cash_flow = annual_savings * (1 - self.tax_rate)++ pv = cash_flow / ((1 + self.cost_of_capital) ** year)++ yearly_cash_flows.append({+ 'year': year,+ 'savings': cash_flow if year > 0 else 0,+ 'one_time_cost': one_time_cost if year == 0 else 0,+ 'net_cash_flow': cash_flow,+ 'present_value': pv+ })++ total_pv = sum(y['present_value'] for y in yearly_cash_flows)++ payback_cumulative = 0+ payback_years = None+ for y in yearly_cash_flows:+ payback_cumulative += y['net_cash_flow']+ if payback_cumulative > 0 and payback_years is None:+ payback_years = y['year']++ return {+ 'synergy_type': 'headcount_reduction',+ 'duplicate_roles': duplicate_roles,+ 'average_loaded_cost': average_loaded_cost,+ 'annual_savings': annual_savings,+ 'one_time_severance_cost': one_time_cost,+ 'ramp_years': ramp_years,+ 'yearly_projections': yearly_cash_flows,+ 'npv': total_pv,+ 'payback_period_years': payback_years,+ 'roi': (total_pv / one_time_cost * 100) if one_time_cost > 0 else 0+ }++ def calculate_facilities_synergy(self, facilities_to_close: int,+ annual_cost_per_facility: float,+ closure_cost_per_facility: float,+ lease_termination_cost: float,+ ramp_years: int = 2) -> Dict[str, Any]:+ """Calculate facilities consolidation synergy"""++ annual_savings = facilities_to_close * annual_cost_per_facility++ one_time_cost = (facilities_to_close * closure_cost_per_facility) + lease_termination_cost++ yearly_cash_flows = []+ for year in range(0, 7):+ if year == 0:+ cash_flow = -one_time_cost+ elif year <= ramp_years:+ realization = year / ramp_years+ savings = annual_savings * realization+ cash_flow = savings * (1 - self.tax_rate)+ else:+ cash_flow = annual_savings * (1 - self.tax_rate)++ pv = cash_flow / ((1 + self.cost_of_capital) ** year)++ yearly_cash_flows.append({+ 'year': year,+ 'net_cash_flow': cash_flow,+ 'present_value': pv+ })++ total_pv = sum(y['present_value'] for y in yearly_cash_flows)++ return {+ 'synergy_type': 'facilities_consolidation',+ 'facilities_to_close': facilities_to_close,+ 'annual_savings': annual_savings,+ 'total_one_time_cost': one_time_cost,+ 'ramp_years': ramp_years,+ 'yearly_projections': yearly_cash_flows,+ 'npv': total_pv+ }++ def calculate_procurement_synergy(self, combined_spend: float,+ volume_discount: float,+ supplier_rationalization_benefit: float,+ implementation_cost: float,+ ramp_years: int = 3) -> Dict[str, Any]:+ """Calculate procurement and purchasing synergy"""++ volume_savings = combined_spend * volume_discount+ rationalization_savings = combined_spend * supplier_rationalization_benefit++ total_annual_savings = volume_savings + rationalization_savings++ yearly_cash_flows = []+ for year in range(0, 7):+ if year == 0:+ cash_flow = -implementation_cost+ elif year <= ramp_years:+ realization = year / ramp_years+ savings = total_annual_savings * realization+ cash_flow = savings * (1 - self.tax_rate)+ else:+ cash_flow = total_annual_savings * (1 - self.tax_rate)++ pv = cash_flow / ((1 + self.cost_of_capital) ** year)++ yearly_cash_flows.append({+ 'year': year,+ 'net_cash_flow': cash_flow,+ 'present_value': pv+ })++ total_pv = sum(y['present_value'] for y in yearly_cash_flows)++ return {+ 'synergy_type': 'procurement',+ 'combined_spend': combined_spend,+ 'volume_discount': volume_discount * 100,+ 'volume_savings': volume_savings,+ 'rationalization_savings': rationalization_savings,+ 'total_annual_savings': total_annual_savings,+ 'implementation_cost': implementation_cost,+ 'yearly_projections': yearly_cash_flows,+ 'npv': total_pv+ }++ def calculate_it_systems_synergy(self, duplicate_systems_cost: float,+ migration_cost: float,+ ongoing_maintenance_reduction: float,+ migration_years: int = 2) -> Dict[str, Any]:+ """Calculate IT systems consolidation synergy"""++ annual_savings = duplicate_systems_cost + ongoing_maintenance_reduction++ yearly_cash_flows = []+ for year in range(0, 7):+ if year == 0:+ cash_flow = -migration_cost * 0.5+ elif year <= migration_years:+ migration_spend = -migration_cost * (0.5 / migration_years)+ realization = year / migration_years+ savings = annual_savings * realization+ cash_flow = (savings * (1 - self.tax_rate)) + migration_spend+ else:+ cash_flow = annual_savings * (1 - self.tax_rate)++ pv = cash_flow / ((1 + self.cost_of_capital) ** year)++ yearly_cash_flows.append({+ 'year': year,+ 'net_cash_flow': cash_flow,+ 'present_value': pv+ })++ total_pv = sum(y['present_value'] for y in yearly_cash_flows)++ return {+ 'synergy_type': 'it_systems',+ 'duplicate_systems_cost': duplicate_systems_cost,+ 'maintenance_reduction': ongoing_maintenance_reduction,+ 'total_annual_savings': annual_savings,+ 'migration_cost': migration_cost,+ 'migration_years': migration_years,+ 'yearly_projections': yearly_cash_flows,+ 'npv': total_pv+ }++ def calculate_shared_services_synergy(self, functions: List[Dict[str, float]],+ consolidation_rate: float,+ setup_cost: float,+ ramp_years: int = 3) -> Dict[str, Any]:+ """Calculate shared services consolidation synergy"""++ function_analysis = []+ total_savings = 0++ for func in functions:+ func_savings = func['annual_cost'] * consolidation_rate+ total_savings += func_savings++ function_analysis.append({+ 'function': func['name'],+ 'current_cost': func['annual_cost'],+ 'consolidation_rate': consolidation_rate * 100,+ 'annual_savings': func_savings+ })++ yearly_cash_flows = []+ for year in range(0, 7):+ if year == 0:+ cash_flow = -setup_cost+ elif year <= ramp_years:+ realization = year / ramp_years+ savings = total_savings * realization+ cash_flow = savings * (1 - self.tax_rate)+ else:+ cash_flow = total_savings * (1 - self.tax_rate)++ pv = cash_flow / ((1 + self.cost_of_capital) ** year)++ yearly_cash_flows.append({+ 'year': year,+ 'net_cash_flow': cash_flow,+ 'present_value': pv+ })++ total_pv = sum(y['present_value'] for y in yearly_cash_flows)++ return {+ 'synergy_type': 'shared_services',+ 'functions': function_analysis,+ 'total_annual_savings': total_savings,+ 'setup_cost': setup_cost,+ 'ramp_years': ramp_years,+ 'yearly_projections': yearly_cash_flows,+ 'npv': total_pv+ }++ def calculate_manufacturing_synergy(self, production_volume: float,+ unit_cost_reduction: float,+ plant_closure_savings: float,+ plant_closure_cost: float,+ capacity_utilization_improvement: float,+ ramp_years: int = 3) -> Dict[str, Any]:+ """Calculate manufacturing and operations synergy"""++ scale_savings = production_volume * unit_cost_reduction+ facility_savings = plant_closure_savings+ utilization_savings = production_volume * capacity_utilization_improvement++ total_annual_savings = scale_savings + facility_savings + utilization_savings++ yearly_cash_flows = []+ for year in range(0, 7):+ if year == 0:+ cash_flow = -plant_closure_cost+ elif year <= ramp_years:+ realization = year / ramp_years+ savings = total_annual_savings * realization+ cash_flow = savings * (1 - self.tax_rate)+ else:+ cash_flow = total_annual_savings * (1 - self.tax_rate)++ pv = cash_flow / ((1 + self.cost_of_capital) ** year)++ yearly_cash_flows.append({+ 'year': year,+ 'net_cash_flow': cash_flow,+ 'present_value': pv+ })++ total_pv = sum(y['present_value'] for y in yearly_cash_flows)++ return {+ 'synergy_type': 'manufacturing',+ 'production_volume': production_volume,+ 'scale_savings': scale_savings,+ 'facility_savings': facility_savings,+ 'utilization_savings': utilization_savings,+ 'total_annual_savings': total_annual_savings,+ 'plant_closure_cost': plant_closure_cost,+ 'yearly_projections': yearly_cash_flows,+ 'npv': total_pv+ }++ def comprehensive_cost_synergy(self, cost_reductions: List[CostReduction]) -> Dict[str, Any]:+ """Aggregate all cost synergy opportunities"""++ synergy_breakdown = []+ total_npv = 0+ total_one_time_costs = 0+ total_annual_savings = 0++ for reduction in cost_reductions:+ yearly_projections = []++ for year in range(0, 7):+ if year == 0:+ cash_flow = -reduction.one_time_cost+ elif year <= reduction.ramp_years:+ realization = year / reduction.ramp_years+ savings = reduction.annual_savings * realization+ cash_flow = savings * (1 - self.tax_rate)+ else:+ cash_flow = reduction.annual_savings * (1 - self.tax_rate)++ pv = cash_flow / ((1 + self.cost_of_capital) ** year)++ yearly_projections.append({+ 'year': year,+ 'net_cash_flow': cash_flow,+ 'present_value': pv+ })++ reduction_npv = sum(y['present_value'] for y in yearly_projections)+ total_npv += reduction_npv+ total_one_time_costs += reduction.one_time_cost+ total_annual_savings += reduction.annual_savings++ synergy_breakdown.append({+ 'category': reduction.category.value,+ 'description': reduction.description,+ 'annual_savings': reduction.annual_savings,+ 'one_time_cost': reduction.one_time_cost,+ 'ramp_years': reduction.ramp_years,+ 'npv': reduction_npv,+ 'roi': (reduction_npv / reduction.one_time_cost * 100) if reduction.one_time_cost > 0 else float('inf'),+ 'yearly_projections': yearly_projections+ })++ synergy_breakdown.sort(key=lambda x: x['npv'], reverse=True)++ return {+ 'total_cost_synergy_npv': total_npv,+ 'total_annual_savings_run_rate': total_annual_savings,+ 'total_one_time_costs': total_one_time_costs,+ 'blended_roi': (total_npv / total_one_time_costs * 100) if total_one_time_costs > 0 else float('inf'),+ 'synergy_breakdown': synergy_breakdown,+ 'cost_of_capital': self.cost_of_capital * 100,+ 'tax_rate': self.tax_rate * 100+ }++ def synergy_realization_tracker(self, planned_savings: float,+ actual_savings_by_quarter: List[float]) -> Dict[str, Any]:+ """Track actual synergy realization vs plan"""++ quarters = len(actual_savings_by_quarter)+ years = quarters / 4++ cumulative_actual = sum(actual_savings_by_quarter)+ cumulative_plan = planned_savings * years++ realization_rate = (cumulative_actual / cumulative_plan * 100) if cumulative_plan > 0 else 0++ quarterly_variance = [+ actual - (planned_savings / 4)+ for actual in actual_savings_by_quarter+ ]++ return {+ 'planned_annual_savings': planned_savings,+ 'quarters_tracked': quarters,+ 'cumulative_actual': cumulative_actual,+ 'cumulative_plan': cumulative_plan,+ 'realization_rate': realization_rate,+ 'quarterly_actual': actual_savings_by_quarter,+ 'quarterly_variance': quarterly_variance,+ 'on_track': realization_rate >= 85.0+ }++if __name__ == '__main__':+ analyzer = CostSynergyAnalyzer(tax_rate=0.25, cost_of_capital=0.10)++ headcount = analyzer.calculate_headcount_synergy(+ duplicate_roles=250,+ average_loaded_cost=120_000,+ severance_multiple=1.5,+ ramp_years=2+ )++ print("=== HEADCOUNT REDUCTION SYNERGY ===\n")+ print(f"Duplicate Roles: {headcount['duplicate_roles']}")+ print(f"Annual Savings: ${headcount['annual_savings']:,.0f}")+ print(f"Severance Cost: ${headcount['one_time_severance_cost']:,.0f}")+ print(f"NPV: ${headcount['npv']:,.0f}")+ print(f"Payback Period: {headcount['payback_period_years']} years")+ print(f"ROI: {headcount['roi']:.0f}%\n")++ print("Yearly Projections:")+ for proj in headcount['yearly_projections'][:5]:+ print(f" Year {proj['year']}: ${proj['net_cash_flow']:,.0f} (PV: ${proj['present_value']:,.0f})")++ cost_reductions = [+ CostReduction(+ CostSynergyType.HEADCOUNT_REDUCTION,+ "Eliminate duplicate corporate functions",+ 30_000_000,+ 45_000_000,+ 2+ ),+ CostReduction(+ CostSynergyType.FACILITIES_CONSOLIDATION,+ "Close redundant offices",+ 15_000_000,+ 8_000_000,+ 2+ ),+ CostReduction(+ CostSynergyType.PROCUREMENT,+ "Volume purchasing discounts",+ 12_000_000,+ 2_000_000,+ 3+ ),+ CostReduction(+ CostSynergyType.IT_SYSTEMS,+ "Consolidate IT infrastructure",+ 8_000_000,+ 10_000_000,+ 2+ )+ ]++ comprehensive = analyzer.comprehensive_cost_synergy(cost_reductions)++ print("\n\n=== COMPREHENSIVE COST SYNERGY ===")+ print(f"Total Annual Savings (Run-Rate): ${comprehensive['total_annual_savings_run_rate']:,.0f}")+ print(f"Total One-Time Costs: ${comprehensive['total_one_time_costs']:,.0f}")+ print(f"Total NPV: ${comprehensive['total_cost_synergy_npv']:,.0f}")+ print(f"Blended ROI: {comprehensive['blended_roi']:.0f}%\n")++ print("Synergy Breakdown (by NPV):")+ for synergy in comprehensive['synergy_breakdown']:+ print(f"\n{synergy['category'].replace('_', ' ').title()}:")+ print(f" Annual Savings: ${synergy['annual_savings']:,.0f}")+ print(f" One-Time Cost: ${synergy['one_time_cost']:,.0f}")+ print(f" NPV: ${synergy['npv']:,.0f}")+ print(f" ROI: {synergy['roi']:.0f}%")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/integration_costs.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/integration_costs.pynew file mode 100644index 000000000..16443914b--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/integration_costs.py@@ -0,0 +1,401 @@+"""Integration Cost Analysis"""+from typing import Dict, Any, List, Optional+from dataclasses import dataclass+from enum import Enum++class IntegrationCategory(Enum):+ IT_INTEGRATION = "it_integration"+ REBRANDING = "rebranding"+ EMPLOYEE_RETENTION = "employee_retention"+ CHANGE_MANAGEMENT = "change_management"+ LEGAL_REGULATORY = "legal_regulatory"+ ADVISORS_FEES = "advisors_fees"+ FACILITIES = "facilities"+ CUSTOMER_RETENTION = "customer_retention"++@dataclass+class IntegrationCost:+ category: IntegrationCategory+ description: str+ estimated_cost: float+ timing_months: int+ is_capitalized: bool = False++class IntegrationCostAnalyzer:+ """Analyze and track M&A integration costs"""++ def __init__(self, deal_value: float):+ self.deal_value = deal_value++ def estimate_it_integration(self, systems_to_integrate: int,+ complexity_factor: float = 1.0,+ third_party_consulting: bool = True) -> Dict[str, Any]:+ """Estimate IT systems integration costs"""++ base_cost_per_system = 500_000+ consulting_premium = 1.3 if third_party_consulting else 1.0++ integration_cost = systems_to_integrate * base_cost_per_system * complexity_factor * consulting_premium++ data_migration_cost = integration_cost * 0.25+ testing_cost = integration_cost * 0.15+ training_cost = integration_cost * 0.10++ total_cost = integration_cost + data_migration_cost + testing_cost + training_cost++ return {+ 'category': 'it_integration',+ 'systems_to_integrate': systems_to_integrate,+ 'complexity_factor': complexity_factor,+ 'third_party_consulting': third_party_consulting,+ 'base_integration_cost': integration_cost,+ 'data_migration': data_migration_cost,+ 'testing': testing_cost,+ 'training': training_cost,+ 'total_cost': total_cost,+ 'estimated_duration_months': 12 + (systems_to_integrate * 2)+ }++ def estimate_rebranding_cost(self, locations: int,+ digital_properties: int,+ product_rebrand: bool,+ target_revenue: float) -> Dict[str, Any]:+ """Estimate rebranding and marketing integration costs"""++ physical_signage = locations * 25_000+ digital_rebrand = digital_properties * 50_000+ collateral_cost = target_revenue * 0.005++ product_cost = 0+ if product_rebrand:+ product_cost = target_revenue * 0.02++ advertising_campaign = target_revenue * 0.03++ total_cost = physical_signage + digital_rebrand + collateral_cost + product_cost + advertising_campaign++ return {+ 'category': 'rebranding',+ 'locations': locations,+ 'digital_properties': digital_properties,+ 'product_rebrand': product_rebrand,+ 'physical_signage_cost': physical_signage,+ 'digital_rebrand_cost': digital_rebrand,+ 'marketing_collateral': collateral_cost,+ 'product_rebranding': product_cost,+ 'advertising_campaign': advertising_campaign,+ 'total_cost': total_cost,+ 'as_pct_of_revenue': (total_cost / target_revenue * 100) if target_revenue > 0 else 0+ }++ def estimate_retention_programs(self, key_employees: int,+ average_compensation: float,+ retention_bonus_pct: float = 0.50,+ vesting_years: int = 2) -> Dict[str, Any]:+ """Estimate employee retention program costs"""++ retention_pool = key_employees * average_compensation * retention_bonus_pct++ stay_bonus_cost = retention_pool * 0.60+ equity_grant_cost = retention_pool * 0.40++ annual_cost = retention_pool / vesting_years++ return {+ 'category': 'employee_retention',+ 'key_employees': key_employees,+ 'average_compensation': average_compensation,+ 'retention_bonus_pct': retention_bonus_pct * 100,+ 'total_retention_pool': retention_pool,+ 'stay_bonus_component': stay_bonus_cost,+ 'equity_grant_component': equity_grant_cost,+ 'vesting_years': vesting_years,+ 'annual_cost': annual_cost,+ 'cost_per_employee': retention_pool / key_employees if key_employees > 0 else 0+ }++ def estimate_change_management(self, total_employees: int,+ training_hours_per_employee: int,+ external_consultants: bool = True) -> Dict[str, Any]:+ """Estimate change management and training costs"""++ training_cost_per_hour = 150+ training_cost = total_employees * training_hours_per_employee * training_cost_per_hour++ communication_cost = total_employees * 100++ consultant_cost = 0+ if external_consultants:+ consultant_cost = self.deal_value * 0.005++ total_cost = training_cost + communication_cost + consultant_cost++ return {+ 'category': 'change_management',+ 'total_employees': total_employees,+ 'training_hours_per_employee': training_hours_per_employee,+ 'external_consultants': external_consultants,+ 'training_cost': training_cost,+ 'communication_programs': communication_cost,+ 'external_consultants_cost': consultant_cost,+ 'total_cost': total_cost,+ 'cost_per_employee': total_cost / total_employees if total_employees > 0 else 0+ }++ def estimate_legal_regulatory(self, jurisdictions: int,+ regulatory_approvals_needed: int,+ litigation_risk: str = 'medium') -> Dict[str, Any]:+ """Estimate legal and regulatory integration costs"""++ legal_base = jurisdictions * 250_000+ regulatory_filings = regulatory_approvals_needed * 500_000++ litigation_reserves = {+ 'low': 0.002,+ 'medium': 0.005,+ 'high': 0.010+ }++ litigation_reserve = self.deal_value * litigation_reserves.get(litigation_risk, 0.005)++ compliance_cost = jurisdictions * 100_000++ total_cost = legal_base + regulatory_filings + litigation_reserve + compliance_cost++ return {+ 'category': 'legal_regulatory',+ 'jurisdictions': jurisdictions,+ 'regulatory_approvals': regulatory_approvals_needed,+ 'litigation_risk': litigation_risk,+ 'legal_base_cost': legal_base,+ 'regulatory_filings': regulatory_filings,+ 'litigation_reserve': litigation_reserve,+ 'compliance_programs': compliance_cost,+ 'total_cost': total_cost+ }++ def estimate_transaction_fees(self, investment_banker_fee_pct: float = 0.01,+ legal_fees: float = 5_000_000,+ accounting_fees: float = 2_000_000,+ other_advisors: float = 1_000_000) -> Dict[str, Any]:+ """Estimate transaction advisory fees"""++ ib_fee = self.deal_value * investment_banker_fee_pct++ total_cost = ib_fee + legal_fees + accounting_fees + other_advisors++ return {+ 'category': 'advisors_fees',+ 'investment_banking_fee': ib_fee,+ 'ib_fee_percentage': investment_banker_fee_pct * 100,+ 'legal_fees': legal_fees,+ 'accounting_fees': accounting_fees,+ 'other_advisors': other_advisors,+ 'total_cost': total_cost,+ 'as_pct_of_deal_value': (total_cost / self.deal_value * 100) if self.deal_value > 0 else 0+ }++ def estimate_customer_retention(self, at_risk_revenue: float,+ retention_program_intensity: str = 'medium') -> Dict[str, Any]:+ """Estimate customer retention program costs"""++ intensity_factors = {+ 'low': 0.03,+ 'medium': 0.05,+ 'high': 0.08+ }++ program_cost_pct = intensity_factors.get(retention_program_intensity, 0.05)++ program_cost = at_risk_revenue * program_cost_pct++ incentive_cost = at_risk_revenue * 0.02+ relationship_mgmt = program_cost * 0.30++ total_cost = program_cost + incentive_cost + relationship_mgmt++ return {+ 'category': 'customer_retention',+ 'at_risk_revenue': at_risk_revenue,+ 'program_intensity': retention_program_intensity,+ 'retention_program_cost': program_cost,+ 'customer_incentives': incentive_cost,+ 'relationship_management': relationship_mgmt,+ 'total_cost': total_cost,+ 'as_pct_of_at_risk_revenue': (total_cost / at_risk_revenue * 100) if at_risk_revenue > 0 else 0+ }++ def comprehensive_integration_budget(self, integration_costs: List[IntegrationCost]) -> Dict[str, Any]:+ """Create comprehensive integration cost budget"""++ cost_breakdown = []+ total_cost = 0+ capitalized_total = 0+ expensed_total = 0++ by_year = {}++ for cost in integration_costs:+ year = (cost.timing_months - 1) // 12 + 1++ if year not in by_year:+ by_year[year] = 0+ by_year[year] += cost.estimated_cost++ total_cost += cost.estimated_cost++ if cost.is_capitalized:+ capitalized_total += cost.estimated_cost+ else:+ expensed_total += cost.estimated_cost++ cost_breakdown.append({+ 'category': cost.category.value,+ 'description': cost.description,+ 'estimated_cost': cost.estimated_cost,+ 'timing_months': cost.timing_months,+ 'year': year,+ 'is_capitalized': cost.is_capitalized,+ 'treatment': 'capitalized' if cost.is_capitalized else 'expensed'+ })++ cost_breakdown.sort(key=lambda x: x['estimated_cost'], reverse=True)++ yearly_schedule = [{'year': y, 'costs': c} for y, c in sorted(by_year.items())]++ return {+ 'total_integration_cost': total_cost,+ 'capitalized_costs': capitalized_total,+ 'expensed_costs': expensed_total,+ 'as_pct_of_deal_value': (total_cost / self.deal_value * 100) if self.deal_value > 0 else 0,+ 'cost_breakdown': cost_breakdown,+ 'yearly_schedule': yearly_schedule,+ 'peak_year': max(by_year.items(), key=lambda x: x[1])[0] if by_year else None,+ 'integration_duration_months': max(c.timing_months for c in integration_costs) if integration_costs else 0+ }++ def integration_cost_benchmarks(self) -> Dict[str, Any]:+ """Provide industry benchmarks for integration costs"""++ return {+ 'typical_ranges_pct_of_deal': {+ 'total_integration': {'low': 2.0, 'median': 5.0, 'high': 10.0},+ 'it_integration': {'low': 0.5, 'median': 1.5, 'high': 3.0},+ 'severance': {'low': 0.5, 'median': 1.0, 'high': 2.5},+ 'retention': {'low': 0.3, 'median': 0.8, 'high': 1.5},+ 'advisors': {'low': 0.5, 'median': 1.0, 'high': 2.0}+ },+ 'timing_benchmarks': {+ 'it_integration': '12-24 months',+ 'organization_design': '6-12 months',+ 'culture_integration': '18-36 months',+ 'full_integration': '24-36 months'+ },+ 'success_factors': [+ 'Clear day-one priorities',+ 'Dedicated integration team',+ 'Strong executive sponsorship',+ 'Regular communication',+ 'Customer focus',+ 'Quick wins identification'+ ]+ }++ def integration_risk_assessment(self, integration_complexity: str,+ cultural_fit: str,+ size_ratio: float) -> Dict[str, Any]:+ """Assess integration risk and potential cost overruns"""++ complexity_risk = {+ 'low': 1.0,+ 'medium': 1.2,+ 'high': 1.5,+ 'very_high': 2.0+ }++ cultural_risk = {+ 'high': 1.0,+ 'medium': 1.15,+ 'low': 1.3+ }++ size_risk = 1.0+ if size_ratio > 0.5:+ size_risk = 1.2+ if size_ratio > 0.75:+ size_risk = 1.4++ combined_risk_multiplier = (+ complexity_risk.get(integration_complexity, 1.2) *+ cultural_risk.get(cultural_fit, 1.15) *+ size_risk+ )++ risk_rating = 'low'+ if combined_risk_multiplier > 1.5:+ risk_rating = 'high'+ elif combined_risk_multiplier > 1.2:+ risk_rating = 'medium'++ return {+ 'integration_complexity': integration_complexity,+ 'cultural_fit': cultural_fit,+ 'size_ratio': size_ratio,+ 'complexity_multiplier': complexity_risk.get(integration_complexity, 1.2),+ 'cultural_multiplier': cultural_risk.get(cultural_fit, 1.15),+ 'size_multiplier': size_risk,+ 'combined_risk_multiplier': combined_risk_multiplier,+ 'risk_rating': risk_rating,+ 'recommended_contingency_pct': (combined_risk_multiplier - 1) * 100+ }++if __name__ == '__main__':+ analyzer = IntegrationCostAnalyzer(deal_value=500_000_000)++ it_integration = analyzer.estimate_it_integration(+ systems_to_integrate=15,+ complexity_factor=1.3,+ third_party_consulting=True+ )++ print("=== IT INTEGRATION COSTS ===\n")+ print(f"Systems to Integrate: {it_integration['systems_to_integrate']}")+ print(f"Base Integration: ${it_integration['base_integration_cost']:,.0f}")+ print(f"Data Migration: ${it_integration['data_migration']:,.0f}")+ print(f"Testing: ${it_integration['testing']:,.0f}")+ print(f"Training: ${it_integration['training']:,.0f}")+ print(f"Total: ${it_integration['total_cost']:,.0f}")+ print(f"Duration: {it_integration['estimated_duration_months']} months")++ integration_costs = [+ IntegrationCost(IntegrationCategory.IT_INTEGRATION, "IT systems consolidation", 25_000_000, 18, True),+ IntegrationCost(IntegrationCategory.EMPLOYEE_RETENTION, "Key employee retention", 15_000_000, 24, False),+ IntegrationCost(IntegrationCategory.REBRANDING, "Rebranding program", 8_000_000, 12, False),+ IntegrationCost(IntegrationCategory.CHANGE_MANAGEMENT, "Change management", 5_000_000, 24, False),+ IntegrationCost(IntegrationCategory.LEGAL_REGULATORY, "Legal/regulatory", 6_000_000, 12, False),+ IntegrationCost(IntegrationCategory.ADVISORS_FEES, "Transaction advisors", 7_000_000, 6, False)+ ]++ budget = analyzer.comprehensive_integration_budget(integration_costs)++ print("\n\n=== COMPREHENSIVE INTEGRATION BUDGET ===")+ print(f"Total Integration Cost: ${budget['total_integration_cost']:,.0f}")+ print(f"As % of Deal Value: {budget['as_pct_of_deal_value']:.1f}%")+ print(f"Capitalized: ${budget['capitalized_costs']:,.0f}")+ print(f"Expensed: ${budget['expensed_costs']:,.0f}")+ print(f"Duration: {budget['integration_duration_months']} months\n")++ print("Cost Breakdown:")+ for cost in budget['cost_breakdown'][:5]:+ print(f" {cost['category'].replace('_', ' ').title()}: ${cost['estimated_cost']:,.0f} ({cost['treatment']})")++ risk = analyzer.integration_risk_assessment(+ integration_complexity='high',+ cultural_fit='medium',+ size_ratio=0.6+ )++ print(f"\n\n=== INTEGRATION RISK ASSESSMENT ===")+ print(f"Risk Rating: {risk['risk_rating'].upper()}")+ print(f"Combined Risk Multiplier: {risk['combined_risk_multiplier']:.2f}x")+ print(f"Recommended Contingency: {risk['recommended_contingency_pct']:.0f}%")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/revenue_synergies.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/revenue_synergies.pynew file mode 100644index 000000000..54177d28e--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/revenue_synergies.py@@ -0,0 +1,400 @@+"""Revenue Synergy Analysis"""+from typing import Dict, Any, List, Optional+from dataclasses import dataclass+from enum import Enum+import numpy as np++class RevenueSynergyType(Enum):+ CROSS_SELL = "cross_sell"+ MARKET_EXPANSION = "market_expansion"+ PRODUCT_BUNDLING = "product_bundling"+ PRICING_POWER = "pricing_power"+ DISTRIBUTION_ACCESS = "distribution_access"+ CHANNEL_OPTIMIZATION = "channel_optimization"+ BRAND_LEVERAGE = "brand_leverage"++@dataclass+class SynergyOpportunity:+ synergy_type: RevenueSynergyType+ description: str+ addressable_revenue: float+ conversion_rate: float+ ramp_years: int+ steady_state_year: int++class RevenueSynergyAnalyzer:+ """Analyze and quantify revenue synergies in M&A transactions"""++ def __init__(self, tax_rate: float = 0.25,+ synergy_discount_rate: float = 0.15):+ self.tax_rate = tax_rate+ self.synergy_discount_rate = synergy_discount_rate++ def calculate_cross_sell_synergy(self, acquirer_customers: int,+ target_customers: int,+ acquirer_arpu: float,+ target_arpu: float,+ cross_sell_rate: float,+ ramp_years: int = 3) -> Dict[str, Any]:+ """Calculate cross-selling revenue synergy"""++ acquirer_to_target = target_customers * cross_sell_rate * acquirer_arpu+ target_to_acquirer = acquirer_customers * cross_sell_rate * target_arpu++ total_annual_synergy = acquirer_to_target + target_to_acquirer++ yearly_synergies = []+ for year in range(1, ramp_years + 4):+ if year <= ramp_years:+ realization = year / ramp_years+ else:+ realization = 1.0++ synergy = total_annual_synergy * realization+ pv = synergy / ((1 + self.synergy_discount_rate) ** year)++ yearly_synergies.append({+ 'year': year,+ 'realization_pct': realization * 100,+ 'revenue_synergy': synergy,+ 'after_tax': synergy * (1 - self.tax_rate),+ 'present_value': pv * (1 - self.tax_rate)+ })++ total_pv = sum(y['present_value'] for y in yearly_synergies)++ return {+ 'synergy_type': 'cross_sell',+ 'acquirer_customers': acquirer_customers,+ 'target_customers': target_customers,+ 'cross_sell_rate': cross_sell_rate * 100,+ 'acquirer_to_target_synergy': acquirer_to_target,+ 'target_to_acquirer_synergy': target_to_acquirer,+ 'total_annual_synergy': total_annual_synergy,+ 'ramp_years': ramp_years,+ 'yearly_projections': yearly_synergies,+ 'total_pv': total_pv,+ 'tax_rate': self.tax_rate * 100+ }++ def calculate_market_expansion_synergy(self, target_revenue_new_markets: float,+ acquirer_product_penetration: float,+ market_share_gain: float,+ ramp_years: int = 4) -> Dict[str, Any]:+ """Calculate geographic/market expansion synergy"""++ addressable_revenue = target_revenue_new_markets * acquirer_product_penetration+ annual_synergy = addressable_revenue * market_share_gain++ yearly_synergies = []+ for year in range(1, ramp_years + 4):+ if year <= ramp_years:+ realization = (year / ramp_years) ** 0.8+ else:+ realization = 1.0++ synergy = annual_synergy * realization+ pv = synergy / ((1 + self.synergy_discount_rate) ** year)++ yearly_synergies.append({+ 'year': year,+ 'realization_pct': realization * 100,+ 'revenue_synergy': synergy,+ 'after_tax': synergy * (1 - self.tax_rate),+ 'present_value': pv * (1 - self.tax_rate)+ })++ total_pv = sum(y['present_value'] for y in yearly_synergies)++ return {+ 'synergy_type': 'market_expansion',+ 'target_revenue_new_markets': target_revenue_new_markets,+ 'acquirer_product_penetration': acquirer_product_penetration * 100,+ 'market_share_gain': market_share_gain * 100,+ 'addressable_revenue': addressable_revenue,+ 'annual_synergy_steady_state': annual_synergy,+ 'ramp_years': ramp_years,+ 'yearly_projections': yearly_synergies,+ 'total_pv': total_pv+ }++ def calculate_product_bundling_synergy(self, standalone_products: List[Dict[str, float]],+ bundle_price_premium: float,+ bundle_adoption_rate: float,+ churn_reduction: float,+ ramp_years: int = 2) -> Dict[str, Any]:+ """Calculate product bundling synergy"""++ total_standalone_revenue = sum(p['revenue'] for p in standalone_products)++ bundle_revenue_lift = total_standalone_revenue * bundle_price_premium * bundle_adoption_rate++ retention_value = total_standalone_revenue * bundle_adoption_rate * churn_reduction++ total_annual_synergy = bundle_revenue_lift + retention_value++ yearly_synergies = []+ for year in range(1, ramp_years + 4):+ if year <= ramp_years:+ realization = year / ramp_years+ else:+ realization = 1.0++ synergy = total_annual_synergy * realization+ pv = synergy / ((1 + self.synergy_discount_rate) ** year)++ yearly_synergies.append({+ 'year': year,+ 'realization_pct': realization * 100,+ 'revenue_synergy': synergy,+ 'bundle_lift_component': bundle_revenue_lift * realization,+ 'retention_component': retention_value * realization,+ 'present_value': pv * (1 - self.tax_rate)+ })++ total_pv = sum(y['present_value'] for y in yearly_synergies)++ return {+ 'synergy_type': 'product_bundling',+ 'standalone_products': standalone_products,+ 'total_standalone_revenue': total_standalone_revenue,+ 'bundle_price_premium': bundle_price_premium * 100,+ 'bundle_adoption_rate': bundle_adoption_rate * 100,+ 'bundle_revenue_lift': bundle_revenue_lift,+ 'retention_value': retention_value,+ 'total_annual_synergy': total_annual_synergy,+ 'yearly_projections': yearly_synergies,+ 'total_pv': total_pv+ }++ def calculate_pricing_power_synergy(self, combined_revenue: float,+ price_increase: float,+ volume_elasticity: float,+ market_share: float,+ ramp_years: int = 3) -> Dict[str, Any]:+ """Calculate pricing power synergy from reduced competition"""++ volume_impact = -1 * price_increase * volume_elasticity++ net_revenue_impact = combined_revenue * (price_increase + volume_impact)++ concentration_risk_factor = 1 - (market_share * 0.5)+ risk_adjusted_synergy = net_revenue_impact * concentration_risk_factor++ yearly_synergies = []+ for year in range(1, ramp_years + 4):+ if year <= ramp_years:+ realization = year / ramp_years+ else:+ realization = 1.0++ synergy = risk_adjusted_synergy * realization+ pv = synergy / ((1 + self.synergy_discount_rate) ** year)++ yearly_synergies.append({+ 'year': year,+ 'realization_pct': realization * 100,+ 'revenue_synergy': synergy,+ 'present_value': pv * (1 - self.tax_rate)+ })++ total_pv = sum(y['present_value'] for y in yearly_synergies)++ return {+ 'synergy_type': 'pricing_power',+ 'combined_revenue': combined_revenue,+ 'price_increase': price_increase * 100,+ 'volume_elasticity': volume_elasticity,+ 'volume_impact': volume_impact * 100,+ 'gross_revenue_impact': net_revenue_impact,+ 'concentration_risk_factor': concentration_risk_factor,+ 'risk_adjusted_synergy': risk_adjusted_synergy,+ 'yearly_projections': yearly_synergies,+ 'total_pv': total_pv+ }++ def calculate_distribution_synergy(self, target_revenue: float,+ acquirer_distribution_advantage: float,+ incremental_reach: float,+ ramp_years: int = 3) -> Dict[str, Any]:+ """Calculate distribution channel synergy"""++ addressable_revenue = target_revenue * incremental_reach++ revenue_uplift = addressable_revenue * acquirer_distribution_advantage++ yearly_synergies = []+ for year in range(1, ramp_years + 4):+ if year <= ramp_years:+ realization = year / ramp_years+ else:+ realization = 1.0++ synergy = revenue_uplift * realization+ pv = synergy / ((1 + self.synergy_discount_rate) ** year)++ yearly_synergies.append({+ 'year': year,+ 'realization_pct': realization * 100,+ 'revenue_synergy': synergy,+ 'present_value': pv * (1 - self.tax_rate)+ })++ total_pv = sum(y['present_value'] for y in yearly_synergies)++ return {+ 'synergy_type': 'distribution',+ 'target_revenue': target_revenue,+ 'acquirer_distribution_advantage': acquirer_distribution_advantage * 100,+ 'incremental_reach': incremental_reach * 100,+ 'addressable_revenue': addressable_revenue,+ 'annual_revenue_uplift': revenue_uplift,+ 'yearly_projections': yearly_synergies,+ 'total_pv': total_pv+ }++ def comprehensive_revenue_synergy(self, opportunities: List[SynergyOpportunity]) -> Dict[str, Any]:+ """Aggregate multiple revenue synergy opportunities"""++ synergy_breakdown = []+ total_pv = 0++ for opp in opportunities:+ annual_synergy = opp.addressable_revenue * opp.conversion_rate++ yearly_projections = []+ for year in range(1, 7):+ if year <= opp.ramp_years:+ realization = year / opp.ramp_years+ elif year < opp.steady_state_year:+ realization = 1.0+ else:+ realization = 1.0++ synergy = annual_synergy * realization+ pv = synergy / ((1 + self.synergy_discount_rate) ** year)++ yearly_projections.append({+ 'year': year,+ 'synergy': synergy,+ 'present_value': pv * (1 - self.tax_rate)+ })++ opp_pv = sum(y['present_value'] for y in yearly_projections)+ total_pv += opp_pv++ synergy_breakdown.append({+ 'synergy_type': opp.synergy_type.value,+ 'description': opp.description,+ 'addressable_revenue': opp.addressable_revenue,+ 'conversion_rate': opp.conversion_rate * 100,+ 'annual_synergy_steady_state': annual_synergy,+ 'ramp_years': opp.ramp_years,+ 'present_value': opp_pv,+ 'yearly_projections': yearly_projections+ })++ return {+ 'total_revenue_synergy_pv': total_pv,+ 'synergy_breakdown': synergy_breakdown,+ 'number_of_opportunities': len(opportunities),+ 'discount_rate': self.synergy_discount_rate * 100,+ 'tax_rate': self.tax_rate * 100+ }++ def synergy_risk_adjustment(self, base_synergy_pv: float,+ execution_risk: str = 'medium',+ timing_risk: str = 'medium') -> Dict[str, Any]:+ """Apply risk adjustments to revenue synergy estimates"""++ execution_discounts = {+ 'low': 0.10,+ 'medium': 0.25,+ 'high': 0.40,+ 'very_high': 0.60+ }++ timing_discounts = {+ 'low': 0.05,+ 'medium': 0.15,+ 'high': 0.25+ }++ exec_discount = execution_discounts.get(execution_risk, 0.25)+ timing_discount = timing_discounts.get(timing_risk, 0.15)++ combined_discount = exec_discount + timing_discount - (exec_discount * timing_discount)++ risk_adjusted_pv = base_synergy_pv * (1 - combined_discount)++ return {+ 'base_synergy_pv': base_synergy_pv,+ 'execution_risk': execution_risk,+ 'timing_risk': timing_risk,+ 'execution_discount': exec_discount * 100,+ 'timing_discount': timing_discount * 100,+ 'combined_discount': combined_discount * 100,+ 'risk_adjusted_synergy_pv': risk_adjusted_pv,+ 'haircut_amount': base_synergy_pv - risk_adjusted_pv+ }++if __name__ == '__main__':+ analyzer = RevenueSynergyAnalyzer(tax_rate=0.25, synergy_discount_rate=0.15)++ cross_sell = analyzer.calculate_cross_sell_synergy(+ acquirer_customers=1_000_000,+ target_customers=500_000,+ acquirer_arpu=100,+ target_arpu=80,+ cross_sell_rate=0.15,+ ramp_years=3+ )++ print("=== CROSS-SELL REVENUE SYNERGY ===\n")+ print(f"Total Annual Synergy (Steady State): ${cross_sell['total_annual_synergy']:,.0f}")+ print(f"Cross-Sell Rate: {cross_sell['cross_sell_rate']:.0f}%")+ print(f"Ramp Period: {cross_sell['ramp_years']} years")+ print(f"Total PV: ${cross_sell['total_pv']:,.0f}\n")++ print("Yearly Projections:")+ for proj in cross_sell['yearly_projections'][:5]:+ print(f" Year {proj['year']}: ${proj['revenue_synergy']:,.0f} (PV: ${proj['present_value']:,.0f})")++ opportunities = [+ SynergyOpportunity(+ RevenueSynergyType.CROSS_SELL,+ "Cross-sell acquirer products to target customers",+ 50_000_000,+ 0.20,+ 3,+ 4+ ),+ SynergyOpportunity(+ RevenueSynergyType.MARKET_EXPANSION,+ "Expand target product to acquirer's APAC markets",+ 30_000_000,+ 0.15,+ 4,+ 5+ ),+ SynergyOpportunity(+ RevenueSynergyType.PRODUCT_BUNDLING,+ "Bundle complementary products",+ 40_000_000,+ 0.25,+ 2,+ 3+ )+ ]++ comprehensive = analyzer.comprehensive_revenue_synergy(opportunities)++ print("\n\n=== COMPREHENSIVE REVENUE SYNERGY ===")+ print(f"Total Revenue Synergy PV: ${comprehensive['total_revenue_synergy_pv']:,.0f}")+ print(f"Number of Opportunities: {comprehensive['number_of_opportunities']}\n")++ for synergy in comprehensive['synergy_breakdown']:+ print(f"\n{synergy['synergy_type'].replace('_', ' ').title()}:")+ print(f" Description: {synergy['description']}")+ print(f" Annual Synergy: ${synergy['annual_synergy_steady_state']:,.0f}")+ print(f" PV: ${synergy['present_value']:,.0f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/synergy_valuation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/synergy_valuation.pynew file mode 100644index 000000000..a4c28bced--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/synergies/synergy_valuation.py@@ -0,0 +1,346 @@+"""Comprehensive Synergy Valuation"""+from typing import Dict, Any, List, Optional+import numpy as np++class SynergyValuation:+ """Comprehensive synergy valuation combining revenue and cost synergies"""++ def __init__(self, wacc: float = 0.10,+ terminal_growth_rate: float = 0.02,+ tax_rate: float = 0.25):+ self.wacc = wacc+ self.terminal_growth_rate = terminal_growth_rate+ self.tax_rate = tax_rate++ def value_synergies_dcf(self, annual_revenue_synergies: List[float],+ annual_cost_synergies: List[float],+ integration_costs_by_year: List[float],+ projection_years: int = 10) -> Dict[str, Any]:+ """Value synergies using DCF methodology"""++ if len(annual_revenue_synergies) < projection_years:+ last_revenue = annual_revenue_synergies[-1] if annual_revenue_synergies else 0+ annual_revenue_synergies.extend([last_revenue] * (projection_years - len(annual_revenue_synergies)))++ if len(annual_cost_synergies) < projection_years:+ last_cost = annual_cost_synergies[-1] if annual_cost_synergies else 0+ annual_cost_synergies.extend([last_cost] * (projection_years - len(annual_cost_synergies)))++ if len(integration_costs_by_year) < projection_years:+ integration_costs_by_year.extend([0] * (projection_years - len(integration_costs_by_year)))++ yearly_cash_flows = []+ total_pv = 0++ for year in range(1, projection_years + 1):+ idx = year - 1++ revenue_synergy = annual_revenue_synergies[idx]+ cost_synergy = annual_cost_synergies[idx]+ integration_cost = integration_costs_by_year[idx]++ gross_synergy = revenue_synergy + cost_synergy+ after_tax_synergy = gross_synergy * (1 - self.tax_rate)+ net_cash_flow = after_tax_synergy - integration_cost++ discount_factor = (1 + self.wacc) ** year+ pv = net_cash_flow / discount_factor++ total_pv += pv++ yearly_cash_flows.append({+ 'year': year,+ 'revenue_synergy': revenue_synergy,+ 'cost_synergy': cost_synergy,+ 'integration_cost': integration_cost,+ 'gross_synergy': gross_synergy,+ 'after_tax_synergy': after_tax_synergy,+ 'net_cash_flow': net_cash_flow,+ 'discount_factor': discount_factor,+ 'present_value': pv+ })++ terminal_year_synergy = gross_synergy * (1 - self.tax_rate)+ terminal_value = terminal_year_synergy * (1 + self.terminal_growth_rate) / (self.wacc - self.terminal_growth_rate)+ terminal_pv = terminal_value / ((1 + self.wacc) ** projection_years)++ total_synergy_value = total_pv + terminal_pv++ return {+ 'explicit_forecast_pv': total_pv,+ 'terminal_value': terminal_value,+ 'terminal_value_pv': terminal_pv,+ 'total_synergy_value': total_synergy_value,+ 'terminal_value_pct': (terminal_pv / total_synergy_value * 100) if total_synergy_value > 0 else 0,+ 'yearly_projections': yearly_cash_flows,+ 'valuation_assumptions': {+ 'wacc': self.wacc * 100,+ 'terminal_growth_rate': self.terminal_growth_rate * 100,+ 'tax_rate': self.tax_rate * 100,+ 'projection_years': projection_years+ }+ }++ def calculate_synergy_multiple(self, total_synergy_value: float,+ purchase_price: float,+ standalone_target_value: Optional[float] = None) -> Dict[str, Any]:+ """Calculate synergy contribution to deal value"""++ if standalone_target_value:+ premium_paid = purchase_price - standalone_target_value+ synergy_captured_by_acquirer = total_synergy_value - premium_paid+ synergy_split_acquirer = (synergy_captured_by_acquirer / total_synergy_value * 100) if total_synergy_value > 0 else 0+ synergy_split_target = 100 - synergy_split_acquirer+ else:+ premium_paid = None+ synergy_captured_by_acquirer = None+ synergy_split_acquirer = None+ synergy_split_target = None++ synergy_to_price_ratio = (total_synergy_value / purchase_price * 100) if purchase_price > 0 else 0++ return {+ 'total_synergy_value': total_synergy_value,+ 'purchase_price': purchase_price,+ 'standalone_target_value': standalone_target_value,+ 'premium_paid': premium_paid,+ 'synergy_captured_by_acquirer': synergy_captured_by_acquirer,+ 'synergy_split': {+ 'acquirer_pct': synergy_split_acquirer,+ 'target_pct': synergy_split_target+ },+ 'synergy_to_price_ratio': synergy_to_price_ratio,+ 'value_creation_analysis': {+ 'creates_value': total_synergy_value > (premium_paid if premium_paid else 0),+ 'npv_of_deal': total_synergy_value - (premium_paid if premium_paid else 0) if premium_paid else None+ }+ }++ def synergy_sensitivity_analysis(self, base_revenue_synergy: float,+ base_cost_synergy: float,+ revenue_scenarios: List[float],+ cost_scenarios: List[float]) -> Dict[str, Any]:+ """Two-way sensitivity analysis for synergy assumptions"""++ sensitivity_matrix = []++ for revenue_mult in revenue_scenarios:+ for cost_mult in cost_scenarios:+ revenue_synergy = base_revenue_synergy * revenue_mult+ cost_synergy = base_cost_synergy * cost_mult++ total_synergy = revenue_synergy + cost_synergy+ after_tax = total_synergy * (1 - self.tax_rate)++ perpetuity_value = after_tax / self.wacc++ sensitivity_matrix.append({+ 'revenue_multiplier': revenue_mult,+ 'cost_multiplier': cost_mult,+ 'revenue_synergy': revenue_synergy,+ 'cost_synergy': cost_synergy,+ 'total_synergy': total_synergy,+ 'synergy_value': perpetuity_value+ })++ min_value = min(s['synergy_value'] for s in sensitivity_matrix)+ max_value = max(s['synergy_value'] for s in sensitivity_matrix)+ base_case = [s for s in sensitivity_matrix if s['revenue_multiplier'] == 1.0 and s['cost_multiplier'] == 1.0][0]++ return {+ 'sensitivity_matrix': sensitivity_matrix,+ 'value_range': {+ 'min': min_value,+ 'max': max_value,+ 'base': base_case['synergy_value']+ },+ 'base_assumptions': {+ 'revenue_synergy': base_revenue_synergy,+ 'cost_synergy': base_cost_synergy+ }+ }++ def calculate_probability_adjusted_synergies(self, synergy_scenarios: List[Dict[str, Any]]) -> Dict[str, Any]:+ """Calculate probability-weighted synergy value"""++ total_probability = sum(s['probability'] for s in synergy_scenarios)+ if abs(total_probability - 1.0) > 0.01:+ raise ValueError(f"Probabilities must sum to 1.0, got {total_probability}")++ scenario_analysis = []+ expected_value = 0++ for scenario in synergy_scenarios:+ synergy_value = scenario['synergy_value']+ probability = scenario['probability']+ weighted_value = synergy_value * probability++ expected_value += weighted_value++ scenario_analysis.append({+ 'scenario_name': scenario['name'],+ 'probability': probability * 100,+ 'synergy_value': synergy_value,+ 'weighted_value': weighted_value+ })++ values = [s['synergy_value'] for s in synergy_scenarios]+ std_dev = np.std(values)+ cv = (std_dev / expected_value * 100) if expected_value > 0 else 0++ return {+ 'expected_synergy_value': expected_value,+ 'scenarios': scenario_analysis,+ 'value_range': {+ 'min': min(values),+ 'max': max(values)+ },+ 'standard_deviation': std_dev,+ 'coefficient_of_variation': cv+ }++ def synergy_realization_schedule(self, total_synergies: float,+ realization_curve: str = 'linear',+ full_realization_years: int = 3) -> Dict[str, Any]:+ """Model synergy realization over time"""++ yearly_realization = []++ for year in range(1, full_realization_years + 4):+ if realization_curve == 'linear':+ if year <= full_realization_years:+ pct = year / full_realization_years+ else:+ pct = 1.0++ elif realization_curve == 's_curve':+ if year <= full_realization_years:+ pct = (year / full_realization_years) ** 0.7+ else:+ pct = 1.0++ elif realization_curve == 'front_loaded':+ if year <= full_realization_years:+ pct = 1 - (1 - year / full_realization_years) ** 2+ else:+ pct = 1.0++ else:+ pct = year / full_realization_years if year <= full_realization_years else 1.0++ synergy_realized = total_synergies * pct++ yearly_realization.append({+ 'year': year,+ 'realization_pct': pct * 100,+ 'synergies_realized': synergy_realized,+ 'incremental_synergies': synergy_realized - (yearly_realization[-1]['synergies_realized'] if year > 1 else 0)+ })++ return {+ 'total_synergies': total_synergies,+ 'realization_curve': realization_curve,+ 'full_realization_years': full_realization_years,+ 'yearly_schedule': yearly_realization+ }++ def compare_deal_with_without_synergies(self, purchase_price: float,+ standalone_target_value: float,+ synergy_value: float,+ acquirer_market_cap: float) -> Dict[str, Any]:+ """Compare deal economics with and without synergies"""++ premium_paid = purchase_price - standalone_target_value+ premium_pct = (premium_paid / standalone_target_value * 100) if standalone_target_value > 0 else 0++ without_synergies_npv = -premium_paid+ with_synergies_npv = synergy_value - premium_paid++ value_creation = with_synergies_npv > 0++ implied_acquirer_value_change = with_synergies_npv+ implied_stock_impact = (implied_acquirer_value_change / acquirer_market_cap * 100) if acquirer_market_cap > 0 else 0++ return {+ 'purchase_price': purchase_price,+ 'standalone_target_value': standalone_target_value,+ 'premium_paid': premium_paid,+ 'premium_pct': premium_pct,+ 'synergy_value': synergy_value,+ 'without_synergies': {+ 'npv': without_synergies_npv,+ 'destroys_value': without_synergies_npv < 0+ },+ 'with_synergies': {+ 'npv': with_synergies_npv,+ 'creates_value': value_creation+ },+ 'synergy_impact': {+ 'value_swing': with_synergies_npv - without_synergies_npv,+ 'synergy_justifies_premium': synergy_value > premium_paid+ },+ 'acquirer_impact': {+ 'market_cap': acquirer_market_cap,+ 'implied_value_change': implied_acquirer_value_change,+ 'implied_stock_impact_pct': implied_stock_impact+ }+ }++if __name__ == '__main__':+ valuator = SynergyValuation(wacc=0.10, terminal_growth_rate=0.02, tax_rate=0.25)++ revenue_synergies = [10_000_000, 20_000_000, 35_000_000, 50_000_000, 60_000_000,+ 70_000_000, 80_000_000, 80_000_000, 80_000_000, 80_000_000]+ cost_synergies = [15_000_000, 30_000_000, 45_000_000, 60_000_000, 65_000_000,+ 65_000_000, 65_000_000, 65_000_000, 65_000_000, 65_000_000]+ integration_costs = [25_000_000, 35_000_000, 15_000_000, 5_000_000, 0,+ 0, 0, 0, 0, 0]++ dcf_value = valuator.value_synergies_dcf(+ annual_revenue_synergies=revenue_synergies,+ annual_cost_synergies=cost_synergies,+ integration_costs_by_year=integration_costs,+ projection_years=10+ )++ print("=== SYNERGY DCF VALUATION ===\n")+ print(f"Explicit Forecast PV: ${dcf_value['explicit_forecast_pv']:,.0f}")+ print(f"Terminal Value: ${dcf_value['terminal_value']:,.0f}")+ print(f"Terminal Value PV: ${dcf_value['terminal_value_pv']:,.0f}")+ print(f"Total Synergy Value: ${dcf_value['total_synergy_value']:,.0f}")+ print(f"Terminal Value %: {dcf_value['terminal_value_pct']:.1f}%\n")++ print("First 5 Years:")+ for year in dcf_value['yearly_projections'][:5]:+ print(f" Year {year['year']}: Rev ${year['revenue_synergy']:,.0f} + Cost ${year['cost_synergy']:,.0f} - Integration ${year['integration_cost']:,.0f} = PV ${year['present_value']:,.0f}")++ comparison = valuator.compare_deal_with_without_synergies(+ purchase_price=800_000_000,+ standalone_target_value=650_000_000,+ synergy_value=dcf_value['total_synergy_value'],+ acquirer_market_cap=5_000_000_000+ )++ print("\n\n=== DEAL ECONOMICS COMPARISON ===")+ print(f"Purchase Price: ${comparison['purchase_price']:,.0f}")+ print(f"Standalone Value: ${comparison['standalone_target_value']:,.0f}")+ print(f"Premium Paid: ${comparison['premium_paid']:,.0f} ({comparison['premium_pct']:.1f}%)")+ print(f"\nWithout Synergies NPV: ${comparison['without_synergies']['npv']:,.0f}")+ print(f"With Synergies NPV: ${comparison['with_synergies']['npv']:,.0f}")+ print(f"Value Creation: {comparison['with_synergies']['creates_value']}")+ print(f"Synergies Justify Premium: {comparison['synergy_impact']['synergy_justifies_premium']}")++ scenarios = [+ {'name': 'Bear Case', 'synergy_value': dcf_value['total_synergy_value'] * 0.6, 'probability': 0.25},+ {'name': 'Base Case', 'synergy_value': dcf_value['total_synergy_value'], 'probability': 0.50},+ {'name': 'Bull Case', 'synergy_value': dcf_value['total_synergy_value'] * 1.4, 'probability': 0.25}+ ]++ prob_adjusted = valuator.calculate_probability_adjusted_synergies(scenarios)++ print("\n\n=== PROBABILITY-ADJUSTED SYNERGIES ===")+ print(f"Expected Value: ${prob_adjusted['expected_synergy_value']:,.0f}")+ print(f"Range: ${prob_adjusted['value_range']['min']:,.0f} - ${prob_adjusted['value_range']['max']:,.0f}")+ print(f"\nScenarios:")+ for scenario in prob_adjusted['scenarios']:+ print(f" {scenario['scenario_name']}: ${scenario['synergy_value']:,.0f} ({scenario['probability']:.0f}% prob)")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/__init__.pynew file mode 100644index 000000000..3edbac122--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/__init__.py@@ -0,0 +1,7 @@+"""Valuation Analysis Module"""+from .precedent_transactions import PrecedentTransactionAnalyzer+from .trading_comps import TradingCompsAnalyzer+from .football_field import FootballFieldChart+from .valuation_summary import ValuationSummary++__all__ = ['PrecedentTransactionAnalyzer', 'TradingCompsAnalyzer', 'FootballFieldChart', 'ValuationSummary']diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/dcf_model.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/dcf_model.pynew file mode 100644index 000000000..557045024--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/dcf_model.py@@ -0,0 +1,357 @@+"""Discounted Cash Flow (DCF) Valuation Model"""+from typing import Dict, Any, List, Optional+import numpy as np++class DCFModel:+ """Comprehensive DCF valuation model"""++ def __init__(self, company_name: str):+ self.company_name = company_name++ def calculate_wacc(self, risk_free_rate: float,+ market_risk_premium: float,+ beta: float,+ cost_of_debt: float,+ tax_rate: float,+ market_value_equity: float,+ market_value_debt: float) -> Dict[str, Any]:+ """Calculate Weighted Average Cost of Capital"""++ cost_of_equity = risk_free_rate + (beta * market_risk_premium)++ after_tax_cost_of_debt = cost_of_debt * (1 - tax_rate)++ total_value = market_value_equity + market_value_debt+ equity_weight = market_value_equity / total_value if total_value > 0 else 0+ debt_weight = market_value_debt / total_value if total_value > 0 else 0++ wacc = (equity_weight * cost_of_equity) + (debt_weight * after_tax_cost_of_debt)++ return {+ 'wacc': wacc,+ 'wacc_pct': wacc * 100,+ 'cost_of_equity': cost_of_equity * 100,+ 'cost_of_equity_pretax': cost_of_equity,+ 'cost_of_debt_pretax': cost_of_debt * 100,+ 'cost_of_debt_aftertax': after_tax_cost_of_debt * 100,+ 'equity_weight': equity_weight * 100,+ 'debt_weight': debt_weight * 100,+ 'inputs': {+ 'risk_free_rate': risk_free_rate * 100,+ 'market_risk_premium': market_risk_premium * 100,+ 'beta': beta,+ 'tax_rate': tax_rate * 100+ }+ }++ def calculate_free_cash_flow(self, ebit: float,+ tax_rate: float,+ depreciation: float,+ capex: float,+ change_in_nwc: float) -> Dict[str, Any]:+ """Calculate Free Cash Flow to Firm"""++ nopat = ebit * (1 - tax_rate)++ fcf = nopat + depreciation - capex - change_in_nwc++ return {+ 'ebit': ebit,+ 'tax': ebit * tax_rate,+ 'nopat': nopat,+ 'add_depreciation': depreciation,+ 'less_capex': capex,+ 'less_change_in_nwc': change_in_nwc,+ 'free_cash_flow': fcf+ }++ def project_cash_flows(self, base_year_fcf: float,+ growth_rates: List[float]) -> List[Dict[str, Any]]:+ """Project future free cash flows"""++ projections = []+ current_fcf = base_year_fcf++ for year, growth_rate in enumerate(growth_rates, 1):+ current_fcf = current_fcf * (1 + growth_rate)++ projections.append({+ 'year': year,+ 'growth_rate': growth_rate * 100,+ 'fcf': current_fcf+ })++ return projections++ def calculate_terminal_value(self, final_year_fcf: float,+ terminal_growth_rate: float,+ wacc: float,+ method: str = 'perpetuity') -> Dict[str, Any]:+ """Calculate terminal value using perpetuity growth or exit multiple"""++ if method == 'perpetuity':+ if wacc <= terminal_growth_rate:+ raise ValueError("WACC must be greater than terminal growth rate")++ terminal_value = (final_year_fcf * (1 + terminal_growth_rate)) / (wacc - terminal_growth_rate)++ return {+ 'method': 'perpetuity_growth',+ 'terminal_value': terminal_value,+ 'terminal_growth_rate': terminal_growth_rate * 100,+ 'terminal_year_fcf': final_year_fcf,+ 'wacc': wacc * 100+ }++ else:+ raise ValueError("Only perpetuity method supported currently")++ def calculate_enterprise_value(self, fcf_projections: List[float],+ terminal_value: float,+ wacc: float) -> Dict[str, Any]:+ """Calculate enterprise value from DCF"""++ pv_fcf_list = []+ pv_fcf_total = 0++ for year, fcf in enumerate(fcf_projections, 1):+ discount_factor = (1 + wacc) ** year+ pv = fcf / discount_factor++ pv_fcf_total += pv++ pv_fcf_list.append({+ 'year': year,+ 'fcf': fcf,+ 'discount_factor': discount_factor,+ 'present_value': pv+ })++ terminal_year = len(fcf_projections)+ terminal_discount_factor = (1 + wacc) ** terminal_year+ pv_terminal_value = terminal_value / terminal_discount_factor++ enterprise_value = pv_fcf_total + pv_terminal_value++ return {+ 'pv_of_fcf': pv_fcf_total,+ 'pv_of_terminal_value': pv_terminal_value,+ 'enterprise_value': enterprise_value,+ 'terminal_value_contribution': (pv_terminal_value / enterprise_value * 100) if enterprise_value > 0 else 0,+ 'fcf_details': pv_fcf_list,+ 'wacc_used': wacc * 100+ }++ def calculate_equity_value(self, enterprise_value: float,+ cash: float,+ debt: float,+ minority_interest: float = 0,+ preferred_stock: float = 0) -> Dict[str, Any]:+ """Convert enterprise value to equity value"""++ equity_value = enterprise_value + cash - debt - minority_interest - preferred_stock++ return {+ 'enterprise_value': enterprise_value,+ 'add_cash': cash,+ 'less_debt': debt,+ 'less_minority_interest': minority_interest,+ 'less_preferred_stock': preferred_stock,+ 'equity_value': equity_value+ }++ def calculate_price_per_share(self, equity_value: float,+ shares_outstanding: float,+ diluted_shares: Optional[float] = None) -> Dict[str, Any]:+ """Calculate price per share"""++ shares = diluted_shares if diluted_shares else shares_outstanding++ price_per_share = equity_value / shares if shares > 0 else 0++ return {+ 'equity_value': equity_value,+ 'shares_outstanding_basic': shares_outstanding,+ 'shares_outstanding_diluted': diluted_shares,+ 'shares_used': shares,+ 'price_per_share': price_per_share+ }++ def comprehensive_dcf(self, wacc_inputs: Dict[str, float],+ fcf_inputs: Dict[str, float],+ growth_rates: List[float],+ terminal_growth_rate: float,+ balance_sheet: Dict[str, float],+ shares_outstanding: float) -> Dict[str, Any]:+ """Complete DCF valuation from inputs to price per share"""++ wacc_result = self.calculate_wacc(**wacc_inputs)+ wacc = wacc_result['wacc']++ base_fcf_calc = self.calculate_free_cash_flow(**fcf_inputs)+ base_fcf = base_fcf_calc['free_cash_flow']++ fcf_projections = self.project_cash_flows(base_fcf, growth_rates)+ fcf_values = [p['fcf'] for p in fcf_projections]++ terminal_value_result = self.calculate_terminal_value(+ fcf_values[-1],+ terminal_growth_rate,+ wacc+ )++ ev_result = self.calculate_enterprise_value(+ fcf_values,+ terminal_value_result['terminal_value'],+ wacc+ )++ equity_result = self.calculate_equity_value(+ ev_result['enterprise_value'],+ balance_sheet['cash'],+ balance_sheet['debt'],+ balance_sheet.get('minority_interest', 0),+ balance_sheet.get('preferred_stock', 0)+ )++ price_result = self.calculate_price_per_share(+ equity_result['equity_value'],+ shares_outstanding,+ balance_sheet.get('diluted_shares')+ )++ return {+ 'company_name': self.company_name,+ 'wacc': wacc_result,+ 'base_year_fcf': base_fcf_calc,+ 'fcf_projections': fcf_projections,+ 'terminal_value': terminal_value_result,+ 'enterprise_value': ev_result,+ 'equity_value': equity_result,+ 'valuation_per_share': price_result,+ 'summary': {+ 'enterprise_value': ev_result['enterprise_value'],+ 'equity_value': equity_result['equity_value'],+ 'price_per_share': price_result['price_per_share'],+ 'wacc': wacc * 100,+ 'terminal_growth': terminal_growth_rate * 100+ }+ }++ def sensitivity_analysis(self, base_fcf: float,+ growth_rates: List[float],+ terminal_growth_scenarios: List[float],+ wacc_scenarios: List[float],+ balance_sheet: Dict[str, float],+ shares_outstanding: float) -> Dict[str, Any]:+ """Two-way sensitivity analysis (WACC vs Terminal Growth)"""++ sensitivity_matrix = []++ for terminal_growth in terminal_growth_scenarios:+ for wacc in wacc_scenarios:+ if wacc <= terminal_growth:+ continue++ fcf_projections_calc = self.project_cash_flows(base_fcf, growth_rates)+ fcf_values = [p['fcf'] for p in fcf_projections_calc]++ terminal_value_calc = self.calculate_terminal_value(+ fcf_values[-1],+ terminal_growth,+ wacc+ )++ ev_calc = self.calculate_enterprise_value(+ fcf_values,+ terminal_value_calc['terminal_value'],+ wacc+ )++ equity_calc = self.calculate_equity_value(+ ev_calc['enterprise_value'],+ balance_sheet['cash'],+ balance_sheet['debt'],+ balance_sheet.get('minority_interest', 0),+ balance_sheet.get('preferred_stock', 0)+ )++ price_calc = self.calculate_price_per_share(+ equity_calc['equity_value'],+ shares_outstanding+ )++ sensitivity_matrix.append({+ 'wacc': wacc * 100,+ 'terminal_growth': terminal_growth * 100,+ 'price_per_share': price_calc['price_per_share'],+ 'equity_value': equity_calc['equity_value']+ })++ return {+ 'sensitivity_matrix': sensitivity_matrix,+ 'wacc_range': [min(wacc_scenarios) * 100, max(wacc_scenarios) * 100],+ 'terminal_growth_range': [min(terminal_growth_scenarios) * 100, max(terminal_growth_scenarios) * 100]+ }++if __name__ == '__main__':+ dcf = DCFModel("Target Corp")++ wacc_inputs = {+ 'risk_free_rate': 0.04,+ 'market_risk_premium': 0.06,+ 'beta': 1.2,+ 'cost_of_debt': 0.05,+ 'tax_rate': 0.25,+ 'market_value_equity': 5_000_000_000,+ 'market_value_debt': 1_000_000_000+ }++ fcf_inputs = {+ 'ebit': 500_000_000,+ 'tax_rate': 0.25,+ 'depreciation': 100_000_000,+ 'capex': 120_000_000,+ 'change_in_nwc': 30_000_000+ }++ growth_rates = [0.10, 0.10, 0.08, 0.08, 0.06]++ balance_sheet = {+ 'cash': 200_000_000,+ 'debt': 1_000_000_000,+ 'minority_interest': 0,+ 'preferred_stock': 0+ }++ result = dcf.comprehensive_dcf(+ wacc_inputs=wacc_inputs,+ fcf_inputs=fcf_inputs,+ growth_rates=growth_rates,+ terminal_growth_rate=0.02,+ balance_sheet=balance_sheet,+ shares_outstanding=100_000_000+ )++ print("=== DCF VALUATION ===\n")+ print(f"Company: {result['company_name']}")+ print(f"\nWACC: {result['wacc']['wacc_pct']:.2f}%")+ print(f" Cost of Equity: {result['wacc']['cost_of_equity']:.2f}%")+ print(f" After-Tax Cost of Debt: {result['wacc']['cost_of_debt_aftertax']:.2f}%")++ print(f"\nBase Year FCF: ${result['base_year_fcf']['free_cash_flow']:,.0f}")++ print("\nFCF Projections:")+ for proj in result['fcf_projections']:+ print(f" Year {proj['year']}: ${proj['fcf']:,.0f} (Growth: {proj['growth_rate']:.1f}%)")++ print(f"\nTerminal Value: ${result['terminal_value']['terminal_value']:,.0f}")+ print(f"Terminal Growth Rate: {result['terminal_value']['terminal_growth_rate']:.1f}%")++ print(f"\nEnterprise Value: ${result['enterprise_value']['enterprise_value']:,.0f}")+ print(f" PV of FCF: ${result['enterprise_value']['pv_of_fcf']:,.0f}")+ print(f" PV of Terminal Value: ${result['enterprise_value']['pv_of_terminal_value']:,.0f}")+ print(f" Terminal Value %: {result['enterprise_value']['terminal_value_contribution']:.1f}%")++ print(f"\nEquity Value: ${result['equity_value']['equity_value']:,.0f}")+ print(f"\nPrice Per Share: ${result['valuation_per_share']['price_per_share']:.2f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/football_field.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/football_field.pynew file mode 100644index 000000000..880511ef6--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/football_field.py@@ -0,0 +1,249 @@+"""Football Field Valuation Chart"""+import sys+from pathlib import Path+from typing import Dict, Any, List, Optional, Tuple+import numpy as np+from dataclasses import dataclass++scripts_path = Path(__file__).parent.parent.parent.parent+sys.path.append(str(scripts_path))++try:+ import matplotlib.pyplot as plt+ import matplotlib.patches as patches+except ImportError:+ plt = None++@dataclass+class ValuationRange:+ method_name: str+ low: float+ high: float+ midpoint: float+ weight: float = 1.0++class FootballFieldChart:+ def __init__(self):+ if plt is None:+ raise ImportError("matplotlib required: pip install matplotlib")++ self.colors = {+ 'DCF': '#2E86AB',+ 'Trading Comps': '#A23B72',+ 'Transaction Comps': '#F18F01',+ 'LBO': '#C73E1D',+ 'Premiums Paid': '#6A994E',+ 'Sum of Parts': '#BC4B51'+ }++ def add_valuation_range(self, method: str, low: float, high: float,+ midpoint: Optional[float] = None, weight: float = 1.0) -> ValuationRange:+ """Add valuation range from methodology"""++ if midpoint is None:+ midpoint = (low + high) / 2++ return ValuationRange(+ method_name=method,+ low=low,+ high=high,+ midpoint=midpoint,+ weight=weight+ )++ def generate_chart(self, valuation_ranges: List[ValuationRange],+ current_price: Optional[float] = None,+ offer_price: Optional[float] = None,+ output_path: Optional[str] = None) -> Dict[str, Any]:+ """Generate football field chart"""++ if not valuation_ranges:+ return {'error': 'No valuation ranges provided'}++ fig, ax = plt.subplots(figsize=(14, 8))++ all_values = []+ for vr in valuation_ranges:+ all_values.extend([vr.low, vr.high])+ if current_price:+ all_values.append(current_price)+ if offer_price:+ all_values.append(offer_price)++ min_val = min(all_values) * 0.9+ max_val = max(all_values) * 1.1++ y_positions = list(range(len(valuation_ranges), 0, -1))++ for i, vr in enumerate(valuation_ranges):+ y = y_positions[i]+ color = self.colors.get(vr.method_name, '#95B8D1')++ ax.barh(y, vr.high - vr.low, left=vr.low, height=0.6,+ color=color, alpha=0.7, edgecolor='black', linewidth=1.5)++ ax.plot(vr.midpoint, y, 'D', color='black', markersize=8, zorder=5)++ ax.text(min_val, y, f'{vr.method_name}', va='center', ha='right',+ fontsize=11, fontweight='bold')++ range_text = f'${vr.low/1e9:.2f}B - ${vr.high/1e9:.2f}B'+ ax.text(max_val, y, range_text, va='center', ha='left',+ fontsize=10)++ if current_price:+ ax.axvline(current_price, color='blue', linestyle='--', linewidth=2,+ label=f'Current Price: ${current_price/1e9:.2f}B', alpha=0.8)++ if offer_price:+ ax.axvline(offer_price, color='red', linestyle='--', linewidth=2,+ label=f'Offer Price: ${offer_price/1e9:.2f}B', alpha=0.8)++ ax.set_xlim(min_val, max_val)+ ax.set_ylim(0.5, len(valuation_ranges) + 0.5)++ ax.set_xlabel('Enterprise Value ($ Billions)', fontsize=12, fontweight='bold')+ ax.set_title('Valuation Summary - Football Field Chart', fontsize=14, fontweight='bold', pad=20)++ ax.xaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'${x/1e9:.1f}B'))++ ax.set_yticks([])+ ax.grid(axis='x', alpha=0.3, linestyle='--')++ if current_price or offer_price:+ ax.legend(loc='upper right', fontsize=10)++ ax.spines['top'].set_visible(False)+ ax.spines['right'].set_visible(False)+ ax.spines['left'].set_visible(False)++ plt.tight_layout()++ if output_path:+ plt.savefig(output_path, dpi=300, bbox_inches='tight')++ chart_data = {+ 'valuation_ranges': [+ {+ 'method': vr.method_name,+ 'low': vr.low,+ 'high': vr.high,+ 'midpoint': vr.midpoint,+ 'range_pct': ((vr.high - vr.low) / vr.midpoint) * 100+ }+ for vr in valuation_ranges+ ],+ 'overall_low': min(vr.low for vr in valuation_ranges),+ 'overall_high': max(vr.high for vr in valuation_ranges),+ 'overall_midpoint': np.mean([vr.midpoint for vr in valuation_ranges]),+ 'current_price': current_price,+ 'offer_price': offer_price+ }++ if current_price:+ chart_data['current_vs_low_pct'] = ((current_price - chart_data['overall_low']) / chart_data['overall_low']) * 100+ chart_data['current_vs_high_pct'] = ((current_price - chart_data['overall_high']) / chart_data['overall_high']) * 100++ if offer_price:+ chart_data['offer_vs_current_pct'] = ((offer_price - current_price) / current_price) * 100 if current_price else 0+ chart_data['offer_vs_midpoint_pct'] = ((offer_price - chart_data['overall_midpoint']) / chart_data['overall_midpoint']) * 100++ return chart_data++ def calculate_weighted_valuation(self, valuation_ranges: List[ValuationRange]) -> Dict[str, float]:+ """Calculate weighted average valuation"""++ total_weight = sum(vr.weight for vr in valuation_ranges)++ weighted_low = sum(vr.low * vr.weight for vr in valuation_ranges) / total_weight+ weighted_high = sum(vr.high * vr.weight for vr in valuation_ranges) / total_weight+ weighted_midpoint = sum(vr.midpoint * vr.weight for vr in valuation_ranges) / total_weight++ return {+ 'weighted_low': weighted_low,+ 'weighted_high': weighted_high,+ 'weighted_midpoint': weighted_midpoint,+ 'total_weight': total_weight+ }++ def analyze_valuation_dispersion(self, valuation_ranges: List[ValuationRange]) -> Dict[str, float]:+ """Analyze dispersion across valuation methods"""++ midpoints = [vr.midpoint for vr in valuation_ranges]++ return {+ 'mean_midpoint': np.mean(midpoints),+ 'median_midpoint': np.median(midpoints),+ 'std_dev': np.std(midpoints),+ 'coefficient_of_variation': (np.std(midpoints) / np.mean(midpoints)) * 100 if np.mean(midpoints) else 0,+ 'min_midpoint': min(midpoints),+ 'max_midpoint': max(midpoints),+ 'range': max(midpoints) - min(midpoints),+ 'range_pct': ((max(midpoints) - min(midpoints)) / np.mean(midpoints)) * 100 if np.mean(midpoints) else 0+ }++ def generate_summary_table(self, valuation_ranges: List[ValuationRange],+ current_price: Optional[float] = None) -> Dict[str, Any]:+ """Generate valuation summary table"""++ table_rows = []+ for vr in valuation_ranges:+ row = {+ 'Method': vr.method_name,+ 'Low ($M)': vr.low / 1_000_000,+ 'Midpoint ($M)': vr.midpoint / 1_000_000,+ 'High ($M)': vr.high / 1_000_000,+ 'Weight': vr.weight+ }++ if current_price:+ row['Implied Premium to Current (%)'] = ((vr.midpoint - current_price) / current_price) * 100++ table_rows.append(row)++ weighted = self.calculate_weighted_valuation(valuation_ranges)+ dispersion = self.analyze_valuation_dispersion(valuation_ranges)++ summary_row = {+ 'Method': 'WEIGHTED AVERAGE',+ 'Low ($M)': weighted['weighted_low'] / 1_000_000,+ 'Midpoint ($M)': weighted['weighted_midpoint'] / 1_000_000,+ 'High ($M)': weighted['weighted_high'] / 1_000_000,+ 'Weight': weighted['total_weight']+ }++ if current_price:+ summary_row['Implied Premium to Current (%)'] = ((weighted['weighted_midpoint'] - current_price) / current_price) * 100++ return {+ 'valuation_methods': table_rows,+ 'weighted_average': summary_row,+ 'dispersion_analysis': dispersion+ }++if __name__ == '__main__':+ chart = FootballFieldChart()++ valuation_ranges = [+ chart.add_valuation_range('DCF', 4.5e9, 5.5e9, 5.0e9, weight=1.5),+ chart.add_valuation_range('Trading Comps', 4.8e9, 6.0e9, 5.4e9, weight=1.0),+ chart.add_valuation_range('Transaction Comps', 5.0e9, 6.2e9, 5.6e9, weight=1.2),+ chart.add_valuation_range('LBO', 4.2e9, 5.2e9, 4.7e9, weight=0.8),+ chart.add_valuation_range('Premiums Paid', 5.5e9, 6.5e9, 6.0e9, weight=1.0)+ ]++ current_price = 4.0e9+ offer_price = 5.5e9++ result = chart.generate_chart(+ valuation_ranges,+ current_price=current_price,+ offer_price=offer_price,+ output_path='football_field.png'+ )++ print(f"Overall Valuation Range: ${result['overall_low']/1e9:.2f}B - ${result['overall_high']/1e9:.2f}B")+ print(f"Offer vs Current: {result['offer_vs_current_pct']:.1f}% premium")++ summary = chart.generate_summary_table(valuation_ranges, current_price)+ print(f"\nWeighted Midpoint: ${summary['weighted_average']['Midpoint ($M)']:.0f}M")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/precedent_transactions.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/precedent_transactions.pynew file mode 100644index 000000000..c35a25284--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/precedent_transactions.py@@ -0,0 +1,349 @@+"""Precedent Transaction Analysis"""+import sys+from pathlib import Path+from typing import Dict, Any, List, Optional, Tuple+import numpy as np+from datetime import datetime, timedelta+from dataclasses import dataclass+from statistics import median, mean, stdev++scripts_path = Path(__file__).parent.parent.parent.parent+sys.path.append(str(scripts_path))++from ..deal_database.database_schema import MADatabase++@dataclass+class TransactionComp:+ deal_id: str+ announcement_date: str+ acquirer_name: str+ target_name: str+ deal_value: float+ enterprise_value: float+ revenue: float+ ebitda: float+ ev_revenue: float+ ev_ebitda: float+ ev_ebit: float+ price_earnings: float+ premium_1day: float+ premium_4week: float+ payment_method: str+ deal_status: str++class PrecedentTransactionAnalyzer:+ def __init__(self, db: Optional[MADatabase] = None):+ self.db = db or MADatabase()++ def find_comparables(self, target_metrics: Dict[str, Any],+ screening_criteria: Optional[Dict[str, Any]] = None) -> List[TransactionComp]:+ """Find comparable M&A transactions"""++ industry = target_metrics.get('industry')+ target_value = target_metrics.get('deal_value', target_metrics.get('enterprise_value', 0))++ criteria = screening_criteria or {}+ years_back = criteria.get('years_back', 3)+ min_value_ratio = criteria.get('min_value_ratio', 0.5)+ max_value_ratio = criteria.get('max_value_ratio', 2.0)+ status_filter = criteria.get('status', 'Completed')++ end_date = datetime.now()+ start_date = end_date - timedelta(days=years_back*365)++ min_value = target_value * min_value_ratio if target_value else 0+ max_value = target_value * max_value_ratio if target_value else float('inf')++ deals = self.db.search_deals({+ 'industry': industry,+ 'start_date': start_date.strftime('%Y-%m-%d'),+ 'end_date': end_date.strftime('%Y-%m-%d'),+ 'deal_status': status_filter+ })++ if target_value:+ deals = [d for d in deals if min_value <= d.get('deal_value', 0) <= max_value]++ comps = []+ for deal in deals:+ financials = self.db.get_deal_financials(deal['deal_id'])+ multiples = self.db.get_deal_multiples(deal['deal_id'])++ if not financials or not multiples:+ continue++ fin = financials[0] if financials else {}+ mult = multiples[0] if multiples else {}++ comp = TransactionComp(+ deal_id=deal['deal_id'],+ announcement_date=deal['announcement_date'],+ acquirer_name=deal['acquirer_name'],+ target_name=deal['target_name'],+ deal_value=deal.get('deal_value', 0),+ enterprise_value=deal.get('enterprise_value', deal.get('deal_value', 0)),+ revenue=fin.get('revenue', 0),+ ebitda=fin.get('ebitda', 0),+ ev_revenue=mult.get('ev_revenue', 0),+ ev_ebitda=mult.get('ev_ebitda', 0),+ ev_ebit=mult.get('ev_ebit', 0),+ price_earnings=mult.get('price_earnings', 0),+ premium_1day=deal.get('premium_1day', 0),+ premium_4week=deal.get('premium_4week', 0),+ payment_method=deal.get('payment_method', ''),+ deal_status=deal.get('deal_status', '')+ )+ comps.append(comp)++ comps.sort(key=lambda x: x.announcement_date, reverse=True)+ return comps++ def calculate_multiples_statistics(self, comps: List[TransactionComp]) -> Dict[str, Dict[str, float]]:+ """Calculate statistical metrics for transaction multiples"""++ def calc_stats(values: List[float], name: str) -> Dict[str, float]:+ clean_vals = [v for v in values if v > 0 and not np.isnan(v) and not np.isinf(v)]+ if not clean_vals:+ return {f'{name}_mean': 0, f'{name}_median': 0, f'{name}_min': 0,+ f'{name}_max': 0, f'{name}_std': 0, f'{name}_count': 0}++ return {+ f'{name}_mean': mean(clean_vals),+ f'{name}_median': median(clean_vals),+ f'{name}_min': min(clean_vals),+ f'{name}_max': max(clean_vals),+ f'{name}_std': stdev(clean_vals) if len(clean_vals) > 1 else 0,+ f'{name}_count': len(clean_vals),+ f'{name}_q1': np.percentile(clean_vals, 25),+ f'{name}_q3': np.percentile(clean_vals, 75)+ }++ stats = {}++ ev_revenue_vals = [c.ev_revenue for c in comps if c.ev_revenue > 0]+ stats['ev_revenue'] = calc_stats(ev_revenue_vals, 'ev_revenue')++ ev_ebitda_vals = [c.ev_ebitda for c in comps if c.ev_ebitda > 0]+ stats['ev_ebitda'] = calc_stats(ev_ebitda_vals, 'ev_ebitda')++ ev_ebit_vals = [c.ev_ebit for c in comps if c.ev_ebit > 0]+ stats['ev_ebit'] = calc_stats(ev_ebit_vals, 'ev_ebit')++ pe_vals = [c.price_earnings for c in comps if c.price_earnings > 0]+ stats['price_earnings'] = calc_stats(pe_vals, 'pe')++ premium_1d_vals = [c.premium_1day for c in comps if c.premium_1day > 0]+ stats['premium_1day'] = calc_stats(premium_1d_vals, 'premium_1d')++ premium_4w_vals = [c.premium_4week for c in comps if c.premium_4week > 0]+ stats['premium_4week'] = calc_stats(premium_4w_vals, 'premium_4w')++ return stats++ def apply_multiples_valuation(self, target_financials: Dict[str, float],+ comps: List[TransactionComp]) -> Dict[str, Any]:+ """Apply transaction multiples to target company"""++ stats = self.calculate_multiples_statistics(comps)++ valuations = {}++ if target_financials.get('revenue'):+ revenue = target_financials['revenue']+ if stats['ev_revenue']['ev_revenue_median'] > 0:+ valuations['ev_revenue_median'] = revenue * stats['ev_revenue']['ev_revenue_median']+ valuations['ev_revenue_mean'] = revenue * stats['ev_revenue']['ev_revenue_mean']+ valuations['ev_revenue_q1'] = revenue * stats['ev_revenue']['ev_revenue_q1']+ valuations['ev_revenue_q3'] = revenue * stats['ev_revenue']['ev_revenue_q3']++ if target_financials.get('ebitda'):+ ebitda = target_financials['ebitda']+ if stats['ev_ebitda']['ev_ebitda_median'] > 0:+ valuations['ev_ebitda_median'] = ebitda * stats['ev_ebitda']['ev_ebitda_median']+ valuations['ev_ebitda_mean'] = ebitda * stats['ev_ebitda']['ev_ebitda_mean']+ valuations['ev_ebitda_q1'] = ebitda * stats['ev_ebitda']['ev_ebitda_q1']+ valuations['ev_ebitda_q3'] = ebitda * stats['ev_ebitda']['ev_ebitda_q3']++ if target_financials.get('ebit'):+ ebit = target_financials['ebit']+ if stats['ev_ebit']['ev_ebit_median'] > 0:+ valuations['ev_ebit_median'] = ebit * stats['ev_ebit']['ev_ebit_median']+ valuations['ev_ebit_mean'] = ebit * stats['ev_ebit']['ev_ebit_mean']++ if target_financials.get('net_income'):+ net_income = target_financials['net_income']+ if stats['price_earnings']['pe_median'] > 0:+ valuations['pe_median'] = net_income * stats['price_earnings']['pe_median']+ valuations['pe_mean'] = net_income * stats['price_earnings']['pe_mean']++ valuation_values = [v for v in valuations.values() if v > 0]+ if valuation_values:+ valuations['blended_median'] = median(valuation_values)+ valuations['blended_mean'] = mean(valuation_values)++ return {+ 'valuations': valuations,+ 'multiples_used': stats,+ 'comp_count': len(comps)+ }++ def build_comp_table(self, comps: List[TransactionComp], target_metrics: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:+ """Build formatted transaction comp table"""++ table_data = []+ for comp in comps:+ row = {+ 'Date': comp.announcement_date,+ 'Acquirer': comp.acquirer_name,+ 'Target': comp.target_name,+ 'Deal Value ($M)': comp.deal_value / 1_000_000 if comp.deal_value else 0,+ 'EV/Revenue': comp.ev_revenue,+ 'EV/EBITDA': comp.ev_ebitda,+ 'EV/EBIT': comp.ev_ebit,+ 'P/E': comp.price_earnings,+ 'Premium 1-Day (%)': comp.premium_1day,+ 'Premium 4-Week (%)': comp.premium_4week,+ 'Payment': comp.payment_method+ }+ table_data.append(row)++ stats = self.calculate_multiples_statistics(comps)++ summary_row = {+ 'Date': 'MEDIAN',+ 'Acquirer': '',+ 'Target': '',+ 'Deal Value ($M)': median([c.deal_value / 1_000_000 for c in comps if c.deal_value]) if comps else 0,+ 'EV/Revenue': stats['ev_revenue']['ev_revenue_median'],+ 'EV/EBITDA': stats['ev_ebitda']['ev_ebitda_median'],+ 'EV/EBIT': stats['ev_ebit']['ev_ebit_median'],+ 'P/E': stats['price_earnings']['pe_median'],+ 'Premium 1-Day (%)': stats['premium_1day']['premium_1d_median'],+ 'Premium 4-Week (%)': stats['premium_4week']['premium_4w_median'],+ 'Payment': ''+ }++ mean_row = {+ 'Date': 'MEAN',+ 'Acquirer': '',+ 'Target': '',+ 'Deal Value ($M)': mean([c.deal_value / 1_000_000 for c in comps if c.deal_value]) if comps else 0,+ 'EV/Revenue': stats['ev_revenue']['ev_revenue_mean'],+ 'EV/EBITDA': stats['ev_ebitda']['ev_ebitda_mean'],+ 'EV/EBIT': stats['ev_ebit']['ev_ebit_mean'],+ 'P/E': stats['price_earnings']['pe_mean'],+ 'Premium 1-Day (%)': stats['premium_1day']['premium_1d_mean'],+ 'Premium 4-Week (%)': stats['premium_4week']['premium_4w_mean'],+ 'Payment': ''+ }++ result = {+ 'comparables': table_data,+ 'summary_statistics': {+ 'median': summary_row,+ 'mean': mean_row,+ 'quartiles': {+ 'ev_revenue_q1': stats['ev_revenue']['ev_revenue_q1'],+ 'ev_revenue_q3': stats['ev_revenue']['ev_revenue_q3'],+ 'ev_ebitda_q1': stats['ev_ebitda']['ev_ebitda_q1'],+ 'ev_ebitda_q3': stats['ev_ebitda']['ev_ebitda_q3']+ }+ },+ 'comp_count': len(comps)+ }++ if target_metrics:+ valuation_result = self.apply_multiples_valuation(target_metrics, comps)+ result['target_valuation'] = valuation_result++ return result++ def sensitivity_analysis(self, target_financials: Dict[str, float],+ comps: List[TransactionComp],+ metric: str = 'ebitda',+ multiple_range: Tuple[float, float] = None) -> Dict[str, Any]:+ """Perform sensitivity analysis on multiples"""++ stats = self.calculate_multiples_statistics(comps)++ if metric == 'ebitda':+ base_multiple = stats['ev_ebitda']['ev_ebitda_median']+ metric_value = target_financials.get('ebitda', 0)+ std = stats['ev_ebitda']['ev_ebitda_std']+ elif metric == 'revenue':+ base_multiple = stats['ev_revenue']['ev_revenue_median']+ metric_value = target_financials.get('revenue', 0)+ std = stats['ev_revenue']['ev_revenue_std']+ else:+ return {}++ if not metric_value or not base_multiple:+ return {}++ if multiple_range:+ min_mult, max_mult = multiple_range+ else:+ min_mult = max(0.1, base_multiple - 2*std)+ max_mult = base_multiple + 2*std++ multiples = np.linspace(min_mult, max_mult, 11)+ metric_adjustments = np.linspace(0.8, 1.2, 11)++ sensitivity_grid = []+ for mult in multiples:+ row = []+ for adj in metric_adjustments:+ valuation = (metric_value * adj) * mult+ row.append(valuation)+ sensitivity_grid.append(row)++ return {+ 'base_multiple': base_multiple,+ 'base_metric_value': metric_value,+ 'base_valuation': metric_value * base_multiple,+ 'multiples_range': multiples.tolist(),+ 'metric_adjustments': metric_adjustments.tolist(),+ 'sensitivity_matrix': sensitivity_grid,+ 'metric_type': metric+ }++ def calculate_implied_premium(self, current_price: float, shares_outstanding: float,+ implied_enterprise_value: float, net_debt: float) -> Dict[str, float]:+ """Calculate implied acquisition premium"""++ current_market_cap = current_price * shares_outstanding+ implied_equity_value = implied_enterprise_value - net_debt+ implied_price_per_share = implied_equity_value / shares_outstanding++ premium = ((implied_price_per_share - current_price) / current_price) * 100++ return {+ 'current_price': current_price,+ 'current_market_cap': current_market_cap,+ 'implied_enterprise_value': implied_enterprise_value,+ 'implied_equity_value': implied_equity_value,+ 'implied_price_per_share': implied_price_per_share,+ 'implied_premium_pct': premium,+ 'premium_dollars': implied_price_per_share - current_price+ }++if __name__ == '__main__':+ analyzer = PrecedentTransactionAnalyzer()++ target_metrics = {+ 'industry': 'Technology',+ 'enterprise_value': 5_000_000_000,+ 'revenue': 1_000_000_000,+ 'ebitda': 250_000_000,+ 'ebit': 200_000_000+ }++ comps = analyzer.find_comparables(target_metrics)+ print(f"Found {len(comps)} comparable transactions")++ comp_table = analyzer.build_comp_table(comps, target_metrics)+ print(f"\nMedian EV/EBITDA: {comp_table['summary_statistics']['median']['EV/EBITDA']:.2f}x")++ if 'target_valuation' in comp_table:+ vals = comp_table['target_valuation']['valuations']+ print(f"Implied Valuation (EV/EBITDA): ${vals.get('ev_ebitda_median', 0):,.0f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/trading_comps.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/trading_comps.pynew file mode 100644index 000000000..a85c95463--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/trading_comps.py@@ -0,0 +1,328 @@+"""Trading Comparables Analysis - Public Company Comps"""+import sys+from pathlib import Path+from typing import Dict, Any, List, Optional+import numpy as np+from dataclasses import dataclass+from statistics import median, mean, stdev+from datetime import datetime++scripts_path = Path(__file__).parent.parent.parent.parent+sys.path.append(str(scripts_path))++try:+ import yfinance as yf+except ImportError:+ yf = None++@dataclass+class TradingComp:+ ticker: str+ company_name: str+ market_cap: float+ enterprise_value: float+ revenue_ltm: float+ ebitda_ltm: float+ ebit_ltm: float+ net_income_ltm: float+ total_debt: float+ cash: float+ shares_outstanding: float+ stock_price: float+ ev_revenue: float+ ev_ebitda: float+ ev_ebit: float+ price_earnings: float+ price_book: float+ price_sales: float+ revenue_growth: float+ ebitda_margin: float+ net_margin: float+ roe: float+ roa: float++class TradingCompsAnalyzer:+ def __init__(self):+ if yf is None:+ raise ImportError("yfinance required: pip install yfinance")++ self.industry_tickers = {+ 'Technology': ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'META', 'NVDA', 'ADBE', 'CRM', 'ORCL', 'IBM'],+ 'Healthcare': ['UNH', 'JNJ', 'PFE', 'ABBV', 'TMO', 'ABT', 'DHR', 'BMY', 'LLY', 'AMGN'],+ 'Financial Services': ['JPM', 'BAC', 'WFC', 'C', 'GS', 'MS', 'BLK', 'SCHW', 'USB', 'PNC'],+ 'Industrials': ['BA', 'HON', 'UNP', 'CAT', 'GE', 'MMM', 'LMT', 'RTX', 'DE', 'EMR'],+ 'Consumer Discretionary': ['AMZN', 'TSLA', 'HD', 'NKE', 'MCD', 'LOW', 'SBUX', 'TGT', 'TJX', 'F'],+ 'Consumer Staples': ['WMT', 'PG', 'KO', 'PEP', 'COST', 'PM', 'MO', 'CL', 'MDLZ', 'KMB'],+ 'Energy': ['XOM', 'CVX', 'COP', 'SLB', 'EOG', 'PXD', 'MPC', 'PSX', 'VLO', 'OXY'],+ 'Materials': ['LIN', 'APD', 'SHW', 'ECL', 'DD', 'NEM', 'FCX', 'NUE', 'VMC', 'MLM']+ }++ def fetch_comp_data(self, ticker: str) -> Optional[TradingComp]:+ """Fetch comprehensive financial data for single company"""+ try:+ stock = yf.Ticker(ticker)+ info = stock.info+ financials = stock.financials+ balance_sheet = stock.balance_sheet++ market_cap = info.get('marketCap', 0)+ shares_outstanding = info.get('sharesOutstanding', 0)+ stock_price = info.get('currentPrice', info.get('regularMarketPrice', 0))+ total_debt = info.get('totalDebt', 0)+ cash = info.get('totalCash', 0)+ enterprise_value = market_cap + total_debt - cash++ revenue_ltm = info.get('totalRevenue', 0)+ ebitda_ltm = info.get('ebitda', 0)+ ebit_ltm = info.get('ebit', ebitda_ltm)+ net_income_ltm = info.get('netIncome', 0)++ revenue_growth = info.get('revenueGrowth', 0) * 100 if info.get('revenueGrowth') else 0+ ebitda_margin = (ebitda_ltm / revenue_ltm * 100) if revenue_ltm else 0+ net_margin = (net_income_ltm / revenue_ltm * 100) if revenue_ltm else 0+ roe = info.get('returnOnEquity', 0) * 100 if info.get('returnOnEquity') else 0+ roa = info.get('returnOnAssets', 0) * 100 if info.get('returnOnAssets') else 0++ ev_revenue = enterprise_value / revenue_ltm if revenue_ltm else 0+ ev_ebitda = enterprise_value / ebitda_ltm if ebitda_ltm else 0+ ev_ebit = enterprise_value / ebit_ltm if ebit_ltm else 0+ price_earnings = info.get('trailingPE', 0)+ price_book = info.get('priceToBook', 0)+ price_sales = info.get('priceToSalesTrailing12Months', 0)++ return TradingComp(+ ticker=ticker,+ company_name=info.get('longName', ticker),+ market_cap=market_cap,+ enterprise_value=enterprise_value,+ revenue_ltm=revenue_ltm,+ ebitda_ltm=ebitda_ltm,+ ebit_ltm=ebit_ltm,+ net_income_ltm=net_income_ltm,+ total_debt=total_debt,+ cash=cash,+ shares_outstanding=shares_outstanding,+ stock_price=stock_price,+ ev_revenue=ev_revenue,+ ev_ebitda=ev_ebitda,+ ev_ebit=ev_ebit,+ price_earnings=price_earnings,+ price_book=price_book,+ price_sales=price_sales,+ revenue_growth=revenue_growth,+ ebitda_margin=ebitda_margin,+ net_margin=net_margin,+ roe=roe,+ roa=roa+ )++ except Exception as e:+ print(f"Error fetching {ticker}: {e}")+ return None++ def find_comparables(self, industry: str, custom_tickers: Optional[List[str]] = None) -> List[TradingComp]:+ """Find public company comparables"""++ tickers = custom_tickers or self.industry_tickers.get(industry, [])++ comps = []+ for ticker in tickers:+ comp = self.fetch_comp_data(ticker)+ if comp and comp.market_cap > 0:+ comps.append(comp)++ return comps++ def calculate_statistics(self, comps: List[TradingComp]) -> Dict[str, Dict[str, float]]:+ """Calculate trading multiples statistics"""++ def calc_stats(values: List[float], name: str) -> Dict[str, float]:+ clean_vals = [v for v in values if v > 0 and not np.isnan(v) and not np.isinf(v)]+ if not clean_vals:+ return {f'{name}_mean': 0, f'{name}_median': 0, f'{name}_min': 0,+ f'{name}_max': 0, f'{name}_std': 0, f'{name}_count': 0}++ return {+ f'{name}_mean': mean(clean_vals),+ f'{name}_median': median(clean_vals),+ f'{name}_min': min(clean_vals),+ f'{name}_max': max(clean_vals),+ f'{name}_std': stdev(clean_vals) if len(clean_vals) > 1 else 0,+ f'{name}_count': len(clean_vals),+ f'{name}_q1': np.percentile(clean_vals, 25),+ f'{name}_q3': np.percentile(clean_vals, 75)+ }++ stats = {}++ stats['ev_revenue'] = calc_stats([c.ev_revenue for c in comps], 'ev_revenue')+ stats['ev_ebitda'] = calc_stats([c.ev_ebitda for c in comps], 'ev_ebitda')+ stats['ev_ebit'] = calc_stats([c.ev_ebit for c in comps], 'ev_ebit')+ stats['price_earnings'] = calc_stats([c.price_earnings for c in comps], 'pe')+ stats['price_book'] = calc_stats([c.price_book for c in comps], 'pb')+ stats['price_sales'] = calc_stats([c.price_sales for c in comps], 'ps')+ stats['revenue_growth'] = calc_stats([c.revenue_growth for c in comps], 'rev_growth')+ stats['ebitda_margin'] = calc_stats([c.ebitda_margin for c in comps], 'ebitda_margin')+ stats['net_margin'] = calc_stats([c.net_margin for c in comps], 'net_margin')+ stats['roe'] = calc_stats([c.roe for c in comps], 'roe')++ return stats++ def apply_trading_multiples(self, target_financials: Dict[str, float],+ comps: List[TradingComp]) -> Dict[str, Any]:+ """Apply trading multiples to target"""++ stats = self.calculate_statistics(comps)+ valuations = {}++ if target_financials.get('revenue'):+ revenue = target_financials['revenue']+ valuations['ev_revenue_median'] = revenue * stats['ev_revenue']['ev_revenue_median']+ valuations['ev_revenue_mean'] = revenue * stats['ev_revenue']['ev_revenue_mean']+ valuations['ev_revenue_q1'] = revenue * stats['ev_revenue']['ev_revenue_q1']+ valuations['ev_revenue_q3'] = revenue * stats['ev_revenue']['ev_revenue_q3']++ if target_financials.get('ebitda'):+ ebitda = target_financials['ebitda']+ valuations['ev_ebitda_median'] = ebitda * stats['ev_ebitda']['ev_ebitda_median']+ valuations['ev_ebitda_mean'] = ebitda * stats['ev_ebitda']['ev_ebitda_mean']+ valuations['ev_ebitda_q1'] = ebitda * stats['ev_ebitda']['ev_ebitda_q1']+ valuations['ev_ebitda_q3'] = ebitda * stats['ev_ebitda']['ev_ebitda_q3']++ if target_financials.get('ebit'):+ ebit = target_financials['ebit']+ valuations['ev_ebit_median'] = ebit * stats['ev_ebit']['ev_ebit_median']+ valuations['ev_ebit_mean'] = ebit * stats['ev_ebit']['ev_ebit_mean']++ if target_financials.get('net_income'):+ net_income = target_financials['net_income']+ valuations['pe_median'] = net_income * stats['price_earnings']['pe_median']+ valuations['pe_mean'] = net_income * stats['price_earnings']['pe_mean']++ valuation_values = [v for v in valuations.values() if v > 0]+ if valuation_values:+ valuations['blended_median'] = median(valuation_values)+ valuations['blended_mean'] = mean(valuation_values)++ return {+ 'valuations': valuations,+ 'multiples_used': stats,+ 'comp_count': len(comps)+ }++ def build_comp_table(self, comps: List[TradingComp], target_metrics: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:+ """Build formatted trading comp table"""++ table_data = []+ for comp in comps:+ row = {+ 'Ticker': comp.ticker,+ 'Company': comp.company_name,+ 'Market Cap ($M)': comp.market_cap / 1_000_000,+ 'EV ($M)': comp.enterprise_value / 1_000_000,+ 'EV/Revenue': comp.ev_revenue,+ 'EV/EBITDA': comp.ev_ebitda,+ 'EV/EBIT': comp.ev_ebit,+ 'P/E': comp.price_earnings,+ 'P/B': comp.price_book,+ 'P/S': comp.price_sales,+ 'Rev Growth (%)': comp.revenue_growth,+ 'EBITDA Margin (%)': comp.ebitda_margin,+ 'Net Margin (%)': comp.net_margin,+ 'ROE (%)': comp.roe+ }+ table_data.append(row)++ stats = self.calculate_statistics(comps)++ summary_row = {+ 'Ticker': 'MEDIAN',+ 'Company': '',+ 'Market Cap ($M)': median([c.market_cap / 1_000_000 for c in comps]),+ 'EV ($M)': median([c.enterprise_value / 1_000_000 for c in comps]),+ 'EV/Revenue': stats['ev_revenue']['ev_revenue_median'],+ 'EV/EBITDA': stats['ev_ebitda']['ev_ebitda_median'],+ 'EV/EBIT': stats['ev_ebit']['ev_ebit_median'],+ 'P/E': stats['price_earnings']['pe_median'],+ 'P/B': stats['price_book']['pb_median'],+ 'P/S': stats['price_sales']['ps_median'],+ 'Rev Growth (%)': stats['revenue_growth']['rev_growth_median'],+ 'EBITDA Margin (%)': stats['ebitda_margin']['ebitda_margin_median'],+ 'Net Margin (%)': stats['net_margin']['net_margin_median'],+ 'ROE (%)': stats['roe']['roe_median']+ }++ result = {+ 'comparables': table_data,+ 'summary_statistics': {+ 'median': summary_row,+ 'detailed_stats': stats+ },+ 'comp_count': len(comps),+ 'as_of_date': datetime.now().strftime('%Y-%m-%d')+ }++ if target_metrics:+ valuation_result = self.apply_trading_multiples(target_metrics, comps)+ result['target_valuation'] = valuation_result++ return result++ def regression_analysis(self, comps: List[TradingComp], x_metric: str = 'ebitda_margin',+ y_metric: str = 'ev_ebitda') -> Dict[str, Any]:+ """Perform regression analysis on comp set"""++ x_vals = []+ y_vals = []++ for comp in comps:+ x = getattr(comp, x_metric, None)+ y = getattr(comp, y_metric, None)++ if x and y and x > 0 and y > 0 and not np.isnan(x) and not np.isnan(y):+ x_vals.append(x)+ y_vals.append(y)++ if len(x_vals) < 3:+ return {'error': 'Insufficient data for regression'}++ coefficients = np.polyfit(x_vals, y_vals, 1)+ slope, intercept = coefficients++ y_pred = [slope * x + intercept for x in x_vals]+ residuals = [y - yp for y, yp in zip(y_vals, y_pred)]+ ss_res = sum(r**2 for r in residuals)+ ss_tot = sum((y - mean(y_vals))**2 for y in y_vals)+ r_squared = 1 - (ss_res / ss_tot) if ss_tot > 0 else 0++ return {+ 'slope': slope,+ 'intercept': intercept,+ 'r_squared': r_squared,+ 'x_metric': x_metric,+ 'y_metric': y_metric,+ 'data_points': len(x_vals),+ 'x_values': x_vals,+ 'y_values': y_vals+ }++if __name__ == '__main__':+ analyzer = TradingCompsAnalyzer()++ print("Fetching Technology sector comps...")+ comps = analyzer.find_comparables('Technology')+ print(f"Found {len(comps)} comparables")++ target_financials = {+ 'revenue': 1_000_000_000,+ 'ebitda': 250_000_000,+ 'ebit': 200_000_000,+ 'net_income': 150_000_000+ }++ comp_table = analyzer.build_comp_table(comps, target_financials)+ print(f"\nMedian EV/EBITDA: {comp_table['summary_statistics']['median']['EV/EBITDA']:.2f}x")++ if 'target_valuation' in comp_table:+ vals = comp_table['target_valuation']['valuations']+ print(f"Implied EV (EV/EBITDA): ${vals.get('ev_ebitda_median', 0):,.0f}")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/valuation_summary.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/valuation_summary.pynew file mode 100644index 000000000..d9323d970--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/valuation/valuation_summary.py@@ -0,0 +1,293 @@+"""Comprehensive Valuation Summary"""+import sys+from pathlib import Path+from typing import Dict, Any, List, Optional+from datetime import datetime++scripts_path = Path(__file__).parent.parent.parent.parent+sys.path.append(str(scripts_path))++from .precedent_transactions import PrecedentTransactionAnalyzer+from .trading_comps import TradingCompsAnalyzer+from .football_field import FootballFieldChart, ValuationRange+from ..deal_database.database_schema import MADatabase++class ValuationSummary:+ def __init__(self, db: Optional[MADatabase] = None):+ self.db = db or MADatabase()+ self.precedent_analyzer = PrecedentTransactionAnalyzer(self.db)+ self.trading_analyzer = TradingCompsAnalyzer()+ self.chart_generator = FootballFieldChart()++ def comprehensive_valuation(self, target_metrics: Dict[str, Any],+ include_methods: Optional[List[str]] = None) -> Dict[str, Any]:+ """Perform comprehensive valuation using multiple methods"""++ methods = include_methods or ['precedent_transactions', 'trading_comps', 'dcf']++ results = {+ 'target_company': target_metrics.get('company_name', 'Target'),+ 'analysis_date': datetime.now().strftime('%Y-%m-%d'),+ 'target_financials': target_metrics,+ 'valuation_methods': {}+ }++ if 'precedent_transactions' in methods:+ precedent_result = self._run_precedent_transactions(target_metrics)+ results['valuation_methods']['precedent_transactions'] = precedent_result++ if 'trading_comps' in methods:+ trading_result = self._run_trading_comps(target_metrics)+ results['valuation_methods']['trading_comps'] = trading_result++ if 'dcf' in methods and target_metrics.get('dcf_valuation'):+ results['valuation_methods']['dcf'] = target_metrics['dcf_valuation']++ valuation_ranges = self._build_valuation_ranges(results['valuation_methods'])+ results['valuation_ranges'] = valuation_ranges++ if valuation_ranges:+ results['weighted_valuation'] = self.chart_generator.calculate_weighted_valuation(valuation_ranges)+ results['dispersion_analysis'] = self.chart_generator.analyze_valuation_dispersion(valuation_ranges)++ if target_metrics.get('current_market_cap'):+ results['premium_analysis'] = self._calculate_premiums(+ target_metrics['current_market_cap'],+ results.get('weighted_valuation', {}).get('weighted_midpoint', 0)+ )++ return results++ def _run_precedent_transactions(self, target_metrics: Dict[str, Any]) -> Dict[str, Any]:+ """Run precedent transaction analysis"""++ comps = self.precedent_analyzer.find_comparables(target_metrics)++ if not comps:+ return {'error': 'No comparable transactions found'}++ target_financials = {+ 'revenue': target_metrics.get('revenue', 0),+ 'ebitda': target_metrics.get('ebitda', 0),+ 'ebit': target_metrics.get('ebit', 0),+ 'net_income': target_metrics.get('net_income', 0)+ }++ valuation_result = self.precedent_analyzer.apply_multiples_valuation(target_financials, comps)+ comp_table = self.precedent_analyzer.build_comp_table(comps)++ return {+ 'method': 'Precedent Transactions',+ 'comp_count': len(comps),+ 'valuation_result': valuation_result,+ 'summary_multiples': comp_table['summary_statistics'],+ 'comparable_deals': [+ {+ 'date': c.announcement_date,+ 'acquirer': c.acquirer_name,+ 'target': c.target_name,+ 'value': c.deal_value+ }+ for c in comps[:10]+ ]+ }++ def _run_trading_comps(self, target_metrics: Dict[str, Any]) -> Dict[str, Any]:+ """Run trading comps analysis"""++ industry = target_metrics.get('industry')+ custom_tickers = target_metrics.get('comp_tickers')++ comps = self.trading_analyzer.find_comparables(industry, custom_tickers)++ if not comps:+ return {'error': 'No trading comparables found'}++ target_financials = {+ 'revenue': target_metrics.get('revenue', 0),+ 'ebitda': target_metrics.get('ebitda', 0),+ 'ebit': target_metrics.get('ebit', 0),+ 'net_income': target_metrics.get('net_income', 0)+ }++ valuation_result = self.trading_analyzer.apply_trading_multiples(target_financials, comps)+ comp_table = self.trading_analyzer.build_comp_table(comps)++ return {+ 'method': 'Trading Comparables',+ 'comp_count': len(comps),+ 'valuation_result': valuation_result,+ 'summary_multiples': comp_table['summary_statistics'],+ 'comparable_companies': [+ {+ 'ticker': c.ticker,+ 'company': c.company_name,+ 'market_cap': c.market_cap,+ 'ev_ebitda': c.ev_ebitda+ }+ for c in comps[:10]+ ]+ }++ def _build_valuation_ranges(self, valuation_methods: Dict[str, Any]) -> List[ValuationRange]:+ """Build valuation ranges from all methods"""++ ranges = []++ if 'precedent_transactions' in valuation_methods:+ pt = valuation_methods['precedent_transactions']+ if 'valuation_result' in pt and 'valuations' in pt['valuation_result']:+ vals = pt['valuation_result']['valuations']++ if 'ev_ebitda_q1' in vals and 'ev_ebitda_q3' in vals:+ low = vals['ev_ebitda_q1']+ high = vals['ev_ebitda_q3']+ mid = vals.get('ev_ebitda_median', (low + high) / 2)+ ranges.append(ValuationRange('Transaction Comps', low, high, mid, weight=1.2))++ if 'trading_comps' in valuation_methods:+ tc = valuation_methods['trading_comps']+ if 'valuation_result' in tc and 'valuations' in tc['valuation_result']:+ vals = tc['valuation_result']['valuations']++ if 'ev_ebitda_q1' in vals and 'ev_ebitda_q3' in vals:+ low = vals['ev_ebitda_q1']+ high = vals['ev_ebitda_q3']+ mid = vals.get('ev_ebitda_median', (low + high) / 2)+ ranges.append(ValuationRange('Trading Comps', low, high, mid, weight=1.0))++ if 'dcf' in valuation_methods:+ dcf = valuation_methods['dcf']+ if 'valuation_range' in dcf:+ vr = dcf['valuation_range']+ ranges.append(ValuationRange('DCF', vr['low'], vr['high'], vr['base'], weight=1.5))++ return ranges++ def _calculate_premiums(self, current_value: float, implied_value: float) -> Dict[str, float]:+ """Calculate implied premiums"""++ premium_pct = ((implied_value - current_value) / current_value) * 100 if current_value else 0+ premium_dollars = implied_value - current_value++ return {+ 'current_value': current_value,+ 'implied_value': implied_value,+ 'premium_percentage': premium_pct,+ 'premium_dollars': premium_dollars+ }++ def generate_football_field(self, comprehensive_result: Dict[str, Any],+ output_path: Optional[str] = None) -> Dict[str, Any]:+ """Generate football field chart from comprehensive valuation"""++ valuation_ranges = comprehensive_result.get('valuation_ranges', [])++ if not valuation_ranges:+ return {'error': 'No valuation ranges available'}++ current_price = comprehensive_result.get('target_financials', {}).get('current_market_cap')+ offer_price = comprehensive_result.get('target_financials', {}).get('offer_price')++ return self.chart_generator.generate_chart(+ valuation_ranges,+ current_price=current_price,+ offer_price=offer_price,+ output_path=output_path+ )++ def generate_executive_summary(self, comprehensive_result: Dict[str, Any]) -> Dict[str, Any]:+ """Generate executive summary of valuation"""++ weighted_val = comprehensive_result.get('weighted_valuation', {})+ dispersion = comprehensive_result.get('dispersion_analysis', {})+ premium = comprehensive_result.get('premium_analysis', {})++ summary = {+ 'valuation_date': comprehensive_result['analysis_date'],+ 'target_company': comprehensive_result['target_company'],+ 'valuation_range': {+ 'low': weighted_val.get('weighted_low', 0),+ 'midpoint': weighted_val.get('weighted_midpoint', 0),+ 'high': weighted_val.get('weighted_high', 0)+ },+ 'methods_used': list(comprehensive_result['valuation_methods'].keys()),+ 'valuation_dispersion': {+ 'coefficient_of_variation': dispersion.get('coefficient_of_variation', 0),+ 'range_pct': dispersion.get('range_pct', 0)+ }+ }++ if premium:+ summary['implied_premium'] = {+ 'percentage': premium.get('premium_percentage', 0),+ 'dollars': premium.get('premium_dollars', 0)+ }++ summary['key_observations'] = self._generate_observations(comprehensive_result)++ return summary++ def _generate_observations(self, comprehensive_result: Dict[str, Any]) -> List[str]:+ """Generate key observations from valuation"""++ observations = []++ dispersion = comprehensive_result.get('dispersion_analysis', {})+ cv = dispersion.get('coefficient_of_variation', 0)++ if cv < 10:+ observations.append("High consensus across valuation methodologies (CV < 10%)")+ elif cv > 20:+ observations.append("Significant dispersion across methodologies suggests valuation uncertainty")++ methods = comprehensive_result.get('valuation_methods', {})++ if 'precedent_transactions' in methods:+ pt = methods['precedent_transactions']+ if pt.get('comp_count', 0) < 5:+ observations.append("Limited precedent transaction data - use with caution")++ if 'trading_comps' in methods:+ tc = methods['trading_comps']+ if tc.get('comp_count', 0) > 10:+ observations.append("Strong trading comps coverage provides robust market benchmark")++ premium = comprehensive_result.get('premium_analysis', {})+ if premium:+ prem_pct = premium.get('premium_percentage', 0)+ if prem_pct > 30:+ observations.append(f"Implied premium of {prem_pct:.1f}% is above typical M&A premiums")+ elif prem_pct < 15:+ observations.append(f"Implied premium of {prem_pct:.1f}% is below market averages")++ return observations++if __name__ == '__main__':+ summary = ValuationSummary()++ target_metrics = {+ 'company_name': 'Target Corp',+ 'industry': 'Technology',+ 'revenue': 1_000_000_000,+ 'ebitda': 250_000_000,+ 'ebit': 200_000_000,+ 'net_income': 150_000_000,+ 'current_market_cap': 4_000_000_000,+ 'dcf_valuation': {+ 'valuation_range': {+ 'low': 4_500_000_000,+ 'base': 5_000_000_000,+ 'high': 5_500_000_000+ }+ }+ }++ result = summary.comprehensive_valuation(target_metrics)+ exec_summary = summary.generate_executive_summary(result)++ print(f"\nValuation Range: ${exec_summary['valuation_range']['low']/1e9:.2f}B - ${exec_summary['valuation_range']['high']/1e9:.2f}B")+ print(f"Midpoint: ${exec_summary['valuation_range']['midpoint']/1e9:.2f}B")++ if 'implied_premium' in exec_summary:+ print(f"Implied Premium: {exec_summary['implied_premium']['percentage']:.1f}%")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.py b/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.pyindex 1a3c73e6e..be575fe19 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.py@@ -40,6 +40,7 @@ try:find, find_company, find_fund,get_entity, get_by_accession_number,get_company_facts, get_company_tickers,+ get_entity_submissions,# Data objectsThirteenF, ProxyStatement, NPX, FundReport,@@ -389,7 +390,7 @@ class EdgarToolsWrapper:def get_financials(self, ticker: str, periods: int = 4,annual: bool = True) -> Dict[str, Any]:"""- Get complete financial statements+ Get complete financial statements with markdown formattingArgs:ticker: Stock ticker symbol@@ -397,9 +398,12 @@ class EdgarToolsWrapper:annual: If True, annual data; if False, quarterly dataReturns:- Balance sheet, income statement, and cash flow data+ Financial statements formatted as markdown tables"""try:+ import pandas as pd+ import numpy as np+company = Company(ticker)financials = company.get_financials() if annual else company.get_quarterly_financials()@@ -409,25 +413,172 @@ class EdgarToolsWrapper:f"No financial data available for {ticker}").to_dict()}- # 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+ # Get all three statements - call as methods+ balance_sheet_stmt = financials.balance_sheet() if callable(financials.balance_sheet) else financials.balance_sheet+ income_stmt = financials.income_statement() if callable(financials.income_statement) else financials.income_statement+ cash_flow_stmt = financials.cashflow_statement() if callable(financials.cashflow_statement) else financials.cashflow_statement++ # Convert Statement to DataFrame and format as markdown+ def statement_to_markdown(stmt, title: str) -> str:+ if stmt is None:+ return f"## {title}\n\nNo data available.\n"++ try:+ # Get DataFrame+ if hasattr(stmt, 'to_dataframe'):+ df = stmt.to_dataframe()+ else:+ return f"## {title}\n\nCannot convert to table.\n"++ if df.empty:+ return f"## {title}\n\nNo data available.\n"++ # Filter out abstract/header rows and limit rows+ if 'abstract' in df.columns:+ df = df[df['abstract'] != True]++ # Get date columns (usually YYYY-MM-DD format)+ date_cols = [col for col in df.columns if '-' in str(col) and len(str(col)) == 10]+ if not date_cols:+ # Try to find any numeric columns+ date_cols = [col for col in df.columns if df[col].dtype in [np.float64, np.int64, 'float64', 'int64']]++ # Keep only label and date columns+ keep_cols = ['label'] + date_cols[:periods]+ available_cols = [col for col in keep_cols if col in df.columns]++ if not available_cols or 'label' not in available_cols:+ return f"## {title}\n\nCannot extract financial data.\n"++ df_display = df[available_cols].copy()++ # Replace NaN with empty string for display+ df_display = df_display.fillna('')++ # Format numbers as millions+ for col in date_cols:+ if col in df_display.columns:+ df_display[col] = df_display[col].apply(+ lambda x: f"${x/1_000_000:,.1f}M" if isinstance(x, (int, float)) and x != '' else x+ )++ # Limit to top 20 key line items+ df_display = df_display.head(20)++ # Convert to markdown table+ markdown = f"## {title}\n\n"+ markdown += df_display.to_markdown(index=False)+ markdown += "\n\n"++ return markdown++ except Exception as e:+ return f"## {title}\n\nError formatting: {str(e)}\n"++ # Generate markdown report+ markdown_report = f"# Financial Statements: {ticker}\n\n"+ markdown_report += f"**Company:** {company.name if hasattr(company, 'name') else ticker}\n"+ markdown_report += f"**CIK:** {company.cik if hasattr(company, 'cik') else 'N/A'}\n"+ markdown_report += f"**Report Type:** {'Annual (10-K)' if annual else 'Quarterly (10-Q)'}\n\n"+ markdown_report += "---\n\n"++ markdown_report += statement_to_markdown(income_stmt, "Income Statement")+ markdown_report += statement_to_markdown(balance_sheet_stmt, "Balance Sheet")+ markdown_report += statement_to_markdown(cash_flow_stmt, "Cash Flow Statement")++ # Extract chart data for key metrics+ chart_data = self._extract_chart_data(income_stmt, balance_sheet_stmt, periods)return {"success": True,"data": {- "balance_sheet": balance_sheet.to_dict() if balance_sheet is not None else None,- "income_statement": income_stmt.to_dict() if income_stmt is not None else None,- "cash_flow": cash_flow.to_dict() if cash_flow is not None else None,+ "ticker": ticker,+ "company_name": company.name if hasattr(company, 'name') else None,+ "cik": company.cik if hasattr(company, 'cik') else None,+ "markdown": markdown_report,"statement_type": "annual" if annual else "quarterly",- "periods": periods+ "chart_data": chart_data,},"parameters": {"ticker": ticker, "periods": periods, "annual": annual}}except Exception as e:return {"error": EdgarError("get_financials", str(e), traceback.format_exc()).to_dict()}+ def _extract_chart_data(self, income_stmt, balance_sheet_stmt, periods: int) -> Dict[str, Any]:+ """Extract key metrics for charting"""+ try:+ import pandas as pd+ import numpy as np++ chart_data = {+ "revenue": [],+ "net_income": [],+ "total_assets": [],+ "total_equity": []+ }++ # Extract from income statement+ if income_stmt and hasattr(income_stmt, 'to_dataframe'):+ df = income_stmt.to_dataframe()+ date_cols = [col for col in df.columns if '-' in str(col) and len(str(col)) == 10]++ # Find revenue row+ revenue_row = df[df['label'].str.contains('Revenue|Contract Revenue', case=False, na=False)]+ if not revenue_row.empty:+ for col in date_cols[:periods]:+ val = revenue_row.iloc[0][col]+ if pd.notna(val) and isinstance(val, (int, float)):+ chart_data["revenue"].append({"period": col, "value": float(val) / 1_000_000})++ # Find net income+ net_income_row = df[df['label'].str.contains('Net Income|Net Earnings', case=False, na=False)]+ if not net_income_row.empty:+ for col in date_cols[:periods]:+ val = net_income_row.iloc[0][col]+ if pd.notna(val) and isinstance(val, (int, float)):+ chart_data["net_income"].append({"period": col, "value": float(val) / 1_000_000})++ # Extract from balance sheet+ if balance_sheet_stmt and hasattr(balance_sheet_stmt, 'to_dataframe'):+ df = balance_sheet_stmt.to_dataframe()+ date_cols = [col for col in df.columns if '-' in str(col) and len(str(col)) == 10]++ # Find total assets+ assets_row = df[df['label'].str.contains('Total Assets', case=False, na=False)]+ if not assets_row.empty:+ for col in date_cols[:periods]:+ val = assets_row.iloc[0][col]+ if pd.notna(val) and isinstance(val, (int, float)):+ chart_data["total_assets"].append({"period": col, "value": float(val) / 1_000_000})++ # Find total equity+ equity_row = df[df['label'].str.contains('Total Equity|Stockholders\' Equity', case=False, na=False)]+ if not equity_row.empty:+ for col in date_cols[:periods]:+ val = equity_row.iloc[0][col]+ if pd.notna(val) and isinstance(val, (int, float)):+ chart_data["total_equity"].append({"period": col, "value": float(val) / 1_000_000})++ # Calculate YoY growth if we have data+ growth = {}+ if len(chart_data["revenue"]) >= 2:+ latest = chart_data["revenue"][0]["value"]+ previous = chart_data["revenue"][1]["value"]+ growth["revenue_yoy"] = round(((latest - previous) / previous) * 100, 1) if previous else 0++ if len(chart_data["net_income"]) >= 2:+ latest = chart_data["net_income"][0]["value"]+ previous = chart_data["net_income"][1]["value"]+ growth["net_income_yoy"] = round(((latest - previous) / previous) * 100, 1) if previous else 0++ chart_data["growth"] = growth++ return chart_data++ except Exception as e:+ print(f"Error extracting chart data: {e}")+ return {}+def get_balance_sheet(self, ticker: str, periods: int = 4,annual: bool = True, as_json: bool = True) -> Dict[str, Any]:"""Get balance sheet data"""@@ -439,9 +590,15 @@ class EdgarToolsWrapper:bs = financials.balance_sheet+ # Convert safely+ if as_json and bs is not None:+ data = bs.to_dict('records') if hasattr(bs, 'to_dict') else str(bs)+ else:+ data = str(bs)+return {"success": True,- "data": bs.to_dict() if as_json and bs is not None else str(bs),+ "data": data,"parameters": {"ticker": ticker, "periods": periods, "annual": annual}}except Exception as e:@@ -458,9 +615,15 @@ class EdgarToolsWrapper:inc = financials.income_statement+ # Convert safely+ if as_json and inc is not None:+ data = inc.to_dict('records') if hasattr(inc, 'to_dict') else str(inc)+ else:+ data = str(inc)+return {"success": True,- "data": inc.to_dict() if as_json and inc is not None else str(inc),+ "data": data,"parameters": {"ticker": ticker, "periods": periods, "annual": annual}}except Exception as e:@@ -477,9 +640,15 @@ class EdgarToolsWrapper:cf = financials.cashflow_statement+ # Convert safely+ if as_json and cf is not None:+ data = cf.to_dict('records') if hasattr(cf, 'to_dict') else str(cf)+ else:+ data = str(cf)+return {"success": True,- "data": cf.to_dict() if as_json and cf is not None else str(cf),+ "data": data,"parameters": {"ticker": ticker, "periods": periods, "annual": annual}}except Exception as e:@@ -1591,7 +1760,7 @@ class EdgarToolsWrapper:def find_company_by_name(self, query: str, top_n: int = 10) -> Dict[str, Any]:"""- Search for companies by name+ Search for companies by name - uses fast local searchArgs:query: Search query string@@ -1601,21 +1770,36 @@ class EdgarToolsWrapper:List of matching companies"""try:- results = find_company(query, top_n=top_n)-- companies = []- if results:- for result in results:- companies.append({- "cik": result.cik if hasattr(result, 'cik') else None,- "name": result.name if hasattr(result, 'name') else str(result),- "ticker": result.ticker if hasattr(result, 'ticker') else None,+ # Use get_company_tickers for fast local search+ from edgar import get_company_tickers++ # Get DataFrame with columns: cik, ticker, company+ df = get_company_tickers()++ # Filter by query (case-insensitive)+ query_lower = query.lower()+ matches = []++ # Iterate DataFrame rows+ for _, row in df.iterrows():+ company_name = str(row['company']) if 'company' in row else ''+ ticker = str(row['ticker']) if 'ticker' in row else ''+ cik = int(row['cik']) if 'cik' in row else None++ if query_lower in company_name.lower() or query_lower in ticker.lower():+ matches.append({+ "cik": cik,+ "name": company_name,+ "ticker": ticker,})+ if len(matches) >= top_n:+ break+return {"success": True,- "data": companies,- "count": len(companies),+ "data": matches,+ "count": len(matches),"parameters": {"query": query, "top_n": top_n}}except Exception as e:@@ -1811,6 +1995,341 @@ class EdgarToolsWrapper:except Exception as e:return {"error": EdgarError("get_filings_by_date", str(e), traceback.format_exc()).to_dict()}+ # =========================================================================+ # ENTITY OPERATIONS+ # =========================================================================++ def get_entity(self, cik: Union[str, int]) -> Dict[str, Any]:+ """+ Get entity information by CIK++ Args:+ cik: Company CIK number++ Returns:+ Entity information+ """+ try:+ entity = get_entity(int(cik))++ return {+ "success": True,+ "data": {+ "cik": entity.cik if hasattr(entity, 'cik') else None,+ "name": entity.name if hasattr(entity, 'name') else None,+ "tickers": entity.tickers if hasattr(entity, 'tickers') else [],+ "category": entity.category if hasattr(entity, 'category') else None,+ "entity_type": entity.entity_type if hasattr(entity, 'entity_type') else None,+ "sic": entity.sic if hasattr(entity, 'sic') else None,+ "state_of_incorporation": entity.state_of_incorporation if hasattr(entity, 'state_of_incorporation') else None,+ },+ "parameters": {"cik": str(cik)}+ }+ except Exception as e:+ return {"error": EdgarError("get_entity", str(e), traceback.format_exc()).to_dict()}++ def get_entity_submissions(self, cik: Union[str, int]) -> Dict[str, Any]:+ """+ Get all submissions for an entity++ Args:+ cik: Company CIK number++ Returns:+ Entity submissions data+ """+ try:+ submissions = get_entity_submissions(int(cik))++ # Extract recent filings+ recent_filings = []+ if submissions and hasattr(submissions, 'recent'):+ recent = submissions.recent+ if hasattr(recent, 'to_dict'):+ recent_filings = recent.to_dict('records')[:50]++ return {+ "success": True,+ "data": {+ "cik": submissions.cik if hasattr(submissions, 'cik') else None,+ "name": submissions.name if hasattr(submissions, 'name') else None,+ "recent_filings": recent_filings,+ "total_filings": len(recent_filings),+ },+ "parameters": {"cik": str(cik)}+ }+ except Exception as e:+ return {"error": EdgarError("get_entity_submissions", str(e), traceback.format_exc()).to_dict()}++ # =========================================================================+ # FUND REPORTS (NPX/NPORT)+ # =========================================================================++ def get_fund_report(self, ticker: str, form: str = "NPORT-P") -> Dict[str, Any]:+ """+ Get fund portfolio report (NPORT or NPX forms)++ Args:+ ticker: Fund ticker symbol+ form: Form type ("NPORT-P", "NPORT-EX", "NPX")++ Returns:+ Fund portfolio holdings+ """+ try:+ company = Company(ticker)+ filings = company.get_filings(form=form)++ if not filings or len(filings) == 0:+ return {+ "success": True,+ "data": {"holdings": [], "note": f"No {form} filings found"},+ "parameters": {"ticker": ticker, "form": form}+ }++ latest_filing = filings[0]+ fund_report = latest_filing.obj()++ holdings = []+ if fund_report:+ if hasattr(fund_report, 'holdings'):+ holdings_data = fund_report.holdings+ if holdings_data is not None and hasattr(holdings_data, 'head'):+ holdings = holdings_data.head(100).to_dict('records')++ return {+ "success": True,+ "data": {+ "filing_date": str(latest_filing.filing_date) if hasattr(latest_filing, 'filing_date') else None,+ "period_of_report": str(latest_filing.period_of_report) if hasattr(latest_filing, 'period_of_report') else None,+ "holdings": holdings,+ "holdings_count": len(holdings),+ },+ "parameters": {"ticker": ticker, "form": form}+ }+ except Exception as e:+ return {"error": EdgarError("get_fund_report", str(e), traceback.format_exc()).to_dict()}++ # =========================================================================+ # DOCUMENT & ATTACHMENT OPERATIONS+ # =========================================================================++ def get_filing_documents(self, accession_number: str) -> Dict[str, Any]:+ """+ Get all documents in a filing++ Args:+ accession_number: SEC accession number++ Returns:+ List of documents in the filing+ """+ try:+ filing = get_by_accession_number(accession_number)++ if not filing:+ return {"error": EdgarError("get_filing_documents", f"Filing not found: {accession_number}").to_dict()}++ documents = []+ if hasattr(filing, 'documents'):+ docs = filing.documents+ if docs:+ for doc in docs:+ documents.append({+ "sequence": doc.sequence if hasattr(doc, 'sequence') else None,+ "document": doc.document if hasattr(doc, 'document') else None,+ "type": doc.type if hasattr(doc, 'type') else None,+ "description": doc.description if hasattr(doc, 'description') else None,+ "size": doc.size if hasattr(doc, 'size') else None,+ })++ return {+ "success": True,+ "data": {+ "accession_number": accession_number,+ "documents": documents,+ "count": len(documents),+ },+ "parameters": {"accession_number": accession_number}+ }+ except Exception as e:+ return {"error": EdgarError("get_filing_documents", str(e), traceback.format_exc()).to_dict()}++ def get_filing_attachments(self, accession_number: str) -> Dict[str, Any]:+ """+ Get attachments/exhibits from a filing++ Args:+ accession_number: SEC accession number++ Returns:+ List of attachments/exhibits+ """+ try:+ filing = get_by_accession_number(accession_number)++ if not filing:+ return {"error": EdgarError("get_filing_attachments", f"Filing not found: {accession_number}").to_dict()}++ attachments_list = []+ if hasattr(filing, 'attachments'):+ attachments = filing.attachments+ if attachments:+ for att in attachments:+ attachments_list.append({+ "sequence": att.sequence if hasattr(att, 'sequence') else None,+ "document": att.document if hasattr(att, 'document') else None,+ "description": att.description if hasattr(att, 'description') else None,+ "type": att.type if hasattr(att, 'type') else None,+ })++ return {+ "success": True,+ "data": {+ "accession_number": accession_number,+ "attachments": attachments_list,+ "count": len(attachments_list),+ },+ "parameters": {"accession_number": accession_number}+ }+ except Exception as e:+ return {"error": EdgarError("get_filing_attachments", str(e), traceback.format_exc()).to_dict()}++ # =========================================================================+ # BATCH OPERATIONS+ # =========================================================================++ def download_filings_batch(self, ticker: str, form: str,+ year: Optional[int] = None,+ limit: int = 10,+ download_details: bool = False) -> Dict[str, Any]:+ """+ Download multiple filings at once++ Args:+ ticker: Stock ticker symbol+ form: Form type+ year: Optional year filter+ limit: Max number of filings to process+ download_details: Whether to download full details++ Returns:+ Summary of downloaded filings+ """+ try:+ from edgar import download_filings++ company = Company(ticker)+ filings = company.get_filings(form=form, year=year)++ downloaded = []+ for i, filing in enumerate(filings):+ if i >= limit:+ break++ filing_info = {+ "accession_number": filing.accession_number,+ "filing_date": str(filing.filing_date) if hasattr(filing, 'filing_date') else None,+ "form": filing.form if hasattr(filing, 'form') else None,+ }++ if download_details:+ try:+ # Download filing details+ filing_obj = filing.obj()+ if filing_obj:+ filing_info["downloaded"] = True+ except:+ filing_info["downloaded"] = False++ downloaded.append(filing_info)++ return {+ "success": True,+ "data": {+ "filings": downloaded,+ "total_downloaded": len(downloaded),+ },+ "parameters": {"ticker": ticker, "form": form, "year": year, "limit": limit}+ }+ except Exception as e:+ return {"error": EdgarError("download_filings_batch", str(e), traceback.format_exc()).to_dict()}++ # =========================================================================+ # STORAGE MANAGEMENT+ # =========================================================================++ def analyze_storage(self) -> Dict[str, Any]:+ """+ Analyze cache storage usage++ Returns:+ Storage analysis with size breakdown+ """+ try:+ from edgar import analyze_storage++ analysis = analyze_storage()++ return {+ "success": True,+ "data": {+ "analysis": str(analysis)[:2000],+ },+ }+ except Exception as e:+ return {"error": EdgarError("analyze_storage", str(e), traceback.format_exc()).to_dict()}++ def optimize_storage(self, dry_run: bool = True) -> Dict[str, Any]:+ """+ Optimize cache storage by removing old/unused files++ Args:+ dry_run: If True, only simulate optimization++ Returns:+ Optimization results+ """+ try:+ from edgar import optimize_storage++ result = optimize_storage(dry_run=dry_run)++ return {+ "success": True,+ "data": {+ "result": str(result)[:2000],+ "dry_run": dry_run,+ },+ }+ except Exception as e:+ return {"error": EdgarError("optimize_storage", str(e), traceback.format_exc()).to_dict()}++ def cleanup_storage(self, older_than_days: int = 30) -> Dict[str, Any]:+ """+ Clean up old cache files++ Args:+ older_than_days: Remove files older than this many days++ Returns:+ Cleanup results+ """+ try:+ from edgar import cleanup_storage++ result = cleanup_storage(older_than_days=older_than_days)++ return {+ "success": True,+ "data": {+ "result": str(result)[:1000],+ "older_than_days": older_than_days,+ },+ }+ except Exception as e:+ return {"error": EdgarError("cleanup_storage", str(e), traceback.format_exc()).to_dict()}+# =========================================================================# XBRL OPERATIONS# =========================================================================@@ -1844,6 +2363,23 @@ class EdgarToolsWrapper:f"No XBRL data available for filing").to_dict()}+ # Safely get counts+ statement_count = 0+ fact_count = 0++ if hasattr(xbrl, 'statements'):+ try:+ statement_count = len(xbrl.statements) if xbrl.statements else 0+ except TypeError:+ # statements might not support len()+ statement_count = 0++ if hasattr(xbrl, 'facts'):+ try:+ fact_count = len(xbrl.facts) if xbrl.facts else 0+ except TypeError:+ fact_count = 0+return {"success": True,"data": {@@ -1851,8 +2387,8 @@ class EdgarToolsWrapper:"document_type": xbrl.document_type if hasattr(xbrl, 'document_type') else None,"period_of_report": str(xbrl.period_of_report) if hasattr(xbrl, 'period_of_report') else None,"reporting_periods": [str(p) for p in xbrl.reporting_periods] if hasattr(xbrl, 'reporting_periods') else [],- "statement_count": len(xbrl.statements) if hasattr(xbrl, 'statements') else 0,- "fact_count": len(xbrl.facts) if hasattr(xbrl, 'facts') else 0,+ "statement_count": statement_count,+ "fact_count": fact_count,},"parameters": {"ticker": ticker, "form": form}}@@ -1911,6 +2447,25 @@ def main(args=None):"get_filing_by_accession <accession_number>","get_filing_text <accession_number> [max_length]","get_filings_by_date <year> [quarter] [form] [limit]"+ ],+ "entity": [+ "get_entity <cik>",+ "get_entity_submissions <cik>"+ ],+ "fund_reports": [+ "get_fund_report <ticker> [form]"+ ],+ "documents": [+ "get_filing_documents <accession_number>",+ "get_filing_attachments <accession_number>"+ ],+ "batch": [+ "download_filings_batch <ticker> <form> [year] [limit]"+ ],+ "storage": [+ "analyze_storage",+ "optimize_storage [dry_run:true|false]",+ "cleanup_storage [older_than_days]"]}}, indent=2))@@ -1960,10 +2515,10 @@ def main(args=None):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 10+ form = args[2] if len(args) > 2 and args[2] else None+ year = int(args[3]) if len(args) > 3 and args[3] else None+ quarter = int(args[4]) if len(args) > 4 and args[4] else None+ limit = int(args[5]) if len(args) > 5 and args[5] else 10result = wrapper.get_company_filings(ticker, form, year, quarter, limit)elif command == "get_corporate_events":@@ -2099,12 +2654,56 @@ def main(args=None):result = wrapper.get_filing_text(accession, max_length)elif command == "get_filings_by_date":- 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+ year = int(args[1]) if len(args) > 1 and args[1] else None+ quarter = int(args[2]) if len(args) > 2 and args[2] else None+ form = args[3] if len(args) > 3 and args[3] else None+ limit = int(args[4]) if len(args) > 4 and args[4] else 50result = wrapper.get_filings_by_date(year, quarter, form, limit)+ # Entity commands+ elif command == "get_entity":+ cik = args[1] if len(args) > 1 else None+ result = wrapper.get_entity(cik)++ elif command == "get_entity_submissions":+ cik = args[1] if len(args) > 1 else None+ result = wrapper.get_entity_submissions(cik)++ # Fund report commands+ elif command == "get_fund_report":+ ticker = args[1] if len(args) > 1 else None+ form = args[2] if len(args) > 2 else "NPORT-P"+ result = wrapper.get_fund_report(ticker, form)++ # Document commands+ elif command == "get_filing_documents":+ accession = args[1] if len(args) > 1 else None+ result = wrapper.get_filing_documents(accession)++ elif command == "get_filing_attachments":+ accession = args[1] if len(args) > 1 else None+ result = wrapper.get_filing_attachments(accession)++ # Batch commands+ elif command == "download_filings_batch":+ ticker = args[1] if len(args) > 1 else None+ form = args[2] if len(args) > 2 else None+ year = int(args[3]) if len(args) > 3 and args[3] else None+ limit = int(args[4]) if len(args) > 4 else 10+ result = wrapper.download_filings_batch(ticker, form, year, limit)++ # Storage commands+ elif command == "analyze_storage":+ result = wrapper.analyze_storage()++ elif command == "optimize_storage":+ dry_run = args[1].lower() == "true" if len(args) > 1 else True+ result = wrapper.optimize_storage(dry_run)++ elif command == "cleanup_storage":+ older_than_days = int(args[1]) if len(args) > 1 else 30+ result = wrapper.cleanup_storage(older_than_days)+else:result = {"error": EdgarError(command, f"Unknown command: {command}").to_dict()}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/angelone.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/angelone.rsindex 6d3bb5a7b..487d33d5a 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/angelone.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/angelone.rs@@ -8,6 +8,10 @@ use serde_json::{json, Value};use super::common::ApiResponse;use totp_rs::{Algorithm, TOTP, Secret};use crate::database::master_contract;+use std::time::Duration;++/// Default timeout for API requests (30 seconds)+const API_TIMEOUT: Duration = Duration::from_secs(30);/// Base URL for AngelOne APIconst ANGELONE_BASE_URL: &str = "https://apiconnect.angelone.in";@@ -56,7 +60,11 @@ async fn angel_api_call(method: &str,payload: Option<Value>,) -> Result<Value, String> {- let client = Client::new();+ let client = Client::builder()+ .timeout(API_TIMEOUT)+ .build()+ .map_err(|e| format!("Failed to create HTTP client: {}", e))?;+let url = format!("{}{}", ANGELONE_BASE_URL, endpoint);let mut builder = build_angel_request(&client, &url, method, api_key, Some(access_token));@@ -68,7 +76,13 @@ async fn angel_api_call(let response = builder.send().await- .map_err(|e| format!("Request failed: {}", e))?;+ .map_err(|e| {+ if e.is_timeout() {+ format!("Request timeout after {}s", API_TIMEOUT.as_secs())+ } else {+ format!("Request failed: {}", e)+ }+ })?;let status = response.status();let text = response@@ -132,7 +146,17 @@ pub async fn angelone_login(password: String,totp: String,) -> ApiResponse<Value> {- let client = Client::new();+ let client = match Client::builder().timeout(API_TIMEOUT).build() {+ Ok(c) => c,+ Err(e) => {+ return ApiResponse {+ success: false,+ data: None,+ error: Some(format!("Failed to create HTTP client: {}", e)),+ timestamp: chrono::Utc::now().timestamp_millis(),+ };+ }+ };let timestamp = chrono::Utc::now().timestamp_millis();let totp_code = match generate_totp_code(&totp) {@@ -526,8 +550,6 @@ pub async fn angelone_get_quote(let timestamp = chrono::Utc::now().timestamp_millis();let quote_mode = mode.unwrap_or_else(|| "FULL".to_string());- eprintln!("[AngelOne Quote] exchange={}, tokens={:?}", exchange, tokens);-let payload = json!({"mode": quote_mode,"exchangeTokens": {@@ -595,8 +617,6 @@ pub async fn angelone_get_historical("todate": to_date});- eprintln!("[AngelOne Historical] exchange={}, token={}, interval={}, from={}, to={}", exchange, symbol_token, interval, from_date, to_date);-match angel_api_call(&api_key,&access_token,@@ -628,11 +648,13 @@ pub async fn angelone_get_historical(}}}- Err(e) => ApiResponse {- success: false,- data: None,- error: Some(e),- timestamp,+ Err(e) => {+ ApiResponse {+ success: false,+ data: None,+ error: Some(e),+ timestamp,+ }},}}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/edgar_cache.rs b/fincept-terminal-desktop/src-tauri/src/commands/edgar_cache.rsnew file mode 100644index 000000000..b3de3d95b--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/edgar_cache.rs@@ -0,0 +1,153 @@+// Edgar Company Tickers Cache - SQLite storage for fast company lookup++use rusqlite::{params, Connection, Result as SqliteResult};+use serde::{Deserialize, Serialize};+use std::sync::Mutex;+use once_cell::sync::Lazy;+use std::path::PathBuf;++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CompanyTicker {+ pub cik: i64,+ pub ticker: String,+ pub company: String,+}++static CACHE_DB_PATH: Lazy<Mutex<Option<PathBuf>>> = Lazy::new(|| Mutex::new(None));++// Set database path (called during app initialization)+pub fn set_cache_db_path(path: PathBuf) {+ let mut db_path = CACHE_DB_PATH.lock().unwrap();+ *db_path = Some(path);+}++// Get cache database connection+fn get_cache_db() -> SqliteResult<Connection> {+ let db_path_guard = CACHE_DB_PATH.lock().unwrap();++ let db_path = db_path_guard.as_ref()+ .ok_or_else(|| rusqlite::Error::InvalidPath("Cache database path not set".into()))?;++ let conn = Connection::open(db_path)?;++ // Create table if not exists+ conn.execute(+ "CREATE TABLE IF NOT EXISTS edgar_company_tickers (+ cik INTEGER PRIMARY KEY,+ ticker TEXT NOT NULL,+ company TEXT NOT NULL,+ updated_at INTEGER NOT NULL+ )",+ [],+ )?;++ // Create indexes for fast searching+ conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_edgar_ticker ON edgar_company_tickers(ticker)",+ [],+ )?;+ conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_edgar_company ON edgar_company_tickers(company COLLATE NOCASE)",+ [],+ )?;++ Ok(conn)+}++#[tauri::command]+pub async fn edgar_cache_store_tickers(tickers: Vec<CompanyTicker>) -> Result<String, String> {+ let conn = get_cache_db().map_err(|e| e.to_string())?;+ let timestamp = chrono::Utc::now().timestamp();++ let tx = conn.unchecked_transaction().map_err(|e| e.to_string())?;++ // Clear existing data+ tx.execute("DELETE FROM edgar_company_tickers", []).map_err(|e| e.to_string())?;++ // Insert new data with REPLACE to handle duplicates+ let mut stmt = tx.prepare(+ "INSERT OR REPLACE INTO edgar_company_tickers (cik, ticker, company, updated_at) VALUES (?1, ?2, ?3, ?4)"+ ).map_err(|e| e.to_string())?;++ for ticker in &tickers {+ stmt.execute(params![ticker.cik, ticker.ticker, ticker.company, timestamp])+ .map_err(|e| e.to_string())?;+ }++ drop(stmt);+ tx.commit().map_err(|e| e.to_string())?;++ Ok(format!("Stored {} companies in cache", tickers.len()))+}++#[tauri::command]+pub async fn edgar_cache_search_companies(query: String, limit: usize) -> Result<Vec<CompanyTicker>, String> {+ let conn = get_cache_db().map_err(|e| e.to_string())?;++ let query_lower = query.to_lowercase();+ let query_pattern = format!("%{}%", query_lower);++ let mut stmt = conn.prepare(+ "SELECT cik, ticker, company FROM edgar_company_tickers+ WHERE LOWER(ticker) LIKE ?1 OR LOWER(company) LIKE ?1+ LIMIT ?2"+ ).map_err(|e| e.to_string())?;++ let rows = stmt.query_map(params![query_pattern, limit as i64], |row| {+ Ok(CompanyTicker {+ cik: row.get(0)?,+ ticker: row.get(1)?,+ company: row.get(2)?,+ })+ }).map_err(|e| e.to_string())?;++ let mut results = Vec::new();+ for row in rows {+ results.push(row.map_err(|e| e.to_string())?);+ }++ Ok(results)+}++#[tauri::command]+pub async fn edgar_cache_get_all_companies() -> Result<Vec<CompanyTicker>, String> {+ let conn = get_cache_db().map_err(|e| e.to_string())?;++ let mut stmt = conn.prepare(+ "SELECT cik, ticker, company FROM edgar_company_tickers"+ ).map_err(|e| e.to_string())?;++ let rows = stmt.query_map([], |row| {+ Ok(CompanyTicker {+ cik: row.get(0)?,+ ticker: row.get(1)?,+ company: row.get(2)?,+ })+ }).map_err(|e| e.to_string())?;++ let mut results = Vec::new();+ for row in rows {+ results.push(row.map_err(|e| e.to_string())?);+ }++ Ok(results)+}++#[tauri::command]+pub async fn edgar_cache_get_count() -> Result<i64, String> {+ let conn = get_cache_db().map_err(|e| e.to_string())?;++ let count: i64 = conn.query_row(+ "SELECT COUNT(*) FROM edgar_company_tickers",+ [],+ |row| row.get(0)+ ).map_err(|e| e.to_string())?;++ Ok(count)+}++#[tauri::command]+pub async fn edgar_cache_is_populated() -> Result<bool, String> {+ let count = edgar_cache_get_count().await?;+ Ok(count > 1000) // Consider populated if >1000 companies+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/ma_analytics.rs b/fincept-terminal-desktop/src-tauri/src/commands/ma_analytics.rsnew file mode 100644index 000000000..a73379bd9--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/ma_analytics.rs@@ -0,0 +1,683 @@+// M&A Analytics Module Commands - Complete M&A and Financial Advisory System+#![allow(dead_code)]+use crate::python;++// ============================================================================+// DEAL DATABASE COMMANDS+// ============================================================================++#[tauri::command]+pub async fn scan_ma_filings(+ app: tauri::AppHandle,+ days_back: Option<i32>,+ filing_types: Option<String>,+) -> Result<String, String> {+ let mut args = vec!["scan".to_string()];+ if let Some(days) = days_back {+ args.push(days.to_string());+ }+ if let Some(types) = filing_types {+ args.push(types);+ }+ python::execute(&app, "Analytics/corporateFinance/deal_database/deal_scanner.py", args).await+}++#[tauri::command]+pub async fn parse_ma_filing(+ app: tauri::AppHandle,+ filing_url: String,+ filing_type: String,+) -> Result<String, String> {+ let args = vec!["parse".to_string(), filing_url, filing_type];+ python::execute(&app, "Analytics/corporateFinance/deal_database/deal_parser.py", args).await+}++#[tauri::command]+pub async fn create_ma_deal(+ app: tauri::AppHandle,+ deal_data: String,+) -> Result<String, String> {+ let args = vec!["create".to_string(), deal_data];+ python::execute(&app, "Analytics/corporateFinance/deal_database/database_schema.py", args).await+}++#[tauri::command]+pub async fn get_all_ma_deals(+ app: tauri::AppHandle,+ filters: Option<String>,+) -> Result<String, String> {+ let mut args = vec!["get_all".to_string()];+ if let Some(f) = filters {+ args.push(f);+ }+ python::execute(&app, "Analytics/corporateFinance/deal_database/database_schema.py", args).await+}++#[tauri::command]+pub async fn search_ma_deals(+ app: tauri::AppHandle,+ query: String,+ search_type: Option<String>,+) -> Result<String, String> {+ let mut args = vec!["search".to_string(), query];+ if let Some(st) = search_type {+ args.push(st);+ }+ python::execute(&app, "Analytics/corporateFinance/deal_database/database_schema.py", args).await+}++#[tauri::command]+pub async fn update_ma_deal(+ app: tauri::AppHandle,+ deal_id: String,+ updates: String,+) -> Result<String, String> {+ let args = vec!["update".to_string(), deal_id, updates];+ python::execute(&app, "Analytics/corporateFinance/deal_database/database_schema.py", args).await+}++// ============================================================================+// VALUATION ANALYSIS COMMANDS+// ============================================================================++#[tauri::command]+pub async fn calculate_precedent_transactions(+ app: tauri::AppHandle,+ target_data: String,+ comp_deals: String,+) -> Result<String, String> {+ let args = vec!["precedent".to_string(), target_data, comp_deals];+ python::execute(&app, "Analytics/corporateFinance/valuation/precedent_transactions.py", args).await+}++#[tauri::command]+pub async fn calculate_trading_comps(+ app: tauri::AppHandle,+ target_ticker: String,+ comp_tickers: String,+) -> Result<String, String> {+ let args = vec!["trading_comps".to_string(), target_ticker, comp_tickers];+ python::execute(&app, "Analytics/corporateFinance/valuation/trading_comps.py", args).await+}++#[tauri::command]+pub async fn calculate_ma_dcf(+ app: tauri::AppHandle,+ wacc_inputs: String,+ fcf_inputs: String,+ growth_rates: String,+ terminal_growth: f64,+ balance_sheet: String,+ shares_outstanding: f64,+) -> Result<String, String> {+ let args = vec![+ "dcf".to_string(),+ wacc_inputs,+ fcf_inputs,+ growth_rates,+ terminal_growth.to_string(),+ balance_sheet,+ shares_outstanding.to_string(),+ ];+ python::execute(&app, "Analytics/corporateFinance/valuation/dcf_model.py", args).await+}++#[tauri::command]+pub async fn calculate_dcf_sensitivity(+ app: tauri::AppHandle,+ base_fcf: f64,+ growth_rates: String,+ terminal_growth_scenarios: String,+ wacc_scenarios: String,+ balance_sheet: String,+ shares_outstanding: f64,+) -> Result<String, String> {+ let args = vec![+ "sensitivity".to_string(),+ base_fcf.to_string(),+ growth_rates,+ terminal_growth_scenarios,+ wacc_scenarios,+ balance_sheet,+ shares_outstanding.to_string(),+ ];+ python::execute(&app, "Analytics/corporateFinance/valuation/dcf_model.py", args).await+}++#[tauri::command]+pub async fn generate_football_field(+ app: tauri::AppHandle,+ valuation_methods: String,+ shares_outstanding: f64,+) -> Result<String, String> {+ let args = vec!["football_field".to_string(), valuation_methods, shares_outstanding.to_string()];+ python::execute(&app, "Analytics/corporateFinance/valuation/football_field.py", args).await+}++// ============================================================================+// MERGER MODEL COMMANDS+// ============================================================================++#[tauri::command]+pub async fn build_merger_model(+ app: tauri::AppHandle,+ acquirer_data: String,+ target_data: String,+ deal_structure: String,+) -> Result<String, String> {+ let args = vec!["build".to_string(), acquirer_data, target_data, deal_structure];+ python::execute(&app, "Analytics/corporateFinance/merger_models/merger_model.py", args).await+}++#[tauri::command]+pub async fn calculate_accretion_dilution(+ app: tauri::AppHandle,+ merger_model_data: String,+) -> Result<String, String> {+ let args = vec!["accretion_dilution".to_string(), merger_model_data];+ python::execute(&app, "Analytics/corporateFinance/merger_models/merger_model.py", args).await+}++#[tauri::command]+pub async fn build_pro_forma(+ app: tauri::AppHandle,+ acquirer_data: String,+ target_data: String,+ year: i32,+) -> Result<String, String> {+ let args = vec!["pro_forma".to_string(), acquirer_data, target_data, year.to_string()];+ python::execute(&app, "Analytics/corporateFinance/merger_models/merger_model.py", args).await+}++#[tauri::command]+pub async fn calculate_sources_uses(+ app: tauri::AppHandle,+ deal_structure: String,+ financing_structure: String,+) -> Result<String, String> {+ let args = vec!["sources_uses".to_string(), deal_structure, financing_structure];+ python::execute(&app, "Analytics/corporateFinance/merger_models/sources_uses.py", args).await+}++#[tauri::command]+pub async fn analyze_contribution(+ app: tauri::AppHandle,+ acquirer_data: String,+ target_data: String,+ ownership_split: f64,+) -> Result<String, String> {+ let args = vec![+ "contribution".to_string(),+ acquirer_data,+ target_data,+ ownership_split.to_string(),+ ];+ python::execute(&app, "Analytics/corporateFinance/merger_models/contribution_analysis.py", args).await+}++// ============================================================================+// LBO MODEL COMMANDS+// ============================================================================++#[tauri::command]+pub async fn build_lbo_model(+ app: tauri::AppHandle,+ company_data: String,+ transaction_assumptions: String,+ projection_years: i32,+) -> Result<String, String> {+ let args = vec![+ "build".to_string(),+ company_data,+ transaction_assumptions,+ projection_years.to_string(),+ ];+ python::execute(&app, "Analytics/corporateFinance/lbo/lbo_model.py", args).await+}++#[tauri::command]+pub async fn calculate_lbo_returns(+ app: tauri::AppHandle,+ entry_valuation: f64,+ exit_valuation: f64,+ equity_invested: f64,+ holding_period: i32,+) -> Result<String, String> {+ let args = vec![+ "returns".to_string(),+ entry_valuation.to_string(),+ exit_valuation.to_string(),+ equity_invested.to_string(),+ holding_period.to_string(),+ ];+ python::execute(&app, "Analytics/corporateFinance/lbo/returns_analysis.py", args).await+}++#[tauri::command]+pub async fn analyze_lbo_debt_schedule(+ app: tauri::AppHandle,+ debt_structure: String,+ cash_flows: String,+ sweep_percentage: f64,+) -> Result<String, String> {+ let args = vec![+ "debt_schedule".to_string(),+ debt_structure,+ cash_flows,+ sweep_percentage.to_string(),+ ];+ python::execute(&app, "Analytics/corporateFinance/lbo/debt_schedule.py", args).await+}++#[tauri::command]+pub async fn calculate_lbo_sensitivity(+ app: tauri::AppHandle,+ base_case: String,+ revenue_growth_scenarios: String,+ exit_multiple_scenarios: String,+) -> Result<String, String> {+ let args = vec![+ "sensitivity".to_string(),+ base_case,+ revenue_growth_scenarios,+ exit_multiple_scenarios,+ ];+ python::execute(&app, "Analytics/corporateFinance/lbo/lbo_model.py", args).await+}++// ============================================================================+// STARTUP VALUATION COMMANDS+// ============================================================================++#[tauri::command]+pub async fn calculate_berkus_valuation(+ app: tauri::AppHandle,+ factor_scores: String,+) -> Result<String, String> {+ let args = vec!["berkus".to_string(), factor_scores];+ python::execute(&app, "Analytics/corporateFinance/startup_valuation/berkus_method.py", args).await+}++#[tauri::command]+pub async fn calculate_scorecard_valuation(+ app: tauri::AppHandle,+ stage: String,+ region: String,+ factor_assessments: String,+) -> Result<String, String> {+ let args = vec!["scorecard".to_string(), stage, region, factor_assessments];+ python::execute(&app, "Analytics/corporateFinance/startup_valuation/scorecard_method.py", args).await+}++#[tauri::command]+pub async fn calculate_vc_method_valuation(+ app: tauri::AppHandle,+ exit_year_metric: f64,+ exit_multiple: f64,+ years_to_exit: i32,+ investment_amount: f64,+ stage: String,+) -> Result<String, String> {+ let args = vec![+ "vc_method".to_string(),+ exit_year_metric.to_string(),+ exit_multiple.to_string(),+ years_to_exit.to_string(),+ investment_amount.to_string(),+ stage,+ ];+ python::execute(&app, "Analytics/corporateFinance/startup_valuation/vc_method.py", args).await+}++#[tauri::command]+pub async fn calculate_first_chicago_valuation(+ app: tauri::AppHandle,+ scenarios: String,+) -> Result<String, String> {+ let args = vec!["first_chicago".to_string(), scenarios];+ python::execute(&app, "Analytics/corporateFinance/startup_valuation/first_chicago_method.py", args).await+}++#[tauri::command]+pub async fn calculate_risk_factor_valuation(+ app: tauri::AppHandle,+ base_valuation: f64,+ risk_assessments: String,+) -> Result<String, String> {+ let args = vec![+ "risk_factor".to_string(),+ base_valuation.to_string(),+ risk_assessments,+ ];+ python::execute(&app, "Analytics/corporateFinance/startup_valuation/risk_factor_summation.py", args).await+}++#[tauri::command]+pub async fn comprehensive_startup_valuation(+ app: tauri::AppHandle,+ startup_name: String,+ berkus_scores: Option<String>,+ scorecard_inputs: Option<String>,+ vc_inputs: Option<String>,+ first_chicago_scenarios: Option<String>,+ risk_factor_assessments: Option<String>,+) -> Result<String, String> {+ let mut args = vec!["comprehensive".to_string(), startup_name];+ if let Some(bs) = berkus_scores { args.push(bs); }+ if let Some(si) = scorecard_inputs { args.push(si); }+ if let Some(vi) = vc_inputs { args.push(vi); }+ if let Some(fcs) = first_chicago_scenarios { args.push(fcs); }+ if let Some(rfa) = risk_factor_assessments { args.push(rfa); }+ python::execute(&app, "Analytics/corporateFinance/startup_valuation/startup_summary.py", args).await+}++#[tauri::command]+pub async fn quick_pre_revenue_valuation(+ app: tauri::AppHandle,+ idea_quality: i32,+ team_quality: i32,+ prototype_status: i32,+ market_size: i32,+) -> Result<String, String> {+ let args = vec![+ "quick_pre_revenue".to_string(),+ idea_quality.to_string(),+ team_quality.to_string(),+ prototype_status.to_string(),+ market_size.to_string(),+ ];+ python::execute(&app, "Analytics/corporateFinance/startup_valuation/startup_summary.py", args).await+}++// ============================================================================+// DEAL STRUCTURE COMMANDS+// ============================================================================++#[tauri::command]+pub async fn analyze_payment_structure(+ app: tauri::AppHandle,+ purchase_price: f64,+ cash_percentage: f64,+ acquirer_cash: f64,+ debt_capacity: f64,+) -> Result<String, String> {+ let args = vec![+ "payment".to_string(),+ purchase_price.to_string(),+ cash_percentage.to_string(),+ acquirer_cash.to_string(),+ debt_capacity.to_string(),+ ];+ python::execute(&app, "Analytics/corporateFinance/deal_structure/payment_structure.py", args).await+}++#[tauri::command]+pub async fn value_earnout(+ app: tauri::AppHandle,+ earnout_params: String,+ financial_projections: String,+) -> Result<String, String> {+ let args = vec!["earnout".to_string(), earnout_params, financial_projections];+ python::execute(&app, "Analytics/corporateFinance/deal_structure/earnout_valuation.py", args).await+}++#[tauri::command]+pub async fn calculate_exchange_ratio(+ app: tauri::AppHandle,+ acquirer_price: f64,+ target_price: f64,+ offer_premium: f64,+) -> Result<String, String> {+ let args = vec![+ "exchange_ratio".to_string(),+ acquirer_price.to_string(),+ target_price.to_string(),+ offer_premium.to_string(),+ ];+ python::execute(&app, "Analytics/corporateFinance/deal_structure/exchange_ratio.py", args).await+}++#[tauri::command]+pub async fn analyze_collar_mechanism(+ app: tauri::AppHandle,+ collar_params: String,+ price_scenarios: String,+) -> Result<String, String> {+ let args = vec!["collar".to_string(), collar_params, price_scenarios];+ python::execute(&app, "Analytics/corporateFinance/deal_structure/collar_mechanism.py", args).await+}++#[tauri::command]+pub async fn value_cvr(+ app: tauri::AppHandle,+ cvr_type: String,+ cvr_params: String,+) -> Result<String, String> {+ let args = vec!["cvr".to_string(), cvr_type, cvr_params];+ python::execute(&app, "Analytics/corporateFinance/deal_structure/cvr_valuation.py", args).await+}++// ============================================================================+// SYNERGIES COMMANDS+// ============================================================================++#[tauri::command]+pub async fn calculate_revenue_synergies(+ app: tauri::AppHandle,+ synergy_type: String,+ synergy_params: String,+) -> Result<String, String> {+ let args = vec!["revenue".to_string(), synergy_type, synergy_params];+ python::execute(&app, "Analytics/corporateFinance/synergies/revenue_synergies.py", args).await+}++#[tauri::command]+pub async fn calculate_cost_synergies(+ app: tauri::AppHandle,+ synergy_type: String,+ synergy_params: String,+) -> Result<String, String> {+ let args = vec!["cost".to_string(), synergy_type, synergy_params];+ python::execute(&app, "Analytics/corporateFinance/synergies/cost_synergies.py", args).await+}++#[tauri::command]+pub async fn estimate_integration_costs(+ app: tauri::AppHandle,+ deal_size: f64,+ complexity_level: String,+ integration_plan: String,+) -> Result<String, String> {+ let args = vec![+ "integration".to_string(),+ deal_size.to_string(),+ complexity_level,+ integration_plan,+ ];+ python::execute(&app, "Analytics/corporateFinance/synergies/integration_costs.py", args).await+}++#[tauri::command]+pub async fn value_synergies_dcf(+ app: tauri::AppHandle,+ revenue_synergies: String,+ cost_synergies: String,+ integration_costs: String,+ discount_rate: f64,+) -> Result<String, String> {+ let args = vec![+ "dcf".to_string(),+ revenue_synergies,+ cost_synergies,+ integration_costs,+ discount_rate.to_string(),+ ];+ python::execute(&app, "Analytics/corporateFinance/synergies/synergy_valuation.py", args).await+}++// ============================================================================+// FAIRNESS OPINION COMMANDS+// ============================================================================++#[tauri::command]+pub async fn generate_fairness_opinion(+ app: tauri::AppHandle,+ valuation_methods: String,+ offer_price: f64,+ qualitative_factors: String,+) -> Result<String, String> {+ let args = vec![+ "fairness".to_string(),+ valuation_methods,+ offer_price.to_string(),+ qualitative_factors,+ ];+ python::execute(&app, "Analytics/corporateFinance/fairness_opinion/valuation_framework.py", args).await+}++#[tauri::command]+pub async fn analyze_premium_fairness(+ app: tauri::AppHandle,+ daily_prices: String,+ offer_price: f64,+ announcement_date: Option<i32>,+) -> Result<String, String> {+ let mut args = vec!["premium".to_string(), daily_prices, offer_price.to_string()];+ if let Some(date) = announcement_date {+ args.push(date.to_string());+ }+ python::execute(&app, "Analytics/corporateFinance/fairness_opinion/premium_analysis.py", args).await+}++#[tauri::command]+pub async fn assess_process_quality(+ app: tauri::AppHandle,+ process_factors: String,+) -> Result<String, String> {+ let args = vec!["process".to_string(), process_factors];+ python::execute(&app, "Analytics/corporateFinance/fairness_opinion/process_quality.py", args).await+}++// ============================================================================+// INDUSTRY METRICS COMMANDS+// ============================================================================++#[tauri::command]+pub async fn calculate_tech_metrics(+ app: tauri::AppHandle,+ sector: String,+ company_data: String,+) -> Result<String, String> {+ let args = vec!["tech".to_string(), sector, company_data];+ python::execute(&app, "Analytics/corporateFinance/industry_metrics/technology.py", args).await+}++#[tauri::command]+pub async fn calculate_healthcare_metrics(+ app: tauri::AppHandle,+ sector: String,+ company_data: String,+) -> Result<String, String> {+ let args = vec!["healthcare".to_string(), sector, company_data];+ python::execute(&app, "Analytics/corporateFinance/industry_metrics/healthcare.py", args).await+}++#[tauri::command]+pub async fn calculate_financial_services_metrics(+ app: tauri::AppHandle,+ sector: String,+ institution_data: String,+) -> Result<String, String> {+ let args = vec!["financial".to_string(), sector, institution_data];+ python::execute(&app, "Analytics/corporateFinance/industry_metrics/financial_services.py", args).await+}++// ============================================================================+// ADVANCED ANALYTICS COMMANDS+// ============================================================================++#[tauri::command]+pub async fn run_monte_carlo_valuation(+ app: tauri::AppHandle,+ base_valuation: f64,+ revenue_growth_mean: f64,+ revenue_growth_std: f64,+ margin_mean: f64,+ margin_std: f64,+ discount_rate: f64,+ simulations: i32,+) -> Result<String, String> {+ let args = vec![+ "monte_carlo".to_string(),+ base_valuation.to_string(),+ revenue_growth_mean.to_string(),+ revenue_growth_std.to_string(),+ margin_mean.to_string(),+ margin_std.to_string(),+ discount_rate.to_string(),+ simulations.to_string(),+ ];+ python::execute(&app, "Analytics/corporateFinance/advanced_analytics/monte_carlo_valuation.py", args).await+}++#[tauri::command]+pub async fn run_regression_valuation(+ app: tauri::AppHandle,+ comp_data: String,+ subject_metrics: String,+ regression_type: String,+) -> Result<String, String> {+ let args = vec!["regression".to_string(), comp_data, subject_metrics, regression_type];+ python::execute(&app, "Analytics/corporateFinance/advanced_analytics/regression_analysis.py", args).await+}++// ============================================================================+// DEAL COMPARISON COMMANDS+// ============================================================================++#[tauri::command]+pub async fn compare_deals(+ app: tauri::AppHandle,+ deals: String,+) -> Result<String, String> {+ let args = vec!["compare".to_string(), deals];+ python::execute(&app, "Analytics/corporateFinance/deal_comparison/deal_comparator.py", args).await+}++#[tauri::command]+pub async fn rank_deals(+ app: tauri::AppHandle,+ deals: String,+ criteria: String,+) -> Result<String, String> {+ let args = vec!["rank".to_string(), deals, criteria];+ python::execute(&app, "Analytics/corporateFinance/deal_comparison/deal_comparator.py", args).await+}++#[tauri::command]+pub async fn benchmark_deal_premium(+ app: tauri::AppHandle,+ target_deal: String,+ comparable_deals: String,+) -> Result<String, String> {+ let args = vec!["benchmark".to_string(), target_deal, comparable_deals];+ python::execute(&app, "Analytics/corporateFinance/deal_comparison/deal_comparator.py", args).await+}++#[tauri::command]+pub async fn analyze_payment_structures(+ app: tauri::AppHandle,+ deals: String,+) -> Result<String, String> {+ let args = vec!["payment_analysis".to_string(), deals];+ python::execute(&app, "Analytics/corporateFinance/deal_comparison/deal_comparator.py", args).await+}++#[tauri::command]+pub async fn analyze_industry_deals(+ app: tauri::AppHandle,+ deals: String,+) -> Result<String, String> {+ let args = vec!["industry_analysis".to_string(), deals];+ python::execute(&app, "Analytics/corporateFinance/deal_comparison/deal_comparator.py", args).await+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rsindex 88802f3f5..09b394e62 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs@@ -13,6 +13,7 @@ pub mod fmp;pub mod federal_reserve;pub mod sec;pub mod edgar;+pub mod edgar_cache;pub mod cftc;pub mod cboe;pub mod bls;@@ -158,3 +159,6 @@ pub mod llm_models;// Custom Index - Aggregate Index Featurepub mod custom_index;++// M&A Analytics - Complete M&A and Financial Advisory System+pub mod ma_analytics;diff --git a/fincept-terminal-desktop/src-tauri/src/commands/unified_trading.rs b/fincept-terminal-desktop/src-tauri/src/commands/unified_trading.rsindex 5219e5083..c3a57e65b 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/unified_trading.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/unified_trading.rs@@ -120,8 +120,6 @@ pub async fn init_trading_session(let mut session_guard = TRADING_SESSION.write().await;*session_guard = Some(session.clone());- eprintln!("[UnifiedTrading] Session initialized: {:?} mode for {}", trading_mode, broker);-Ok(session)}@@ -159,7 +157,6 @@ pub async fn switch_trading_mode(mode: String) -> Result<TradingSession, String>session.paper_portfolio_id = Some(portfolio.id);}- eprintln!("[UnifiedTrading] Switched to {:?} mode", trading_mode);Ok(session.clone())} else {Err("No active trading session".to_string())@@ -200,23 +197,29 @@ async fn place_paper_order(let symbol = format!("{}:{}", order.exchange, order.symbol);+ // For market orders without price, use a default price estimate (will be filled at market)+ let order_price = if order.order_type == "market" && order.price.is_none() {+ // Use a default placeholder price - order will be filled at actual market price+ Some(1000.0) // Default estimate for margin calculation+ } else {+ order.price+ };+let paper_order = paper_trading::place_order(portfolio_id,&symbol,&order.side,&order.order_type,order.quantity,- order.price,+ order_price,order.stop_price,false, // reduce_only).map_err(|e| e.to_string())?;- // For market orders, auto-fill immediately if we have a price+ // For market orders, auto-fill immediately with estimated priceif order.order_type == "market" {- if let Some(price) = order.price {- let _ = paper_trading::fill_order(&paper_order.id, price, None);- }- // Otherwise, the order will be filled when we receive a tick+ let fill_price = order.price.unwrap_or(order_price.unwrap_or(1000.0));+ let _ = paper_trading::fill_order(&paper_order.id, fill_price, None);}Ok(UnifiedOrderResponse {@@ -388,14 +391,7 @@ pub async fn process_tick_for_paper_trading(};if should_fill {- match paper_trading::fill_order(&order.id, price, None) {- Ok(trade) => {- eprintln!("[PaperTrading] Filled order {} at {}: {:?}", order.id, price, trade);- }- Err(e) => {- eprintln!("[PaperTrading] Failed to fill order {}: {}", order.id, e);- }- }+ let _ = paper_trading::fill_order(&order.id, price, None);}}diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rsindex e287a0a83..6a1f88b53 100644--- a/fincept-terminal-desktop/src-tauri/src/lib.rs+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs@@ -669,6 +669,12 @@ pub fn run() {.map(|p| p.join("fincept_terminal.db").to_string_lossy().to_string()).unwrap_or_else(|_| "fincept_terminal.db".to_string());+ // Initialize edgar cache database+ if let Ok(app_data_dir) = app.path().app_data_dir() {+ let edgar_cache_path = app_data_dir.join("edgar_company_cache.db");+ commands::edgar_cache::set_cache_db_path(edgar_cache_path);+ }+// Use tauri::async_runtime to spawn task in Tauri's runtimetauri::async_runtime::spawn(async move {// Set router app handle@@ -775,6 +781,11 @@ pub fn run() {commands::market_data::get_financials,commands::yfinance::execute_yfinance_command,commands::edgar::execute_edgar_command,+ commands::edgar_cache::edgar_cache_store_tickers,+ commands::edgar_cache::edgar_cache_search_companies,+ commands::edgar_cache::edgar_cache_get_all_companies,+ commands::edgar_cache::edgar_cache_get_count,+ commands::edgar_cache::edgar_cache_is_populated,commands::alphavantage::execute_alphavantage_command,commands::alphavantage::get_alphavantage_quote,commands::alphavantage::get_alphavantage_daily,@@ -2329,7 +2340,57 @@ pub fn run() {commands::llm_models::get_llm_models_by_provider,commands::llm_models::get_all_llm_models,commands::llm_models::get_llm_stats,- commands::llm_models::search_llm_models+ commands::llm_models::search_llm_models,+ // M&A Analytics Commands (Complete M&A and Financial Advisory System)+ commands::ma_analytics::scan_ma_filings,+ commands::ma_analytics::parse_ma_filing,+ commands::ma_analytics::create_ma_deal,+ commands::ma_analytics::get_all_ma_deals,+ commands::ma_analytics::search_ma_deals,+ commands::ma_analytics::update_ma_deal,+ commands::ma_analytics::calculate_precedent_transactions,+ commands::ma_analytics::calculate_trading_comps,+ commands::ma_analytics::calculate_ma_dcf,+ commands::ma_analytics::calculate_dcf_sensitivity,+ commands::ma_analytics::generate_football_field,+ commands::ma_analytics::build_merger_model,+ commands::ma_analytics::calculate_accretion_dilution,+ commands::ma_analytics::build_pro_forma,+ commands::ma_analytics::calculate_sources_uses,+ commands::ma_analytics::analyze_contribution,+ commands::ma_analytics::build_lbo_model,+ commands::ma_analytics::calculate_lbo_returns,+ commands::ma_analytics::analyze_lbo_debt_schedule,+ commands::ma_analytics::calculate_lbo_sensitivity,+ commands::ma_analytics::calculate_berkus_valuation,+ commands::ma_analytics::calculate_scorecard_valuation,+ commands::ma_analytics::calculate_vc_method_valuation,+ commands::ma_analytics::calculate_first_chicago_valuation,+ commands::ma_analytics::calculate_risk_factor_valuation,+ commands::ma_analytics::comprehensive_startup_valuation,+ commands::ma_analytics::quick_pre_revenue_valuation,+ commands::ma_analytics::analyze_payment_structure,+ commands::ma_analytics::value_earnout,+ commands::ma_analytics::calculate_exchange_ratio,+ commands::ma_analytics::analyze_collar_mechanism,+ commands::ma_analytics::value_cvr,+ commands::ma_analytics::calculate_revenue_synergies,+ commands::ma_analytics::calculate_cost_synergies,+ commands::ma_analytics::estimate_integration_costs,+ commands::ma_analytics::value_synergies_dcf,+ commands::ma_analytics::generate_fairness_opinion,+ commands::ma_analytics::analyze_premium_fairness,+ commands::ma_analytics::assess_process_quality,+ commands::ma_analytics::calculate_tech_metrics,+ commands::ma_analytics::calculate_healthcare_metrics,+ commands::ma_analytics::calculate_financial_services_metrics,+ commands::ma_analytics::run_monte_carlo_valuation,+ commands::ma_analytics::run_regression_valuation,+ commands::ma_analytics::compare_deals,+ commands::ma_analytics::rank_deals,+ commands::ma_analytics::benchmark_deal_premium,+ commands::ma_analytics::analyze_payment_structures,+ commands::ma_analytics::analyze_industry_deals]).run(tauri::generate_context!()).expect("error while running tauri application");diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/angelone.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/angelone.rsindex 35eb03c5a..8f8448514 100644--- a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/angelone.rs+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/angelone.rs@@ -30,7 +30,7 @@ use tokio_tungstenite::{// ============================================================================const ANGEL_WS_URL: &str = "wss://smartapisocket.angelone.in/smart-stream";-const HEARTBEAT_INTERVAL: u64 = 30; // spec says 30 seconds+const HEARTBEAT_INTERVAL: u64 = 30; // per official spec// Subscription modes (official spec)const MODE_LTP: u8 = 1; // packet size = 51 bytes@@ -240,7 +240,6 @@ impl AngelOneAdapter {fn parse_binary_data(data: &[u8]) -> Option<AngelTick> {// Minimum LTP packet = 51 bytesif data.len() < 51 {- eprintln!("[AngelOne WS] Binary packet too small: {} bytes (need >= 51)", data.len());return None;}@@ -343,15 +342,33 @@ impl AngelOneAdapter {let mut messages = Vec::new();+ // Extract best bid/ask from depth data if available+ let (best_bid, best_bid_qty, best_ask, best_ask_qty) = if let Some(ref entries) = tick.best_five {+ let best_bid_entry = entries.iter().filter(|e| e.is_buy).max_by(|a, b|+ a.price.partial_cmp(&b.price).unwrap_or(std::cmp::Ordering::Equal)+ );+ let best_ask_entry = entries.iter().filter(|e| !e.is_buy).min_by(|a, b|+ a.price.partial_cmp(&b.price).unwrap_or(std::cmp::Ordering::Equal)+ );+ (+ best_bid_entry.map(|e| e.price),+ best_bid_entry.map(|e| e.quantity as f64),+ best_ask_entry.map(|e| e.price),+ best_ask_entry.map(|e| e.quantity as f64),+ )+ } else {+ (None, None, None, None)+ };+// Always emit a Ticker messagemessages.push(MarketMessage::Ticker(TickerData {provider: "angelone".to_string(),symbol: symbol.clone(),price: tick.ltp,- bid: None,- ask: None,- bid_size: if tick.total_buy_qty > 0.0 { Some(tick.total_buy_qty) } else { None },- ask_size: if tick.total_sell_qty > 0.0 { Some(tick.total_sell_qty) } else { None },+ bid: best_bid,+ ask: best_ask,+ bid_size: best_bid_qty.or(if tick.total_buy_qty > 0.0 { Some(tick.total_buy_qty) } else { None }),+ ask_size: best_ask_qty.or(if tick.total_sell_qty > 0.0 { Some(tick.total_sell_qty) } else { None }),volume: if tick.volume > 0 { Some(tick.volume as f64) } else { None },high: if tick.high > 0.0 { Some(tick.high) } else { None },low: if tick.low > 0.0 { Some(tick.low) } else { None },@@ -426,15 +443,13 @@ impl AngelOneAdapter {#[async_trait]impl WebSocketAdapter for AngelOneAdapter {async fn connect(&mut self) -> anyhow::Result<()> {- eprintln!("[AngelOne WS] Connecting to {}", ANGEL_WS_URL);- eprintln!("[AngelOne WS] auth_token_len={}, api_key_len={}, client_code={}, feed_token_len={}",- self.auth_token.len(), self.api_key.len(), self.client_code, self.feed_token.len());-let uri: Uri = ANGEL_WS_URL.parse()?;+ // NOTE: Angel One WebSocket does NOT use "Bearer" prefix for Authorization header+ // It expects just the raw JWT token (authToken from login response)let request = Request::builder().uri(&uri).header("Host", uri.host().unwrap_or("smartapisocket.angelone.in"))- .header("Authorization", format!("Bearer {}", &self.auth_token))+ .header("Authorization", &self.auth_token) // NO "Bearer" prefix!.header("x-api-key", &self.api_key).header("x-client-code", &self.client_code).header("x-feed-token", &self.feed_token)@@ -445,7 +460,6 @@ impl WebSocketAdapter for AngelOneAdapter {.body(())?;let (ws_stream, response) = connect_async_with_config(request, None, false).await?;- eprintln!("[AngelOne WS] ✓ Connected! Response status: {}", response.status());*self.ws_stream.write().await = Some(ws_stream);*self.is_connected.write().await = true;@@ -459,15 +473,33 @@ impl WebSocketAdapter for AngelOneAdapter {tokio::spawn(async move {let mut msg_count: u64 = 0;loop {- let mut stream = ws_stream_clone.write().await;- if let Some(ref mut ws) = *stream {- match ws.next().await {- Some(Ok(Message::Binary(data))) => {- msg_count += 1;- if msg_count <= 5 || msg_count % 100 == 0 {- eprintln!("[AngelOne WS] Binary msg #{}: {} bytes, mode={}",- msg_count, data.len(), if data.len() > 0 { data[0] } else { 0 });+ // Use a short timeout to avoid holding the lock indefinitely+ // This allows subscribe() to acquire the lock between reads+ let message = {+ let mut stream = ws_stream_clone.write().await;+ if let Some(ref mut ws) = *stream {+ // Use tokio::time::timeout to avoid blocking forever+ match tokio::time::timeout(+ tokio::time::Duration::from_millis(100),+ ws.next()+ ).await {+ Ok(Some(msg)) => Some(msg),+ Ok(None) => {+ *is_connected_clone.write().await = false;+ break;}+ Err(_) => None, // Timeout - no message, continue loop+ }+ } else {+ break;+ }+ }; // Lock is released here++ // Process message outside the lock+ if let Some(msg_result) = message {+ match msg_result {+ Ok(Message::Binary(data)) => {+ msg_count += 1;if let Some(tick) = AngelOneAdapter::parse_binary_data(&data) {let map = token_map_clone.read().await;@@ -482,40 +514,30 @@ impl WebSocketAdapter for AngelOneAdapter {}}}- Some(Ok(Message::Text(text))) => {+ Ok(Message::Text(text)) => {if text == "pong" {// heartbeat response} else {- eprintln!("[AngelOne WS] Text: {}", text);}}- Some(Ok(Message::Ping(data))) => {- if let Err(e) = ws.send(Message::Pong(data)).await {- eprintln!("[AngelOne WS] Failed to send pong: {}", e);+ Ok(Message::Ping(data)) => {+ // Send pong - need to reacquire lock+ if let Some(ref mut ws) = *ws_stream_clone.write().await {+ if let Err(e) = ws.send(Message::Pong(data)).await {+ }}}- Some(Ok(Message::Pong(_))) => {+ Ok(Message::Pong(_)) => {// pong response to our ping}- Some(Err(e)) => {- eprintln!("[AngelOne WS] Error: {}", e);- *is_connected_clone.write().await = false;- break;- }- None => {- eprintln!("[AngelOne WS] Connection closed by server");+ Err(e) => {*is_connected_clone.write().await = false;break;}_ => {}}- } else {- break;}- drop(stream);- tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;}- eprintln!("[AngelOne WS] Message handler loop ended. Total messages: {}", msg_count);});// Heartbeat: send "ping" every 30 seconds per spec@@ -525,12 +547,10 @@ impl WebSocketAdapter for AngelOneAdapter {loop {tokio::time::sleep(tokio::time::Duration::from_secs(HEARTBEAT_INTERVAL)).await;if !*is_connected_hb.read().await {- eprintln!("[AngelOne WS] Heartbeat: not connected, stopping");break;}if let Some(ref mut ws) = *ws_stream_hb.write().await {if let Err(e) = ws.send(Message::Text("ping".to_string())).await {- eprintln!("[AngelOne WS] Heartbeat send failed: {}", e);break;}}@@ -541,13 +561,11 @@ impl WebSocketAdapter for AngelOneAdapter {}async fn disconnect(&mut self) -> anyhow::Result<()> {- eprintln!("[AngelOne WS] Disconnecting...");if let Some(ref mut ws) = *self.ws_stream.write().await {ws.close(None).await?;}*self.ws_stream.write().await = None;*self.is_connected.write().await = false;- eprintln!("[AngelOne WS] Disconnected");Ok(())}@@ -557,6 +575,7 @@ impl WebSocketAdapter for AngelOneAdapter {channel: &str,_params: Option<Value>,) -> anyhow::Result<()> {+let mode = match channel {"depth" | "snap" | "snap_quote" | "full" => AngelMode::SnapQuote, // depth is part of SnapQuote in v2"quote" => AngelMode::Quote,@@ -589,12 +608,10 @@ impl WebSocketAdapter for AngelOneAdapter {};let request_json = serde_json::to_string(&request)?;- eprintln!("[AngelOne WS] Subscribe request: {}", request_json);if let Some(ref mut ws) = *self.ws_stream.write().await {ws.send(Message::Text(request_json)).await?;self.subscriptions.write().await.insert(symbol.to_string(), mode);- eprintln!("[AngelOne WS] ✓ Subscribed to {} ({})", symbol, channel);} else {return Err(anyhow::anyhow!("WebSocket not connected"));}@@ -629,7 +646,6 @@ impl WebSocketAdapter for AngelOneAdapter {if let Some(ref mut ws) = *self.ws_stream.write().await {ws.send(Message::Text(serde_json::to_string(&request)?)).await?;self.subscriptions.write().await.remove(symbol);- eprintln!("[AngelOne WS] Unsubscribed from {}", symbol);}}diff --git a/fincept-terminal-desktop/src-tauri/tauri.conf.json b/fincept-terminal-desktop/src-tauri/tauri.conf.jsonindex 79992ee5c..c3f9712d1 100644--- a/fincept-terminal-desktop/src-tauri/tauri.conf.json+++ b/fincept-terminal-desktop/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"$schema": "https://schema.tauri.app/config/2","productName": "FinceptTerminal",- "version": "3.2.0",+ "version": "3.2.1","identifier": "com.fincept.terminal","build": {"beforeDevCommand": "bun run dev",diff --git a/fincept-terminal-desktop/src/brokers/stocks/BaseStockBrokerAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/BaseStockBrokerAdapter.tsindex 34e8538cc..622e39674 100644--- a/fincept-terminal-desktop/src/brokers/stocks/BaseStockBrokerAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/BaseStockBrokerAdapter.ts@@ -279,6 +279,48 @@ export abstract class BaseStockBrokerAdapter implements IStockBrokerAdapter {return BaseStockBrokerAdapter.isTokenValidForTodayIST(tokenTimestamp);}+ /**+ * Validate token with IST date check (for Indian brokers)+ * First checks if token is from today (IST), then validates with API+ * Subclasses should override validateTokenWithApi() for broker-specific API validation+ */+ protected async validateTokenWithDateCheck(): Promise<boolean> {+ try {+ // First check: Is token from today (IST)?+ const credentials = await this.loadCredentials();+ if (credentials?.tokenTimestamp) {+ const isFromToday = BaseStockBrokerAdapter.isTokenValidForTodayIST(credentials.tokenTimestamp);+ if (!isFromToday) {+ console.log(`[${this.brokerId}] Token is from a previous day, needs re-authentication`);+ return false;+ }+ }++ // Second check: Validate with broker-specific API (if implemented)+ if (this.accessToken) {+ const isValid = await this.validateTokenWithApi(this.accessToken);+ console.log(`[${this.brokerId}] Token API validation result: ${isValid}`);+ return isValid;+ }++ return false;+ } catch (error) {+ console.error(`[${this.brokerId}] Token validation error:`, error);+ return false;+ }+ }++ /**+ * Broker-specific API token validation+ * Override this in subclasses to implement broker-specific validation+ * Default implementation returns true (assumes valid if we have a token)+ */+ protected async validateTokenWithApi(_token: string): Promise<boolean> {+ // Default: assume valid if token exists+ // Subclasses should override with actual API validation+ return true;+ }+// ============================================================================// Authentication Guard// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/aliceblue/AliceBlueAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/aliceblue/AliceBlueAdapter.tsindex 6feb05c9f..13617bc29 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/aliceblue/AliceBlueAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/aliceblue/AliceBlueAdapter.ts@@ -198,14 +198,21 @@ export class AliceBlueAdapter extends BaseStockBrokerAdapter {}/**- * Validate session+ * Validate session (uses base class date check + API validation)*/- private async validateSession(sessionId: string): Promise<boolean> {+ private async validateSession(_sessionId: string): Promise<boolean> {+ return this.validateTokenWithDateCheck();+ }++ /**+ * AliceBlue-specific API session validation+ */+ protected override async validateTokenWithApi(token: string): Promise<boolean> {try {const response = await invoke<{ success: boolean }>('aliceblue_validate_session', {userId: this.userId,apiSecret: this.apiSecret,- sessionId: sessionId,+ sessionId: token,});return response.success;} catch {diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/angelone/AngelOneAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/AngelOneAdapter.tsindex 1fcd3221d..9e2d3abc1 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/angelone/AngelOneAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/AngelOneAdapter.ts@@ -308,7 +308,6 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {// If feedToken is missing (old credentials format), re-authenticate to get itif (!this.feedToken && this.apiKey && this.clientCode && this.password && this.totpSecret) {- console.log('[AngelOne] Token valid but feedToken missing — re-authenticating for WebSocket support...');const authResult = await this.authenticate({apiKey: this.apiKey,userId: this.clientCode,@@ -390,9 +389,12 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {// ============================================================================protected async placeOrderInternal(params: OrderParams): Promise<OrderResponse> {- // Get symbol token first- const instrument = await this.getInstrument(params.symbol, params.exchange);- const symbolToken = instrument?.token || '0';+ // Use token from params if provided, otherwise lookup+ let symbolToken = params.token;+ if (!symbolToken) {+ const instrument = await this.getInstrument(params.symbol, params.exchange);+ symbolToken = instrument?.token || '0';+ }const angelParams = toAngelOneOrderParams(params, symbolToken);@@ -930,40 +932,60 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {if (exchange === 'NSE_INDEX') apiExchange = 'NSE';if (exchange === 'BSE_INDEX') apiExchange = 'BSE';+ const MAX_RETRIES = 3;+while (currentStart <= endDate) {const currentEnd = new Date(currentStart);currentEnd.setDate(currentEnd.getDate() + chunkDays - 1);if (currentEnd > endDate) currentEnd.setTime(endDate.getTime());- try {- const response = await invoke<{- success: boolean;- data?: unknown[][];- error?: string;- }>('angelone_get_historical', {- apiKey: this.apiKey,- accessToken: this.accessToken,- exchange: apiExchange,- symbolToken: token,- interval,- fromDate: this.formatDateIST(currentStart),- toDate: this.formatDateIST(currentEnd),- });+ let chunkSuccess = false;+ let chunkRetries = 0;- if (response.success && response.data) {- const candles = response.data.map(fromAngelOneOHLCV);- allCandles.push(...candles);+ while (!chunkSuccess && chunkRetries < MAX_RETRIES) {+ try {+ const response = await invoke<{+ success: boolean;+ data?: unknown[][];+ error?: string;+ }>('angelone_get_historical', {+ apiKey: this.apiKey,+ accessToken: this.accessToken,+ exchange: apiExchange,+ symbolToken: token,+ interval,+ fromDate: this.formatDateIST(currentStart),+ toDate: this.formatDateIST(currentEnd),+ });++ if (response.success && response.data) {+ const candles = response.data.map(fromAngelOneOHLCV);+ allCandles.push(...candles);+ chunkSuccess = true;+ } else {+ // Check if error is rate limit related+ const isRateLimit = response.error?.includes('Try After Sometime') ||+ response.error?.includes('rate limit');++ if (isRateLimit && chunkRetries < MAX_RETRIES - 1) {+ // Exponential backoff: 1s, 2s, 4s+ const backoffDelay = Math.pow(2, chunkRetries) * 1000;+ await new Promise(resolve => setTimeout(resolve, backoffDelay));+ chunkRetries++;+ } else {+ chunkSuccess = true; // Skip this chunk and continue+ }+ }+ } catch (error) {+ chunkSuccess = true; // Skip this chunk and continue}+ }- currentStart.setDate(currentEnd.getDate() + 1);+ currentStart.setDate(currentEnd.getDate() + 1);- // Rate limit delay- if (currentStart <= endDate) {- await new Promise(resolve => setTimeout(resolve, 500));- }- } catch (error) {- console.error(`[AngelOne] OHLCV chunk error:`, error);- currentStart.setDate(currentEnd.getDate() + 1);+ // Rate limit delay between chunks (reduced to 300ms for faster loading)+ if (currentStart <= endDate) {+ await new Promise(resolve => setTimeout(resolve, 300));}}@@ -1024,9 +1046,7 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {try {// Try real WebSocket connection via Rust backendawait this.connectRealWebSocket();- console.log('[AngelOne] ✓ WebSocket connected via Rust backend');} catch (error) {- console.warn('[AngelOne] WebSocket connection failed, falling back to REST polling:', error);this.usePollingFallback = true;this.startQuotePolling();}@@ -1036,13 +1056,6 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {* Connect to real Angel One WebSocket via Tauri/Rust backend*/private async connectRealWebSocket(): Promise<void> {- console.log('[AngelOne WS] connectRealWebSocket called:', {- hasAccessToken: !!this.accessToken,- hasApiKey: !!this.apiKey,- hasFeedToken: !!this.feedToken,- hasClientCode: !!this.clientCode,- });-if (!this.accessToken || !this.apiKey || !this.feedToken) {throw new Error(`Missing tokens: accessToken=${!!this.accessToken}, apiKey=${!!this.apiKey}, feedToken=${!!this.feedToken}`);}@@ -1112,11 +1125,6 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {const symbol = symbolInfo?.symbol || data.symbol;const exchange = symbolInfo?.exchange || ('NSE' as StockExchange);- console.log(`[AngelOne WebSocket] Depth update for ${symbol}:`, {- bids: data.bids?.length || 0,- asks: data.asks?.length || 0,- });-// Get best bid/ask from depthconst bestBid = data.bids?.[0];const bestAsk = data.asks?.[0];@@ -1167,19 +1175,16 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {timestamp: number;}>('angelone_status', (event) => {const status = event.payload;- console.log(`[AngelOne WebSocket] Status: ${status.status} - ${status.message || ''}`);if (status.status === 'disconnected' || status.status === 'error') {this.wsConnected = false;if (!this.usePollingFallback) {- console.warn('[AngelOne] WebSocket disconnected, enabling polling fallback');this.usePollingFallback = true;this.startQuotePolling();}} else if (status.status === 'connected') {this.wsConnected = true;if (this.usePollingFallback) {- console.log('[AngelOne] WebSocket reconnected, disabling polling fallback');this.usePollingFallback = false;this.stopQuotePolling();}@@ -1206,7 +1211,7 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {try {await invoke('angelone_ws_disconnect');} catch (err) {- console.warn('[AngelOne] WebSocket disconnect error:', err);+ // Silent error handling}this.wsConnected = false;@@ -1284,7 +1289,6 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {this.pollingSymbols.clear();this.usePollingFallback = false;this.wsConnected = false;- console.log('[AngelOne] WebSocket disconnected');}protected async subscribeInternal(@@ -1310,10 +1314,7 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {symbol: `${wsExchange}:${token}`,mode: wsMode,});-- console.log(`[AngelOne] ✓ WebSocket subscribed to ${symbol} (${wsExchange}:${token}, mode: ${wsMode})`);} catch (error) {- console.error(`[AngelOne] WebSocket subscribe failed:`, error);if (!this.usePollingFallback) {this.usePollingFallback = true;this.startQuotePolling();@@ -1347,12 +1348,9 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {await invoke('angelone_ws_unsubscribe', {symbol: `${wsExchange}:${token}`,});- console.log(`[AngelOne] ✓ WebSocket unsubscribed from ${symbol}`);} catch (error) {- console.warn(`[AngelOne] WebSocket unsubscribe failed:`, error);+ // Silent error handling}- } else {- console.log(`[AngelOne] Removed ${key} from polling`);}}@@ -1388,9 +1386,11 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {return response.data.map(item => ({symbol: String(item.symbol || item.tradingsymbol || ''),+ tradingSymbol: String(item.tradingsymbol || item.symbol || ''), // AngelOne's full trading symbol (e.g., "RELIANCE-EQ")exchange: String(item.exchange || 'NSE') as StockExchange,name: String(item.name || item.symbol || ''),token: String(item.symboltoken || item.token || '0'),+ instrumentToken: String(item.symboltoken || item.token || '0'), // For compatibilitylotSize: Number(item.lotsize || 1),tickSize: Number(item.ticksize || 0.05),instrumentType: String(item.instrumenttype || 'EQ') as any,@@ -1409,9 +1409,27 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {* AngelOne API expects dates in IST, not UTC.*/private formatDateIST(date: Date): string {- const istOffset = 5.5 * 60 * 60 * 1000; // 5 hours 30 minutes in ms- const istDate = new Date(date.getTime() + istOffset);- return istDate.toISOString().replace('T', ' ').slice(0, 16);+ // Convert to IST using toLocaleString with IST timezone+ const formatter = new Intl.DateTimeFormat('en-IN', {+ timeZone: 'Asia/Kolkata',+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ hour12: false+ });++ const parts = formatter.formatToParts(date);+ const values: Record<string, string> = {};+ parts.forEach(part => {+ if (part.type !== 'literal') {+ values[part.type] = part.value;+ }+ });++ // Format as "yyyy-MM-dd HH:mm"+ return `${values.year}-${values.month}-${values.day} ${values.hour}:${values.minute}`;}async getInstrument(symbol: string, exchange: StockExchange): Promise<Instrument | null> {@@ -1423,7 +1441,7 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {}>('angelone_get_instrument', {apiKey: this.apiKey,symbol,- exchange,+ exchange: String(exchange), // Convert to string});if (!response.success || !response.data) {diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/angelone/mapper.ts b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/mapper.tsindex cb53e9b92..03186d839 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/angelone/mapper.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/mapper.ts@@ -446,15 +446,16 @@ export function fromAngelOneTick(}/**- * Convert subscription mode to Angel One WS mode+ * Convert subscription mode to Angel One WS mode string+ * NOTE: Rust command expects string, not number*/-export function toAngelOneWSMode(mode: SubscriptionMode): number {- const modeMap: Record<SubscriptionMode, number> = {- ltp: 1, // LTP mode- quote: 2, // Quote mode- full: 3, // Snap Quote mode (full depth)+export function toAngelOneWSMode(mode: SubscriptionMode): string {+ const modeMap: Record<SubscriptionMode, string> = {+ ltp: 'ltp', // LTP mode+ quote: 'quote', // Quote mode+ full: 'snap', // Snap Quote mode (full depth)};- return modeMap[mode] || 2;+ return modeMap[mode] || 'quote';}// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/dhan/DhanAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/dhan/DhanAdapter.tsindex dd3745322..352d9475e 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/dhan/DhanAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/dhan/DhanAdapter.ts@@ -248,13 +248,20 @@ export class DhanAdapter extends BaseStockBrokerAdapter {}/**- * Validate access token+ * Validate access token (uses base class date check + API validation)*/- private async validateToken(token: string, clientId: string): Promise<boolean> {+ private async validateToken(_token: string, _clientId: string): Promise<boolean> {+ return this.validateTokenWithDateCheck();+ }++ /**+ * Dhan-specific API token validation+ */+ protected override async validateTokenWithApi(token: string): Promise<boolean> {try {const response = await invoke<{ success: boolean }>('dhan_validate_token', {accessToken: token,- clientId,+ clientId: this.clientId,});return response.success;} catch {diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/fivepaisa/FivePaisaAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/fivepaisa/FivePaisaAdapter.tsindex de18a1ac3..194226d34 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/fivepaisa/FivePaisaAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/fivepaisa/FivePaisaAdapter.ts@@ -238,14 +238,21 @@ export class FivePaisaAdapter extends BaseStockBrokerAdapter {}/**- * Validate access token+ * Validate access token (uses base class date check + API validation)*/- private async validateToken(accessToken: string): Promise<boolean> {+ private async validateToken(_accessToken: string): Promise<boolean> {+ return this.validateTokenWithDateCheck();+ }++ /**+ * 5Paisa-specific API token validation+ */+ protected override async validateTokenWithApi(token: string): Promise<boolean> {try {const response = await invoke<{ success: boolean }>('fivepaisa_validate_token', {apiKey: this.apiKey,clientId: this.clientId,- accessToken,+ accessToken: token,});return response.success;} catch {diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/fyers/FyersAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/FyersAdapter.tsindex 9787dafd0..32bf49e6a 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/fyers/FyersAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/FyersAdapter.ts@@ -263,31 +263,14 @@ export class FyersAdapter extends BaseStockBrokerAdapter {this.apiSecret = credentials.apiSecret || null;this.accessToken = credentials.accessToken || null;- // If we have an access token, assume valid (Fyers tokens don't expire for 24h)- // If expired, API calls will fail and user will need to re-auth+ // If we have an access token, validate itif (this.accessToken) {- // TODO: Add token validation when Fyers provides an endpoint- // For now, optimistically restore session- console.log(`[${this.brokerId}] Access token found, attempting to restore session...`);+ console.log(`[${this.brokerId}] Access token found, validating...`);- // Test token with a lightweight API call- try {- await this.getFundsInternal();- this._isConnected = true;- console.log(`[${this.brokerId}] ✓ Session restored successfully`);-- // Download master contract for WebSocket symbol lookup (uses correct public Fyers URL)- try {- console.log(`[${this.brokerId}] Downloading master contract for WebSocket...`);- await invoke('download_fyers_master_contract');- console.log(`[${this.brokerId}] ✓ Master contract ready`);- } catch (mcErr) {- console.warn(`[${this.brokerId}] Master contract download failed:`, mcErr);- }-- return true;- } catch (err) {- console.warn(`[${this.brokerId}] Access token expired or invalid, clearing from storage...`);+ // First check if token is from today (IST)+ const isTokenValid = await this.validateToken(this.accessToken);+ if (!isTokenValid) {+ console.warn(`[${this.brokerId}] Token validation failed (expired or from previous day)`);// Clear expired token from databaseawait this.storeCredentials({@@ -302,6 +285,20 @@ export class FyersAdapter extends BaseStockBrokerAdapter {console.log(`[${this.brokerId}] Please re-authenticate to continue`);return false;}++ this._isConnected = true;+ console.log(`[${this.brokerId}] ✓ Session restored successfully`);++ // Download master contract for WebSocket symbol lookup (uses correct public Fyers URL)+ try {+ console.log(`[${this.brokerId}] Downloading master contract for WebSocket...`);+ await invoke('download_fyers_master_contract');+ console.log(`[${this.brokerId}] ✓ Master contract ready`);+ } catch (mcErr) {+ console.warn(`[${this.brokerId}] Master contract download failed:`, mcErr);+ }++ return true;}console.log(`[${this.brokerId}] No access token found, manual authentication required`);@@ -312,6 +309,26 @@ export class FyersAdapter extends BaseStockBrokerAdapter {}}+ /**+ * Validate token using IST date check and API validation+ */+ private async validateToken(_token: string): Promise<boolean> {+ return this.validateTokenWithDateCheck();+ }++ /**+ * Override to provide Fyers-specific API validation+ */+ protected override async validateTokenWithApi(token: string): Promise<boolean> {+ try {+ // Test token with a lightweight API call (get funds)+ await this.getFundsInternal();+ return true;+ } catch {+ return false;+ }+ }+// ============================================================================// Orders - Internal Implementations// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/groww/GrowwAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/groww/GrowwAdapter.tsindex 334289aae..269add7fa 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/groww/GrowwAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/groww/GrowwAdapter.ts@@ -202,9 +202,16 @@ export class GrowwAdapter extends BaseStockBrokerAdapter {}/**- * Validate access token+ * Validate access token (uses base class date check + API validation)*/- private async validateToken(token: string): Promise<boolean> {+ private async validateToken(_token: string): Promise<boolean> {+ return this.validateTokenWithDateCheck();+ }++ /**+ * Groww-specific API token validation+ */+ protected override async validateTokenWithApi(token: string): Promise<boolean> {try {const response = await invoke<{ success: boolean }>('groww_validate_token', {accessToken: token,diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/iifl/IIFLAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/iifl/IIFLAdapter.tsindex b5096c9ef..7cd5bdb89 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/iifl/IIFLAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/iifl/IIFLAdapter.ts@@ -254,16 +254,23 @@ export class IIFLAdapter extends BaseStockBrokerAdapter {}/**- * Validate access token+ * Validate access token (uses base class date check + API validation)*/- private async validateToken(accessToken: string): Promise<boolean> {+ private async validateToken(_accessToken: string): Promise<boolean> {+ return this.validateTokenWithDateCheck();+ }++ /**+ * IIFL-specific API token validation+ */+ protected override async validateTokenWithApi(token: string): Promise<boolean> {try {const response = await invoke<{success: boolean;data?: boolean;error?: string;}>('iifl_validate_token', {- accessToken,+ accessToken: token,});return response.success && response.data === true;} catch {diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/kotak/KotakAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/kotak/KotakAdapter.tsindex 16ac4d60c..5d1e6466e 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/kotak/KotakAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/kotak/KotakAdapter.ts@@ -337,9 +337,16 @@ export class KotakAdapter extends BaseStockBrokerAdapter {}/**- * Validate access token+ * Validate access token (uses base class date check + API validation)*/- private async validateToken(token: string): Promise<boolean> {+ private async validateToken(_token: string): Promise<boolean> {+ return this.validateTokenWithDateCheck();+ }++ /**+ * Kotak-specific API token validation+ */+ protected override async validateTokenWithApi(token: string): Promise<boolean> {try {const response = await invoke<{ success: boolean }>('kotak_validate_token', {authToken: token,diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/shoonya/ShoonyaAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/shoonya/ShoonyaAdapter.tsindex ba617a0aa..82e684ec6 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/shoonya/ShoonyaAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/shoonya/ShoonyaAdapter.ts@@ -208,18 +208,20 @@ export class ShoonyaAdapter extends BaseStockBrokerAdapter {this.userId = credentials.userId || null;if (this.accessToken) {- // Test token with funds call- try {- await this.getFundsInternal();- this._isConnected = true;- console.log(`[${this.brokerId}] ✓ Session restored successfully`);- return true;- } catch (err) {- console.warn(`[${this.brokerId}] Access token expired or invalid`);+ console.log(`[${this.brokerId}] Access token found, validating...`);++ // First check if token is from today (IST)+ const isTokenValid = await this.validateToken(this.accessToken);+ if (!isTokenValid) {+ console.warn(`[${this.brokerId}] Token validation failed (expired or from previous day)`);this.accessToken = null;this._isConnected = false;return false;}++ this._isConnected = true;+ console.log(`[${this.brokerId}] ✓ Session restored successfully`);+ return true;}return false;@@ -229,6 +231,26 @@ export class ShoonyaAdapter extends BaseStockBrokerAdapter {}}+ /**+ * Validate token using IST date check and API validation+ */+ private async validateToken(_token: string): Promise<boolean> {+ return this.validateTokenWithDateCheck();+ }++ /**+ * Override to provide Shoonya-specific API validation+ */+ protected override async validateTokenWithApi(token: string): Promise<boolean> {+ try {+ // Test token with a lightweight API call (get funds)+ await this.getFundsInternal();+ return true;+ } catch {+ return false;+ }+ }+// ============================================================================// Orders - Internal Implementations// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/upstox/UpstoxAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/upstox/UpstoxAdapter.tsindex 1c86cc43e..0320d71e8 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/upstox/UpstoxAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/upstox/UpstoxAdapter.ts@@ -225,9 +225,16 @@ export class UpstoxAdapter extends BaseStockBrokerAdapter {}/**- * Validate access token+ * Validate access token (uses base class date check + API validation)*/- private async validateToken(token: string): Promise<boolean> {+ private async validateToken(_token: string): Promise<boolean> {+ return this.validateTokenWithDateCheck();+ }++ /**+ * Upstox-specific API token validation+ */+ protected override async validateTokenWithApi(token: string): Promise<boolean> {try {const response = await invoke<{ success: boolean }>('upstox_validate_token', {accessToken: token,diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/ZerodhaAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/ZerodhaAdapter.tsindex 297ec4136..edd14fd1a 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/ZerodhaAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/ZerodhaAdapter.ts@@ -231,9 +231,16 @@ export class ZerodhaAdapter extends BaseStockBrokerAdapter {}/**- * Validate access token+ * Validate access token (uses base class date check + API validation)*/- private async validateToken(token: string): Promise<boolean> {+ private async validateToken(_token: string): Promise<boolean> {+ return this.validateTokenWithDateCheck();+ }++ /**+ * Zerodha-specific API token validation+ */+ protected override async validateTokenWithApi(token: string): Promise<boolean> {try {const response = await invoke<{ success: boolean }>('zerodha_validate_token', {apiKey: this.apiKey,diff --git a/fincept-terminal-desktop/src/brokers/stocks/types.ts b/fincept-terminal-desktop/src/brokers/stocks/types.tsindex e00631cfd..a8edfc709 100644--- a/fincept-terminal-desktop/src/brokers/stocks/types.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/types.ts@@ -62,11 +62,15 @@ export type OptionType = 'CE' | 'PE' | 'CALL' | 'PUT';export interface Instrument {symbol: string; // "RELIANCE", "AAPL"+ tradingSymbol?: string; // Broker-specific format "RELIANCE-EQ", "NIFTY23DEC17500CE"name: string; // "Reliance Industries Ltd"exchange: StockExchange;instrumentType: InstrumentType;currency: Currency;- token?: string; // Broker-specific token+ token?: string; // Broker-specific token (AngelOne: symboltoken)+ instrumentToken?: string; // Zerodha instrument token+ exchangeToken?: string; // Zerodha exchange token+ segment?: string; // Trading segmentisin?: string; // International Securities IDlotSize: number;tickSize: number;@@ -130,6 +134,8 @@ export interface OrderParams {validity?: OrderValidity;disclosedQuantity?: number; // Iceberg orderstag?: string; // Order tag/reference+ token?: string; // Broker-specific instrument token (avoids re-lookup)+ tradingSymbol?: string; // Broker-specific trading symbol format// Region-specific (optional)amo?: boolean; // After Market Order (India)squareOff?: number; // Bracket order targetdiff --git a/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx b/fincept-terminal-desktop/src/components/auth/PricingScreen.tsxindex 21eac0eeb..2236df0b5 100644--- a/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx+++ b/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx@@ -301,18 +301,19 @@ const handleSelectPlan = async () => {{/* Features Section - Flexible Height */}<div className="flex-1"><div className="text-xs text-zinc-300 space-y-0.5">- <div className="flex items-center">- <Check className="w-3 h-3 text-green-400 mr-2 flex-shrink-0" />- <span>{plan.support_display}</span>- </div>- <div className="flex items-center">- <Check className="w-3 h-3 text-green-400 mr-2 flex-shrink-0" />- <span>All API endpoints</span>- </div>- <div className="flex items-center">- <Check className="w-3 h-3 text-green-400 mr-2 flex-shrink-0" />- <span>Real-time data access</span>- </div>+ {plan.features && plan.features.length > 0 ? (+ plan.features.map((feature: string, idx: number) => (+ <div key={idx} className="flex items-center">+ <Check className="w-3 h-3 text-green-400 mr-2 flex-shrink-0" />+ <span>{feature}</span>+ </div>+ ))+ ) : (+ <div className="flex items-center">+ <Check className="w-3 h-3 text-green-400 mr-2 flex-shrink-0" />+ <span>{plan.support_display}</span>+ </div>+ )}</div></div></div>diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsxindex 667a214be..43ded7747 100644--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx@@ -62,6 +62,7 @@ const ExcelTab = React.lazy(() => import('@/components/tabs/excel'));const SurfaceAnalyticsTab = React.lazy(() => import('@/components/tabs/surface-analytics'));const PolymarketTab = React.lazy(() => import('@/components/tabs/polymarket'));const TradeVisualizationTab = React.lazy(() => import('@/components/tabs/trade-visualization'));+const MAAnalyticsTab = React.lazy(() => import('@/components/tabs/MAAnalyticsTab'));const AlphaArenaTab = React.lazy(() => import('@/components/tabs/alpha-arena'));const NotesTab = React.lazy(() => import('@/components/tabs/notes').then(m => ({ default: m.NotesTab })));@@ -875,6 +876,13 @@ function FinxeptTerminalContent() {>Code Editor</TabsTrigger>+ <TabsTrigger+ value="ma-analytics"+ style={activeTab === 'ma-analytics' ? tabStyles.active : tabStyles.default}+ title="M&A Analytics"+ >+ M&A Analytics+ </TabsTrigger><TabsTriggervalue="profile"style={activeTab === 'profile' ? tabStyles.active : tabStyles.default}@@ -1074,6 +1082,11 @@ function FinxeptTerminalContent() {<AlphaArenaTab /></React.Suspense></TabsContent>+ <TabsContent value="ma-analytics" className="h-full m-0 p-0">+ <React.Suspense fallback={<TabLoadingFallback />}>+ <MAAnalyticsTab />+ </React.Suspense>+ </TabsContent></Tabs>)}</div>diff --git a/fincept-terminal-desktop/src/components/tabs/MAAnalyticsTab.tsx b/fincept-terminal-desktop/src/components/tabs/MAAnalyticsTab.tsxnew file mode 100644index 000000000..c8ac0de6d--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/MAAnalyticsTab.tsx@@ -0,0 +1,8 @@+/**+ * MAAnalyticsTab - Re-export from modularized folder+ *+ * Complete M&A and Financial Advisory System+ * Bloomberg FA Replacement+ */++export { default } from './ma-analytics/MAAnalyticsTab';diff --git a/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx b/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsxindex d0d4221b0..f1b9b310c 100644--- a/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx@@ -12,6 +12,7 @@ import { brokerMCPBridge } from '@/services/mcp/internal/BrokerMCPBridge';import { notesMCPBridge } from '@/services/mcp/internal/NotesMCPBridge';import MarkdownRenderer from '@/components/common/MarkdownRenderer';import ContextSelector from '@/components/common/ContextSelector';+import FinancialSparklines from './FinancialSparklines';// Fincept Terminal Design System Colorsconst FINCEPT = {@@ -61,14 +62,18 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTabconst [statistics, setStatistics] = useState({ totalSessions: 0, totalMessages: 0, totalTokens: 0 });const [mcpToolsCount, setMcpToolsCount] = useState(0);const [linkedContexts, setLinkedContexts] = useState<RecordedContext[]>([]);+ const [activeToolCalls, setActiveToolCalls] = useState<Array<{ name: string; args: any; status: 'calling' | 'success' | 'error' }>>([]);+ const [pendingChartData, setPendingChartData] = useState<any>(null);// LLM Configuration stateconst [activeLLMConfig, setActiveLLMConfig] = useState<LLMConfig | null>(null);+ const [allLLMConfigs, setAllLLMConfigs] = useState<LLMConfig[]>([]);const [llmGlobalSettings, setLLMGlobalSettings] = useState<LLMGlobalSettings>({temperature: 0.7,max_tokens: 4096,system_prompt: ''});+ const [showLLMSelector, setShowLLMSelector] = useState(false);const handleContextsChange = (contexts: RecordedContext[]) => {setLinkedContexts(contexts);@@ -83,6 +88,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTabconst sessionsListRef = useRef<HTMLDivElement>(null);const streamedContentRef = useRef<string>(''); // Track accumulated streaming contentconst retryTimeoutsRef = useRef<Set<NodeJS.Timeout>>(new Set()); // Track pending retry timeouts+ const llmSelectorRef = useRef<HTMLDivElement>(null);// Check if current provider supports MCP toolsconst providerSupportsMCP = () => {@@ -179,6 +185,23 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTabscrollToBottom();}, [messages, streamingContent]);+ // Click outside to close LLM selector+ useEffect(() => {+ const handleClickOutside = (event: MouseEvent) => {+ if (llmSelectorRef.current && !llmSelectorRef.current.contains(event.target as Node)) {+ setShowLLMSelector(false);+ }+ };++ if (showLLMSelector) {+ document.addEventListener('mousedown', handleClickOutside);+ }++ return () => {+ document.removeEventListener('mousedown', handleClickOutside);+ };+ }, [showLLMSelector]);+const scrollToBottom = () => {messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });};@@ -211,12 +234,14 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTabconst loadLLMConfiguration = async () => {try {- const [activeConfig, globalSettings] = await Promise.all([+ const [activeConfig, globalSettings, allConfigs] = await Promise.all([sqliteService.getActiveLLMConfig(),- sqliteService.getLLMGlobalSettings()+ sqliteService.getLLMGlobalSettings(),+ sqliteService.getLLMConfigs()]);setActiveLLMConfig(activeConfig);+ setAllLLMConfigs(allConfigs);setLLMGlobalSettings(globalSettings);if (!activeConfig) {@@ -228,6 +253,20 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab}};+ const switchLLMProvider = async (provider: string) => {+ try {+ setSystemStatus('STATUS: SWITCHING LLM PROVIDER...');+ await sqliteService.setActiveLLMProvider(provider);+ await loadLLMConfiguration();+ setShowLLMSelector(false);+ setSystemStatus('STATUS: READY');+ console.log(`[ChatTab] Switched to LLM provider: ${provider}`);+ } catch (error) {+ console.error('[ChatTab] Failed to switch LLM provider:', error);+ setSystemStatus('ERROR: Failed to switch provider');+ }+ };+const loadMCPToolsCount = async (retryCount = 0, maxRetries = MCP_MAX_RETRIES) => {try {const { mcpToolService } = await import('@/services/mcp/mcpToolService');@@ -501,15 +540,34 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTabconst handleToolCallback = (toolName: string, args: any, result?: any) => {if (!result) {+ // Tool call startedconsole.log(`[Tool Call] ${toolName}`, args);- setSystemStatus('STATUS: Fetching data...');+ setSystemStatus(`STATUS: Calling ${toolName}...`);+ setActiveToolCalls(prev => [...prev, { name: toolName, args, status: 'calling' }]);} else {+ // Tool call completedconsole.log(`[Tool Result] ${toolName}`, result);setSystemStatus('STATUS: Processing response...');+ setActiveToolCalls(prev =>+ prev.map(call =>+ call.name === toolName && call.status === 'calling'+ ? { ...call, status: result.error ? 'error' : 'success' }+ : call+ )+ );++ // Store chart data for financial tools+ if (result.chart_data) {+ console.log('[ChatTab] Chart data received:', result.chart_data);+ setPendingChartData({+ data: result.chart_data,+ ticker: result.ticker,+ company: result.company+ });+ }// Check if a report was created and schedule navigation after completionif (toolName === 'create_report_template' && result?.id) {- // Store the flag to navigate after response is complete(window as any).__navigateToReportBuilder = true;}}@@ -518,16 +576,28 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTabconst saveAssistantMessage = async (sessionUuid: string, content: string, usage?: any): Promise<void> => {if (!activeLLMConfig) return;+ // Save message with chart data if available+ const chartData = pendingChartData;+const aiMessage = await sqliteService.addChatMessage({session_uuid: sessionUuid,role: 'assistant',content,provider: activeLLMConfig.provider,model: activeLLMConfig.model,- tokens_used: usage?.totalTokens+ tokens_used: usage?.totalTokens,+ tool_calls: activeToolCalls.length > 0 ? activeToolCalls.map(call => ({+ name: call.name,+ args: call.args,+ timestamp: new Date().toISOString(),+ status: call.status+ })) : undefined,+ metadata: chartData ? { chart_data: chartData.data, ticker: chartData.ticker, company: chartData.company } : undefined});setMessages(prev => [...prev, aiMessage]);+ setActiveToolCalls([]);+ setPendingChartData(null);};const saveErrorMessage = async (sessionUuid: string, error: string): Promise<void> => {@@ -813,8 +883,68 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab</span>)}</div>+ {/* Tool calls indicator - like Perplexity sources */}+ {message.tool_calls && message.tool_calls.length > 0 && (+ <div style={{+ marginBottom: '12px',+ padding: '8px 12px',+ background: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ display: 'flex',+ flexWrap: 'wrap',+ gap: '6px',+ alignItems: 'center'+ }}>+ <span style={{+ color: FINCEPT.GRAY,+ fontSize: '9px',+ letterSpacing: '0.5px',+ textTransform: 'uppercase'+ }}>+ Tools Used:+ </span>+ {message.tool_calls.map((tool, idx) => (+ <div+ key={idx}+ style={{+ padding: '4px 8px',+ background: tool.status === 'success' ? FINCEPT.GREEN + '20' :+ tool.status === 'error' ? FINCEPT.RED + '20' : FINCEPT.ORANGE + '20',+ border: `1px solid ${tool.status === 'success' ? FINCEPT.GREEN :+ tool.status === 'error' ? FINCEPT.RED : FINCEPT.ORANGE}`,+ borderRadius: '3px',+ fontSize: '9px',+ color: tool.status === 'success' ? FINCEPT.GREEN :+ tool.status === 'error' ? FINCEPT.RED : FINCEPT.ORANGE,+ letterSpacing: '0.5px',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <span style={{ fontSize: '8px' }}>+ {tool.status === 'success' ? '✓' : tool.status === 'error' ? '✗' : '⋯'}+ </span>+ {tool.name.replace('edgar_', '').replace(/_/g, ' ')}+ </div>+ ))}+ </div>+ )}+{message.role === 'assistant' && message.content ? (- <MarkdownRenderer content={message.content} />+ <>+ <MarkdownRenderer content={message.content} />+ {message.metadata?.chart_data && (+ <FinancialSparklines+ data={message.metadata.chart_data}+ ticker={message.metadata.ticker}+ company={message.metadata.company}+ responseText={message.content}+ />+ )}+ </>) : (<div style={{color: FINCEPT.WHITE,@@ -846,7 +976,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab};const renderStreamingMessage = () => {- if (!streamingContent) return null;+ if (!streamingContent && activeToolCalls.length === 0) return null;return (<div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'flex-start' }}>@@ -865,29 +995,97 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTabpaddingBottom: '6px',borderBottom: `1px solid ${FINCEPT.BORDER}`}}>- <Bot size={12} color={FINCEPT.ORANGE} />+ <Bot+ size={12}+ color={FINCEPT.ORANGE}+ style={{ animation: 'spin 2s linear infinite' }}+ /><span style={{color: FINCEPT.ORANGE,fontSize: '9px',fontWeight: 700,- letterSpacing: '0.5px'+ letterSpacing: '0.5px',+ animation: 'fadeInOut 1.5s ease-in-out infinite'}}>{t('messages.typing').toUpperCase()}</span>- </div>- <div style={{- color: FINCEPT.WHITE,- fontSize: '11px',- lineHeight: '1.6',- whiteSpace: 'pre-wrap',- fontFamily: '"IBM Plex Mono", "Consolas", monospace'- }}>- {streamingContent}<span style={{color: FINCEPT.ORANGE,- animation: 'blink 1s infinite'- }}>▊</span>+ fontSize: '9px',+ animation: 'dots 1.5s steps(4, end) infinite'+ }}>+ <span>.</span>+ <span>.</span>+ <span>.</span>+ </span></div>++ {/* Live tool calls - Perplexity-style */}+ {activeToolCalls.length > 0 && (+ <div style={{+ marginBottom: streamingContent ? '12px' : '0',+ padding: '8px 12px',+ background: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ display: 'flex',+ flexWrap: 'wrap',+ gap: '6px',+ alignItems: 'center'+ }}>+ <span style={{+ color: FINCEPT.GRAY,+ fontSize: '9px',+ letterSpacing: '0.5px',+ textTransform: 'uppercase'+ }}>+ Calling:+ </span>+ {activeToolCalls.map((tool, idx) => (+ <div+ key={idx}+ style={{+ padding: '4px 8px',+ background: tool.status === 'success' ? FINCEPT.GREEN + '20' :+ tool.status === 'error' ? FINCEPT.RED + '20' : FINCEPT.ORANGE + '20',+ border: `1px solid ${tool.status === 'success' ? FINCEPT.GREEN :+ tool.status === 'error' ? FINCEPT.RED : FINCEPT.ORANGE}`,+ borderRadius: '3px',+ fontSize: '9px',+ color: tool.status === 'success' ? FINCEPT.GREEN :+ tool.status === 'error' ? FINCEPT.RED : FINCEPT.ORANGE,+ letterSpacing: '0.5px',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ animation: tool.status === 'calling' ? 'pulse 1.5s infinite' : 'none'+ }}+ >+ <span style={{ fontSize: '8px' }}>+ {tool.status === 'success' ? '✓' : tool.status === 'error' ? '✗' : '⋯'}+ </span>+ {tool.name.replace('edgar_', '').replace('stock_', '').replace(/_/g, ' ')}+ </div>+ ))}+ </div>+ )}++ {streamingContent && (+ <div style={{+ color: FINCEPT.WHITE,+ fontSize: '11px',+ lineHeight: '1.6',+ whiteSpace: 'pre-wrap',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'+ }}>+ {streamingContent}+ <span style={{+ color: FINCEPT.ORANGE,+ animation: 'blink 1s infinite'+ }}>▊</span>+ </div>+ )}</div></div>);@@ -933,6 +1131,23 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab0%, 50% { opacity: 1; }51%, 100% { opacity: 0; }}+ @keyframes pulse {+ 0%, 100% { opacity: 0.6; transform: scale(1); }+ 50% { opacity: 1; transform: scale(1.02); }+ }+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ @keyframes fadeInOut {+ 0%, 100% { opacity: 0.5; }+ 50% { opacity: 1; }+ }+ @keyframes dots {+ 0%, 20% { content: '.'; }+ 40% { content: '..'; }+ 60%, 100% { content: '...'; }+ }`}</style>{/* Top Navigation Bar */}<div style={{@@ -955,14 +1170,136 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab{t('title').toUpperCase()}</span><span style={{ color: FINCEPT.GRAY }}>|</span>- <span style={{- color: FINCEPT.YELLOW,- fontSize: '9px',- fontWeight: 700,- letterSpacing: '0.5px'- }}>- {activeLLMConfig?.provider.toUpperCase() || 'NO PROVIDER'}- </span>++ {/* LLM Provider Selector */}+ <div ref={llmSelectorRef} style={{ position: 'relative' }}>+ <button+ onClick={() => setShowLLMSelector(!showLLMSelector)}+ style={{+ backgroundColor: `${FINCEPT.YELLOW}20`,+ border: `1px solid ${FINCEPT.YELLOW}40`,+ color: FINCEPT.YELLOW,+ padding: '4px 10px',+ fontSize: '9px',+ fontWeight: 700,+ borderRadius: '2px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ letterSpacing: '0.5px',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = `${FINCEPT.YELLOW}30`;+ e.currentTarget.style.borderColor = FINCEPT.YELLOW;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = `${FINCEPT.YELLOW}20`;+ e.currentTarget.style.borderColor = `${FINCEPT.YELLOW}40`;+ }}+ title="Switch LLM Provider"+ >+ <Bot size={10} />+ {activeLLMConfig?.provider.toUpperCase() || 'NO PROVIDER'}+ <span style={{ fontSize: '7px' }}>▼</span>+ </button>++ {/* Dropdown Menu */}+ {showLLMSelector && (+ <div style={{+ position: 'absolute',+ top: '100%',+ left: 0,+ marginTop: '4px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.ORANGE}`,+ borderRadius: '2px',+ padding: '4px',+ minWidth: '220px',+ maxHeight: '400px',+ overflowY: 'auto',+ zIndex: 1000,+ boxShadow: `0 4px 12px ${FINCEPT.DARK_BG}80`+ }}>+ <div style={{+ padding: '6px 8px',+ fontSize: '8px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ letterSpacing: '0.5px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ marginBottom: '4px'+ }}>+ SELECT LLM PROVIDER+ </div>+ {allLLMConfigs.length > 0 ? (+ allLLMConfigs.map((config) => (+ <button+ key={config.provider}+ onClick={() => switchLLMProvider(config.provider)}+ style={{+ width: '100%',+ backgroundColor: activeLLMConfig?.provider === config.provider ? `${FINCEPT.ORANGE}20` : 'transparent',+ border: activeLLMConfig?.provider === config.provider ? `1px solid ${FINCEPT.ORANGE}` : `1px solid ${FINCEPT.BORDER}`,+ color: activeLLMConfig?.provider === config.provider ? FINCEPT.ORANGE : FINCEPT.WHITE,+ padding: '8px',+ fontSize: '9px',+ fontWeight: 600,+ borderRadius: '2px',+ cursor: 'pointer',+ textAlign: 'left',+ marginBottom: '2px',+ display: 'flex',+ flexDirection: 'column',+ gap: '4px',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ if (activeLLMConfig?.provider !== config.provider) {+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;+ e.currentTarget.style.borderColor = FINCEPT.MUTED;+ }+ }}+ onMouseLeave={(e) => {+ if (activeLLMConfig?.provider !== config.provider) {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.borderColor = FINCEPT.BORDER;+ }+ }}+ >+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <span style={{ fontWeight: 700, letterSpacing: '0.3px' }}>+ {config.provider.toUpperCase()}+ </span>+ {activeLLMConfig?.provider === config.provider && (+ <span style={{ color: FINCEPT.GREEN, fontSize: '8px' }}>● ACTIVE</span>+ )}+ </div>+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY }}>+ Model: {config.model || 'N/A'}+ </div>+ {config.base_url && (+ <div style={{ fontSize: '7px', color: FINCEPT.MUTED }}>+ {config.base_url}+ </div>+ )}+ </button>+ ))+ ) : (+ <div style={{+ padding: '12px',+ textAlign: 'center',+ fontSize: '9px',+ color: FINCEPT.MUTED+ }}>+ No LLM providers configured. Go to Settings to add one.+ </div>+ )}+ </div>+ )}+ </div>+<span style={{ color: FINCEPT.GRAY }}>|</span><span style={{color: FINCEPT.WHITE,diff --git a/fincept-terminal-desktop/src/components/tabs/chat/FinancialSparklines.tsx b/fincept-terminal-desktop/src/components/tabs/chat/FinancialSparklines.tsxnew file mode 100644index 000000000..8bd1d6ac2--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/chat/FinancialSparklines.tsx@@ -0,0 +1,229 @@+import React, { useMemo } from 'react';++interface DataPoint {+ period: string;+ value: number;+}++interface ChartData {+ revenue?: DataPoint[];+ net_income?: DataPoint[];+ total_assets?: DataPoint[];+ total_equity?: DataPoint[];+ growth?: {+ revenue_yoy?: number;+ net_income_yoy?: number;+ total_assets_yoy?: number;+ total_equity_yoy?: number;+ };+}++interface FinancialSparklinesProps {+ data: ChartData;+ ticker?: string;+ company?: string;+ responseText?: string;+}++// Keywords to match in response text+const METRIC_KEYWORDS: Record<string, string[]> = {+ revenue: ['revenue', 'sales', 'top line', 'total revenue'],+ net_income: ['net income', 'profit', 'earnings', 'bottom line', 'net profit'],+ total_assets: ['assets', 'total assets'],+ total_equity: ['equity', 'shareholders equity', 'book value'],+};++// Format large numbers+const formatValue = (value: number): string => {+ if (value >= 1000) return `$${(value / 1000).toFixed(1)}B`;+ if (value >= 1) return `$${value.toFixed(1)}M`;+ return `$${(value * 1000).toFixed(0)}K`;+};++// Simple SVG sparkline+const Sparkline: React.FC<{ values: number[]; color: string; width?: number; height?: number }> = ({+ values,+ color,+ width = 60,+ height = 24+}) => {+ if (values.length < 2) return null;++ const min = Math.min(...values);+ const max = Math.max(...values);+ const range = max - min || 1;++ const points = values.map((v, i) => {+ const x = (i / (values.length - 1)) * width;+ const y = height - ((v - min) / range) * (height - 4) - 2;+ return `${x},${y}`;+ }).join(' ');++ return (+ <svg width={width} height={height} style={{ display: 'block' }}>+ <polyline+ points={points}+ fill="none"+ stroke={color}+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ {/* End dot */}+ <circle+ cx={(values.length - 1) / (values.length - 1) * width}+ cy={height - ((values[values.length - 1] - min) / range) * (height - 4) - 2}+ r="3"+ fill={color}+ />+ </svg>+ );+};++// Single metric row+const MetricRow: React.FC<{+ label: string;+ values: DataPoint[];+ growth?: number;+ color: string;+}> = ({ label, values, growth, color }) => {+ const sortedValues = [...values].sort((a, b) => a.period.localeCompare(b.period));+ const numericValues = sortedValues.map(v => v.value);+ const latest = sortedValues[sortedValues.length - 1];+ const oldest = sortedValues[0];++ return (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ padding: '6px 10px',+ background: 'rgba(255,255,255,0.03)',+ borderRadius: '4px',+ borderLeft: `3px solid ${color}`,+ }}>+ <div style={{ minWidth: '80px' }}>+ <div style={{ fontSize: '10px', color: '#888', textTransform: 'uppercase', letterSpacing: '0.5px' }}>+ {label}+ </div>+ <div style={{ fontSize: '13px', color: '#fff', fontWeight: 600 }}>+ {formatValue(latest.value)}+ </div>+ </div>++ <Sparkline values={numericValues} color={color} />++ <div style={{ fontSize: '10px', color: '#666', minWidth: '70px' }}>+ {formatValue(oldest.value)} → {formatValue(latest.value)}+ </div>++ {growth !== undefined && (+ <div style={{+ fontSize: '11px',+ fontWeight: 600,+ color: growth >= 0 ? '#00D66F' : '#FF3B3B',+ minWidth: '50px',+ textAlign: 'right'+ }}>+ {growth >= 0 ? '+' : ''}{growth.toFixed(1)}%+ </div>+ )}+ </div>+ );+};++const FinancialSparklines: React.FC<FinancialSparklinesProps> = ({+ data,+ ticker,+ company,+ responseText = ''+}) => {+ // Determine which metrics to show based on response text+ const metricsToShow = useMemo(() => {+ const text = responseText.toLowerCase();+ const metrics: Array<{ key: keyof ChartData; label: string; color: string }> = [];++ // Check each metric type+ if (data.revenue?.length) {+ const hasKeyword = METRIC_KEYWORDS.revenue.some(kw => text.includes(kw));+ if (hasKeyword || !responseText) {+ metrics.push({ key: 'revenue', label: 'Revenue', color: '#3b82f6' });+ }+ }++ if (data.net_income?.length) {+ const hasKeyword = METRIC_KEYWORDS.net_income.some(kw => text.includes(kw));+ if (hasKeyword || !responseText) {+ metrics.push({ key: 'net_income', label: 'Net Income', color: '#10b981' });+ }+ }++ if (data.total_assets?.length) {+ const hasKeyword = METRIC_KEYWORDS.total_assets.some(kw => text.includes(kw));+ if (hasKeyword) {+ metrics.push({ key: 'total_assets', label: 'Assets', color: '#f59e0b' });+ }+ }++ if (data.total_equity?.length) {+ const hasKeyword = METRIC_KEYWORDS.total_equity.some(kw => text.includes(kw));+ if (hasKeyword) {+ metrics.push({ key: 'total_equity', label: 'Equity', color: '#8b5cf6' });+ }+ }++ // If no keywords matched but we have data, show revenue and net_income by default+ if (metrics.length === 0) {+ if (data.revenue?.length) metrics.push({ key: 'revenue', label: 'Revenue', color: '#3b82f6' });+ if (data.net_income?.length) metrics.push({ key: 'net_income', label: 'Net Income', color: '#10b981' });+ }++ return metrics;+ }, [data, responseText]);++ if (metricsToShow.length === 0) return null;++ return (+ <div style={{+ marginTop: '12px',+ padding: '10px',+ background: 'rgba(0,0,0,0.3)',+ borderRadius: '6px',+ border: '1px solid rgba(255,255,255,0.1)',+ }}>+ {(ticker || company) && (+ <div style={{+ fontSize: '10px',+ color: '#666',+ marginBottom: '8px',+ textTransform: 'uppercase',+ letterSpacing: '0.5px'+ }}>+ {company || ticker} • Financial Trends+ </div>+ )}++ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>+ {metricsToShow.map(metric => {+ const values = data[metric.key] as DataPoint[] | undefined;+ if (!values?.length) return null;++ const growthKey = `${metric.key}_yoy` as keyof NonNullable<ChartData['growth']>;+ const growth = data.growth?.[growthKey];++ return (+ <MetricRow+ key={metric.key}+ label={metric.label}+ values={values}+ growth={growth}+ color={metric.color}+ />+ );+ })}+ </div>+ </div>+ );+};++export default FinancialSparklines;diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsxindex 303263875..a507df40e 100644--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsx+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsx@@ -169,71 +169,70 @@ export function CryptoTopNav({<div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />- {/* Trading Mode Toggle */}+ {/* Trading Mode Toggle - Matches Equity Tab Style */}<div style={{display: 'flex',alignItems: 'center',- gap: '8px',- padding: '4px 12px',- backgroundColor: tradingMode === 'live' ? `${FINCEPT.RED}20` : `${FINCEPT.GREEN}20`,- border: `2px solid ${tradingMode === 'live' ? FINCEPT.RED : FINCEPT.GREEN}`,- borderRadius: '4px'+ gap: '2px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ padding: '2px',}}>- {/* Mode Indicator */}- <div style={{- display: 'flex',- alignItems: 'center',- gap: '6px'- }}>- <div style={{- width: '8px',- height: '8px',- borderRadius: '50%',- backgroundColor: tradingMode === 'live' ? FINCEPT.RED : FINCEPT.GREEN,- boxShadow: `0 0 8px ${tradingMode === 'live' ? FINCEPT.RED : FINCEPT.GREEN}`,- animation: tradingMode === 'live' ? 'pulse 1s infinite' : 'none'- }} />- <span style={{- fontSize: '11px',- fontWeight: 700,- color: tradingMode === 'live' ? FINCEPT.RED : FINCEPT.GREEN,- letterSpacing: '1px'- }}>- {tradingMode === 'live' ? '🔴 LIVE' : '⚪ PAPER'}- </span>- </div>-- <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />-<buttononClick={() => onTradingModeChange('paper')}style={{- padding: '4px 10px',- backgroundColor: tradingMode === 'paper' ? FINCEPT.GREEN : FINCEPT.PANEL_BG,- border: `1px solid ${tradingMode === 'paper' ? FINCEPT.GREEN : FINCEPT.BORDER}`,+ padding: '6px 14px',+ backgroundColor: tradingMode === 'paper' ? FINCEPT.GREEN : 'transparent',+ border: 'none',color: tradingMode === 'paper' ? FINCEPT.DARK_BG : FINCEPT.GRAY,cursor: 'pointer',fontSize: '10px',fontWeight: 700,- transition: 'all 0.2s'+ letterSpacing: '0.5px',+ transition: 'all 0.2s',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',}}>- {t('header.paper')}+ {tradingMode === 'paper' && (+ <div style={{+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ backgroundColor: FINCEPT.DARK_BG,+ }} />+ )}+ PAPER</button><buttononClick={handleLiveModeClick}style={{- padding: '4px 10px',- backgroundColor: tradingMode === 'live' ? FINCEPT.RED : FINCEPT.PANEL_BG,- border: `1px solid ${tradingMode === 'live' ? FINCEPT.RED : FINCEPT.BORDER}`,+ padding: '6px 14px',+ backgroundColor: tradingMode === 'live' ? FINCEPT.RED : 'transparent',+ border: 'none',color: tradingMode === 'live' ? FINCEPT.WHITE : FINCEPT.GRAY,cursor: 'pointer',fontSize: '10px',fontWeight: 700,- transition: 'all 0.2s'+ letterSpacing: '0.5px',+ transition: 'all 0.2s',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',}}>- {t('header.live')}+ {tradingMode === 'live' && (+ <div style={{+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ backgroundColor: FINCEPT.WHITE,+ boxShadow: `0 0 6px ${FINCEPT.WHITE}`,+ animation: 'pulse 1s infinite',+ }} />+ )}+ LIVE</button></div></div>diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsxindex bfee7180a..41644b81b 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsx@@ -30,7 +30,7 @@ import {} from './components';import type { SymbolSearchResult, SupportedBroker } from '@/services/trading/masterContractService';-import type { StockExchange, Quote, MarketDepth } from '@/brokers/stocks/types';+import type { StockExchange, Quote, MarketDepth, TimeFrame } from '@/brokers/stocks/types';import { GridTradingPanel } from '../trading/grid-trading';// Market hours and caching utilities@@ -207,6 +207,19 @@ function EquityTradingContent() {const [isBottomPanelMinimized, setIsBottomPanelMinimized] = useState(false);const [showSettings, setShowSettings] = useState(false);+ // Chart timeframe - default to 5m for real brokers, 1d for yfinance+ const [chartInterval, setChartInterval] = useState<TimeFrame>('5m');++ // Set correct chart interval when broker changes or on initial load+ // yfinance only supports daily data, real brokers default to 5m intraday+ useEffect(() => {+ if (activeBroker) {+ const defaultInterval = activeBroker === 'yfinance' ? '1d' : '5m';+ setChartInterval(defaultInterval);+ console.log(`[EquityTrading] Setting chart interval to ${defaultInterval} for broker ${activeBroker}`);+ }+ }, [activeBroker]);+// Filter trades for the selected symbol (memoized)const symbolTrades = useMemo(() => {if (!selectedSymbol || !trades || trades.length === 0) return [];@@ -280,6 +293,7 @@ function EquityTradingContent() {if (brokerChanged) {setQuote(null);setMarketDepth(null);+ // Note: chart interval is now handled by dedicated useEffect on activeBroker change}}@@ -1467,7 +1481,8 @@ function EquityTradingContent() {<StockTradingChartsymbol={selectedSymbol}exchange={selectedExchange}- interval={activeBroker === 'yfinance' ? '1d' : '5m'}+ interval={chartInterval}+ onIntervalChange={setChartInterval}liveQuote={quote ? {lastPrice: quote.lastPrice,change: quote.change || 0,@@ -1855,9 +1870,9 @@ function EquityTradingContent() {<table style={{ width: '100%', fontSize: '10px' }}><thead><tr style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>- <th style={{ padding: '4px', textAlign: 'left', color: FINCEPT.GRAY }}>QTY</th>+ <th style={{ padding: '4px', textAlign: 'left', color: FINCEPT.GRAY }}>ORDERS</th>+ <th style={{ padding: '4px', textAlign: 'center', color: FINCEPT.GRAY }}>QTY</th><th style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GRAY }}>PRICE</th>- <th style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GRAY }}>ORDERS</th></tr></thead><tbody>@@ -1866,15 +1881,15 @@ function EquityTradingContent() {: [null, null, null, null, null]).map((bid, i) => (<tr key={i} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}40` }}>- <td style={{ padding: '4px', color: FINCEPT.WHITE }}>+ <td style={{ padding: '4px', color: FINCEPT.GRAY }}>+ {bid?.orders ?? '--'}+ </td>+ <td style={{ padding: '4px', textAlign: 'center', color: FINCEPT.WHITE }}>{bid?.quantity ? bid.quantity.toLocaleString('en-IN') : '--'}</td><td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GREEN }}>{bid?.price ? fmtPrice(bid.price) : '--'}</td>- <td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GRAY }}>- {bid?.orders || '--'}- </td></tr>))}</tbody>@@ -1904,7 +1919,7 @@ function EquityTradingContent() {<thead><tr style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}><th style={{ padding: '4px', textAlign: 'left', color: FINCEPT.GRAY }}>PRICE</th>- <th style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GRAY }}>QTY</th>+ <th style={{ padding: '4px', textAlign: 'center', color: FINCEPT.GRAY }}>QTY</th><th style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GRAY }}>ORDERS</th></tr></thead>@@ -1917,11 +1932,11 @@ function EquityTradingContent() {<td style={{ padding: '4px', color: FINCEPT.RED }}>{ask?.price ? fmtPrice(ask.price) : '--'}</td>- <td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.WHITE }}>+ <td style={{ padding: '4px', textAlign: 'center', color: FINCEPT.WHITE }}>{ask?.quantity ? ask.quantity.toLocaleString('en-IN') : '--'}</td><td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GRAY }}>- {ask?.orders || '--'}+ {ask?.orders ?? '--'}</td></tr>))}diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsxindex fce4fe1bc..2fa56b6da 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx@@ -30,6 +30,7 @@ interface StockTradingChartProps {height?: number;timezone?: string; // e.g., 'Asia/Kolkata' for ISTliveQuote?: LiveQuote; // Live quote data from parent for consistent display+ onIntervalChange?: (interval: TimeFrame) => void; // Callback when user changes timeframe}// Available timeframes@@ -47,18 +48,19 @@ const TIMEFRAMES: { value: TimeFrame; label: string }[] = [];// Helper to convert TimeFrame to days for historical data range+// Optimized for AngelOne API rate limits and chart performanceconst timeframeToDays = (tf: TimeFrame): number => {switch (tf) {- case '1m': return 7; // 1 min -> 7 days- case '3m': return 7; // 3 min -> 7 days- case '5m': return 14; // 5 min -> 14 days- case '10m': return 14; // 10 min -> 14 days- case '15m': return 30; // 15 min -> 30 days- case '30m': return 30; // 30 min -> 30 days- case '1h': return 60; // 1 hour -> 60 days- case '2h': return 90; // 2 hours -> 90 days (3 months)+ case '1m': return 2; // 1 min -> 2 days (avoid rate limits)+ case '3m': return 3; // 3 min -> 3 days+ case '5m': return 5; // 5 min -> 5 days (reasonable for 5m chart)+ case '10m': return 7; // 10 min -> 7 days+ case '15m': return 10; // 15 min -> 10 days (reduced from 30 to avoid rate limits)+ case '30m': return 15; // 30 min -> 15 days (reduced from 30)+ case '1h': return 30; // 1 hour -> 30 days (reduced from 60)+ case '2h': return 60; // 2 hours -> 60 days (reduced from 90)case '4h': return 90; // 4 hours -> 90 days (3 months)- case '1d': return 90; // 1 day -> 90 days (3 months) - default for paper trading+ case '1d': return 180; // 1 day -> 180 days (6 months)case '1w': return 365; // 1 week -> 1 yearcase '1M': return 1825; // 1 month -> 5 yearsdefault: return 90; // Default to 3 months@@ -89,10 +91,11 @@ const EXCHANGE_TIMEZONES: Record<string, string> = {export function StockTradingChart({symbol,exchange,- interval: initialInterval = '1d',+ interval: initialInterval = '5m',height,timezone: propTimezone,- liveQuote+ liveQuote,+ onIntervalChange}: StockTradingChartProps) {// Auto-detect timezone based on exchange if not providedconst timezone = propTimezone || EXCHANGE_TIMEZONES[exchange] || EXCHANGE_TIMEZONES.DEFAULT;@@ -112,11 +115,15 @@ export function StockTradingChart({// Sync selectedInterval when initialInterval prop changes (e.g., broker switch)useEffect(() => {+ console.log(`[StockTradingChart] Syncing interval from prop: ${initialInterval}`);setSelectedInterval(initialInterval);}, [initialInterval]);- // Fetch historical data- const fetchHistoricalData = useCallback(async () => {+ // Fetch historical data with retry for race condition handling+ const fetchHistoricalData = useCallback(async (retryCount = 0) => {+ const MAX_RETRIES = 5;+ const RETRY_DELAY = 800; // ms+if (!symbol || !exchange) {console.log('[StockTradingChart] No symbol or exchange selected');setError('Please select a symbol');@@ -125,11 +132,53 @@ export function StockTradingChart({}if (!adapter || !isAuthenticated) {+ if (retryCount < MAX_RETRIES) {+ console.log(`[StockTradingChart] Adapter or auth not ready, retry ${retryCount + 1}/${MAX_RETRIES} in ${RETRY_DELAY}ms...`);+ setTimeout(() => fetchHistoricalData(retryCount + 1), RETRY_DELAY);+ return;+ }setError('Please authenticate with your broker to view charts');setIsLoading(false);return;}+ // Check if adapter is actually connected (internal state)+ // This handles the race condition where isAuthenticated is true but adapter._isConnected is not yet+ if (!adapter.isConnected) {+ if (retryCount < MAX_RETRIES) {+ console.log(`[StockTradingChart] Adapter not connected yet, retry ${retryCount + 1}/${MAX_RETRIES} in ${RETRY_DELAY}ms...`);+ setTimeout(() => fetchHistoricalData(retryCount + 1), RETRY_DELAY);+ return;+ }+ console.warn('[StockTradingChart] Adapter still not connected after retries');+ setError('Broker connection not ready. Please try again.');+ setIsLoading(false);+ return;+ }++ // Check if master contract/instrument lookup is ready (for brokers that need it)+ // This prevents fetching with token='0' which returns empty data+ if (typeof adapter.getInstrument === 'function') {+ try {+ const instrument = await adapter.getInstrument(symbol, exchange);+ if (!instrument || !instrument.token || instrument.token === '0') {+ if (retryCount < MAX_RETRIES) {+ console.log(`[StockTradingChart] Instrument token not ready for ${symbol}, retry ${retryCount + 1}/${MAX_RETRIES} in ${RETRY_DELAY}ms...`);+ setTimeout(() => fetchHistoricalData(retryCount + 1), RETRY_DELAY);+ return;+ }+ console.warn('[StockTradingChart] Instrument token still not available after retries');+ setError('Symbol data not ready. Please ensure master contract is downloaded.');+ setIsLoading(false);+ return;+ }+ console.log(`[StockTradingChart] Instrument token ready: ${symbol} -> ${instrument.token}`);+ } catch (err) {+ console.warn('[StockTradingChart] getInstrument check failed:', err);+ // Continue anyway - some brokers may not need this+ }+ }+try {setIsLoading(true);setError(null);@@ -144,18 +193,20 @@ export function StockTradingChart({console.log(`[StockTradingChart] Date range: ${from.toISOString()} to ${to.toISOString()}`);// Fetch OHLCV data from stock broker adapter (Fyers, Zerodha, etc.)- const ohlcvData: OHLCV[] = await adapter.getOHLCV(- symbol,- exchange,- selectedInterval,- from,- to+ // Use a timeout to prevent infinite loading+ const fetchTimeout = new Promise<OHLCV[]>((_, reject) =>+ setTimeout(() => reject(new Error('Data fetch timeout - broker may be rate limited')), 60000) // 60 second timeout);+ const ohlcvData: OHLCV[] = await Promise.race([+ adapter.getOHLCV(symbol, exchange, selectedInterval, from, to),+ fetchTimeout+ ]);+console.log(`[StockTradingChart] Fetched ${ohlcvData.length} candles from ${adapter.brokerId}`);if (ohlcvData.length === 0) {- setError('No historical data available. Check your API credentials and symbol format.');+ setError('No historical data available. Try a different timeframe or check your connection.');setIsLoading(false);return;}@@ -198,7 +249,15 @@ export function StockTradingChart({setIsLoading(false);} catch (err) {console.error('[StockTradingChart] Failed to fetch historical data:', err);- setError(err instanceof Error ? err.message : 'Failed to load chart data');++ // If we have existing data, keep showing it with a warning+ if (chartData.length > 0) {+ console.warn('[StockTradingChart] Keeping existing chart data visible despite error');+ setError('Failed to update chart. Showing previous data.');+ } else {+ setError(err instanceof Error ? err.message : 'Failed to load chart data. Try again or select a different timeframe.');+ }+setIsLoading(false);}}, [adapter, isAuthenticated, symbol, exchange, selectedInterval]);@@ -332,7 +391,10 @@ export function StockTradingChart({{TIMEFRAMES.map((tf) => (<buttonkey={tf.value}- onClick={() => setSelectedInterval(tf.value)}+ onClick={() => {+ setSelectedInterval(tf.value);+ onIntervalChange?.(tf.value);+ }}disabled={isLoading}className={`px-2 py-0.5 text-[9px] font-medium rounded transition-colors disabled:opacity-50 ${selectedInterval === tf.value@@ -376,6 +438,7 @@ export function StockTradingChart({showToolbar={true}showHeader={false}timezone={timezone}+ interval={selectedInterval}/></div>)}@@ -389,6 +452,23 @@ export function StockTradingChart({</div></div>)}++ {/* Error Notification - non-blocking, appears at bottom */}+ {error && chartData.length > 0 && (+ <div className="absolute bottom-2 left-1/2 -translate-x-1/2 bg-red-900/90 backdrop-blur-sm px-4 py-2 rounded border border-red-700 z-10 max-w-md">+ <div className="flex items-center gap-2">+ <AlertCircle className="w-4 h-4 text-red-400 flex-shrink-0" />+ <span className="text-xs text-red-200">{error}</span>+ <button+ onClick={() => setError(null)}+ className="ml-2 text-red-400 hover:text-red-200 transition-colors"+ title="Dismiss"+ >+ ×+ </button>+ </div>+ </div>+ )}</div></div>);diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/MAAnalyticsTab.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/MAAnalyticsTab.tsxnew file mode 100644index 000000000..9816a5a28--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/MAAnalyticsTab.tsx@@ -0,0 +1,215 @@+/**+ * M&A Analytics Tab - Bloomberg FA Replacement+ *+ * Complete M&A and Financial Advisory System+ * Three-panel terminal layout following Fincept design system+ */++import React, { useState } from 'react';+import {+ Building2,+ TrendingUp,+ Calculator,+ BarChart3,+ Rocket,+ FileText,+ GitMerge,+ Zap,+ Activity,+ Target,+ Database,+} from 'lucide-react';++// Import Fincept styles+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, EFFECTS, COMMON_STYLES } from '../portfolio-tab/finceptStyles';++// Import tab components+import { DealDatabasePanel } from './panels/DealDatabasePanel';+import { ValuationPanel } from './panels/ValuationPanel';+import { MergerModelPanel } from './panels/MergerModelPanel';+import { LBOModelPanel } from './panels/LBOModelPanel';+import { StartupValuationPanel } from './panels/StartupValuationPanel';+import { DealStructurePanel } from './panels/DealStructurePanel';+import { SynergiesPanel } from './panels/SynergiesPanel';+import { FairnessOpinionPanel } from './panels/FairnessOpinionPanel';+import { IndustryMetricsPanel } from './panels/IndustryMetricsPanel';+import { AdvancedAnalyticsPanel } from './panels/AdvancedAnalyticsPanel';++type AnalysisModule =+ | 'deal_database'+ | 'valuation'+ | 'merger_model'+ | 'lbo'+ | 'startup'+ | 'deal_structure'+ | 'synergies'+ | 'fairness'+ | 'industry_metrics'+ | 'advanced';++const MODULES = [+ { id: 'deal_database' as const, label: 'DEAL DATABASE', icon: Database },+ { id: 'valuation' as const, label: 'VALUATION', icon: TrendingUp },+ { id: 'merger_model' as const, label: 'MERGER MODEL', icon: GitMerge },+ { id: 'lbo' as const, label: 'LBO MODEL', icon: Building2 },+ { id: 'startup' as const, label: 'STARTUP', icon: Rocket },+ { id: 'deal_structure' as const, label: 'DEAL STRUCTURE', icon: FileText },+ { id: 'synergies' as const, label: 'SYNERGIES', icon: Zap },+ { id: 'fairness' as const, label: 'FAIRNESS OPINION', icon: Target },+ { id: 'industry_metrics' as const, label: 'INDUSTRY METRICS', icon: BarChart3 },+ { id: 'advanced' as const, label: 'ADVANCED', icon: Activity },+];++const MAAnalyticsTab: React.FC = () => {+ const [activeModule, setActiveModule] = useState<AnalysisModule>('deal_database');+ const [selectedDeal, setSelectedDeal] = useState<any>(null);++ const renderActivePanel = () => {+ switch (activeModule) {+ case 'deal_database':+ return <DealDatabasePanel onSelectDeal={setSelectedDeal} />;+ case 'valuation':+ return <ValuationPanel selectedDeal={selectedDeal} />;+ case 'merger_model':+ return <MergerModelPanel selectedDeal={selectedDeal} />;+ case 'lbo':+ return <LBOModelPanel selectedDeal={selectedDeal} />;+ case 'startup':+ return <StartupValuationPanel />;+ case 'deal_structure':+ return <DealStructurePanel selectedDeal={selectedDeal} />;+ case 'synergies':+ return <SynergiesPanel selectedDeal={selectedDeal} />;+ case 'fairness':+ return <FairnessOpinionPanel selectedDeal={selectedDeal} />;+ case 'industry_metrics':+ return <IndustryMetricsPanel />;+ case 'advanced':+ return <AdvancedAnalyticsPanel selectedDeal={selectedDeal} />;+ default:+ return null;+ }+ };++ return (+ <div+ style={{+ ...COMMON_STYLES.container,+ fontFamily: TYPOGRAPHY.MONO,+ }}+ >+ {/* Top Navigation Bar */}+ <div+ style={{+ ...COMMON_STYLES.header,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ flexWrap: 'wrap',+ gap: SPACING.MEDIUM,+ }}+ >+ {/* Left Section - Title */}+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.MEDIUM }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>+ <Building2 size={16} color={FINCEPT.ORANGE} />+ <span+ style={{+ color: FINCEPT.ORANGE,+ fontWeight: TYPOGRAPHY.BOLD,+ fontSize: TYPOGRAPHY.SUBHEADING,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ }}+ >+ M&A ANALYTICS+ </span>+ </div>++ <div style={COMMON_STYLES.verticalDivider} />++ {/* Module Selector Tabs */}+ <div style={{ display: 'flex', gap: SPACING.TINY }}>+ {MODULES.map((module) => {+ const Icon = module.icon;+ const isActive = activeModule === module.id;+ return (+ <button+ key={module.id}+ onClick={() => setActiveModule(module.id)}+ style={{+ ...COMMON_STYLES.tabButton(isActive),+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ }}+ >+ <Icon size={12} />+ {module.label}+ </button>+ );+ })}+ </div>+ </div>++ {/* Right Section - Actions */}+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>+ <span+ style={{+ fontSize: TYPOGRAPHY.TINY,+ color: FINCEPT.GRAY,+ letterSpacing: TYPOGRAPHY.WIDE,+ }}+ >+ BLOOMBERG FA REPLACEMENT+ </span>+ </div>+ </div>++ {/* Main Content Area */}+ <div+ style={{+ flex: 1,+ overflow: 'hidden',+ display: 'flex',+ flexDirection: 'column',+ }}+ >+ {renderActivePanel()}+ </div>++ {/* Status Bar */}+ <div+ style={{+ backgroundColor: FINCEPT.HEADER_BG,+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ padding: `${SPACING.SMALL} ${SPACING.LARGE}`,+ fontSize: TYPOGRAPHY.TINY,+ color: FINCEPT.GRAY,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}+ >+ <div style={{ display: 'flex', gap: SPACING.LARGE }}>+ <span>+ MODULE: <span style={{ color: FINCEPT.ORANGE }}>{MODULES.find((m) => m.id === activeModule)?.label}</span>+ </span>+ {selectedDeal && (+ <span>+ SELECTED DEAL:{' '}+ <span style={{ color: FINCEPT.CYAN }}>+ {selectedDeal.acquirer_name} + {selectedDeal.target_name}+ </span>+ </span>+ )}+ </div>+ <div>+ <span style={{ color: FINCEPT.MUTED }}>TERMINAL v3.2.1</span>+ </div>+ </div>+ </div>+ );+};++export default MAAnalyticsTab;diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/AdvancedAnalyticsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/AdvancedAnalyticsPanel.tsxnew file mode 100644index 000000000..9ea42fed4--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/AdvancedAnalyticsPanel.tsx@@ -0,0 +1,10 @@+import React from 'react';+import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { Activity } from 'lucide-react';++export const AdvancedAnalyticsPanel: React.FC<{ selectedDeal?: any }> = () => (+ <div style={COMMON_STYLES.emptyState}>+ <Activity size={48} style={{ opacity: 0.3, marginBottom: SPACING.DEFAULT }} />+ <div style={{ fontSize: TYPOGRAPHY.BODY, color: FINCEPT.GRAY }}>AdvancedAnalyticsPanel - Under Construction</div>+ </div>+);diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/DealDatabasePanel.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/DealDatabasePanel.tsxnew file mode 100644index 000000000..2486cf5c5--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/DealDatabasePanel.tsx@@ -0,0 +1,578 @@+/**+ * Deal Database Panel - M&A Deal Tracker & SEC Filing Scanner+ *+ * Three-panel layout:+ * - LEFT: Deal list & search+ * - CENTER: Deal details & financials+ * - RIGHT: SEC filing scanner & actions+ */++import React, { useState, useEffect } from 'react';+import {+ Search,+ RefreshCw,+ Plus,+ FileText,+ TrendingUp,+ DollarSign,+ Calendar,+ Building2,+ Filter,+ Download,+ Eye,+ Database,+} from 'lucide-react';++import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { MAAnalyticsService, type MADeal } from '@/services/maAnalyticsService';++interface DealDatabasePanelProps {+ onSelectDeal: (deal: MADeal | null) => void;+}++export const DealDatabasePanel: React.FC<DealDatabasePanelProps> = ({ onSelectDeal }) => {+ const [deals, setDeals] = useState<MADeal[]>([]);+ const [selectedDeal, setSelectedDeal] = useState<MADeal | null>(null);+ const [searchQuery, setSearchQuery] = useState('');+ const [loading, setLoading] = useState(false);+ const [scanningFilings, setScanningFilings] = useState(false);+ const [recentFilings, setRecentFilings] = useState<any[]>([]);++ // Load deals on mount+ useEffect(() => {+ loadDeals();+ }, []);++ const loadDeals = async () => {+ setLoading(true);+ try {+ const result = await MAAnalyticsService.DealDatabase.getAllDeals();+ setDeals(result);+ } catch (error) {+ console.error('Failed to load deals:', error);+ } finally {+ setLoading(false);+ }+ };++ const handleSelectDeal = (deal: MADeal) => {+ setSelectedDeal(deal);+ onSelectDeal(deal);+ };++ const handleScanFilings = async () => {+ setScanningFilings(true);+ try {+ const result = await MAAnalyticsService.DealDatabase.scanFilings(30);+ setRecentFilings(JSON.parse(result as string) || []);+ } catch (error) {+ console.error('Failed to scan filings:', error);+ } finally {+ setScanningFilings(false);+ }+ };++ const handleSearch = async () => {+ if (!searchQuery.trim()) {+ loadDeals();+ return;+ }+ setLoading(true);+ try {+ const results = await MAAnalyticsService.DealDatabase.searchDeals(searchQuery);+ setDeals(results);+ } catch (error) {+ console.error('Search failed:', error);+ } finally {+ setLoading(false);+ }+ };++ const formatCurrency = (value: number) => {+ if (value >= 1_000_000_000) {+ return `$${(value / 1_000_000_000).toFixed(2)}B`;+ } else if (value >= 1_000_000) {+ return `$${(value / 1_000_000).toFixed(2)}M`;+ }+ return `$${value.toLocaleString()}`;+ };++ return (+ <div+ style={{+ display: 'flex',+ height: '100%',+ overflow: 'hidden',+ }}+ >+ {/* LEFT PANEL - Deal List */}+ <div+ style={{+ width: '320px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderRight: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ }}+ >+ {/* Search Header */}+ <div+ style={{+ padding: SPACING.DEFAULT,+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}+ >+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>DEAL SEARCH</div>+ <div style={{ display: 'flex', gap: SPACING.SMALL }}>+ <div style={{ position: 'relative', flex: 1 }}>+ <Search+ size={12}+ style={{+ position: 'absolute',+ left: '8px',+ top: '50%',+ transform: 'translateY(-50%)',+ color: FINCEPT.GRAY,+ }}+ />+ <input+ type="text"+ placeholder="Search deals..."+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ onKeyPress={(e) => e.key === 'Enter' && handleSearch()}+ style={{+ ...COMMON_STYLES.inputField,+ paddingLeft: '28px',+ fontSize: TYPOGRAPHY.SMALL,+ }}+ />+ </div>+ <button+ onClick={handleSearch}+ style={{+ ...COMMON_STYLES.buttonPrimary,+ padding: '8px',+ }}+ title="Search"+ >+ <Search size={12} />+ </button>+ <button+ onClick={loadDeals}+ style={{+ ...COMMON_STYLES.buttonSecondary,+ padding: '8px',+ }}+ title="Refresh"+ >+ <RefreshCw size={12} />+ </button>+ </div>+ </div>++ {/* Deal List */}+ <div+ style={{+ flex: 1,+ overflow: 'auto',+ }}+ >+ {loading ? (+ <div style={{ ...COMMON_STYLES.emptyState, padding: SPACING.XLARGE }}>+ <div+ className="animate-spin"+ style={{+ width: '20px',+ height: '20px',+ border: `2px solid ${FINCEPT.BORDER}`,+ borderTop: `2px solid ${FINCEPT.ORANGE}`,+ borderRadius: '50%',+ marginBottom: SPACING.SMALL,+ }}+ />+ <span>Loading deals...</span>+ </div>+ ) : deals.length === 0 ? (+ <div style={{ ...COMMON_STYLES.emptyState, padding: SPACING.XLARGE }}>+ <Database size={32} style={{ marginBottom: SPACING.SMALL, opacity: 0.3 }} />+ <span>No deals found</span>+ <button onClick={handleScanFilings} style={{ ...COMMON_STYLES.buttonPrimary, marginTop: SPACING.DEFAULT }}>+ <Plus size={12} style={{ marginRight: SPACING.TINY }} />+ SCAN FILINGS+ </button>+ </div>+ ) : (+ deals.map((deal) => {+ const isSelected = selectedDeal?.deal_id === deal.deal_id;+ return (+ <div+ key={deal.deal_id}+ onClick={() => handleSelectDeal(deal)}+ style={{+ padding: SPACING.DEFAULT,+ backgroundColor: isSelected ? `${FINCEPT.ORANGE}15` : 'transparent',+ borderLeft: isSelected ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ cursor: 'pointer',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => {+ if (!isSelected) {+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;+ }+ }}+ onMouseLeave={(e) => {+ if (!isSelected) {+ e.currentTarget.style.backgroundColor = 'transparent';+ }+ }}+ >+ <div style={{ fontSize: TYPOGRAPHY.SMALL, fontWeight: TYPOGRAPHY.BOLD, color: FINCEPT.WHITE }}>+ {deal.target_name}+ </div>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY, marginTop: SPACING.TINY }}>+ {deal.acquirer_name}+ </div>+ <div+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ marginTop: SPACING.SMALL,+ fontSize: TYPOGRAPHY.TINY,+ }}+ >+ <span style={{ color: FINCEPT.CYAN }}>{formatCurrency(deal.deal_value)}</span>+ <span+ style={{+ color: deal.premium_1day > 0 ? FINCEPT.GREEN : FINCEPT.RED,+ }}+ >+ {deal.premium_1day > 0 ? '+' : ''}+ {deal.premium_1day.toFixed(1)}%+ </span>+ </div>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.MUTED, marginTop: SPACING.TINY }}>+ {deal.announced_date}+ </div>+ </div>+ );+ })+ )}+ </div>+ </div>++ {/* CENTER PANEL - Deal Details */}+ <div+ style={{+ flex: 1,+ backgroundColor: FINCEPT.DARK_BG,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ }}+ >+ {selectedDeal ? (+ <>+ {/* Deal Header */}+ <div+ style={{+ padding: SPACING.LARGE,+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,+ }}+ >+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>+ <div>+ <div style={{ fontSize: TYPOGRAPHY.HEADING, fontWeight: TYPOGRAPHY.BOLD, color: FINCEPT.WHITE }}>+ {selectedDeal.target_name}+ </div>+ <div+ style={{+ fontSize: TYPOGRAPHY.BODY,+ color: FINCEPT.GRAY,+ marginTop: SPACING.TINY,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ }}+ >+ <Building2 size={12} />+ <span>Acquired by {selectedDeal.acquirer_name}</span>+ </div>+ </div>+ <div style={{ textAlign: 'right' }}>+ <div style={{ fontSize: TYPOGRAPHY.HEADING, fontWeight: TYPOGRAPHY.BOLD, color: FINCEPT.CYAN }}>+ {formatCurrency(selectedDeal.deal_value)}+ </div>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY, marginTop: SPACING.TINY }}>+ DEAL VALUE+ </div>+ </div>+ </div>++ {/* Status Badge */}+ <div style={{ marginTop: SPACING.DEFAULT }}>+ <span+ style={{+ ...COMMON_STYLES.badgeInfo,+ backgroundColor: selectedDeal.status === 'Completed' ? `${FINCEPT.GREEN}20` : `${FINCEPT.YELLOW}20`,+ color: selectedDeal.status === 'Completed' ? FINCEPT.GREEN : FINCEPT.YELLOW,+ }}+ >+ {selectedDeal.status.toUpperCase()}+ </span>+ <span+ style={{+ ...COMMON_STYLES.badgeInfo,+ marginLeft: SPACING.SMALL,+ }}+ >+ {selectedDeal.industry.toUpperCase()}+ </span>+ </div>+ </div>++ {/* Deal Metrics */}+ <div+ style={{+ padding: SPACING.LARGE,+ overflow: 'auto',+ }}+ >+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>KEY METRICS</div>++ <div+ style={{+ display: 'grid',+ gridTemplateColumns: '1fr 1fr',+ gap: SPACING.DEFAULT,+ }}+ >+ {/* Premium */}+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>PREMIUM (1-DAY)</div>+ <div+ style={{+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ color: selectedDeal.premium_1day > 0 ? FINCEPT.GREEN : FINCEPT.RED,+ marginTop: SPACING.TINY,+ }}+ >+ {selectedDeal.premium_1day > 0 ? '+' : ''}+ {selectedDeal.premium_1day.toFixed(1)}%+ </div>+ </div>++ {/* Payment Structure */}+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>PAYMENT STRUCTURE</div>+ <div style={{ marginTop: SPACING.SMALL, fontSize: TYPOGRAPHY.SMALL }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: FINCEPT.GRAY }}>Cash:</span>+ <span style={{ color: FINCEPT.WHITE }}>{selectedDeal.payment_cash_pct}%</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: SPACING.TINY }}>+ <span style={{ color: FINCEPT.GRAY }}>Stock:</span>+ <span style={{ color: FINCEPT.WHITE }}>{selectedDeal.payment_stock_pct}%</span>+ </div>+ </div>+ </div>++ {/* EV/Revenue */}+ {selectedDeal.ev_revenue && (+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>EV / REVENUE</div>+ <div+ style={{+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ color: FINCEPT.CYAN,+ marginTop: SPACING.TINY,+ }}+ >+ {selectedDeal.ev_revenue.toFixed(2)}x+ </div>+ </div>+ )}++ {/* EV/EBITDA */}+ {selectedDeal.ev_ebitda && (+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>EV / EBITDA</div>+ <div+ style={{+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ color: FINCEPT.CYAN,+ marginTop: SPACING.TINY,+ }}+ >+ {selectedDeal.ev_ebitda.toFixed(2)}x+ </div>+ </div>+ )}++ {/* Synergies */}+ {selectedDeal.synergies && (+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>EST. SYNERGIES</div>+ <div+ style={{+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ color: FINCEPT.GREEN,+ marginTop: SPACING.TINY,+ }}+ >+ {formatCurrency(selectedDeal.synergies)}+ </div>+ </div>+ )}++ {/* Announced Date */}+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>ANNOUNCED</div>+ <div+ style={{+ fontSize: TYPOGRAPHY.SMALL,+ color: FINCEPT.WHITE,+ marginTop: SPACING.TINY,+ }}+ >+ {selectedDeal.announced_date}+ </div>+ </div>+ </div>+ </div>+ </>+ ) : (+ <div style={COMMON_STYLES.emptyState}>+ <Eye size={32} style={{ marginBottom: SPACING.SMALL, opacity: 0.3 }} />+ <span>Select a deal to view details</span>+ </div>+ )}+ </div>++ {/* RIGHT PANEL - SEC Filing Scanner */}+ <div+ style={{+ width: '300px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderLeft: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ }}+ >+ {/* Scanner Header */}+ <div+ style={{+ padding: SPACING.DEFAULT,+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}+ >+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>SEC FILING SCANNER</div>+ <button+ onClick={handleScanFilings}+ disabled={scanningFilings}+ style={{+ ...COMMON_STYLES.buttonPrimary,+ width: '100%',+ opacity: scanningFilings ? 0.7 : 1,+ }}+ >+ {scanningFilings ? (+ <>+ <div+ className="animate-spin"+ style={{+ width: '12px',+ height: '12px',+ border: `2px solid ${FINCEPT.DARK_BG}`,+ borderTop: `2px solid transparent`,+ borderRadius: '50%',+ marginRight: SPACING.TINY,+ display: 'inline-block',+ }}+ />+ SCANNING...+ </>+ ) : (+ <>+ <RefreshCw size={12} style={{ marginRight: SPACING.TINY }} />+ SCAN RECENT FILINGS+ </>+ )}+ </button>+ </div>++ {/* Recent Filings List */}+ <div+ style={{+ flex: 1,+ overflow: 'auto',+ padding: SPACING.DEFAULT,+ }}+ >+ {recentFilings.length === 0 ? (+ <div style={COMMON_STYLES.emptyState}>+ <FileText size={24} style={{ marginBottom: SPACING.SMALL, opacity: 0.3 }} />+ <span style={{ fontSize: TYPOGRAPHY.TINY }}>No recent filings</span>+ </div>+ ) : (+ recentFilings.map((filing, index) => (+ <div+ key={index}+ style={{+ ...COMMON_STYLES.metricCard,+ marginBottom: SPACING.SMALL,+ }}+ >+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.ORANGE, fontWeight: TYPOGRAPHY.BOLD }}>+ {filing.filing_type}+ </div>+ <div style={{ fontSize: TYPOGRAPHY.SMALL, color: FINCEPT.WHITE, marginTop: SPACING.TINY }}>+ {filing.company_name}+ </div>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY, marginTop: SPACING.TINY }}>+ {filing.filing_date}+ </div>+ <div+ style={{+ marginTop: SPACING.SMALL,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ }}+ >+ <span+ style={{+ fontSize: TYPOGRAPHY.TINY,+ color: FINCEPT.CYAN,+ }}+ >+ Confidence: {filing.confidence_score}%+ </span>+ <button+ style={{+ ...COMMON_STYLES.buttonSecondary,+ fontSize: '7px',+ padding: '4px 6px',+ }}+ >+ VIEW+ </button>+ </div>+ </div>+ ))+ )}+ </div>+ </div>+ </div>+ );+};diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/DealStructurePanel.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/DealStructurePanel.tsxnew file mode 100644index 000000000..cd5c3b593--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/DealStructurePanel.tsx@@ -0,0 +1,10 @@+import React from 'react';+import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { Activity } from 'lucide-react';++export const DealStructurePanel: React.FC<{ selectedDeal?: any }> = () => (+ <div style={COMMON_STYLES.emptyState}>+ <Activity size={48} style={{ opacity: 0.3, marginBottom: SPACING.DEFAULT }} />+ <div style={{ fontSize: TYPOGRAPHY.BODY, color: FINCEPT.GRAY }}>DealStructurePanel - Under Construction</div>+ </div>+);diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/FairnessOpinionPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/FairnessOpinionPanel.tsxnew file mode 100644index 000000000..8985c5bf2--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/FairnessOpinionPanel.tsx@@ -0,0 +1,10 @@+import React from 'react';+import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { Activity } from 'lucide-react';++export const FairnessOpinionPanel: React.FC<{ selectedDeal?: any }> = () => (+ <div style={COMMON_STYLES.emptyState}>+ <Activity size={48} style={{ opacity: 0.3, marginBottom: SPACING.DEFAULT }} />+ <div style={{ fontSize: TYPOGRAPHY.BODY, color: FINCEPT.GRAY }}>FairnessOpinionPanel - Under Construction</div>+ </div>+);diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/IndustryMetricsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/IndustryMetricsPanel.tsxnew file mode 100644index 000000000..ddfb28952--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/IndustryMetricsPanel.tsx@@ -0,0 +1,10 @@+import React from 'react';+import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { Activity } from 'lucide-react';++export const IndustryMetricsPanel: React.FC<{ selectedDeal?: any }> = () => (+ <div style={COMMON_STYLES.emptyState}>+ <Activity size={48} style={{ opacity: 0.3, marginBottom: SPACING.DEFAULT }} />+ <div style={{ fontSize: TYPOGRAPHY.BODY, color: FINCEPT.GRAY }}>IndustryMetricsPanel - Under Construction</div>+ </div>+);diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/LBOModelPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/LBOModelPanel.tsxnew file mode 100644index 000000000..8a9417c52--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/LBOModelPanel.tsx@@ -0,0 +1,10 @@+import React from 'react';+import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { Activity } from 'lucide-react';++export const LBOModelPanel: React.FC<{ selectedDeal?: any }> = () => (+ <div style={COMMON_STYLES.emptyState}>+ <Activity size={48} style={{ opacity: 0.3, marginBottom: SPACING.DEFAULT }} />+ <div style={{ fontSize: TYPOGRAPHY.BODY, color: FINCEPT.GRAY }}>LBOModelPanel - Under Construction</div>+ </div>+);diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/MergerModelPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/MergerModelPanel.tsxnew file mode 100644index 000000000..1fc5fc625--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/MergerModelPanel.tsx@@ -0,0 +1,13 @@+import React from 'react';+import { GitMerge } from 'lucide-react';+import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';++export const MergerModelPanel: React.FC<{ selectedDeal: any }> = () => (+ <div style={COMMON_STYLES.emptyState}>+ <GitMerge size={48} style={{ opacity: 0.3, marginBottom: SPACING.DEFAULT }} />+ <div style={{ fontSize: TYPOGRAPHY.BODY, color: FINCEPT.GRAY }}>Merger Model - Under Construction</div>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.MUTED, marginTop: SPACING.SMALL }}>+ Accretion/Dilution, Pro Forma, Sources & Uses+ </div>+ </div>+);diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/StartupValuationPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/StartupValuationPanel.tsxnew file mode 100644index 000000000..8cdf03534--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/StartupValuationPanel.tsx@@ -0,0 +1,10 @@+import React from 'react';+import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { Activity } from 'lucide-react';++export const StartupValuationPanel: React.FC<{ selectedDeal?: any }> = () => (+ <div style={COMMON_STYLES.emptyState}>+ <Activity size={48} style={{ opacity: 0.3, marginBottom: SPACING.DEFAULT }} />+ <div style={{ fontSize: TYPOGRAPHY.BODY, color: FINCEPT.GRAY }}>StartupValuationPanel - Under Construction</div>+ </div>+);diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/SynergiesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/SynergiesPanel.tsxnew file mode 100644index 000000000..4c9885969--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/SynergiesPanel.tsx@@ -0,0 +1,10 @@+import React from 'react';+import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { Activity } from 'lucide-react';++export const SynergiesPanel: React.FC<{ selectedDeal?: any }> = () => (+ <div style={COMMON_STYLES.emptyState}>+ <Activity size={48} style={{ opacity: 0.3, marginBottom: SPACING.DEFAULT }} />+ <div style={{ fontSize: TYPOGRAPHY.BODY, color: FINCEPT.GRAY }}>SynergiesPanel - Under Construction</div>+ </div>+);diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/ValuationPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/ValuationPanel.tsxnew file mode 100644index 000000000..00a588ae1--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/panels/ValuationPanel.tsx@@ -0,0 +1,54 @@+import React, { useState } from 'react';+import { Calculator, TrendingUp, BarChart2, Combine } from 'lucide-react';+import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';++interface ValuationPanelProps {+ selectedDeal: any;+}++export const ValuationPanel: React.FC<ValuationPanelProps> = ({ selectedDeal }) => {+ const [valuationMethod, setValuationMethod] = useState<'dcf' | 'comps' | 'precedent' | 'football'>('dcf');++ return (+ <div style={{ padding: SPACING.LARGE }}>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>VALUATION ANALYSIS</div>++ {/* Method Selector */}+ <div style={{ display: 'flex', gap: SPACING.SMALL, marginBottom: SPACING.LARGE }}>+ {[+ { id: 'dcf', label: 'DCF', icon: Calculator },+ { id: 'comps', label: 'TRADING COMPS', icon: BarChart2 },+ { id: 'precedent', label: 'PRECEDENT TX', icon: TrendingUp },+ { id: 'football', label: 'FOOTBALL FIELD', icon: Combine },+ ].map((method) => {+ const Icon = method.icon;+ return (+ <button+ key={method.id}+ onClick={() => setValuationMethod(method.id as any)}+ style={{+ ...COMMON_STYLES.tabButton(valuationMethod === method.id),+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.TINY,+ }}+ >+ <Icon size={12} />+ {method.label}+ </button>+ );+ })}+ </div>++ <div style={COMMON_STYLES.emptyState}>+ <Calculator size={48} style={{ opacity: 0.3, marginBottom: SPACING.DEFAULT }} />+ <div style={{ fontSize: TYPOGRAPHY.BODY, color: FINCEPT.GRAY }}>+ Valuation Module - Under Construction+ </div>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.MUTED, marginTop: SPACING.SMALL }}>+ DCF, Trading Comps, Precedent Transactions, Football Field+ </div>+ </div>+ </div>+ );+};diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/index.tsxindex 44fa75f24..4d1c26b12 100644--- a/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx+++ b/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx@@ -6,7 +6,9 @@ import { Plus, RefreshCw, Search, Play, Square, Trash2, Settings, Zap, CheckCircimport { mcpManager, MCPServerWithStats } from '../../../services/mcp/mcpManager';import { sqliteService } from '../../../services/core/sqliteService';import { useBrokerContext } from '../../../contexts/BrokerContext';+import { useStockBrokerContext } from '../../../contexts/StockBrokerContext';import { brokerMCPBridge } from '../../../services/mcp/internal/BrokerMCPBridge';+import { stockBrokerMCPBridge } from '../../../services/mcp/internal/StockBrokerMCPBridge';import MCPMarketplace from './marketplace/MCPMarketplace';import MCPAddServerModal from './MCPAddServerModal';import MCPToolsManagement from './MCPToolsManagement';@@ -46,10 +48,17 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {const [searchTerm, setSearchTerm] = useState('');const [selectedServerId, setSelectedServerId] = useState<string | null>(null);- // Broker context for MCP bridge+ // Crypto broker context for MCP bridgeconst { activeAdapter, tradingMode, activeBroker } = useBrokerContext();- // Connect broker to MCP bridge+ // Stock broker context for MCP bridge+ const stockBrokerCtx = useStockBrokerContext();+ const stockAdapter = stockBrokerCtx?.adapter;+ const stockTradingMode = stockBrokerCtx?.tradingMode;+ const stockActiveBroker = stockBrokerCtx?.activeBroker;+ const stockIsAuthenticated = stockBrokerCtx?.isAuthenticated;++ // Connect crypto broker to MCP bridgeuseEffect(() => {if (activeAdapter) {brokerMCPBridge.connect({@@ -57,7 +66,7 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {tradingMode,activeBroker,});- console.log(`[MCP] Connected to ${activeBroker} in ${tradingMode} mode`);+ console.log(`[MCP] Connected to crypto broker: ${activeBroker} (${tradingMode} mode)`);}return () => {@@ -65,6 +74,23 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {};}, [activeAdapter, tradingMode, activeBroker]);+ // Connect stock broker to MCP bridge+ useEffect(() => {+ if (stockAdapter && stockIsAuthenticated && stockActiveBroker) {+ stockBrokerMCPBridge.connect({+ activeAdapter: stockAdapter,+ tradingMode: stockTradingMode || 'paper',+ activeBroker: stockActiveBroker,+ isAuthenticated: stockIsAuthenticated,+ });+ console.log(`[MCP] Connected to stock broker: ${stockActiveBroker} (${stockTradingMode} mode)`);+ }++ return () => {+ stockBrokerMCPBridge.disconnect();+ };+ }, [stockAdapter, stockIsAuthenticated, stockActiveBroker, stockTradingMode]);+useEffect(() => {const initializeServers = async () => {try {diff --git a/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx b/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsxindex 90c2e7633..0f7082f04 100644--- a/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx@@ -30,17 +30,25 @@ const SentIcon: React.FC<{ s: string; size?: number }> = ({ s, size = 10 }) =>s === 'BULLISH' ? <TrendingUp size={size} /> : s === 'BEARISH' ? <TrendingDown size={size} /> : <Minus size={size} />;// ══════════════════════════════════════════════════════════════-// NEWS GRID CARD – compact, shows key info at a glance+// NEWS GRID CARD – compact, shows key info + inline actions// ══════════════════════════════════════════════════════════════const NewsGridCard: React.FC<{article: NewsArticle;- onClick: () => void;-}> = ({ article, onClick }) => {+ onAnalyze: (article: NewsArticle) => void;+ analyzing: boolean;+ analysisData: NewsAnalysisData | null;+ showAnalysis: boolean;+ currentAnalyzingId: string | null;+ openExternal: (url: string) => void;+}> = ({ article, onAnalyze, analyzing, analysisData, showAnalysis, currentAnalyzingId, openExternal }) => {const [hovered, setHovered] = useState(false);+ const [expanded, setExpanded] = useState(false);const isHighPri = article.priority === 'FLASH' || article.priority === 'URGENT';+ const isAnalyzing = analyzing && currentAnalyzingId === article.id;+ const hasAnalysis = showAnalysis && analysisData && currentAnalyzingId === article.id;+return (<div- onClick={onClick}onMouseEnter={() => setHovered(true)}onMouseLeave={() => setHovered(false)}style={{@@ -49,11 +57,9 @@ const NewsGridCard: React.FC<{border: `1px solid ${isHighPri ? `${priColor(article.priority)}40` : F.BORDER}`,borderLeft: `3px solid ${priColor(article.priority)}`,borderRadius: '2px',- cursor: 'pointer',transition: 'background 0.15s',display: 'flex',flexDirection: 'column',- justifyContent: 'space-between',minHeight: '100px',}}>@@ -68,22 +74,135 @@ const NewsGridCard: React.FC<{</div>{/* Headline */}- <div style={{- color: F.WHITE,- fontSize: '11px',- fontWeight: 600,- lineHeight: '1.4',- flex: 1,- overflow: 'hidden',- textOverflow: 'ellipsis',- display: '-webkit-box',- WebkitLineClamp: 3,- WebkitBoxOrient: 'vertical' as any,- marginBottom: '8px',- }}>{article.headline}</div>+ <div+ onClick={() => setExpanded(!expanded)}+ style={{+ color: F.WHITE,+ fontSize: '11px',+ fontWeight: 600,+ lineHeight: '1.4',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ display: '-webkit-box',+ WebkitLineClamp: expanded ? 'unset' : 3,+ WebkitBoxOrient: 'vertical' as any,+ marginBottom: '8px',+ cursor: 'pointer',+ }}+ >{article.headline}</div>++ {/* Summary (when expanded) */}+ {expanded && (+ <div style={{+ color: F.GRAY,+ fontSize: '10px',+ lineHeight: '1.5',+ marginBottom: '8px',+ paddingLeft: '8px',+ borderLeft: `2px solid ${F.BORDER}`,+ }}>{article.summary}</div>+ )}++ {/* Tickers (when expanded) */}+ {expanded && article.tickers && article.tickers.length > 0 && (+ <div style={{ display: 'flex', gap: '4px', marginBottom: '8px', flexWrap: 'wrap' }}>+ {article.tickers.map((ticker, i) => (+ <span key={i} style={{+ padding: '1px 6px', backgroundColor: `${F.GREEN}15`, color: F.GREEN,+ fontSize: '8px', fontWeight: 700, borderRadius: '2px', border: `1px solid ${F.GREEN}30`,+ }}>{ticker}</span>+ ))}+ </div>+ )}++ {/* Action Buttons (visible on hover or when expanded) */}+ {(hovered || expanded) && article.link && (+ <div style={{+ display: 'flex',+ gap: '4px',+ marginBottom: '8px',+ opacity: hovered || expanded ? 1 : 0,+ transition: 'opacity 0.2s',+ }}>+ <button+ onClick={(e) => { e.stopPropagation(); openExternal(article.link!); }}+ style={{+ flex: 1, padding: '5px 8px', backgroundColor: F.BLUE, color: F.WHITE,+ border: 'none', fontSize: '8px', fontWeight: 700, cursor: 'pointer',+ borderRadius: '2px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px',+ }}+ ><ExternalLink size={9} />OPEN</button>+ <button+ onClick={(e) => { e.stopPropagation(); navigator.clipboard.writeText(article.link!); }}+ style={{+ padding: '5px 8px', background: 'none', border: `1px solid ${F.BORDER}`,+ color: F.GRAY, fontSize: '8px', fontWeight: 700, cursor: 'pointer',+ borderRadius: '2px', display: 'flex', alignItems: 'center', gap: '3px',+ }}+ ><Copy size={9} /></button>+ <button+ onClick={(e) => { e.stopPropagation(); onAnalyze(article); setExpanded(true); }}+ disabled={isAnalyzing}+ style={{+ flex: 1, padding: '5px 8px',+ backgroundColor: isAnalyzing ? F.MUTED : F.PURPLE,+ color: F.WHITE, border: 'none', fontSize: '8px', fontWeight: 700,+ cursor: isAnalyzing ? 'not-allowed' : 'pointer',+ borderRadius: '2px', opacity: isAnalyzing ? 0.5 : 1,+ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px',+ }}+ ><Zap size={9} />{isAnalyzing ? 'ANALYZING...' : 'ANALYZE'}</button>+ </div>+ )}++ {/* AI Analysis Results (inline, when available) */}+ {hasAnalysis && expanded && (+ <div style={{ borderTop: `1px solid ${F.BORDER}`, paddingTop: '8px', marginTop: '4px' }}>+ <div style={{+ padding: '4px 8px', backgroundColor: `${F.PURPLE}15`, border: `1px solid ${F.PURPLE}`,+ borderRadius: '2px', marginBottom: '8px', fontSize: '8px',+ }}>+ <span style={{ color: F.PURPLE, fontWeight: 700, letterSpacing: '0.5px' }}>AI ANALYSIS</span>+ </div>++ <div style={{+ fontSize: '9px', color: F.WHITE, lineHeight: '1.5', padding: '6px 8px',+ backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px', marginBottom: '8px',+ }}>{analysisData.analysis.summary}</div>++ {analysisData.analysis.key_points.length > 0 && (+ <div style={{ marginBottom: '8px' }}>+ <div style={{ fontSize: '8px', color: F.GRAY, fontWeight: 700, marginBottom: '4px' }}>KEY POINTS</div>+ <div style={{ padding: '6px 8px', backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px' }}>+ {analysisData.analysis.key_points.slice(0, 3).map((pt, i) => (+ <div key={i} style={{+ fontSize: '8px', color: F.WHITE, paddingLeft: '6px',+ borderLeft: `2px solid ${F.ORANGE}`, marginBottom: '4px', lineHeight: '1.4',+ }}>{pt}</div>+ ))}+ </div>+ </div>+ )}++ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px' }}>+ <div style={{ padding: '6px', backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px' }}>+ <div style={{ fontSize: '8px', color: F.GRAY, fontWeight: 700, marginBottom: '3px' }}>SENTIMENT</div>+ <div style={{ fontSize: '8px', color: getSentimentColor(analysisData.analysis.sentiment.score), fontWeight: 700 }}>+ {analysisData.analysis.sentiment.score.toFixed(2)}+ </div>+ </div>+ <div style={{ padding: '6px', backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px' }}>+ <div style={{ fontSize: '8px', color: F.GRAY, fontWeight: 700, marginBottom: '3px' }}>URGENCY</div>+ <div style={{ fontSize: '8px', color: getUrgencyColor(analysisData.analysis.market_impact.urgency), fontWeight: 700 }}>+ {analysisData.analysis.market_impact.urgency}+ </div>+ </div>+ </div>+ </div>+ )}{/* Bottom: badges row */}- <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap', marginTop: '8px' }}>{isHighPri && (<span style={{padding: '1px 6px', fontSize: '8px', fontWeight: 700, borderRadius: '2px',@@ -391,7 +510,6 @@ const NewsTab: React.FC = () => {const [loading, setLoading] = useState(true);const [activeSources, setActiveSources] = useState<string[]>([]);const [feedCount, setFeedCount] = useState(9);- const [selectedArticle, setSelectedArticle] = useState<NewsArticle | null>(null);const [refreshInterval, setRefreshInterval] = useState(10);const [showIntervalSettings, setShowIntervalSettings] = useState(false);const [isRecording, setIsRecording] = useState(false);@@ -400,6 +518,7 @@ const NewsTab: React.FC = () => {const [showAnalysis, setShowAnalysis] = useState(false);const [showFeedSettings, setShowFeedSettings] = useState(false);const [searchQuery, setSearchQuery] = useState('');+ const [currentAnalyzingId, setCurrentAnalyzingId] = useState<string | null>(null);// ── Data loading ──const recordCurrentData = async () => {@@ -438,13 +557,21 @@ const NewsTab: React.FC = () => {} catch { /* silent */ } finally { setLoading(false); }}, [isRecording, activeFilter]);- const handleAnalyzeArticle = async () => {- if (!selectedArticle?.link) return;- setAnalyzingArticle(true); setShowAnalysis(false); setAnalysisData(null);+ const handleAnalyzeArticle = async (article: NewsArticle) => {+ if (!article?.link) return;+ setAnalyzingArticle(true);+ setShowAnalysis(false);+ setAnalysisData(null);+ setCurrentAnalyzingId(article.id);try {- const result = await analyzeNewsArticle(selectedArticle.link);- if (result.success && 'data' in result) { setAnalysisData(result.data); setShowAnalysis(true); }- } catch { /* silent */ } finally { setAnalyzingArticle(false); }+ const result = await analyzeNewsArticle(article.link);+ if (result.success && 'data' in result) {+ setAnalysisData(result.data);+ setShowAnalysis(true);+ }+ } catch { /* silent */ } finally {+ setAnalyzingArticle(false);+ }};const isInitialMount = useRef(true);@@ -849,7 +976,7 @@ const NewsTab: React.FC = () => {) : (<div style={{display: 'grid',- gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',+ gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',gap: '8px',alignContent: 'start',}}>@@ -857,7 +984,12 @@ const NewsTab: React.FC = () => {<NewsGridCardkey={article.id}article={article}- onClick={() => { setSelectedArticle(article); setShowAnalysis(false); setAnalysisData(null); }}+ onAnalyze={handleAnalyzeArticle}+ analyzing={analyzingArticle}+ analysisData={analysisData}+ showAnalysis={showAnalysis}+ currentAnalyzingId={currentAnalyzingId}+ openExternal={openExternal}/>))}</div>@@ -889,19 +1021,6 @@ const NewsTab: React.FC = () => {</div></div>- {/* ── ARTICLE DETAIL MODAL (overlay, on demand) ── */}- {selectedArticle && (- <ArticleDetailModal- article={selectedArticle}- onClose={() => setSelectedArticle(null)}- onAnalyze={handleAnalyzeArticle}- analyzing={analyzingArticle}- analysisData={analysisData}- showAnalysis={showAnalysis}- openExternal={openExternal}- />- )}-{/* ── CSS ── */}<style>{`@keyframes ntBlink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0.3; } }diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx b/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsxindex dcb584212..4dda18745 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx@@ -33,6 +33,7 @@ interface ProChartProps {showHeader?: boolean; // Option to hide the symbol/OHLC headeronToolChange?: (tool: DrawingTool | null) => void;timezone?: string; // e.g., 'Asia/Kolkata' for IST, 'America/New_York' for EST+ interval?: string; // Timeframe/interval for proper time scale formatting (e.g., '1m', '5m', '1h', '1d')}export function ProChartWithToolkit({@@ -44,6 +45,7 @@ export function ProChartWithToolkit({showHeader = true,onToolChange,timezone,+ interval = '1d',}: ProChartProps) {const chartContainerRef = useRef<HTMLDivElement>(null);const chartRef = useRef<IChartApi | null>(null);@@ -63,6 +65,13 @@ export function ProChartWithToolkit({if (!chartContainerRef.current) return;const containerHeight = chartContainerRef.current.clientHeight || height;++ // Determine time visibility based on interval+ // For intraday timeframes (minutes, hours), show time+ // For daily and above, time is less important+ const isIntradayTimeframe = interval ? !['1d', '1w', '1M'].includes(interval) : true;+ const showSeconds = interval ? ['1m', '3m', '5m'].includes(interval) : false;+// Build localization options for timezoneconst localizationOptions = timezone ? {locale: 'en-IN', // Use Indian locale for IST, can be customized per timezone@@ -130,8 +139,8 @@ export function ProChartWithToolkit({},timeScale: {borderColor: '#2a2a2a',- timeVisible: true,- secondsVisible: false,+ timeVisible: isIntradayTimeframe, // Show time for intraday timeframes+ secondsVisible: showSeconds, // Show seconds for very short timeframes (1m, 3m, 5m)},});@@ -277,7 +286,7 @@ export function ProChartWithToolkit({pluginManager.destroy();chart.remove();};- }, [height, showVolume, timezone]);+ }, [height, showVolume, timezone, interval]);// Update chart datauseEffect(() => {diff --git a/fincept-terminal-desktop/src/constants/version.ts b/fincept-terminal-desktop/src/constants/version.tsindex c795f939c..8624ed6d6 100644--- a/fincept-terminal-desktop/src/constants/version.ts+++ b/fincept-terminal-desktop/src/constants/version.ts@@ -6,7 +6,7 @@// Run `bun run sync-version` to sync from package.json// Or edit package.json and run build/dev to auto-sync-export const APP_VERSION = '3.2.0';+export const APP_VERSION = '3.2.1';export const APP_NAME = 'Fincept Terminal';export const APP_BUILD_DATE = new Date().toISOString().split('T')[0];diff --git a/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx b/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsxindex a4bb48c74..1cbe58093 100644--- a/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx+++ b/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx@@ -212,6 +212,9 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {const abortControllerRef = useRef<AbortController | null>(null);const hasInitializedRef = useRef(false);+ // Counter to force adapter re-initialization+ const [adapterInitKey, setAdapterInitKey] = useState(0);+// ============================================================================// COMPUTED VALUES (Memoized)// ============================================================================@@ -280,10 +283,12 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {if (savedBroker && STOCK_BROKER_REGISTRY[savedBroker]) {console.log(`[StockBrokerContext] Found saved broker: ${savedBroker}`);setActiveBrokerState(savedBroker);+ // Note: isLoading will be set to false by initializeAdapter useEffect} else {// No saved broker - scan all brokers to find one with valid sessionconsole.log('[StockBrokerContext] No saved broker, scanning for valid sessions...');const allBrokers = getAllStockBrokers();+ let foundBroker = false;for (const broker of allBrokers) {try {@@ -296,6 +301,7 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {if (isValid) {console.log(`[StockBrokerContext] Found valid session for: ${broker.id}`);setActiveBrokerState(broker.id);+ foundBroker = true;break;}}@@ -303,6 +309,11 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {// Skip broker if check fails}}++ // If no broker found, set loading to false here+ if (!foundBroker) {+ setIsLoading(false);+ }}console.log('[StockBrokerContext] Preferences loaded', {@@ -311,7 +322,6 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {});} catch (err) {console.error('[StockBrokerContext] Failed to load preferences:', err);- } finally {setIsLoading(false);}};@@ -320,11 +330,19 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {}, []);// Auto-create adapter when broker changes (including on startup)+ // adapterInitKey forces re-init when incremented (for re-selecting same broker)useEffect(() => {const initializeAdapter = async () => {- if (!activeBroker || adapter?.brokerId === activeBroker) return;+ if (!activeBroker) {+ // If we're skipping init and isLoading is true, set it to false+ if (isLoading) {+ setIsLoading(false);+ }+ return;+ }- console.log(`[StockBrokerContext] Initializing adapter for: ${activeBroker}`);+ console.log(`[StockBrokerContext] Initializing adapter for: ${activeBroker} (key: ${adapterInitKey})`);+ setIsLoading(true);try {const newAdapter = createStockBrokerAdapter(activeBroker);@@ -362,6 +380,7 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {setAdapter(newAdapter);}+ setIsLoading(false);return;}@@ -379,14 +398,18 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {console.log(`[StockBrokerContext] ✓ Credentials loaded into adapter memory`);}- // If access_token exists, attempt auto-restore session- if (storedCreds.accessToken && typeof (newAdapter as any).initFromStorage === 'function') {- console.log(`[StockBrokerContext] Access token found, attempting auto-restore...`);+ // Attempt auto-restore or auto-authenticate+ if (typeof (newAdapter as any).initFromStorage === 'function') {+ console.log(`[StockBrokerContext] Attempting auto-restore/auto-authenticate...`);const restored = await (newAdapter as any).initFromStorage();if (restored) {console.log(`[StockBrokerContext] ✓ Session restored successfully`);++ // CRITICAL: Set adapter BEFORE isAuthenticated to avoid race condition+ setAdapter(newAdapter);setIsAuthenticated(true);+ setError(null);// Initialize unified trading sessiontry {@@ -396,31 +419,49 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {console.error('[StockBrokerContext] Failed to init trading session:', sessionErr);}- // Note: Data will be auto-loaded by the useEffect that watches isAuthenticated+ // Success - skip setting adapter again below+ setIsLoading(false);+ return;} else {- console.log(`[StockBrokerContext] Session restore failed (token may be expired)`);- // Indian broker tokens expire at midnight IST - notify user- setError(`Session expired. Please re-authenticate with ${activeBroker}.`);+ console.log(`[StockBrokerContext] Auto-restore failed - session expired or invalid`);+ setAdapter(newAdapter);setIsAuthenticated(false);+ setError(`Session expired for ${activeBroker}. Please re-authenticate in the BROKERS tab.`);+ setIsLoading(false);+ return; // Don't set adapter again below}} else {- console.log(`[StockBrokerContext] No access token found, manual OAuth required`);+ console.log(`[StockBrokerContext] No initFromStorage method, manual OAuth required`);+ setAdapter(newAdapter);+ setIsAuthenticated(false);+ setError(null); // No error - just needs manual auth+ setIsLoading(false);+ return;}} else {console.log(`[StockBrokerContext] No stored credentials found`);+ setAdapter(newAdapter);+ setIsAuthenticated(false);+ setError(null); // No error - just needs initial setup+ setIsLoading(false);+ return;}} catch (loadErr) {console.log('[StockBrokerContext] Failed to load credentials:', loadErr);+ setAdapter(newAdapter);+ setIsAuthenticated(false);+ setError(null);+ setIsLoading(false);+ return;}-- setAdapter(newAdapter);} catch (err) {console.error('[StockBrokerContext] Failed to create adapter:', err);+ setIsLoading(false);}};initializeAdapter();- }, [activeBroker, tradingMode]);+ }, [activeBroker, tradingMode, adapterInitKey]);// ============================================================================// BROKER MANAGEMENT@@ -434,11 +475,20 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {// Abort any ongoing connectionabortControllerRef.current?.abort();+ // Check if re-selecting the same broker (needs re-init)+ const isReselecting = brokerId === activeBroker;+// Clean up existing adapter (DON'T logout - preserves credentials in DB)- if (adapter && adapter.brokerId !== brokerId) {- console.log(`[StockBrokerContext] Switching from ${adapter.brokerId} to ${brokerId}, preserving credentials`);- // Don't call logout() - it deletes credentials from database- // Just reset the adapter instance+ if (adapter) {+ console.log(`[StockBrokerContext] ${isReselecting ? 'Re-initializing' : 'Switching from'} ${adapter.brokerId} ${isReselecting ? '' : `to ${brokerId}`}, preserving credentials`);+ // Cleanup WebSocket connections without deleting credentials+ try {+ if (adapter.disconnectWebSocket) {+ await adapter.disconnectWebSocket();+ }+ } catch (err) {+ console.error('[StockBrokerContext] Failed to disconnect WebSocket:', err);+ }}// Reset state@@ -458,13 +508,19 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {await safeStorageSet(STORAGE_KEYS.STOCK_TRADING_MODE, 'paper');}- // Set new broker+ // Set new broker (or same broker for re-init)setActiveBrokerState(brokerId);await safeStorageSet(STORAGE_KEYS.ACTIVE_STOCK_BROKER, brokerId);- // Adapter will be created by useEffect watching activeBroker+ // If re-selecting same broker, increment key to force re-initialization+ if (isReselecting) {+ console.log(`[StockBrokerContext] Re-selecting same broker, forcing re-init...`);+ setAdapterInitKey(prev => prev + 1);+ }++ // Adapter will be created by useEffect watching activeBroker + adapterInitKeyconsole.log(`[StockBrokerContext] Active broker set to: ${brokerId}`);- }, [adapter, tradingMode]);+ }, [adapter, tradingMode, activeBroker]);const setTradingMode = useCallback(async (mode: 'live' | 'paper') => {setTradingModeState(mode);@@ -569,6 +625,24 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {try {await adapterToUse.connectWebSocket();console.log(`[StockBrokerContext] ✓ WebSocket connected for ${activeBroker}`);++ // If in paper trading mode, set up tick handler to update paper positions+ if (tradingMode === 'paper') {+ const { invoke } = await import('@tauri-apps/api/core');+ adapterToUse.onTick(async (tick) => {+ try {+ // Update paper trading position prices+ const symbol = `${tick.exchange}:${tick.symbol}`;+ await invoke('process_tick_for_paper_trading', {+ symbol,+ price: tick.lastPrice+ });+ } catch (err) {+ console.error('[StockBrokerContext] Failed to process tick for paper trading:', err);+ }+ });+ console.log(`[StockBrokerContext] ✓ Paper trading tick handler registered`);+ }} catch (wsErr) {console.warn(`[StockBrokerContext] WebSocket connection failed for ${activeBroker}, will use REST polling:`, wsErr);}@@ -768,7 +842,10 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {try {if (tradingMode === 'paper') {// Fetch from unified trading service (paper positions)+ console.log('[StockBrokerContext] Fetching paper positions from DB...');const unifiedPositions = await getUnifiedPositions();+ console.log(`[StockBrokerContext] Fetched ${unifiedPositions.length} positions from DB:`, unifiedPositions);+// Convert UnifiedPosition to Position formatconst convertedPositions: Position[] = unifiedPositions.map((p) => ({symbol: p.symbol,@@ -785,6 +862,8 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {pnlPercent: p.entry_price > 0 ? ((p.current_price - p.entry_price) / p.entry_price) * 100 : 0,dayPnl: 0,}));++ console.log(`[StockBrokerContext] Setting ${convertedPositions.length} positions in state`);setPositions(convertedPositions);} else if (adapter) {// Fetch from live broker@@ -1000,6 +1079,96 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {}}, [tradingMode, isAuthenticated, adapter]);+ // ============================================================================+ // AUTO-REFRESH POSITIONS AFTER ORDER PLACEMENT (FROM MCP/CHAT)+ // ============================================================================++ useEffect(() => {+ const handleOrderPlaced = async (event: Event) => {+ const customEvent = event as CustomEvent;+ console.log('[StockBrokerContext] Order placed, refreshing data from DB...', customEvent.detail);+ // Simply refresh positions and orders from database+ await refreshPositions();+ await refreshOrders();+ };++ window.addEventListener('stock-order-placed', handleOrderPlaced);+ return () => {+ window.removeEventListener('stock-order-placed', handleOrderPlaced);+ };+ }, [refreshPositions, refreshOrders]);++ // ============================================================================+ // PERIODIC REFRESH FOR PAPER TRADING (Real-time price updates from WebSocket)+ // ============================================================================++ useEffect(() => {+ // Only in paper mode with active positions+ if (tradingMode !== 'paper' || !isAuthenticated) {+ return;+ }++ // Refresh every 3 seconds to show updated prices+ // (WebSocket updates the DB, we just need to read it)+ const intervalId = setInterval(() => {+ refreshPositions();+ }, 3000);++ return () => clearInterval(intervalId);+ }, [tradingMode, isAuthenticated, refreshPositions]);++ // ============================================================================+ // SUBSCRIBE TO POSITION SYMBOLS (Paper Trading Real-time Updates)+ // ============================================================================++ useEffect(() => {+ // Only subscribe in paper mode when we have positions+ if (tradingMode !== 'paper' || !adapter || positions.length === 0) {+ return;+ }++ // Subscribe to all position symbols once+ const subscribeToPositions = async () => {+ console.log(`[StockBrokerContext] Subscribing to ${positions.length} position symbols...`);+ for (const pos of positions) {+ try {+ await adapter.subscribe(pos.symbol, pos.exchange, 'quote');+ } catch (err) {+ console.warn(`[StockBrokerContext] Failed to subscribe to ${pos.symbol}:`, err);+ }+ }+ };++ subscribeToPositions();+ }, [positions.map(p => p.symbol).join(','), tradingMode, adapter]); // Only re-run if symbols change++ // ============================================================================+ // MCP BRIDGE INTEGRATION+ // ============================================================================++ useEffect(() => {+ // Connect stock broker adapter to MCP bridge for AI-controlled trading+ if (adapter && isAuthenticated && activeBroker) {+ import('@/services/mcp/internal').then(({ stockBrokerMCPBridge }) => {+ stockBrokerMCPBridge.connect({+ activeAdapter: adapter,+ tradingMode,+ activeBroker,+ isAuthenticated,+ });++ console.log(`[StockBrokerContext] Connected to MCP bridge: ${activeBroker} (${tradingMode} mode)`);+ });++ return () => {+ import('@/services/mcp/internal').then(({ stockBrokerMCPBridge }) => {+ stockBrokerMCPBridge.disconnect();+ console.log('[StockBrokerContext] Disconnected from MCP bridge');+ });+ };+ }+ }, [adapter, isAuthenticated, activeBroker, tradingMode]);+// ============================================================================// ERROR HANDLING// ============================================================================diff --git a/fincept-terminal-desktop/src/contexts/stockBrokerAuthState.ts b/fincept-terminal-desktop/src/contexts/stockBrokerAuthState.tsnew file mode 100644index 000000000..d73c4f722--- /dev/null+++ b/fincept-terminal-desktop/src/contexts/stockBrokerAuthState.ts@@ -0,0 +1,200 @@+/**+ * Stock Broker Auth State Machine+ *+ * Atomic state transitions for broker authentication.+ * Prevents race conditions by bundling related state updates.+ */++import type { IStockBrokerAdapter } from '@/brokers/stocks/types';++// ============================================================================+// STATE TYPES+// ============================================================================++export type AuthStatus =+ | 'idle' // No broker selected+ | 'initializing' // Loading credentials from DB+ | 'connecting' // Attempting to authenticate+ | 'authenticated' // Successfully connected+ | 'error' // Authentication failed+ | 'disconnecting'; // Logging out++export interface AuthState {+ status: AuthStatus;+ brokerId: string | null;+ adapter: IStockBrokerAdapter | null;+ error: string | null;+ timestamp: number;+}++// ============================================================================+// ACTIONS+// ============================================================================++export type AuthAction =+ | { type: 'SELECT_BROKER'; brokerId: string }+ | { type: 'INIT_START' }+ | { type: 'INIT_SUCCESS'; adapter: IStockBrokerAdapter }+ | { type: 'INIT_FAILURE'; error: string }+ | { type: 'CONNECT_START' }+ | { type: 'CONNECT_SUCCESS'; adapter: IStockBrokerAdapter }+ | { type: 'CONNECT_FAILURE'; error: string }+ | { type: 'DISCONNECT_START' }+ | { type: 'DISCONNECT_COMPLETE' }+ | { type: 'CLEAR_ERROR' }+ | { type: 'RESET' };++// ============================================================================+// INITIAL STATE+// ============================================================================++export const initialAuthState: AuthState = {+ status: 'idle',+ brokerId: null,+ adapter: null,+ error: null,+ timestamp: 0,+};++// ============================================================================+// REDUCER+// ============================================================================++export function authReducer(state: AuthState, action: AuthAction): AuthState {+ const timestamp = Date.now();++ switch (action.type) {+ case 'SELECT_BROKER':+ return {+ ...state,+ brokerId: action.brokerId,+ status: 'idle',+ adapter: null,+ error: null,+ timestamp,+ };++ case 'INIT_START':+ return {+ ...state,+ status: 'initializing',+ error: null,+ timestamp,+ };++ case 'INIT_SUCCESS':+ return {+ ...state,+ status: 'authenticated',+ adapter: action.adapter,+ error: null,+ timestamp,+ };++ case 'INIT_FAILURE':+ return {+ ...state,+ status: 'error',+ adapter: null,+ error: action.error,+ timestamp,+ };++ case 'CONNECT_START':+ return {+ ...state,+ status: 'connecting',+ error: null,+ timestamp,+ };++ case 'CONNECT_SUCCESS':+ return {+ ...state,+ status: 'authenticated',+ adapter: action.adapter,+ error: null,+ timestamp,+ };++ case 'CONNECT_FAILURE':+ return {+ ...state,+ status: 'error',+ error: action.error,+ timestamp,+ };++ case 'DISCONNECT_START':+ return {+ ...state,+ status: 'disconnecting',+ timestamp,+ };++ case 'DISCONNECT_COMPLETE':+ return {+ ...state,+ status: 'idle',+ adapter: null,+ error: null,+ timestamp,+ };++ case 'CLEAR_ERROR':+ return {+ ...state,+ error: null,+ status: state.adapter ? 'authenticated' : 'idle',+ timestamp,+ };++ case 'RESET':+ return {+ ...initialAuthState,+ timestamp,+ };++ default:+ return state;+ }+}++// ============================================================================+// SELECTORS+// ============================================================================++export const authSelectors = {+ isAuthenticated: (state: AuthState): boolean =>+ state.status === 'authenticated' && state.adapter !== null,++ isLoading: (state: AuthState): boolean =>+ state.status === 'initializing' || state.status === 'connecting',++ isIdle: (state: AuthState): boolean =>+ state.status === 'idle',++ hasError: (state: AuthState): boolean =>+ state.status === 'error' && state.error !== null,++ canConnect: (state: AuthState): boolean =>+ state.brokerId !== null && (state.status === 'idle' || state.status === 'error'),+};++// ============================================================================+// STATE MACHINE VALIDATION+// ============================================================================++const validTransitions: Record<AuthStatus, AuthAction['type'][]> = {+ idle: ['SELECT_BROKER', 'INIT_START', 'CONNECT_START', 'RESET'],+ initializing: ['INIT_SUCCESS', 'INIT_FAILURE', 'RESET'],+ connecting: ['CONNECT_SUCCESS', 'CONNECT_FAILURE', 'RESET'],+ authenticated: ['DISCONNECT_START', 'SELECT_BROKER', 'RESET'],+ error: ['CONNECT_START', 'CLEAR_ERROR', 'SELECT_BROKER', 'RESET'],+ disconnecting: ['DISCONNECT_COMPLETE', 'RESET'],+};++export function isValidTransition(state: AuthState, action: AuthAction): boolean {+ const allowedActions = validTransitions[state.status];+ return allowedActions?.includes(action.type) ?? false;+}diff --git a/fincept-terminal-desktop/src/services/chat/llmApi.ts b/fincept-terminal-desktop/src/services/chat/llmApi.tsindex fcba3bd83..3a83547b4 100644--- a/fincept-terminal-desktop/src/services/chat/llmApi.ts+++ b/fincept-terminal-desktop/src/services/chat/llmApi.ts@@ -58,7 +58,8 @@ class LLMApiService {throw new Error(result.error || 'Tool execution failed');}- return result.data;+ // Return full result object (includes chart_data, ticker, company, etc.)+ return result;} else {// External MCP server - use mcpManagerconst { mcpManager } = await import('../mcp/mcpManager');@@ -736,8 +737,16 @@ class LLMApiService {formattedTools.map(t => t.function.name));// Build messages array+ const defaultSystemPrompt = `You are a helpful assistant with access to tools. Use them when appropriate to help the user.++When you use the edgar_get_financials tool, it returns financial data with chart_data containing YoY comparisons. The chart_data includes:+- revenue, net_income, total_assets, total_equity with historical periods+- growth metrics showing YoY percentage changes++Mention the year-over-year growth percentages when discussing financial performance to provide meaningful context.`;+const messages: ChatMessage[] = [- { role: 'system', content: config.systemPrompt || 'You are a helpful assistant with access to tools. Use them when appropriate to help the user.' },+ { role: 'system', content: config.systemPrompt || defaultSystemPrompt },...conversationHistory,{ role: 'user', content: userMessage }];@@ -1068,7 +1077,27 @@ class LLMApiService {const result = await this.executeMCPTool(serverId, toolName, args);console.log('[Fincept Tools] Tool result:', result);onToolCall?.(toolName, args, result);- toolResults += `\n**Tool: ${toolName}**\nResult: ${JSON.stringify(result, null, 2)}\n`;++ // Extract the most relevant content from result+ let resultContent = '';+ if (result.content) {+ resultContent = result.content;+ } else if (result.data && typeof result.data === 'string') {+ resultContent = result.data;+ } else if (result.data?.markdown) {+ resultContent = result.data.markdown;+ } else if (result.markdown) {+ resultContent = result.markdown;+ } else if (result.message) {+ resultContent = result.message;+ } else if (result.data) {+ // Fallback: stringify data but limit size+ resultContent = JSON.stringify(result.data, null, 2).slice(0, 2000);+ } else {+ resultContent = JSON.stringify(result, null, 2).slice(0, 2000);+ }++ toolResults += `\n**Tool: ${toolName}**\n${resultContent}\n`;} catch (toolError) {console.error('[Fincept Tools] Tool error:', toolError);toolResults += `\n**Tool: ${toolName}**\nError: ${toolError instanceof Error ? toolError.message : 'Unknown error'}\n`;@@ -1080,8 +1109,10 @@ class LLMApiService {if (toolResults) {console.log('[Fincept Tools] Sending tool results back to LLM for formatting');- // Build new prompt with tool results- const newPrompt = `${fullPrompt}\n\nAssistant: I used the following tools:\n${toolResults}\n\nNow I'll provide a natural language summary based on these results.`;+ // Build SIMPLE prompt with ONLY the user's last question and tool results+ // No full history needed - just format the data+ const userQuestion = messages[messages.length - 1]?.content || 'Please summarize the data';+ const newPrompt = `User asked: "${userQuestion}"\n\nI retrieved this data:\n${toolResults}\n\nPlease provide a clear, concise summary of this data in natural language.`;const followUpBody = {prompt: newPrompt,diff --git a/fincept-terminal-desktop/src/services/core/sqliteService.ts b/fincept-terminal-desktop/src/services/core/sqliteService.tsindex 527796955..4e8030ab3 100644--- a/fincept-terminal-desktop/src/services/core/sqliteService.ts+++ b/fincept-terminal-desktop/src/services/core/sqliteService.ts@@ -352,6 +352,20 @@ export interface ChatMessage {provider?: string;model?: string;tokens_used?: number;+ tool_calls?: ToolCall[];+ metadata?: {+ chart_data?: any;+ ticker?: string;+ company?: string;+ };+}++export interface ToolCall {+ name: string;+ args: any;+ result?: any;+ timestamp: string;+ status: 'calling' | 'success' | 'error';}export const createChatSession = async (title: string): Promise<ChatSession> => {diff --git a/fincept-terminal-desktop/src/services/maAnalyticsService.ts b/fincept-terminal-desktop/src/services/maAnalyticsService.tsnew file mode 100644index 000000000..57ac2c703--- /dev/null+++ b/fincept-terminal-desktop/src/services/maAnalyticsService.ts@@ -0,0 +1,977 @@+/**+ * M&A Analytics Service - Bloomberg FA Replacement System+ *+ * Complete M&A and Financial Advisory toolkit covering:+ * - Deal Database & SEC Filing Scanner+ * - Valuation Analysis (DCF, Comps, Precedent Transactions)+ * - Merger Models (Accretion/Dilution, Pro Forma)+ * - LBO Models+ * - Startup Valuation (5 methods)+ * - Deal Structure (Payment, Earnout, CVR, Collar)+ * - Synergies (Revenue & Cost)+ * - Fairness Opinions+ * - Industry-Specific Metrics (Tech, Healthcare, Financial Services)+ * - Advanced Analytics (Monte Carlo, Regression)+ * - Deal Comparison & Benchmarking+ */++import { invoke } from '@tauri-apps/api/core';++// =============================================================================+// TYPES+// =============================================================================++export interface MADeal {+ deal_id: string;+ target_name: string;+ acquirer_name: string;+ deal_value: number;+ offer_price_per_share?: number;+ premium_1day: number;+ payment_cash_pct: number;+ payment_stock_pct: number;+ ev_revenue?: number;+ ev_ebitda?: number;+ synergies?: number;+ status: string;+ industry: string;+ announced_date: string;+}++export interface ValuationResult {+ method: string;+ valuation: number;+ range?: { min: number; max: number };+ assumptions: Record<string, any>;+ sensitivity?: any;+}++export interface DCFInputs {+ wacc_inputs: {+ risk_free_rate: number;+ market_risk_premium: number;+ beta: number;+ cost_of_debt: number;+ tax_rate: number;+ market_value_equity: number;+ market_value_debt: number;+ };+ fcf_inputs: {+ ebit: number;+ tax_rate: number;+ depreciation: number;+ capex: number;+ change_in_nwc: number;+ };+ growth_rates: number[];+ terminal_growth: number;+ balance_sheet: {+ cash: number;+ debt: number;+ minority_interest?: number;+ preferred_stock?: number;+ };+ shares_outstanding: number;+}++export interface MergerModelInputs {+ acquirer_data: {+ revenue: number;+ ebitda: number;+ ebit: number;+ net_income: number;+ shares_outstanding: number;+ eps: number;+ market_cap: number;+ };+ target_data: {+ revenue: number;+ ebitda: number;+ ebit: number;+ net_income: number;+ shares_outstanding: number;+ eps: number;+ market_cap: number;+ };+ deal_structure: {+ purchase_price: number;+ payment_cash_pct: number;+ payment_stock_pct: number;+ exchange_ratio?: number;+ };+}++export interface LBOInputs {+ company_data: {+ revenue: number;+ ebitda: number;+ ebit: number;+ capex: number;+ nwc: number;+ };+ transaction_assumptions: {+ purchase_price: number;+ entry_multiple: number;+ exit_multiple: number;+ debt_percent: number;+ equity_percent: number;+ };+ projection_years: number;+}++export interface StartupValuationInputs {+ startup_name: string;+ berkus_scores?: Record<string, number>;+ scorecard_inputs?: {+ stage: string;+ region: string;+ assessments: Record<string, number>;+ };+ vc_inputs?: {+ exit_year_metric: number;+ exit_multiple: number;+ years_to_exit: number;+ investment_amount: number;+ stage: string;+ };+ first_chicago_scenarios?: Array<{+ name: string;+ probability: number;+ exit_year: number;+ exit_value: number;+ description: string;+ }>;+ risk_factor_assessments?: Record<string, number>;+}++export interface SynergyInputs {+ revenue_synergies?: {+ type: string;+ params: Record<string, any>;+ };+ cost_synergies?: {+ type: string;+ params: Record<string, any>;+ };+ integration_costs?: {+ deal_size: number;+ complexity_level: string;+ integration_plan: Record<string, any>;+ };+}++export interface FairnessOpinionInputs {+ valuation_methods: ValuationResult[];+ offer_price: number;+ qualitative_factors: string[];+ daily_prices?: number[];+ announcement_date?: number;+}++// =============================================================================+// DEAL DATABASE OPERATIONS+// =============================================================================++export class DealDatabaseService {+ /**+ * Scan SEC filings for M&A activity+ */+ static async scanFilings(+ daysBack: number = 30,+ filingTypes?: string[]+ ): Promise<any> {+ return invoke('scan_ma_filings', {+ daysBack,+ filingTypes: filingTypes ? JSON.stringify(filingTypes) : undefined,+ });+ }++ /**+ * Parse a specific SEC filing for deal details+ */+ static async parseFiling(+ filingUrl: string,+ filingType: string+ ): Promise<any> {+ return invoke('parse_ma_filing', {+ filingUrl,+ filingType,+ });+ }++ /**+ * Create a new M&A deal in database+ */+ static async createDeal(dealData: Partial<MADeal>): Promise<any> {+ return invoke('create_ma_deal', {+ dealData: JSON.stringify(dealData),+ });+ }++ /**+ * Get all M&A deals with optional filters+ */+ static async getAllDeals(filters?: Record<string, any>): Promise<MADeal[]> {+ const result = await invoke('get_all_ma_deals', {+ filters: filters ? JSON.stringify(filters) : undefined,+ });+ return JSON.parse(result as string);+ }++ /**+ * Search M&A deals by query+ */+ static async searchDeals(+ query: string,+ searchType?: 'target' | 'acquirer' | 'industry'+ ): Promise<MADeal[]> {+ const result = await invoke('search_ma_deals', {+ query,+ searchType,+ });+ return JSON.parse(result as string);+ }++ /**+ * Update an existing deal+ */+ static async updateDeal(+ dealId: string,+ updates: Partial<MADeal>+ ): Promise<any> {+ return invoke('update_ma_deal', {+ dealId,+ updates: JSON.stringify(updates),+ });+ }+}++// =============================================================================+// VALUATION ANALYSIS+// =============================================================================++export class ValuationService {+ /**+ * Calculate valuation using precedent transactions+ */+ static async calculatePrecedentTransactions(+ targetData: Record<string, any>,+ compDeals: MADeal[]+ ): Promise<ValuationResult> {+ const result = await invoke('calculate_precedent_transactions', {+ targetData: JSON.stringify(targetData),+ compDeals: JSON.stringify(compDeals),+ });+ return JSON.parse(result as string);+ }++ /**+ * Calculate trading comps valuation+ */+ static async calculateTradingComps(+ targetTicker: string,+ compTickers: string[]+ ): Promise<ValuationResult> {+ const result = await invoke('calculate_trading_comps', {+ targetTicker,+ compTickers: JSON.stringify(compTickers),+ });+ return JSON.parse(result as string);+ }++ /**+ * Run comprehensive DCF valuation+ */+ static async calculateDCF(inputs: DCFInputs): Promise<any> {+ const result = await invoke('calculate_ma_dcf', {+ waccInputs: JSON.stringify(inputs.wacc_inputs),+ fcfInputs: JSON.stringify(inputs.fcf_inputs),+ growthRates: JSON.stringify(inputs.growth_rates),+ terminalGrowth: inputs.terminal_growth,+ balanceSheet: JSON.stringify(inputs.balance_sheet),+ sharesOutstanding: inputs.shares_outstanding,+ });+ return JSON.parse(result as string);+ }++ /**+ * Calculate DCF sensitivity analysis+ */+ static async calculateDCFSensitivity(+ baseFcf: number,+ growthRates: number[],+ terminalGrowthScenarios: number[],+ waccScenarios: number[],+ balanceSheet: Record<string, number>,+ sharesOutstanding: number+ ): Promise<any> {+ const result = await invoke('calculate_dcf_sensitivity', {+ baseFcf,+ growthRates: JSON.stringify(growthRates),+ terminalGrowthScenarios: JSON.stringify(terminalGrowthScenarios),+ waccScenarios: JSON.stringify(waccScenarios),+ balanceSheet: JSON.stringify(balanceSheet),+ sharesOutstanding,+ });+ return JSON.parse(result as string);+ }++ /**+ * Generate football field chart+ */+ static async generateFootballField(+ valuationMethods: ValuationResult[],+ sharesOutstanding: number+ ): Promise<any> {+ const result = await invoke('generate_football_field', {+ valuationMethods: JSON.stringify(valuationMethods),+ sharesOutstanding,+ });+ return JSON.parse(result as string);+ }+}++// =============================================================================+// MERGER MODELS+// =============================================================================++export class MergerModelService {+ /**+ * Build complete merger model+ */+ static async buildMergerModel(inputs: MergerModelInputs): Promise<any> {+ const result = await invoke('build_merger_model', {+ acquirerData: JSON.stringify(inputs.acquirer_data),+ targetData: JSON.stringify(inputs.target_data),+ dealStructure: JSON.stringify(inputs.deal_structure),+ });+ return JSON.parse(result as string);+ }++ /**+ * Calculate accretion/dilution analysis+ */+ static async calculateAccretionDilution(+ mergerModelData: Record<string, any>+ ): Promise<any> {+ const result = await invoke('calculate_accretion_dilution', {+ mergerModelData: JSON.stringify(mergerModelData),+ });+ return JSON.parse(result as string);+ }++ /**+ * Build pro forma financials+ */+ static async buildProForma(+ acquirerData: Record<string, any>,+ targetData: Record<string, any>,+ year: number+ ): Promise<any> {+ const result = await invoke('build_pro_forma', {+ acquirerData: JSON.stringify(acquirerData),+ targetData: JSON.stringify(targetData),+ year,+ });+ return JSON.parse(result as string);+ }++ /**+ * Calculate sources and uses of funds+ */+ static async calculateSourcesUses(+ dealStructure: Record<string, any>,+ financingStructure: Record<string, any>+ ): Promise<any> {+ const result = await invoke('calculate_sources_uses', {+ dealStructure: JSON.stringify(dealStructure),+ financingStructure: JSON.stringify(financingStructure),+ });+ return JSON.parse(result as string);+ }++ /**+ * Analyze contribution analysis+ */+ static async analyzeContribution(+ acquirerData: Record<string, any>,+ targetData: Record<string, any>,+ ownershipSplit: number+ ): Promise<any> {+ const result = await invoke('analyze_contribution', {+ acquirerData: JSON.stringify(acquirerData),+ targetData: JSON.stringify(targetData),+ ownershipSplit,+ });+ return JSON.parse(result as string);+ }+}++// =============================================================================+// LBO MODELS+// =============================================================================++export class LBOModelService {+ /**+ * Build complete LBO model+ */+ static async buildLBOModel(inputs: LBOInputs): Promise<any> {+ const result = await invoke('build_lbo_model', {+ companyData: JSON.stringify(inputs.company_data),+ transactionAssumptions: JSON.stringify(inputs.transaction_assumptions),+ projectionYears: inputs.projection_years,+ });+ return JSON.parse(result as string);+ }++ /**+ * Calculate LBO returns (IRR, MOIC)+ */+ static async calculateLBOReturns(+ entryValuation: number,+ exitValuation: number,+ equityInvested: number,+ holdingPeriod: number+ ): Promise<any> {+ const result = await invoke('calculate_lbo_returns', {+ entryValuation,+ exitValuation,+ equityInvested,+ holdingPeriod,+ });+ return JSON.parse(result as string);+ }++ /**+ * Analyze LBO debt schedule+ */+ static async analyzeDebtSchedule(+ debtStructure: Record<string, any>,+ cashFlows: Record<string, any>,+ sweepPercentage: number+ ): Promise<any> {+ const result = await invoke('analyze_lbo_debt_schedule', {+ debtStructure: JSON.stringify(debtStructure),+ cashFlows: JSON.stringify(cashFlows),+ sweepPercentage,+ });+ return JSON.parse(result as string);+ }++ /**+ * Calculate LBO sensitivity analysis+ */+ static async calculateLBOSensitivity(+ baseCase: Record<string, any>,+ revenueGrowthScenarios: number[],+ exitMultipleScenarios: number[]+ ): Promise<any> {+ const result = await invoke('calculate_lbo_sensitivity', {+ baseCase: JSON.stringify(baseCase),+ revenueGrowthScenarios: JSON.stringify(revenueGrowthScenarios),+ exitMultipleScenarios: JSON.stringify(exitMultipleScenarios),+ });+ return JSON.parse(result as string);+ }+}++// =============================================================================+// STARTUP VALUATION+// =============================================================================++export class StartupValuationService {+ /**+ * Calculate Berkus Method valuation+ */+ static async calculateBerkusValuation(+ factorScores: Record<string, number>+ ): Promise<any> {+ const result = await invoke('calculate_berkus_valuation', {+ factorScores: JSON.stringify(factorScores),+ });+ return JSON.parse(result as string);+ }++ /**+ * Calculate Scorecard Method valuation+ */+ static async calculateScorecardValuation(+ stage: string,+ region: string,+ factorAssessments: Record<string, number>+ ): Promise<any> {+ const result = await invoke('calculate_scorecard_valuation', {+ stage,+ region,+ factorAssessments: JSON.stringify(factorAssessments),+ });+ return JSON.parse(result as string);+ }++ /**+ * Calculate VC Method valuation+ */+ static async calculateVCMethodValuation(+ exitYearMetric: number,+ exitMultiple: number,+ yearsToExit: number,+ investmentAmount: number,+ stage: string+ ): Promise<any> {+ const result = await invoke('calculate_vc_method_valuation', {+ exitYearMetric,+ exitMultiple,+ yearsToExit,+ investmentAmount,+ stage,+ });+ return JSON.parse(result as string);+ }++ /**+ * Calculate First Chicago Method valuation+ */+ static async calculateFirstChicagoValuation(+ scenarios: Array<{+ name: string;+ probability: number;+ exit_year: number;+ exit_value: number;+ description: string;+ }>+ ): Promise<any> {+ const result = await invoke('calculate_first_chicago_valuation', {+ scenarios: JSON.stringify(scenarios),+ });+ return JSON.parse(result as string);+ }++ /**+ * Calculate Risk Factor Summation valuation+ */+ static async calculateRiskFactorValuation(+ baseValuation: number,+ riskAssessments: Record<string, number>+ ): Promise<any> {+ const result = await invoke('calculate_risk_factor_valuation', {+ baseValuation,+ riskAssessments: JSON.stringify(riskAssessments),+ });+ return JSON.parse(result as string);+ }++ /**+ * Comprehensive startup valuation using all methods+ */+ static async comprehensiveStartupValuation(+ inputs: StartupValuationInputs+ ): Promise<any> {+ const result = await invoke('comprehensive_startup_valuation', {+ startupName: inputs.startup_name,+ berkusScores: inputs.berkus_scores ? JSON.stringify(inputs.berkus_scores) : undefined,+ scorecardInputs: inputs.scorecard_inputs ? JSON.stringify(inputs.scorecard_inputs) : undefined,+ vcInputs: inputs.vc_inputs ? JSON.stringify(inputs.vc_inputs) : undefined,+ firstChicagoScenarios: inputs.first_chicago_scenarios+ ? JSON.stringify(inputs.first_chicago_scenarios)+ : undefined,+ riskFactorAssessments: inputs.risk_factor_assessments+ ? JSON.stringify(inputs.risk_factor_assessments)+ : undefined,+ });+ return JSON.parse(result as string);+ }++ /**+ * Quick pre-revenue valuation+ */+ static async quickPreRevenueValuation(+ ideaQuality: number,+ teamQuality: number,+ prototypeStatus: number,+ marketSize: number+ ): Promise<any> {+ const result = await invoke('quick_pre_revenue_valuation', {+ ideaQuality,+ teamQuality,+ prototypeStatus,+ marketSize,+ });+ return JSON.parse(result as string);+ }+}++// =============================================================================+// DEAL STRUCTURE+// =============================================================================++export class DealStructureService {+ /**+ * Analyze payment structure+ */+ static async analyzePaymentStructure(+ purchasePrice: number,+ cashPercentage: number,+ acquirerCash: number,+ debtCapacity: number+ ): Promise<any> {+ const result = await invoke('analyze_payment_structure', {+ purchasePrice,+ cashPercentage,+ acquirerCash,+ debtCapacity,+ });+ return JSON.parse(result as string);+ }++ /**+ * Value earnout provision+ */+ static async valueEarnout(+ earnoutParams: Record<string, any>,+ financialProjections: Record<string, any>+ ): Promise<any> {+ const result = await invoke('value_earnout', {+ earnoutParams: JSON.stringify(earnoutParams),+ financialProjections: JSON.stringify(financialProjections),+ });+ return JSON.parse(result as string);+ }++ /**+ * Calculate exchange ratio+ */+ static async calculateExchangeRatio(+ acquirerPrice: number,+ targetPrice: number,+ offerPremium: number+ ): Promise<any> {+ const result = await invoke('calculate_exchange_ratio', {+ acquirerPrice,+ targetPrice,+ offerPremium,+ });+ return JSON.parse(result as string);+ }++ /**+ * Analyze collar mechanism+ */+ static async analyzeCollarMechanism(+ collarParams: Record<string, any>,+ priceScenarios: Record<string, any>+ ): Promise<any> {+ const result = await invoke('analyze_collar_mechanism', {+ collarParams: JSON.stringify(collarParams),+ priceScenarios: JSON.stringify(priceScenarios),+ });+ return JSON.parse(result as string);+ }++ /**+ * Value Contingent Value Right (CVR)+ */+ static async valueCVR(+ cvrType: string,+ cvrParams: Record<string, any>+ ): Promise<any> {+ const result = await invoke('value_cvr', {+ cvrType,+ cvrParams: JSON.stringify(cvrParams),+ });+ return JSON.parse(result as string);+ }+}++// =============================================================================+// SYNERGIES+// =============================================================================++export class SynergiesService {+ /**+ * Calculate revenue synergies+ */+ static async calculateRevenueSynergies(+ synergyType: string,+ synergyParams: Record<string, any>+ ): Promise<any> {+ const result = await invoke('calculate_revenue_synergies', {+ synergyType,+ synergyParams: JSON.stringify(synergyParams),+ });+ return JSON.parse(result as string);+ }++ /**+ * Calculate cost synergies+ */+ static async calculateCostSynergies(+ synergyType: string,+ synergyParams: Record<string, any>+ ): Promise<any> {+ const result = await invoke('calculate_cost_synergies', {+ synergyType,+ synergyParams: JSON.stringify(synergyParams),+ });+ return JSON.parse(result as string);+ }++ /**+ * Estimate integration costs+ */+ static async estimateIntegrationCosts(+ dealSize: number,+ complexityLevel: string,+ integrationPlan: Record<string, any>+ ): Promise<any> {+ const result = await invoke('estimate_integration_costs', {+ dealSize,+ complexityLevel,+ integrationPlan: JSON.stringify(integrationPlan),+ });+ return JSON.parse(result as string);+ }++ /**+ * Value synergies using DCF+ */+ static async valueSynergiesDCF(+ revenueSynergies: Record<string, any>,+ costSynergies: Record<string, any>,+ integrationCosts: Record<string, any>,+ discountRate: number+ ): Promise<any> {+ const result = await invoke('value_synergies_dcf', {+ revenueSynergies: JSON.stringify(revenueSynergies),+ costSynergies: JSON.stringify(costSynergies),+ integrationCosts: JSON.stringify(integrationCosts),+ discountRate,+ });+ return JSON.parse(result as string);+ }+}++// =============================================================================+// FAIRNESS OPINION+// =============================================================================++export class FairnessOpinionService {+ /**+ * Generate fairness opinion+ */+ static async generateFairnessOpinion(+ inputs: FairnessOpinionInputs+ ): Promise<any> {+ const result = await invoke('generate_fairness_opinion', {+ valuationMethods: JSON.stringify(inputs.valuation_methods),+ offerPrice: inputs.offer_price,+ qualitativeFactors: JSON.stringify(inputs.qualitative_factors),+ });+ return JSON.parse(result as string);+ }++ /**+ * Analyze premium fairness+ */+ static async analyzePremiumFairness(+ dailyPrices: number[],+ offerPrice: number,+ announcementDate?: number+ ): Promise<any> {+ const result = await invoke('analyze_premium_fairness', {+ dailyPrices: JSON.stringify(dailyPrices),+ offerPrice,+ announcementDate,+ });+ return JSON.parse(result as string);+ }++ /**+ * Assess process quality+ */+ static async assessProcessQuality(+ processFactors: Record<string, any>+ ): Promise<any> {+ const result = await invoke('assess_process_quality', {+ processFactors: JSON.stringify(processFactors),+ });+ return JSON.parse(result as string);+ }+}++// =============================================================================+// INDUSTRY METRICS+// =============================================================================++export class IndustryMetricsService {+ /**+ * Calculate technology sector metrics+ */+ static async calculateTechMetrics(+ sector: 'saas' | 'marketplace' | 'semiconductor',+ companyData: Record<string, any>+ ): Promise<any> {+ const result = await invoke('calculate_tech_metrics', {+ sector,+ companyData: JSON.stringify(companyData),+ });+ return JSON.parse(result as string);+ }++ /**+ * Calculate healthcare sector metrics+ */+ static async calculateHealthcareMetrics(+ sector: 'pharma' | 'biotech' | 'devices' | 'services',+ companyData: Record<string, any>+ ): Promise<any> {+ const result = await invoke('calculate_healthcare_metrics', {+ sector,+ companyData: JSON.stringify(companyData),+ });+ return JSON.parse(result as string);+ }++ /**+ * Calculate financial services metrics+ */+ static async calculateFinancialServicesMetrics(+ sector: 'banking' | 'insurance' | 'asset_management',+ institutionData: Record<string, any>+ ): Promise<any> {+ const result = await invoke('calculate_financial_services_metrics', {+ sector,+ institutionData: JSON.stringify(institutionData),+ });+ return JSON.parse(result as string);+ }+}++// =============================================================================+// ADVANCED ANALYTICS+// =============================================================================++export class AdvancedAnalyticsService {+ /**+ * Run Monte Carlo valuation simulation+ */+ static async runMonteCarloValuation(+ baseValuation: number,+ revenueGrowthMean: number,+ revenueGrowthStd: number,+ marginMean: number,+ marginStd: number,+ discountRate: number,+ simulations: number = 10000+ ): Promise<any> {+ const result = await invoke('run_monte_carlo_valuation', {+ baseValuation,+ revenueGrowthMean,+ revenueGrowthStd,+ marginMean,+ marginStd,+ discountRate,+ simulations,+ });+ return JSON.parse(result as string);+ }++ /**+ * Run regression-based valuation+ */+ static async runRegressionValuation(+ compData: Record<string, any>[],+ subjectMetrics: Record<string, any>,+ regressionType: 'ols' | 'multiple'+ ): Promise<any> {+ const result = await invoke('run_regression_valuation', {+ compData: JSON.stringify(compData),+ subjectMetrics: JSON.stringify(subjectMetrics),+ regressionType,+ });+ return JSON.parse(result as string);+ }+}++// =============================================================================+// DEAL COMPARISON+// =============================================================================++export class DealComparisonService {+ /**+ * Compare multiple deals side-by-side+ */+ static async compareDeals(deals: MADeal[]): Promise<any> {+ const result = await invoke('compare_deals', {+ deals: JSON.stringify(deals),+ });+ return JSON.parse(result as string);+ }++ /**+ * Rank deals by criteria+ */+ static async rankDeals(+ deals: MADeal[],+ criteria: 'premium' | 'deal_value' | 'ev_revenue' | 'ev_ebitda' | 'synergies'+ ): Promise<any> {+ const result = await invoke('rank_deals', {+ deals: JSON.stringify(deals),+ criteria,+ });+ return JSON.parse(result as string);+ }++ /**+ * Benchmark deal premium against comparables+ */+ static async benchmarkDealPremium(+ targetDeal: MADeal,+ comparableDeals: MADeal[]+ ): Promise<any> {+ const result = await invoke('benchmark_deal_premium', {+ targetDeal: JSON.stringify(targetDeal),+ comparableDeals: JSON.stringify(comparableDeals),+ });+ return JSON.parse(result as string);+ }++ /**+ * Analyze payment structures across deals+ */+ static async analyzePaymentStructures(deals: MADeal[]): Promise<any> {+ const result = await invoke('analyze_payment_structures', {+ deals: JSON.stringify(deals),+ });+ return JSON.parse(result as string);+ }++ /**+ * Analyze deals by industry+ */+ static async analyzeIndustryDeals(deals: MADeal[]): Promise<any> {+ const result = await invoke('analyze_industry_deals', {+ deals: JSON.stringify(deals),+ });+ return JSON.parse(result as string);+ }+}++// =============================================================================+// UNIFIED SERVICE EXPORT+// =============================================================================++export const MAAnalyticsService = {+ DealDatabase: DealDatabaseService,+ Valuation: ValuationService,+ MergerModel: MergerModelService,+ LBO: LBOModelService,+ StartupValuation: StartupValuationService,+ DealStructure: DealStructureService,+ Synergies: SynergiesService,+ FairnessOpinion: FairnessOpinionService,+ IndustryMetrics: IndustryMetricsService,+ AdvancedAnalytics: AdvancedAnalyticsService,+ DealComparison: DealComparisonService,+};++export default MAAnalyticsService;diff --git a/fincept-terminal-desktop/src/services/mcp/internal/NodeEditorMCPBridge.ts b/fincept-terminal-desktop/src/services/mcp/internal/NodeEditorMCPBridge.tsnew file mode 100644index 000000000..62ed22739--- /dev/null+++ b/fincept-terminal-desktop/src/services/mcp/internal/NodeEditorMCPBridge.ts@@ -0,0 +1,962 @@+/**+ * Node Editor MCP Bridge+ *+ * Connects the MCP tool contexts to the actual Node Editor system.+ * Provides the implementation for all node editor MCP operations.+ */++import { terminalMCPProvider } from './TerminalMCPProvider';+import {+ TerminalContexts,+ NodeTypeInfo,+ NodeTypeDetails,+ NodeCategoryInfo,+ CreateWorkflowParams,+ AddNodeParams,+ ConnectNodesParams,+ ConfigureNodeParams,+ UpdateWorkflowParams,+ WorkflowInfo,+ WorkflowExecutionResult,+ WorkflowValidation,+ NodePropertyInfo,+} from './types';+import { NodeRegistry } from '@/services/nodeSystem/NodeRegistry';+import { NodeLoader, initializeNodeSystem } from '@/services/nodeSystem/NodeLoader';+import { workflowService } from '@/services/core/workflowService';+import type {+ WorkflowNode,+ WorkflowEdge,+ Workflow,+ WorkflowNodeData,+ BaseNodeData,+ DataSourceNodeData,+ TechnicalIndicatorNodeData,+ PythonAgentNodeData,+ MCPToolNodeData,+ ResultsDisplayNodeData,+ AgentMediatorNodeData,+} from '@/types/workflow';++/**+ * Category metadata for better descriptions+ */+const CATEGORY_METADATA: Record<string, { displayName: string; description: string; icon: string; color: string }> = {+ trigger: {+ displayName: 'Triggers',+ description: 'Workflow entry points - manual, scheduled, price alerts, market events',+ icon: 'Zap',+ color: '#a855f7',+ },+ marketData: {+ displayName: 'Market Data',+ description: 'Fetch real-time and historical market data from various sources',+ icon: 'Activity',+ color: '#22c55e',+ },+ trading: {+ displayName: 'Trading',+ description: 'Execute and manage trades - orders, positions, balance',+ icon: 'TrendingUp',+ color: '#14b8a6',+ },+ analytics: {+ displayName: 'Analytics',+ description: 'Financial analysis - technical indicators, portfolio optimization, backtesting',+ icon: 'BarChart2',+ color: '#06b6d4',+ },+ controlFlow: {+ displayName: 'Control Flow',+ description: 'Workflow logic - conditions, loops, branching, merging',+ icon: 'GitBranch',+ color: '#eab308',+ },+ transform: {+ displayName: 'Transform',+ description: 'Data manipulation - filter, map, aggregate, sort, join',+ icon: 'Filter',+ color: '#ec4899',+ },+ safety: {+ displayName: 'Safety',+ description: 'Risk management - position limits, loss limits, trading hours',+ icon: 'Shield',+ color: '#ef4444',+ },+ notifications: {+ displayName: 'Notifications',+ description: 'Send alerts - email, Telegram, Discord, Slack, SMS, webhooks',+ icon: 'Bell',+ color: '#f97316',+ },+ agents: {+ displayName: 'AI Agents',+ description: 'AI-powered analysis - investor personas, geopolitics, hedge fund strategies',+ icon: 'Brain',+ color: '#8b5cf6',+ },+ core: {+ displayName: 'Core',+ description: 'Basic workflow operations - filter, merge, set, switch, code',+ icon: 'Workflow',+ color: '#6b7280',+ },+};++/**+ * Map node group names to our categories+ */+function mapGroupToCategory(groups: string[] | undefined): string {+ if (!groups || !Array.isArray(groups) || groups.length === 0) {+ return 'core';+ }+ const groupLower = groups.map(g => (g || '').toLowerCase());++ if (groupLower.some(g => g.includes('trigger'))) return 'trigger';+ if (groupLower.some(g => g.includes('market') || g.includes('data') || g.includes('yfinance'))) return 'marketData';+ if (groupLower.some(g => g.includes('trading') || g.includes('order') || g.includes('position'))) return 'trading';+ if (groupLower.some(g => g.includes('analytic') || g.includes('indicator') || g.includes('backtest'))) return 'analytics';+ if (groupLower.some(g => g.includes('control') || g.includes('flow') || g.includes('logic'))) return 'controlFlow';+ if (groupLower.some(g => g.includes('transform') || g.includes('filter') || g.includes('map'))) return 'transform';+ if (groupLower.some(g => g.includes('safety') || g.includes('risk'))) return 'safety';+ if (groupLower.some(g => g.includes('notification') || g.includes('alert') || g.includes('message'))) return 'notifications';+ if (groupLower.some(g => g.includes('agent') || g.includes('ai'))) return 'agents';++ return 'core';+}++/**+ * NodeEditorMCPBridge Class+ * Singleton that provides the bridge between MCP and the Node Editor+ */+class NodeEditorMCPBridgeClass {+ private initialized = false;+ private navigateToTab?: (tab: string) => void;+ private loadWorkflowInEditor?: (workflowId: string) => void;++ /**+ * Initialize the bridge and inject contexts+ */+ async initialize(): Promise<void> {+ if (this.initialized) {+ return;+ }++ // Ensure node system is loaded+ if (!NodeLoader.isLoaded()) {+ await initializeNodeSystem();+ }++ // Build and inject contexts+ this.injectContexts();+ this.initialized = true;+ console.log('[NodeEditorMCPBridge] Initialized with node editor contexts');+ }++ /**+ * Set navigation callback (called from React component)+ */+ setNavigationCallback(navigate: (tab: string) => void): void {+ this.navigateToTab = navigate;+ // Re-inject contexts with updated navigation+ if (this.initialized) {+ this.injectContexts();+ }+ }++ /**+ * Set workflow loader callback (called from NodeEditorTab)+ */+ setWorkflowLoaderCallback(loader: (workflowId: string) => void): void {+ this.loadWorkflowInEditor = loader;+ if (this.initialized) {+ this.injectContexts();+ }+ }++ /**+ * Inject all node editor contexts into the MCP provider+ */+ private injectContexts(): void {+ const contexts: Partial<TerminalContexts> = {+ // Node Discovery+ listAvailableNodes: this.listAvailableNodes.bind(this),+ getNodeDetails: this.getNodeDetails.bind(this),+ getNodeCategories: this.getNodeCategories.bind(this),++ // Workflow Creation+ createNodeWorkflow: this.createNodeWorkflow.bind(this),+ addNodeToWorkflow: this.addNodeToWorkflow.bind(this),+ connectNodes: this.connectNodes.bind(this),+ configureNode: this.configureNode.bind(this),++ // Workflow Management+ listNodeWorkflows: this.listNodeWorkflows.bind(this),+ getNodeWorkflow: this.getNodeWorkflow.bind(this),+ updateNodeWorkflow: this.updateNodeWorkflow.bind(this),+ deleteNodeWorkflow: this.deleteNodeWorkflow.bind(this),+ duplicateNodeWorkflow: this.duplicateNodeWorkflow.bind(this),++ // Workflow Execution+ executeNodeWorkflow: this.executeNodeWorkflow.bind(this),+ stopNodeWorkflow: this.stopNodeWorkflow.bind(this),+ getWorkflowResults: this.getWorkflowResults.bind(this),+ validateNodeWorkflow: this.validateNodeWorkflow.bind(this),++ // Helpers+ openWorkflowInEditor: this.openWorkflowInEditor.bind(this),+ exportNodeWorkflow: this.exportNodeWorkflow.bind(this),+ importNodeWorkflow: this.importNodeWorkflow.bind(this),+ };++ terminalMCPProvider.setContexts(contexts);+ }++ // ============================================================================+ // NODE DISCOVERY METHODS+ // ============================================================================++ async listAvailableNodes(category?: string, search?: string): Promise<NodeTypeInfo[]> {+ let nodes = NodeRegistry.getAllNodes() || [];++ // Filter by category+ if (category && nodes.length > 0) {+ nodes = nodes.filter(node => {+ const nodeCategory = mapGroupToCategory(node.group);+ return nodeCategory === category;+ });+ }++ // Filter by search+ if (search && nodes.length > 0) {+ const searchLower = search.toLowerCase();+ nodes = nodes.filter(node =>+ node.name?.toLowerCase().includes(searchLower) ||+ node.displayName?.toLowerCase().includes(searchLower) ||+ node.description?.toLowerCase().includes(searchLower)+ );+ }++ return nodes.map(node => ({+ name: node.name,+ displayName: node.displayName,+ description: node.description,+ category: mapGroupToCategory(node.group),+ icon: node.icon,+ color: node.defaults?.color,+ inputs: Array.isArray(node.inputs) ? node.inputs.map(i => typeof i === 'string' ? i : 'main') : ['main'],+ outputs: Array.isArray(node.outputs)+ ? node.outputs.map(o => typeof o === 'string' ? o : (o as any).type || 'main')+ : ['main'],+ }));+ }++ async getNodeDetails(nodeType: string): Promise<NodeTypeDetails | null> {+ try {+ const description = NodeRegistry.getNodeTypeDescription(nodeType);+ if (!description) return null;++ const properties: NodePropertyInfo[] = (description.properties || []).map(prop => ({+ name: prop.name,+ displayName: prop.displayName,+ type: prop.type,+ default: prop.default,+ description: prop.description,+ required: prop.required,+ options: prop.options && Array.isArray(prop.options)+ ? prop.options.map((opt: any) => ({+ name: opt.name || opt.displayName || String(opt.value),+ value: opt.value,+ description: opt.description,+ }))+ : undefined,+ }));++ return {+ name: description.name,+ displayName: description.displayName,+ description: description.description,+ category: mapGroupToCategory(description.group),+ icon: description.icon,+ color: description.defaults?.color,+ inputs: Array.isArray(description.inputs) ? description.inputs.map(i => typeof i === 'string' ? i : 'main') : ['main'],+ outputs: Array.isArray(description.outputs)+ ? description.outputs.map(o => typeof o === 'string' ? o : (o as any).type || 'main')+ : ['main'],+ version: Array.isArray(description.version) ? description.version[0] : description.version,+ properties,+ hints: description.hints?.map(h => h.message),+ usableAsTool: description.usableAsTool,+ };+ } catch {+ return null;+ }+ }++ async getNodeCategories(): Promise<NodeCategoryInfo[]> {+ const allNodes = NodeRegistry.getAllNodes() || [];+ const categoryCounts: Record<string, number> = {};++ // Count nodes per category+ for (const node of allNodes) {+ const category = mapGroupToCategory(node.group);+ categoryCounts[category] = (categoryCounts[category] || 0) + 1;+ }++ // Build category info with metadata+ return Object.entries(CATEGORY_METADATA).map(([name, meta]) => ({+ name,+ displayName: meta.displayName,+ description: meta.description,+ nodeCount: categoryCounts[name] || 0,+ icon: meta.icon,+ color: meta.color,+ }));+ }++ // ============================================================================+ // WORKFLOW CREATION METHODS+ // ============================================================================++ async createNodeWorkflow(params: CreateWorkflowParams): Promise<WorkflowInfo> {+ const id = `workflow_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;++ // Convert input nodes to WorkflowNode format with proper ReactFlow data structure+ // This handles both UI types (data-source, system, etc.) and backend types (yfinance, manualTrigger, etc.)+ const nodes: WorkflowNode[] = (params.nodes || []).map(n => {+ // Map the provided type to proper UI type+ const uiType = this.mapToUINodeType(n.type || 'custom');+ const backendType = n.parameters?.nodeType || n.type;++ return {+ id: n.id,+ type: uiType,+ position: n.position,+ data: this.createNodeData(+ uiType,+ backendType,+ n.label || n.type || 'Node',+ n.parameters || {}+ ),+ };+ });++ // Convert input edges to WorkflowEdge format with proper styling+ const edges: WorkflowEdge[] = (params.edges || []).map((e, idx) => ({+ id: `edge_${idx}_${e.source}_${e.target}`,+ source: e.source,+ target: e.target,+ sourceHandle: e.sourceHandle || null,+ targetHandle: e.targetHandle || null,+ animated: true,+ style: { stroke: '#ea580c', strokeWidth: 2 },+ }));++ const workflow: Workflow = {+ id,+ name: params.name,+ description: params.description,+ nodes,+ edges,+ status: 'draft',+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ };++ await workflowService.saveWorkflow(workflow);++ return this.workflowToInfo(workflow);+ }++ /**+ * Get default color for a node type (both UI types and backend types)+ */+ private getNodeColor(nodeType: string): string {+ const colorMap: Record<string, string> = {+ // UI node types+ 'data-source': '#3b82f6',+ 'technical-indicator': '#10b981',+ 'agent-mediator': '#8b5cf6',+ 'results-display': '#f59e0b',+ 'backtest': '#06b6d4',+ 'optimization': '#a855f7',+ 'system': '#10b981',+ 'custom': '#6b7280',+ 'mcp-tool': '#ea580c',+ 'python-agent': '#22c55e',++ // Backend node types mapped to colors+ 'manualTrigger': '#10b981',+ 'scheduleTrigger': '#a855f7',+ 'priceAlertTrigger': '#f97316',+ 'newsEventTrigger': '#f97316',+ 'marketEventTrigger': '#f97316',+ 'webhookTrigger': '#f97316',+ 'yfinance': '#3b82f6',+ 'getQuote': '#3b82f6',+ 'getHistoricalData': '#3b82f6',+ 'getMarketDepth': '#3b82f6',+ 'streamQuotes': '#3b82f6',+ 'getFundamentals': '#3b82f6',+ 'getTickerStats': '#3b82f6',+ 'stockData': '#3b82f6',+ 'technicalIndicators': '#10b981',+ 'placeOrder': '#14b8a6',+ 'modifyOrder': '#14b8a6',+ 'cancelOrder': '#14b8a6',+ 'getPositions': '#14b8a6',+ 'getHoldings': '#14b8a6',+ 'getOrders': '#14b8a6',+ 'getBalance': '#14b8a6',+ 'closePosition': '#14b8a6',+ 'portfolioOptimization': '#06b6d4',+ 'backtestEngine': '#06b6d4',+ 'riskAnalysis': '#06b6d4',+ 'performanceMetrics': '#06b6d4',+ 'correlationMatrix': '#06b6d4',+ 'ifElse': '#eab308',+ 'switch': '#eab308',+ 'loop': '#eab308',+ 'wait': '#eab308',+ 'merge': '#eab308',+ 'split': '#eab308',+ 'errorHandler': '#ef4444',+ 'filterTransform': '#ec4899',+ 'map': '#ec4899',+ 'aggregate': '#ec4899',+ 'sort': '#ec4899',+ 'groupBy': '#ec4899',+ 'join': '#ec4899',+ 'deduplicate': '#ec4899',+ 'reshape': '#ec4899',+ 'riskCheck': '#ef4444',+ 'positionSizeLimit': '#ef4444',+ 'lossLimit': '#ef4444',+ 'tradingHoursCheck': '#ef4444',+ 'webhookNotification': '#f97316',+ 'email': '#f97316',+ 'telegram': '#f97316',+ 'discord': '#f97316',+ 'slack': '#f97316',+ 'sms': '#f97316',+ 'agentMediator': '#8b5cf6',+ 'agent': '#8b5cf6',+ 'multiAgent': '#8b5cf6',+ 'geopoliticsAgent': '#8b5cf6',+ 'hedgeFundAgent': '#8b5cf6',+ 'investorAgent': '#8b5cf6',+ 'filter': '#6b7280',+ 'set': '#6b7280',+ 'code': '#6b7280',+ 'resultsDisplay': '#f59e0b',+ };+ return colorMap[nodeType] || '#6b7280';+ }++ /**+ * Map backend node types to UI component types+ * This is critical for proper rendering in ReactFlow+ */+ private mapToUINodeType(backendType: string): string {+ // Trigger nodes+ if (backendType.includes('Trigger') || backendType === 'manual') {+ return 'system';+ }++ // Data source nodes+ const dataSourceNodes = [+ 'yfinance', 'getQuote', 'getHistoricalData', 'getMarketDepth',+ 'streamQuotes', 'getFundamentals', 'getTickerStats', 'stockData'+ ];+ if (dataSourceNodes.includes(backendType)) {+ return 'data-source';+ }++ // Technical indicator nodes+ if (backendType === 'technicalIndicators' || backendType.includes('indicator')) {+ return 'technical-indicator';+ }++ // Agent nodes+ const agentNodes = [+ 'agentMediator', 'agent', 'multiAgent', 'geopoliticsAgent',+ 'hedgeFundAgent', 'investorAgent'+ ];+ if (agentNodes.includes(backendType)) {+ return 'agent-mediator';+ }++ // Results display+ if (backendType === 'resultsDisplay' || backendType === 'results-display') {+ return 'results-display';+ }++ // Backtest nodes+ if (backendType === 'backtestEngine' || backendType === 'backtest') {+ return 'backtest';+ }++ // Optimization nodes+ if (backendType === 'portfolioOptimization' || backendType === 'optimization') {+ return 'optimization';+ }++ // If it's already a UI type, return as-is+ const uiTypes = [+ 'data-source', 'technical-indicator', 'agent-mediator',+ 'results-display', 'backtest', 'optimization', 'system',+ 'custom', 'mcp-tool', 'python-agent'+ ];+ if (uiTypes.includes(backendType)) {+ return backendType;+ }++ // Default to custom for everything else+ return 'custom';+ }++ /**+ * Create proper ReactFlow node data structure for any node type+ * Returns BaseNodeData compatible structure+ */+ private createNodeData(+ nodeType: string,+ backendType: string,+ label: string,+ parameters: Record<string, any> = {}+ ): WorkflowNodeData {+ const uiType = this.mapToUINodeType(nodeType);+ const color = parameters.color || this.getNodeColor(backendType || nodeType);++ // Determine input/output based on node type+ const hasInput = !['system', 'trigger'].includes(uiType) &&+ !nodeType.includes('Trigger') &&+ !backendType?.includes('Trigger');+ const hasOutput = uiType !== 'results-display';++ // Build base node data that satisfies BaseNodeData interface+ const baseData: BaseNodeData = {+ label: label || backendType || nodeType || 'Node',+ status: 'idle',+ onLabelChange: () => {},+ };++ // Add extra properties based on node type+ // These properties are used by the ReactFlow UI components+ const extendedData = {+ ...baseData,+ color: color,+ nodeType: backendType || nodeType,+ hasInput: hasInput,+ hasOutput: hasOutput,+ ...parameters,+ };++ // Return as proper type based on UI node type+ switch (uiType) {+ case 'data-source':+ return extendedData as DataSourceNodeData;+ case 'technical-indicator':+ return extendedData as TechnicalIndicatorNodeData;+ case 'python-agent':+ return extendedData as PythonAgentNodeData;+ case 'mcp-tool':+ return extendedData as MCPToolNodeData;+ case 'results-display':+ return extendedData as ResultsDisplayNodeData;+ case 'agent-mediator':+ return extendedData as AgentMediatorNodeData;+ default:+ // For custom/system/other types, return as BaseNodeData with extras+ return extendedData as DataSourceNodeData; // DataSourceNodeData is a good default+ }+ }++ async addNodeToWorkflow(params: AddNodeParams): Promise<WorkflowInfo> {+ const workflow = await workflowService.loadWorkflow(params.workflowId);+ if (!workflow) {+ throw new Error(`Workflow '${params.workflowId}' not found`);+ }++ // Map the provided node type to proper UI type+ const uiType = this.mapToUINodeType(params.nodeType);+ const backendType = params.parameters?.nodeType || params.nodeType;++ const newNode: WorkflowNode = {+ id: params.nodeId,+ type: uiType,+ position: params.position,+ data: this.createNodeData(+ uiType,+ backendType,+ params.label || params.nodeType,+ params.parameters || {}+ ),+ };++ // Ensure nodes array exists+ if (!workflow.nodes) {+ workflow.nodes = [];+ }+ workflow.nodes.push(newNode);+ workflow.updatedAt = new Date().toISOString();+ await workflowService.saveWorkflow(workflow);++ return this.workflowToInfo(workflow);+ }++ async connectNodes(params: ConnectNodesParams): Promise<WorkflowInfo> {+ const workflow = await workflowService.loadWorkflow(params.workflowId);+ if (!workflow) {+ throw new Error(`Workflow '${params.workflowId}' not found`);+ }++ const newEdge: WorkflowEdge = {+ id: `edge_${params.sourceNodeId}_${params.targetNodeId}_${Date.now()}`,+ source: params.sourceNodeId,+ target: params.targetNodeId,+ sourceHandle: params.sourceHandle || 'main',+ targetHandle: params.targetHandle || 'main',+ };++ // Ensure edges array exists+ if (!workflow.edges) {+ workflow.edges = [];+ }+ workflow.edges.push(newEdge);+ workflow.updatedAt = new Date().toISOString();+ await workflowService.saveWorkflow(workflow);++ return this.workflowToInfo(workflow);+ }++ async configureNode(params: ConfigureNodeParams): Promise<WorkflowInfo> {+ const workflow = await workflowService.loadWorkflow(params.workflowId);+ if (!workflow) {+ throw new Error(`Workflow '${params.workflowId}' not found`);+ }++ const nodes = workflow.nodes || [];+ const node = nodes.find(n => n.id === params.nodeId);+ if (!node) {+ throw new Error(`Node '${params.nodeId}' not found in workflow`);+ }++ // Merge parameters into node data+ node.data = {+ ...node.data,+ ...params.parameters,+ };++ workflow.updatedAt = new Date().toISOString();+ await workflowService.saveWorkflow(workflow);++ return this.workflowToInfo(workflow);+ }++ // ============================================================================+ // WORKFLOW MANAGEMENT METHODS+ // ============================================================================++ async listNodeWorkflows(status?: string): Promise<WorkflowInfo[]> {+ let workflows = await workflowService.listWorkflows() || [];++ if (status && workflows.length > 0) {+ workflows = workflows.filter(w => w.status === status);+ }++ return workflows.map(w => this.workflowToInfo(w));+ }++ async getNodeWorkflow(workflowId: string): Promise<WorkflowInfo | null> {+ const workflow = await workflowService.loadWorkflow(workflowId);+ return workflow ? this.workflowToInfo(workflow) : null;+ }++ async updateNodeWorkflow(params: UpdateWorkflowParams): Promise<WorkflowInfo> {+ const workflow = await workflowService.loadWorkflow(params.workflowId);+ if (!workflow) {+ throw new Error(`Workflow '${params.workflowId}' not found`);+ }++ if (params.name !== undefined) {+ workflow.name = params.name;+ }+ if (params.description !== undefined) {+ workflow.description = params.description;+ }+ if (params.nodes !== undefined) {+ // Map all nodes to proper UI types with full ReactFlow data structure+ workflow.nodes = (params.nodes || []).map(n => {+ const uiType = this.mapToUINodeType(n.type || 'custom');+ const backendType = n.parameters?.nodeType || n.type;++ return {+ id: n.id,+ type: uiType,+ position: n.position,+ data: this.createNodeData(+ uiType,+ backendType,+ n.label || n.type || 'Node',+ n.parameters || {}+ ),+ };+ });+ }+ if (params.edges !== undefined) {+ workflow.edges = (params.edges || []).map((e, idx) => ({+ id: `edge_${idx}_${e.source}_${e.target}`,+ source: e.source,+ target: e.target,+ sourceHandle: e.sourceHandle || null,+ targetHandle: e.targetHandle || null,+ animated: true,+ style: { stroke: '#ea580c', strokeWidth: 2 },+ }));+ }++ workflow.updatedAt = new Date().toISOString();+ await workflowService.saveWorkflow(workflow);++ return this.workflowToInfo(workflow);+ }++ async deleteNodeWorkflow(workflowId: string): Promise<void> {+ await workflowService.deleteWorkflow(workflowId);+ }++ async duplicateNodeWorkflow(workflowId: string, newName: string): Promise<WorkflowInfo> {+ const original = await workflowService.loadWorkflow(workflowId);+ if (!original) {+ throw new Error(`Workflow '${workflowId}' not found`);+ }++ const newId = `workflow_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;+ const duplicate: Workflow = {+ ...original,+ id: newId,+ name: newName,+ status: 'draft',+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ };++ await workflowService.saveWorkflow(duplicate);++ return this.workflowToInfo(duplicate);+ }++ // ============================================================================+ // WORKFLOW EXECUTION METHODS+ // ============================================================================++ async executeNodeWorkflow(workflowId: string, _inputData?: any): Promise<WorkflowExecutionResult> {+ const startTime = Date.now();++ try {+ await workflowService.executeWorkflow(workflowId);++ // Wait a bit for execution to complete (simplified - real implementation would use proper async handling)+ await new Promise(resolve => setTimeout(resolve, 200));++ const workflow = await workflowService.loadWorkflow(workflowId);++ return {+ success: workflow?.status === 'completed',+ workflowId,+ results: workflow?.results,+ duration: Date.now() - startTime,+ };+ } catch (error: any) {+ return {+ success: false,+ workflowId,+ error: error.message || 'Execution failed',+ duration: Date.now() - startTime,+ };+ }+ }++ async stopNodeWorkflow(workflowId: string): Promise<void> {+ await workflowService.stopWorkflow(workflowId);+ }++ async getWorkflowResults(workflowId: string): Promise<WorkflowExecutionResult | null> {+ const workflow = await workflowService.loadWorkflow(workflowId);+ if (!workflow) return null;++ return {+ success: workflow.status === 'completed',+ workflowId,+ results: workflow.results,+ };+ }++ async validateNodeWorkflow(workflowId: string): Promise<WorkflowValidation> {+ const workflow = await workflowService.loadWorkflow(workflowId);+ if (!workflow) {+ return { valid: false, errors: [`Workflow '${workflowId}' not found`] };+ }++ const errors: string[] = [];+ const warnings: string[] = [];+ const nodes = workflow.nodes || [];+ const edges = workflow.edges || [];++ // Check for empty workflow+ if (nodes.length === 0) {+ errors.push('Workflow has no nodes');+ }++ // Check for trigger node+ const hasTrigger = nodes.some(n =>+ n.type?.toLowerCase().includes('trigger') || n.type?.toLowerCase().includes('manual')+ );+ if (!hasTrigger && nodes.length > 0) {+ warnings.push('Workflow has no trigger node - it will need to be started manually');+ }++ // Check for disconnected nodes+ const connectedNodes = new Set<string>();+ for (const edge of edges) {+ connectedNodes.add(edge.source);+ connectedNodes.add(edge.target);+ }+ for (const node of nodes) {+ if (nodes.length > 1 && !connectedNodes.has(node.id)) {+ warnings.push(`Node '${node.id}' is not connected to any other node`);+ }+ }++ // Check for invalid node types+ for (const node of nodes) {+ if (node.type && !NodeRegistry.hasNodeType(node.type)) {+ errors.push(`Unknown node type '${node.type}' in node '${node.id}'`);+ }+ }++ // Check for broken edges+ const nodeIds = new Set(nodes.map(n => n.id));+ for (const edge of edges) {+ if (!nodeIds.has(edge.source)) {+ errors.push(`Edge references non-existent source node '${edge.source}'`);+ }+ if (!nodeIds.has(edge.target)) {+ errors.push(`Edge references non-existent target node '${edge.target}'`);+ }+ }++ return {+ valid: errors.length === 0,+ errors,+ warnings: warnings.length > 0 ? warnings : undefined,+ };+ }++ // ============================================================================+ // HELPER METHODS+ // ============================================================================++ async openWorkflowInEditor(workflowId: string): Promise<void> {+ // Navigate to Node Editor tab (tab value is 'nodes')+ if (this.navigateToTab) {+ this.navigateToTab('nodes');+ }++ // Load the workflow in the editor+ if (this.loadWorkflowInEditor) {+ // Small delay to ensure tab is active+ await new Promise(resolve => setTimeout(resolve, 100));+ this.loadWorkflowInEditor(workflowId);+ }+ }++ async exportNodeWorkflow(workflowId: string): Promise<any> {+ const workflow = await workflowService.loadWorkflow(workflowId);+ if (!workflow) {+ throw new Error(`Workflow '${workflowId}' not found`);+ }++ // Return a clean export format+ return {+ name: workflow.name,+ description: workflow.description,+ nodes: (workflow.nodes || []).map(n => ({+ id: n.id,+ type: n.type,+ position: n.position,+ parameters: n.data,+ })),+ edges: (workflow.edges || []).map(e => ({+ source: e.source,+ target: e.target,+ sourceHandle: e.sourceHandle,+ targetHandle: e.targetHandle,+ })),+ exportedAt: new Date().toISOString(),+ version: '1.0',+ };+ }++ async importNodeWorkflow(workflowData: any): Promise<WorkflowInfo> {+ // Create a new workflow from the imported data+ return this.createNodeWorkflow({+ name: workflowData.name || 'Imported Workflow',+ description: workflowData.description,+ nodes: (workflowData.nodes || []).map((n: any) => ({+ id: n.id,+ type: n.type,+ position: n.position || { x: 100, y: 100 },+ parameters: n.parameters || n.data,+ label: n.label,+ })),+ edges: (workflowData.edges || []).map((e: any) => ({+ source: e.source,+ target: e.target,+ sourceHandle: e.sourceHandle,+ targetHandle: e.targetHandle,+ })),+ });+ }++ // ============================================================================+ // UTILITY METHODS+ // ============================================================================++ private workflowToInfo(workflow: Workflow): WorkflowInfo {+ return {+ id: workflow.id,+ name: workflow.name,+ description: workflow.description,+ status: workflow.status,+ nodes: (workflow.nodes || []).map(n => ({+ id: n.id,+ type: n.type || 'unknown',+ position: n.position,+ parameters: n.data,+ label: n.data?.label as string,+ })),+ edges: this.edgesToEdgeInputs(workflow.edges || []),+ createdAt: workflow.createdAt,+ updatedAt: workflow.updatedAt,+ };+ }++ /**+ * Convert workflow edges to WorkflowEdgeInput format+ * Handles null -> undefined conversion for sourceHandle/targetHandle+ */+ private edgesToEdgeInputs(edges: WorkflowEdge[]): import('./types').WorkflowEdgeInput[] {+ return (edges || []).map(e => ({+ source: e.source,+ target: e.target,+ sourceHandle: e.sourceHandle ?? undefined,+ targetHandle: e.targetHandle ?? undefined,+ }));+ }+}++// Export singleton instance+export const nodeEditorMCPBridge = new NodeEditorMCPBridgeClass();diff --git a/fincept-terminal-desktop/src/services/mcp/internal/StockBrokerMCPBridge.ts b/fincept-terminal-desktop/src/services/mcp/internal/StockBrokerMCPBridge.tsnew file mode 100644index 000000000..b1a5cb74c--- /dev/null+++ b/fincept-terminal-desktop/src/services/mcp/internal/StockBrokerMCPBridge.ts@@ -0,0 +1,775 @@+// Stock Broker MCP Bridge - Connects StockBrokerContext to MCP Internal Tools+// Provides unified trading interface for all Indian stock brokers via MCP+// Supports both LIVE and PAPER trading modes++import { terminalMCPProvider } from './TerminalMCPProvider';+import type { IStockBrokerAdapter } from '@/brokers/stocks/types';+import type {+ OrderParams,+ ModifyOrderParams,+ Position,+ Holding,+ Order,+ Trade,+ Funds,+ Quote,+ MarketDepth,+ DepthLevel,+ Instrument,+ TimeFrame,+ StockExchange,+ ProductType,+ OrderType,+ OrderSide,+ OrderValidity,+ MarginRequired,+} from '@/brokers/stocks/types';++/**+ * Format date in IST (Indian Standard Time)+ */+function formatIST(): string {+ return new Date().toLocaleString('en-IN', {+ timeZone: 'Asia/Kolkata',+ year: 'numeric',+ month: 'short',+ day: 'numeric',+ hour: '2-digit',+ minute: '2-digit',+ second: '2-digit',+ hour12: false,+ });+}++interface StockBrokerMCPBridgeConfig {+ activeAdapter: IStockBrokerAdapter | null;+ tradingMode: 'live' | 'paper';+ activeBroker: string | null;+ isAuthenticated: boolean;+}++/**+ * Bridge that connects StockBrokerContext to MCP tools+ * Allows AI to control stock trading across ALL Indian brokers+ * (AngelOne, Zerodha, Upstox, Fyers, Dhan, AliceBlue, 5Paisa, Groww, IIFL, Kotak, Shoonya, etc.)+ */+export class StockBrokerMCPBridge {+ private config: StockBrokerMCPBridgeConfig | null = null;++ /**+ * Initialize or update the bridge with stock broker context+ */+ connect(config: StockBrokerMCPBridgeConfig): void {+ this.config = config;+ this.updateMCPContexts();+ }++ /**+ * Disconnect and clear contexts+ */+ disconnect(): void {+ this.config = null;+ terminalMCPProvider.setContexts({+ placeStockTrade: undefined,+ cancelStockOrder: undefined,+ modifyStockOrder: undefined,+ getStockPositions: undefined,+ getStockHoldings: undefined,+ getStockFunds: undefined,+ getStockOrders: undefined,+ getStockTrades: undefined,+ getStockMarginRequired: undefined,+ convertStockPosition: undefined,+ exitStockPosition: undefined,+ getStockQuote: undefined,+ getStockMarketDepth: undefined,+ searchStockInstruments: undefined,+ getStockHistoricalData: undefined,+ });+ }++ /**+ * Update MCP contexts with current adapter methods+ */+ private updateMCPContexts(): void {+ if (!this.config?.activeAdapter || !this.config.isAuthenticated) {+ console.warn('[StockBrokerMCPBridge] No active authenticated adapter available');+ return;+ }++ const { activeAdapter, tradingMode, activeBroker } = this.config;++ terminalMCPProvider.setContexts({+ // ========================================================================+ // ORDER PLACEMENT & MANAGEMENT+ // ========================================================================++ /**+ * Place a stock order (Market, Limit, SL, SL-M, etc.)+ * Supports both live and paper trading+ */+ placeStockTrade: async (params: {+ symbol: string;+ exchange: string;+ transaction_type: 'BUY' | 'SELL';+ quantity: number;+ order_type: string;+ product_type: string;+ price?: number;+ trigger_price?: number;+ disclosed_quantity?: number;+ validity?: string;+ variety?: string;+ tag?: string;+ token?: string;+ tradingSymbol?: string;+ }) => {+ try {+ // Route to unified trading service if in paper mode+ if (tradingMode === 'paper') {+ // Use unified trading service for paper trading+ const { placeOrder: unifiedPlaceOrder } = await import('@/services/unifiedTradingService');++ // Handle both 'side' and 'transaction_type' (AI might send either)+ const transactionType = (params.transaction_type || (params as any).side || 'BUY').toUpperCase();+ const side = transactionType.toLowerCase() as 'buy' | 'sell';++ // For market orders, fetch current market price+ let marketPrice = params.price;+ if (params.order_type.toLowerCase() === 'market' && !marketPrice && activeAdapter) {+ try {+ const quote = await activeAdapter.getQuote(params.symbol, params.exchange as any);+ marketPrice = quote.lastPrice;+ console.log(`[StockBrokerMCPBridge] Fetched market price for ${params.symbol}: ${marketPrice}`);+ } catch (err) {+ console.warn(`[StockBrokerMCPBridge] Failed to fetch market price for ${params.symbol}:`, err);+ // Will fall back to placeholder price in Rust+ }+ }++ const unifiedOrder = {+ symbol: params.symbol,+ exchange: params.exchange,+ side: side,+ order_type: params.order_type.toLowerCase() as 'market' | 'limit' | 'stop' | 'stop_limit',+ quantity: params.quantity,+ price: marketPrice,+ stop_price: params.trigger_price,+ product_type: params.product_type as 'CNC' | 'MIS' | 'NRML',+ };++ const result = await unifiedPlaceOrder(unifiedOrder);++ // Dispatch event to trigger UI refresh+ if (result.success) {+ window.dispatchEvent(new CustomEvent('stock-order-placed', {+ detail: {+ orderId: result.order_id,+ symbol: params.symbol,+ exchange: params.exchange,+ mode: tradingMode+ }+ }));+ }++ return {+ success: result.success,+ orderId: result.order_id,+ broker: activeBroker,+ mode: tradingMode,+ symbol: params.symbol,+ transactionType: transactionType,+ quantity: params.quantity,+ orderType: params.order_type,+ productType: params.product_type,+ price: params.price,+ message: result.message,+ timestamp: formatIST(),+ };+ }++ // Live mode: use adapter directly+ const orderParams: OrderParams = {+ symbol: params.symbol,+ exchange: params.exchange as StockExchange,+ side: params.transaction_type as OrderSide,+ quantity: params.quantity,+ orderType: params.order_type as OrderType,+ productType: params.product_type as ProductType,+ price: params.price,+ triggerPrice: params.trigger_price,+ disclosedQuantity: params.disclosed_quantity || 0,+ validity: (params.validity || 'DAY') as OrderValidity,+ tag: params.tag,+ token: params.token,+ tradingSymbol: params.tradingSymbol,+ };++ const result = await activeAdapter.placeOrder(orderParams);++ // Dispatch event to trigger UI refresh+ if (result.success) {+ window.dispatchEvent(new CustomEvent('stock-order-placed', {+ detail: {+ orderId: result.orderId,+ symbol: params.symbol,+ exchange: params.exchange,+ mode: tradingMode+ }+ }));+ }++ return {+ success: true,+ orderId: result.orderId,+ broker: activeBroker,+ mode: tradingMode,+ symbol: params.symbol,+ transactionType: params.transaction_type,+ quantity: params.quantity,+ orderType: params.order_type,+ productType: params.product_type,+ price: params.price,+ message: result.message,+ timestamp: formatIST(),+ };+ } catch (error: any) {+ console.error('[StockBrokerMCPBridge] Order placement error:', error);+ const errorMsg = error?.message || error?.toString() || 'Unknown error';+ throw new Error(`Failed to place stock order: ${errorMsg}`);+ }+ },++ /**+ * Modify an existing order+ */+ modifyStockOrder: async (params: {+ order_id: string;+ quantity?: number;+ price?: number;+ trigger_price?: number;+ order_type?: string;+ validity?: string;+ }) => {+ try {+ const modifyParams: ModifyOrderParams = {+ orderId: params.order_id,+ quantity: params.quantity,+ price: params.price,+ triggerPrice: params.trigger_price,+ orderType: params.order_type as OrderType | undefined,+ validity: params.validity as 'DAY' | 'IOC' | undefined,+ };++ const result = await activeAdapter.modifyOrder(modifyParams);++ return {+ success: true,+ orderId: result.orderId,+ message: result.message,+ timestamp: new Date().toISOString(),+ };+ } catch (error: any) {+ throw new Error(`Failed to modify order: ${error.message}`);+ }+ },++ /**+ * Cancel an order by ID+ */+ cancelStockOrder: async (orderId: string, variety?: string) => {+ try {+ const result = await activeAdapter.cancelOrder(orderId);++ return {+ success: true,+ orderId: result.orderId,+ message: result.message,+ timestamp: new Date().toISOString(),+ };+ } catch (error: any) {+ throw new Error(`Failed to cancel order: ${error.message}`);+ }+ },++ // ========================================================================+ // POSITION & HOLDINGS MANAGEMENT+ // ========================================================================++ /**+ * Get all open positions+ */+ getStockPositions: async () => {+ try {+ const positions = await activeAdapter.getPositions();+ return positions.map((p: Position) => ({+ symbol: p.symbol,+ exchange: p.exchange,+ productType: p.productType,+ quantity: p.quantity,+ averagePrice: p.averagePrice,+ lastPrice: p.lastPrice,+ pnl: p.pnl,+ pnlPercent: p.pnlPercent,+ dayPnl: p.dayPnl,+ buyQuantity: p.buyQuantity,+ sellQuantity: p.sellQuantity,+ buyValue: p.buyValue,+ sellValue: p.sellValue,+ }));+ } catch (error: any) {+ console.error('[StockBrokerMCPBridge] Failed to fetch positions:', error);+ return [];+ }+ },++ /**+ * Get all holdings (long-term investments)+ */+ getStockHoldings: async () => {+ try {+ const holdings = await activeAdapter.getHoldings();+ return holdings.map((h: Holding) => ({+ symbol: h.symbol,+ exchange: h.exchange,+ isin: h.isin,+ quantity: h.quantity,+ averagePrice: h.averagePrice,+ lastPrice: h.lastPrice,+ pnl: h.pnl,+ pnlPercent: h.pnlPercent,+ investedValue: h.investedValue,+ currentValue: h.currentValue,+ collateralQuantity: h.collateralQuantity,+ pledgedQuantity: h.pledgedQuantity,+ t1Quantity: h.t1Quantity,+ }));+ } catch (error: any) {+ console.error('[StockBrokerMCPBridge] Failed to fetch holdings:', error);+ return [];+ }+ },++ /**+ * Get account funds/margins+ */+ getStockFunds: async () => {+ try {+ const funds = await activeAdapter.getFunds();+ return {+ availableCash: funds.availableCash,+ usedMargin: funds.usedMargin,+ availableMargin: funds.availableMargin,+ totalBalance: funds.totalBalance,+ currency: funds.currency,+ equityAvailable: funds.equityAvailable,+ commodityAvailable: funds.commodityAvailable,+ collateral: funds.collateral,+ unrealizedPnl: funds.unrealizedPnl,+ realizedPnl: funds.realizedPnl,+ };+ } catch (error: any) {+ throw new Error(`Failed to fetch funds: ${error.message}`);+ }+ },++ // ========================================================================+ // ORDER & TRADE HISTORY+ // ========================================================================++ /**+ * Get all orders (with optional filtering)+ */+ getStockOrders: async (filters?: { status?: string; symbol?: string }) => {+ try {+ const orders = await activeAdapter.getOrders();++ let filteredOrders = orders;++ // Apply status filter+ if (filters?.status) {+ filteredOrders = filteredOrders.filter((o: Order) =>+ o.status.toLowerCase() === filters.status?.toLowerCase()+ );+ }++ // Apply symbol filter+ if (filters?.symbol) {+ filteredOrders = filteredOrders.filter((o: Order) =>+ o.symbol === filters.symbol+ );+ }++ return filteredOrders.map((o: Order) => ({+ orderId: o.orderId,+ symbol: o.symbol,+ exchange: o.exchange,+ side: o.side,+ orderType: o.orderType,+ productType: o.productType,+ quantity: o.quantity,+ price: o.price,+ triggerPrice: o.triggerPrice,+ validity: o.validity,+ status: o.status,+ filledQuantity: o.filledQuantity,+ pendingQuantity: o.pendingQuantity,+ averagePrice: o.averagePrice,+ placedAt: o.placedAt,+ updatedAt: o.updatedAt,+ exchangeOrderId: o.exchangeOrderId,+ statusMessage: o.statusMessage,+ tag: o.tag,+ }));+ } catch (error: any) {+ throw new Error(`Failed to fetch orders: ${error.message}`);+ }+ },++ /**+ * Get trade book (executed trades)+ */+ getStockTrades: async () => {+ try {+ const trades = await activeAdapter.getTradeBook();+ return trades.map((t: Trade) => ({+ tradeId: t.tradeId,+ orderId: t.orderId,+ symbol: t.symbol,+ exchange: t.exchange,+ side: t.side,+ productType: t.productType,+ quantity: t.quantity,+ price: t.price,+ tradedAt: t.tradedAt,+ exchangeTradeId: t.exchangeTradeId,+ }));+ } catch (error: any) {+ throw new Error(`Failed to fetch trades: ${error.message}`);+ }+ },++ // ========================================================================+ // MARGIN & RISK CALCULATION+ // ========================================================================++ /**+ * Calculate margin required for an order+ */+ getStockMarginRequired: async (params: {+ symbol: string;+ exchange: string;+ transaction_type: 'BUY' | 'SELL';+ quantity: number;+ order_type: string;+ product_type: string;+ price?: number;+ }) => {+ try {+ // Check if broker supports margin calculation+ if (typeof activeAdapter.getMarginRequired !== 'function') {+ return {+ success: false,+ error: 'Margin calculation not supported by this broker',+ };+ }++ const orderParams: OrderParams = {+ symbol: params.symbol,+ exchange: params.exchange as StockExchange,+ side: params.transaction_type as OrderSide,+ quantity: params.quantity,+ orderType: params.order_type as OrderType,+ productType: params.product_type as ProductType,+ price: params.price,+ };++ const margin = await activeAdapter.getMarginRequired(orderParams);++ return {+ success: true,+ totalMargin: margin.totalMargin,+ initialMargin: margin.initialMargin,+ exposureMargin: margin.exposureMargin,+ spanMargin: margin.spanMargin,+ optionPremium: margin.optionPremium,+ };+ } catch (error: any) {+ throw new Error(`Failed to calculate margin: ${error.message}`);+ }+ },++ // ========================================================================+ // POSITION CONVERSION & EXIT+ // ========================================================================++ /**+ * Convert position (e.g., Intraday to Delivery)+ */+ convertStockPosition: async (params: {+ symbol: string;+ exchange: string;+ transaction_type: 'BUY' | 'SELL';+ quantity: number;+ old_product_type: string;+ new_product_type: string;+ }) => {+ try {+ // Check if broker supports position conversion+ if (typeof (activeAdapter as any).convertPosition !== 'function') {+ return {+ success: false,+ error: 'Position conversion not supported by this broker',+ };+ }++ await (activeAdapter as any).convertPosition(+ params.symbol,+ params.exchange as StockExchange,+ params.transaction_type,+ params.quantity,+ params.old_product_type as ProductType,+ params.new_product_type as ProductType+ );++ return {+ success: true,+ message: `Position converted from ${params.old_product_type} to ${params.new_product_type}`,+ };+ } catch (error: any) {+ throw new Error(`Failed to convert position: ${error.message}`);+ }+ },++ /**+ * Exit a position (close all quantity)+ */+ exitStockPosition: async (params: {+ symbol: string;+ exchange: string;+ product_type: string;+ }) => {+ try {+ // Get current positions to find the position+ const positions = await activeAdapter.getPositions();+ const position = positions.find(+ (p: Position) =>+ p.symbol === params.symbol &&+ p.exchange === params.exchange &&+ p.productType === params.product_type+ );++ if (!position) {+ throw new Error(`No open position found for ${params.symbol}`);+ }++ // Determine exit side (opposite of current position)+ const exitSide: 'BUY' | 'SELL' = position.quantity > 0 ? 'SELL' : 'BUY';+ const exitQuantity = Math.abs(position.quantity);++ // Place market order to exit+ const orderParams: OrderParams = {+ symbol: params.symbol,+ exchange: params.exchange as StockExchange,+ side: exitSide,+ quantity: exitQuantity,+ orderType: 'MARKET' as OrderType,+ productType: params.product_type as ProductType,+ validity: 'DAY',+ };++ const result = await activeAdapter.placeOrder(orderParams);++ return {+ success: true,+ orderId: result.orderId,+ symbol: params.symbol,+ quantity: exitQuantity,+ side: exitSide,+ message: `Position exited: ${exitSide} ${exitQuantity} ${params.symbol}`,+ };+ } catch (error: any) {+ throw new Error(`Failed to exit position: ${error.message}`);+ }+ },++ // ========================================================================+ // MARKET DATA+ // ========================================================================++ /**+ * Get real-time quote for a symbol+ */+ getStockQuote: async (params: { symbol: string; exchange: string }) => {+ try {+ const quote = await activeAdapter.getQuote(+ params.symbol,+ params.exchange as StockExchange+ );++ return {+ symbol: quote.symbol,+ exchange: quote.exchange,+ lastPrice: quote.lastPrice,+ open: quote.open,+ high: quote.high,+ low: quote.low,+ close: quote.close,+ previousClose: quote.previousClose,+ volume: quote.volume,+ averagePrice: quote.averagePrice,+ change: quote.change,+ changePercent: quote.changePercent,+ bid: quote.bid,+ bidQty: quote.bidQty,+ ask: quote.ask,+ askQty: quote.askQty,+ lowerCircuit: quote.lowerCircuit,+ upperCircuit: quote.upperCircuit,+ timestamp: quote.timestamp,+ };+ } catch (error: any) {+ throw new Error(`Failed to fetch quote: ${error.message}`);+ }+ },++ /**+ * Get market depth (order book)+ */+ getStockMarketDepth: async (params: { symbol: string; exchange: string }) => {+ try {+ const depth = await activeAdapter.getMarketDepth(+ params.symbol,+ params.exchange as StockExchange+ );++ return {+ bids: depth.bids.map((b: DepthLevel) => ({+ price: b.price,+ quantity: b.quantity,+ orders: b.orders,+ })),+ asks: depth.asks.map((s: DepthLevel) => ({+ price: s.price,+ quantity: s.quantity,+ orders: s.orders,+ })),+ timestamp: depth.timestamp,+ };+ } catch (error: any) {+ throw new Error(`Failed to fetch market depth: ${error.message}`);+ }+ },++ /**+ * Search for instruments/symbols+ */+ searchStockInstruments: async (query: string, exchange?: string) => {+ try {+ const instruments = await activeAdapter.searchSymbols(+ query,+ exchange as StockExchange | undefined+ );++ return instruments.map((i: Instrument) => ({+ instrumentToken: i.instrumentToken,+ exchangeToken: i.exchangeToken,+ symbol: i.symbol,+ tradingSymbol: i.tradingSymbol,+ name: i.name,+ exchange: i.exchange,+ segment: i.segment,+ instrumentType: i.instrumentType,+ lotSize: i.lotSize,+ tickSize: i.tickSize,+ }));+ } catch (error: any) {+ throw new Error(`Failed to search instruments: ${error.message}`);+ }+ },++ /**+ * Get historical OHLCV data+ */+ getStockHistoricalData: async (params: {+ symbol: string;+ exchange: string;+ timeframe: string;+ from_date: string;+ to_date: string;+ }) => {+ try {+ // Check if broker supports historical data+ if (typeof (activeAdapter as any).getHistoricalData !== 'function') {+ return {+ success: false,+ error: 'Historical data not supported by this broker',+ data: [],+ };+ }++ const data = await (activeAdapter as any).getHistoricalData(+ params.symbol,+ params.exchange as StockExchange,+ params.timeframe as TimeFrame,+ new Date(params.from_date),+ new Date(params.to_date)+ );++ return data.map((candle: { timestamp: number; open: number; high: number; low: number; close: number; volume: number }) => ({+ timestamp: candle.timestamp,+ open: candle.open,+ high: candle.high,+ low: candle.low,+ close: candle.close,+ volume: candle.volume,+ }));+ } catch (error: any) {+ throw new Error(`Failed to fetch historical data: ${error.message}`);+ }+ },+ });++ console.log(+ `[StockBrokerMCPBridge] Connected to ${activeBroker} (${tradingMode} mode)`+ );+ }++ /**+ * Check if bridge is connected+ */+ isConnected(): boolean {+ return (+ this.config !== null &&+ this.config.activeAdapter !== null &&+ this.config.isAuthenticated+ );+ }++ /**+ * Get current configuration+ */+ getConfig(): StockBrokerMCPBridgeConfig | null {+ return this.config;+ }++ /**+ * Get connection status details+ */+ getStatus(): {+ connected: boolean;+ broker: string | null;+ mode: 'live' | 'paper' | null;+ authenticated: boolean;+ } {+ return {+ connected: this.isConnected(),+ broker: this.config?.activeBroker || null,+ mode: this.config?.tradingMode || null,+ authenticated: this.config?.isAuthenticated || false,+ };+ }+}++// Singleton instance+export const stockBrokerMCPBridge = new StockBrokerMCPBridge();diff --git a/fincept-terminal-desktop/src/services/mcp/internal/TerminalMCPProvider.ts b/fincept-terminal-desktop/src/services/mcp/internal/TerminalMCPProvider.tsindex 1d3fd27d4..08c195508 100644--- a/fincept-terminal-desktop/src/services/mcp/internal/TerminalMCPProvider.ts+++ b/fincept-terminal-desktop/src/services/mcp/internal/TerminalMCPProvider.ts@@ -87,7 +87,13 @@ class TerminalMCPProvider {const result: InternalToolResult = await tool.handler(args, this.contexts);return {success: result.success,- data: result.data ?? result.message,+ data: result.data ?? result.message ?? result.content,+ // Preserve additional metadata for charts, etc.+ chart_data: result.chart_data,+ ticker: result.ticker,+ company: result.company,+ content: result.content,+ message: result.message,error: result.error,toolName: name,serverId: INTERNAL_SERVER_ID,diff --git a/fincept-terminal-desktop/src/services/mcp/internal/index.ts b/fincept-terminal-desktop/src/services/mcp/internal/index.tsindex 38cadf693..120d902ac 100644--- a/fincept-terminal-desktop/src/services/mcp/internal/index.ts+++ b/fincept-terminal-desktop/src/services/mcp/internal/index.ts@@ -12,10 +12,15 @@ import { marketDataTools } from './tools/market-data';import { workflowTools } from './tools/workflow';import { notesTools } from './tools/notes';import { cryptoTradingTools } from './tools/crypto-trading';+import { stockTradingTools } from './tools/stock-trading';import { reportBuilderTools } from './tools/report-builder';+import { edgarTools } from './tools/edgar';+import { nodeEditorTools } from './tools/node-editor';import { reportBuilderMCPBridge } from './ReportBuilderMCPBridge';import { brokerMCPBridge } from './BrokerMCPBridge';+import { stockBrokerMCPBridge } from './StockBrokerMCPBridge';import { notesMCPBridge } from './NotesMCPBridge';+import { nodeEditorMCPBridge } from './NodeEditorMCPBridge';// Flag to ensure initialization only runs oncelet isInitialized = false;@@ -45,7 +50,10 @@ export function initializeInternalMCP(): void {terminalMCPProvider.registerTools(workflowTools);terminalMCPProvider.registerTools(notesTools);terminalMCPProvider.registerTools(cryptoTradingTools);+ terminalMCPProvider.registerTools(stockTradingTools);terminalMCPProvider.registerTools(reportBuilderTools);+ terminalMCPProvider.registerTools(edgarTools);+ terminalMCPProvider.registerTools(nodeEditorTools);console.log(`[Internal MCP] Registered ${terminalMCPProvider.getToolCount()} tools`);@@ -53,6 +61,10 @@ export function initializeInternalMCP(): void {reportBuilderMCPBridge.initializeGlobalContexts();console.log('[Internal MCP] Report Builder bridge initialized');+ // Initialize Node Editor bridge contexts+ nodeEditorMCPBridge.initialize();+ console.log('[Internal MCP] Node Editor bridge initialized');+// Mark as initializedisInitialized = true;console.log('[Internal MCP] Initialization complete');@@ -71,7 +83,20 @@ export function isInternalMCPInitialized(): boolean {export { terminalMCPProvider } from './TerminalMCPProvider';export { brokerMCPBridge } from './BrokerMCPBridge';+export { stockBrokerMCPBridge } from './StockBrokerMCPBridge';export { notesMCPBridge } from './NotesMCPBridge';export { reportBuilderMCPBridge } from './ReportBuilderMCPBridge';+export { nodeEditorMCPBridge } from './NodeEditorMCPBridge';export { INTERNAL_SERVER_ID, INTERNAL_SERVER_NAME } from './types';export type { TerminalContexts, InternalTool, InternalToolResult } from './types';+export type {+ NodeTypeInfo,+ NodeTypeDetails,+ NodeCategoryInfo,+ CreateWorkflowParams,+ WorkflowNodeInput,+ WorkflowEdgeInput,+ WorkflowInfo,+ WorkflowExecutionResult,+ WorkflowValidation,+} from './types';diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/edgar.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/edgar.tsnew file mode 100644index 000000000..712892674--- /dev/null+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/edgar.ts@@ -0,0 +1,970 @@+// Edgar Tools MCP - SEC EDGAR data access via edgartools Python library+// Provides comprehensive access to SEC filings, financials, insider transactions, etc.++import { InternalTool } from '../types';+import { invoke } from '@tauri-apps/api/core';++interface CompanyTicker {+ cik: number;+ ticker: string;+ company: string;+}++/**+ * Load and cache all company tickers from SEC into SQLite+ */+async function loadCompanyTickers(): Promise<CompanyTicker[]> {+ try {+ // Check if cache is already populated+ const isPopulated = await invoke<boolean>('edgar_cache_is_populated');++ if (isPopulated) {+ console.log('[Edgar Cache] Using SQLite cache');+ const companies = await invoke<CompanyTicker[]>('edgar_cache_get_all_companies');+ console.log(`[Edgar Cache] Loaded ${companies.length} companies from SQLite`);+ return companies;+ }++ console.log('[Edgar Cache] Populating SQLite cache from SEC...');++ // Get ALL tickers from SEC (no limit)+ const result = await executeEdgarCommand('get_company_tickers', [999999]);++ if (result.success && result.data) {+ const tickers: CompanyTicker[] = result.data;++ // Store in SQLite+ await invoke('edgar_cache_store_tickers', { tickers });++ console.log(`[Edgar Cache] Stored ${tickers.length} companies in SQLite`);+ return tickers;+ }++ throw new Error('Failed to load company tickers from SEC');+ } catch (error) {+ console.error('[Edgar Cache] Error loading tickers:', error);+ // Try to return whatever is in cache+ try {+ return await invoke<CompanyTicker[]>('edgar_cache_get_all_companies');+ } catch {+ return [];+ }+ }+}++/**+ * Common company name aliases and abbreviations+ */+const COMPANY_ALIASES: Record<string, string[]> = {+ 'sp': ['s&p', 'sandp', 's and p', 'standard and poors', 'standard poors'],+ 'snp': ['s&p', 'sandp', 's and p', 'standard and poors', 'standard poors'],+ 's&p': ['sp', 'snp', 'sandp', 'standard and poors'],+ 'jp': ['jpmorgan', 'jp morgan'],+ 'jpmorgan': ['jp', 'jp morgan'],+ 'ms': ['morgan stanley'],+ 'gs': ['goldman', 'goldman sachs'],+ 'bofa': ['bank of america'],+ 'citi': ['citigroup', 'citibank'],+ 'wells': ['wells fargo'],+ 'amex': ['american express'],+};++/**+ * Normalize query for better matching+ */+function normalizeQuery(query: string): string[] {+ const lower = query.toLowerCase().replace(/[^\w\s&]/g, '');+ const variants = [lower];++ // Check for known aliases+ for (const [abbrev, aliases] of Object.entries(COMPANY_ALIASES)) {+ if (lower.includes(abbrev)) {+ for (const alias of aliases) {+ variants.push(lower.replace(abbrev, alias));+ }+ }+ }++ return variants;+}++/**+ * Fuzzy search company tickers from cache with improved scoring+ */+function fuzzySearchCompanies(query: string, companies: CompanyTicker[], maxResults: number = 10): CompanyTicker[] {+ const queryVariants = normalizeQuery(query);+ const queryLower = query.toLowerCase().replace(/[^\w\s&]/g, '');+ const queryWords = queryLower.split(/\s+/).filter(w => w.length > 0);++ if (queryWords.length === 0) return [];++ const scoredResults = companies.map(company => {+ const nameLower = company.company.toLowerCase().replace(/[^\w\s&]/g, '');+ const tickerLower = company.ticker.toLowerCase();+ let score = 0;++ // Check all query variants+ for (const variant of queryVariants) {+ const variantWords = variant.split(/\s+/).filter(w => w.length > 0);++ // Exact ticker match = highest priority+ if (tickerLower === variant.replace(/\s+/g, '')) {+ score = Math.max(score, 10000);+ }+ // Ticker starts with query (no spaces)+ else if (tickerLower.startsWith(variant.replace(/\s+/g, ''))) {+ score = Math.max(score, 5000);+ }+ // Exact company name match+ else if (nameLower === variant) {+ score = Math.max(score, 2000);+ }+ // Company name starts with query+ else if (nameLower.startsWith(variant)) {+ score = Math.max(score, 1000);+ }+ // Company name contains exact query phrase+ else if (nameLower.includes(variant)) {+ score = Math.max(score, 800);+ }+ // Word-based matching+ else {+ const nameWords = nameLower.split(/\s+/);++ // Count matching words with position bonus+ let wordScore = 0;+ let matchedCount = 0;++ for (let i = 0; i < variantWords.length; i++) {+ const qw = variantWords[i];+ for (let j = 0; j < nameWords.length; j++) {+ const nw = nameWords[j];++ // Exact word match+ if (nw === qw) {+ wordScore += 100;+ matchedCount++;+ // Bonus for matching at same position+ if (i === j) wordScore += 50;+ }+ // Word starts with query word+ else if (nw.startsWith(qw) && qw.length >= 2) {+ wordScore += 60;+ matchedCount++;+ }+ // Query word starts with name word (e.g., "global" matches "glob")+ else if (qw.startsWith(nw) && nw.length >= 3) {+ wordScore += 40;+ matchedCount++;+ }+ }+ }++ // Only count if we matched most words+ if (matchedCount >= Math.ceil(variantWords.length * 0.5)) {+ // Bonus for matching all query words+ if (matchedCount >= variantWords.length) {+ wordScore += 200;+ }+ score = Math.max(score, wordScore);+ }+ }+ }++ // Prefer shorter names (more specific companies) - but less aggressively+ if (score > 0) {+ score -= company.company.length * 0.02;+ }++ return { company, score };+ });++ // Filter and sort by score+ return scoredResults+ .filter(r => r.score > 0)+ .sort((a, b) => b.score - a.score)+ .slice(0, maxResults)+ .map(r => r.company);+}++/**+ * Helper to build args array from params object based on command signature+ */+function buildArgsArray(command: string, params: any): any[] {+ const args: any[] = [];++ // Map of command -> expected argument order+ const commandSignatures: Record<string, string[]> = {+ // Configuration+ 'set_identity': ['identity'],+ 'get_identity': [],+ 'configure_connection': ['verify_ssl', 'proxy', 'timeout'],+ 'clear_cache': ['dry_run'],+ 'get_storage_info': [],++ // Company operations+ 'get_company': ['ticker'],+ 'get_company_filings': ['ticker', 'form', 'year', 'quarter', 'limit'],+ 'get_corporate_events': ['ticker', 'limit'],+ 'get_latest_filing': ['ticker', 'form', 'n'],+ 'get_corporate_events_categorized': ['ticker', 'limit'],++ // Financials+ 'get_financials': ['ticker', 'periods', 'annual'],+ 'get_balance_sheet': ['ticker', 'periods', 'annual', 'as_json'],+ 'get_income_statement': ['ticker', 'periods', 'annual', 'as_json'],+ 'get_cash_flow': ['ticker', 'periods', 'annual', 'as_json'],+ 'get_company_facts': ['cik'],+ 'get_xbrl_data': ['ticker', 'form'],++ // Insider transactions+ 'get_insider_transactions': ['ticker', 'limit'],+ 'get_insider_transactions_detailed': ['ticker', 'limit'],++ // Fund holdings+ 'get_fund_holdings': ['ticker', 'limit'],+ 'get_fund_holdings_detailed': ['ticker', 'quarters'],++ // Enhanced data extraction+ 'extract_supply_chain': ['ticker'],+ 'get_segment_financials': ['ticker'],+ 'extract_debt_holders': ['ticker'],++ // Proxy statements+ 'get_proxy_statement': ['ticker'],++ // Current filings+ 'get_current_filings': ['form', 'page_size'],+ 'get_latest_filings': ['form', 'page_size'],++ // Search & discovery+ 'find_company': ['query', 'top_n'],+ 'find': ['identifier'],+ 'get_company_tickers': ['limit'],++ // Filing operations+ 'get_filing_by_accession': ['accession_number'],+ 'get_filing_text': ['accession_number', 'max_length'],+ 'get_filings_by_date': ['year', 'quarter', 'form', 'limit'],++ // Entity operations+ 'get_entity': ['cik'],+ 'get_entity_submissions': ['cik'],++ // Fund reports (NPX/NPORT)+ 'get_fund_report': ['ticker', 'form'],++ // Document & attachment operations+ 'get_filing_documents': ['accession_number'],+ 'get_filing_attachments': ['accession_number'],++ // Batch operations+ 'download_filings_batch': ['ticker', 'form', 'year', 'limit'],++ // Storage management+ 'analyze_storage': [],+ 'optimize_storage': ['dry_run'],+ 'cleanup_storage': ['older_than_days'],+ };++ const signature = commandSignatures[command];+ if (!signature) {+ // Unknown command, pass all params as-is+ return Object.values(params);+ }++ // Build args in correct order+ for (const paramName of signature) {+ const value = params[paramName];+ if (value !== undefined && value !== null) {+ args.push(value);+ }+ }++ return args;+}++/**+ * Execute Edgar tools command via Python script+ */+async function executeEdgarCommand(command: string, args: any[]): Promise<any> {+ try {+ // Build args: [command, ...params] - all must be strings+ const scriptArgs = [command, ...args.map(arg => String(arg))];++ const result = await invoke('execute_python_script', {+ app: null, // Will be injected by Tauri+ scriptName: 'edgar_tools.py',+ args: scriptArgs,+ env: {}+ });++ // Parse JSON response from Python+ const parsed = typeof result === 'string' ? JSON.parse(result) : result;+ return parsed;+ } catch (error) {+ console.error(`[Edgar MCP] Error executing ${command}:`, error);+ throw error;+ }+}++/**+ * Auto-resolve ticker from company name query using cached fuzzy matching+ */+async function resolveTickerFromQuery(query: string): Promise<string | null> {+ try {+ // Load all companies into cache (only happens once per 24h)+ const allCompanies = await loadCompanyTickers();++ if (allCompanies.length === 0) {+ console.warn('[Edgar MCP] No company data available in cache');+ return null;+ }++ // Fuzzy search against cached data+ const matches = fuzzySearchCompanies(query, allCompanies, 5);++ if (matches.length > 0) {+ const bestMatch = matches[0];+ console.log(`[Edgar MCP] Resolved "${query}" → "${bestMatch.ticker}" (${bestMatch.company}) from ${allCompanies.length} companies`);+ return bestMatch.ticker;+ }++ console.warn(`[Edgar MCP] No matches found for "${query}"`);+ return null;+ } catch (error) {+ console.warn(`[Edgar MCP] Failed to resolve ticker for "${query}":`, error);+ return null;+ }+}++export const edgarTools: InternalTool[] = [+ // ============================================================================+ // UNIFIED EDGAR EXECUTOR - Handles ALL edgar_tools.py commands+ // ============================================================================++ {+ name: 'edgar_execute',+ description: 'Execute any SEC Edgar command. Automatically resolves company ticker from name. Supports 90+ commands for financials, filings, insider transactions, holdings, entity data, documents, batch operations, and storage management.',+ inputSchema: {+ type: 'object',+ properties: {+ command: {+ type: 'string',+ description: 'Edgar command to execute',+ enum: [+ // Configuration+ 'set_identity', 'get_identity', 'configure_connection', 'clear_cache', 'get_storage_info',+ // Company+ 'get_company', 'get_company_filings', 'get_corporate_events', 'get_latest_filing',+ 'get_corporate_events_categorized',+ // Financials+ 'get_financials', 'get_balance_sheet', 'get_income_statement', 'get_cash_flow',+ 'get_company_facts', 'get_xbrl_data',+ // Insider & Holdings+ 'get_insider_transactions', 'get_insider_transactions_detailed',+ 'get_fund_holdings', 'get_fund_holdings_detailed',+ // Enhanced extraction+ 'extract_supply_chain', 'get_segment_financials', 'extract_debt_holders',+ // Proxy+ 'get_proxy_statement',+ // Current filings+ 'get_current_filings', 'get_latest_filings',+ // Search+ 'find_company', 'find', 'get_company_tickers',+ // Filing operations+ 'get_filing_by_accession', 'get_filing_text', 'get_filings_by_date',+ // Entity operations+ 'get_entity', 'get_entity_submissions',+ // Fund reports+ 'get_fund_report',+ // Documents+ 'get_filing_documents', 'get_filing_attachments',+ // Batch operations+ 'download_filings_batch',+ // Storage management+ 'analyze_storage', 'optimize_storage', 'cleanup_storage',+ ],+ },+ query: {+ type: 'string',+ description: 'Company name to search (e.g., "Apple", "Microsoft"). Will auto-resolve to ticker symbol.',+ },+ ticker: {+ type: 'string',+ description: 'Stock ticker symbol (e.g., AAPL, MSFT). Use this if you already know the exact ticker.',+ },+ form: {+ type: 'string',+ description: 'SEC form type (e.g., "10-K", "10-Q", "8-K", "DEF 14A", "13F-HR", "NPORT-P", "NPX")',+ },+ year: {+ type: 'number',+ description: 'Year filter for filings',+ },+ quarter: {+ type: 'number',+ description: 'Quarter filter (1-4)',+ },+ limit: {+ type: 'number',+ description: 'Maximum number of results to return',+ },+ periods: {+ type: 'number',+ description: 'Number of periods for financial data',+ },+ annual: {+ type: 'boolean',+ description: 'True for annual data, false for quarterly',+ },+ as_json: {+ type: 'boolean',+ description: 'Return as JSON format',+ },+ n: {+ type: 'number',+ description: 'Number of items',+ },+ quarters: {+ type: 'number',+ description: 'Number of quarters',+ },+ cik: {+ type: 'string',+ description: 'Company CIK number',+ },+ identifier: {+ type: 'string',+ description: 'Ticker, CIK, or accession number',+ },+ top_n: {+ type: 'number',+ description: 'Number of top results',+ },+ accession_number: {+ type: 'string',+ description: 'SEC accession number',+ },+ max_length: {+ type: 'number',+ description: 'Maximum text length',+ },+ page_size: {+ type: 'number',+ description: 'Results per page',+ },+ dry_run: {+ type: 'boolean',+ description: 'Dry run mode for cache operations',+ },+ verify_ssl: {+ type: 'boolean',+ description: 'Verify SSL certificates',+ },+ proxy: {+ type: 'string',+ description: 'Proxy server URL',+ },+ timeout: {+ type: 'number',+ description: 'Request timeout in seconds',+ },+ identity: {+ type: 'string',+ description: 'User identity for SEC (name + email)',+ },+ older_than_days: {+ type: 'number',+ description: 'Remove cache files older than this many days',+ },+ },+ required: ['command'],+ },+ handler: async (args) => {+ const { command, query, ticker, ...restParams } = args;++ // Auto-resolve ticker from query if provided+ let finalTicker = ticker;+ if (query && !ticker) {+ const resolvedTicker = await resolveTickerFromQuery(query);+ if (!resolvedTicker) {+ return {+ success: false,+ error: `Could not resolve ticker for company "${query}". Please verify the company name or provide exact ticker symbol.`,+ };+ }+ finalTicker = resolvedTicker;+ }++ // Build final params with resolved ticker+ const params = {+ ...restParams,+ ticker: finalTicker,+ };++ // Build args array+ const commandArgs = buildArgsArray(command, params);++ try {+ const result = await executeEdgarCommand(command, commandArgs);++ return {+ success: true,+ data: result,+ message: `Executed ${command} successfully`,+ resolvedTicker: finalTicker !== ticker ? finalTicker : undefined,+ };+ } catch (error: any) {+ return {+ success: false,+ error: error?.message || String(error),+ command,+ params,+ };+ }+ },+ },++ // ============================================================================+ // QUICK ACCESS SHORTCUTS - Common operations with simple interfaces+ // ============================================================================++ {+ name: 'edgar_get_company_overview',+ description: 'Get complete company overview including info, latest financials, and recent filings. One-stop query for company analysis.',+ inputSchema: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'Company name (e.g., "Tesla", "Apple")' },+ ticker: { type: 'string', description: 'Or exact ticker symbol (e.g., TSLA, AAPL)' },+ },+ required: [],+ },+ handler: async (args) => {+ // Resolve ticker+ let ticker = args.ticker;+ if (args.query && !ticker) {+ ticker = await resolveTickerFromQuery(args.query);+ if (!ticker) {+ return { success: false, error: `Could not find company: ${args.query}` };+ }+ }++ if (!ticker) {+ return { success: false, error: 'Must provide either query or ticker' };+ }++ try {+ // Get company info+ const companyInfo = await executeEdgarCommand('get_company', [ticker]);++ // Get latest financials+ const financials = await executeEdgarCommand('get_financials', [ticker, 4, true]);++ // Get recent filings+ const filings = await executeEdgarCommand('get_company_filings', [ticker, '', '', '', 10]);++ return {+ success: true,+ data: {+ company: companyInfo,+ financials: financials,+ recent_filings: filings,+ },+ ticker,+ message: `Retrieved complete overview for ${ticker}`,+ };+ } catch (error: any) {+ return {+ success: false,+ error: error?.message || String(error),+ };+ }+ },+ },++ {+ name: 'edgar_search_company',+ description: 'Search for companies by name and get basic info with tickers',+ inputSchema: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'Company name or partial name to search' },+ top_n: { type: 'number', description: 'Number of results (default: 10)' },+ },+ required: ['query'],+ },+ handler: async (args) => {+ const topN = args.top_n || 10;++ try {+ const result = await executeEdgarCommand('find_company', [args.query, topN]);+ return {+ success: true,+ data: result,+ message: `Found ${result.count || 0} companies matching "${args.query}"`,+ };+ } catch (error: any) {+ return {+ success: false,+ error: error?.message || String(error),+ };+ }+ },+ },++ {+ name: 'edgar_get_financials',+ description: 'Get complete financial statements (income statement, balance sheet, cash flow) for any company. Supports both ANNUAL and QUARTERLY data. Use annual=false for quarterly/Q1/Q2/Q3/Q4/10-Q data. Returns beautifully formatted markdown tables.',+ inputSchema: {+ type: 'object',+ properties: {+ company_name: {+ type: 'string',+ description: 'Company name to get financials for (e.g., "Apple", "Microsoft", "Tesla", "S&P Global", "JPMorgan"). Will automatically resolve to correct ticker.'+ },+ periods: {+ type: 'number',+ description: 'Number of years/quarters to show (default: 3)'+ },+ annual: {+ type: 'boolean',+ description: 'IMPORTANT: Set to FALSE for quarterly/Q1/Q2/Q3/Q4/10-Q data. Set to TRUE (default) for annual/yearly/10-K data. If user says "quarterly", "Q4", "Q1", "10-Q" etc., use annual=false.'+ },+ },+ required: ['company_name'],+ },+ handler: async (args) => {+ console.log('[edgar_get_financials] Called with args:', JSON.stringify(args));++ // Try multiple possible parameter names+ let companyName = args.company_name || args.query || args.ticker || args.company || args.name || args.symbol;++ // If still nothing, try to find any string value in args+ if (!companyName) {+ const stringValues = Object.values(args).filter(v => typeof v === 'string' && v.length > 0);+ if (stringValues.length > 0) {+ companyName = stringValues[0];+ console.log(`[edgar_get_financials] Using first string value found: "${companyName}"`);+ }+ }++ if (!companyName) {+ console.error('[edgar_get_financials] ERROR: No company identifier found. Received args:', args);+ return {+ success: false,+ error: 'Missing company name. Please provide a company name like "Apple" or "Microsoft".',+ debug: { receivedKeys: Object.keys(args), receivedValues: args }+ };+ }++ console.log(`[edgar_get_financials] Resolving company: "${companyName}"`);+ const ticker = await resolveTickerFromQuery(companyName);++ if (!ticker) {+ return {+ success: false,+ error: `Could not find company "${companyName}". Please check the spelling or try a different company name.`+ };+ }++ console.log(`[edgar_get_financials] Resolved "${companyName}" → ${ticker}`);++ const periods = args.periods || 3;+ const annual = args.annual !== false; // default true++ try {+ const result = await executeEdgarCommand('get_financials', [ticker, periods, annual]);++ console.log('[edgar_get_financials] Raw result from Python:', JSON.stringify(result, null, 2).slice(0, 500));++ // Extract markdown and chart data from result+ const markdown = result?.data?.markdown || result?.markdown;+ const chartData = result?.data?.chart_data;++ console.log('[edgar_get_financials] chart_data:', chartData ? 'present' : 'MISSING');++ if (markdown) {+ // Return markdown + chart data for LLM to display+ const toolResult = {+ success: true,+ content: markdown,+ chart_data: chartData,+ ticker,+ company: result?.data?.company_name,+ message: `Financial statements for ${ticker} (${annual ? 'Annual' : 'Quarterly'})`,+ };+ console.log('[edgar_get_financials] Returning with chart_data:', !!chartData);+ return toolResult;+ }++ // Fallback to raw data+ return {+ success: true,+ data: result,+ ticker,+ message: `Retrieved ${annual ? 'annual' : 'quarterly'} financials for ${ticker}`,+ };+ } catch (error: any) {+ return {+ success: false,+ error: error?.message || String(error),+ };+ }+ },+ },++ {+ name: 'edgar_get_insider_activity',+ description: 'Get insider transaction activity (Form 4 filings) with buy/sell details',+ inputSchema: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'Company name' },+ ticker: { type: 'string', description: 'Or ticker symbol' },+ limit: { type: 'number', description: 'Number of transactions (default: 25)' },+ detailed: { type: 'boolean', description: 'Get detailed transaction breakdown (default: true)' },+ },+ required: [],+ },+ handler: async (args) => {+ let ticker = args.ticker;+ if (args.query && !ticker) {+ ticker = await resolveTickerFromQuery(args.query);+ if (!ticker) {+ return { success: false, error: `Could not find company: ${args.query}` };+ }+ }++ if (!ticker) {+ return { success: false, error: 'Must provide either query or ticker' };+ }++ const limit = args.limit || 25;+ const detailed = args.detailed !== false; // default true+ const command = detailed ? 'get_insider_transactions_detailed' : 'get_insider_transactions';++ try {+ const result = await executeEdgarCommand(command, [ticker, limit]);+ return {+ success: true,+ data: result,+ ticker,+ message: `Retrieved insider transactions for ${ticker}`,+ };+ } catch (error: any) {+ return {+ success: false,+ error: error?.message || String(error),+ };+ }+ },+ },++ {+ name: 'edgar_get_institutional_holdings',+ description: 'Get institutional holdings (13F filings) showing major fund ownership',+ inputSchema: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'Company name' },+ ticker: { type: 'string', description: 'Or ticker symbol' },+ quarters: { type: 'number', description: 'Number of quarters (default: 2)' },+ },+ required: [],+ },+ handler: async (args) => {+ let ticker = args.ticker;+ if (args.query && !ticker) {+ ticker = await resolveTickerFromQuery(args.query);+ if (!ticker) {+ return { success: false, error: `Could not find company: ${args.query}` };+ }+ }++ if (!ticker) {+ return { success: false, error: 'Must provide either query or ticker' };+ }++ const quarters = args.quarters || 2;++ try {+ const result = await executeEdgarCommand('get_fund_holdings_detailed', [ticker, quarters]);+ return {+ success: true,+ data: result,+ ticker,+ message: `Retrieved institutional holdings for ${ticker}`,+ };+ } catch (error: any) {+ return {+ success: false,+ error: error?.message || String(error),+ };+ }+ },+ },++ {+ name: 'edgar_get_corporate_events',+ description: 'Get corporate events from 8-K filings (M&A, management changes, earnings, etc.)',+ inputSchema: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'Company name' },+ ticker: { type: 'string', description: 'Or ticker symbol' },+ limit: { type: 'number', description: 'Number of events (default: 30)' },+ categorized: { type: 'boolean', description: 'Categorize by event type (default: true)' },+ },+ required: [],+ },+ handler: async (args) => {+ let ticker = args.ticker;+ if (args.query && !ticker) {+ ticker = await resolveTickerFromQuery(args.query);+ if (!ticker) {+ return { success: false, error: `Could not find company: ${args.query}` };+ }+ }++ if (!ticker) {+ return { success: false, error: 'Must provide either query or ticker' };+ }++ const limit = args.limit || 30;+ const categorized = args.categorized !== false; // default true+ const command = categorized ? 'get_corporate_events_categorized' : 'get_corporate_events';++ try {+ const result = await executeEdgarCommand(command, [ticker, limit]);+ return {+ success: true,+ data: result,+ ticker,+ message: `Retrieved corporate events for ${ticker}`,+ };+ } catch (error: any) {+ return {+ success: false,+ error: error?.message || String(error),+ };+ }+ },+ },++ {+ name: 'edgar_get_current_filings',+ description: 'Get real-time current SEC filings across all companies',+ inputSchema: {+ type: 'object',+ properties: {+ form: { type: 'string', description: 'Filter by form type (e.g., "10-K", "8-K")' },+ page_size: { type: 'number', description: 'Results per page (default: 40)' },+ },+ required: [],+ },+ handler: async (args) => {+ const form = args.form || '';+ const pageSize = args.page_size || 40;++ try {+ const result = await executeEdgarCommand('get_current_filings', [form, pageSize]);+ return {+ success: true,+ data: result,+ message: `Retrieved current ${form || 'all'} filings`,+ };+ } catch (error: any) {+ return {+ success: false,+ error: error?.message || String(error),+ };+ }+ },+ },++ {+ name: 'edgar_get_entity_info',+ description: 'Get detailed entity information by CIK number',+ inputSchema: {+ type: 'object',+ properties: {+ cik: { type: 'string', description: 'Company CIK number' },+ },+ required: ['cik'],+ },+ handler: async (args) => {+ try {+ const result = await executeEdgarCommand('get_entity', [args.cik]);+ return {+ success: true,+ data: result,+ message: `Retrieved entity info for CIK ${args.cik}`,+ };+ } catch (error: any) {+ return {+ success: false,+ error: error?.message || String(error),+ };+ }+ },+ },++ {+ name: 'edgar_get_filing_documents',+ description: 'Get all documents and attachments from a specific filing',+ inputSchema: {+ type: 'object',+ properties: {+ accession_number: { type: 'string', description: 'SEC accession number' },+ },+ required: ['accession_number'],+ },+ handler: async (args) => {+ try {+ const documents = await executeEdgarCommand('get_filing_documents', [args.accession_number]);+ const attachments = await executeEdgarCommand('get_filing_attachments', [args.accession_number]);++ return {+ success: true,+ data: {+ documents,+ attachments,+ },+ message: `Retrieved documents for filing ${args.accession_number}`,+ };+ } catch (error: any) {+ return {+ success: false,+ error: error?.message || String(error),+ };+ }+ },+ },++ {+ name: 'edgar_analyze_storage',+ description: 'Analyze Edgar cache storage usage and get statistics',+ inputSchema: {+ type: 'object',+ properties: {},+ required: [],+ },+ handler: async () => {+ try {+ const result = await executeEdgarCommand('analyze_storage', []);+ return {+ success: true,+ data: result,+ message: 'Storage analysis completed',+ };+ } catch (error: any) {+ return {+ success: false,+ error: error?.message || String(error),+ };+ }+ },+ },+];diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.tsindex 0e5e4414f..9af4ef889 100644--- a/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.ts+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.ts@@ -1,11 +1,12 @@import { InternalTool } from '../types';const AVAILABLE_TABS = [- 'dashboard', 'markets', 'news', 'watchlist', 'portfolio', 'analytics',- 'economics', 'dbnomics', 'economic-calendar', 'geopolitics', 'maritime',- 'options', 'equity-research', 'screener', 'kraken',- 'chat', 'docs', 'node-editor', 'code-editor', 'forum', 'marketplace',- 'profile', 'support', 'settings', 'backtesting', 'mcp', 'trading', 'report-builder'+ 'dashboard', 'markets', 'news', 'watchlist', 'portfolio', 'research',+ 'economics', 'dbnomics', 'geopolitics', 'maritime', 'screener',+ 'chat', 'docs', 'nodes', 'code', 'forum', 'marketplace',+ 'profile', 'support', 'settings', 'backtesting', 'mcp', 'trading',+ 'reportbuilder', 'equity-trading', 'datasources', 'ai-quant-lab',+ 'notes', 'agents', 'monitoring', 'polymarket', 'derivatives', 'asia-markets', 'akshare'];const AVAILABLE_SCREENS = ['pricing', 'dashboard', 'profile', 'login'];diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/node-editor.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/node-editor.tsnew file mode 100644index 000000000..ff9c118d7--- /dev/null+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/node-editor.ts@@ -0,0 +1,1228 @@+/**+ * Node Editor MCP Tools+ *+ * Provides AI/Chat access to the node-based workflow editor.+ * Allows LLM to:+ * - List available nodes and their configurations+ * - Create complete workflows with nodes and edges+ * - Save workflows to the node editor for execution+ * - Execute and manage workflows+ */++import { InternalTool } from '../types';++/**+ * Node categories for easier discovery+ */+const NODE_CATEGORIES = [+ 'trigger', // Workflow entry points (ManualTrigger, ScheduleTrigger, PriceAlert, etc.)+ 'marketData', // Market data nodes (YFinance, GetQuote, GetHistoricalData, etc.)+ 'trading', // Trading nodes (PlaceOrder, CancelOrder, GetPositions, etc.)+ 'analytics', // Analytics nodes (TechnicalIndicators, PortfolioOptimization, Backtest, etc.)+ 'controlFlow', // Control flow (IfElse, Switch, Loop, Wait, Merge, Split, etc.)+ 'transform', // Data transformation (Filter, Map, Aggregate, Sort, GroupBy, Join, etc.)+ 'safety', // Risk management (RiskCheck, PositionSizeLimit, LossLimit, etc.)+ 'notifications', // Notifications (Webhook, Email, Telegram, Discord, Slack, SMS)+ 'agents', // AI agents (AgentMediator, GeopoliticsAgent, HedgeFundAgent, etc.)+ 'core', // Core nodes (Filter, Merge, Set, Switch, Code)+];++/**+ * Available node types mapped to their internal names+ * This helps LLM know exactly which node types exist+ */+const AVAILABLE_NODE_TYPES = {+ // Triggers+ manualTrigger: 'Start workflow manually',+ scheduleTrigger: 'Run on schedule (cron)',+ priceAlertTrigger: 'Trigger when price hits threshold',+ newsEventTrigger: 'Trigger on news events',+ marketEventTrigger: 'Trigger on market open/close/volatility',+ webhookTrigger: 'Trigger from external webhook',++ // Market Data+ yfinance: 'Fetch stock data from Yahoo Finance',+ getQuote: 'Get real-time price quote',+ getHistoricalData: 'Fetch historical OHLCV data',+ getMarketDepth: 'Get order book depth',+ streamQuotes: 'Stream real-time quotes (WebSocket)',+ getFundamentals: 'Fetch fundamental data (P/E, dividends)',+ getTickerStats: 'Get ticker statistics',+ stockData: 'General stock data node',++ // Trading+ placeOrder: 'Place buy/sell order',+ modifyOrder: 'Modify existing order',+ cancelOrder: 'Cancel open order',+ getPositions: 'Get current positions',+ getHoldings: 'Get portfolio holdings',+ getOrders: 'Get order history',+ getBalance: 'Get account balance',+ closePosition: 'Close a position',++ // Analytics+ technicalIndicators: 'Calculate technical indicators (RSI, MACD, SMA, EMA, BB, etc.)',+ portfolioOptimization: 'Optimize portfolio allocation (Mean-Variance)',+ backtestEngine: 'Backtest trading strategy',+ riskAnalysis: 'Calculate risk metrics (VaR, Sharpe, etc.)',+ performanceMetrics: 'Analyze performance (returns, drawdown)',+ correlationMatrix: 'Calculate asset correlations',++ // Control Flow+ ifElse: 'Conditional branching (if/else)',+ switch: 'Multi-way routing based on value',+ loop: 'Iterate over array items',+ wait: 'Pause execution for duration',+ merge: 'Combine multiple data streams',+ split: 'Split stream into multiple',+ errorHandler: 'Catch and handle errors',++ // Transform+ filterTransform: 'Filter items by condition',+ map: 'Transform each item',+ aggregate: 'Aggregate data (sum, avg, count)',+ sort: 'Sort items by field',+ groupBy: 'Group items by field',+ join: 'Join two datasets',+ deduplicate: 'Remove duplicates',+ reshape: 'Restructure data shape',++ // Safety+ riskCheck: 'Validate against risk limits',+ positionSizeLimit: 'Enforce position size limits',+ lossLimit: 'Enforce max loss limits',+ tradingHoursCheck: 'Validate trading hours',++ // Notifications+ webhookNotification: 'Send HTTP webhook',+ email: 'Send email notification',+ telegram: 'Send Telegram message',+ discord: 'Send Discord message',+ slack: 'Send Slack message',+ sms: 'Send SMS notification',++ // AI Agents+ agentMediator: 'Mediate between AI agents',+ agent: 'Custom AI agent',+ multiAgent: 'Orchestrate multiple agents',+ geopoliticsAgent: 'Geopolitical analysis',+ hedgeFundAgent: 'Hedge fund strategy',+ investorAgent: 'Investor persona analysis',++ // Core+ filter: 'Basic filter node',+ set: 'Set/modify data fields',+ code: 'Execute custom JavaScript',+};++export const nodeEditorTools: InternalTool[] = [+ // ============================================================================+ // SMART WORKFLOW BUILDER (PRIMARY TOOL FOR LLM)+ // ============================================================================+ {+ name: 'node_editor_build_workflow',+ description: `PREFERRED TOOL: Build a workflow automatically using available nodes. Describe what you want the workflow to do and this tool will create it with sensible defaults.++AVAILABLE NODE TYPES:+${Object.entries(AVAILABLE_NODE_TYPES).map(([type, desc]) => `- ${type}: ${desc}`).join('\n')}++PRIMARY DATA SOURCE: yfinance (Yahoo Finance)+The yfinance node is the main data source supporting:+- Historical OHLCV data (operation: "history")+- Real-time quotes (operation: "quote")+- Company info, financials, balance sheet, cash flow+- Earnings, dividends, splits, recommendations+- Options chains, institutional holders, ESG data++WORKFLOW PATTERNS:+1. Technical Analysis: manualTrigger -> yfinance(history) -> technicalIndicators -> results+2. Alert System: manualTrigger -> yfinance(quote) -> ifElse (condition) -> telegram/discord+3. Trading Bot: scheduleTrigger -> yfinance(quote) -> technicalIndicators -> ifElse -> riskCheck -> placeOrder+4. Fundamental Analysis: manualTrigger -> yfinance(financials/balanceSheet) -> transform -> results+5. Backtesting: manualTrigger -> yfinance(history, 1y+) -> technicalIndicators -> backtestEngine++DEFAULT PARAMETERS:+- yfinance: operation="history", period="1mo", interval="1d" (for technical analysis)+- yfinance: operation="quote" (for real-time alerts)+- technicalIndicators: indicator="RSI", period=14+- ifElse: uses expression like "{{$json.RSI}} < 30"+- placeOrder: paperTrading=true, includes riskCheck by default++Just describe what you want and provide any specific symbols, indicators, or conditions.`,+ inputSchema: {+ type: 'object',+ properties: {+ name: {+ type: 'string',+ description: 'Workflow name',+ },+ goal: {+ type: 'string',+ description: 'What should this workflow do? E.g., "Monitor AAPL RSI and alert when oversold", "Backtest SMA crossover strategy on TSLA"',+ },+ symbols: {+ type: 'string',+ description: 'Stock/crypto symbols to use (comma-separated). E.g., "AAPL", "AAPL,MSFT,GOOGL"',+ },+ data_type: {+ type: 'string',+ description: 'What data to fetch from yfinance: history (default, OHLCV), quote (real-time), info, financials, balanceSheet, cashFlow, earnings, dividends, recommendations, options',+ enum: ['history', 'quote', 'info', 'financials', 'balanceSheet', 'cashFlow', 'earnings', 'dividends', 'recommendations', 'options', ''],+ },+ period: {+ type: 'string',+ description: 'Data period for history: 1d, 5d, 1mo (default), 3mo, 6mo, 1y, 2y, 5y, ytd, max',+ enum: ['1d', '5d', '1mo', '3mo', '6mo', '1y', '2y', '5y', 'ytd', 'max', ''],+ },+ interval: {+ type: 'string',+ description: 'Data interval: 1m, 5m, 15m, 30m, 1h, 1d (default), 1wk, 1mo',+ enum: ['1m', '5m', '15m', '30m', '1h', '1d', '1wk', '1mo', ''],+ },+ indicators: {+ type: 'string',+ description: 'Technical indicators with optional periods. Format: "RSI" or "RSI:14,MACD:12,SMA:20,EMA:9,BB:20". Available: RSI, MACD, SMA, EMA, BB, ATR, ADX, STOCH, OBV, VWAP. Leave empty for data-only workflows.',+ },+ conditions: {+ type: 'string',+ description: 'Conditions for alerts/actions. Use {{$json.field}} syntax. E.g., "{{$json.RSI}} < 30", "{{$json.close}} > 150", "{{$json.MACD}} > {{$json.signal}}"',+ },+ notification_type: {+ type: 'string',+ description: 'How to notify: telegram, discord, slack, email, webhook, or none',+ enum: ['telegram', 'discord', 'slack', 'email', 'webhook', 'none', ''],+ },+ notification_message: {+ type: 'string',+ description: 'Custom notification message. Can use {{$json.field}} placeholders. Default: "{symbol} Alert triggered!"',+ },+ include_trading: {+ type: 'string',+ description: 'Include trading nodes? "yes" adds risk check + place order nodes',+ enum: ['yes', 'no', ''],+ },+ trade_side: {+ type: 'string',+ description: 'If include_trading=yes, the trade direction',+ enum: ['BUY', 'SELL', ''],+ },+ trade_quantity: {+ type: 'number',+ description: 'If include_trading=yes, quantity to trade. Default: 1',+ },+ trade_order_type: {+ type: 'string',+ description: 'If include_trading=yes, order type',+ enum: ['MARKET', 'LIMIT', ''],+ },+ max_position_size: {+ type: 'number',+ description: 'If include_trading=yes, max position size for risk check. Default: 1000',+ },+ max_daily_loss: {+ type: 'number',+ description: 'If include_trading=yes, max daily loss for risk check. Default: 500',+ },+ trigger_type: {+ type: 'string',+ description: 'How to start: manual (default), schedule, priceAlert',+ enum: ['manual', 'schedule', 'priceAlert', ''],+ },+ schedule: {+ type: 'string',+ description: 'If trigger_type=schedule, cron expression. E.g., "0 9 * * 1-5" for 9am weekdays',+ },+ price_alert_threshold: {+ type: 'number',+ description: 'If trigger_type=priceAlert, the price threshold',+ },+ },+ required: ['name', 'goal'],+ },+ handler: async (args, contexts) => {+ if (!contexts.createNodeWorkflow) {+ return { success: false, error: 'Node editor context not available' };+ }++ // Parse inputs - LLM provides all parameters explicitly+ const symbols = args.symbols ? args.symbols.split(',').map((s: string) => s.trim().toUpperCase()) : ['AAPL'];+ const dataType = args.data_type || 'history';+ const period = args.period || '1mo';+ const interval = args.interval || '1d';+ const triggerType = args.trigger_type || 'manual';+ const notificationType = args.notification_type || 'none';+ const includeTrading = args.include_trading === 'yes';+ const primarySymbol = symbols[0];++ // Parse indicators with optional periods: "RSI:14,MACD:12,SMA:20" or "RSI,MACD,SMA"+ const indicatorConfigs: Array<{ name: string; period: number }> = [];+ if (args.indicators) {+ const parts = args.indicators.split(',').map((s: string) => s.trim().toUpperCase());+ for (const part of parts) {+ if (part.includes(':')) {+ const [name, periodStr] = part.split(':');+ indicatorConfigs.push({ name: name.trim(), period: parseInt(periodStr) || 14 });+ } else {+ // Default periods if not specified+ const defaultPeriods: Record<string, number> = {+ RSI: 14, MACD: 12, SMA: 20, EMA: 9, BB: 20, ATR: 14, ADX: 14, STOCH: 14, OBV: 0, VWAP: 0+ };+ indicatorConfigs.push({ name: part, period: defaultPeriods[part] || 14 });+ }+ }+ }++ // Trading parameters+ const tradeSide = args.trade_side || 'BUY';+ const tradeQuantity = args.trade_quantity || 1;+ const tradeOrderType = args.trade_order_type || 'MARKET';+ const maxPositionSize = args.max_position_size || 1000;+ const maxDailyLoss = args.max_daily_loss || 500;+ const priceAlertThreshold = args.price_alert_threshold || 0;++ // Build nodes array using ReactFlow UI node types+ // The UI expects specific node types: 'data-source', 'technical-indicator', 'custom', 'backtest', etc.+ const nodes: any[] = [];+ const edges: any[] = [];+ let xPos = 100;+ let yPos = 100;+ const xStep = 280;+ const yStep = 150;++ // Helper to add node with proper ReactFlow structure+ // The 'type' is the UI component type, 'nodeType' is the backend execution type+ const addNode = (id: string, uiType: string, backendType: string, data: any, label: string, color: string) => {+ nodes.push({+ id,+ type: uiType, // UI component type (data-source, technical-indicator, custom, etc.)+ position: { x: xPos, y: yPos },+ parameters: {+ nodeType: backendType, // Backend execution type (yfinance, technicalIndicators, etc.)+ ...data,+ },+ label,+ });+ xPos += xStep;+ return id;+ };++ // Helper to connect nodes+ const connect = (source: string, target: string, sourceHandle?: string) => {+ edges.push({ source, target, sourceHandle });+ };++ // 1. Add trigger node (system type for triggers)+ let lastNodeId: string;+ if (triggerType === 'schedule' && args.schedule) {+ lastNodeId = addNode('trigger', 'system', 'scheduleTrigger', {+ cronExpression: args.schedule,+ icon: 'Clock',+ }, 'Schedule Trigger', '#a855f7');+ } else if (triggerType === 'priceAlert') {+ lastNodeId = addNode('trigger', 'system', 'priceAlertTrigger', {+ symbol: primarySymbol,+ threshold: priceAlertThreshold,+ icon: 'Bell',+ }, `Price Alert ($${priceAlertThreshold})`, '#f97316');+ } else {+ lastNodeId = addNode('trigger', 'system', 'manualTrigger', {+ icon: 'Play',+ }, 'Manual Start', '#10b981');+ }++ // 2. Add data fetching node (data-source type)+ const yfinanceParams: any = {+ symbol: primarySymbol,+ operation: dataType,+ dataSource: 'yfinance',+ };++ // Add history-specific params+ if (dataType === 'history') {+ yfinanceParams.period = period;+ yfinanceParams.interval = interval;+ yfinanceParams.autoAdjust = true;+ }++ // Add financials-specific params+ if (['financials', 'balanceSheet', 'cashFlow'].includes(dataType)) {+ yfinanceParams.frequency = 'annual';+ }++ const operationLabel = dataType === 'history' ? `${primarySymbol} Historical (${period})` :+ dataType === 'quote' ? `${primarySymbol} Quote` :+ `${primarySymbol} ${dataType.charAt(0).toUpperCase() + dataType.slice(1)}`;++ const dataNodeId = addNode('fetch_data', 'data-source', 'yfinance', yfinanceParams, operationLabel, '#3b82f6');+ connect(lastNodeId, dataNodeId);+ lastNodeId = dataNodeId;++ // 3. Add technical indicators (technical-indicator type)+ if (indicatorConfigs.length > 0 && dataType === 'history') {+ // For multiple indicators, combine them into one node+ const indicatorList = indicatorConfigs.map(ic => `${ic.name}(${ic.period})`).join(', ');+ const indicatorId = addNode('indicators', 'technical-indicator', 'technicalIndicators', {+ indicators: indicatorConfigs,+ symbol: primarySymbol,+ // First indicator as primary+ indicator: indicatorConfigs[0].name,+ period: indicatorConfigs[0].period,+ }, `Indicators: ${indicatorList}`, '#10b981');+ connect(lastNodeId, indicatorId);+ lastNodeId = indicatorId;+ }++ // 4. Add condition check if conditions provided+ if (args.conditions) {+ yPos += yStep; // Move down for branching+ xPos = 100 + xStep * 3; // Position after indicators++ const conditionId = addNode('condition', 'custom', 'ifElse', {+ condition: args.conditions,+ icon: 'GitBranch',+ color: '#eab308',+ }, `If: ${args.conditions}`, '#eab308');+ connect(lastNodeId, conditionId);+ lastNodeId = conditionId;++ // Branch for true condition+ let trueNodeId = lastNodeId;++ // 5. Add safety check if trading enabled+ if (includeTrading) {+ yPos += yStep; // Move down+ xPos = 100 + xStep * 4;++ const riskCheckId = addNode('risk_check', 'custom', 'riskCheck', {+ maxPositionSize: maxPositionSize,+ maxDailyLoss: maxDailyLoss,+ icon: 'Shield',+ color: '#ef4444',+ }, `Risk Check (max: $${maxPositionSize})`, '#ef4444');+ connect(lastNodeId, riskCheckId, 'true');++ const orderNodeId = addNode('place_order', 'custom', 'placeOrder', {+ symbol: primarySymbol,+ orderType: tradeOrderType,+ side: tradeSide,+ quantity: tradeQuantity,+ paperTrading: true,+ icon: 'TrendingUp',+ color: '#14b8a6',+ }, `${tradeSide} ${tradeQuantity} ${primarySymbol}`, '#14b8a6');+ connect(riskCheckId, orderNodeId);+ trueNodeId = orderNodeId;+ }++ // 6. Add notification if requested+ if (notificationType && notificationType !== 'none') {+ const message = args.notification_message || `${primarySymbol} Alert: Condition triggered!`;+ xPos += xStep;++ const notifyId = addNode('notify', 'custom', notificationType, {+ message: message,+ notificationType: notificationType,+ icon: 'Bell',+ color: '#f97316',+ }, `${notificationType.charAt(0).toUpperCase() + notificationType.slice(1)} Alert`, '#f97316');+ connect(includeTrading ? trueNodeId : lastNodeId, notifyId, includeTrading ? undefined : 'true');+ }+ } else {+ // No condition - add results display or notification+ if (notificationType && notificationType !== 'none') {+ const message = args.notification_message || `${primarySymbol} analysis complete.`;+ const notifyId = addNode('notify', 'custom', notificationType, {+ message: message,+ notificationType: notificationType,+ icon: 'Bell',+ color: '#f97316',+ }, `${notificationType.charAt(0).toUpperCase() + notificationType.slice(1)} Notification`, '#f97316');+ connect(lastNodeId, notifyId);+ } else {+ // Add results display at the end+ const resultsId = addNode('results', 'results-display', 'resultsDisplay', {+ displayFormat: 'table',+ }, 'Results', '#f59e0b');+ connect(lastNodeId, resultsId);+ }+ }++ // Create the workflow+ const result = await contexts.createNodeWorkflow({+ name: args.name,+ description: args.goal,+ nodes,+ edges,+ });++ return {+ success: true,+ data: {+ workflowId: result.id,+ workflow: result,+ summary: {+ nodesCount: nodes.length,+ edgesCount: edges.length,+ symbols: symbols,+ dataSource: 'yfinance',+ dataType: dataType,+ period: dataType === 'history' ? period : undefined,+ interval: dataType === 'history' ? interval : undefined,+ indicators: indicatorConfigs.length > 0 ? indicatorConfigs : undefined,+ conditions: args.conditions || undefined,+ trading: includeTrading ? {+ side: tradeSide,+ quantity: tradeQuantity,+ orderType: tradeOrderType,+ riskLimits: { maxPositionSize, maxDailyLoss }+ } : undefined,+ notifications: notificationType !== 'none' && notificationType !== '' ? {+ type: notificationType,+ message: args.notification_message || 'default'+ } : undefined,+ },+ },+ message: `Workflow "${args.name}" created with ${nodes.length} nodes! View it in the Node Editor tab (tab: "nodes"). Workflow ID: ${result.id}`,+ };+ },+ },++ // ============================================================================+ // NODE DISCOVERY TOOLS+ // ============================================================================+ {+ name: 'node_editor_list_available_nodes',+ description: `List all available nodes in the workflow editor. Returns node types with their configurations, parameters, and connection types. Use this to understand what nodes can be used to build a workflow.++Categories available: ${NODE_CATEGORIES.join(', ')}++Common use cases:+- "What nodes are available for technical analysis?" -> filter by 'analytics' category+- "Show me trading nodes" -> filter by 'trading' category+- "What trigger nodes can start a workflow?" -> filter by 'trigger' category`,+ inputSchema: {+ type: 'object',+ properties: {+ category: {+ type: 'string',+ description: `Filter by category: ${NODE_CATEGORIES.join(', ')}. Leave empty to get all nodes.`,+ enum: [...NODE_CATEGORIES, ''],+ },+ search: {+ type: 'string',+ description: 'Search query to filter nodes by name or description',+ },+ },+ required: [],+ },+ handler: async (args, contexts) => {+ if (!contexts.listAvailableNodes) {+ return { success: false, error: 'Node editor context not available' };+ }+ const nodes = await contexts.listAvailableNodes(args.category, args.search);+ return {+ success: true,+ data: nodes,+ message: `Found ${nodes.length} nodes${args.category ? ` in category '${args.category}'` : ''}`,+ };+ },+ },++ {+ name: 'node_editor_get_node_details',+ description: `Get detailed information about a specific node type including all its parameters, default values, and connection types. Use this before configuring a node in a workflow.`,+ inputSchema: {+ type: 'object',+ properties: {+ node_type: {+ type: 'string',+ description: 'The node type name (e.g., "technicalIndicators", "placeOrder", "yfinance")',+ },+ },+ required: ['node_type'],+ },+ handler: async (args, contexts) => {+ if (!contexts.getNodeDetails) {+ return { success: false, error: 'Node editor context not available' };+ }+ const details = await contexts.getNodeDetails(args.node_type);+ if (!details) {+ return { success: false, error: `Node type '${args.node_type}' not found` };+ }+ return {+ success: true,+ data: details,+ message: `Node details for '${details.displayName}'`,+ };+ },+ },++ {+ name: 'node_editor_get_node_categories',+ description: 'Get all available node categories with their descriptions and node counts.',+ inputSchema: {+ type: 'object',+ properties: {},+ required: [],+ },+ handler: async (_args, contexts) => {+ if (!contexts.getNodeCategories) {+ return { success: false, error: 'Node editor context not available' };+ }+ const categories = await contexts.getNodeCategories();+ return {+ success: true,+ data: categories,+ message: `Found ${categories.length} node categories`,+ };+ },+ },++ // ============================================================================+ // WORKFLOW CREATION TOOLS+ // ============================================================================+ {+ name: 'node_editor_create_workflow',+ description: `Create a complete workflow with nodes and edges. The workflow will be saved and available in the Node Editor tab.++IMPORTANT:+- Each node needs a unique ID (use descriptive names like 'trigger_1', 'fetch_data_1', 'indicators_1')+- Position nodes logically (start from left, flow to right). Use x: 100, 280, 560... and y: 100+- Use UI node types: 'system' (triggers), 'data-source' (data fetching), 'technical-indicator', 'custom', 'results-display'+- Include nodeType in parameters for backend execution type+- Include color and label for proper rendering++Example workflow structure:+{+ "name": "RSI Alert Workflow",+ "description": "Fetches stock data and calculates RSI, sends alert if oversold",+ "nodes": [+ { "id": "trigger_1", "type": "system", "position": { "x": 100, "y": 100 }, "parameters": { "nodeType": "manualTrigger", "color": "#10b981" }, "label": "Manual Start" },+ { "id": "data_1", "type": "data-source", "position": { "x": 380, "y": 100 }, "parameters": { "nodeType": "yfinance", "symbol": "AAPL", "period": "1mo", "operation": "history", "color": "#3b82f6" }, "label": "AAPL Historical" },+ { "id": "rsi_1", "type": "technical-indicator", "position": { "x": 660, "y": 100 }, "parameters": { "nodeType": "technicalIndicators", "indicator": "RSI", "period": 14, "color": "#10b981" }, "label": "RSI(14)" },+ { "id": "check_1", "type": "custom", "position": { "x": 940, "y": 100 }, "parameters": { "nodeType": "ifElse", "condition": "{{$json.RSI}} < 30", "color": "#eab308" }, "label": "If RSI < 30" },+ { "id": "alert_1", "type": "custom", "position": { "x": 1220, "y": 50 }, "parameters": { "nodeType": "telegram", "message": "RSI Oversold Alert!", "color": "#f97316" }, "label": "Telegram Alert" }+ ],+ "edges": [+ { "source": "trigger_1", "target": "data_1" },+ { "source": "data_1", "target": "rsi_1" },+ { "source": "rsi_1", "target": "check_1" },+ { "source": "check_1", "target": "alert_1", "sourceHandle": "true" }+ ]+}`,+ inputSchema: {+ type: 'object',+ properties: {+ name: {+ type: 'string',+ description: 'Workflow name (e.g., "RSI Alert Strategy", "Portfolio Rebalancer")',+ },+ description: {+ type: 'string',+ description: 'Description of what the workflow does',+ },+ nodes: {+ type: 'string',+ description: 'JSON array of nodes. Each node has: id (string), type (node type name), position ({x, y}), parameters (object with node-specific config)',+ },+ edges: {+ type: 'string',+ description: 'JSON array of edges connecting nodes. Each edge has: source (node id), target (node id), optional sourceHandle/targetHandle for specific outputs',+ },+ },+ required: ['name', 'nodes', 'edges'],+ },+ handler: async (args, contexts) => {+ if (!contexts.createNodeWorkflow) {+ return { success: false, error: 'Node editor context not available' };+ }++ // Parse nodes and edges from JSON strings+ let nodes, edges;+ try {+ nodes = typeof args.nodes === 'string' ? JSON.parse(args.nodes) : args.nodes;+ edges = typeof args.edges === 'string' ? JSON.parse(args.edges) : args.edges;+ } catch (e) {+ return { success: false, error: `Invalid JSON in nodes or edges: ${e}` };+ }++ const result = await contexts.createNodeWorkflow({+ name: args.name,+ description: args.description || '',+ nodes,+ edges,+ });++ return {+ success: true,+ data: result,+ message: `Workflow "${args.name}" created with ${nodes.length} nodes and ${edges.length} edges. ID: ${result.id}`,+ };+ },+ },++ {+ name: 'node_editor_add_node_to_workflow',+ description: `Add a single node to an existing workflow. Useful for building workflows incrementally.`,+ inputSchema: {+ type: 'object',+ properties: {+ workflow_id: {+ type: 'string',+ description: 'The workflow ID to add the node to',+ },+ node_id: {+ type: 'string',+ description: 'Unique ID for the new node (e.g., "indicator_2", "alert_1")',+ },+ node_type: {+ type: 'string',+ description: 'Type of node to add (e.g., "technicalIndicators", "placeOrder")',+ },+ position_x: {+ type: 'number',+ description: 'X position in the editor (default: auto-calculated)',+ default: 100,+ },+ position_y: {+ type: 'number',+ description: 'Y position in the editor (default: auto-calculated)',+ default: 100,+ },+ parameters: {+ type: 'string',+ description: 'JSON object with node parameters',+ },+ label: {+ type: 'string',+ description: 'Display label for the node',+ },+ },+ required: ['workflow_id', 'node_id', 'node_type'],+ },+ handler: async (args, contexts) => {+ if (!contexts.addNodeToWorkflow) {+ return { success: false, error: 'Node editor context not available' };+ }++ let parameters = {};+ if (args.parameters) {+ try {+ parameters = typeof args.parameters === 'string' ? JSON.parse(args.parameters) : args.parameters;+ } catch (e) {+ return { success: false, error: `Invalid JSON in parameters: ${e}` };+ }+ }++ const result = await contexts.addNodeToWorkflow({+ workflowId: args.workflow_id,+ nodeId: args.node_id,+ nodeType: args.node_type,+ position: { x: args.position_x || 100, y: args.position_y || 100 },+ parameters,+ label: args.label,+ });++ return {+ success: true,+ data: result,+ message: `Node '${args.node_id}' of type '${args.node_type}' added to workflow`,+ };+ },+ },++ {+ name: 'node_editor_connect_nodes',+ description: `Connect two nodes in a workflow with an edge. Creates the data flow between nodes.`,+ inputSchema: {+ type: 'object',+ properties: {+ workflow_id: {+ type: 'string',+ description: 'The workflow ID',+ },+ source_node_id: {+ type: 'string',+ description: 'ID of the source node (output)',+ },+ target_node_id: {+ type: 'string',+ description: 'ID of the target node (input)',+ },+ source_handle: {+ type: 'string',+ description: 'Output handle name (e.g., "true", "false" for IfElse, or "main" for standard)',+ },+ target_handle: {+ type: 'string',+ description: 'Input handle name (usually "main")',+ },+ },+ required: ['workflow_id', 'source_node_id', 'target_node_id'],+ },+ handler: async (args, contexts) => {+ if (!contexts.connectNodes) {+ return { success: false, error: 'Node editor context not available' };+ }++ const result = await contexts.connectNodes({+ workflowId: args.workflow_id,+ sourceNodeId: args.source_node_id,+ targetNodeId: args.target_node_id,+ sourceHandle: args.source_handle || 'main',+ targetHandle: args.target_handle || 'main',+ });++ return {+ success: true,+ data: result,+ message: `Connected '${args.source_node_id}' -> '${args.target_node_id}'`,+ };+ },+ },++ {+ name: 'node_editor_configure_node',+ description: `Update the parameters/configuration of a node in a workflow.`,+ inputSchema: {+ type: 'object',+ properties: {+ workflow_id: {+ type: 'string',+ description: 'The workflow ID',+ },+ node_id: {+ type: 'string',+ description: 'ID of the node to configure',+ },+ parameters: {+ type: 'string',+ description: 'JSON object with parameter updates (will be merged with existing)',+ },+ },+ required: ['workflow_id', 'node_id', 'parameters'],+ },+ handler: async (args, contexts) => {+ if (!contexts.configureNode) {+ return { success: false, error: 'Node editor context not available' };+ }++ let parameters;+ try {+ parameters = typeof args.parameters === 'string' ? JSON.parse(args.parameters) : args.parameters;+ } catch (e) {+ return { success: false, error: `Invalid JSON in parameters: ${e}` };+ }++ const result = await contexts.configureNode({+ workflowId: args.workflow_id,+ nodeId: args.node_id,+ parameters,+ });++ return {+ success: true,+ data: result,+ message: `Node '${args.node_id}' configured successfully`,+ };+ },+ },++ // ============================================================================+ // WORKFLOW MANAGEMENT TOOLS+ // ============================================================================+ {+ name: 'node_editor_list_workflows',+ description: 'List all saved workflows in the node editor. Returns workflow IDs, names, descriptions, and status.',+ inputSchema: {+ type: 'object',+ properties: {+ status: {+ type: 'string',+ description: 'Filter by status: idle, running, completed, error, draft',+ enum: ['idle', 'running', 'completed', 'error', 'draft', ''],+ },+ },+ required: [],+ },+ handler: async (args, contexts) => {+ if (!contexts.listNodeWorkflows) {+ return { success: false, error: 'Node editor context not available' };+ }+ const workflows = await contexts.listNodeWorkflows(args.status);+ return {+ success: true,+ data: workflows,+ message: `Found ${workflows.length} workflows`,+ };+ },+ },++ {+ name: 'node_editor_get_workflow',+ description: 'Get complete details of a workflow including all nodes, edges, and their configurations.',+ inputSchema: {+ type: 'object',+ properties: {+ workflow_id: {+ type: 'string',+ description: 'The workflow ID to retrieve',+ },+ },+ required: ['workflow_id'],+ },+ handler: async (args, contexts) => {+ if (!contexts.getNodeWorkflow) {+ return { success: false, error: 'Node editor context not available' };+ }+ const workflow = await contexts.getNodeWorkflow(args.workflow_id);+ if (!workflow) {+ return { success: false, error: `Workflow '${args.workflow_id}' not found` };+ }+ return {+ success: true,+ data: workflow,+ message: `Workflow "${workflow.name}" with ${(workflow.nodes || []).length} nodes`,+ };+ },+ },++ {+ name: 'node_editor_update_workflow',+ description: 'Update an existing workflow (name, description, or full node/edge replacement).',+ inputSchema: {+ type: 'object',+ properties: {+ workflow_id: {+ type: 'string',+ description: 'The workflow ID to update',+ },+ name: {+ type: 'string',+ description: 'New workflow name',+ },+ description: {+ type: 'string',+ description: 'New workflow description',+ },+ nodes: {+ type: 'string',+ description: 'Optional: JSON array of nodes to replace existing nodes',+ },+ edges: {+ type: 'string',+ description: 'Optional: JSON array of edges to replace existing edges',+ },+ },+ required: ['workflow_id'],+ },+ handler: async (args, contexts) => {+ if (!contexts.updateNodeWorkflow) {+ return { success: false, error: 'Node editor context not available' };+ }++ let nodes, edges;+ if (args.nodes) {+ try {+ nodes = typeof args.nodes === 'string' ? JSON.parse(args.nodes) : args.nodes;+ } catch (e) {+ return { success: false, error: `Invalid JSON in nodes: ${e}` };+ }+ }+ if (args.edges) {+ try {+ edges = typeof args.edges === 'string' ? JSON.parse(args.edges) : args.edges;+ } catch (e) {+ return { success: false, error: `Invalid JSON in edges: ${e}` };+ }+ }++ const result = await contexts.updateNodeWorkflow({+ workflowId: args.workflow_id,+ name: args.name,+ description: args.description,+ nodes,+ edges,+ });++ return {+ success: true,+ data: result,+ message: `Workflow '${args.workflow_id}' updated successfully`,+ };+ },+ },++ {+ name: 'node_editor_delete_workflow',+ description: 'Delete a workflow from the node editor.',+ inputSchema: {+ type: 'object',+ properties: {+ workflow_id: {+ type: 'string',+ description: 'The workflow ID to delete',+ },+ },+ required: ['workflow_id'],+ },+ handler: async (args, contexts) => {+ if (!contexts.deleteNodeWorkflow) {+ return { success: false, error: 'Node editor context not available' };+ }+ await contexts.deleteNodeWorkflow(args.workflow_id);+ return {+ success: true,+ message: `Workflow '${args.workflow_id}' deleted`,+ };+ },+ },++ {+ name: 'node_editor_duplicate_workflow',+ description: 'Duplicate an existing workflow with a new name.',+ inputSchema: {+ type: 'object',+ properties: {+ workflow_id: {+ type: 'string',+ description: 'The workflow ID to duplicate',+ },+ new_name: {+ type: 'string',+ description: 'Name for the duplicated workflow',+ },+ },+ required: ['workflow_id', 'new_name'],+ },+ handler: async (args, contexts) => {+ if (!contexts.duplicateNodeWorkflow) {+ return { success: false, error: 'Node editor context not available' };+ }+ const result = await contexts.duplicateNodeWorkflow(args.workflow_id, args.new_name);+ return {+ success: true,+ data: result,+ message: `Workflow duplicated as "${args.new_name}" with ID: ${result.id}`,+ };+ },+ },++ // ============================================================================+ // WORKFLOW EXECUTION TOOLS+ // ============================================================================+ {+ name: 'node_editor_execute_workflow',+ description: 'Execute a workflow. The workflow will run all nodes from triggers to outputs.',+ inputSchema: {+ type: 'object',+ properties: {+ workflow_id: {+ type: 'string',+ description: 'The workflow ID to execute',+ },+ input_data: {+ type: 'string',+ description: 'Optional JSON input data for the workflow (passed to trigger nodes)',+ },+ },+ required: ['workflow_id'],+ },+ handler: async (args, contexts) => {+ if (!contexts.executeNodeWorkflow) {+ return { success: false, error: 'Node editor context not available' };+ }++ let inputData;+ if (args.input_data) {+ try {+ inputData = typeof args.input_data === 'string' ? JSON.parse(args.input_data) : args.input_data;+ } catch (e) {+ return { success: false, error: `Invalid JSON in input_data: ${e}` };+ }+ }++ const result = await contexts.executeNodeWorkflow(args.workflow_id, inputData);+ return {+ success: true,+ data: result,+ message: `Workflow execution ${result.success ? 'completed' : 'failed'}`,+ };+ },+ },++ {+ name: 'node_editor_stop_workflow',+ description: 'Stop a running workflow execution.',+ inputSchema: {+ type: 'object',+ properties: {+ workflow_id: {+ type: 'string',+ description: 'The workflow ID to stop',+ },+ },+ required: ['workflow_id'],+ },+ handler: async (args, contexts) => {+ if (!contexts.stopNodeWorkflow) {+ return { success: false, error: 'Node editor context not available' };+ }+ await contexts.stopNodeWorkflow(args.workflow_id);+ return {+ success: true,+ message: `Workflow '${args.workflow_id}' stopped`,+ };+ },+ },++ {+ name: 'node_editor_get_execution_results',+ description: 'Get the results of a workflow execution including output from each node.',+ inputSchema: {+ type: 'object',+ properties: {+ workflow_id: {+ type: 'string',+ description: 'The workflow ID to get results for',+ },+ },+ required: ['workflow_id'],+ },+ handler: async (args, contexts) => {+ if (!contexts.getWorkflowResults) {+ return { success: false, error: 'Node editor context not available' };+ }+ const results = await contexts.getWorkflowResults(args.workflow_id);+ return {+ success: true,+ data: results,+ message: results ? 'Execution results retrieved' : 'No results available',+ };+ },+ },++ // ============================================================================+ // HELPER TOOLS+ // ============================================================================+ {+ name: 'node_editor_validate_workflow',+ description: 'Validate a workflow for errors before execution. Checks for missing connections, invalid parameters, etc.',+ inputSchema: {+ type: 'object',+ properties: {+ workflow_id: {+ type: 'string',+ description: 'The workflow ID to validate',+ },+ },+ required: ['workflow_id'],+ },+ handler: async (args, contexts) => {+ if (!contexts.validateNodeWorkflow) {+ return { success: false, error: 'Node editor context not available' };+ }+ const validation = await contexts.validateNodeWorkflow(args.workflow_id);+ return {+ success: true,+ data: validation,+ message: validation.valid ? 'Workflow is valid' : `Found ${validation.errors.length} issues`,+ };+ },+ },++ {+ name: 'node_editor_open_workflow',+ description: 'Open a workflow in the Node Editor tab (tab: "nodes") for visual editing. Navigates to the Node Editor and loads the workflow.',+ inputSchema: {+ type: 'object',+ properties: {+ workflow_id: {+ type: 'string',+ description: 'The workflow ID to open in the editor',+ },+ },+ required: ['workflow_id'],+ },+ handler: async (args, contexts) => {+ if (!contexts.openWorkflowInEditor) {+ return { success: false, error: 'Node editor context not available' };+ }+ await contexts.openWorkflowInEditor(args.workflow_id);+ return {+ success: true,+ message: `Workflow opened in Node Editor. You can now visually edit it.`,+ };+ },+ },++ {+ name: 'node_editor_export_workflow',+ description: 'Export a workflow as JSON for sharing or backup.',+ inputSchema: {+ type: 'object',+ properties: {+ workflow_id: {+ type: 'string',+ description: 'The workflow ID to export',+ },+ },+ required: ['workflow_id'],+ },+ handler: async (args, contexts) => {+ if (!contexts.exportNodeWorkflow) {+ return { success: false, error: 'Node editor context not available' };+ }+ const exported = await contexts.exportNodeWorkflow(args.workflow_id);+ return {+ success: true,+ data: exported,+ message: 'Workflow exported as JSON',+ };+ },+ },++ {+ name: 'node_editor_import_workflow',+ description: 'Import a workflow from JSON.',+ inputSchema: {+ type: 'object',+ properties: {+ workflow_json: {+ type: 'string',+ description: 'JSON string of the workflow to import',+ },+ new_name: {+ type: 'string',+ description: 'Optional: Override the workflow name',+ },+ },+ required: ['workflow_json'],+ },+ handler: async (args, contexts) => {+ if (!contexts.importNodeWorkflow) {+ return { success: false, error: 'Node editor context not available' };+ }++ let workflowData;+ try {+ workflowData = typeof args.workflow_json === 'string'+ ? JSON.parse(args.workflow_json)+ : args.workflow_json;+ } catch (e) {+ return { success: false, error: `Invalid workflow JSON: ${e}` };+ }++ if (args.new_name) {+ workflowData.name = args.new_name;+ }++ const result = await contexts.importNodeWorkflow(workflowData);+ return {+ success: true,+ data: result,+ message: `Workflow "${result.name}" imported with ID: ${result.id}`,+ };+ },+ },+];diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/stock-trading.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/stock-trading.tsnew file mode 100644index 000000000..6032c7e67--- /dev/null+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/stock-trading.ts@@ -0,0 +1,847 @@+// Stock Trading MCP Tools - Unified multi-broker stock trading tools+// Supports ALL Indian stock brokers (AngelOne, Zerodha, Upstox, Fyers, Dhan, etc.)+// Works with both LIVE and PAPER trading modes++import { InternalTool } from '../types';++export const stockTradingTools: InternalTool[] = [+ // ============================================================================+ // ORDER PLACEMENT+ // ============================================================================++ {+ name: 'stock_place_market_order',+ description: '[PRIMARY TOOL FOR STOCKS] Place a stock market order on NSE/BSE (buy/sell at current market price). Automatically searches for the correct instrument. Use this for all stock orders on Indian exchanges.',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Stock symbol (e.g., RELIANCE, TCS, INFY). Use exact symbol from search results.' },+ exchange: { type: 'string', description: 'Exchange', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ transaction_type: { type: 'string', description: 'Transaction type', enum: ['BUY', 'SELL'] },+ quantity: { type: 'number', description: 'Number of shares to trade' },+ product_type: { type: 'string', description: 'Product type', enum: ['INTRADAY', 'DELIVERY', 'MARGIN', 'BO', 'CO'] },+ tag: { type: 'string', description: 'Optional tag for order identification' },+ auto_search: { type: 'boolean', description: 'Auto-search symbol if not found (default: true)' },+ },+ required: ['symbol', 'exchange', 'transaction_type', 'quantity'],+ },+ handler: async (args, contexts) => {+ if (!contexts.placeStockTrade) {+ return { success: false, error: 'Stock trading context not available. Ensure stock broker is connected and authenticated.' };+ }++ // Default product type to DELIVERY if not specified+ const productType = args.product_type || 'DELIVERY';++ // Ensure quantity is a number (AI might send as string)+ const quantity = typeof args.quantity === 'string' ? parseFloat(args.quantity) : args.quantity;++ // Auto-search symbol if enabled (default true)+ let finalSymbol = args.symbol;+ let finalExchange = args.exchange;+ let symbolToken: string | undefined;++ if (args.auto_search !== false && contexts.searchStockInstruments) {+ try {+ const searchResults = await contexts.searchStockInstruments(args.symbol, args.exchange);++ if (searchResults.length === 0) {+ return {+ success: false,+ error: `Symbol "${args.symbol}" not found on ${args.exchange}. Please verify the symbol.`,+ };+ }++ // Use first result (most relevant)+ const instrument = searchResults[0];+ finalSymbol = instrument.tradingSymbol || instrument.symbol;+ finalExchange = instrument.exchange;+ symbolToken = instrument.instrumentToken || instrument.token;++ console.log(`[MCP] Symbol resolved: "${args.symbol}" → "${finalSymbol}" (token: ${symbolToken}) on ${finalExchange}`);+ } catch (searchErr) {+ console.warn(`[MCP] Symbol search failed, using original: ${searchErr}`);+ // Continue with original symbol+ }+ }++ const result = await contexts.placeStockTrade({+ ...args,+ symbol: finalSymbol,+ exchange: finalExchange,+ token: symbolToken,+ quantity: quantity,+ product_type: productType,+ order_type: 'MARKET',+ validity: 'DAY',+ });++ return {+ success: true,+ data: result,+ message: `Market ${args.transaction_type} order placed: ${quantity} ${finalSymbol} @ ${finalExchange} (${productType})`,+ };+ },+ },++ {+ name: 'stock_place_limit_order',+ description: 'Place a limit order for stocks (buy/sell at specified price). Auto-searches symbol if not exact.',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Stock symbol. Can be partial (e.g., "rites", "tcs") - will auto-search.' },+ exchange: { type: 'string', description: 'Exchange', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ transaction_type: { type: 'string', description: 'Transaction type', enum: ['BUY', 'SELL'] },+ quantity: { type: 'number', description: 'Number of shares' },+ price: { type: 'number', description: 'Limit price' },+ product_type: { type: 'string', description: 'Product type', enum: ['INTRADAY', 'DELIVERY', 'MARGIN', 'BO', 'CO'] },+ disclosed_quantity: { type: 'number', description: 'Disclosed quantity (iceberg order)' },+ validity: { type: 'string', description: 'Order validity', enum: ['DAY', 'IOC'] },+ tag: { type: 'string', description: 'Optional tag' },+ auto_search: { type: 'boolean', description: 'Auto-search symbol (default: true)' },+ },+ required: ['symbol', 'exchange', 'transaction_type', 'quantity', 'price', 'product_type'],+ },+ handler: async (args, contexts) => {+ if (!contexts.placeStockTrade) {+ return { success: false, error: 'Stock trading context not available' };+ }++ // Auto-resolve symbol+ let finalSymbol = args.symbol;+ let finalExchange = args.exchange;+ let symbolToken: string | undefined;++ if (args.auto_search !== false && contexts.searchStockInstruments) {+ try {+ const searchResults = await contexts.searchStockInstruments(args.symbol, args.exchange);++ if (searchResults.length === 0) {+ return {+ success: false,+ error: `Symbol "${args.symbol}" not found on ${args.exchange}. Try stock_search_instruments first.`,+ };+ }++ const instrument = searchResults[0];+ finalSymbol = instrument.tradingSymbol || instrument.symbol;+ finalExchange = instrument.exchange;+ symbolToken = instrument.instrumentToken || instrument.token;++ console.log(`[MCP] Symbol resolved: "${args.symbol}" → "${finalSymbol}" (token: ${symbolToken}) on ${finalExchange}`);+ } catch (searchErr) {+ console.warn(`[MCP] Symbol search failed: ${searchErr}`);+ }+ }++ const result = await contexts.placeStockTrade({+ ...args,+ symbol: finalSymbol,+ exchange: finalExchange,+ token: symbolToken,+ order_type: 'LIMIT',+ validity: args.validity || 'DAY',+ });++ return {+ success: true,+ data: result,+ message: `Limit ${args.transaction_type} order placed: ${args.quantity} ${finalSymbol} @ ₹${args.price}`,+ };+ },+ },++ {+ name: 'stock_place_stop_loss_order',+ description: 'Place a stop-loss order (SL or SL-M) for stocks',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Stock symbol' },+ exchange: { type: 'string', description: 'Exchange', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ transaction_type: { type: 'string', description: 'Transaction type', enum: ['BUY', 'SELL'] },+ quantity: { type: 'number', description: 'Number of shares' },+ trigger_price: { type: 'number', description: 'Stop-loss trigger price' },+ price: { type: 'number', description: 'Limit price (optional, for SL order. Omit for SL-M)' },+ product_type: { type: 'string', description: 'Product type', enum: ['INTRADAY', 'DELIVERY', 'MARGIN'] },+ tag: { type: 'string', description: 'Optional tag' },+ },+ required: ['symbol', 'exchange', 'transaction_type', 'quantity', 'trigger_price', 'product_type'],+ },+ handler: async (args, contexts) => {+ if (!contexts.placeStockTrade) {+ return { success: false, error: 'Stock trading context not available' };+ }+ const orderType = args.price ? 'SL' : 'SL-M';+ const result = await contexts.placeStockTrade({+ ...args,+ order_type: orderType,+ validity: 'DAY',+ });+ return {+ success: true,+ data: result,+ message: `Stop-loss ${args.transaction_type} order placed: ${args.quantity} ${args.symbol} @ trigger ₹${args.trigger_price}`,+ };+ },+ },++ {+ name: 'stock_place_bracket_order',+ description: 'Place a bracket order (BO) with stop-loss and target',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Stock symbol' },+ exchange: { type: 'string', description: 'Exchange', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ transaction_type: { type: 'string', description: 'Transaction type', enum: ['BUY', 'SELL'] },+ quantity: { type: 'number', description: 'Number of shares' },+ price: { type: 'number', description: 'Entry price' },+ stop_loss: { type: 'number', description: 'Stop-loss points from entry' },+ target: { type: 'number', description: 'Target profit points from entry' },+ trailing_stop_loss: { type: 'number', description: 'Trailing SL points (optional)' },+ tag: { type: 'string', description: 'Optional tag' },+ },+ required: ['symbol', 'exchange', 'transaction_type', 'quantity', 'price', 'stop_loss', 'target'],+ },+ handler: async (args, contexts) => {+ if (!contexts.placeStockTrade) {+ return { success: false, error: 'Stock trading context not available' };+ }+ const result = await contexts.placeStockTrade({+ ...args,+ order_type: 'LIMIT',+ product_type: 'BO',+ variety: 'bo',+ validity: 'DAY',+ });+ return {+ success: true,+ data: result,+ message: `Bracket order placed: ${args.transaction_type} ${args.quantity} ${args.symbol} (SL: ${args.stop_loss}, Target: ${args.target})`,+ };+ },+ },++ {+ name: 'stock_place_cover_order',+ description: 'Place a cover order (CO) with mandatory stop-loss',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Stock symbol' },+ exchange: { type: 'string', description: 'Exchange', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ transaction_type: { type: 'string', description: 'Transaction type', enum: ['BUY', 'SELL'] },+ quantity: { type: 'number', description: 'Number of shares' },+ trigger_price: { type: 'number', description: 'Stop-loss trigger price' },+ tag: { type: 'string', description: 'Optional tag' },+ },+ required: ['symbol', 'exchange', 'transaction_type', 'quantity', 'trigger_price'],+ },+ handler: async (args, contexts) => {+ if (!contexts.placeStockTrade) {+ return { success: false, error: 'Stock trading context not available' };+ }+ const result = await contexts.placeStockTrade({+ ...args,+ order_type: 'MARKET',+ product_type: 'CO',+ variety: 'co',+ validity: 'DAY',+ });+ return {+ success: true,+ data: result,+ message: `Cover order placed: ${args.transaction_type} ${args.quantity} ${args.symbol} with SL @ ₹${args.trigger_price}`,+ };+ },+ },++ {+ name: 'stock_place_amo_order',+ description: 'Place an After Market Order (AMO) for next trading day',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Stock symbol' },+ exchange: { type: 'string', description: 'Exchange', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ transaction_type: { type: 'string', description: 'Transaction type', enum: ['BUY', 'SELL'] },+ quantity: { type: 'number', description: 'Number of shares' },+ order_type: { type: 'string', description: 'Order type', enum: ['MARKET', 'LIMIT', 'SL', 'SL-M'] },+ price: { type: 'number', description: 'Price (for LIMIT/SL orders)' },+ trigger_price: { type: 'number', description: 'Trigger price (for SL/SL-M orders)' },+ product_type: { type: 'string', description: 'Product type', enum: ['INTRADAY', 'DELIVERY'] },+ tag: { type: 'string', description: 'Optional tag' },+ },+ required: ['symbol', 'exchange', 'transaction_type', 'quantity', 'order_type', 'product_type'],+ },+ handler: async (args, contexts) => {+ if (!contexts.placeStockTrade) {+ return { success: false, error: 'Stock trading context not available' };+ }+ const result = await contexts.placeStockTrade({+ ...args,+ variety: 'amo',+ validity: 'DAY',+ });+ return {+ success: true,+ data: result,+ message: `AMO placed: ${args.transaction_type} ${args.quantity} ${args.symbol} (${args.order_type})`,+ };+ },+ },++ // ============================================================================+ // ORDER MANAGEMENT+ // ============================================================================++ {+ name: 'stock_modify_order',+ description: 'Modify an existing order (price, quantity, trigger)',+ inputSchema: {+ type: 'object',+ properties: {+ order_id: { type: 'string', description: 'Order ID to modify' },+ quantity: { type: 'number', description: 'New quantity' },+ price: { type: 'number', description: 'New limit price' },+ trigger_price: { type: 'number', description: 'New trigger price (for SL orders)' },+ order_type: { type: 'string', description: 'New order type', enum: ['MARKET', 'LIMIT', 'SL', 'SL-M'] },+ validity: { type: 'string', description: 'New validity', enum: ['DAY', 'IOC'] },+ },+ required: ['order_id'],+ },+ handler: async (args, contexts) => {+ if (!contexts.modifyStockOrder) {+ return { success: false, error: 'Stock trading context not available' };+ }+ const result = await contexts.modifyStockOrder(args);+ return {+ success: true,+ data: result,+ message: `Order ${args.order_id} modified successfully`,+ };+ },+ },++ {+ name: 'stock_cancel_order',+ description: 'Cancel a pending order by ID',+ inputSchema: {+ type: 'object',+ properties: {+ order_id: { type: 'string', description: 'Order ID to cancel' },+ variety: { type: 'string', description: 'Order variety (regular, amo, bo, co)' },+ },+ required: ['order_id'],+ },+ handler: async (args, contexts) => {+ if (!contexts.cancelStockOrder) {+ return { success: false, error: 'Stock trading context not available' };+ }+ const result = await contexts.cancelStockOrder(args.order_id, args.variety);+ return {+ success: true,+ data: result,+ message: `Order ${args.order_id} cancelled`,+ };+ },+ },++ {+ name: 'stock_cancel_all_orders',+ description: 'Cancel all open orders (with optional symbol filter)',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Symbol to cancel orders for (optional, cancels all if not provided)' },+ },+ },+ handler: async (args, contexts) => {+ if (!contexts.getStockOrders || !contexts.cancelStockOrder) {+ return { success: false, error: 'Stock trading context not available' };+ }++ const orders = await contexts.getStockOrders({ status: 'open' });+ const targetOrders = args.symbol+ ? orders.filter((o: any) => o.symbol === args.symbol || o.tradingSymbol === args.symbol)+ : orders;++ const results = await Promise.allSettled(+ targetOrders.map((o: any) => contexts.cancelStockOrder!(o.orderId, o.variety))+ );++ const cancelled = results.filter((r) => r.status === 'fulfilled').length;+ return {+ success: true,+ data: { cancelled, total: targetOrders.length },+ message: `Cancelled ${cancelled}/${targetOrders.length} orders`,+ };+ },+ },++ // ============================================================================+ // POSITION & HOLDINGS+ // ============================================================================++ {+ name: 'stock_get_positions',+ description: 'Get all open stock positions',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Filter by symbol (optional)' },+ product: { type: 'string', description: 'Filter by product type (optional)' },+ },+ },+ handler: async (args, contexts) => {+ if (!contexts.getStockPositions) {+ return { success: false, error: 'Stock trading context not available' };+ }+ let positions = await contexts.getStockPositions();++ if (args.symbol) {+ positions = positions.filter((p: any) => p.symbol === args.symbol || p.tradingSymbol === args.symbol);+ }+ if (args.product) {+ positions = positions.filter((p: any) => p.product === args.product);+ }++ return { success: true, data: positions };+ },+ },++ {+ name: 'stock_get_holdings',+ description: 'Get all long-term stock holdings',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Filter by symbol (optional)' },+ },+ },+ handler: async (args, contexts) => {+ if (!contexts.getStockHoldings) {+ return { success: false, error: 'Stock trading context not available' };+ }+ let holdings = await contexts.getStockHoldings();++ if (args.symbol) {+ holdings = holdings.filter((h: any) => h.symbol === args.symbol || h.tradingSymbol === args.symbol);+ }++ return { success: true, data: holdings };+ },+ },++ {+ name: 'stock_convert_position',+ description: 'Convert position from one product type to another (e.g., Intraday to Delivery)',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Stock symbol' },+ exchange: { type: 'string', description: 'Exchange', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ transaction_type: { type: 'string', description: 'Position side', enum: ['BUY', 'SELL'] },+ quantity: { type: 'number', description: 'Quantity to convert' },+ old_product_type: { type: 'string', description: 'Current product type', enum: ['INTRADAY', 'DELIVERY', 'MARGIN'] },+ new_product_type: { type: 'string', description: 'New product type', enum: ['INTRADAY', 'DELIVERY', 'MARGIN'] },+ },+ required: ['symbol', 'exchange', 'transaction_type', 'quantity', 'old_product_type', 'new_product_type'],+ },+ handler: async (args, contexts) => {+ if (!contexts.convertStockPosition) {+ return { success: false, error: 'Position conversion not available' };+ }+ const result = await contexts.convertStockPosition(args);+ return {+ success: true,+ data: result,+ message: `Position converted: ${args.quantity} ${args.symbol} from ${args.old_product_type} to ${args.new_product_type}`,+ };+ },+ },++ {+ name: 'stock_exit_position',+ description: 'Exit/close an open position completely',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Stock symbol' },+ exchange: { type: 'string', description: 'Exchange', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ product_type: { type: 'string', description: 'Product type', enum: ['INTRADAY', 'DELIVERY', 'MARGIN'] },+ },+ required: ['symbol', 'exchange', 'product_type'],+ },+ handler: async (args, contexts) => {+ if (!contexts.exitStockPosition) {+ return { success: false, error: 'Position exit not available' };+ }+ const result = await contexts.exitStockPosition(args);+ return {+ success: true,+ data: result,+ message: `Position exited for ${args.symbol}`,+ };+ },+ },++ // ============================================================================+ // ACCOUNT INFO+ // ============================================================================++ {+ name: 'stock_get_funds',+ description: 'Get account funds/margins (equity and commodity)',+ inputSchema: {+ type: 'object',+ properties: {+ segment: { type: 'string', description: 'Segment filter', enum: ['equity', 'commodity'] },+ },+ },+ handler: async (args, contexts) => {+ if (!contexts.getStockFunds) {+ return { success: false, error: 'Stock trading context not available' };+ }+ const funds = await contexts.getStockFunds();++ if (args.segment) {+ return { success: true, data: funds[args.segment] };+ }++ return { success: true, data: funds };+ },+ },++ {+ name: 'stock_get_margin_required',+ description: 'Calculate margin required for an order before placing it',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Stock symbol' },+ exchange: { type: 'string', description: 'Exchange', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ transaction_type: { type: 'string', description: 'Transaction type', enum: ['BUY', 'SELL'] },+ quantity: { type: 'number', description: 'Number of shares' },+ order_type: { type: 'string', description: 'Order type', enum: ['MARKET', 'LIMIT', 'SL', 'SL-M'] },+ product_type: { type: 'string', description: 'Product type', enum: ['INTRADAY', 'DELIVERY', 'MARGIN', 'BO', 'CO'] },+ price: { type: 'number', description: 'Price (for LIMIT orders)' },+ },+ required: ['symbol', 'exchange', 'transaction_type', 'quantity', 'order_type', 'product_type'],+ },+ handler: async (args, contexts) => {+ if (!contexts.getStockMarginRequired) {+ return { success: false, error: 'Margin calculation not available' };+ }+ const result = await contexts.getStockMarginRequired(args);+ return { success: true, data: result };+ },+ },++ // ============================================================================+ // ORDER & TRADE HISTORY+ // ============================================================================++ {+ name: 'stock_get_orders',+ description: 'Get order history with optional filters',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Filter by symbol' },+ status: { type: 'string', description: 'Filter by status', enum: ['open', 'complete', 'cancelled', 'rejected', 'pending'] },+ },+ },+ handler: async (args, contexts) => {+ if (!contexts.getStockOrders) {+ return { success: false, error: 'Stock trading context not available' };+ }+ const orders = await contexts.getStockOrders(args);+ return { success: true, data: orders };+ },+ },++ {+ name: 'stock_get_trades',+ description: 'Get executed trades (trade book)',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Filter by symbol (optional)' },+ },+ },+ handler: async (args, contexts) => {+ if (!contexts.getStockTrades) {+ return { success: false, error: 'Stock trading context not available' };+ }+ let trades = await contexts.getStockTrades();++ if (args.symbol) {+ trades = trades.filter((t: any) => t.symbol === args.symbol || t.tradingSymbol === args.symbol);+ }++ return { success: true, data: trades };+ },+ },++ // ============================================================================+ // MARKET DATA+ // ============================================================================++ {+ name: 'stock_get_quote',+ description: 'Get real-time quote for a stock symbol',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Stock symbol (e.g., RELIANCE)' },+ exchange: { type: 'string', description: 'Exchange', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ },+ required: ['symbol', 'exchange'],+ },+ handler: async (args, contexts) => {+ if (!contexts.getStockQuote) {+ return { success: false, error: 'Market data context not available' };+ }+ const quote = await contexts.getStockQuote(args);+ return { success: true, data: quote };+ },+ },++ {+ name: 'stock_get_market_depth',+ description: 'Get market depth (order book with bid/ask levels)',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Stock symbol' },+ exchange: { type: 'string', description: 'Exchange', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ },+ required: ['symbol', 'exchange'],+ },+ handler: async (args, contexts) => {+ if (!contexts.getStockMarketDepth) {+ return { success: false, error: 'Market data context not available' };+ }+ const depth = await contexts.getStockMarketDepth(args);+ return { success: true, data: depth };+ },+ },++ {+ name: 'stock_search_instruments',+ description: 'Search for stock symbols. Returns exact and fuzzy matches. ALWAYS use this before placing orders with partial/ambiguous symbols.',+ inputSchema: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'Search query - supports fuzzy search (e.g., "rites", "tata", "reliance")' },+ exchange: { type: 'string', description: 'Exchange filter (optional)', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ limit: { type: 'number', description: 'Max results to return (default: 10)' },+ },+ required: ['query'],+ },+ handler: async (args, contexts) => {+ if (!contexts.searchStockInstruments) {+ return { success: false, error: 'Instrument search not available. Ensure broker is authenticated.' };+ }++ try {+ const instruments = await contexts.searchStockInstruments(args.query, args.exchange);++ // Limit results+ const limit = args.limit || 10;+ const limitedResults = instruments.slice(0, limit);++ if (limitedResults.length === 0) {+ return {+ success: false,+ error: `No instruments found matching "${args.query}"${args.exchange ? ` on ${args.exchange}` : ''}. Check spelling or try broader search.`,+ data: [],+ };+ }++ // Format results for better AI understanding+ const formattedResults = limitedResults.map((inst: any) => ({+ symbol: inst.symbol,+ tradingSymbol: inst.tradingSymbol,+ name: inst.name,+ exchange: inst.exchange,+ instrumentType: inst.instrumentType,+ lotSize: inst.lotSize,+ }));++ return {+ success: true,+ data: formattedResults,+ message: `Found ${limitedResults.length} match${limitedResults.length > 1 ? 'es' : ''} for "${args.query}". Use tradingSymbol for orders.`,+ };+ } catch (error: any) {+ return {+ success: false,+ error: `Search failed: ${error.message}`,+ };+ }+ },+ },++ {+ name: 'stock_get_historical_data',+ description: 'Get historical OHLCV data for a stock',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Stock symbol' },+ exchange: { type: 'string', description: 'Exchange', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ timeframe: { type: 'string', description: 'Timeframe', enum: ['1minute', '5minute', '15minute', '30minute', '60minute', 'day', 'week', 'month'] },+ from_date: { type: 'string', description: 'Start date (YYYY-MM-DD)' },+ to_date: { type: 'string', description: 'End date (YYYY-MM-DD)' },+ },+ required: ['symbol', 'exchange', 'timeframe', 'from_date', 'to_date'],+ },+ handler: async (args, contexts) => {+ if (!contexts.getStockHistoricalData) {+ return { success: false, error: 'Historical data not available' };+ }+ const data = await contexts.getStockHistoricalData(args);+ return { success: true, data };+ },+ },++ // ============================================================================+ // WATCHLIST & FAVORITES+ // ============================================================================++ {+ name: 'stock_add_to_watchlist',+ description: 'Add a stock symbol to watchlist',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Stock symbol' },+ exchange: { type: 'string', description: 'Exchange', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ },+ required: ['symbol', 'exchange'],+ },+ handler: async (args, contexts) => {+ if (!contexts.addToWatchlist) {+ return { success: false, error: 'Watchlist not available' };+ }+ await contexts.addToWatchlist(`${args.symbol}:${args.exchange}`);+ return { success: true, message: `${args.symbol} added to watchlist` };+ },+ },++ {+ name: 'stock_remove_from_watchlist',+ description: 'Remove a stock symbol from watchlist',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Stock symbol' },+ exchange: { type: 'string', description: 'Exchange', enum: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'] },+ },+ required: ['symbol', 'exchange'],+ },+ handler: async (args, contexts) => {+ if (!contexts.removeFromWatchlist) {+ return { success: false, error: 'Watchlist not available' };+ }+ await contexts.removeFromWatchlist(`${args.symbol}:${args.exchange}`);+ return { success: true, message: `${args.symbol} removed from watchlist` };+ },+ },++ // ============================================================================+ // BROKER & MODE MANAGEMENT+ // ============================================================================++ {+ name: 'stock_switch_broker',+ description: 'Switch active stock broker',+ inputSchema: {+ type: 'object',+ properties: {+ broker: {+ type: 'string',+ description: 'Broker ID',+ enum: ['angelone', 'zerodha', 'upstox', 'fyers', 'dhan', 'aliceblue', 'fivepaisa', 'groww', 'iifl', 'kotak', 'shoonya', 'motilal'],+ },+ },+ required: ['broker'],+ },+ handler: async (args, _contexts) => {+ // This would need integration with StockBrokerContext+ return { success: false, error: 'Broker switching via MCP not yet implemented. Use the UI broker selector.' };+ },+ },++ {+ name: 'stock_switch_trading_mode',+ description: 'Switch between live and paper trading mode',+ inputSchema: {+ type: 'object',+ properties: {+ mode: { type: 'string', description: 'Trading mode', enum: ['live', 'paper'] },+ },+ required: ['mode'],+ },+ handler: async (args, _contexts) => {+ // This would need integration with StockBrokerContext+ return { success: false, error: 'Trading mode switching via MCP not yet implemented. Use the UI mode toggle.' };+ },+ },++ // ============================================================================+ // PORTFOLIO METRICS+ // ============================================================================++ {+ name: 'stock_get_portfolio_summary',+ description: 'Get comprehensive portfolio summary with P&L',+ inputSchema: {+ type: 'object',+ properties: {},+ },+ handler: async (_args, contexts) => {+ if (!contexts.getStockPositions || !contexts.getStockHoldings || !contexts.getStockFunds) {+ return { success: false, error: 'Portfolio data not available' };+ }++ const positions = await contexts.getStockPositions();+ const holdings = await contexts.getStockHoldings();+ const funds = await contexts.getStockFunds();++ const totalPositionPnl = positions.reduce((sum: number, p: any) => sum + (p.pnl || 0), 0);+ const totalHoldingPnl = holdings.reduce((sum: number, h: any) => sum + (h.pnl || 0), 0);+ const totalPnl = totalPositionPnl + totalHoldingPnl;++ const totalPositionValue = positions.reduce((sum: number, p: any) => sum + (p.value || 0), 0);+ const totalHoldingValue = holdings.reduce((sum: number, h: any) => sum + (h.value || 0), 0);+ const totalInvestmentValue = totalPositionValue + totalHoldingValue;++ return {+ success: true,+ data: {+ funds,+ positions: {+ count: positions.length,+ totalValue: totalPositionValue,+ totalPnl: totalPositionPnl,+ },+ holdings: {+ count: holdings.length,+ totalValue: totalHoldingValue,+ totalPnl: totalHoldingPnl,+ },+ overall: {+ totalInvestmentValue,+ totalPnl,+ pnlPercentage: totalInvestmentValue > 0 ? (totalPnl / totalInvestmentValue) * 100 : 0,+ },+ },+ };+ },+ },+];diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/trading.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/trading.tsindex 7a54fe33c..bcc553dbe 100644--- a/fincept-terminal-desktop/src/services/mcp/internal/tools/trading.ts+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/trading.ts@@ -3,7 +3,7 @@ import { InternalTool } from '../types';export const tradingTools: InternalTool[] = [{name: 'place_order',- description: 'Place a buy or sell order through the active broker',+ description: 'Place a crypto order through the active crypto broker (Kraken, Binance, etc). For STOCKS, use stock_place_market_order or stock_place_limit_order instead.',inputSchema: {type: 'object',properties: {diff --git a/fincept-terminal-desktop/src/services/mcp/internal/types.ts b/fincept-terminal-desktop/src/services/mcp/internal/types.tsindex d44f9f464..bef7fafd8 100644--- a/fincept-terminal-desktop/src/services/mcp/internal/types.ts+++ b/fincept-terminal-desktop/src/services/mcp/internal/types.ts@@ -23,6 +23,11 @@ export interface InternalToolResult {data?: any;message?: string;error?: string;+ // Additional metadata for financial tools+ chart_data?: any;+ ticker?: string;+ company?: string;+ content?: string;}export interface TerminalContexts {@@ -31,7 +36,7 @@ export interface TerminalContexts {getActiveTab?: () => string;navigateToScreen?: (screen: string) => void;- // Trading / Brokers+ // Trading / Brokers (Crypto)placeTrade?: (params: any) => Promise<any>;cancelOrder?: (orderId: string) => Promise<any>;modifyOrder?: (orderId: string, updates: any) => Promise<any>;@@ -41,6 +46,23 @@ export interface TerminalContexts {getHoldings?: () => Promise<any>;closePosition?: (symbol: string) => Promise<any>;+ // Stock Trading+ placeStockTrade?: (params: any) => Promise<any>;+ cancelStockOrder?: (orderId: string, variety?: string) => Promise<any>;+ modifyStockOrder?: (params: any) => Promise<any>;+ getStockPositions?: () => Promise<any>;+ getStockHoldings?: () => Promise<any>;+ getStockFunds?: () => Promise<any>;+ getStockOrders?: (filters?: any) => Promise<any>;+ getStockTrades?: () => Promise<any>;+ getStockMarginRequired?: (params: any) => Promise<any>;+ convertStockPosition?: (params: any) => Promise<any>;+ exitStockPosition?: (params: any) => Promise<any>;+ getStockQuote?: (params: any) => Promise<any>;+ getStockMarketDepth?: (params: any) => Promise<any>;+ searchStockInstruments?: (query: string, exchange?: string) => Promise<any[]>;+ getStockHistoricalData?: (params: any) => Promise<any>;+// PortfoliogetPortfolios?: () => Promise<any>;createPortfolio?: (params: any) => Promise<any>;@@ -103,6 +125,161 @@ export interface TerminalContexts {listReportComponents?: () => Promise<any[]>;deleteReportComponent?: (id: string) => Promise<void>;applyReportTheme?: (theme: string) => Promise<void>;++ // Node Editor - Node Discovery+ listAvailableNodes?: (category?: string, search?: string) => Promise<NodeTypeInfo[]>;+ getNodeDetails?: (nodeType: string) => Promise<NodeTypeDetails | null>;+ getNodeCategories?: () => Promise<NodeCategoryInfo[]>;++ // Node Editor - Workflow Creation+ createNodeWorkflow?: (params: CreateWorkflowParams) => Promise<WorkflowInfo>;+ addNodeToWorkflow?: (params: AddNodeParams) => Promise<WorkflowInfo>;+ connectNodes?: (params: ConnectNodesParams) => Promise<WorkflowInfo>;+ configureNode?: (params: ConfigureNodeParams) => Promise<WorkflowInfo>;++ // Node Editor - Workflow Management+ listNodeWorkflows?: (status?: string) => Promise<WorkflowInfo[]>;+ getNodeWorkflow?: (workflowId: string) => Promise<WorkflowInfo | null>;+ updateNodeWorkflow?: (params: UpdateWorkflowParams) => Promise<WorkflowInfo>;+ deleteNodeWorkflow?: (workflowId: string) => Promise<void>;+ duplicateNodeWorkflow?: (workflowId: string, newName: string) => Promise<WorkflowInfo>;++ // Node Editor - Workflow Execution+ executeNodeWorkflow?: (workflowId: string, inputData?: any) => Promise<WorkflowExecutionResult>;+ stopNodeWorkflow?: (workflowId: string) => Promise<void>;+ getWorkflowResults?: (workflowId: string) => Promise<WorkflowExecutionResult | null>;+ validateNodeWorkflow?: (workflowId: string) => Promise<WorkflowValidation>;++ // Node Editor - Helpers+ openWorkflowInEditor?: (workflowId: string) => Promise<void>;+ exportNodeWorkflow?: (workflowId: string) => Promise<any>;+ importNodeWorkflow?: (workflowData: any) => Promise<WorkflowInfo>;+}++// ============================================================================+// Node Editor Types+// ============================================================================++export interface NodeTypeInfo {+ name: string;+ displayName: string;+ description: string;+ category: string;+ icon?: string;+ color?: string;+ inputs: string[];+ outputs: string[];+}++export interface NodeTypeDetails extends NodeTypeInfo {+ version: number;+ properties: NodePropertyInfo[];+ hints?: string[];+ usableAsTool?: boolean;+}++export interface NodePropertyInfo {+ name: string;+ displayName: string;+ type: string;+ default?: any;+ description?: string;+ required?: boolean;+ options?: Array<{ name: string; value: any; description?: string }>;+}++export interface NodeCategoryInfo {+ name: string;+ displayName: string;+ description: string;+ nodeCount: number;+ icon?: string;+ color?: string;+}++export interface CreateWorkflowParams {+ name: string;+ description?: string;+ nodes: WorkflowNodeInput[];+ edges: WorkflowEdgeInput[];+}++export interface WorkflowNodeInput {+ id: string;+ type: string;+ position: { x: number; y: number };+ parameters?: Record<string, any>;+ label?: string;+}++export interface WorkflowEdgeInput {+ source: string;+ target: string;+ sourceHandle?: string;+ targetHandle?: string;+}++export interface AddNodeParams {+ workflowId: string;+ nodeId: string;+ nodeType: string;+ position: { x: number; y: number };+ parameters?: Record<string, any>;+ label?: string;+}++export interface ConnectNodesParams {+ workflowId: string;+ sourceNodeId: string;+ targetNodeId: string;+ sourceHandle?: string;+ targetHandle?: string;+}++export interface ConfigureNodeParams {+ workflowId: string;+ nodeId: string;+ parameters: Record<string, any>;+}++export interface UpdateWorkflowParams {+ workflowId: string;+ name?: string;+ description?: string;+ nodes?: WorkflowNodeInput[];+ edges?: WorkflowEdgeInput[];+}++export interface WorkflowInfo {+ id: string;+ name: string;+ description?: string;+ status: 'idle' | 'running' | 'completed' | 'error' | 'draft';+ nodes: WorkflowNodeInput[];+ edges: WorkflowEdgeInput[];+ createdAt?: string;+ updatedAt?: string;+}++export interface WorkflowExecutionResult {+ success: boolean;+ workflowId: string;+ results?: Record<string, NodeExecutionResultInfo>;+ error?: string;+ duration?: number;+}++export interface NodeExecutionResultInfo {+ success: boolean;+ data?: any;+ error?: string;+ duration?: number;+}++export interface WorkflowValidation {+ valid: boolean;+ errors: string[];+ warnings?: string[];}export const INTERNAL_SERVER_ID = 'fincept-terminal';diff --git a/fincept-terminal-desktop/src/services/mcp/mcpToolService.ts b/fincept-terminal-desktop/src/services/mcp/mcpToolService.tsindex d74f5be8f..00e1f9c54 100644--- a/fincept-terminal-desktop/src/services/mcp/mcpToolService.ts+++ b/fincept-terminal-desktop/src/services/mcp/mcpToolService.ts@@ -24,6 +24,12 @@ export interface MCPToolExecutionResult {toolName: string;serverId: string;executionTime?: number;+ // Additional metadata for financial tools+ chart_data?: any;+ ticker?: string;+ company?: string;+ content?: string;+ message?: string;}export interface MCPToolValidationResult {diff --git a/fincept-terminal-desktop/src/services/payment/paymentApi.tsx b/fincept-terminal-desktop/src/services/payment/paymentApi.tsxindex 34d4c7d5b..6778ac937 100644--- a/fincept-terminal-desktop/src/services/payment/paymentApi.tsx+++ b/fincept-terminal-desktop/src/services/payment/paymentApi.tsx@@ -188,7 +188,7 @@ const makePaymentApiRequest = async <T = any>(export class PaymentApiService {// Get all subscription plans from APIstatic async getSubscriptionPlans(): Promise<PaymentApiResponse<SubscriptionPlan[]>> {- const response = await makePaymentApiRequest<PlansResponse>('GET', '/payment/plans');+ const response = await makePaymentApiRequest<PlansResponse>('GET', '/cashfree/plans');// Backend returns: { success: true, message: "Success", data: [plans array] }if (response.success && response.data) {@@ -255,7 +255,7 @@ export class PaymentApiService {currency: request.currency || 'USD'};- const response = await makePaymentApiRequest<{ data: CheckoutResponse }>('POST', '/payment/create-order', requestBody, headers);+ const response = await makePaymentApiRequest<{ data: CheckoutResponse }>('POST', '/cashfree/create-order', requestBody, headers);// Construct checkout URL from payment_session_idif (response.success && response.data?.data?.payment_session_id) {diff --git a/fincept-terminal-desktop/src/services/trading/quoteDeduplicationService.ts b/fincept-terminal-desktop/src/services/trading/quoteDeduplicationService.tsnew file mode 100644index 000000000..aa50840c5--- /dev/null+++ b/fincept-terminal-desktop/src/services/trading/quoteDeduplicationService.ts@@ -0,0 +1,165 @@+/**+ * Quote Deduplication Service+ *+ * Prevents multiple concurrent requests for the same symbol.+ * Implements request coalescing and TTL-based caching.+ */++import type { Quote, StockExchange } from '@/brokers/stocks/types';++interface CacheEntry {+ quote: Quote;+ timestamp: number;+}++interface PendingRequest {+ promise: Promise<Quote>;+ timestamp: number;+}++// Cache TTL based on market status+const CACHE_TTL_MARKET_OPEN = 5000; // 5 seconds+const CACHE_TTL_MARKET_CLOSED = 60000; // 1 minute+const PENDING_REQUEST_TIMEOUT = 30000; // 30 seconds++class QuoteDeduplicationService {+ private cache: Map<string, CacheEntry> = new Map();+ private pendingRequests: Map<string, PendingRequest> = new Map();++ private getKey(symbol: string, exchange: StockExchange): string {+ return `${exchange}:${symbol}`;+ }++ private getCacheTTL(exchange: StockExchange): number {+ // Simple market hours check (can be enhanced with marketHoursService)+ const now = new Date();+ const hour = now.getHours();+ const isWeekend = now.getDay() === 0 || now.getDay() === 6;++ // Indian markets: 9:15 AM - 3:30 PM IST+ const isIndianExchange = ['NSE', 'BSE', 'NFO', 'BFO', 'MCX', 'CDS'].includes(exchange);+ if (isIndianExchange) {+ const isOpen = !isWeekend && hour >= 9 && hour < 16;+ return isOpen ? CACHE_TTL_MARKET_OPEN : CACHE_TTL_MARKET_CLOSED;+ }++ // US markets: 9:30 AM - 4:00 PM EST (simplified)+ return CACHE_TTL_MARKET_OPEN;+ }++ /**+ * Get quote with deduplication and caching+ */+ async getQuote(+ symbol: string,+ exchange: StockExchange,+ fetchFn: () => Promise<Quote>+ ): Promise<Quote> {+ const key = this.getKey(symbol, exchange);+ const now = Date.now();+ const ttl = this.getCacheTTL(exchange);++ // Check cache first+ const cached = this.cache.get(key);+ if (cached && (now - cached.timestamp) < ttl) {+ return cached.quote;+ }++ // Check if request already pending+ const pending = this.pendingRequests.get(key);+ if (pending && (now - pending.timestamp) < PENDING_REQUEST_TIMEOUT) {+ return pending.promise;+ }++ // Create new request+ const promise = fetchFn()+ .then((quote) => {+ this.cache.set(key, { quote, timestamp: Date.now() });+ return quote;+ })+ .finally(() => {+ this.pendingRequests.delete(key);+ });++ this.pendingRequests.set(key, { promise, timestamp: now });+ return promise;+ }++ /**+ * Get multiple quotes with batching+ */+ async getMultiQuotes(+ symbols: Array<{ symbol: string; exchange: StockExchange }>,+ batchFetchFn: (symbols: Array<{ symbol: string; exchange: StockExchange }>) => Promise<Map<string, Quote>>+ ): Promise<Map<string, Quote>> {+ const now = Date.now();+ const result = new Map<string, Quote>();+ const toFetch: Array<{ symbol: string; exchange: StockExchange }> = [];++ // Check cache for each symbol+ for (const { symbol, exchange } of symbols) {+ const key = this.getKey(symbol, exchange);+ const ttl = this.getCacheTTL(exchange);+ const cached = this.cache.get(key);++ if (cached && (now - cached.timestamp) < ttl) {+ result.set(key, cached.quote);+ } else {+ toFetch.push({ symbol, exchange });+ }+ }++ // Fetch missing quotes in batch+ if (toFetch.length > 0) {+ try {+ const fetched = await batchFetchFn(toFetch);+ for (const [key, quote] of fetched) {+ this.cache.set(key, { quote, timestamp: Date.now() });+ result.set(key, quote);+ }+ } catch (error) {+ console.error('[QuoteDedup] Batch fetch failed:', error);+ }+ }++ return result;+ }++ /**+ * Invalidate cache for symbol+ */+ invalidate(symbol: string, exchange: StockExchange): void {+ const key = this.getKey(symbol, exchange);+ this.cache.delete(key);+ }++ /**+ * Clear all cached data+ */+ clear(): void {+ this.cache.clear();+ this.pendingRequests.clear();+ }++ /**+ * Update cache from WebSocket tick+ */+ updateFromTick(symbol: string, exchange: StockExchange, quote: Quote): void {+ const key = this.getKey(symbol, exchange);+ this.cache.set(key, { quote, timestamp: Date.now() });+ }++ /**+ * Get cache stats for debugging+ */+ getStats(): { cacheSize: number; pendingRequests: number } {+ return {+ cacheSize: this.cache.size,+ pendingRequests: this.pendingRequests.size,+ };+ }+}++// Singleton instance+export const quoteDeduplicationService = new QuoteDeduplicationService();+export default quoteDeduplicationService;diff --git a/scripts/generate_latest_json.py b/scripts/generate_latest_json.pyindex cb10f67d7..a8f36b4bd 100644--- a/scripts/generate_latest_json.py+++ b/scripts/generate_latest_json.py@@ -43,9 +43,9 @@ def main():if not merged['platforms']:print("No platforms found from JSON files, generating from artifacts...")- # Windows NSIS- nsis_zips = glob.glob("release-files/*.nsis.zip")- nsis_sigs = glob.glob("release-files/*.nsis.zip.sig")+ # Windows NSIS (x86_64)+ nsis_zips = glob.glob("release-files/*-x86_64-windows.nsis.zip")+ nsis_sigs = glob.glob("release-files/*-x86_64-windows.nsis.zip.sig")if nsis_zips and nsis_sigs:nsis_filename = os.path.basename(nsis_zips[0])with open(nsis_sigs[0], 'r') as f:@@ -54,11 +54,11 @@ def main():"signature": signature,"url": f"{repo_url}/releases/download/{tag_name}/{nsis_filename}"}- print("Added windows-x86_64 from artifacts")+ print(f"Added windows-x86_64 from artifacts: {nsis_filename}")- # macOS ARM (aarch64)- macos_arm_tars = [f for f in glob.glob("release-files/*.app.tar.gz") if 'aarch64' in f]- macos_arm_sigs = [f for f in glob.glob("release-files/*.app.tar.gz.sig") if 'aarch64' in f]+ # macOS ARM64 (aarch64)+ macos_arm_tars = glob.glob("release-files/*-arm64-darwin.app.tar.gz")+ macos_arm_sigs = glob.glob("release-files/*-arm64-darwin.app.tar.gz.sig")if macos_arm_tars and macos_arm_sigs:tar_filename = os.path.basename(macos_arm_tars[0])with open(macos_arm_sigs[0], 'r') as f:@@ -67,11 +67,11 @@ def main():"signature": signature,"url": f"{repo_url}/releases/download/{tag_name}/{tar_filename}"}- print("Added darwin-aarch64 from artifacts")+ print(f"Added darwin-aarch64 from artifacts: {tar_filename}")- # macOS Intel (x86_64)- macos_x64_tars = [f for f in glob.glob("release-files/*.app.tar.gz") if 'x86_64' in f and 'aarch64' not in f]- macos_x64_sigs = [f for f in glob.glob("release-files/*.app.tar.gz.sig") if 'x86_64' in f and 'aarch64' not in f]+ # macOS x64 (x86_64)+ macos_x64_tars = glob.glob("release-files/*-x64-darwin.app.tar.gz")+ macos_x64_sigs = glob.glob("release-files/*-x64-darwin.app.tar.gz.sig")if macos_x64_tars and macos_x64_sigs:tar_filename = os.path.basename(macos_x64_tars[0])with open(macos_x64_sigs[0], 'r') as f:@@ -80,11 +80,11 @@ def main():"signature": signature,"url": f"{repo_url}/releases/download/{tag_name}/{tar_filename}"}- print("Added darwin-x86_64 from artifacts")+ print(f"Added darwin-x86_64 from artifacts: {tar_filename}")- # Linux- linux_tars = glob.glob("release-files/*.AppImage.tar.gz")- linux_sigs = glob.glob("release-files/*.AppImage.tar.gz.sig")+ # Linux x86_64+ linux_tars = glob.glob("release-files/*-x86_64-linux.AppImage.tar.gz")+ linux_sigs = glob.glob("release-files/*-x86_64-linux.AppImage.tar.gz.sig")if linux_tars and linux_sigs:tar_filename = os.path.basename(linux_tars[0])with open(linux_sigs[0], 'r') as f:@@ -93,7 +93,7 @@ def main():"signature": signature,"url": f"{repo_url}/releases/download/{tag_name}/{tar_filename}"}- print("Added linux-x86_64 from artifacts")+ print(f"Added linux-x86_64 from artifacts: {tar_filename}")# Write the merged JSONwith open('release-files/latest.json', 'w') as f: