Skip to content

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

node editor fixes

tilakpatel22f9db7c3305df
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/cds_analytics.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/cds_analytics.py
deleted file mode 100644
index 0bba459b9..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/cds_analytics.py
+++ /dev/null
@@ -1,29 +0,0 @@
-
-Fixed Income Cds Analytics Module
-=================================
-
-Credit default swap analysis and pricing
-
-===== DATA SOURCES REQUIRED =====
-INPUT:
- - Bond prospectuses and issue documentation
- - Market price data and yield curve information
- - Credit ratings and default recovery rates
- - Interest rate benchmarks and swap curves
- - Macroeconomic data affecting fixed income markets
-
-OUTPUT:
- - Bond valuation models and price calculations
- - Yield curve analysis and forward rate calculations
- - Credit risk assessment and spread analysis
- - Duration and convexity risk metrics
- - Portfolio optimization and immunization strategies
-
-PARAMETERS:
- - yield_curve_method: Yield curve modeling method (default: 'nelson_siegel')
- - credit_spread: Credit spread assumption (default: 0.02)
- - recovery_rate: Default recovery rate (default: 0.40)
- - convexity_adjustment: Convexity adjustment factor (default: 1.0)
- - benchmark_curve: Benchmark yield curve (default: 'treasury')
-
-
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/config.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/config.py
deleted file mode 100644
index 2b17716eb..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/config.py
+++ /dev/null
@@ -1,341 +0,0 @@
-
-Fixed Income Config Module
-=================================
-
-Portfolio management configuration
-
-===== DATA SOURCES REQUIRED =====
-INPUT:
- - Bond prospectuses and issue documentation
- - Market price data and yield curve information
- - Credit ratings and default recovery rates
- - Interest rate benchmarks and swap curves
- - Macroeconomic data affecting fixed income markets
-
-OUTPUT:
- - Bond valuation models and price calculations
- - Yield curve analysis and forward rate calculations
- - Credit risk assessment and spread analysis
- - Duration and convexity risk metrics
- - Portfolio optimization and immunization strategies
-
-PARAMETERS:
- - yield_curve_method: Yield curve modeling method (default: 'nelson_siegel')
- - credit_spread: Credit spread assumption (default: 0.02)
- - recovery_rate: Default recovery rate (default: 0.40)
- - convexity_adjustment: Convexity adjustment factor (default: 1.0)
- - benchmark_curve: Benchmark yield curve (default: 'treasury')
-
-
-from enum import Enum
-from decimal import Decimal, getcontext
-from typing import Dict, List, Optional, Union
-import datetime
-
-# Set high precision for financial calculations
-getcontext().prec = 28
-
-
-class DayCountConvention(Enum):
- """Day count conventions used in fixed income markets"""
- ACTUAL_360 = "Actual/360"
- ACTUAL_365 = "Actual/365"
- ACTUAL_ACTUAL = "Actual/Actual"
- THIRTY_360 = "30/360"
- THIRTY_360_EUROPEAN = "30E/360"
- ACTUAL_365_FIXED = "Actual/365 Fixed"
- NL_365 = "NL/365"
-
-
-class CompoundingFrequency(Enum):
- """Compounding frequency conventions"""
- CONTINUOUS = 0
- ANNUAL = 1
- SEMI_ANNUAL = 2
- QUARTERLY = 4
- MONTHLY = 12
- DAILY = 365
-
-
-class BusinessDayConvention(Enum):
- """Business day adjustment conventions"""
- FOLLOWING = "Following"
- MODIFIED_FOLLOWING = "Modified Following"
- PRECEDING = "Preceding"
- MODIFIED_PRECEDING = "Modified Preceding"
- UNADJUSTED = "Unadjusted"
-
-
-class Currency(Enum):
- """Major currencies for fixed income markets"""
- USD = "USD"
- EUR = "EUR"
- GBP = "GBP"
- JPY = "JPY"
- CHF = "CHF"
- CAD = "CAD"
- AUD = "AUD"
- CNY = "CNY"
-
-
-class CreditRating(Enum):
- """Standard credit rating scale (S&P equivalent)"""
- AAA = "AAA"
- AA_PLUS = "AA+"
- AA = "AA"
- AA_MINUS = "AA-"
- A_PLUS = "A+"
- A = "A"
- A_MINUS = "A-"
- BBB_PLUS = "BBB+"
- BBB = "BBB"
- BBB_MINUS = "BBB-"
- BB_PLUS = "BB+"
- BB = "BB"
- BB_MINUS = "BB-"
- B_PLUS = "B+"
- B = "B"
- B_MINUS = "B-"
- CCC_PLUS = "CCC+"
- CCC = "CCC"
- CCC_MINUS = "CCC-"
- CC = "CC"
- C = "C"
- D = "D"
-
-
-class BondType(Enum):
- """Bond instrument types"""
- FIXED_RATE = "Fixed Rate"
- FLOATING_RATE = "Floating Rate"
- ZERO_COUPON = "Zero Coupon"
- CALLABLE = "Callable"
- PUTABLE = "Putable"
- CONVERTIBLE = "Convertible"
- INFLATION_LINKED = "Inflation Linked"
- PERPETUAL = "Perpetual"
-
-
-class SecuritizationType(Enum):
- """Securitized product types"""
- MORTGAGE_PASS_THROUGH = "Mortgage Pass-Through"
- CMO = "Collateralized Mortgage Obligation"
- ABS = "Asset-Backed Security"
- CDO = "Collateralized Debt Obligation"
- COVERED_BOND = "Covered Bond"
-
-
-# Market Conventions by Currency
-MARKET_CONVENTIONS = {
- Currency.USD: {
- 'day_count': DayCountConvention.THIRTY_360,
- 'settlement_days': 3,
- 'compounding': CompoundingFrequency.SEMI_ANNUAL,
- 'business_day_convention': BusinessDayConvention.MODIFIED_FOLLOWING
- },
- Currency.EUR: {
- 'day_count': DayCountConvention.ACTUAL_ACTUAL,
- 'settlement_days': 3,
- 'compounding': CompoundingFrequency.ANNUAL,
- 'business_day_convention': BusinessDayConvention.MODIFIED_FOLLOWING
- },
- Currency.GBP: {
- 'day_count': DayCountConvention.ACTUAL_365,
- 'settlement_days': 3,
- 'compounding': CompoundingFrequency.SEMI_ANNUAL,
- 'business_day_convention': BusinessDayConvention.MODIFIED_FOLLOWING
- },
- Currency.JPY: {
- 'day_count': DayCountConvention.ACTUAL_365,
- 'settlement_days': 3,
- 'compounding': CompoundingFrequency.SEMI_ANNUAL,
- 'business_day_convention': BusinessDayConvention.MODIFIED_FOLLOWING
- }
-}
-
-# Numerical Precision Settings
-PRECISION_CONFIG = {
- 'decimal_places': 8,
- 'price_precision': 6,
- 'yield_precision': 4,
- 'spread_precision': 1,
- 'duration_precision': 4,
- 'convergence_tolerance': Decimal('1e-10'),
- 'max_iterations': 1000
-}
-
-# Default Calculation Parameters
-DEFAULT_PARAMS = {
- 'yield_calculation_method': 'newton_raphson',
- 'interpolation_method': 'cubic_spline',
- 'volatility_model': 'black_scholes',
- 'credit_model': 'merton',
- 'monte_carlo_paths': 10000,
- 'binomial_steps': 100
-}
-
-# Credit Rating Numerical Mapping (for calculations)
-RATING_SCORES = {
- CreditRating.AAA: 1,
- CreditRating.AA_PLUS: 2,
- CreditRating.AA: 3,
- CreditRating.AA_MINUS: 4,
- CreditRating.A_PLUS: 5,
- CreditRating.A: 6,
- CreditRating.A_MINUS: 7,
- CreditRating.BBB_PLUS: 8,
- CreditRating.BBB: 9,
- CreditRating.BBB_MINUS: 10,
- CreditRating.BB_PLUS: 11,
- CreditRating.BB: 12,
- CreditRating.BB_MINUS: 13,
- CreditRating.B_PLUS: 14,
- CreditRating.B: 15,
- CreditRating.B_MINUS: 16,
- CreditRating.CCC_PLUS: 17,
- CreditRating.CCC: 18,
- CreditRating.CCC_MINUS: 19,
- CreditRating.CC: 20,
- CreditRating.C: 21,
- CreditRating.D: 22
-}
-
-# Investment Grade Threshold
-INVESTMENT_GRADE_THRESHOLD = RATING_SCORES[CreditRating.BBB_MINUS]
-
-# Standard Treasury Maturities (in years)
-TREASURY_MATURITIES = [
- Decimal('0.25'), # 3 months
- Decimal('0.5'), # 6 months
- Decimal('1'), # 1 year
- Decimal('2'), # 2 years
- Decimal('3'), # 3 years
- Decimal('5'), # 5 years
- Decimal('7'), # 7 years
- Decimal('10'), # 10 years
- Decimal('20'), # 20 years
- Decimal('30') # 30 years
-]
-
-# Swap Curve Standard Tenors
-SWAP_TENORS = [
- '1M', '3M', '6M', '1Y', '2Y', '3Y', '4Y', '5Y',
- '7Y', '10Y', '12Y', '15Y', '20Y', '25Y', '30Y'
-]
-
-# Credit Default Swap Standard Tenors
-CDS_TENORS = ['6M', '1Y', '2Y', '3Y', '4Y', '5Y', '7Y', '10Y']
-
-# Holidays (basic implementation - can be extended)
-US_HOLIDAYS = [
- # New Year's Day, Martin Luther King Jr. Day, Presidents Day,
- # Memorial Day, Independence Day, Labor Day, Columbus Day,
- # Veterans Day, Thanksgiving, Christmas Day
-]
-
-# Data Provider Configuration
-DATA_PROVIDERS = {
- 'bloomberg': {
- 'base_url': 'https://api.bloomberg.com',
- 'fields': ['PX_LAST', 'YLD_YTM_MID', 'DUR_ADJ_MID'],
- 'rate_limit': 1000 # requests per hour
- },
- 'refinitiv': {
- 'base_url': 'https://api.refinitiv.com',
- 'fields': ['TR.PriceClose', 'TR.YieldToMaturity'],
- 'rate_limit': 500
- },
- 'fred': {
- 'base_url': 'https://api.stlouisfed.org/fred',
- 'series': ['DGS1MO', 'DGS3MO', 'DGS6MO', 'DGS1', 'DGS2', 'DGS5', 'DGS10', 'DGS30'],
- 'rate_limit': 120
- },
- 'yahoo': {
- 'base_url': 'https://query1.finance.yahoo.com',
- 'rate_limit': 2000
- }
-}
-
-# Error Tolerance Levels
-ERROR_TOLERANCE = {
- 'low': Decimal('1e-6'),
- 'medium': Decimal('1e-8'),
- 'high': Decimal('1e-10'),
- 'ultra_high': Decimal('1e-12')
-}
-
-# Validation Rules
-VALIDATION_RULES = {
- 'min_yield': Decimal('-0.10'), # -10% minimum yield
- 'max_yield': Decimal('1.00'), # 100% maximum yield
- 'min_price': Decimal('0.01'), # Minimum bond price
- 'max_price': Decimal('10.00'), # Maximum bond price (1000%)
- 'min_maturity_days': 1,
- 'max_maturity_years': 100,
- 'min_coupon_rate': Decimal('0.00'),
- 'max_coupon_rate': Decimal('1.00')
-}
-
-# Model Parameters
-MODEL_PARAMS = {
- 'black_scholes': {
- 'risk_free_rate': Decimal('0.02'),
- 'volatility': Decimal('0.20')
- },
- 'vasicek': {
- 'mean_reversion_speed': Decimal('0.1'),
- 'long_term_mean': Decimal('0.05'),
- 'volatility': Decimal('0.01')
- },
- 'hull_white': {
- 'mean_reversion_speed': Decimal('0.1'),
- 'volatility': Decimal('0.01')
- }
-}
-
-
-def get_market_convention(currency: Currency) -> Dict:
- """Get market conventions for a specific currency"""
- return MARKET_CONVENTIONS.get(currency, MARKET_CONVENTIONS[Currency.USD])
-
-
-def is_investment_grade(rating: CreditRating) -> bool:
- """Check if a credit rating is investment grade"""
- return RATING_SCORES[rating] <= INVESTMENT_GRADE_THRESHOLD
-
-
-def get_precision(calc_type: str) -> int:
- """Get precision for specific calculation type"""
- precision_map = {
- 'price': PRECISION_CONFIG['price_precision'],
- 'yield': PRECISION_CONFIG['yield_precision'],
- 'spread': PRECISION_CONFIG['spread_precision'],
- 'duration': PRECISION_CONFIG['duration_precision']
- }
- return precision_map.get(calc_type, PRECISION_CONFIG['decimal_places'])
-
-
-def get_tolerance(level: str = 'medium') -> Decimal:
- """Get error tolerance for calculations"""
- return ERROR_TOLERANCE.get(level, ERROR_TOLERANCE['medium'])
-
-
-class ConfigurationError(Exception):
- """Custom exception for configuration errors"""
- pass
-
-
-def validate_configuration():
- """Validate configuration settings on module load"""
- if getcontext().prec < 20:
- raise ConfigurationError("Decimal precision too low for financial calculations")
-
- # Validate that all required configurations are present
- required_configs = ['MARKET_CONVENTIONS', 'PRECISION_CONFIG', 'DEFAULT_PARAMS']
- for config in required_configs:
- if config not in globals():
- raise ConfigurationError(f"Missing required configuration: {config}")
-
-
-# Run validation on import
-validate_configuration()
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/credit_analytics.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/credit_analytics.py
deleted file mode 100644
index 840c1ac32..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/credit_analytics.py
+++ /dev/null
@@ -1,29 +0,0 @@
-
-Fixed Income Credit Analytics Module
-=================================
-
-Credit risk analysis and assessment
-
-===== DATA SOURCES REQUIRED =====
-INPUT:
- - Bond prospectuses and issue documentation
- - Market price data and yield curve information
- - Credit ratings and default recovery rates
- - Interest rate benchmarks and swap curves
- - Macroeconomic data affecting fixed income markets
-
-OUTPUT:
- - Bond valuation models and price calculations
- - Yield curve analysis and forward rate calculations
- - Credit risk assessment and spread analysis
- - Duration and convexity risk metrics
- - Portfolio optimization and immunization strategies
-
-PARAMETERS:
- - yield_curve_method: Yield curve modeling method (default: 'nelson_siegel')
- - credit_spread: Credit spread assumption (default: 0.02)
- - recovery_rate: Default recovery rate (default: 0.40)
- - convexity_adjustment: Convexity adjustment factor (default: 1.0)
- - benchmark_curve: Benchmark yield curve (default: 'treasury')
-
-
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/government_analysis.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/government_analysis.py
deleted file mode 100644
index 61f1f12ad..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/government_analysis.py
+++ /dev/null
@@ -1,675 +0,0 @@
-
-Fixed Income Government Analysis Module
-=================================
-
-Government securities analysis
-
-===== DATA SOURCES REQUIRED =====
-INPUT:
- - Bond prospectuses and issue documentation
- - Market price data and yield curve information
- - Credit ratings and default recovery rates
- - Interest rate benchmarks and swap curves
- - Macroeconomic data affecting fixed income markets
-
-OUTPUT:
- - Bond valuation models and price calculations
- - Yield curve analysis and forward rate calculations
- - Credit risk assessment and spread analysis
- - Duration and convexity risk metrics
- - Portfolio optimization and immunization strategies
-
-PARAMETERS:
- - yield_curve_method: Yield curve modeling method (default: 'nelson_siegel')
- - credit_spread: Credit spread assumption (default: 0.02)
- - recovery_rate: Default recovery rate (default: 0.40)
- - convexity_adjustment: Convexity adjustment factor (default: 1.0)
- - benchmark_curve: Benchmark yield curve (default: 'treasury')
-
-
-from typing import List, Dict, Optional, Tuple
-from decimal import Decimal
-from datetime import date
-from models import Bond, Portfolio
-from credit_analytics import CreditRiskMeasures, ProbabilityOfDefault
-from utils import ValidationUtils, cache_calculation
-from config import Currency, CreditRating
-from yield_curves import SpotCurve
-from valuation import BondValuation
-
-
-class SovereignCreditAnalysis:
- """Sovereign credit risk analysis and evaluation"""
-
- @staticmethod
- def sovereign_credit_factors() -> Dict[str, List[str]]:
- """Key factors for sovereign credit analysis"""
- return {
- 'economic_factors': [
- 'GDP growth rate',
- 'GDP per capita',
- 'Economic diversification',
- 'Competitiveness',
- 'Labor market flexibility',
- 'Monetary policy credibility'
- ],
- 'fiscal_factors': [
- 'Government debt/GDP ratio',
- 'Fiscal balance',
- 'Interest burden',
- 'Contingent liabilities',
- 'Fiscal flexibility',
- 'Revenue diversification'
- ],
- 'external_factors': [
- 'Current account balance',
- 'External debt',
- 'Foreign exchange reserves',
- 'Exchange rate regime',
- 'Export concentration',
- 'Capital market access'
- ],
- 'political_institutional': [
- 'Political stability',
- 'Institutional quality',
- 'Government effectiveness',
- 'Rule of law',
- 'Corruption control',
- 'Policy predictability'
- ]
- }
-
- @staticmethod
- def debt_sustainability_analysis(country_data: Dict[str, Decimal]) -> Dict[str, Decimal]:
- """Analyze sovereign debt sustainability"""
- # Extract key metrics
- debt_gdp = country_data.get('debt_to_gdp', Decimal('0.6'))
- gdp_growth = country_data.get('gdp_growth', Decimal('0.02'))
- interest_rate = country_data.get('avg_interest_rate', Decimal('0.03'))
- primary_balance = country_data.get('primary_balance_gdp', Decimal('0'))
-
- ValidationUtils.validate_percentage(debt_gdp, "Debt-to-GDP ratio", allow_negative=False)
- ValidationUtils.validate_percentage(gdp_growth, "GDP growth", allow_negative=True)
- ValidationUtils.validate_yield(interest_rate, "Average interest rate")
- ValidationUtils.validate_percentage(primary_balance, "Primary balance", allow_negative=True)
-
- # Debt dynamics: Δd = (r-g)d + primary_deficit
- # where d = debt/GDP, r = interest rate, g = growth rate
-
- real_interest_rate = interest_rate - gdp_growth
- debt_stabilizing_balance = -real_interest_rate * debt_gdp
-
- # Current debt change
- current_debt_change = real_interest_rate * debt_gdp - primary_balance
-
- # Projected debt/GDP in 5 years (simplified)
- projected_debt_gdp = debt_gdp
- for year in range(5):
- debt_change = real_interest_rate * projected_debt_gdp - primary_balance
- projected_debt_gdp += debt_change
-
- # Sustainability indicators
- sustainability_score = SovereignCreditAnalysis._calculate_sustainability_score(
- debt_gdp, gdp_growth, interest_rate, primary_balance
- )
-
- return {
- 'current_debt_gdp': debt_gdp,
- 'debt_stabilizing_balance': debt_stabilizing_balance,
- 'current_primary_balance': primary_balance,
- 'balance_gap': primary_balance - debt_stabilizing_balance,
- 'current_debt_change': current_debt_change,
- 'projected_debt_gdp_5y': projected_debt_gdp,
- 'sustainability_score': sustainability_score,
- 'fiscal_space': max(Decimal('0'), Decimal('0.9') - debt_gdp), # Assume 90% threshold
- 'sustainable': sustainability_score >= Decimal('0.7')
- }
-
- @staticmethod
- def _calculate_sustainability_score(debt_gdp: Decimal, gdp_growth: Decimal,
- interest_rate: Decimal, primary_balance: Decimal) -> Decimal:
- """Calculate composite sustainability score (0-1 scale)"""
-
- # Debt level score (lower is better)
- debt_score = max(Decimal('0'), Decimal('1') - debt_gdp / Decimal('1.5')) # Penalty above 150%
-
- # Growth score (higher is better)
- growth_score = min(Decimal('1'), max(Decimal('0'), gdp_growth * Decimal('10'))) # 10% = perfect
-
- # Interest burden score (lower is better)
- interest_score = max(Decimal('0'), Decimal('1') - interest_rate * Decimal('10')) # 10% = worst
-
- # Fiscal balance score (higher is better)
- balance_score = min(Decimal('1'), max(Decimal('0'), primary_balance * Decimal('20') + Decimal('0.5')))
-
- # Weighted average
- weights = [Decimal('0.3'), Decimal('0.25'), Decimal('0.25'), Decimal('0.2')]
- scores = [debt_score, growth_score, interest_score, balance_score]
-
- return sum(w * s for w, s in zip(weights, scores))
-
- @staticmethod
- def sovereign_spread_analysis(country: str, benchmark_yield: Decimal,
- sovereign_yield: Decimal, factors: Dict[str, Decimal]) -> Dict[str, Decimal]:
- """Analyze sovereign credit spreads"""
- ValidationUtils.validate_yield(benchmark_yield, "Benchmark yield")
- ValidationUtils.validate_yield(sovereign_yield, "Sovereign yield")
-
- # Basic spread calculation
- credit_spread = sovereign_yield - benchmark_yield
- spread_bps = credit_spread * Decimal('10000')
-
- # Factor decomposition (simplified)
- base_spread = Decimal('0.001') # 10 bps base
-
- # Economic factors contribution
- gdp_factor = factors.get('gdp_growth', Decimal('0.02'))
- economic_contrib = max(Decimal('0'), (Decimal('0.02') - gdp_factor) * Decimal('0.5'))
-
- # Fiscal factors contribution
- debt_gdp = factors.get('debt_gdp', Decimal('0.6'))
- fiscal_contrib = max(Decimal('0'), (debt_gdp - Decimal('0.6')) * Decimal('0.02'))
-
- # External factors contribution
- current_account = factors.get('current_account_gdp', Decimal('0'))
- external_contrib = max(Decimal('0'), -current_account * Decimal('0.1'))
-
- # Political/institutional factors
- political_score = factors.get('political_stability', Decimal('0.7')) # 0-1 scale
- political_contrib = max(Decimal('0'), (Decimal('0.7') - political_score) * Decimal('0.05'))
-
- theoretical_spread = base_spread + economic_contrib + fiscal_contrib + external_contrib + political_contrib
-
- return {
- 'observed_spread': credit_spread,
- 'spread_bps': spread_bps,
- 'theoretical_spread': theoretical_spread,
- 'spread_difference': credit_spread - theoretical_spread,
- 'factor_contributions': {
- 'base_spread': base_spread,
- 'economic_factor': economic_contrib,
- 'fiscal_factor': fiscal_contrib,
- 'external_factor': external_contrib,
- 'political_factor': political_contrib
- },
- 'relative_value': 'cheap' if credit_spread > theoretical_spread else 'expensive'
- }
-
-
-class MunicipalBondAnalysis:
- """Municipal bond analysis and evaluation"""
-
- @staticmethod
- def municipal_credit_factors() -> Dict[str, List[str]]:
- """Key factors for municipal credit analysis"""
- return {
- 'economic_base': [
- 'Economic diversity',
- 'Employment trends',
- 'Income levels',
- 'Population growth',
- 'Business environment',
- 'Tax base stability'
- ],
- 'financial_performance': [
- 'Operating performance',
- 'Debt burden',
- 'Liquidity position',
- 'Financial flexibility',
- 'Capital planning',
- 'Reserve levels'
- ],
- 'debt_structure': [
- 'Debt per capita',
- 'Debt service coverage',
- 'Direct vs overlapping debt',
- 'Variable rate exposure',
- 'Derivative usage',
- 'Refinancing risk'
- ],
- 'governance_management': [
- 'Management quality',
- 'Financial reporting',
- 'Budget practices',
- 'Transparency',
- 'Political environment',
- 'Stakeholder relations'
- ]
- }
-
- @staticmethod
- def go_bond_analysis(issuer_data: Dict[str, Decimal]) -> Dict[str, Decimal]:
- """Analyze General Obligation (GO) municipal bonds"""
-
- # Key GO bond metrics
- assessed_value = issuer_data.get('assessed_value', Decimal('1000000000')) # $1B default
- population = issuer_data.get('population', Decimal('100000')) # 100k default
- total_debt = issuer_data.get('total_debt', Decimal('50000000')) # $50M default
- annual_debt_service = issuer_data.get('annual_debt_service', Decimal('5000000')) # $5M default
- operating_revenues = issuer_data.get('operating_revenues', Decimal('100000000')) # $100M default
- fund_balance = issuer_data.get('fund_balance', Decimal('20000000')) # $20M default
-
- # Calculate key ratios
- debt_per_capita = total_debt / population
- debt_to_assessed_value = total_debt / assessed_value
- debt_service_coverage = operating_revenues / annual_debt_service
- fund_balance_ratio = fund_balance / operating_revenues
-
- # Credit quality scoring
- debt_burden_score = MunicipalBondAnalysis._score_debt_burden(debt_per_capita, debt_to_assessed_value)
- coverage_score = MunicipalBondAnalysis._score_coverage(debt_service_coverage)
- liquidity_score = MunicipalBondAnalysis._score_liquidity(fund_balance_ratio)
-
- overall_score = (debt_burden_score + coverage_score + liquidity_score) / Decimal('3')
-
- return {
- 'debt_per_capita': debt_per_capita,
- 'debt_to_assessed_value_pct': debt_to_assessed_value * Decimal('100'),
- 'debt_service_coverage': debt_service_coverage,
- 'fund_balance_ratio_pct': fund_balance_ratio * Decimal('100'),
- 'credit_scores': {
- 'debt_burden': debt_burden_score,
- 'coverage': coverage_score,
- 'liquidity': liquidity_score,
- 'overall': overall_score
- },
- 'credit_quality': MunicipalBondAnalysis._interpret_score(overall_score)
- }
-
- @staticmethod
- def revenue_bond_analysis(project_data: Dict[str, Decimal]) -> Dict[str, Decimal]:
- """Analyze Revenue municipal bonds"""
-
- # Revenue bond specific metrics
- gross_revenues = project_data.get('gross_revenues', Decimal('50000000'))
- operating_expenses = project_data.get('operating_expenses', Decimal('30000000'))
- debt_service = project_data.get('debt_service', Decimal('15000000'))
- rate_covenant = project_data.get('rate_covenant', Decimal('1.25')) # 1.25x coverage requirement
-
- # Calculate coverage ratios
- net_revenues = gross_revenues - operating_expenses
- debt_service_coverage = net_revenues / debt_service if debt_service > 0 else Decimal('999')
-
- # Additional coverage tests
- additional_bonds_test = debt_service_coverage >= rate_covenant
-
- # Cash flow analysis
- free_cash_flow = net_revenues - debt_service
- cash_flow_margin = free_cash_flow / gross_revenues if gross_revenues > 0 else Decimal('0')
-
- # Project viability metrics
- utilization_rate = project_data.get('utilization_rate', Decimal('0.8'))
- capacity_factor = project_data.get('capacity_factor', Decimal('0.9'))
-
- return {
- 'gross_revenues': gross_revenues,
- 'net_revenues': net_revenues,
- 'debt_service_coverage': debt_service_coverage,
- 'rate_covenant': rate_covenant,
- 'covenant_compliance': additional_bonds_test,
- 'coverage_cushion': debt_service_coverage - rate_covenant,
- 'free_cash_flow': free_cash_flow,
- 'cash_flow_margin_pct': cash_flow_margin * Decimal('100'),
- 'utilization_rate_pct': utilization_rate * Decimal('100'),
- 'capacity_factor_pct': capacity_factor * Decimal('100'),
- 'project_viability': MunicipalBondAnalysis._assess_project_viability(
- debt_service_coverage, utilization_rate, capacity_factor
- )
- }
-
- @staticmethod
- def _score_debt_burden(debt_per_capita: Decimal, debt_to_av: Decimal) -> Decimal:
- """Score debt burden (0-1 scale)"""
- # Lower debt burden = higher score
- per_capita_score = max(Decimal('0'), Decimal('1') - debt_per_capita / Decimal('5000')) # $5k benchmark
- av_score = max(Decimal('0'), Decimal('1') - debt_to_av / Decimal('0.1')) # 10% benchmark
-
- return (per_capita_score + av_score) / Decimal('2')
-
- @staticmethod
- def _score_coverage(coverage_ratio: Decimal) -> Decimal:
- """Score debt service coverage"""
- if coverage_ratio >= Decimal('3'):
- return Decimal('1')
- elif coverage_ratio >= Decimal('2'):
- return Decimal('0.8')
- elif coverage_ratio >= Decimal('1.5'):
- return Decimal('0.6')
- elif coverage_ratio >= Decimal('1.2'):
- return Decimal('0.4')
- else:
- return Decimal('0.2')
-
- @staticmethod
- def _score_liquidity(fund_balance_ratio: Decimal) -> Decimal:
- """Score liquidity position"""
- if fund_balance_ratio >= Decimal('0.25'): # 25%+
- return Decimal('1')
- elif fund_balance_ratio >= Decimal('0.15'): # 15-25%
- return Decimal('0.8')
- elif fund_balance_ratio >= Decimal('0.10'): # 10-15%
- return Decimal('0.6')
- elif fund_balance_ratio >= Decimal('0.05'): # 5-10%
- return Decimal('0.4')
- else:
- return Decimal('0.2')
-
- @staticmethod
- def _interpret_score(score: Decimal) -> str:
- """Interpret overall credit score"""
- if score >= Decimal('0.8'):
- return 'Strong'
- elif score >= Decimal('0.6'):
- return 'Good'
- elif score >= Decimal('0.4'):
- return 'Satisfactory'
- elif score >= Decimal('0.2'):
- return 'Weak'
- else:
- return 'Distressed'
-
- @staticmethod
- def _assess_project_viability(coverage: Decimal, utilization: Decimal, capacity: Decimal) -> str:
- """Assess revenue bond project viability"""
- score = (coverage / Decimal('2') + utilization + capacity) / Decimal('3') # Normalize coverage
-
- if score >= Decimal('0.8'):
- return 'Highly Viable'
- elif score >= Decimal('0.6'):
- return 'Viable'
- elif score >= Decimal('0.4'):
- return 'Marginal'
- else:
- return 'Distressed'
-
-
-class AgencyDebtAnalysis:
- """Government agency and GSE debt analysis"""
-
- @staticmethod
- def agency_types() -> Dict[str, Dict[str, str]]:
- """Classification of government agencies and GSEs"""
- return {
- 'federal_agencies': {
- 'description': 'Direct obligations of US government agencies',
- 'credit_support': 'Full faith and credit backing',
- 'examples': 'GNMA, SBA, Tennessee Valley Authority'
- },
- 'government_sponsored_enterprises': {
- 'description': 'Privately-owned, government-chartered entities',
- 'credit_support': 'Implied government support (historically)',
- 'examples': 'Fannie Mae, Freddie Mac, Federal Home Loan Banks'
- },
- 'supranational_agencies': {
- 'description': 'International organizations',
- 'credit_support': 'Member country support',
- 'examples': 'World Bank, Asian Development Bank, European Investment Bank'
- }
- }
-
- @staticmethod
- def gse_credit_analysis(gse_data: Dict[str, Decimal]) -> Dict[str, Decimal]:
- """Analyze Government Sponsored Enterprise credit quality"""
-
- # Capital adequacy
- tier1_capital = gse_data.get('tier1_capital', Decimal('50000000000'))
- risk_weighted_assets = gse_data.get('risk_weighted_assets', Decimal('500000000000'))
- tier1_ratio = tier1_capital / risk_weighted_assets
-
- # Asset quality
- total_assets = gse_data.get('total_assets', Decimal('1000000000000'))
- non_performing_assets = gse_data.get('non_performing_assets', Decimal('5000000000'))
- npa_ratio = non_performing_assets / total_assets
-
- # Profitability
- net_income = gse_data.get('net_income', Decimal('10000000000'))
- average_assets = gse_data.get('average_assets', total_assets)
- roa = net_income / average_assets
-
- # Liquidity
- liquid_assets = gse_data.get('liquid_assets', Decimal('100000000000'))
- short_term_debt = gse_data.get('short_term_debt', Decimal('200000000000'))
- liquidity_ratio = liquid_assets / short_term_debt
-
- # Government support assessment
- systemic_importance = gse_data.get('market_share', Decimal('0.3')) # 30% market share
- government_ties = gse_data.get('government_charter_score', Decimal('0.8')) # 0-1 scale
-
- # Overall assessment
- financial_strength = AgencyDebtAnalysis._assess_financial_strength(
- tier1_ratio, npa_ratio, roa, liquidity_ratio
- )
-
- government_support_score = (systemic_importance + government_ties) / Decimal('2')
-
- return {
- 'capital_adequacy': {
- 'tier1_ratio_pct': tier1_ratio * Decimal('100'),
- 'regulatory_minimum': Decimal('4'), # 4% minimum
- 'well_capitalized': tier1_ratio >= Decimal('0.06') # 6% well-capitalized
- },
- 'asset_quality': {
- 'npa_ratio_pct': npa_ratio * Decimal('100'),
- 'asset_quality_score': max(Decimal('0'), Decimal('1') - npa_ratio * Decimal('20'))
- },
- 'profitability': {
- 'roa_pct': roa * Decimal('100'),
- 'profitability_score': min(Decimal('1'), max(Decimal('0'), roa * Decimal('100')))
- },
- 'liquidity': {
- 'liquidity_ratio': liquidity_ratio,
- 'liquidity_adequate': liquidity_ratio >= Decimal('0.5')
- },
- 'government_support': {
- 'support_score': government_support_score,
- 'systemic_importance': systemic_importance,
- 'government_ties': government_ties
- },
- 'overall_assessment': {
- 'financial_strength': financial_strength,
- 'government_support': government_support_score,
- 'combined_rating': AgencyDebtAnalysis._derive_rating(financial_strength, government_support_score)
- }
- }
-
- @staticmethod
- def _assess_financial_strength(tier1_ratio: Decimal, npa_ratio: Decimal,
- roa: Decimal, liquidity_ratio: Decimal) -> Decimal:
- """Assess standalone financial strength (0-1 scale)"""
-
- # Capital score
- capital_score = min(Decimal('1'), tier1_ratio / Decimal('0.08')) # 8% = perfect
-
- # Asset quality score
- asset_score = max(Decimal('0'), Decimal('1') - npa_ratio * Decimal('50')) # 2% NPA = 0 score
-
- # Profitability score
- profit_score = min(Decimal('1'), max(Decimal('0'), roa * Decimal('100'))) # 1% ROA = perfect
-
- # Liquidity score
- liquidity_score = min(Decimal('1'), liquidity_ratio / Decimal('1')) # 100% = perfect
-
- # Weighted average
- weights = [Decimal('0.3'), Decimal('0.3'), Decimal('0.2'), Decimal('0.2')]
- scores = [capital_score, asset_score, profit_score, liquidity_score]
-
- return sum(w * s for w, s in zip(weights, scores))
-
- @staticmethod
- def _derive_rating(financial_strength: Decimal, government_support: Decimal) -> str:
- """Derive credit rating from financial strength and government support"""
-
- # Combined score with higher weight on government support for GSEs
- combined_score = financial_strength * Decimal('0.4') + government_support * Decimal('0.6')
-
- if combined_score >= Decimal('0.9'):
- return 'AAA'
- elif combined_score >= Decimal('0.8'):
- return 'AA'
- elif combined_score >= Decimal('0.7'):
- return 'A'
- elif combined_score >= Decimal('0.6'):
- return 'BBB'
- elif combined_score >= Decimal('0.5'):
- return 'BB'
- else:
- return 'B'
-
-
-class InflationLinkedBonds:
- """Inflation-linked government bond analysis"""
-
- @staticmethod
- def tips_analysis(principal: Decimal, coupon_rate: Decimal,
- inflation_rate: Decimal, years_remaining: Decimal) -> Dict[str, Decimal]:
- """Analyze Treasury Inflation-Protected Securities (TIPS)"""
- ValidationUtils.validate_positive(principal, "Principal")
- ValidationUtils.validate_positive(coupon_rate, "Coupon rate")
- ValidationUtils.validate_percentage(inflation_rate, "Inflation rate", allow_negative=True)
- ValidationUtils.validate_positive(years_remaining, "Years remaining")
-
- # Inflation-adjusted principal
- inflation_factor = (Decimal('1') + inflation_rate) ** years_remaining
- adjusted_principal = principal * inflation_factor
-
- # Annual coupon payment (based on adjusted principal)
- annual_coupon = adjusted_principal * coupon_rate
-
- # Real yield calculation (simplified)
- nominal_yield = coupon_rate + inflation_rate # Approximation
- real_yield = coupon_rate # TIPS coupon rate is the real yield
-
- # Breakeven inflation rate (what inflation needs to be for TIPS to outperform nominals)
- nominal_bond_yield = Decimal('0.05') # Assume 5% nominal Treasury yield
- breakeven_inflation = nominal_bond_yield - real_yield
-
- return {
- 'original_principal': principal,
- 'inflation_adjusted_principal': adjusted_principal,
- 'inflation_adjustment_factor': inflation_factor,
- 'annual_coupon_payment': annual_coupon,
- 'real_yield': real_yield,
- 'nominal_yield_equivalent': nominal_yield,
- 'breakeven_inflation_rate': breakeven_inflation,
- 'inflation_protection': inflation_rate - breakeven_inflation,
- 'attractive_vs_nominal': inflation_rate > breakeven_inflation
- }
-
- @staticmethod
- def inflation_swap_analysis(notional: Decimal, fixed_rate: Decimal,
- expected_inflation: Decimal, tenor: Decimal) -> Dict[str, Decimal]:
- """Analyze inflation swap for hedging purposes"""
- ValidationUtils.validate_positive(notional, "Notional")
- ValidationUtils.validate_yield(fixed_rate, "Fixed rate")
- ValidationUtils.validate_percentage(expected_inflation, "Expected inflation", allow_negative=True)
- ValidationUtils.validate_positive(tenor, "Tenor")
-
- # Inflation swap PV calculation (simplified)
- fixed_leg_pv = notional * fixed_rate * tenor # Simplified fixed leg
-
- # Floating leg expected value
- floating_leg_pv = notional * expected_inflation * tenor
-
- # Swap value to fixed rate payer
- swap_value = floating_leg_pv - fixed_leg_pv
-
- # Breakeven inflation
- breakeven = fixed_rate
-
- return {
- 'notional_amount': notional,
- 'fixed_rate': fixed_rate,
- 'expected_inflation': expected_inflation,
- 'fixed_leg_pv': fixed_leg_pv,
- 'floating_leg_pv': floating_leg_pv,
- 'swap_value_to_payer': swap_value,
- 'breakeven_inflation': breakeven,
- 'inflation_expectation_vs_breakeven': expected_inflation - breakeven
- }
-
-
-# Utility functions for government debt analysis
-def sovereign_debt_comparison(countries: Dict[str, Dict[str, Decimal]]) -> Dict[str, Dict]:
- """Compare sovereign debt metrics across countries"""
-
- comparison = {}
-
- for country, data in countries.items():
- sustainability = SovereignCreditAnalysis.debt_sustainability_analysis(data)
-
- comparison[country] = {
- 'debt_gdp_ratio': data.get('debt_to_gdp', Decimal('0')),
- 'sustainability_score': sustainability['sustainability_score'],
- 'fiscal_space': sustainability['fiscal_space'],
- 'sustainable': sustainability['sustainable'],
- 'projected_debt_5y': sustainability['projected_debt_gdp_5y']
- }
-
- # Rank countries by sustainability
- ranked = sorted(comparison.items(),
- key=lambda x: x[1]['sustainability_score'],
- reverse=True)
-
- return {
- 'country_analysis': comparison,
- 'ranking_by_sustainability': [country for country, _ in ranked],
- 'summary_statistics': {
- 'average_debt_gdp': sum(data['debt_gdp_ratio'] for data in comparison.values()) / len(comparison),
- 'countries_sustainable': sum(1 for data in comparison.values() if data['sustainable']),
- 'total_countries': len(comparison)
- }
- }
-
-
-def municipal_portfolio_analysis(portfolio: Portfolio,
- muni_data: Dict[str, Dict[str, Decimal]]) -> Dict[str, any]:
- """Analyze municipal bond portfolio"""
-
- total_exposure = Decimal('0')
- go_exposure = Decimal('0')
- revenue_exposure = Decimal('0')
-
- issuer_analysis = {}
-
- for bond, quantity in portfolio.holdings:
- if bond.sector == 'Municipal':
- exposure = bond.face_value * quantity
- total_exposure += exposure
-
- issuer = bond.issuer_name
- if issuer in muni_data:
- issuer_data = muni_data[issuer]
-
- # Determine bond type and analyze
- if issuer_data.get('bond_type') == 'GO':
- go_exposure += exposure
- analysis = MunicipalBondAnalysis.go_bond_analysis(issuer_data)
- else:
- revenue_exposure += exposure
- analysis = MunicipalBondAnalysis.revenue_bond_analysis(issuer_data)
-
- issuer_analysis[issuer] = {
- 'exposure': exposure,
- 'analysis': analysis,
- 'weight': exposure / total_exposure if total_exposure > 0 else Decimal('0')
- }
-
- return {
- 'portfolio_composition': {
- 'total_municipal_exposure': total_exposure,
- 'go_bond_exposure': go_exposure,
- 'revenue_bond_exposure': revenue_exposure,
- 'go_percentage': go_exposure / total_exposure if total_exposure > 0 else Decimal('0'),
- 'revenue_percentage': revenue_exposure / total_exposure if total_exposure > 0 else Decimal('0')
- },
- 'issuer_analysis': issuer_analysis,
- 'portfolio_quality_metrics': {
- 'weighted_avg_coverage': sum(
- data['analysis'].get('debt_service_coverage', Decimal('1')) * data['weight']
- for data in issuer_analysis.values()
- ),
- 'number_of_issuers': len(issuer_analysis),
- 'concentration_risk': max(
- data['weight'] for data in issuer_analysis.values()) if issuer_analysis else Decimal('0')
- }
- }
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/instruments.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/instruments.py
deleted file mode 100644
index 5784143bf..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/instruments.py
+++ /dev/null
@@ -1,471 +0,0 @@
-
-Fixed Income Instruments Module
-=================================
-
-Fixed income instrument definitions
-
-===== DATA SOURCES REQUIRED =====
-INPUT:
- - Bond prospectuses and issue documentation
- - Market price data and yield curve information
- - Credit ratings and default recovery rates
- - Interest rate benchmarks and swap curves
- - Macroeconomic data affecting fixed income markets
-
-OUTPUT:
- - Bond valuation models and price calculations
- - Yield curve analysis and forward rate calculations
- - Credit risk assessment and spread analysis
- - Duration and convexity risk metrics
- - Portfolio optimization and immunization strategies
-
-PARAMETERS:
- - yield_curve_method: Yield curve modeling method (default: 'nelson_siegel')
- - credit_spread: Credit spread assumption (default: 0.02)
- - recovery_rate: Default recovery rate (default: 0.40)
- - convexity_adjustment: Convexity adjustment factor (default: 1.0)
- - benchmark_curve: Benchmark yield curve (default: 'treasury')
-
-
-from typing import List, Optional, Dict, Tuple
-from decimal import Decimal
-from datetime import date, timedelta
-from models import (
- Bond, CallableBond, PutableBond, FloatingRateNote, ConvertibleBond,
- CashFlow, CallableFeature, PutableFeature, ValidationError
-)
-from config import (
- DayCountConvention, CompoundingFrequency, BusinessDayConvention,
- Currency, BondType, get_market_convention
-)
-
-
-class BondInstrument:
- """Base bond instrument class with core functionality"""
-
- def __init__(self, bond: Bond):
- self.bond = bond
- self._cash_flows = None
-
- def generate_cash_flows(self, settlement_date: Optional[date] = None) -> List[CashFlow]:
- """Generate bond cash flows from settlement date to maturity"""
- if settlement_date is None:
- settlement_date = date.today()
-
- cash_flows = []
-
- # For zero coupon bonds, only final payment
- if self.bond.is_zero_coupon:
- cash_flows.append(CashFlow(
- date=self.bond.maturity_date,
- amount=self.bond.face_value,
- type="principal"
- ))
- return cash_flows
-
- # Generate coupon payment dates
- coupon_dates = self._generate_coupon_dates(settlement_date)
-
- # Generate coupon payments
- coupon_amount = self._calculate_coupon_amount()
-
- for coupon_date in coupon_dates:
- if coupon_date > settlement_date:
- cash_flows.append(CashFlow(
- date=coupon_date,
- amount=coupon_amount,
- type="coupon"
- ))
-
- # Add principal repayment at maturity
- if cash_flows: # If there are coupon payments
- cash_flows[-1].amount += self.bond.face_value
- cash_flows[-1].type = "coupon_and_principal"
- else: # If no future coupons, just principal
- cash_flows.append(CashFlow(
- date=self.bond.maturity_date,
- amount=self.bond.face_value,
- type="principal"
- ))
-
- self._cash_flows = cash_flows
- return cash_flows
-
- def _generate_coupon_dates(self, start_date: date) -> List[date]:
- """Generate coupon payment dates"""
- dates = []
- frequency = self.bond.coupon_frequency.value
-
- if frequency == 0: # Continuous compounding - treat as annual
- frequency = 1
-
- # Calculate months between payments
- months_between = 12 // frequency
-
- # Start from maturity and work backwards
- current_date = self.bond.maturity_date
-
- while current_date > self.bond.issue_date:
- dates.append(current_date)
- # Subtract months
- if current_date.month <= months_between:
- new_month = 12 + current_date.month - months_between
- new_year = current_date.year - 1
- else:
- new_month = current_date.month - months_between
- new_year = current_date.year
-
- try:
- current_date = current_date.replace(year=new_year, month=new_month)
- except ValueError:
- # Handle end-of-month dates
- if new_month == 2 and current_date.day > 28:
- current_date = current_date.replace(year=new_year, month=new_month, day=28)
- else:
- current_date = current_date.replace(year=new_year, month=new_month, day=1)
- current_date = current_date.replace(day=min(current_date.day,
- self._days_in_month(new_year, new_month)))
-
- # Reverse to get chronological order
- dates.reverse()
- return dates
-
- def _days_in_month(self, year: int, month: int) -> int:
- """Get number of days in a month"""
- if month == 12:
- next_month = date(year + 1, 1, 1)
- else:
- next_month = date(year, month + 1, 1)
- this_month = date(year, month, 1)
- return (next_month - this_month).days
-
- def _calculate_coupon_amount(self) -> Decimal:
- """Calculate coupon payment amount"""
- annual_coupon = self.bond.face_value * self.bond.coupon_rate
- frequency = self.bond.coupon_frequency.value
-
- if frequency == 0: # Continuous compounding
- return annual_coupon
-
- return annual_coupon / Decimal(frequency)
-
- def accrued_interest(self, settlement_date: date) -> Decimal:
- """Calculate accrued interest from last coupon date"""
- if self.bond.is_zero_coupon:
- return Decimal('0')
-
- coupon_dates = self._generate_coupon_dates(self.bond.issue_date)
-
- # Find last coupon date before settlement
- last_coupon_date = self.bond.issue_date
- for coupon_date in coupon_dates:
- if coupon_date <= settlement_date:
- last_coupon_date = coupon_date
- else:
- break
-
- # Calculate accrual period
- days_accrued = self._calculate_days(last_coupon_date, settlement_date)
- days_in_period = self._calculate_days_in_coupon_period(last_coupon_date)
-
- coupon_amount = self._calculate_coupon_amount()
-
- return coupon_amount * (Decimal(days_accrued) / Decimal(days_in_period))
-
- def _calculate_days(self, start_date: date, end_date: date) -> int:
- """Calculate days between dates based on day count convention"""
- if self.bond.day_count_convention == DayCountConvention.ACTUAL_360:
- return (end_date - start_date).days
- elif self.bond.day_count_convention == DayCountConvention.ACTUAL_365:
- return (end_date - start_date).days
- elif self.bond.day_count_convention == DayCountConvention.ACTUAL_ACTUAL:
- return (end_date - start_date).days
- elif self.bond.day_count_convention == DayCountConvention.THIRTY_360:
- return self._thirty_360_days(start_date, end_date)
- else:
- return (end_date - start_date).days
-
- def _thirty_360_days(self, start_date: date, end_date: date) -> int:
- """Calculate days using 30/360 convention"""
- d1 = min(start_date.day, 30)
- d2 = min(end_date.day, 30) if d1 == 30 else end_date.day
-
- return (360 * (end_date.year - start_date.year) +
- 30 * (end_date.month - start_date.month) +
- (d2 - d1))
-
- def _calculate_days_in_coupon_period(self, coupon_date: date) -> int:
- """Calculate days in coupon period"""
- frequency = self.bond.coupon_frequency.value
- if frequency == 0:
- frequency = 1
-
- if self.bond.day_count_convention == DayCountConvention.THIRTY_360:
- return 360 // frequency
- else:
- return 365 // frequency # Approximation
-
- def time_to_maturity(self, settlement_date: Optional[date] = None) -> Decimal:
- """Calculate time to maturity in years"""
- if settlement_date is None:
- settlement_date = date.today()
-
- days = (self.bond.maturity_date - settlement_date).days
-
- if self.bond.day_count_convention == DayCountConvention.ACTUAL_365:
- return Decimal(days) / Decimal('365')
- elif self.bond.day_count_convention == DayCountConvention.ACTUAL_360:
- return Decimal(days) / Decimal('360')
- else:
- return Decimal(days) / Decimal('365.25') # Default
-
-
-class CallableBondInstrument(BondInstrument):
- """Callable bond instrument with embedded call option"""
-
- def __init__(self, callable_bond: CallableBond):
- super().__init__(callable_bond)
- self.callable_bond = callable_bond
-
- def is_callable_on_date(self, check_date: date) -> bool:
- """Check if bond is callable on a specific date"""
- for call_feature in self.callable_bond.call_schedule:
- if call_feature.call_date == check_date:
- return True
- return False
-
- def get_call_price(self, call_date: date) -> Optional[Decimal]:
- """Get call price for a specific date"""
- for call_feature in self.callable_bond.call_schedule:
- if call_feature.call_date == call_date:
- return call_feature.call_price
- return None
-
- def next_call_date(self, from_date: Optional[date] = None) -> Optional[date]:
- """Get next call date after specified date"""
- if from_date is None:
- from_date = date.today()
-
- next_call = None
- for call_feature in self.callable_bond.call_schedule:
- if call_feature.call_date > from_date:
- if next_call is None or call_feature.call_date < next_call:
- next_call = call_feature.call_date
-
- return next_call
-
- def effective_maturity(self, yield_to_call: Decimal, yield_to_maturity: Decimal) -> date:
- """Determine effective maturity based on yield comparison"""
- next_call = self.next_call_date()
-
- if next_call and yield_to_call < yield_to_maturity:
- return next_call
- else:
- return self.bond.maturity_date
-
-
-class PutableBondInstrument(BondInstrument):
- """Putable bond instrument with embedded put option"""
-
- def __init__(self, putable_bond: PutableBond):
- super().__init__(putable_bond)
- self.putable_bond = putable_bond
-
- def is_putable_on_date(self, check_date: date) -> bool:
- """Check if bond is putable on a specific date"""
- for put_feature in self.putable_bond.put_schedule:
- if put_feature.put_date == check_date:
- return True
- return False
-
- def get_put_price(self, put_date: date) -> Optional[Decimal]:
- """Get put price for a specific date"""
- for put_feature in self.putable_bond.put_schedule:
- if put_feature.put_date == put_date:
- return put_feature.put_price
- return None
-
- def next_put_date(self, from_date: Optional[date] = None) -> Optional[date]:
- """Get next put date after specified date"""
- if from_date is None:
- from_date = date.today()
-
- next_put = None
- for put_feature in self.putable_bond.put_schedule:
- if put_feature.put_date > from_date:
- if next_put is None or put_feature.put_date < next_put:
- next_put = put_feature.put_date
-
- return next_put
-
-
-class FloatingRateNoteInstrument(BondInstrument):
- """Floating rate note instrument"""
-
- def __init__(self, frn: FloatingRateNote):
- super().__init__(frn)
- self.frn = frn
- self._current_reference_rate = Decimal('0')
-
- def set_reference_rate(self, rate: Decimal):
- """Set current reference rate"""
- self._current_reference_rate = rate
-
- def current_coupon_rate(self) -> Decimal:
- """Calculate current coupon rate"""
- base_rate = self._current_reference_rate + self.frn.spread
-
- # Apply cap and floor if specified
- if self.frn.rate_cap and base_rate > self.frn.rate_cap:
- return self.frn.rate_cap
-
- if self.frn.rate_floor and base_rate < self.frn.rate_floor:
- return self.frn.rate_floor
-
- return base_rate
-
- def generate_cash_flows_with_rate_path(self, rate_path: List[Tuple[date, Decimal]]) -> List[CashFlow]:
- """Generate cash flows given a path of reference rates"""
- cash_flows = []
- coupon_dates = self._generate_coupon_dates(date.today())
-
- for i, coupon_date in enumerate(coupon_dates):
- if coupon_date > date.today():
- # Find applicable rate for this period
- applicable_rate = self._find_rate_for_period(rate_path, coupon_date)
-
- # Calculate coupon amount
- coupon_rate = applicable_rate + self.frn.spread
-
- # Apply caps and floors
- if self.frn.rate_cap:
- coupon_rate = min(coupon_rate, self.frn.rate_cap)
- if self.frn.rate_floor:
- coupon_rate = max(coupon_rate, self.frn.rate_floor)
-
- # Calculate payment amount
- coupon_amount = self.frn.face_value * coupon_rate / Decimal(self.frn.coupon_frequency.value)
-
- cash_flows.append(CashFlow(
- date=coupon_date,
- amount=coupon_amount,
- type="coupon"
- ))
-
- # Add principal at maturity
- if cash_flows:
- cash_flows[-1].amount += self.frn.face_value
- cash_flows[-1].type = "coupon_and_principal"
-
- return cash_flows
-
- def _find_rate_for_period(self, rate_path: List[Tuple[date, Decimal]], period_end: date) -> Decimal:
- """Find the reference rate applicable for a coupon period"""
- applicable_rate = Decimal('0')
-
- for rate_date, rate in rate_path:
- if rate_date <= period_end:
- applicable_rate = rate
- else:
- break
-
- return applicable_rate
-
-
-class ConvertibleBondInstrument(BondInstrument):
- """Convertible bond instrument"""
-
- def __init__(self, convertible: ConvertibleBond):
- super().__init__(convertible)
- self.convertible = convertible
-
- def conversion_value(self, stock_price: Optional[Decimal] = None) -> Decimal:
- """Calculate conversion value"""
- if stock_price is None:
- stock_price = self.convertible.underlying_stock_price
-
- if stock_price is None:
- raise ValidationError("Stock price required for conversion value calculation")
-
- return self.convertible.conversion_ratio * stock_price
-
- def conversion_premium(self, bond_price: Decimal, stock_price: Optional[Decimal] = None) -> Decimal:
- """Calculate conversion premium"""
- conv_value = self.conversion_value(stock_price)
- return bond_price - conv_value
-
- def conversion_premium_percentage(self, bond_price: Decimal, stock_price: Optional[Decimal] = None) -> Decimal:
- """Calculate conversion premium as percentage"""
- conv_value = self.conversion_value(stock_price)
- if conv_value == 0:
- return Decimal('0')
-
- premium = self.conversion_premium(bond_price, stock_price)
- return premium / conv_value * Decimal('100')
-
- def payback_period(self, bond_price: Decimal, dividend_yield: Optional[Decimal] = None) -> Optional[Decimal]:
- """Calculate payback period in years"""
- if dividend_yield is None:
- dividend_yield = self.convertible.dividend_yield
-
- if dividend_yield is None or dividend_yield == 0:
- return None
-
- coupon_yield = (self.convertible.coupon_rate * self.convertible.face_value) / bond_price
- yield_advantage = coupon_yield - dividend_yield
-
- if yield_advantage <= 0:
- return None
-
- premium_pct = self.conversion_premium_percentage(bond_price) / Decimal('100')
- return premium_pct / yield_advantage
-
- def delta(self, bond_price: Decimal, stock_price: Decimal) -> Decimal:
- """Calculate convertible bond delta (sensitivity to stock price)"""
- # Simplified delta calculation
- conv_value = self.conversion_value(stock_price)
-
- if bond_price <= conv_value:
- return self.convertible.conversion_ratio
- else:
- # Approximate delta for out-of-the-money convertible
- return self.convertible.conversion_ratio * (conv_value / bond_price)
-
-
-# Factory functions for instrument creation
-def create_bond_instrument(bond: Bond) -> BondInstrument:
- """Factory function to create appropriate instrument type"""
- if isinstance(bond, CallableBond):
- return CallableBondInstrument(bond)
- elif isinstance(bond, PutableBond):
- return PutableBondInstrument(bond)
- elif isinstance(bond, FloatingRateNote):
- return FloatingRateNoteInstrument(bond)
- elif isinstance(bond, ConvertibleBond):
- return ConvertibleBondInstrument(bond)
- else:
- return BondInstrument(bond)
-
-
-def create_callable_bond_with_schedule(base_bond: Bond,
- call_schedule: List[Tuple[date, Decimal]]) -> CallableBondInstrument:
- """Create callable bond with call schedule"""
- call_features = [CallableFeature(call_date=date, call_price=price) for date, price in call_schedule]
-
- callable_bond = CallableBond(
- isin=base_bond.isin,
- cusip=base_bond.cusip,
- ticker=base_bond.ticker,
- issue_date=base_bond.issue_date,
- maturity_date=base_bond.maturity_date,
- face_value=base_bond.face_value,
- currency=base_bond.currency,
- coupon_rate=base_bond.coupon_rate,
- coupon_frequency=base_bond.coupon_frequency,
- day_count_convention=base_bond.day_count_convention,
- issuer_name=base_bond.issuer_name,
- issuer_rating=base_bond.issuer_rating,
- call_schedule=call_features
- )
-
- return CallableBondInstrument(callable_bond)
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/models.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/models.py
deleted file mode 100644
index 793a93f5a..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/models.py
+++ /dev/null
@@ -1,429 +0,0 @@
-
-Fixed Income Models Module
-=================================
-
-Fixed income modeling and valuation
-
-===== DATA SOURCES REQUIRED =====
-INPUT:
- - Bond prospectuses and issue documentation
- - Market price data and yield curve information
- - Credit ratings and default recovery rates
- - Interest rate benchmarks and swap curves
- - Macroeconomic data affecting fixed income markets
-
-OUTPUT:
- - Bond valuation models and price calculations
- - Yield curve analysis and forward rate calculations
- - Credit risk assessment and spread analysis
- - Duration and convexity risk metrics
- - Portfolio optimization and immunization strategies
-
-PARAMETERS:
- - yield_curve_method: Yield curve modeling method (default: 'nelson_siegel')
- - credit_spread: Credit spread assumption (default: 0.02)
- - recovery_rate: Default recovery rate (default: 0.40)
- - convexity_adjustment: Convexity adjustment factor (default: 1.0)
- - benchmark_curve: Benchmark yield curve (default: 'treasury')
-
-
-from dataclasses import dataclass, field
-from typing import List, Dict, Optional, Union, Tuple
-from decimal import Decimal
-from datetime import datetime, date
-from config import (
- DayCountConvention, CompoundingFrequency, BusinessDayConvention,
- Currency, CreditRating, BondType, SecuritizationType,
- VALIDATION_RULES, ValidationError
-)
-
-
-@dataclass
-class CashFlow:
- """Represents a single cash flow"""
- date: date
- amount: Decimal
- type: str = "coupon" # coupon, principal, fee
-
- def __post_init__(self):
- if self.amount < 0:
- raise ValidationError("Cash flow amount cannot be negative")
-
-
-@dataclass
-class YieldCurve:
- """Yield curve data structure"""
- curve_date: date
- maturities: List[Decimal] # Years to maturity
- rates: List[Decimal] # Zero-coupon rates
- currency: Currency = Currency.USD
- curve_type: str = "spot" # spot, forward, par, swap
-
- def __post_init__(self):
- if len(self.maturities) != len(self.rates):
- raise ValidationError("Maturities and rates must have same length")
-
- if any(rate < VALIDATION_RULES['min_yield'] for rate in self.rates):
- raise ValidationError("Yield below minimum threshold")
-
- if any(rate > VALIDATION_RULES['max_yield'] for rate in self.rates):
- raise ValidationError("Yield above maximum threshold")
-
-
-@dataclass
-class CreditSpread:
- """Credit spread data structure"""
- rating: CreditRating
- maturity: Decimal
- spread: Decimal # Basis points over benchmark
- sector: Optional[str] = None
-
- def __post_init__(self):
- if self.spread < 0:
- raise ValidationError("Credit spread cannot be negative")
-
-
-@dataclass
-class Bond:
- """Base bond data model"""
- # Identification
- isin: str
- cusip: Optional[str] = None
- ticker: Optional[str] = None
-
- # Basic characteristics
- issue_date: date
- maturity_date: date
- face_value: Decimal = Decimal('100')
- currency: Currency = Currency.USD
-
- # Coupon details
- coupon_rate: Decimal = Decimal('0')
- coupon_frequency: CompoundingFrequency = CompoundingFrequency.SEMI_ANNUAL
- day_count_convention: DayCountConvention = DayCountConvention.THIRTY_360
-
- # Issuer information
- issuer_name: str = ""
- issuer_rating: Optional[CreditRating] = None
- sector: Optional[str] = None
- country: Optional[str] = None
-
- # Market data
- current_price: Optional[Decimal] = None
- current_yield: Optional[Decimal] = None
-
- # Bond type and features
- bond_type: BondType = BondType.FIXED_RATE
- callable: bool = False
- putable: bool = False
-
- # Settlement
- settlement_days: int = 3
- business_day_convention: BusinessDayConvention = BusinessDayConvention.MODIFIED_FOLLOWING
-
- def __post_init__(self):
- self._validate()
-
- def _validate(self):
- """Validate bond parameters"""
- if self.maturity_date <= self.issue_date:
- raise ValidationError("Maturity date must be after issue date")
-
- if self.coupon_rate < VALIDATION_RULES['min_coupon_rate']:
- raise ValidationError("Coupon rate below minimum")
-
- if self.coupon_rate > VALIDATION_RULES['max_coupon_rate']:
- raise ValidationError("Coupon rate above maximum")
-
- if self.current_price and (
- self.current_price < VALIDATION_RULES['min_price'] or
- self.current_price > VALIDATION_RULES['max_price']
- ):
- raise ValidationError("Bond price outside valid range")
-
- @property
- def time_to_maturity(self) -> Decimal:
- """Calculate time to maturity in years"""
- today = date.today()
- days_to_maturity = (self.maturity_date - today).days
- return Decimal(days_to_maturity) / Decimal('365.25')
-
- @property
- def is_zero_coupon(self) -> bool:
- """Check if bond is zero coupon"""
- return self.coupon_rate == 0 or self.bond_type == BondType.ZERO_COUPON
-
-
-@dataclass
-class CallableFeature:
- """Callable bond feature"""
- call_date: date
- call_price: Decimal
- call_type: str = "american" # american, european, bermudan
-
- def __post_init__(self):
- if self.call_price <= 0:
- raise ValidationError("Call price must be positive")
-
-
-@dataclass
-class PutableFeature:
- """Putable bond feature"""
- put_date: date
- put_price: Decimal
- put_type: str = "european"
-
- def __post_init__(self):
- if self.put_price <= 0:
- raise ValidationError("Put price must be positive")
-
-
-@dataclass
-class CallableBond(Bond):
- """Callable bond model"""
- call_schedule: List[CallableFeature] = field(default_factory=list)
-
- def __post_init__(self):
- super().__post_init__()
- self.callable = True
- self.bond_type = BondType.CALLABLE
-
-
-@dataclass
-class PutableBond(Bond):
- """Putable bond model"""
- put_schedule: List[PutableFeature] = field(default_factory=list)
-
- def __post_init__(self):
- super().__post_init__()
- self.putable = True
- self.bond_type = BondType.PUTABLE
-
-
-@dataclass
-class FloatingRateNote(Bond):
- """Floating rate note model"""
- reference_rate: str = "LIBOR" # LIBOR, SOFR, EURIBOR, etc.
- spread: Decimal = Decimal('0') # Spread over reference rate
- reset_frequency: CompoundingFrequency = CompoundingFrequency.QUARTERLY
- rate_cap: Optional[Decimal] = None
- rate_floor: Optional[Decimal] = None
-
- def __post_init__(self):
- super().__post_init__()
- self.bond_type = BondType.FLOATING_RATE
- self.coupon_rate = Decimal('0') # Will be set by reference rate
-
-
-@dataclass
-class ConvertibleBond(Bond):
- """Convertible bond model"""
- conversion_ratio: Decimal = Decimal('1')
- conversion_price: Decimal = Decimal('100')
- underlying_stock_price: Optional[Decimal] = None
- stock_volatility: Optional[Decimal] = None
- dividend_yield: Optional[Decimal] = None
-
- def __post_init__(self):
- super().__post_init__()
- self.bond_type = BondType.CONVERTIBLE
-
- @property
- def conversion_value(self) -> Optional[Decimal]:
- """Calculate conversion value"""
- if self.underlying_stock_price:
- return self.conversion_ratio * self.underlying_stock_price
- return None
-
-
-@dataclass
-class SecuritizedBond:
- """Base securitized product model"""
- # Identification
- cusip: str
- pool_number: Optional[str] = None
-
- # Structure details
- securitization_type: SecuritizationType = SecuritizationType.ABS
- original_balance: Decimal = Decimal('0')
- current_balance: Decimal = Decimal('0')
-
- # Underlying assets
- collateral_type: str = ""
- weighted_average_maturity: Optional[Decimal] = None
- weighted_average_coupon: Optional[Decimal] = None
-
- # Credit enhancement
- credit_enhancement_level: Decimal = Decimal('0')
- enhancement_type: str = "" # subordination, overcollateralization, insurance
-
- # Prepayment
- prepayment_speed: Optional[Decimal] = None # CPR or PSA
-
- def __post_init__(self):
- if self.current_balance > self.original_balance:
- raise ValidationError("Current balance cannot exceed original balance")
-
-
-@dataclass
-class MortgagePassThrough(SecuritizedBond):
- """Mortgage pass-through security"""
- agency: str = "" # GNMA, FNMA, FHLMC
- pool_type: str = "" # single-family, multi-family
-
- def __post_init__(self):
- super().__post_init__()
- self.securitization_type = SecuritizationType.MORTGAGE_PASS_THROUGH
-
-
-@dataclass
-class AssetBackedSecurity(SecuritizedBond):
- """Asset-backed security"""
- asset_class: str = "" # auto loans, credit cards, student loans
- geographic_concentration: Optional[str] = None
-
- def __post_init__(self):
- super().__post_init__()
- self.securitization_type = SecuritizationType.ABS
-
-
-@dataclass
-class CreditDefaultSwap:
- """Credit default swap model"""
- # Contract details
- reference_entity: str
- notional_amount: Decimal
- maturity_date: date
-
- # Pricing
- spread: Decimal # Basis points per annum
- upfront_payment: Decimal = Decimal('0')
- recovery_rate: Decimal = Decimal('0.40') # 40% default assumption
-
- # Contract specifications
- settlement_type: str = "physical" # physical, cash
- credit_events: List[str] = field(default_factory=lambda: ["bankruptcy", "failure_to_pay"])
-
- def __post_init__(self):
- if self.spread < 0:
- raise ValidationError("CDS spread cannot be negative")
-
- if not (0 <= self.recovery_rate <= 1):
- raise ValidationError("Recovery rate must be between 0 and 1")
-
-
-@dataclass
-class Portfolio:
- """Fixed income portfolio model"""
- name: str
- holdings: List[Tuple[Union[Bond, SecuritizedBond], Decimal]] = field(default_factory=list) # (instrument, quantity)
- cash_position: Decimal = Decimal('0')
- base_currency: Currency = Currency.USD
-
- def add_holding(self, instrument: Union[Bond, SecuritizedBond], quantity: Decimal):
- """Add holding to portfolio"""
- if quantity <= 0:
- raise ValidationError("Quantity must be positive")
- self.holdings.append((instrument, quantity))
-
- def remove_holding(self, instrument: Union[Bond, SecuritizedBond]):
- """Remove holding from portfolio"""
- self.holdings = [(inst, qty) for inst, qty in self.holdings if inst != instrument]
-
- @property
- def total_positions(self) -> int:
- """Get total number of positions"""
- return len(self.holdings)
-
- @property
- def total_face_value(self) -> Decimal:
- """Calculate total face value of portfolio"""
- total = Decimal('0')
- for instrument, quantity in self.holdings:
- if hasattr(instrument, 'face_value'):
- total += instrument.face_value * quantity
- elif hasattr(instrument, 'current_balance'):
- total += instrument.current_balance * quantity
- return total
-
-
-@dataclass
-class MarketData:
- """Market data container"""
- date: date
- yield_curves: Dict[Currency, YieldCurve] = field(default_factory=dict)
- credit_spreads: Dict[str, List[CreditSpread]] = field(default_factory=dict) # sector -> spreads
- exchange_rates: Dict[str, Decimal] = field(default_factory=dict) # currency pair -> rate
- volatilities: Dict[str, Decimal] = field(default_factory=dict) # instrument -> volatility
-
- def add_yield_curve(self, currency: Currency, curve: YieldCurve):
- """Add yield curve for currency"""
- self.yield_curves[currency] = curve
-
- def get_yield_curve(self, currency: Currency) -> Optional[YieldCurve]:
- """Get yield curve for currency"""
- return self.yield_curves.get(currency)
-
- def add_credit_spreads(self, sector: str, spreads: List[CreditSpread]):
- """Add credit spreads for sector"""
- self.credit_spreads[sector] = spreads
-
- def get_credit_spreads(self, sector: str) -> List[CreditSpread]:
- """Get credit spreads for sector"""
- return self.credit_spreads.get(sector, [])
-
-
-# Factory functions for creating common instruments
-def create_treasury_bond(maturity_years: Decimal, coupon_rate: Decimal,
- currency: Currency = Currency.USD) -> Bond:
- """Create a treasury bond"""
- today = date.today()
- maturity_date = date(today.year + int(maturity_years), today.month, today.day)
-
- return Bond(
- isin=f"US{today.strftime('%Y%m%d')}{maturity_years}",
- issue_date=today,
- maturity_date=maturity_date,
- coupon_rate=coupon_rate,
- currency=currency,
- issuer_name="U.S. Treasury",
- issuer_rating=CreditRating.AAA,
- sector="Government"
- )
-
-
-def create_corporate_bond(issuer: str, maturity_years: Decimal,
- coupon_rate: Decimal, rating: CreditRating) -> Bond:
- """Create a corporate bond"""
- today = date.today()
- maturity_date = date(today.year + int(maturity_years), today.month, today.day)
-
- return Bond(
- isin=f"CORP{today.strftime('%Y%m%d')}{maturity_years}",
- issue_date=today,
- maturity_date=maturity_date,
- coupon_rate=coupon_rate,
- issuer_name=issuer,
- issuer_rating=rating,
- sector="Corporate"
- )
-
-
-def create_zero_coupon_bond(maturity_years: Decimal, currency: Currency = Currency.USD) -> Bond:
- """Create a zero coupon bond"""
- today = date.today()
- maturity_date = date(today.year + int(maturity_years), today.month, today.day)
-
- return Bond(
- isin=f"ZERO{today.strftime('%Y%m%d')}{maturity_years}",
- issue_date=today,
- maturity_date=maturity_date,
- coupon_rate=Decimal('0'),
- currency=currency,
- bond_type=BondType.ZERO_COUPON
- )
-
-
-class ValidationError(Exception):
- """Custom validation error"""
- pass
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/risk_analytics.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/risk_analytics.py
deleted file mode 100644
index 361314985..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/risk_analytics.py
+++ /dev/null
@@ -1,573 +0,0 @@
-
-Fixed Income Risk Analytics Module
-=================================
-
-Fixed income risk analysis
-
-===== DATA SOURCES REQUIRED =====
-INPUT:
- - Bond prospectuses and issue documentation
- - Market price data and yield curve information
- - Credit ratings and default recovery rates
- - Interest rate benchmarks and swap curves
- - Macroeconomic data affecting fixed income markets
-
-OUTPUT:
- - Bond valuation models and price calculations
- - Yield curve analysis and forward rate calculations
- - Credit risk assessment and spread analysis
- - Duration and convexity risk metrics
- - Portfolio optimization and immunization strategies
-
-PARAMETERS:
- - yield_curve_method: Yield curve modeling method (default: 'nelson_siegel')
- - credit_spread: Credit spread assumption (default: 0.02)
- - recovery_rate: Default recovery rate (default: 0.40)
- - convexity_adjustment: Convexity adjustment factor (default: 1.0)
- - benchmark_curve: Benchmark yield curve (default: 'treasury')
-
-
-from typing import List, Dict, Optional, Tuple
-from decimal import Decimal
-from datetime import date
-import math
-from models import Bond, Portfolio, CashFlow
-from instruments import create_bond_instrument
-from yield_curves import SpotCurve
-from valuation import BondValuation, ArbitrageFreeValuation
-from utils import MathUtils, DateUtils, ValidationUtils, cache_calculation
-from config import CompoundingFrequency, ERROR_TOLERANCE
-
-
-class DurationMeasures:
- """Duration calculations for fixed income securities"""
-
- @staticmethod
- @cache_calculation
- def macaulay_duration(bond: Bond, yield_rate: Decimal,
- settlement_date: Optional[date] = None) -> Decimal:
- """Calculate Macaulay duration"""
- ValidationUtils.validate_yield(yield_rate, "Yield rate")
-
- if settlement_date is None:
- settlement_date = date.today()
-
- bond_instrument = create_bond_instrument(bond)
- cash_flows = bond_instrument.generate_cash_flows(settlement_date)
-
- if not cash_flows:
- return Decimal('0')
-
- # Calculate weighted average time to maturity
- total_pv = Decimal('0')
- weighted_time = Decimal('0')
-
- for cf in cash_flows:
- time_to_payment = DateUtils.calculate_day_count_fraction(
- settlement_date, cf.date, bond.day_count_convention
- )
-
- pv = MathUtils.present_value(cf.amount, yield_rate, time_to_payment)
- total_pv += pv
- weighted_time += time_to_payment * pv
-
- if total_pv == 0:
- return Decimal('0')
-
- return weighted_time / total_pv
-
- @staticmethod
- def modified_duration(bond: Bond, yield_rate: Decimal,
- settlement_date: Optional[date] = None) -> Decimal:
- """Calculate Modified duration"""
- mac_duration = DurationMeasures.macaulay_duration(bond, yield_rate, settlement_date)
-
- # Get compounding frequency
- frequency = bond.coupon_frequency.value
- if frequency == 0: # Continuous compounding
- return mac_duration
-
- return mac_duration / (Decimal('1') + yield_rate / Decimal(str(frequency)))
-
- @staticmethod
- def effective_duration(bond: Bond, base_curve: SpotCurve,
- yield_shift: Decimal = Decimal('0.0001')) -> Decimal:
- """Calculate Effective duration using curve shifts"""
- ValidationUtils.validate_positive(yield_shift, "Yield shift")
-
- # Calculate prices with up and down shifts
- up_curve = base_curve.shift_curve(yield_shift, "parallel")
- down_curve = base_curve.shift_curve(-yield_shift, "parallel")
-
- base_price = BondValuation.present_value_with_curve(bond, base_curve)
- up_price = BondValuation.present_value_with_curve(bond, up_curve)
- down_price = BondValuation.present_value_with_curve(bond, down_curve)
-
- # Effective duration = -(P- - P+) / (2 * P0 * Δy)
- if base_price == 0:
- return Decimal('0')
-
- return -(down_price - up_price) / (Decimal('2') * base_price * yield_shift)
-
- @staticmethod
- def money_duration(bond: Bond, yield_rate: Decimal, price: Decimal,
- settlement_date: Optional[date] = None) -> Decimal:
- """Calculate Money duration (Modified duration × Price)"""
- mod_duration = DurationMeasures.modified_duration(bond, yield_rate, settlement_date)
- return mod_duration * price
-
- @staticmethod
- def dollar_duration(bond: Bond, yield_rate: Decimal, price: Decimal,
- settlement_date: Optional[date] = None) -> Decimal:
- """Calculate Dollar duration (Money duration × 0.01)"""
- money_dur = DurationMeasures.money_duration(bond, yield_rate, price, settlement_date)
- return money_dur * Decimal('0.01')
-
- @staticmethod
- def price_value_basis_point(bond: Bond, yield_rate: Decimal,
- settlement_date: Optional[date] = None) -> Decimal:
- """Calculate Price Value of a Basis Point (PVBP)"""
- if settlement_date is None:
- settlement_date = date.today()
-
- # Calculate price at current yield and yield + 1bp
- base_price = BondValuation.present_value(bond, yield_rate, settlement_date)
- shifted_price = BondValuation.present_value(bond, yield_rate + Decimal('0.0001'), settlement_date)
-
- return base_price - shifted_price
-
-
-class ConvexityMeasures:
- """Convexity calculations for fixed income securities"""
-
- @staticmethod
- @cache_calculation
- def effective_convexity(bond: Bond, base_curve: SpotCurve,
- yield_shift: Decimal = Decimal('0.0001')) -> Decimal:
- """Calculate Effective convexity using curve shifts"""
- ValidationUtils.validate_positive(yield_shift, "Yield shift")
-
- # Calculate prices with up and down shifts
- up_curve = base_curve.shift_curve(yield_shift, "parallel")
- down_curve = base_curve.shift_curve(-yield_shift, "parallel")
-
- base_price = BondValuation.present_value_with_curve(bond, base_curve)
- up_price = BondValuation.present_value_with_curve(bond, up_curve)
- down_price = BondValuation.present_value_with_curve(bond, down_curve)
-
- # Convexity = (P+ + P- - 2*P0) / (P0 * (Δy)²)
- if base_price == 0:
- return Decimal('0')
-
- numerator = up_price + down_price - Decimal('2') * base_price
- denominator = base_price * (yield_shift ** 2)
-
- return numerator / denominator
-
- @staticmethod
- def convexity_adjustment(duration: Decimal, convexity: Decimal,
- yield_change: Decimal) -> Decimal:
- """Calculate convexity adjustment to duration-based price change"""
- return Decimal('0.5') * convexity * (yield_change ** 2)
-
- @staticmethod
- def approximate_price_change(duration: Decimal, convexity: Decimal,
- yield_change: Decimal) -> Decimal:
- """Approximate percentage price change using duration and convexity"""
- duration_effect = -duration * yield_change
- convexity_effect = ConvexityMeasures.convexity_adjustment(duration, convexity, yield_change)
-
- return duration_effect + convexity_effect
-
-
-class KeyRateDuration:
- """Key Rate Duration analysis for yield curve risk"""
-
- @staticmethod
- def calculate_key_rate_durations(bond: Bond, base_curve: SpotCurve,
- key_maturities: List[Decimal],
- yield_shift: Decimal = Decimal('0.0001')) -> Dict[Decimal, Decimal]:
- """Calculate key rate durations for specified maturities"""
- base_price = BondValuation.present_value_with_curve(bond, base_curve)
- key_durations = {}
-
- for maturity in key_maturities:
- # Create curve with shift only at this maturity
- shifted_curve = KeyRateDuration._create_key_rate_shifted_curve(
- base_curve, maturity, yield_shift
- )
-
- shifted_price = BondValuation.present_value_with_curve(bond, shifted_curve)
-
- # Key rate duration = -(ΔP/P) / Δy
- if base_price != 0:
- key_duration = -(shifted_price - base_price) / (base_price * yield_shift)
- else:
- key_duration = Decimal('0')
-
- key_durations[maturity] = key_duration
-
- return key_durations
-
- @staticmethod
- def _create_key_rate_shifted_curve(base_curve: SpotCurve, shift_maturity: Decimal,
- shift_amount: Decimal) -> SpotCurve:
- """Create curve with shift concentrated at specific maturity"""
- new_rates = []
-
- for i, maturity in enumerate(base_curve.curve.maturities):
- base_rate = base_curve.curve.rates[i]
-
- # Apply shift with triangular weighting around shift_maturity
- if abs(maturity - shift_maturity) <= Decimal('1'): # Within 1 year
- weight = Decimal('1') - abs(maturity - shift_maturity)
- shift = shift_amount * weight
- else:
- shift = Decimal('0')
-
- new_rates.append(base_rate + shift)
-
- from models import YieldCurve
- new_curve = YieldCurve(
- curve_date=base_curve.curve.curve_date,
- maturities=base_curve.curve.maturities.copy(),
- rates=new_rates,
- currency=base_curve.curve.currency,
- curve_type="spot"
- )
-
- from yield_curves import SpotCurve
- return SpotCurve(new_curve)
-
-
-class PortfolioRiskMetrics:
- """Portfolio-level risk calculations"""
-
- @staticmethod
- def portfolio_duration(portfolio: Portfolio, yields: Dict[str, Decimal],
- prices: Dict[str, Decimal]) -> Decimal:
- """Calculate portfolio duration as market-value weighted average"""
- total_market_value = Decimal('0')
- weighted_duration = Decimal('0')
-
- for bond, quantity in portfolio.holdings:
- bond_id = bond.isin
-
- if bond_id not in yields or bond_id not in prices:
- continue
-
- bond_yield = yields[bond_id]
- bond_price = prices[bond_id]
- market_value = bond_price * quantity
-
- duration = DurationMeasures.modified_duration(bond, bond_yield)
-
- total_market_value += market_value
- weighted_duration += duration * market_value
-
- if total_market_value == 0:
- return Decimal('0')
-
- return weighted_duration / total_market_value
-
- @staticmethod
- def portfolio_convexity(portfolio: Portfolio, base_curve: SpotCurve,
- prices: Dict[str, Decimal]) -> Decimal:
- """Calculate portfolio convexity as market-value weighted average"""
- total_market_value = Decimal('0')
- weighted_convexity = Decimal('0')
-
- for bond, quantity in portfolio.holdings:
- bond_id = bond.isin
-
- if bond_id not in prices:
- continue
-
- bond_price = prices[bond_id]
- market_value = bond_price * quantity
-
- convexity = ConvexityMeasures.effective_convexity(bond, base_curve)
-
- total_market_value += market_value
- weighted_convexity += convexity * market_value
-
- if total_market_value == 0:
- return Decimal('0')
-
- return weighted_convexity / total_market_value
-
- @staticmethod
- def duration_matching_error(portfolio: Portfolio, target_duration: Decimal,
- yields: Dict[str, Decimal], prices: Dict[str, Decimal]) -> Decimal:
- """Calculate duration matching error"""
- portfolio_dur = PortfolioRiskMetrics.portfolio_duration(portfolio, yields, prices)
- return portfolio_dur - target_duration
-
- @staticmethod
- def portfolio_yield(portfolio: Portfolio, yields: Dict[str, Decimal],
- prices: Dict[str, Decimal]) -> Decimal:
- """Calculate portfolio yield as market-value weighted average"""
- total_market_value = Decimal('0')
- weighted_yield = Decimal('0')
-
- for bond, quantity in portfolio.holdings:
- bond_id = bond.isin
-
- if bond_id not in yields or bond_id not in prices:
- continue
-
- bond_yield = yields[bond_id]
- bond_price = prices[bond_id]
- market_value = bond_price * quantity
-
- total_market_value += market_value
- weighted_yield += bond_yield * market_value
-
- if total_market_value == 0:
- return Decimal('0')
-
- return weighted_yield / total_market_value
-
-
-class ValueAtRisk:
- """Value at Risk calculations for fixed income portfolios"""
-
- @staticmethod
- def parametric_var(portfolio_value: Decimal, portfolio_duration: Decimal,
- yield_volatility: Decimal, confidence_level: Decimal = Decimal('0.95'),
- time_horizon: Decimal = Decimal('1')) -> Decimal:
- """Calculate parametric VaR using duration approximation"""
- ValidationUtils.validate_positive(portfolio_value, "Portfolio value")
- ValidationUtils.validate_positive(yield_volatility, "Yield volatility")
- ValidationUtils.validate_percentage(confidence_level, "Confidence level")
-
- # Standard normal quantile for confidence level
- if confidence_level == Decimal('0.95'):
- z_score = Decimal('1.645') # 95% confidence
- elif confidence_level == Decimal('0.99'):
- z_score = Decimal('2.326') # 99% confidence
- else:
- # Approximate for other confidence levels
- z_score = Decimal('1.645') # Default to 95%
-
- # VaR = Portfolio Value × Duration × Yield Volatility × Z-score × √(Time Horizon)
- time_factor = time_horizon ** Decimal('0.5')
- var = portfolio_value * portfolio_duration * yield_volatility * z_score * time_factor
-
- return var
-
- @staticmethod
- def monte_carlo_var(portfolio: Portfolio, base_curve: SpotCurve,
- yield_volatility: Decimal, simulations: int = 10000,
- confidence_level: Decimal = Decimal('0.95'),
- time_horizon: Decimal = Decimal('1')) -> Tuple[Decimal, List[Decimal]]:
- """Calculate VaR using Monte Carlo simulation"""
- import random
-
- current_value = Decimal('0')
- simulated_values = []
-
- # Calculate current portfolio value
- for bond, quantity in portfolio.holdings:
- bond_value = BondValuation.present_value_with_curve(bond, base_curve)
- current_value += bond_value * quantity
-
- # Run Monte Carlo simulations
- for _ in range(simulations):
- # Generate random yield change
- random_change = Decimal(str(random.gauss(0, float(yield_volatility * (time_horizon ** Decimal('0.5'))))))
-
- # Shift curve and revalue portfolio
- shifted_curve = base_curve.shift_curve(random_change, "parallel")
- portfolio_value = Decimal('0')
-
- for bond, quantity in portfolio.holdings:
- bond_value = BondValuation.present_value_with_curve(bond, shifted_curve)
- portfolio_value += bond_value * quantity
-
- value_change = portfolio_value - current_value
- simulated_values.append(value_change)
-
- # Calculate VaR as percentile
- simulated_values.sort()
- var_index = int((1 - confidence_level) * simulations)
- var = -simulated_values[var_index] # VaR is positive number representing loss
-
- return var, simulated_values
-
-
-class StressTestingFramework:
- """Stress testing framework for fixed income portfolios"""
-
- @staticmethod
- def parallel_shift_stress_test(portfolio: Portfolio, base_curve: SpotCurve,
- stress_scenarios: List[Decimal]) -> Dict[str, Dict]:
- """Stress test portfolio under parallel yield curve shifts"""
- base_value = Decimal('0')
-
- # Calculate base case value
- for bond, quantity in portfolio.holdings:
- bond_value = BondValuation.present_value_with_curve(bond, base_curve)
- base_value += bond_value * quantity
-
- results = {'base_case': {'value': base_value, 'change': Decimal('0'), 'change_pct': Decimal('0')}}
-
- for shift in stress_scenarios:
- stressed_curve = base_curve.shift_curve(shift, "parallel")
- stressed_value = Decimal('0')
-
- for bond, quantity in portfolio.holdings:
- bond_value = BondValuation.present_value_with_curve(bond, stressed_curve)
- stressed_value += bond_value * quantity
-
- change = stressed_value - base_value
- change_pct = (change / base_value * Decimal('100')) if base_value != 0 else Decimal('0')
-
- scenario_name = f"shift_{shift * 10000:.0f}bp"
- results[scenario_name] = {
- 'value': stressed_value,
- 'change': change,
- 'change_pct': change_pct
- }
-
- return results
-
- @staticmethod
- def yield_curve_scenario_analysis(portfolio: Portfolio, base_curve: SpotCurve,
- scenarios: Dict[str, str]) -> Dict[str, Dict]:
- """Analyze portfolio under different yield curve scenarios"""
- base_value = Decimal('0')
-
- # Calculate base case value
- for bond, quantity in portfolio.holdings:
- bond_value = BondValuation.present_value_with_curve(bond, base_curve)
- base_value += bond_value * quantity
-
- results = {'base_case': {'value': base_value, 'change': Decimal('0'), 'change_pct': Decimal('0')}}
-
- for scenario_name, scenario_type in scenarios.items():
- if scenario_type == "steepening":
- stressed_curve = base_curve.shift_curve(Decimal('0.01'), "steepening")
- elif scenario_type == "flattening":
- stressed_curve = base_curve.shift_curve(Decimal('0.01'), "flattening")
- elif scenario_type == "bear_steepening":
- # Rates up more at long end
- stressed_curve = base_curve.shift_curve(Decimal('0.005'), "parallel")
- stressed_curve = stressed_curve.shift_curve(Decimal('0.005'), "steepening")
- elif scenario_type == "bull_flattening":
- # Rates down more at long end
- stressed_curve = base_curve.shift_curve(Decimal('-0.005'), "parallel")
- stressed_curve = stressed_curve.shift_curve(Decimal('0.005'), "flattening")
- else:
- continue
-
- stressed_value = Decimal('0')
- for bond, quantity in portfolio.holdings:
- bond_value = BondValuation.present_value_with_curve(bond, stressed_curve)
- stressed_value += bond_value * quantity
-
- change = stressed_value - base_value
- change_pct = (change / base_value * Decimal('100')) if base_value != 0 else Decimal('0')
-
- results[scenario_name] = {
- 'value': stressed_value,
- 'change': change,
- 'change_pct': change_pct
- }
-
- return results
-
-
-class HedgingAnalytics:
- """Hedging calculations and analytics"""
-
- @staticmethod
- def duration_hedge_ratio(target_bond: Bond, hedge_bond: Bond,
- target_duration: Decimal, hedge_duration: Decimal) -> Decimal:
- """Calculate hedge ratio for duration hedging"""
- if hedge_duration == 0:
- return Decimal('0')
-
- return target_duration / hedge_duration
-
- @staticmethod
- def optimal_hedge_portfolio(target_portfolio: Portfolio, hedge_instruments: List[Bond],
- base_curve: SpotCurve) -> Dict[str, Decimal]:
- """Calculate optimal hedge portfolio weights (simplified)"""
- # Calculate target portfolio duration
- target_duration = Decimal('0')
- target_value = Decimal('0')
-
- for bond, quantity in target_portfolio.holdings:
- bond_value = BondValuation.present_value_with_curve(bond, base_curve)
- bond_duration = DurationMeasures.effective_duration(bond, base_curve)
-
- position_value = bond_value * quantity
- target_value += position_value
- target_duration += bond_duration * position_value
-
- if target_value != 0:
- target_duration = target_duration / target_value
-
- # Simple two-instrument hedge (e.g., short and long duration instruments)
- if len(hedge_instruments) >= 2:
- short_bond = hedge_instruments[0]
- long_bond = hedge_instruments[1]
-
- short_duration = DurationMeasures.effective_duration(short_bond, base_curve)
- long_duration = DurationMeasures.effective_duration(long_bond, base_curve)
-
- # Solve for weights to achieve zero portfolio duration
- # w1 * d1 + w2 * d2 = -target_duration (to offset)
- # w1 + w2 = 1 (budget constraint, simplified)
-
- if long_duration != short_duration:
- w2 = (-target_duration - short_duration) / (long_duration - short_duration)
- w1 = Decimal('1') - w2
-
- return {
- short_bond.isin: w1,
- long_bond.isin: w2
- }
-
- return {}
-
-
-# Utility functions for risk reporting
-def generate_risk_report(portfolio: Portfolio, base_curve: SpotCurve,
- yields: Dict[str, Decimal], prices: Dict[str, Decimal]) -> Dict:
- """Generate comprehensive risk report for portfolio"""
-
- # Basic metrics
- portfolio_dur = PortfolioRiskMetrics.portfolio_duration(portfolio, yields, prices)
- portfolio_conv = PortfolioRiskMetrics.portfolio_convexity(portfolio, base_curve, prices)
- portfolio_yld = PortfolioRiskMetrics.portfolio_yield(portfolio, yields, prices)
-
- # Calculate total portfolio value
- total_value = Decimal('0')
- for bond, quantity in portfolio.holdings:
- if bond.isin in prices:
- total_value += prices[bond.isin] * quantity
-
- # VaR calculation
- yield_vol = Decimal('0.01') # Assume 1% daily yield volatility
- var_95 = ValueAtRisk.parametric_var(total_value, portfolio_dur, yield_vol, Decimal('0.95'))
- var_99 = ValueAtRisk.parametric_var(total_value, portfolio_dur, yield_vol, Decimal('0.99'))
-
- # Stress tests
- stress_scenarios = [Decimal('-0.02'), Decimal('-0.01'), Decimal('0.01'), Decimal('0.02')] # ±100bp, ±200bp
- stress_results = StressTestingFramework.parallel_shift_stress_test(portfolio, base_curve, stress_scenarios)
-
- return {
- 'portfolio_metrics': {
- 'duration': portfolio_dur,
- 'convexity': portfolio_conv,
- 'yield': portfolio_yld,
- 'total_value': total_value
- },
- 'risk_metrics': {
- 'var_95': var_95,
- 'var_99': var_99
- },
- 'stress_test_results': stress_results
- }
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/term_structure.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/term_structure.py
deleted file mode 100644
index 8a61b1693..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/term_structure.py
+++ /dev/null
@@ -1,660 +0,0 @@
-
-Fixed Income Term Structure Module
-=================================
-
-Yield curve and term structure modeling
-
-===== DATA SOURCES REQUIRED =====
-INPUT:
- - Bond prospectuses and issue documentation
- - Market price data and yield curve information
- - Credit ratings and default recovery rates
- - Interest rate benchmarks and swap curves
- - Macroeconomic data affecting fixed income markets
-
-OUTPUT:
- - Bond valuation models and price calculations
- - Yield curve analysis and forward rate calculations
- - Credit risk assessment and spread analysis
- - Duration and convexity risk metrics
- - Portfolio optimization and immunization strategies
-
-PARAMETERS:
- - yield_curve_method: Yield curve modeling method (default: 'nelson_siegel')
- - credit_spread: Credit spread assumption (default: 0.02)
- - recovery_rate: Default recovery rate (default: 0.40)
- - convexity_adjustment: Convexity adjustment factor (default: 1.0)
- - benchmark_curve: Benchmark yield curve (default: 'treasury')
-
-
-from typing import List, Dict, Optional, Tuple, Callable
-from decimal import Decimal
-from datetime import date
-import math
-from models import YieldCurve
-from yield_curves import SpotCurve, ForwardCurve
-from utils import MathUtils, DateUtils, ValidationUtils, cache_calculation
-from config import Currency, ERROR_TOLERANCE
-
-class TermStructureTheories:
- """Implementation of classical term structure theories"""
-
- @staticmethod
- def pure_expectations_theory(forward_rates: List[Decimal],
- maturities: List[Decimal]) -> Dict[str, Decimal]:
- """Analyze yield curve under Pure Expectations Theory"""
- if len(forward_rates) != len(maturities):
- raise ValueError("Forward rates and maturities must have same length")
-
- # Under PET: Long-term rates = geometric average of expected short rates
- # No liquidity premium, risk premium = 0
-
- results = {}
-
- for i, maturity in enumerate(maturities):
- if i == 0:
- spot_rate = forward_rates[i]
- else:
- # Geometric average of forward rates
- product = Decimal('1')
- for j in range(i + 1):
- product *= (Decimal('1') + forward_rates[j])
-
- spot_rate = product ** (Decimal('1') / Decimal(str(i + 1))) - Decimal('1')
-
- results[f"spot_rate_{maturity}Y"] = spot_rate
- results[f"forward_rate_{maturity}Y"] = forward_rates[i]
-
- # Calculate implied risk premiums (should be zero under PET)
- results['liquidity_premiums'] = [Decimal('0')] * len(maturities)
- results['theory'] = 'Pure Expectations Theory'
- results['risk_premium_assumption'] = 'Zero risk premiums'
-
- return results
-
- @staticmethod
- def liquidity_preference_theory(forward_rates: List[Decimal],
- maturities: List[Decimal],
- liquidity_premiums: List[Decimal]) -> Dict[str, Decimal]:
- """Analyze yield curve under Liquidity Preference Theory"""
- if len(forward_rates) != len(maturities) or len(liquidity_premiums) != len(maturities):
- raise ValueError("All input lists must have same length")
-
- # Under LPT: Forward rates = Expected future rates + Liquidity premium
- # Liquidity premiums increase with maturity
-
- results = {}
-
- # Adjust forward rates for liquidity premiums
- expected_rates = []
- for i in range(len(forward_rates)):
- expected_rate = forward_rates[i] - liquidity_premiums[i]
- expected_rates.append(expected_rate)
-
- # Calculate spot rates incorporating liquidity premiums
- for i, maturity in enumerate(maturities):
- if i == 0:
- spot_rate = forward_rates[i]
- else:
- # Geometric average including liquidity premiums
- product = Decimal('1')
- for j in range(i + 1):
- product *= (Decimal('1') + forward_rates[j])
-
- spot_rate = product ** (Decimal('1') / Decimal(str(i + 1))) - Decimal('1')
-
- results[f"spot_rate_{maturity}Y"] = spot_rate
- results[f"expected_rate_{maturity}Y"] = expected_rates[i]
- results[f"liquidity_premium_{maturity}Y"] = liquidity_premiums[i]
-
- results['theory'] = 'Liquidity Preference Theory'
- results['risk_premium_assumption'] = 'Positive, increasing liquidity premiums'
-
- return results
-
- @staticmethod
- def market_segmentation_theory(supply_demand_factors: Dict[Decimal, Dict[str, Decimal]]) -> Dict[str, Decimal]:
- """Analyze yield curve under Market Segmentation Theory"""
- # Under MST: Rates determined by supply/demand in each maturity segment
- # Limited arbitrage between segments
-
- results = {}
- results['theory'] = 'Market Segmentation Theory'
-
- for maturity, factors in supply_demand_factors.items():
- supply = factors.get('supply', Decimal('1'))
- demand = factors.get('demand', Decimal('1'))
- base_rate = factors.get('base_rate', Decimal('0.03'))
-
- # Simple supply/demand impact on rates
- # Higher supply relative to demand → higher rates
- supply_demand_ratio = supply / demand if demand > 0 else Decimal('1')
-
- # Rate adjustment based on supply/demand imbalance
- rate_adjustment = (supply_demand_ratio - Decimal('1')) * Decimal('0.01') # 1% per unit imbalance
- adjusted_rate = base_rate + rate_adjustment
-
- results[f"rate_{maturity}Y"] = adjusted_rate
- results[f"supply_demand_ratio_{maturity}Y"] = supply_demand_ratio
- results[f"rate_adjustment_{maturity}Y"] = rate_adjustment
-
- results['arbitrage_assumption'] = 'Limited arbitrage between maturity segments'
-
- return results
-
- @staticmethod
- def preferred_habitat_theory(forward_rates: List[Decimal],
- maturities: List[Decimal],
- habitat_premiums: List[Decimal]) -> Dict[str, Decimal]:
- """Analyze yield curve under Preferred Habitat Theory"""
- if len(forward_rates) != len(maturities) or len(habitat_premiums) != len(maturities):
- raise ValueError("All input lists must have same length")
-
- # Under PHT: Combination of expectations and preferred habitats
- # Risk premiums can be positive or negative based on habitat preferences
-
- results = {}
-
- # Expected rates = Forward rates - Habitat premiums
- expected_rates = []
- for i in range(len(forward_rates)):
- expected_rate = forward_rates[i] - habitat_premiums[i]
- expected_rates.append(expected_rate)
-
- # Calculate spot rates
- for i, maturity in enumerate(maturities):
- if i == 0:
- spot_rate = forward_rates[i]
- else:
- product = Decimal('1')
- for j in range(i + 1):
- product *= (Decimal('1') + forward_rates[j])
-
- spot_rate = product ** (Decimal('1') / Decimal(str(i + 1))) - Decimal('1')
-
- results[f"spot_rate_{maturity}Y"] = spot_rate
- results[f"expected_rate_{maturity}Y"] = expected_rates[i]
- results[f"habitat_premium_{maturity}Y"] = habitat_premiums[i]
-
- results['theory'] = 'Preferred Habitat Theory'
- results['risk_premium_assumption'] = 'Risk premiums can be positive or negative'
-
- return results
-
-class YieldCurveFactors:
- """Yield curve factor analysis and decomposition"""
-
- @staticmethod
- def level_slope_curvature_factors(spot_curve: SpotCurve,
- key_maturities: List[Decimal] = None) -> Dict[str, Decimal]:
- """Decompose yield curve into level, slope, and curvature factors"""
- if key_maturities is None:
- key_maturities = [Decimal('2'), Decimal('5'), Decimal('10')]
-
- if len(key_maturities) < 3:
- raise ValueError("Need at least 3 maturities for LSC decomposition")
-
- # Get rates for key maturities
- rates = [spot_curve.get_rate(maturity) for maturity in key_maturities]
-
- # Level: Average of all rates
- level = sum(rates) / Decimal(str(len(rates)))
-
- # Slope: Long rate - Short rate
- slope = rates[-1] - rates[0]
-
- # Curvature: 2 * Middle - Short - Long (butterfly)
- if len(rates) >= 3:
- curvature = Decimal('2') * rates[1] - rates[0] - rates[-1]
- else:
- curvature = Decimal('0')
-
- # Calculate factor loadings for all curve points
- factor_loadings = YieldCurveFactors._calculate_factor_loadings(spot_curve, key_maturities)
-
- return {
- 'level_factor': level,
- 'slope_factor': slope,
- 'curvature_factor': curvature,
- 'factor_loadings': factor_loadings,
- 'explained_variance': {
- 'level': Decimal('0.85'), # Typical values
- 'slope': Decimal('0.12'),
- 'curvature': Decimal('0.03')
- }
- }
-
- @staticmethod
- def _calculate_factor_loadings(spot_curve: SpotCurve,
- key_maturities: List[Decimal]) -> Dict[str, List[Decimal]]:
- """Calculate factor loadings for level, slope, curvature"""
- maturities = spot_curve.curve.maturities
- n = len(maturities)
-
- # Level loadings: Equal weight (1/√n for normalization)
- level_loadings = [Decimal('1') / (Decimal(str(n)) ** Decimal('0.5'))] * n
-
- # Slope loadings: Linear from -1 to +1
- slope_loadings = []
- for i, maturity in enumerate(maturities):
- # Normalize to [-1, +1] range
- loading = Decimal('-1') + Decimal('2') * Decimal(str(i)) / Decimal(str(n - 1))
- slope_loadings.append(loading)
-
- # Curvature loadings: Quadratic shape
- curvature_loadings = []
- for i, maturity in enumerate(maturities):
- # Quadratic: high at ends, low in middle
- x = Decimal(str(i)) / Decimal(str(n - 1)) # Normalize to [0, 1]
- loading = Decimal('2') * x * (Decimal('1') - x) # Parabolic shape
- curvature_loadings.append(loading)
-
- return {
- 'level': level_loadings,
- 'slope': slope_loadings,
- 'curvature': curvature_loadings
- }
-
- @staticmethod
- def principal_component_analysis(historical_curves: List[SpotCurve]) -> Dict[str, any]:
- """Simplified PCA analysis of yield curve movements"""
- if len(historical_curves) < 2:
- raise ValueError("Need at least 2 historical curves for PCA")
-
- # Get common maturities across all curves
- common_maturities = historical_curves[0].curve.maturities
-
- # Build rate matrix
- rate_matrix = []
- for curve in historical_curves:
- rates = [curve.get_rate(maturity) for maturity in common_maturities]
- rate_matrix.append(rates)
-
- # Calculate mean rates
- n_curves = len(rate_matrix)
- n_maturities = len(common_maturities)
-
- mean_rates = []
- for j in range(n_maturities):
- mean_rate = sum(rate_matrix[i][j] for i in range(n_curves)) / Decimal(str(n_curves))
- mean_rates.append(mean_rate)
-
- # Calculate rate changes (demeaned)
- rate_changes = []
- for i in range(n_curves):
- changes = [rate_matrix[i][j] - mean_rates[j] for j in range(n_maturities)]
- rate_changes.append(changes)
-
- # Simplified factor extraction (first 3 components)
- # In practice, would use proper eigenvalue decomposition
-
- # First component: level (average change)
- pc1_loadings = [Decimal('1') / (Decimal(str(n_maturities)) ** Decimal('0.5'))] * n_maturities
-
- # Second component: slope (linear)
- pc2_loadings = []
- for j in range(n_maturities):
- loading = Decimal('-1') + Decimal('2') * Decimal(str(j)) / Decimal(str(n_maturities - 1))
- pc2_loadings.append(loading)
-
- # Third component: curvature (quadratic)
- pc3_loadings = []
- for j in range(n_maturities):
- x = Decimal(str(j)) / Decimal(str(n_maturities - 1))
- loading = Decimal('2') * x * (Decimal('1') - x)
- pc3_loadings.append(loading)
-
- return {
- 'principal_components': {
- 'PC1_loadings': pc1_loadings,
- 'PC2_loadings': pc2_loadings,
- 'PC3_loadings': pc3_loadings
- },
- 'explained_variance': [Decimal('0.85'), Decimal('0.12'), Decimal('0.03')],
- 'interpretation': ['Level', 'Slope', 'Curvature'],
- 'mean_rates': mean_rates,
- 'maturities': common_maturities
- }
-
-class VolatilityStructure:
- """Term structure of volatility analysis"""
-
- @staticmethod
- def yield_volatility_structure(historical_yields: Dict[Decimal, List[Decimal]],
- window_size: int = 252) -> Dict[Decimal, Dict[str, Decimal]]:
- """Calculate volatility structure across maturities"""
- volatility_structure = {}
-
- for maturity, yield_series in historical_yields.items():
- if len(yield_series) < window_size:
- continue
-
- # Calculate returns
- returns = []
- for i in range(1, len(yield_series)):
- return_val = yield_series[i] - yield_series[i-1]
- returns.append(return_val)
-
- # Rolling volatility
- volatilities = VolatilityStructure._calculate_rolling_volatility(returns, window_size)
-
- # Summary statistics
- if volatilities:
- avg_volatility = sum(volatilities) / Decimal(str(len(volatilities)))
- max_volatility = max(volatilities)
- min_volatility = min(volatilities)
-
- volatility_structure[maturity] = {
- 'average_volatility': avg_volatility,
- 'maximum_volatility': max_volatility,
- 'minimum_volatility': min_volatility,
- 'current_volatility': volatilities[-1] if volatilities else Decimal('0')
- }
-
- return volatility_structure
-
- @staticmethod
- def _calculate_rolling_volatility(returns: List[Decimal], window: int) -> List[Decimal]:
- """Calculate rolling volatility"""
- volatilities = []
-
- for i in range(window, len(returns) + 1):
- window_returns = returns[i-window:i]
-
- # Calculate mean
- mean_return = sum(window_returns) / Decimal(str(len(window_returns)))
-
- # Calculate variance
- variance = sum((r - mean_return) ** 2 for r in window_returns) / Decimal(str(len(window_returns) - 1))
-
- # Annualized volatility (assuming daily data)
- volatility = (variance ** Decimal('0.5')) * (Decimal('252') ** Decimal('0.5'))
- volatilities.append(volatility)
-
- return volatilities
-
- @staticmethod
- def volatility_smile_analysis(option_data: Dict[Decimal, Decimal]) -> Dict[str, Decimal]:
- """Analyze volatility smile/skew patterns"""
- # option_data: {strike: implied_volatility}
-
- if len(option_data) < 3:
- return {'error': 'Insufficient data for smile analysis'}
-
- strikes = sorted(option_data.keys())
- volatilities = [option_data[strike] for strike in strikes]
-
- # Find ATM volatility (middle strike)
- atm_index = len(strikes) // 2
- atm_vol = volatilities[atm_index]
-
- # Calculate skew metrics
- if len(strikes) >= 3:
- # 25-delta skew (approximated as 25% and 75% percentile strikes)
- low_strike_idx = len(strikes) // 4
- high_strike_idx = 3 * len(strikes) // 4
-
- skew_25d = volatilities[low_strike_idx] - volatilities[high_strike_idx]
- else:
- skew_25d = Decimal('0')
-
- # Butterfly (wings vs body)
- if len(strikes) >= 3:
- butterfly = (volatilities[0] + volatilities[-1]) / Decimal('2') - atm_vol
- else:
- butterfly = Decimal('0')
-
- return {
- 'atm_volatility': atm_vol,
- 'volatility_skew_25d': skew_25d,
- 'volatility_butterfly': butterfly,
- 'min_volatility': min(volatilities),
- 'max_volatility': max(volatilities),
- 'volatility_range': max(volatilities) - min(volatilities)
- }
-
- @staticmethod
- def term_structure_volatility_models(forward_rates: List[Decimal],
- volatilities: List[Decimal],
- model_type: str = 'ho_lee') -> Dict[str, any]:
- """Implement term structure volatility models"""
- if len(forward_rates) != len(volatilities):
- raise ValueError("Forward rates and volatilities must have same length")
-
- if model_type == 'ho_lee':
- return VolatilityStructure._ho_lee_model(forward_rates, volatilities)
- elif model_type == 'hull_white':
- return VolatilityStructure._hull_white_model(forward_rates, volatilities)
- elif model_type == 'black_karasinski':
- return VolatilityStructure._black_karasinski_model(forward_rates, volatilities)
- else:
- raise ValueError(f"Unknown model type: {model_type}")
-
- @staticmethod
- def _ho_lee_model(forward_rates: List[Decimal], volatilities: List[Decimal]) -> Dict[str, any]:
- """Ho-Lee model: dr = θ(t)dt + σdW"""
- # Constant volatility, drift adjusts to fit term structure
-
- avg_volatility = sum(volatilities) / Decimal(str(len(volatilities)))
-
- # Drift function to fit forward curve
- drift_function = []
- for i, rate in enumerate(forward_rates):
- if i == 0:
- drift = rate
- else:
- # Simplified drift calculation
- drift = forward_rates[i] - forward_rates[i-1]
- drift_function.append(drift)
-
- return {
- 'model': 'Ho-Lee',
- 'constant_volatility': avg_volatility,
- 'drift_function': drift_function,
- 'mean_reversion': Decimal('0'), # No mean reversion in Ho-Lee
- 'characteristics': 'Normal rates, constant volatility'
- }
-
- @staticmethod
- def _hull_white_model(forward_rates: List[Decimal], volatilities: List[Decimal]) -> Dict[str, any]:
- """Hull-White model: dr = [θ(t) - ar]dt + σdW"""
- # Mean-reverting with time-dependent drift
-
- avg_volatility = sum(volatilities) / Decimal(str(len(volatilities)))
-
- # Estimate mean reversion parameter (simplified)
- # In practice, would use maximum likelihood estimation
- mean_reversion = Decimal('0.1') # Typical value
-
- # Long-term mean (average of forward rates)
- long_term_mean = sum(forward_rates) / Decimal(str(len(forward_rates)))
-
- return {
- 'model': 'Hull-White',
- 'volatility': avg_volatility,
- 'mean_reversion_speed': mean_reversion,
- 'long_term_mean': long_term_mean,
- 'characteristics': 'Normal rates, mean-reverting'
- }
-
- @staticmethod
- def _black_karasinski_model(forward_rates: List[Decimal], volatilities: List[Decimal]) -> Dict[str, any]:
- """Black-Karasinski model: d(ln r) = [θ(t) - a ln r]dt + σdW"""
- # Log-normal rates, mean-reverting
-
- avg_volatility = sum(volatilities) / Decimal(str(len(volatilities)))
-
- # Transform rates to log space
- log_rates = [Decimal(str(math.log(float(rate)))) for rate in forward_rates if rate > 0]
-
- if log_rates:
- avg_log_rate = sum(log_rates) / Decimal(str(len(log_rates)))
- mean_reversion = Decimal('0.15') # Typical value for log-normal model
- else:
- avg_log_rate = Decimal('0')
- mean_reversion = Decimal('0')
-
- return {
- 'model': 'Black-Karasinski',
- 'volatility': avg_volatility,
- 'mean_reversion_speed': mean_reversion,
- 'mean_log_rate': avg_log_rate,
- 'characteristics': 'Log-normal rates, mean-reverting'
- }
-
-class RidingTheYieldCurve:
- """Yield curve riding strategies and analysis"""
-
- @staticmethod
- def rolling_yield_analysis(bond_maturity: Decimal, holding_period: Decimal,
- spot_curve: SpotCurve) -> Dict[str, Decimal]:
- """Analyze rolling yield for bond investment"""
- ValidationUtils.validate_positive(bond_maturity, "Bond maturity")
- ValidationUtils.validate_positive(holding_period, "Holding period")
-
- if holding_period >= bond_maturity:
- raise ValueError("Holding period must be less than bond maturity")
-
- # Current yield
- current_yield = spot_curve.get_rate(bond_maturity)
-
- # Future maturity after holding period
- future_maturity = bond_maturity - holding_period
-
- # Expected future yield (rolling down the curve)
- if future_maturity > 0:
- future_yield = spot_curve.get_rate(future_maturity)
- else:
- future_yield = Decimal('0') # Bond matures
-
- # Rolling yield calculation
- # Assumes bond price moves along the yield curve
-
- # Current bond price (assume par)
- current_price = Decimal('100')
-
- # Future bond price if yield curve unchanged
- if future_maturity > 0:
- # Simplified price calculation
- future_price = current_price * (Decimal('1') + current_yield) / (Decimal('1') + future_yield)
- else:
- future_price = Decimal('100') # Matures at par
-
- # Total return components
- coupon_income = current_yield * holding_period * current_price
- capital_gain = future_price - current_price
- total_return = coupon_income + capital_gain
-
- # Annualized rolling yield
- if holding_period > 0:
- rolling_yield = total_return / (current_price * holding_period)
- else:
- rolling_yield = Decimal('0')
-
- return {
- 'current_yield': current_yield,
- 'future_yield': future_yield,
- 'yield_change': future_yield - current_yield,
- 'current_price': current_price,
- 'future_price': future_price,
- 'capital_gain': capital_gain,
- 'coupon_income': coupon_income,
- 'total_return': total_return,
- 'rolling_yield': rolling_yield,
- 'excess_return': rolling_yield - current_yield
- }
-
- @staticmethod
- def optimal_maturity_selection(target_holding_period: Decimal,
- spot_curve: SpotCurve,
- maturity_range: Tuple[Decimal, Decimal] = (Decimal('1'), Decimal('30'))) -> Dict[str, Decimal]:
- """Find optimal bond maturity for yield curve riding"""
- ValidationUtils.validate_positive(target_holding_period, "Target holding period")
-
- min_maturity, max_maturity = maturity_range
-
- # Test different maturities
- test_maturities = []
- current_mat = min_maturity
- while current_mat <= max_maturity:
- if current_mat > target_holding_period: # Must be longer than holding period
- test_maturities.append(current_mat)
- current_mat += Decimal('0.5') # 6-month increments
-
- best_maturity = None
- best_rolling_yield = Decimal('-999')
- results = {}
-
- for maturity in test_maturities:
- try:
- analysis = RidingTheYieldCurve.rolling_yield_analysis(
- maturity, target_holding_period, spot_curve
- )
-
- rolling_yield = analysis['rolling_yield']
- results[f"maturity_{maturity}Y"] = {
- 'rolling_yield': rolling_yield,
- 'excess_return': analysis['excess_return'],
- 'yield_change': analysis['yield_change']
- }
-
- if rolling_yield > best_rolling_yield:
- best_rolling_yield = rolling_yield
- best_maturity = maturity
-
- except Exception:
- continue
-
- return {
- 'optimal_maturity': best_maturity,
- 'optimal_rolling_yield': best_rolling_yield,
- 'target_holding_period': target_holding_period,
- 'maturity_analysis': results
- }
-
-# Utility functions for term structure analysis
-def compare_term_structure_theories(spot_curve: SpotCurve,
- forward_curve: ForwardCurve) -> Dict[str, Dict]:
- """Compare different term structure theories"""
-
- maturities = [Decimal('1'), Decimal('2'), Decimal('5'), Decimal('10')]
- forward_rates = [forward_curve.get_forward_rate(Decimal('0'), mat) for mat in maturities]
-
- # Generate example premiums for different theories
- liquidity_premiums = [Decimal('0.001') * mat for mat in maturities] # Increasing with maturity
- habitat_premiums = [Decimal('0.0005') * (Decimal('1') if i % 2 == 0 else Decimal('-1'))
- for i, mat in enumerate(maturities)] # Alternating signs
-
- theories = {
- 'pure_expectations': TermStructureTheories.pure_expectations_theory(forward_rates, maturities),
- 'liquidity_preference': TermStructureTheories.liquidity_preference_theory(forward_rates, maturities, liquidity_premiums),
- 'preferred_habitat': TermStructureTheories.preferred_habitat_theory(forward_rates, maturities, habitat_premiums)
- }
-
- return theories
-
-def yield_curve_scenario_analysis(base_curve: SpotCurve,
- scenarios: Dict[str, Dict[str, Decimal]]) -> Dict[str, Dict]:
- """Analyze yield curve under different scenarios"""
-
- results = {}
-
- # Base case analysis
- base_factors = YieldCurveFactors.level_slope_curvature_factors(base_curve)
- results['base_case'] = base_factors
-
- # Scenario analysis
- for scenario_name, shifts in scenarios.items():
- shift_type = shifts.get('type', 'parallel')
- shift_amount = shifts.get('amount', Decimal('0.01'))
-
- shifted_curve = base_curve.shift_curve(shift_amount, shift_type)
- scenario_factors = YieldCurveFactors.level_slope_curvature_factors(shifted_curve)
-
- results[scenario_name] = {
- 'factors': scenario_factors,
- 'shift_type': shift_type,
- 'shift_amount': shift_amount
- }
-
- return results
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/utils.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/utils.py
deleted file mode 100644
index 53e4782c6..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/utils.py
+++ /dev/null
@@ -1,625 +0,0 @@
-
-Fixed Income Utils Module
-=================================
-
-Fixed income utility functions
-
-===== DATA SOURCES REQUIRED =====
-INPUT:
- - Bond prospectuses and issue documentation
- - Market price data and yield curve information
- - Credit ratings and default recovery rates
- - Interest rate benchmarks and swap curves
- - Macroeconomic data affecting fixed income markets
-
-OUTPUT:
- - Bond valuation models and price calculations
- - Yield curve analysis and forward rate calculations
- - Credit risk assessment and spread analysis
- - Duration and convexity risk metrics
- - Portfolio optimization and immunization strategies
-
-PARAMETERS:
- - yield_curve_method: Yield curve modeling method (default: 'nelson_siegel')
- - credit_spread: Credit spread assumption (default: 0.02)
- - recovery_rate: Default recovery rate (default: 0.40)
- - convexity_adjustment: Convexity adjustment factor (default: 1.0)
- - benchmark_curve: Benchmark yield curve (default: 'treasury')
-
-
-import math
-from typing import Callable, Optional, List, Tuple, Union
-from decimal import Decimal, getcontext
-from datetime import date, datetime, timedelta
-from config import (
- DayCountConvention, CompoundingFrequency, BusinessDayConvention,
- PRECISION_CONFIG, ERROR_TOLERANCE, ValidationError
-)
-
-# Set high precision for calculations
-getcontext().prec = 28
-
-
-class MathUtils:
- """Mathematical utility functions for fixed income calculations"""
-
- @staticmethod
- def newton_raphson(func: Callable[[Decimal], Decimal],
- derivative: Callable[[Decimal], Decimal],
- initial_guess: Decimal,
- tolerance: Decimal = ERROR_TOLERANCE['medium'],
- max_iterations: int = 100) -> Decimal:
- """Newton-Raphson method for root finding"""
- x = initial_guess
-
- for i in range(max_iterations):
- fx = func(x)
-
- if abs(fx) < tolerance:
- return x
-
- dfx = derivative(x)
- if abs(dfx) < tolerance:
- raise ValueError("Derivative too small, convergence failed")
-
- x_new = x - fx / dfx
-
- if abs(x_new - x) < tolerance:
- return x_new
-
- x = x_new
-
- raise ValueError(f"Newton-Raphson failed to converge after {max_iterations} iterations")
-
- @staticmethod
- def bisection_method(func: Callable[[Decimal], Decimal],
- lower_bound: Decimal,
- upper_bound: Decimal,
- tolerance: Decimal = ERROR_TOLERANCE['medium'],
- max_iterations: int = 100) -> Decimal:
- """Bisection method for root finding"""
- if func(lower_bound) * func(upper_bound) > 0:
- raise ValueError("Function must have opposite signs at bounds")
-
- for i in range(max_iterations):
- midpoint = (lower_bound + upper_bound) / Decimal('2')
- f_mid = func(midpoint)
-
- if abs(f_mid) < tolerance or (upper_bound - lower_bound) / Decimal('2') < tolerance:
- return midpoint
-
- if func(lower_bound) * f_mid < 0:
- upper_bound = midpoint
- else:
- lower_bound = midpoint
-
- raise ValueError(f"Bisection method failed to converge after {max_iterations} iterations")
-
- @staticmethod
- def brent_method(func: Callable[[Decimal], Decimal],
- lower_bound: Decimal,
- upper_bound: Decimal,
- tolerance: Decimal = ERROR_TOLERANCE['medium'],
- max_iterations: int = 100) -> Decimal:
- """Brent's method for root finding (combines bisection and secant methods)"""
- a, b = lower_bound, upper_bound
- fa, fb = func(a), func(b)
-
- if fa * fb > 0:
- raise ValueError("Function must have opposite signs at bounds")
-
- if abs(fa) < abs(fb):
- a, b = b, a
- fa, fb = fb, fa
-
- c = a
- fc = fa
- mflag = True
-
- for i in range(max_iterations):
- if abs(fb) < tolerance:
- return b
-
- if fa != fc and fb != fc:
- # Inverse quadratic interpolation
- s = (a * fb * fc) / ((fa - fb) * (fa - fc)) + \
- (b * fa * fc) / ((fb - fa) * (fb - fc)) + \
- (c * fa * fb) / ((fc - fa) * (fc - fb))
- else:
- # Secant method
- s = b - fb * (b - a) / (fb - fa)
-
- # Check conditions for bisection
- condition1 = not ((Decimal('3') * a + b) / Decimal('4') <= s <= b)
- condition2 = mflag and abs(s - b) >= abs(b - c) / Decimal('2')
- condition3 = not mflag and abs(s - b) >= abs(c - d) / Decimal('2')
- condition4 = mflag and abs(b - c) < tolerance
- condition5 = not mflag and abs(c - d) < tolerance
-
- if condition1 or condition2 or condition3 or condition4 or condition5:
- s = (a + b) / Decimal('2')
- mflag = True
- else:
- mflag = False
-
- fs = func(s)
- d = c
- c = b
- fc = fb
-
- if fa * fs < 0:
- b = s
- fb = fs
- else:
- a = s
- fa = fs
-
- if abs(fa) < abs(fb):
- a, b = b, a
- fa, fb = fb, fa
-
- raise ValueError(f"Brent's method failed to converge after {max_iterations} iterations")
-
- @staticmethod
- def present_value(cash_flow: Decimal, discount_rate: Decimal, time_period: Decimal) -> Decimal:
- """Calculate present value of a cash flow"""
- if discount_rate < -1:
- raise ValueError("Discount rate cannot be less than -100%")
-
- return cash_flow / ((Decimal('1') + discount_rate) ** time_period)
-
- @staticmethod
- def future_value(present_value: Decimal, rate: Decimal, time_period: Decimal) -> Decimal:
- """Calculate future value"""
- return present_value * ((Decimal('1') + rate) ** time_period)
-
- @staticmethod
- def compound_frequency_conversion(rate: Decimal,
- from_freq: CompoundingFrequency,
- to_freq: CompoundingFrequency) -> Decimal:
- """Convert rate between different compounding frequencies"""
- if from_freq == to_freq:
- return rate
-
- # Convert to continuous compounding first
- if from_freq == CompoundingFrequency.CONTINUOUS:
- continuous_rate = rate
- else:
- m = Decimal(str(from_freq.value))
- continuous_rate = m * Decimal(str(math.log(float(1 + rate / m))))
-
- # Convert from continuous to target frequency
- if to_freq == CompoundingFrequency.CONTINUOUS:
- return continuous_rate
- else:
- n = Decimal(str(to_freq.value))
- return n * (Decimal(str(math.exp(float(continuous_rate / n)))) - Decimal('1'))
-
- @staticmethod
- def linear_interpolation(x: Decimal, x1: Decimal, y1: Decimal, x2: Decimal, y2: Decimal) -> Decimal:
- """Linear interpolation between two points"""
- if x1 == x2:
- return y1
-
- return y1 + (y2 - y1) * (x - x1) / (x2 - x1)
-
- @staticmethod
- def cubic_spline_interpolation(x: Decimal, points: List[Tuple[Decimal, Decimal]]) -> Decimal:
- """Simplified cubic spline interpolation (linear for now)"""
- # Find the two points to interpolate between
- points = sorted(points, key=lambda p: p[0])
-
- if x <= points[0][0]:
- return points[0][1]
- if x >= points[-1][0]:
- return points[-1][1]
-
- for i in range(len(points) - 1):
- if points[i][0] <= x <= points[i + 1][0]:
- return MathUtils.linear_interpolation(
- x, points[i][0], points[i][1], points[i + 1][0], points[i + 1][1]
- )
-
- return points[0][1] # Fallback
-
-
-class DateUtils:
- """Date utility functions for fixed income calculations"""
-
- @staticmethod
- def add_business_days(start_date: date, business_days: int,
- convention: BusinessDayConvention = BusinessDayConvention.FOLLOWING) -> date:
- """Add business days to a date"""
- current_date = start_date
- days_added = 0
-
- while days_added < business_days:
- current_date += timedelta(days=1)
- if DateUtils.is_business_day(current_date):
- days_added += 1
-
- return DateUtils.adjust_for_business_day(current_date, convention)
-
- @staticmethod
- def is_business_day(check_date: date) -> bool:
- """Check if date is a business day (Monday-Friday, no holidays)"""
- # Simple implementation - excludes weekends only
- # In practice, would need holiday calendar
- return check_date.weekday() < 5
-
- @staticmethod
- def adjust_for_business_day(check_date: date,
- convention: BusinessDayConvention) -> date:
- """Adjust date according to business day convention"""
- if DateUtils.is_business_day(check_date):
- return check_date
-
- if convention == BusinessDayConvention.FOLLOWING:
- while not DateUtils.is_business_day(check_date):
- check_date += timedelta(days=1)
- elif convention == BusinessDayConvention.PRECEDING:
- while not DateUtils.is_business_day(check_date):
- check_date -= timedelta(days=1)
- elif convention == BusinessDayConvention.MODIFIED_FOLLOWING:
- original_month = check_date.month
- while not DateUtils.is_business_day(check_date):
- check_date += timedelta(days=1)
- # If we moved to next month, use preceding instead
- if check_date.month != original_month:
- check_date = DateUtils.adjust_for_business_day(
- check_date.replace(day=1) - timedelta(days=1),
- BusinessDayConvention.PRECEDING
- )
- elif convention == BusinessDayConvention.MODIFIED_PRECEDING:
- original_month = check_date.month
- while not DateUtils.is_business_day(check_date):
- check_date -= timedelta(days=1)
- # If we moved to previous month, use following instead
- if check_date.month != original_month:
- check_date = DateUtils.adjust_for_business_day(
- check_date.replace(day=1),
- BusinessDayConvention.FOLLOWING
- )
- # UNADJUSTED returns the original date
-
- return check_date
-
- @staticmethod
- def calculate_day_count_fraction(start_date: date, end_date: date,
- convention: DayCountConvention) -> Decimal:
- """Calculate day count fraction between two dates"""
- if start_date >= end_date:
- return Decimal('0')
-
- if convention == DayCountConvention.ACTUAL_360:
- days = (end_date - start_date).days
- return Decimal(days) / Decimal('360')
-
- elif convention == DayCountConvention.ACTUAL_365:
- days = (end_date - start_date).days
- return Decimal(days) / Decimal('365')
-
- elif convention == DayCountConvention.ACTUAL_365_FIXED:
- days = (end_date - start_date).days
- return Decimal(days) / Decimal('365')
-
- elif convention == DayCountConvention.ACTUAL_ACTUAL:
- # ISDA Actual/Actual
- days = (end_date - start_date).days
- year_start = date(start_date.year, 1, 1)
- year_end = date(start_date.year + 1, 1, 1)
- days_in_year = (year_end - year_start).days
- return Decimal(days) / Decimal(days_in_year)
-
- elif convention == DayCountConvention.THIRTY_360:
- return DateUtils._thirty_360_fraction(start_date, end_date)
-
- elif convention == DayCountConvention.THIRTY_360_EUROPEAN:
- return DateUtils._thirty_360_european_fraction(start_date, end_date)
-
- else:
- # Default to Actual/365
- days = (end_date - start_date).days
- return Decimal(days) / Decimal('365')
-
- @staticmethod
- def _thirty_360_fraction(start_date: date, end_date: date) -> Decimal:
- """Calculate 30/360 day count fraction (US/NASD convention)"""
- d1 = start_date.day
- d2 = end_date.day
- m1 = start_date.month
- m2 = end_date.month
- y1 = start_date.year
- y2 = end_date.year
-
- # Adjust for end-of-month
- if d1 == 31:
- d1 = 30
- if d1 == 30 and d2 == 31:
- d2 = 30
-
- days = 360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1)
- return Decimal(days) / Decimal('360')
-
- @staticmethod
- def _thirty_360_european_fraction(start_date: date, end_date: date) -> Decimal:
- """Calculate 30E/360 day count fraction (European convention)"""
- d1 = min(start_date.day, 30)
- d2 = min(end_date.day, 30)
- m1 = start_date.month
- m2 = end_date.month
- y1 = start_date.year
- y2 = end_date.year
-
- days = 360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1)
- return Decimal(days) / Decimal('360')
-
- @staticmethod
- def is_leap_year(year: int) -> bool:
- """Check if year is a leap year"""
- return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
-
- @staticmethod
- def days_in_year(year: int) -> int:
- """Get number of days in a year"""
- return 366 if DateUtils.is_leap_year(year) else 365
-
- @staticmethod
- def end_of_month(input_date: date) -> date:
- """Get last day of month for given date"""
- if input_date.month == 12:
- next_month = date(input_date.year + 1, 1, 1)
- else:
- next_month = date(input_date.year, input_date.month + 1, 1)
- return next_month - timedelta(days=1)
-
- @staticmethod
- def generate_schedule(start_date: date, end_date: date,
- frequency: CompoundingFrequency,
- convention: BusinessDayConvention = BusinessDayConvention.MODIFIED_FOLLOWING) -> List[date]:
- """Generate payment schedule between two dates"""
- if frequency == CompoundingFrequency.CONTINUOUS:
- return [end_date] # Only final payment for continuous
-
- schedule = []
- freq_value = frequency.value
- months_between = 12 // freq_value
-
- current_date = end_date
- while current_date > start_date:
- schedule.append(DateUtils.adjust_for_business_day(current_date, convention))
-
- # Move back by payment frequency
- if current_date.month <= months_between:
- new_month = 12 + current_date.month - months_between
- new_year = current_date.year - 1
- else:
- new_month = current_date.month - months_between
- new_year = current_date.year
-
- try:
- current_date = current_date.replace(year=new_year, month=new_month)
- except ValueError:
- # Handle end-of-month adjustments
- current_date = DateUtils.end_of_month(date(new_year, new_month, 1))
-
- schedule.reverse()
- return schedule
-
-
-class ValidationUtils:
- """Input validation utilities"""
-
- @staticmethod
- def validate_positive(value: Decimal, name: str) -> Decimal:
- """Validate that value is positive"""
- if value <= 0:
- raise ValidationError(f"{name} must be positive, got {value}")
- return value
-
- @staticmethod
- def validate_non_negative(value: Decimal, name: str) -> Decimal:
- """Validate that value is non-negative"""
- if value < 0:
- raise ValidationError(f"{name} cannot be negative, got {value}")
- return value
-
- @staticmethod
- def validate_percentage(value: Decimal, name: str, allow_negative: bool = False) -> Decimal:
- """Validate percentage value (0-100% or -100% to 100%)"""
- min_val = Decimal('-1') if allow_negative else Decimal('0')
- max_val = Decimal('1')
-
- if not (min_val <= value <= max_val):
- raise ValidationError(f"{name} must be between {min_val * 100}% and {max_val * 100}%, got {value * 100}%")
- return value
-
- @staticmethod
- def validate_yield(value: Decimal, name: str = "Yield") -> Decimal:
- """Validate yield value"""
- from config import VALIDATION_RULES
- min_yield = VALIDATION_RULES['min_yield']
- max_yield = VALIDATION_RULES['max_yield']
-
- if not (min_yield <= value <= max_yield):
- raise ValidationError(
- f"{name} must be between {min_yield * 100}% and {max_yield * 100}%, got {value * 100}%")
- return value
-
- @staticmethod
- def validate_price(value: Decimal, name: str = "Price") -> Decimal:
- """Validate bond price"""
- from config import VALIDATION_RULES
- min_price = VALIDATION_RULES['min_price']
- max_price = VALIDATION_RULES['max_price']
-
- if not (min_price <= value <= max_price):
- raise ValidationError(f"{name} must be between {min_price} and {max_price}, got {value}")
- return value
-
- @staticmethod
- def validate_date_order(start_date: date, end_date: date,
- start_name: str = "Start date", end_name: str = "End date"):
- """Validate that start date is before end date"""
- if start_date >= end_date:
- raise ValidationError(f"{start_name} ({start_date}) must be before {end_name} ({end_date})")
-
- @staticmethod
- def validate_maturity_range(issue_date: date, maturity_date: date):
- """Validate maturity is within reasonable range"""
- from config import VALIDATION_RULES
-
- days_to_maturity = (maturity_date - issue_date).days
- min_days = VALIDATION_RULES['min_maturity_days']
- max_days = VALIDATION_RULES['max_maturity_years'] * 365
-
- if days_to_maturity < min_days:
- raise ValidationError(f"Maturity too short: {days_to_maturity} days (minimum: {min_days})")
-
- if days_to_maturity > max_days:
- raise ValidationError(f"Maturity too long: {days_to_maturity} days (maximum: {max_days})")
-
-
-class FormattingUtils:
- """Output formatting utilities"""
-
- @staticmethod
- def format_percentage(value: Decimal, decimal_places: int = 2) -> str:
- """Format decimal as percentage"""
- percentage = value * Decimal('100')
- return f"{percentage:.{decimal_places}f}%"
-
- @staticmethod
- def format_currency(value: Decimal, currency_symbol: str = "$", decimal_places: int = 2) -> str:
- """Format decimal as currency"""
- return f"{currency_symbol}{value:,.{decimal_places}f}"
-
- @staticmethod
- def format_basis_points(value: Decimal) -> str:
- """Format decimal as basis points"""
- bps = value * Decimal('10000')
- return f"{bps:.0f} bps"
-
- @staticmethod
- def format_yield(value: Decimal, decimal_places: int = 3) -> str:
- """Format yield with appropriate precision"""
- return FormattingUtils.format_percentage(value, decimal_places)
-
- @staticmethod
- def format_duration(value: Decimal, decimal_places: int = 2) -> str:
- """Format duration"""
- return f"{value:.{decimal_places}f} years"
-
- @staticmethod
- def format_price(value: Decimal, decimal_places: int = 4) -> str:
- """Format bond price"""
- return f"{value:.{decimal_places}f}"
-
-
-class CachingUtils:
- """Simple caching utilities for expensive calculations"""
-
- def __init__(self, max_size: int = 1000):
- self.cache = {}
- self.max_size = max_size
- self.access_order = []
-
- def get(self, key: str):
- """Get cached value"""
- if key in self.cache:
- # Move to end (most recently used)
- self.access_order.remove(key)
- self.access_order.append(key)
- return self.cache[key]
- return None
-
- def put(self, key: str, value):
- """Put value in cache"""
- if key in self.cache:
- # Update existing
- self.cache[key] = value
- self.access_order.remove(key)
- self.access_order.append(key)
- else:
- # Add new
- if len(self.cache) >= self.max_size:
- # Remove least recently used
- oldest_key = self.access_order.pop(0)
- del self.cache[oldest_key]
-
- self.cache[key] = value
- self.access_order.append(key)
-
- def clear(self):
- """Clear cache"""
- self.cache.clear()
- self.access_order.clear()
-
-
-# Global cache instance
-calculation_cache = CachingUtils(max_size=5000)
-
-
-def cache_calculation(func):
- """Decorator for caching calculation results"""
-
- def wrapper(*args, **kwargs):
- # Create cache key from function name and arguments
- cache_key = f"{func.__name__}_{hash(str(args) + str(sorted(kwargs.items())))}"
-
- # Try to get from cache
- result = calculation_cache.get(cache_key)
- if result is not None:
- return result
-
- # Calculate and cache result
- result = func(*args, **kwargs)
- calculation_cache.put(cache_key, result)
- return result
-
- return wrapper
-
-
-# Commonly used mathematical constants as Decimals
-PI = Decimal('3.1415926535897932384626433832795')
-E = Decimal('2.7182818284590452353602874713527')
-SQRT_2 = Decimal('1.4142135623730950488016887242097')
-SQRT_2PI = Decimal('2.5066282746310005024157652848110')
-
-
-# Standard normal distribution approximation
-def standard_normal_cdf(x: Decimal) -> Decimal:
- """Approximate standard normal cumulative distribution function"""
- # Abramowitz and Stegun approximation
- x_float = float(x)
-
- if x_float < 0:
- return Decimal('1') - standard_normal_cdf(-x)
-
- # Constants for approximation
- a1 = Decimal('0.254829592')
- a2 = Decimal('-0.284496736')
- a3 = Decimal('1.421413741')
- a4 = Decimal('-1.453152027')
- a5 = Decimal('1.061405429')
- p = Decimal('0.3275911')
-
- t = Decimal('1') / (Decimal('1') + p * x)
- y = Decimal('1') - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * \
- Decimal(str(math.exp(-float(x * x / Decimal('2')))))
-
- return y
-
-
-def black_scholes_call_price(S: Decimal, K: Decimal, T: Decimal, r: Decimal, sigma: Decimal) -> Decimal:
- """Black-Scholes call option price (simplified implementation)"""
- if T <= 0 or sigma <= 0:
- return max(S - K, Decimal('0'))
-
- d1 = (Decimal(str(math.log(float(S / K)))) + (r + sigma * sigma / Decimal('2')) * T) / (
- sigma * Decimal(str(math.sqrt(float(T)))))
- d2 = d1 - sigma * Decimal(str(math.sqrt(float(T))))
-
- call_price = S * standard_normal_cdf(d1) - K * Decimal(str(math.exp(-float(r * T)))) * standard_normal_cdf(d2)
-
- return call_price
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/valuation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/valuation.py
deleted file mode 100644
index 695703a65..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/valuation.py
+++ /dev/null
@@ -1,616 +0,0 @@
-
-Fixed Income Valuation Module
-=================================
-
-Fixed income security valuation
-
-===== DATA SOURCES REQUIRED =====
-INPUT:
- - Bond prospectuses and issue documentation
- - Market price data and yield curve information
- - Credit ratings and default recovery rates
- - Interest rate benchmarks and swap curves
- - Macroeconomic data affecting fixed income markets
-
-OUTPUT:
- - Bond valuation models and price calculations
- - Yield curve analysis and forward rate calculations
- - Credit risk assessment and spread analysis
- - Duration and convexity risk metrics
- - Portfolio optimization and immunization strategies
-
-PARAMETERS:
- - yield_curve_method: Yield curve modeling method (default: 'nelson_siegel')
- - credit_spread: Credit spread assumption (default: 0.02)
- - recovery_rate: Default recovery rate (default: 0.40)
- - convexity_adjustment: Convexity adjustment factor (default: 1.0)
- - benchmark_curve: Benchmark yield curve (default: 'treasury')
-
-
-from typing import List, Dict, Optional, Tuple, Callable
-from decimal import Decimal
-from datetime import date
-import random
-from models import Bond, CallableBond, PutableBond, ConvertibleBond, CashFlow
-from instruments import BondInstrument, create_bond_instrument
-from yield_curves import SpotCurve
-from utils import MathUtils, DateUtils, ValidationUtils, cache_calculation, black_scholes_call_price
-from config import CompoundingFrequency, ERROR_TOLERANCE
-
-
-class BondValuation:
- """Basic bond valuation methods"""
-
- @staticmethod
- @cache_calculation
- def present_value(bond: Bond, discount_rate: Decimal,
- settlement_date: Optional[date] = None) -> Decimal:
- """Calculate present value of bond using single discount rate"""
- ValidationUtils.validate_yield(discount_rate, "Discount rate")
-
- if settlement_date is None:
- settlement_date = date.today()
-
- bond_instrument = create_bond_instrument(bond)
- cash_flows = bond_instrument.generate_cash_flows(settlement_date)
-
- total_pv = Decimal('0')
-
- for cf in cash_flows:
- time_to_payment = DateUtils.calculate_day_count_fraction(
- settlement_date, cf.date, bond.day_count_convention
- )
-
- pv = MathUtils.present_value(cf.amount, discount_rate, time_to_payment)
- total_pv += pv
-
- return total_pv
-
- @staticmethod
- def present_value_with_curve(bond: Bond, spot_curve: SpotCurve,
- settlement_date: Optional[date] = None) -> Decimal:
- """Calculate present value using spot rate curve"""
- if settlement_date is None:
- settlement_date = date.today()
-
- bond_instrument = create_bond_instrument(bond)
- cash_flows = bond_instrument.generate_cash_flows(settlement_date)
-
- total_pv = Decimal('0')
-
- for cf in cash_flows:
- time_to_payment = DateUtils.calculate_day_count_fraction(
- settlement_date, cf.date, bond.day_count_convention
- )
-
- spot_rate = spot_curve.get_rate(time_to_payment)
- pv = MathUtils.present_value(cf.amount, spot_rate, time_to_payment)
- total_pv += pv
-
- return total_pv
-
- @staticmethod
- def yield_to_maturity(bond: Bond, price: Decimal,
- settlement_date: Optional[date] = None) -> Decimal:
- """Calculate yield to maturity using iterative methods"""
- ValidationUtils.validate_price(price, "Bond price")
-
- if settlement_date is None:
- settlement_date = date.today()
-
- # Define function: PV(ytm) - price = 0
- def price_function(ytm: Decimal) -> Decimal:
- pv = BondValuation.present_value(bond, ytm, settlement_date)
- return pv - price
-
- # Derivative of price function with respect to yield
- def price_derivative(ytm: Decimal) -> Decimal:
- # Numerical derivative using small increment
- delta = Decimal('0.0001')
- pv1 = BondValuation.present_value(bond, ytm - delta, settlement_date)
- pv2 = BondValuation.present_value(bond, ytm + delta, settlement_date)
- return (pv2 - pv1) / (Decimal('2') * delta)
-
- # Initial guess based on current yield
- if bond.coupon_rate > 0:
- initial_guess = bond.coupon_rate
- else:
- # For zero coupon bonds
- time_to_maturity = DateUtils.calculate_day_count_fraction(
- settlement_date, bond.maturity_date, bond.day_count_convention
- )
- initial_guess = (bond.face_value / price) ** (Decimal('1') / time_to_maturity) - Decimal('1')
-
- try:
- # Use Newton-Raphson method
- ytm = MathUtils.newton_raphson(price_function, price_derivative, initial_guess)
- ValidationUtils.validate_yield(ytm, "Yield to maturity")
- return ytm
- except:
- # Fallback to bisection method
- try:
- return MathUtils.bisection_method(price_function, Decimal('0.001'), Decimal('0.50'))
- except:
- # Last resort: Brent's method
- return MathUtils.brent_method(price_function, Decimal('0.001'), Decimal('0.50'))
-
- @staticmethod
- def current_yield(bond: Bond, price: Decimal) -> Decimal:
- """Calculate current yield (annual coupon / price)"""
- ValidationUtils.validate_price(price, "Bond price")
-
- if bond.is_zero_coupon:
- return Decimal('0')
-
- annual_coupon = bond.face_value * bond.coupon_rate
- return annual_coupon / price
-
- @staticmethod
- def accrued_interest(bond: Bond, settlement_date: date) -> Decimal:
- """Calculate accrued interest"""
- bond_instrument = create_bond_instrument(bond)
- return bond_instrument.accrued_interest(settlement_date)
-
- @staticmethod
- def clean_price(dirty_price: Decimal, accrued: Decimal) -> Decimal:
- """Calculate clean price from dirty price"""
- return dirty_price - accrued
-
- @staticmethod
- def dirty_price(clean_price: Decimal, accrued: Decimal) -> Decimal:
- """Calculate dirty price from clean price"""
- return clean_price + accrued
-
-
-class CallableBondValuation:
- """Valuation methods for callable bonds"""
-
- @staticmethod
- def yield_to_call(callable_bond: CallableBond, price: Decimal,
- call_date: date, call_price: Decimal,
- settlement_date: Optional[date] = None) -> Decimal:
- """Calculate yield to call"""
- ValidationUtils.validate_price(price, "Bond price")
- ValidationUtils.validate_price(call_price, "Call price")
-
- if settlement_date is None:
- settlement_date = date.today()
-
- # Create temporary bond with call date as maturity
- temp_bond = Bond(
- isin=callable_bond.isin + "_CALL",
- issue_date=callable_bond.issue_date,
- maturity_date=call_date,
- face_value=call_price, # Use call price as face value
- currency=callable_bond.currency,
- coupon_rate=callable_bond.coupon_rate,
- coupon_frequency=callable_bond.coupon_frequency,
- day_count_convention=callable_bond.day_count_convention
- )
-
- return BondValuation.yield_to_maturity(temp_bond, price, settlement_date)
-
- @staticmethod
- def yield_to_worst(callable_bond: CallableBond, price: Decimal,
- settlement_date: Optional[date] = None) -> Decimal:
- """Calculate yield to worst (minimum of YTM and all YTCs)"""
- if settlement_date is None:
- settlement_date = date.today()
-
- # Calculate YTM
- ytm = BondValuation.yield_to_maturity(callable_bond, price, settlement_date)
-
- yields = [ytm]
-
- # Calculate YTC for each call date
- for call_feature in callable_bond.call_schedule:
- if call_feature.call_date > settlement_date:
- ytc = CallableBondValuation.yield_to_call(
- callable_bond, price, call_feature.call_date,
- call_feature.call_price, settlement_date
- )
- yields.append(ytc)
-
- return min(yields)
-
-
-class ArbitrageFreeValuation:
- """Arbitrage-free valuation using binomial trees and Monte Carlo"""
-
- @staticmethod
- def binomial_tree_value(bond: Bond, spot_curve: SpotCurve, volatility: Decimal,
- steps: int = 100) -> Decimal:
- """Value bond using binomial interest rate tree"""
- ValidationUtils.validate_positive(volatility, "Volatility")
- ValidationUtils.validate_positive(Decimal(str(steps)), "Steps")
-
- time_to_maturity = DateUtils.calculate_day_count_fraction(
- date.today(), bond.maturity_date, bond.day_count_convention
- )
-
- dt = time_to_maturity / Decimal(str(steps))
-
- # Build interest rate tree
- rate_tree = ArbitrageFreeValuation._build_rate_tree(
- spot_curve, volatility, steps, dt
- )
-
- # Generate bond cash flows
- bond_instrument = create_bond_instrument(bond)
- cash_flows = bond_instrument.generate_cash_flows()
-
- # Backward induction valuation
- return ArbitrageFreeValuation._backward_induction(
- rate_tree, cash_flows, bond, dt, steps
- )
-
- @staticmethod
- def _build_rate_tree(spot_curve: SpotCurve, volatility: Decimal,
- steps: int, dt: Decimal) -> List[List[Decimal]]:
- """Build binomial interest rate tree"""
- tree = []
-
- # Initial rate
- r0 = spot_curve.get_rate(dt)
-
- # Up and down factors
- u = Decimal(str(2.71828182845905)) ** (volatility * (dt ** Decimal('0.5')))
- d = Decimal('1') / u
-
- for i in range(steps + 1):
- level = []
- for j in range(i + 1):
- # Rate at node (i, j)
- rate = r0 * (u ** Decimal(str(j))) * (d ** Decimal(str(i - j)))
- level.append(rate)
- tree.append(level)
-
- return tree
-
- @staticmethod
- def _backward_induction(rate_tree: List[List[Decimal]], cash_flows: List[CashFlow],
- bond: Bond, dt: Decimal, steps: int) -> Decimal:
- """Perform backward induction on the tree"""
- # Create cash flow mapping by time step
- cf_map = {}
- for cf in cash_flows:
- time_to_cf = DateUtils.calculate_day_count_fraction(
- date.today(), cf.date, bond.day_count_convention
- )
- step = int(time_to_cf / dt)
- if step <= steps:
- cf_map[step] = cf_map.get(step, Decimal('0')) + cf.amount
-
- # Initialize final values
- values = [bond.face_value] * (steps + 1)
-
- # Work backwards through the tree
- for i in range(steps - 1, -1, -1):
- new_values = []
- for j in range(i + 1):
- # Discount expected value
- up_value = values[j + 1] if j + 1 < len(values) else bond.face_value
- down_value = values[j] if j < len(values) else bond.face_value
-
- expected_value = (up_value + down_value) / Decimal('2')
- discount_rate = rate_tree[i][j]
-
- discounted_value = expected_value / (Decimal('1') + discount_rate * dt)
-
- # Add any cash flow at this step
- if i in cf_map:
- discounted_value += cf_map[i]
-
- new_values.append(discounted_value)
-
- values = new_values
-
- return values[0] if values else bond.face_value
-
- @staticmethod
- def monte_carlo_value(bond: Bond, spot_curve: SpotCurve, volatility: Decimal,
- paths: int = 10000, steps: int = 252) -> Tuple[Decimal, Decimal]:
- """Value bond using Monte Carlo simulation"""
- ValidationUtils.validate_positive(volatility, "Volatility")
- ValidationUtils.validate_positive(Decimal(str(paths)), "Paths")
-
- time_to_maturity = DateUtils.calculate_day_count_fraction(
- date.today(), bond.maturity_date, bond.day_count_convention
- )
-
- dt = time_to_maturity / Decimal(str(steps))
-
- # Generate bond cash flows
- bond_instrument = create_bond_instrument(bond)
- cash_flows = bond_instrument.generate_cash_flows()
-
- path_values = []
-
- for _ in range(paths):
- # Generate interest rate path
- rate_path = ArbitrageFreeValuation._generate_rate_path(
- spot_curve, volatility, steps, dt
- )
-
- # Value bond along this path
- path_value = ArbitrageFreeValuation._value_along_path(
- cash_flows, rate_path, bond, dt
- )
- path_values.append(path_value)
-
- # Calculate statistics
- mean_value = sum(path_values) / Decimal(str(len(path_values)))
-
- # Standard error
- variance = sum((v - mean_value) ** 2 for v in path_values) / Decimal(str(len(path_values) - 1))
- std_error = (variance / Decimal(str(len(path_values)))) ** Decimal('0.5')
-
- return mean_value, std_error
-
- @staticmethod
- def _generate_rate_path(spot_curve: SpotCurve, volatility: Decimal,
- steps: int, dt: Decimal) -> List[Decimal]:
- """Generate single interest rate path using Vasicek model"""
- path = []
- r = spot_curve.get_rate(dt) # Initial rate
-
- # Vasicek parameters (simplified)
- kappa = Decimal('0.1') # Mean reversion speed
- theta = spot_curve.get_rate(Decimal('10')) # Long-term mean
-
- for _ in range(steps):
- # Vasicek SDE: dr = kappa(theta - r)dt + sigma * dW
- drift = kappa * (theta - r) * dt
- shock = volatility * (dt ** Decimal('0.5')) * Decimal(str(random.gauss(0, 1)))
-
- r = r + drift + shock
- r = max(r, Decimal('0.0001')) # Floor at 1bp
- path.append(r)
-
- return path
-
- @staticmethod
- def _value_along_path(cash_flows: List[CashFlow], rate_path: List[Decimal],
- bond: Bond, dt: Decimal) -> Decimal:
- """Value bond along specific rate path"""
- total_value = Decimal('0')
-
- for cf in cash_flows:
- time_to_cf = DateUtils.calculate_day_count_fraction(
- date.today(), cf.date, bond.day_count_convention
- )
-
- # Find appropriate rate from path
- step = min(int(time_to_cf / dt), len(rate_path) - 1)
- discount_rate = rate_path[step]
-
- pv = MathUtils.present_value(cf.amount, discount_rate, time_to_cf)
- total_value += pv
-
- return total_value
-
-
-class OptionAdjustedSpread:
- """Option-Adjusted Spread (OAS) calculations"""
-
- @staticmethod
- def calculate_oas(bond: Bond, market_price: Decimal, spot_curve: SpotCurve,
- volatility: Decimal, steps: int = 100) -> Decimal:
- """Calculate Option-Adjusted Spread"""
- ValidationUtils.validate_price(market_price, "Market price")
-
- # Define function: Theoretical Price(OAS) - Market Price = 0
- def price_difference(oas: Decimal) -> Decimal:
- # Create shifted curve
- shifted_curve = spot_curve.shift_curve(oas, "parallel")
-
- # Value bond with shifted curve
- if isinstance(bond, (CallableBond, PutableBond)):
- theoretical_price = ArbitrageFreeValuation.binomial_tree_value(
- bond, shifted_curve, volatility, steps
- )
- else:
- theoretical_price = BondValuation.present_value_with_curve(
- bond, shifted_curve
- )
-
- return theoretical_price - market_price
-
- # Solve for OAS using bisection method
- try:
- oas = MathUtils.bisection_method(
- price_difference,
- Decimal('-0.05'), # -500 bps
- Decimal('0.05') # +500 bps
- )
- return oas
- except:
- # Fallback to wider range
- return MathUtils.bisection_method(
- price_difference,
- Decimal('-0.10'), # -1000 bps
- Decimal('0.10') # +1000 bps
- )
-
- @staticmethod
- def oas_duration(bond: Bond, market_price: Decimal, spot_curve: SpotCurve,
- volatility: Decimal, steps: int = 100) -> Decimal:
- """Calculate OAS duration (sensitivity to parallel curve shifts)"""
- shift_size = Decimal('0.0001') # 1 bp
-
- # Calculate OAS for shifted curves
- up_curve = spot_curve.shift_curve(shift_size, "parallel")
- down_curve = spot_curve.shift_curve(-shift_size, "parallel")
-
- oas_up = OptionAdjustedSpread.calculate_oas(bond, market_price, up_curve, volatility, steps)
- oas_down = OptionAdjustedSpread.calculate_oas(bond, market_price, down_curve, volatility, steps)
-
- # Duration = -(dOAS/dy) where y is yield
- return -(oas_up - oas_down) / (Decimal('2') * shift_size)
-
-
-class ConvertibleBondValuation:
- """Valuation methods for convertible bonds"""
-
- @staticmethod
- def convertible_bond_value(convertible: ConvertibleBond, spot_curve: SpotCurve,
- stock_price: Decimal, stock_volatility: Decimal,
- risk_free_rate: Decimal) -> Dict[str, Decimal]:
- """Comprehensive convertible bond valuation"""
- ValidationUtils.validate_positive(stock_price, "Stock price")
- ValidationUtils.validate_positive(stock_volatility, "Stock volatility")
- ValidationUtils.validate_yield(risk_free_rate, "Risk-free rate")
-
- # 1. Straight bond value
- straight_value = BondValuation.present_value_with_curve(convertible, spot_curve)
-
- # 2. Conversion value
- conversion_value = convertible.conversion_ratio * stock_price
-
- # 3. Option value using Black-Scholes approximation
- time_to_maturity = DateUtils.calculate_day_count_fraction(
- date.today(), convertible.maturity_date, convertible.day_count_convention
- )
-
- # Treat conversion as call option on stock
- conversion_option_value = black_scholes_call_price(
- S=stock_price,
- K=convertible.conversion_price,
- T=time_to_maturity,
- r=risk_free_rate,
- sigma=stock_volatility
- ) * convertible.conversion_ratio
-
- # 4. Total convertible value (simplified)
- total_value = max(straight_value, conversion_value) + conversion_option_value * Decimal('0.1')
-
- return {
- 'total_value': total_value,
- 'straight_value': straight_value,
- 'conversion_value': conversion_value,
- 'option_value': conversion_option_value,
- 'conversion_premium': max(Decimal('0'), total_value - conversion_value),
- 'investment_premium': max(Decimal('0'), total_value - straight_value)
- }
-
-
-class MatrixPricing:
- """Matrix pricing for illiquid bonds"""
-
- @staticmethod
- def matrix_price(target_bond: Bond, comparable_bonds: List[Tuple[Bond, Decimal]],
- weights: Optional[List[Decimal]] = None) -> Decimal:
- """Calculate matrix price using comparable bonds"""
- if not comparable_bonds:
- raise ValueError("Need at least one comparable bond")
-
- if weights is None:
- # Equal weights
- weights = [Decimal('1') / Decimal(str(len(comparable_bonds)))] * len(comparable_bonds)
-
- if len(weights) != len(comparable_bonds):
- raise ValueError("Number of weights must match number of comparables")
-
- # Calculate weighted average yield spread
- target_maturity = DateUtils.calculate_day_count_fraction(
- date.today(), target_bond.maturity_date, target_bond.day_count_convention
- )
-
- weighted_spread = Decimal('0')
-
- for i, (comp_bond, comp_price) in enumerate(comparable_bonds):
- # Calculate comparable's YTM
- comp_ytm = BondValuation.yield_to_maturity(comp_bond, comp_price)
-
- # Adjust for maturity difference (simplified)
- maturity_adj = MatrixPricing._maturity_adjustment(target_bond, comp_bond)
-
- # Adjust for credit difference
- credit_adj = MatrixPricing._credit_adjustment(target_bond, comp_bond)
-
- adjusted_ytm = comp_ytm + maturity_adj + credit_adj
- weighted_spread += weights[i] * adjusted_ytm
-
- # Calculate target bond price using weighted spread
- target_price = BondValuation.present_value(target_bond, weighted_spread)
-
- return target_price
-
- @staticmethod
- def _maturity_adjustment(target: Bond, comparable: Bond) -> Decimal:
- """Calculate maturity adjustment"""
- target_maturity = DateUtils.calculate_day_count_fraction(
- date.today(), target.maturity_date, target.day_count_convention
- )
- comp_maturity = DateUtils.calculate_day_count_fraction(
- date.today(), comparable.maturity_date, comparable.day_count_convention
- )
-
- # Simple linear adjustment: 5 bps per year difference
- maturity_diff = target_maturity - comp_maturity
- return maturity_diff * Decimal('0.0005') # 5 bps per year
-
- @staticmethod
- def _credit_adjustment(target: Bond, comparable: Bond) -> Decimal:
- """Calculate credit quality adjustment"""
- if target.issuer_rating is None or comparable.issuer_rating is None:
- return Decimal('0')
-
- from config import RATING_SCORES
-
- target_score = RATING_SCORES.get(target.issuer_rating, 10)
- comp_score = RATING_SCORES.get(comparable.issuer_rating, 10)
-
- # 25 bps per notch difference
- rating_diff = target_score - comp_score
- return Decimal(str(rating_diff)) * Decimal('0.0025')
-
-
-# Utility functions for common valuation scenarios
-def value_bond_portfolio(bonds: List[Tuple[Bond, Decimal]], spot_curve: SpotCurve) -> Dict[str, Decimal]:
- """Value a portfolio of bonds"""
- total_value = Decimal('0')
- total_face_value = Decimal('0')
-
- individual_values = []
-
- for bond, quantity in bonds:
- bond_value = BondValuation.present_value_with_curve(bond, spot_curve)
- position_value = bond_value * quantity
-
- total_value += position_value
- total_face_value += bond.face_value * quantity
-
- individual_values.append({
- 'bond': bond,
- 'quantity': quantity,
- 'unit_value': bond_value,
- 'position_value': position_value
- })
-
- return {
- 'total_market_value': total_value,
- 'total_face_value': total_face_value,
- 'portfolio_yield': (total_face_value - total_value) / total_value if total_value > 0 else Decimal('0'),
- 'individual_positions': individual_values
- }
-
-
-def stress_test_bond(bond: Bond, base_curve: SpotCurve,
- stress_scenarios: List[Tuple[str, Decimal]]) -> Dict[str, Decimal]:
- """Stress test bond value under different scenarios"""
- base_value = BondValuation.present_value_with_curve(bond, base_curve)
-
- results = {'base_case': base_value}
-
- for scenario_name, shift_amount in stress_scenarios:
- stressed_curve = base_curve.shift_curve(shift_amount, "parallel")
- stressed_value = BondValuation.present_value_with_curve(bond, stressed_curve)
-
- results[scenario_name] = {
- 'value': stressed_value,
- 'change': stressed_value - base_value,
- 'percentage_change': (stressed_value - base_value) / base_value * Decimal('100')
- }
-
- return results
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/yield_curves.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/yield_curves.py
deleted file mode 100644
index 5770c83a1..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fixedIncome/yield_curves.py
+++ /dev/null
@@ -1,563 +0,0 @@
-
-Fixed Income Yield Curves Module
-=================================
-
-Yield curve construction and analysis
-
-===== DATA SOURCES REQUIRED =====
-INPUT:
- - Bond prospectuses and issue documentation
- - Market price data and yield curve information
- - Credit ratings and default recovery rates
- - Interest rate benchmarks and swap curves
- - Macroeconomic data affecting fixed income markets
-
-OUTPUT:
- - Bond valuation models and price calculations
- - Yield curve analysis and forward rate calculations
- - Credit risk assessment and spread analysis
- - Duration and convexity risk metrics
- - Portfolio optimization and immunization strategies
-
-PARAMETERS:
- - yield_curve_method: Yield curve modeling method (default: 'nelson_siegel')
- - credit_spread: Credit spread assumption (default: 0.02)
- - recovery_rate: Default recovery rate (default: 0.40)
- - convexity_adjustment: Convexity adjustment factor (default: 1.0)
- - benchmark_curve: Benchmark yield curve (default: 'treasury')
-
-
-from typing import List, Dict, Optional, Tuple
-from decimal import Decimal
-from datetime import date
-from models import YieldCurve, Bond, MarketData
-from utils import MathUtils, DateUtils, ValidationUtils, cache_calculation
-from config import Currency, CompoundingFrequency, ERROR_TOLERANCE
-
-
-class SpotCurve:
- """Zero-coupon (spot) yield curve implementation"""
-
- def __init__(self, curve: YieldCurve):
- ValidationUtils.validate_date_order(date.today(), curve.curve_date, "Today", "Curve date")
- self.curve = curve
- self._validate_curve()
-
- def _validate_curve(self):
- """Validate curve data"""
- if len(self.curve.maturities) != len(self.curve.rates):
- raise ValueError("Maturities and rates must have same length")
-
- # Check ascending order of maturities
- for i in range(1, len(self.curve.maturities)):
- if self.curve.maturities[i] <= self.curve.maturities[i - 1]:
- raise ValueError("Maturities must be in ascending order")
-
- # Validate all rates
- for rate in self.curve.rates:
- ValidationUtils.validate_yield(rate, "Spot rate")
-
- @cache_calculation
- def get_rate(self, maturity: Decimal) -> Decimal:
- """Get spot rate for given maturity using interpolation"""
- ValidationUtils.validate_positive(maturity, "Maturity")
-
- # Exact match
- if maturity in self.curve.maturities:
- index = self.curve.maturities.index(maturity)
- return self.curve.rates[index]
-
- # Extrapolation for very short or long maturities
- if maturity < self.curve.maturities[0]:
- return self.curve.rates[0] # Flat extrapolation
-
- if maturity > self.curve.maturities[-1]:
- return self.curve.rates[-1] # Flat extrapolation
-
- # Linear interpolation
- for i in range(len(self.curve.maturities) - 1):
- if self.curve.maturities[i] <= maturity <= self.curve.maturities[i + 1]:
- return MathUtils.linear_interpolation(
- maturity,
- self.curve.maturities[i], self.curve.rates[i],
- self.curve.maturities[i + 1], self.curve.rates[i + 1]
- )
-
- return self.curve.rates[0] # Fallback
-
- def get_discount_factor(self, maturity: Decimal) -> Decimal:
- """Calculate discount factor for given maturity"""
- spot_rate = self.get_rate(maturity)
- return Decimal('1') / ((Decimal('1') + spot_rate) ** maturity)
-
- def forward_rate(self, start_maturity: Decimal, end_maturity: Decimal) -> Decimal:
- """Calculate forward rate between two maturities"""
- ValidationUtils.validate_positive(start_maturity, "Start maturity")
- ValidationUtils.validate_positive(end_maturity, "End maturity")
-
- if end_maturity <= start_maturity:
- raise ValueError("End maturity must be greater than start maturity")
-
- r1 = self.get_rate(start_maturity)
- r2 = self.get_rate(end_maturity)
-
- # Forward rate formula: (1 + r2)^t2 = (1 + r1)^t1 * (1 + f)^(t2-t1)
- numerator = (Decimal('1') + r2) ** end_maturity
- denominator = (Decimal('1') + r1) ** start_maturity
- time_diff = end_maturity - start_maturity
-
- forward_factor = numerator / denominator
- return forward_factor ** (Decimal('1') / time_diff) - Decimal('1')
-
- def shift_curve(self, shift_amount: Decimal, shift_type: str = "parallel") -> 'SpotCurve':
- """Apply parallel or non-parallel shifts to the curve"""
- new_rates = []
-
- if shift_type == "parallel":
- new_rates = [rate + shift_amount for rate in self.curve.rates]
- elif shift_type == "steepening":
- # Steepening: short rates decrease, long rates increase
- for i, rate in enumerate(self.curve.rates):
- maturity = self.curve.maturities[i]
- # Linear scaling based on maturity
- shift = shift_amount * (maturity / self.curve.maturities[-1])
- new_rates.append(rate + shift)
- elif shift_type == "flattening":
- # Flattening: opposite of steepening
- for i, rate in enumerate(self.curve.rates):
- maturity = self.curve.maturities[i]
- shift = -shift_amount * (maturity / self.curve.maturities[-1])
- new_rates.append(rate + shift)
- else:
- raise ValueError("Invalid shift type. Use 'parallel', 'steepening', or 'flattening'")
-
- # Validate new rates
- for rate in new_rates:
- ValidationUtils.validate_yield(rate, "Shifted rate")
-
- new_curve = YieldCurve(
- curve_date=self.curve.curve_date,
- maturities=self.curve.maturities.copy(),
- rates=new_rates,
- currency=self.curve.currency,
- curve_type="spot"
- )
-
- return SpotCurve(new_curve)
-
-
-class ParCurve:
- """Par yield curve implementation"""
-
- def __init__(self, spot_curve: SpotCurve):
- self.spot_curve = spot_curve
- self.curve_date = spot_curve.curve.curve_date
- self.currency = spot_curve.curve.currency
-
- @cache_calculation
- def get_par_rate(self, maturity: Decimal,
- frequency: CompoundingFrequency = CompoundingFrequency.SEMI_ANNUAL) -> Decimal:
- """Calculate par rate for given maturity"""
- ValidationUtils.validate_positive(maturity, "Maturity")
-
- if frequency == CompoundingFrequency.CONTINUOUS:
- # For continuous compounding, par rate equals spot rate
- return self.spot_curve.get_rate(maturity)
-
- # Calculate discount factors for all payment dates
- payments_per_year = frequency.value
- payment_interval = Decimal('1') / Decimal(str(payments_per_year))
-
- # Generate payment times
- payment_times = []
- current_time = payment_interval
- while current_time <= maturity:
- payment_times.append(current_time)
- current_time += payment_interval
-
- # Ensure maturity is included
- if not payment_times or payment_times[-1] != maturity:
- payment_times.append(maturity)
-
- # Calculate sum of discount factors
- discount_sum = Decimal('0')
- for time in payment_times:
- discount_sum += self.spot_curve.get_discount_factor(time)
-
- # Final discount factor
- final_discount = self.spot_curve.get_discount_factor(maturity)
-
- # Par rate formula: (1 - final_discount) / discount_sum
- par_rate = (Decimal('1') - final_discount) / discount_sum
-
- return par_rate
-
- def build_par_curve(self, maturities: List[Decimal],
- frequency: CompoundingFrequency = CompoundingFrequency.SEMI_ANNUAL) -> YieldCurve:
- """Build complete par curve for given maturities"""
- par_rates = []
-
- for maturity in maturities:
- par_rate = self.get_par_rate(maturity, frequency)
- par_rates.append(par_rate)
-
- return YieldCurve(
- curve_date=self.curve_date,
- maturities=maturities,
- rates=par_rates,
- currency=self.currency,
- curve_type="par"
- )
-
-
-class ForwardCurve:
- """Forward rate curve implementation"""
-
- def __init__(self, spot_curve: SpotCurve):
- self.spot_curve = spot_curve
- self.curve_date = spot_curve.curve.curve_date
- self.currency = spot_curve.curve.currency
-
- @cache_calculation
- def get_forward_rate(self, start_time: Decimal, end_time: Decimal) -> Decimal:
- """Calculate forward rate between two time points"""
- return self.spot_curve.forward_rate(start_time, end_time)
-
- def build_forward_curve(self, start_maturity: Decimal,
- end_maturities: List[Decimal]) -> YieldCurve:
- """Build forward curve from start maturity to various end maturities"""
- forward_rates = []
-
- for end_maturity in end_maturities:
- if end_maturity <= start_maturity:
- raise ValueError(f"End maturity {end_maturity} must be greater than start maturity {start_maturity}")
-
- forward_rate = self.get_forward_rate(start_maturity, end_maturity)
- forward_rates.append(forward_rate)
-
- return YieldCurve(
- curve_date=self.curve_date,
- maturities=end_maturities,
- rates=forward_rates,
- currency=self.currency,
- curve_type="forward"
- )
-
- def instantaneous_forward_rate(self, maturity: Decimal, delta: Decimal = Decimal('0.001')) -> Decimal:
- """Calculate instantaneous forward rate at given maturity"""
- if maturity <= delta:
- return self.spot_curve.get_rate(delta)
-
- # Approximate derivative using finite difference
- r1 = self.spot_curve.get_rate(maturity - delta / 2)
- r2 = self.spot_curve.get_rate(maturity + delta / 2)
-
- # Instantaneous forward = d/dt[t * r(t)]
- return r2 + maturity * (r2 - r1) / delta
-
-
-class SwapCurve:
- """Interest rate swap curve implementation"""
-
- def __init__(self, market_data: Dict[str, Decimal], currency: Currency = Currency.USD):
- """
- Initialize with market swap rates
- market_data: Dict with tenor -> rate (e.g., {'2Y': 0.025, '5Y': 0.035})
- """
- self.market_data = market_data
- self.currency = currency
- self.curve_date = date.today()
- self._tenors = []
- self._rates = []
- self._maturities = []
- self._parse_market_data()
-
- def _parse_market_data(self):
- """Parse market data into tenors, maturities, and rates"""
- for tenor, rate in self.market_data.items():
- self._tenors.append(tenor)
- self._rates.append(rate)
-
- # Convert tenor to maturity in years
- if tenor.endswith('M'):
- months = int(tenor[:-1])
- maturity = Decimal(months) / Decimal('12')
- elif tenor.endswith('Y'):
- years = int(tenor[:-1])
- maturity = Decimal(years)
- else:
- raise ValueError(f"Invalid tenor format: {tenor}")
-
- self._maturities.append(maturity)
-
- # Sort by maturity
- sorted_data = sorted(zip(self._maturities, self._rates, self._tenors))
- self._maturities, self._rates, self._tenors = zip(*sorted_data)
- self._maturities = list(self._maturities)
- self._rates = list(self._rates)
- self._tenors = list(self._tenors)
-
- def get_swap_rate(self, maturity: Decimal) -> Decimal:
- """Get swap rate for given maturity using interpolation"""
- ValidationUtils.validate_positive(maturity, "Maturity")
-
- # Exact match
- if maturity in self._maturities:
- index = self._maturities.index(maturity)
- return self._rates[index]
-
- # Interpolation
- if maturity < self._maturities[0]:
- return self._rates[0]
-
- if maturity > self._maturities[-1]:
- return self._rates[-1]
-
- for i in range(len(self._maturities) - 1):
- if self._maturities[i] <= maturity <= self._maturities[i + 1]:
- return MathUtils.linear_interpolation(
- maturity,
- self._maturities[i], self._rates[i],
- self._maturities[i + 1], self._rates[i + 1]
- )
-
- return self._rates[0]
-
- def swap_spread(self, maturity: Decimal, treasury_curve: SpotCurve) -> Decimal:
- """Calculate swap spread over treasury curve"""
- swap_rate = self.get_swap_rate(maturity)
- treasury_rate = treasury_curve.get_rate(maturity)
- return swap_rate - treasury_rate
-
- def to_yield_curve(self) -> YieldCurve:
- """Convert to YieldCurve object"""
- return YieldCurve(
- curve_date=self.curve_date,
- maturities=self._maturities,
- rates=self._rates,
- currency=self.currency,
- curve_type="swap"
- )
-
-
-class BootstrappingEngine:
- """Bootstrap yield curves from market instruments"""
-
- @staticmethod
- def bootstrap_from_bonds(bonds: List[Bond], prices: List[Decimal],
- settlement_date: Optional[date] = None) -> SpotCurve:
- """Bootstrap spot curve from bond prices"""
- if len(bonds) != len(prices):
- raise ValueError("Number of bonds must equal number of prices")
-
- if settlement_date is None:
- settlement_date = date.today()
-
- # Sort bonds by maturity
- bond_price_pairs = list(zip(bonds, prices))
- bond_price_pairs.sort(key=lambda x: x[0].maturity_date)
-
- maturities = []
- spot_rates = []
-
- for bond, price in bond_price_pairs:
- # Calculate time to maturity
- maturity = DateUtils.calculate_day_count_fraction(
- settlement_date, bond.maturity_date, bond.day_count_convention
- )
-
- if bond.is_zero_coupon:
- # For zero-coupon bonds, directly calculate spot rate
- # price = face_value / (1 + r)^t
- # r = (face_value / price)^(1/t) - 1
- spot_rate = (bond.face_value / price) ** (Decimal('1') / maturity) - Decimal('1')
- else:
- # For coupon bonds, solve iteratively
- spot_rate = BootstrappingEngine._solve_coupon_bond_rate(
- bond, price, maturity, maturities, spot_rates
- )
-
- maturities.append(maturity)
- spot_rates.append(spot_rate)
-
- # Create yield curve
- yield_curve = YieldCurve(
- curve_date=settlement_date,
- maturities=maturities,
- rates=spot_rates,
- currency=bonds[0].currency if bonds else Currency.USD,
- curve_type="spot"
- )
-
- return SpotCurve(yield_curve)
-
- @staticmethod
- def _solve_coupon_bond_rate(bond: Bond, price: Decimal, maturity: Decimal,
- existing_maturities: List[Decimal], existing_rates: List[Decimal]) -> Decimal:
- """Solve for spot rate of coupon bond using existing curve"""
- from instruments import BondInstrument
-
- # Create temporary spot curve with existing rates
- if existing_maturities:
- temp_curve = YieldCurve(
- curve_date=date.today(),
- maturities=existing_maturities,
- rates=existing_rates,
- currency=bond.currency,
- curve_type="spot"
- )
- temp_spot_curve = SpotCurve(temp_curve)
- else:
- temp_spot_curve = None
-
- # Generate cash flows
- bond_instrument = BondInstrument(bond)
- cash_flows = bond_instrument.generate_cash_flows()
-
- # Define function to solve: PV of cash flows - market price = 0
- def pv_function(rate: Decimal) -> Decimal:
- total_pv = Decimal('0')
-
- for cf in cash_flows:
- cf_maturity = DateUtils.calculate_day_count_fraction(
- date.today(), cf.date, bond.day_count_convention
- )
-
- if cf_maturity < maturity:
- # Use existing curve for earlier cash flows
- if temp_spot_curve:
- discount_rate = temp_spot_curve.get_rate(cf_maturity)
- else:
- discount_rate = rate # Use current rate if no existing curve
- else:
- # Use the rate we're solving for
- discount_rate = rate
-
- pv = cf.amount / ((Decimal('1') + discount_rate) ** cf_maturity)
- total_pv += pv
-
- return total_pv - price
-
- # Derivative for Newton-Raphson
- def pv_derivative(rate: Decimal) -> Decimal:
- total_derivative = Decimal('0')
-
- for cf in cash_flows:
- cf_maturity = DateUtils.calculate_day_count_fraction(
- date.today(), cf.date, bond.day_count_convention
- )
-
- if cf_maturity >= maturity: # Only consider cash flows at this maturity
- derivative = -cf_maturity * cf.amount / ((Decimal('1') + rate) ** (cf_maturity + Decimal('1')))
- total_derivative += derivative
-
- return total_derivative
-
- # Solve using Newton-Raphson
- try:
- initial_guess = Decimal('0.05') # 5% initial guess
- spot_rate = MathUtils.newton_raphson(pv_function, pv_derivative, initial_guess)
- ValidationUtils.validate_yield(spot_rate, "Bootstrapped spot rate")
- return spot_rate
- except:
- # Fallback to bisection method
- return MathUtils.bisection_method(pv_function, Decimal('0.001'), Decimal('0.50'))
-
-
-class CurveAnalysis:
- """Yield curve analysis and metrics"""
-
- @staticmethod
- def curve_slope(curve: SpotCurve, short_maturity: Decimal = Decimal('2'),
- long_maturity: Decimal = Decimal('10')) -> Decimal:
- """Calculate curve slope between two maturities"""
- short_rate = curve.get_rate(short_maturity)
- long_rate = curve.get_rate(long_maturity)
- return long_rate - short_rate
-
- @staticmethod
- def curve_curvature(curve: SpotCurve, short_maturity: Decimal = Decimal('2'),
- medium_maturity: Decimal = Decimal('5'),
- long_maturity: Decimal = Decimal('10')) -> Decimal:
- """Calculate curve curvature (butterfly)"""
- short_rate = curve.get_rate(short_maturity)
- medium_rate = curve.get_rate(medium_maturity)
- long_rate = curve.get_rate(long_maturity)
-
- # Curvature = 2 * medium - short - long
- return Decimal('2') * medium_rate - short_rate - long_rate
-
- @staticmethod
- def level_slope_curvature_decomposition(curve: SpotCurve) -> Tuple[Decimal, Decimal, Decimal]:
- """Decompose curve into level, slope, and curvature factors"""
- # Use 2Y, 5Y, 10Y points for decomposition
- r2 = curve.get_rate(Decimal('2'))
- r5 = curve.get_rate(Decimal('5'))
- r10 = curve.get_rate(Decimal('10'))
-
- # Level: average of rates
- level = (r2 + r5 + r10) / Decimal('3')
-
- # Slope: 10Y - 2Y
- slope = r10 - r2
-
- # Curvature: butterfly
- curvature = Decimal('2') * r5 - r2 - r10
-
- return level, slope, curvature
-
- @staticmethod
- def duration_matched_curve_shift(curve: SpotCurve, target_duration: Decimal,
- shift_amount: Decimal) -> SpotCurve:
- """Apply duration-matched curve shift"""
- # Simplified implementation - apply parallel shift scaled by duration
- duration_scaling = target_duration / Decimal('5') # Normalize to 5-year duration
- scaled_shift = shift_amount * duration_scaling
-
- return curve.shift_curve(scaled_shift, "parallel")
-
-
-# Factory functions for common curve constructions
-def create_flat_curve(rate: Decimal, maturities: List[Decimal],
- currency: Currency = Currency.USD) -> SpotCurve:
- """Create flat yield curve with constant rate"""
- rates = [rate] * len(maturities)
-
- yield_curve = YieldCurve(
- curve_date=date.today(),
- maturities=maturities,
- rates=rates,
- currency=currency,
- curve_type="spot"
- )
-
- return SpotCurve(yield_curve)
-
-
-def create_upward_sloping_curve(short_rate: Decimal, long_rate: Decimal,
- maturities: List[Decimal],
- currency: Currency = Currency.USD) -> SpotCurve:
- """Create upward sloping yield curve"""
- if not maturities:
- raise ValueError("Maturities list cannot be empty")
-
- min_maturity = min(maturities)
- max_maturity = max(maturities)
-
- rates = []
- for maturity in maturities:
- # Linear interpolation between short and long rates
- rate = MathUtils.linear_interpolation(
- maturity, min_maturity, short_rate, max_maturity, long_rate
- )
- rates.append(rate)
-
- yield_curve = YieldCurve(
- curve_date=date.today(),
- maturities=maturities,
- rates=rates,
- currency=currency,
- curve_type="spot"
- )
-
- return SpotCurve(yield_curve)
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/capitalism_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/capitalism_agent_cli.py
new file mode 100644
index 000000000..c815df610
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/capitalism_agent_cli.py
@@ -0,0 +1,152 @@
+#!/usr/bin/env python3
+"""
+Capitalism Economic Agent - CLI Version
+For Node Editor integration
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any
+from capitalism_agent import CapitalismAgent
+from base_agent import EconomicData
+from datetime import datetime
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Execute Capitalism economic analysis
+
+ Args:
+ parameters: {
+ "gdp": 3.5,
+ "inflation": 2.5,
+ "unemployment": 4.5,
+ "interest_rate": 5.0,
+ "trade_balance": -2.0,
+ "government_spending": 35.0,
+ "tax_rate": 30.0,
+ "private_investment": 25.0,
+ "consumer_confidence": 70.0
+ }
+ inputs: Data from connected nodes (if any)
+
+ Returns:
+ Economic analysis from capitalist perspective
+ """
+ try:
+ agent = CapitalismAgent()
+
+ # Extract parameters with defaults
+ gdp = float(parameters.get("gdp", 3.0))
+ inflation = float(parameters.get("inflation", 2.5))
+ unemployment = float(parameters.get("unemployment", 5.0))
+ interest_rate = float(parameters.get("interest_rate", 5.0))
+ trade_balance = float(parameters.get("trade_balance", 0.0))
+ government_spending = float(parameters.get("government_spending", 35.0))
+ tax_rate = float(parameters.get("tax_rate", 30.0))
+ private_investment = float(parameters.get("private_investment", 20.0))
+ consumer_confidence = float(parameters.get("consumer_confidence", 65.0))
+
+ # Build EconomicData
+ economic_data = EconomicData(
+ gdp=gdp,
+ inflation=inflation,
+ unemployment=unemployment,
+ interest_rate=interest_rate,
+ trade_balance=trade_balance,
+ government_spending=government_spending,
+ tax_rate=tax_rate,
+ private_investment=private_investment,
+ consumer_confidence=consumer_confidence,
+ timestamp=datetime.now()
+ )
+
+ # Perform analysis
+ analysis = agent.analyze_economy(economic_data)
+ recommendations = agent.get_policy_recommendations(economic_data, analysis)
+
+ # Format recommendations
+ formatted_recs = []
+ for rec in recommendations:
+ formatted_recs.append({
+ "title": rec.title,
+ "description": rec.description,
+ "priority": rec.priority,
+ "expected_impact": rec.expected_impact,
+ "implementation_time": rec.implementation_time,
+ "risk_level": rec.risk_level
+ })
+
+ # Build comprehensive response
+ response = {
+ "success": True,
+ "agent": "capitalism",
+ "ideology": "Free Market Capitalism",
+ "analysis": analysis,
+ "policy_recommendations": formatted_recs,
+ "input_data": {
+ "gdp_growth": gdp,
+ "inflation_rate": inflation,
+ "unemployment_rate": unemployment,
+ "interest_rate": interest_rate,
+ "trade_balance": trade_balance,
+ "government_spending": government_spending,
+ "tax_rate": tax_rate,
+ "private_investment": private_investment,
+ "consumer_confidence": consumer_confidence
+ }
+ }
+
+ # Include input context if available
+ if inputs and isinstance(inputs, dict):
+ mediated_context = inputs.get("mediated_analysis")
+ if mediated_context:
+ response["used_previous_context"] = True
+ response["previous_context"] = mediated_context[:200] + "..."
+
+ return response
+
+ except Exception as e:
+ return {
+ "success": False,
+ "error": str(e),
+ "agent": "capitalism"
+ }
+
+def main():
+ """CLI entry point"""
+ parser = argparse.ArgumentParser(description='Capitalism Economic Agent')
+ parser.add_argument('--parameters', type=str, required=True, help='JSON string of parameters')
+ parser.add_argument('--inputs', type=str, required=True, help='JSON string of inputs')
+
+ args = parser.parse_args()
+
+ try:
+ parameters = json.loads(args.parameters)
+ inputs = json.loads(args.inputs)
+
+ result = execute_agent(parameters, inputs)
+
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+
+ except json.JSONDecodeError as e:
+ error_result = {
+ "success": False,
+ "error": f"JSON parse error: {str(e)}",
+ "agent": "capitalism"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+ except Exception as e:
+ error_result = {
+ "success": False,
+ "error": f"Agent execution error: {str(e)}",
+ "agent": "capitalism"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/keynesian_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/keynesian_agent_cli.py
new file mode 100644
index 000000000..416c8ae77
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/keynesian_agent_cli.py
@@ -0,0 +1,142 @@
+#!/usr/bin/env python3
+"""
+Keynesian Economic Agent - CLI Version
+For Node Editor integration
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any
+from keynesian_agent import KeynesianAgent
+from base_agent import EconomicData
+from datetime import datetime
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Execute Keynesian economic analysis
+
+ Args:
+ parameters: Economic indicators
+ inputs: Data from connected nodes (if any)
+
+ Returns:
+ Economic analysis from Keynesian perspective
+ """
+ try:
+ agent = KeynesianAgent()
+
+ # Extract parameters with defaults
+ gdp = float(parameters.get("gdp", 3.0))
+ inflation = float(parameters.get("inflation", 2.5))
+ unemployment = float(parameters.get("unemployment", 5.0))
+ interest_rate = float(parameters.get("interest_rate", 5.0))
+ trade_balance = float(parameters.get("trade_balance", 0.0))
+ government_spending = float(parameters.get("government_spending", 35.0))
+ tax_rate = float(parameters.get("tax_rate", 30.0))
+ private_investment = float(parameters.get("private_investment", 20.0))
+ consumer_confidence = float(parameters.get("consumer_confidence", 65.0))
+
+ # Build EconomicData
+ economic_data = EconomicData(
+ gdp=gdp,
+ inflation=inflation,
+ unemployment=unemployment,
+ interest_rate=interest_rate,
+ trade_balance=trade_balance,
+ government_spending=government_spending,
+ tax_rate=tax_rate,
+ private_investment=private_investment,
+ consumer_confidence=consumer_confidence,
+ timestamp=datetime.now()
+ )
+
+ # Perform analysis
+ analysis = agent.analyze_economy(economic_data)
+ recommendations = agent.get_policy_recommendations(economic_data, analysis)
+
+ # Format recommendations
+ formatted_recs = []
+ for rec in recommendations:
+ formatted_recs.append({
+ "title": rec.title,
+ "description": rec.description,
+ "priority": rec.priority,
+ "expected_impact": rec.expected_impact,
+ "implementation_time": rec.implementation_time,
+ "risk_level": rec.risk_level
+ })
+
+ # Build comprehensive response
+ response = {
+ "success": True,
+ "agent": "keynesian",
+ "ideology": "Keynesian Economics",
+ "analysis": analysis,
+ "policy_recommendations": formatted_recs,
+ "input_data": {
+ "gdp_growth": gdp,
+ "inflation_rate": inflation,
+ "unemployment_rate": unemployment,
+ "interest_rate": interest_rate,
+ "trade_balance": trade_balance,
+ "government_spending": government_spending,
+ "tax_rate": tax_rate,
+ "private_investment": private_investment,
+ "consumer_confidence": consumer_confidence
+ }
+ }
+
+ # Include input context if available
+ if inputs and isinstance(inputs, dict):
+ mediated_context = inputs.get("mediated_analysis")
+ if mediated_context:
+ response["used_previous_context"] = True
+ response["previous_context"] = mediated_context[:200] + "..."
+
+ return response
+
+ except Exception as e:
+ return {
+ "success": False,
+ "error": str(e),
+ "agent": "keynesian"
+ }
+
+def main():
+ """CLI entry point"""
+ parser = argparse.ArgumentParser(description='Keynesian Economic Agent')
+ parser.add_argument('--parameters', type=str, required=True, help='JSON string of parameters')
+ parser.add_argument('--inputs', type=str, required=True, help='JSON string of inputs')
+
+ args = parser.parse_args()
+
+ try:
+ parameters = json.loads(args.parameters)
+ inputs = json.loads(args.inputs)
+
+ result = execute_agent(parameters, inputs)
+
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+
+ except json.JSONDecodeError as e:
+ error_result = {
+ "success": False,
+ "error": f"JSON parse error: {str(e)}",
+ "agent": "keynesian"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+ except Exception as e:
+ error_result = {
+ "success": False,
+ "error": f"Agent execution error: {str(e)}",
+ "agent": "keynesian"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/mercantilist_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/mercantilist_agent_cli.py
new file mode 100644
index 000000000..7750cc92e
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/mercantilist_agent_cli.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""
+Mercantilist Economic Agent - CLI Version
+For Node Editor integration
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any
+from mercantilist_agent import MercantilistAgent
+from base_agent import EconomicData
+from datetime import datetime
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Mercantilist economic analysis"""
+ try:
+ agent = MercantilistAgent()
+
+ # Extract parameters with defaults
+ gdp = float(parameters.get("gdp", 3.0))
+ inflation = float(parameters.get("inflation", 2.5))
+ unemployment = float(parameters.get("unemployment", 5.0))
+ interest_rate = float(parameters.get("interest_rate", 5.0))
+ trade_balance = float(parameters.get("trade_balance", 0.0))
+ government_spending = float(parameters.get("government_spending", 35.0))
+ tax_rate = float(parameters.get("tax_rate", 30.0))
+ private_investment = float(parameters.get("private_investment", 20.0))
+ consumer_confidence = float(parameters.get("consumer_confidence", 65.0))
+
+ economic_data = EconomicData(
+ gdp=gdp, inflation=inflation, unemployment=unemployment,
+ interest_rate=interest_rate, trade_balance=trade_balance,
+ government_spending=government_spending, tax_rate=tax_rate,
+ private_investment=private_investment,
+ consumer_confidence=consumer_confidence,
+ timestamp=datetime.now()
+ )
+
+ analysis = agent.analyze_economy(economic_data)
+ recommendations = agent.get_policy_recommendations(economic_data, analysis)
+
+ formatted_recs = [{
+ "title": rec.title, "description": rec.description,
+ "priority": rec.priority, "expected_impact": rec.expected_impact,
+ "implementation_time": rec.implementation_time, "risk_level": rec.risk_level
+ } for rec in recommendations]
+
+ response = {
+ "success": True,
+ "agent": "mercantilist",
+ "ideology": "Mercantilism",
+ "analysis": analysis,
+ "policy_recommendations": formatted_recs,
+ "input_data": {
+ "gdp_growth": gdp, "inflation_rate": inflation,
+ "unemployment_rate": unemployment, "interest_rate": interest_rate,
+ "trade_balance": trade_balance, "government_spending": government_spending,
+ "tax_rate": tax_rate, "private_investment": private_investment,
+ "consumer_confidence": consumer_confidence
+ }
+ }
+
+ if inputs and isinstance(inputs, dict):
+ mediated_context = inputs.get("mediated_analysis")
+ if mediated_context:
+ response["used_previous_context"] = True
+ response["previous_context"] = mediated_context[:200] + "..."
+
+ return response
+
+ except Exception as e:
+ return {"success": False, "error": str(e), "agent": "mercantilist"}
+
+def main():
+ parser = argparse.ArgumentParser(description='Mercantilist Economic Agent')
+ parser.add_argument('--parameters', type=str, required=True)
+ parser.add_argument('--inputs', type=str, required=True)
+ args = parser.parse_args()
+
+ try:
+ result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+ except Exception as e:
+ print(json.dumps({"success": False, "error": str(e), "agent": "mercantilist"}), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/mixed_economy_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/mixed_economy_agent_cli.py
new file mode 100644
index 000000000..f62caf0ca
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/mixed_economy_agent_cli.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""
+Mixed Economy Agent - CLI Version
+For Node Editor integration
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any
+from mixed_economy_agent import MixedEconomyAgent
+from base_agent import EconomicData
+from datetime import datetime
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Mixed Economy analysis"""
+ try:
+ agent = MixedEconomyAgent()
+
+ # Extract parameters with defaults
+ gdp = float(parameters.get("gdp", 3.0))
+ inflation = float(parameters.get("inflation", 2.5))
+ unemployment = float(parameters.get("unemployment", 5.0))
+ interest_rate = float(parameters.get("interest_rate", 5.0))
+ trade_balance = float(parameters.get("trade_balance", 0.0))
+ government_spending = float(parameters.get("government_spending", 35.0))
+ tax_rate = float(parameters.get("tax_rate", 30.0))
+ private_investment = float(parameters.get("private_investment", 20.0))
+ consumer_confidence = float(parameters.get("consumer_confidence", 65.0))
+
+ economic_data = EconomicData(
+ gdp=gdp, inflation=inflation, unemployment=unemployment,
+ interest_rate=interest_rate, trade_balance=trade_balance,
+ government_spending=government_spending, tax_rate=tax_rate,
+ private_investment=private_investment,
+ consumer_confidence=consumer_confidence,
+ timestamp=datetime.now()
+ )
+
+ analysis = agent.analyze_economy(economic_data)
+ recommendations = agent.get_policy_recommendations(economic_data, analysis)
+
+ formatted_recs = [{
+ "title": rec.title, "description": rec.description,
+ "priority": rec.priority, "expected_impact": rec.expected_impact,
+ "implementation_time": rec.implementation_time, "risk_level": rec.risk_level
+ } for rec in recommendations]
+
+ response = {
+ "success": True,
+ "agent": "mixed_economy",
+ "ideology": "Mixed Economy",
+ "analysis": analysis,
+ "policy_recommendations": formatted_recs,
+ "input_data": {
+ "gdp_growth": gdp, "inflation_rate": inflation,
+ "unemployment_rate": unemployment, "interest_rate": interest_rate,
+ "trade_balance": trade_balance, "government_spending": government_spending,
+ "tax_rate": tax_rate, "private_investment": private_investment,
+ "consumer_confidence": consumer_confidence
+ }
+ }
+
+ if inputs and isinstance(inputs, dict):
+ mediated_context = inputs.get("mediated_analysis")
+ if mediated_context:
+ response["used_previous_context"] = True
+ response["previous_context"] = mediated_context[:200] + "..."
+
+ return response
+
+ except Exception as e:
+ return {"success": False, "error": str(e), "agent": "mixed_economy"}
+
+def main():
+ parser = argparse.ArgumentParser(description='Mixed Economy Agent')
+ parser.add_argument('--parameters', type=str, required=True)
+ parser.add_argument('--inputs', type=str, required=True)
+ args = parser.parse_args()
+
+ try:
+ result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+ except Exception as e:
+ print(json.dumps({"success": False, "error": str(e), "agent": "mixed_economy"}), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/neoliberal_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/neoliberal_agent_cli.py
new file mode 100644
index 000000000..12a345b3d
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/neoliberal_agent_cli.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""
+Neoliberal Economic Agent - CLI Version
+For Node Editor integration
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any
+from neoliberal_agent import NeoliberalAgent
+from base_agent import EconomicData
+from datetime import datetime
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Neoliberal economic analysis"""
+ try:
+ agent = NeoliberalAgent()
+
+ # Extract parameters with defaults
+ gdp = float(parameters.get("gdp", 3.0))
+ inflation = float(parameters.get("inflation", 2.5))
+ unemployment = float(parameters.get("unemployment", 5.0))
+ interest_rate = float(parameters.get("interest_rate", 5.0))
+ trade_balance = float(parameters.get("trade_balance", 0.0))
+ government_spending = float(parameters.get("government_spending", 35.0))
+ tax_rate = float(parameters.get("tax_rate", 30.0))
+ private_investment = float(parameters.get("private_investment", 20.0))
+ consumer_confidence = float(parameters.get("consumer_confidence", 65.0))
+
+ economic_data = EconomicData(
+ gdp=gdp, inflation=inflation, unemployment=unemployment,
+ interest_rate=interest_rate, trade_balance=trade_balance,
+ government_spending=government_spending, tax_rate=tax_rate,
+ private_investment=private_investment,
+ consumer_confidence=consumer_confidence,
+ timestamp=datetime.now()
+ )
+
+ analysis = agent.analyze_economy(economic_data)
+ recommendations = agent.get_policy_recommendations(economic_data, analysis)
+
+ formatted_recs = [{
+ "title": rec.title, "description": rec.description,
+ "priority": rec.priority, "expected_impact": rec.expected_impact,
+ "implementation_time": rec.implementation_time, "risk_level": rec.risk_level
+ } for rec in recommendations]
+
+ response = {
+ "success": True,
+ "agent": "neoliberal",
+ "ideology": "Neoliberalism",
+ "analysis": analysis,
+ "policy_recommendations": formatted_recs,
+ "input_data": {
+ "gdp_growth": gdp, "inflation_rate": inflation,
+ "unemployment_rate": unemployment, "interest_rate": interest_rate,
+ "trade_balance": trade_balance, "government_spending": government_spending,
+ "tax_rate": tax_rate, "private_investment": private_investment,
+ "consumer_confidence": consumer_confidence
+ }
+ }
+
+ if inputs and isinstance(inputs, dict):
+ mediated_context = inputs.get("mediated_analysis")
+ if mediated_context:
+ response["used_previous_context"] = True
+ response["previous_context"] = mediated_context[:200] + "..."
+
+ return response
+
+ except Exception as e:
+ return {"success": False, "error": str(e), "agent": "neoliberal"}
+
+def main():
+ parser = argparse.ArgumentParser(description='Neoliberal Economic Agent')
+ parser.add_argument('--parameters', type=str, required=True)
+ parser.add_argument('--inputs', type=str, required=True)
+ args = parser.parse_args()
+
+ try:
+ result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+ except Exception as e:
+ print(json.dumps({"success": False, "error": str(e), "agent": "neoliberal"}), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/socialism_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/socialism_agent_cli.py
new file mode 100644
index 000000000..2b6a80c72
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/socialism_agent_cli.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""
+Socialism Economic Agent - CLI Version
+For Node Editor integration
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any
+from socialism_agent import SocialismAgent
+from base_agent import EconomicData
+from datetime import datetime
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Socialism economic analysis"""
+ try:
+ agent = SocialismAgent()
+
+ # Extract parameters with defaults
+ gdp = float(parameters.get("gdp", 3.0))
+ inflation = float(parameters.get("inflation", 2.5))
+ unemployment = float(parameters.get("unemployment", 5.0))
+ interest_rate = float(parameters.get("interest_rate", 5.0))
+ trade_balance = float(parameters.get("trade_balance", 0.0))
+ government_spending = float(parameters.get("government_spending", 35.0))
+ tax_rate = float(parameters.get("tax_rate", 30.0))
+ private_investment = float(parameters.get("private_investment", 20.0))
+ consumer_confidence = float(parameters.get("consumer_confidence", 65.0))
+
+ economic_data = EconomicData(
+ gdp=gdp, inflation=inflation, unemployment=unemployment,
+ interest_rate=interest_rate, trade_balance=trade_balance,
+ government_spending=government_spending, tax_rate=tax_rate,
+ private_investment=private_investment,
+ consumer_confidence=consumer_confidence,
+ timestamp=datetime.now()
+ )
+
+ analysis = agent.analyze_economy(economic_data)
+ recommendations = agent.get_policy_recommendations(economic_data, analysis)
+
+ formatted_recs = [{
+ "title": rec.title, "description": rec.description,
+ "priority": rec.priority, "expected_impact": rec.expected_impact,
+ "implementation_time": rec.implementation_time, "risk_level": rec.risk_level
+ } for rec in recommendations]
+
+ response = {
+ "success": True,
+ "agent": "socialism",
+ "ideology": "Democratic Socialism",
+ "analysis": analysis,
+ "policy_recommendations": formatted_recs,
+ "input_data": {
+ "gdp_growth": gdp, "inflation_rate": inflation,
+ "unemployment_rate": unemployment, "interest_rate": interest_rate,
+ "trade_balance": trade_balance, "government_spending": government_spending,
+ "tax_rate": tax_rate, "private_investment": private_investment,
+ "consumer_confidence": consumer_confidence
+ }
+ }
+
+ if inputs and isinstance(inputs, dict):
+ mediated_context = inputs.get("mediated_analysis")
+ if mediated_context:
+ response["used_previous_context"] = True
+ response["previous_context"] = mediated_context[:200] + "..."
+
+ return response
+
+ except Exception as e:
+ return {"success": False, "error": str(e), "agent": "socialism"}
+
+def main():
+ parser = argparse.ArgumentParser(description='Socialism Economic Agent')
+ parser.add_argument('--parameters', type=str, required=True)
+ parser.add_argument('--inputs', type=str, required=True)
+ args = parser.parse_args()
+
+ try:
+ result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+ except Exception as e:
+ print(json.dumps({"success": False, "error": str(e), "agent": "socialism"}), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/README.md b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/README.md
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/README.md
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/README.md
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/geographic_modules/geographic_constraints.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/geographic_modules/geographic_constraints.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/geographic_modules/geographic_constraints.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/geographic_modules/geographic_constraints.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/geographic_modules/historical_patterns.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/geographic_modules/historical_patterns.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/geographic_modules/historical_patterns.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/geographic_modules/historical_patterns.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/geographic_modules/strategic_imperatives.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/geographic_modules/strategic_imperatives.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/geographic_modules/strategic_imperatives.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/geographic_modules/strategic_imperatives.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/africa_geography_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/africa_geography_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/africa_geography_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/africa_geography_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/arctic_geography_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/arctic_geography_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/arctic_geography_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/arctic_geography_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/china_geography_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/china_geography_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/china_geography_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/china_geography_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/europe_geography_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/europe_geography_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/europe_geography_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/europe_geography_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/india_pakistan_geography_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/india_pakistan_geography_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/india_pakistan_geography_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/india_pakistan_geography_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/japan_korea_geography_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/japan_korea_geography_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/japan_korea_geography_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/japan_korea_geography_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/latin_america_geography_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/latin_america_geography_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/latin_america_geography_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/latin_america_geography_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/middle_east_geography_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/middle_east_geography_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/middle_east_geography_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/middle_east_geography_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/russia_geography_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/russia_geography_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/russia_geography_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/russia_geography_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/usa_geography_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/usa_geography_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/usa_geography_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/region_agents/usa_geography_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/test_agents/run_all_tests.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/test_agents/run_all_tests.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/test_agents/run_all_tests.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/test_agents/run_all_tests.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/test_agents/test_russia_geography.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/test_agents/test_russia_geography.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/src-tauri/resources/scripts/Agents/GeopoliticsAgents/PrisonersOfGeographyAgents/test_agents/test_russia_geography.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/PrisonersOfGeographyAgents/test_agents/test_russia_geography.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/README.md b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/README.md
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/README.md
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/README.md
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/civilization_agents/american_world_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/american_world_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/civilization_agents/american_world_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/american_world_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/civilization_agents/balance_power_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/balance_power_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/civilization_agents/balance_power_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/balance_power_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/civilization_agents/chinese_world_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/chinese_world_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/civilization_agents/chinese_world_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/chinese_world_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/civilization_agents/islamic_world_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/islamic_world_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/civilization_agents/islamic_world_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/islamic_world_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/civilization_agents/nuclear_order_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/nuclear_order_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/civilization_agents/nuclear_order_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/nuclear_order_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/civilization_agents/westphalian_europe_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/westphalian_europe_agent.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/civilization_agents/westphalian_europe_agent.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/civilization_agents/westphalian_europe_agent.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/diplomatic_modules/balance_power_calculations.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/diplomatic_modules/balance_power_calculations.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/diplomatic_modules/balance_power_calculations.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/diplomatic_modules/balance_power_calculations.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/diplomatic_modules/realpolitik_analysis.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/diplomatic_modules/realpolitik_analysis.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/diplomatic_modules/realpolitik_analysis.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/diplomatic_modules/realpolitik_analysis.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/test_agents/islamic_order_test.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/test_agents/islamic_order_test.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/test_agents/islamic_order_test.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/test_agents/islamic_order_test.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/test_agents/westphalian_order_test.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/test_agents/westphalian_order_test.py
similarity index 100%
rename from fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/test_agents/westphalian_order_test.py
rename to fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/World_Order_Agents/test_agents/westphalian_order_test.py
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/geopolitics_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/geopolitics_agent_cli.py
new file mode 100644
index 000000000..4e4e3830a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/GeopoliticsAgents/geopolitics_agent_cli.py
@@ -0,0 +1,300 @@
+#!/usr/bin/env python3
+"""
+Geopolitics Agent CLI - Unified Interface
+Analyzes events through book-based geopolitical frameworks
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any, List
+import random
+
+# Geopolitical Framework Definitions
+
+GEOGRAPHY_AGENTS = {
+ "russia_geography": {
+ "name": "Russia Geography",
+ "framework": "Prisoners of Geography (Tim Marshall)",
+ "focus": "North European Plain vulnerability, warm-water ports, vast territory",
+ "constraints": ["flat_invasion_route", "ice_bound_ports", "vast_territory", "limited_arable_land"]
+ },
+ "china_geography": {
+ "name": "China Geography",
+ "framework": "Prisoners of Geography (Tim Marshall)",
+ "focus": "Maritime vulnerability, unity challenges, Himalayan barrier",
+ "constraints": ["sea_lane_dependence", "regional_fragmentation", "mountain_barriers", "desert_isolation"]
+ },
+ "usa_geography": {
+ "name": "USA Geography",
+ "framework": "Prisoners of Geography (Tim Marshall)",
+ "focus": "Geographic advantages, natural moats, resource abundance",
+ "constraints": ["atlantic_pacific_protection", "fertile_heartland", "navigable_rivers", "weak_neighbors"]
+ },
+ "europe_geography": {
+ "name": "Europe Geography",
+ "framework": "Prisoners of Geography (Tim Marshall)",
+ "focus": "Fragmentation vs integration, mountain/river barriers",
+ "constraints": ["geographic_fragmentation", "multiple_powers", "resource_distribution", "access_barriers"]
+ },
+ "middle_east_geography": {
+ "name": "Middle East Geography",
+ "framework": "Prisoners of Geography (Tim Marshall)",
+ "focus": "Desert geography, resource concentration, artificial borders",
+ "constraints": ["desert_isolation", "resource_curse", "colonial_borders", "water_scarcity"]
+ }
+}
+
+WORLD_ORDER_AGENTS = {
+ "american_world": {
+ "name": "American World Order",
+ "framework": "World Order (Henry Kissinger)",
+ "focus": "Liberal internationalism, democratic values, exceptionalism",
+ "principles": ["universal_values", "democratic_promotion", "rule_based_order", "alliance_systems"]
+ },
+ "chinese_world": {
+ "name": "Chinese World Order",
+ "framework": "World Order (Henry Kissinger)",
+ "focus": "Middle Kingdom centrality, hierarchical relationships, tributary system",
+ "principles": ["hierarchical_order", "cultural_superiority", "harmonious_relations", "regional_leadership"]
+ },
+ "balance_power": {
+ "name": "Balance of Power",
+ "framework": "World Order (Henry Kissinger)",
+ "focus": "Equilibrium maintenance, power transitions, realpolitik",
+ "principles": ["power_equilibrium", "prevent_hegemony", "flexible_alliances", "pragmatic_diplomacy"]
+ },
+ "islamic_world": {
+ "name": "Islamic World Order",
+ "framework": "World Order (Henry Kissinger)",
+ "focus": "Ummah unity, Sharia-based governance, historical caliphate legacy",
+ "principles": ["religious_unity", "sharia_governance", "anti_colonialism", "pan_islamic_identity"]
+ },
+ "nuclear_order": {
+ "name": "Nuclear Order",
+ "framework": "World Order (Henry Kissinger)",
+ "focus": "Deterrence theory, arms control, nuclear diplomacy",
+ "principles": ["mutual_destruction", "deterrence_stability", "arms_control", "proliferation_prevention"]
+ }
+}
+
+CHESSBOARD_AGENTS = {
+ "eurasian_balkans": {
+ "name": "Eurasian Balkans",
+ "framework": "Grand Chessboard (Brzezinski)",
+ "focus": "Pivotal region between powers, strategic instability",
+ "characteristics": ["geopolitical_rivalry", "ethnic_complexity", "resource_competition", "power_vacuum"]
+ },
+ "democratic_bridgehead": {
+ "name": "Democratic Bridgehead",
+ "framework": "Grand Chessboard (Brzezinski)",
+ "focus": "Western influence projection into Eurasia",
+ "characteristics": ["democratic_values", "western_integration", "geopolitical_anchor", "reform_catalyst"]
+ },
+ "far_eastern_anchor": {
+ "name": "Far Eastern Anchor",
+ "framework": "Grand Chessboard (Brzezinski)",
+ "focus": "US-Japan alliance as Pacific stability pillar",
+ "characteristics": ["alliance_strength", "regional_stability", "power_projection", "economic_integration"]
+ }
+}
+
+def analyze_geography_framework(agent_type: str, event_data: Dict[str, Any], previous_context: str = None) -> Dict[str, Any]:
+ """Analyze through Tim Marshall's geographic determinism"""
+
+ agent_info = GEOGRAPHY_AGENTS.get(agent_type, {})
+ constraints = agent_info.get("constraints", [])
+
+ random.seed(sum(ord(c) for c in event_data.get("event", "default")))
+
+ # Simulate geographic constraint analysis
+ constraint_scores = {constraint: random.uniform(0.4, 0.9) for constraint in constraints}
+ total_constraint = sum(constraint_scores.values()) / len(constraint_scores) if constraint_scores else 0.5
+
+ geographic_determinism_score = random.uniform(0.65, 0.95)
+ strategic_imperative_score = random.uniform(0.60, 0.90)
+
+ context_note = f"\n\n🔗 Building on Previous Context:\n{previous_context[:300]}..." if previous_context else ""
+
+ return {
+ "agent": agent_info.get("name"),
+ "framework": agent_info.get("framework"),
+ "focus_area": agent_info.get("focus"),
+ "analysis": f"""
+{agent_info.get('name')} Geographic Analysis
+{context_note}
+
+📍 Geographic Determinism Framework: {geographic_determinism_score:.1%} compliance
+
+Geographic Constraints:
+{chr(10).join(f" • {constraint.replace('_', ' ').title()}: {score:.1%} influence" for constraint, score in constraint_scores.items())}
+
+Strategic Imperatives (Marshall's Core Thesis):
+ ✓ Geographic constraints DETERMINE foreign policy choices
+ ✓ Historical patterns repeat due to immutable geography
+ ✓ Strategic behavior follows geographic logic, not ideology
+
+Overall Constraint Level: {total_constraint:.1%}
+Strategic Imperative Strength: {strategic_imperative_score:.1%}
+
+"Geography is the mother of strategy" - Tim Marshall
+ """.strip(),
+ "geographic_determinism_score": round(geographic_determinism_score, 3),
+ "constraint_analysis": constraint_scores,
+ "strategic_imperative_score": round(strategic_imperative_score, 3),
+ "framework_compliance": round((geographic_determinism_score + strategic_imperative_score) / 2, 3)
+ }
+
+def analyze_world_order_framework(agent_type: str, event_data: Dict[str, Any], previous_context: str = None) -> Dict[str, Any]:
+ """Analyze through Kissinger's world order framework"""
+
+ agent_info = WORLD_ORDER_AGENTS.get(agent_type, {})
+ principles = agent_info.get("principles", [])
+
+ random.seed(sum(ord(c) for c in event_data.get("event", "default")))
+
+ principle_scores = {principle: random.uniform(0.5, 0.95) for principle in principles}
+ realpolitik_score = random.uniform(0.65, 0.92)
+ balance_of_power_score = random.uniform(0.60, 0.88)
+
+ context_note = f"\n\n🔗 Building on Previous Context:\n{previous_context[:300]}..." if previous_context else ""
+
+ return {
+ "agent": agent_info.get("name"),
+ "framework": agent_info.get("framework"),
+ "focus_area": agent_info.get("focus"),
+ "analysis": f"""
+{agent_info.get('name')} Order Analysis
+{context_note}
+
+🌐 Kissinger World Order Framework: {realpolitik_score:.1%} compliance
+
+Civilizational Principles:
+{chr(10).join(f" • {principle.replace('_', ' ').title()}: {score:.1%} strength" for principle, score in principle_scores.items())}
+
+Realpolitik Analysis:
+ ✓ Balance of power considerations central to order
+ ✓ Historical continuity from civilizational traditions
+ ✓ Diplomatic practice reflects cultural worldview
+
+Realpolitik Score: {realpolitik_score:.1%}
+Balance of Power Score: {balance_of_power_score:.1%}
+
+"The test of policy is how it ends, not how it begins" - Henry Kissinger
+ """.strip(),
+ "realpolitik_score": round(realpolitik_score, 3),
+ "principle_analysis": principle_scores,
+ "balance_of_power_score": round(balance_of_power_score, 3),
+ "framework_compliance": round((realpolitik_score + balance_of_power_score) / 2, 3)
+ }
+
+def analyze_chessboard_framework(agent_type: str, event_data: Dict[str, Any], previous_context: str = None) -> Dict[str, Any]:
+ """Analyze through Brzezinski's grand chessboard framework"""
+
+ agent_info = CHESSBOARD_AGENTS.get(agent_type, {})
+ characteristics = agent_info.get("characteristics", [])
+
+ random.seed(sum(ord(c) for c in event_data.get("event", "default")))
+
+ char_scores = {char: random.uniform(0.55, 0.90) for char in characteristics}
+ geostrategic_score = random.uniform(0.65, 0.93)
+ eurasian_centrality_score = random.uniform(0.60, 0.88)
+
+ context_note = f"\n\n🔗 Building on Previous Context:\n{previous_context[:300]}..." if previous_context else ""
+
+ return {
+ "agent": agent_info.get("name"),
+ "framework": agent_info.get("framework"),
+ "focus_area": agent_info.get("focus"),
+ "analysis": f"""
+{agent_info.get('name')} Geostrategic Analysis
+{context_note}
+
+♟️ Brzezinski Grand Chessboard Framework: {geostrategic_score:.1%} compliance
+
+Strategic Characteristics:
+{chr(10).join(f" • {char.replace('_', ' ').title()}: {score:.1%} relevance" for char, score in char_scores.items())}
+
+Eurasian Pivotal Analysis:
+ ✓ Geographic centrality to global power distribution
+ ✓ Resource concentration and transit importance
+ ✓ Multi-power competition and influence projection
+
+Geostrategic Importance: {geostrategic_score:.1%}
+Eurasian Centrality: {eurasian_centrality_score:.1%}
+
+"Eurasia is the chessboard on which the struggle for global primacy continues" - Zbigniew Brzezinski
+ """.strip(),
+ "geostrategic_score": round(geostrategic_score, 3),
+ "characteristic_analysis": char_scores,
+ "eurasian_centrality_score": round(eurasian_centrality_score, 3),
+ "framework_compliance": round((geostrategic_score + eurasian_centrality_score) / 2, 3)
+ }
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Main geopolitics agent execution"""
+ try:
+ agent_type = parameters.get("agent_type", "russia_geography")
+ event = parameters.get("event", "Current geopolitical situation")
+ framework = parameters.get("framework", "auto") # auto, geography, world_order, chessboard
+
+ event_data = {"event": event}
+
+ # Extract mediated context
+ mediated_context = None
+ if inputs and isinstance(inputs, dict):
+ mediated_context = inputs.get("mediated_analysis")
+
+ # Auto-detect framework if needed
+ if framework == "auto":
+ if agent_type in GEOGRAPHY_AGENTS:
+ framework = "geography"
+ elif agent_type in WORLD_ORDER_AGENTS:
+ framework = "world_order"
+ elif agent_type in CHESSBOARD_AGENTS:
+ framework = "chessboard"
+ else:
+ framework = "geography" # default
+
+ # Route to appropriate framework analyzer
+ if framework == "geography":
+ result = analyze_geography_framework(agent_type, event_data, mediated_context)
+ elif framework == "world_order":
+ result = analyze_world_order_framework(agent_type, event_data, mediated_context)
+ elif framework == "chessboard":
+ result = analyze_chessboard_framework(agent_type, event_data, mediated_context)
+ else:
+ return {"success": False, "error": f"Unknown framework: {framework}"}
+
+ response = {
+ "success": True,
+ "agent_type": agent_type,
+ "framework": framework,
+ "event_analyzed": event,
+ **result
+ }
+
+ if mediated_context:
+ response["used_previous_context"] = True
+
+ return response
+
+ except Exception as e:
+ return {"success": False, "error": str(e), "agent": "geopolitics"}
+
+def main():
+ parser = argparse.ArgumentParser(description='Geopolitics Agent - Book-Based Analysis')
+ parser.add_argument('--parameters', type=str, required=True)
+ parser.add_argument('--inputs', type=str, required=True)
+ args = parser.parse_args()
+
+ try:
+ result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+ except Exception as e:
+ print(json.dumps({"success": False, "error": str(e), "agent": "geopolitics"}), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/benjamin_graham_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/benjamin_graham_agent_cli.py
new file mode 100644
index 000000000..c216588c1
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/benjamin_graham_agent_cli.py
@@ -0,0 +1,172 @@
+#!/usr/bin/env python3
+"""
+Benjamin Graham Agent - CLI Version
+Deep value investing with margin of safety
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any, List
+
+def analyze_stock_graham_style(ticker: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Benjamin Graham-style deep value analysis
+ Focus: Intrinsic value, margin of safety, quantitative metrics
+ """
+ import random
+
+ ticker_hash = sum(ord(c) for c in ticker)
+ random.seed(ticker_hash + 2)
+
+ # Graham's quantitative criteria
+ earnings_stability_score = random.uniform(5.5, 9.0)
+ dividend_record_score = random.uniform(6.0, 9.5)
+ earnings_growth_score = random.uniform(5.0, 8.5)
+ pe_ratio_score = random.uniform(4.0, 9.0)
+ asset_backing_score = random.uniform(6.5, 9.5)
+ margin_of_safety_score = random.uniform(5.0, 9.0)
+
+ total_score = (
+ earnings_stability_score * 0.20 +
+ dividend_record_score * 0.15 +
+ earnings_growth_score * 0.15 +
+ pe_ratio_score * 0.20 +
+ asset_backing_score * 0.15 +
+ margin_of_safety_score * 0.15
+ )
+
+ if total_score >= 7.5:
+ signal = "bullish"
+ recommendation = "BUY - Strong margin of safety"
+ confidence = random.uniform(75.0, 95.0)
+ elif total_score >= 6.0:
+ signal = "neutral"
+ recommendation = "HOLD - Adequate but not compelling"
+ confidence = random.uniform(55.0, 75.0)
+ else:
+ signal = "bearish"
+ recommendation = "AVOID - Insufficient margin of safety"
+ confidence = random.uniform(40.0, 65.0)
+
+ analysis = {
+ "ticker": ticker,
+ "signal": signal,
+ "confidence": round(confidence, 2),
+ "total_score": round(total_score, 2),
+ "reasoning": f"""
+Benjamin Graham Deep Value Analysis for {ticker}
+
+📊 Overall Score: {total_score:.1f}/10 - {signal.upper()}
+
+Earnings Stability (Score: {earnings_stability_score:.1f}/10):
+{'✓' if earnings_stability_score >= 7 else '⚠'} No deficit in past 10 years
+{'✓' if earnings_stability_score >= 7 else '⚠'} Consistent earnings pattern
+{'✓' if earnings_stability_score >= 7 else '⚠'} Quality of earnings
+
+Dividend Record (Score: {dividend_record_score:.1f}/10):
+{'✓' if dividend_record_score >= 7 else '⚠'} Uninterrupted dividends for 20+ years
+{'✓' if dividend_record_score >= 7 else '⚠'} Dividend growth consistency
+{'✓' if dividend_record_score >= 7 else '⚠'} Payout ratio sustainability
+
+Earnings Growth (Score: {earnings_growth_score:.1f}/10):
+{'✓' if earnings_growth_score >= 7 else '⚠'} 33% increase over 10 years
+{'✓' if earnings_growth_score >= 7 else '⚠'} Stable growth trajectory
+{'✓' if earnings_growth_score >= 7 else '⚠'} No erratic fluctuations
+
+P/E Ratio (Score: {pe_ratio_score:.1f}/10):
+{'✓' if pe_ratio_score >= 6 else '⚠'} Current P/E below 15x
+{'✓' if pe_ratio_score >= 6 else '⚠'} Historical P/E comparison
+{'✓' if pe_ratio_score >= 6 else '⚠'} Earnings quality adjustment
+
+Asset Backing (Score: {asset_backing_score:.1f}/10):
+{'✓' if asset_backing_score >= 7 else '⚠'} Current ratio above 2.0
+{'✓' if asset_backing_score >= 7 else '⚠'} Long-term debt below working capital
+{'✓' if asset_backing_score >= 7 else '⚠'} Book value support
+
+Margin of Safety (Score: {margin_of_safety_score:.1f}/10):
+{'✓' if margin_of_safety_score >= 6 else '⚠'} Price below 2/3 of intrinsic value
+{'✓' if margin_of_safety_score >= 6 else '⚠'} Multiple valuation methods converge
+
+💡 Recommendation: {recommendation}
+📈 Confidence Level: {confidence:.1f}%
+
+"The margin of safety is always dependent on the price paid." - Benjamin Graham
+ """.strip(),
+ "metrics": {
+ "earnings_stability_score": round(earnings_stability_score, 2),
+ "dividend_record_score": round(dividend_record_score, 2),
+ "earnings_growth_score": round(earnings_growth_score, 2),
+ "pe_ratio_score": round(pe_ratio_score, 2),
+ "asset_backing_score": round(asset_backing_score, 2),
+ "margin_of_safety_score": round(margin_of_safety_score, 2)
+ }
+ }
+
+ return analysis
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Main agent execution function"""
+ try:
+ tickers = parameters.get("tickers", ["AAPL"])
+ end_date = parameters.get("end_date", "2024-12-31")
+
+ if isinstance(tickers, str):
+ tickers = [tickers]
+
+ results = {}
+ for ticker in tickers:
+ analysis = analyze_stock_graham_style(ticker, parameters)
+ results[ticker] = analysis
+
+ return {
+ "success": True,
+ "agent": "benjamin_graham",
+ "execution_date": end_date,
+ "tickers_analyzed": len(tickers),
+ "signals": {ticker: results[ticker]["signal"] for ticker in results},
+ "analysis": results
+ }
+
+ except Exception as e:
+ return {
+ "success": False,
+ "error": str(e),
+ "agent": "benjamin_graham"
+ }
+
+def main():
+ """CLI entry point"""
+ parser = argparse.ArgumentParser(description='Benjamin Graham Agent - Deep Value Analysis')
+ parser.add_argument('--parameters', type=str, required=True, help='JSON string of parameters')
+ parser.add_argument('--inputs', type=str, required=True, help='JSON string of inputs')
+
+ args = parser.parse_args()
+
+ try:
+ parameters = json.loads(args.parameters)
+ inputs = json.loads(args.inputs)
+ result = execute_agent(parameters, inputs)
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+
+ except json.JSONDecodeError as e:
+ error_result = {
+ "success": False,
+ "error": f"JSON parse error: {str(e)}",
+ "agent": "benjamin_graham"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+ except Exception as e:
+ error_result = {
+ "success": False,
+ "error": f"Agent execution error: {str(e)}",
+ "agent": "benjamin_graham"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/bill_miller_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/bill_miller_agent_cli.py
new file mode 100644
index 000000000..b051b8756
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/bill_miller_agent_cli.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python3
+"""
+Bill Miller Agent - CLI Version
+Contrarian value + technology focus
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any
+import random
+
+def analyze_stock_miller_style(ticker: str, parameters: Dict[str, Any], previous_context: str = None) -> Dict[str, Any]:
+ """
+ Bill Miller-style contrarian value investing
+ Focus: Technology value plays, contrarian timing, concentrated positions
+ """
+ ticker_hash = sum(ord(c) for c in ticker)
+ random.seed(ticker_hash)
+
+ contrarian_opportunity = random.uniform(4.0, 9.5)
+ technology_value = random.uniform(5.0, 9.0)
+ long_term_drivers = random.uniform(6.0, 9.5)
+ market_misperception = random.uniform(3.0, 8.5)
+ concentration_worthiness = random.uniform(5.0, 9.0)
+
+ context_adjustment = ""
+ if previous_context:
+ context_adjustment = f"\n\n🔗 Building on Previous Analysis:\n{previous_context[:500]}...\n"
+ contrarian_opportunity *= 1.02
+ concentration_worthiness *= 1.03
+
+ total_score = (
+ contrarian_opportunity * 0.30 +
+ concentration_worthiness * 0.25 +
+ technology_value * 0.20 +
+ long_term_drivers * 0.15 +
+ market_misperception * 0.10
+ )
+
+ # Miller's high-conviction approach
+ if total_score >= 8.0:
+ signal = "bullish"
+ recommendation = "BUY - High-conviction contrarian opportunity"
+ confidence = random.uniform(80.0, 95.0)
+ elif total_score <= 4.0:
+ signal = "bearish"
+ recommendation = "PASS - Lacks contrarian value setup"
+ confidence = random.uniform(60.0, 75.0)
+ else:
+ signal = "neutral"
+ recommendation = "WATCH - Potential developing, wait for better entry"
+ confidence = random.uniform(50.0, 70.0)
+
+ analysis = {
+ "ticker": ticker,
+ "signal": signal,
+ "confidence": round(confidence, 2),
+ "total_score": round(total_score, 2),
+ "reasoning": f"""
+Bill Miller Contrarian Value Analysis for {ticker}
+{context_adjustment}
+📊 Overall Score: {total_score:.1f}/10 - {signal.upper()}
+
+Contrarian Opportunity (Score: {contrarian_opportunity:.1f}/10):
+{'✓' if contrarian_opportunity >= 7 else '⚠'} Extreme valuation creating setup
+{'✓' if contrarian_opportunity >= 7 else '⚠'} Market pessimism vs business reality
+{'✓' if contrarian_opportunity >= 7 else '⚠'} Temporary challenges with long-term potential
+
+Technology Value Potential (Score: {technology_value:.1f}/10):
+{'✓' if technology_value >= 7 else '⚠'} Asset-light scalable model
+{'✓' if technology_value >= 7 else '⚠'} Network effects and switching costs
+{'✓' if technology_value >= 7 else '⚠'} R&D efficiency and innovation
+
+Long-Term Growth Drivers (Score: {long_term_drivers:.1f}/10):
+{'✓' if long_term_drivers >= 7 else '⚠'} Consistent revenue growth track record
+{'✓' if long_term_drivers >= 7 else '⚠'} Reinvestment for future growth
+{'✓' if long_term_drivers >= 7 else '⚠'} Balance sheet capacity for expansion
+
+Market Misperception (Score: {market_misperception:.1f}/10):
+{'✓' if market_misperception >= 6 else '⚠'} Quality company at value multiple
+{'✓' if market_misperception >= 6 else '⚠'} Growth story with temporary headwinds
+{'✓' if market_misperception >= 6 else '⚠'} Asset value not recognized by market
+
+Concentration Worthiness (Score: {concentration_worthiness:.1f}/10):
+{'✓' if concentration_worthiness >= 7 else '⚠'} Strong competitive position
+{'✓' if concentration_worthiness >= 7 else '⚠'} Significant upside potential (50%+)
+{'✓' if concentration_worthiness >= 7 else '⚠'} Durable business model
+
+💡 Recommendation: {recommendation}
+📈 Confidence Level: {confidence:.1f}%
+
+"Being early is the same as being wrong, but being contrarian and right is very rewarding." - Bill Miller
+ """.strip(),
+ "metrics": {
+ "contrarian_opportunity": round(contrarian_opportunity, 2),
+ "technology_value": round(technology_value, 2),
+ "long_term_drivers": round(long_term_drivers, 2),
+ "market_misperception": round(market_misperception, 2),
+ "concentration_worthiness": round(concentration_worthiness, 2)
+ }
+ }
+
+ return analysis
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Main agent execution"""
+ try:
+ tickers = parameters.get("tickers", ["AAPL"])
+ end_date = parameters.get("end_date", "2024-12-31")
+
+ if isinstance(tickers, str):
+ tickers = [tickers]
+
+ mediated_context = None
+ if inputs and isinstance(inputs, dict):
+ mediated_context = inputs.get("mediated_analysis")
+
+ results = {}
+ for ticker in tickers:
+ analysis = analyze_stock_miller_style(ticker, parameters, mediated_context)
+ results[ticker] = analysis
+
+ response = {
+ "success": True,
+ "agent": "bill_miller",
+ "execution_date": end_date,
+ "tickers_analyzed": len(tickers),
+ "signals": {ticker: results[ticker]["signal"] for ticker in results},
+ "analysis": results
+ }
+
+ if mediated_context:
+ response["used_previous_context"] = True
+
+ return response
+
+ except Exception as e:
+ return {"success": False, "error": str(e), "agent": "bill_miller"}
+
+def main():
+ parser = argparse.ArgumentParser(description='Bill Miller Agent - Contrarian Value Analysis')
+ parser.add_argument('--parameters', type=str, required=True)
+ parser.add_argument('--inputs', type=str, required=True)
+ args = parser.parse_args()
+
+ try:
+ result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+ except Exception as e:
+ print(json.dumps({"success": False, "error": str(e), "agent": "bill_miller"}), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/charlie_munger_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/charlie_munger_agent_cli.py
new file mode 100644
index 000000000..de51e311d
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/charlie_munger_agent_cli.py
@@ -0,0 +1,194 @@
+#!/usr/bin/env python3
+"""
+Charlie Munger Agent - CLI Version
+Multidisciplinary thinking and rational decision-making
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any, List
+
+def analyze_stock_munger_style(ticker: str, parameters: Dict[str, Any], previous_context: str = None) -> Dict[str, Any]:
+ """
+ Charlie Munger-style analysis using mental models and multidisciplinary thinking
+ Focus: Psychology, incentives, cognitive biases, competitive advantages
+ Can incorporate insights from previous agents if provided
+ """
+ import random
+
+ ticker_hash = sum(ord(c) for c in ticker)
+ random.seed(ticker_hash + 1) # Different seed than Buffett
+
+ # Munger's mental models scoring
+ psychology_score = random.uniform(5.0, 9.5)
+ incentives_score = random.uniform(6.0, 9.0)
+ competitive_position_score = random.uniform(6.5, 9.5)
+ mental_models_score = random.uniform(5.5, 8.5)
+ margin_of_safety_score = random.uniform(4.5, 9.0)
+
+ # Adjust scores based on previous agent context if available
+ context_adjustment = ""
+ if previous_context:
+ context_adjustment = f"\n\n🔗 Building on Previous Analysis:\n{previous_context[:500]}...\n"
+ # Slightly adjust scores based on having additional context (simulating informed decision)
+ psychology_score *= 1.05
+ mental_models_score *= 1.08
+
+ total_score = (
+ psychology_score * 0.25 +
+ incentives_score * 0.25 +
+ competitive_position_score * 0.25 +
+ mental_models_score * 0.15 +
+ margin_of_safety_score * 0.10
+ )
+
+ if total_score >= 8.0:
+ signal = "bullish"
+ recommendation = "BUY - Rational analysis supports investment"
+ confidence = random.uniform(75.0, 95.0)
+ elif total_score >= 6.5:
+ signal = "neutral"
+ recommendation = "HOLD - More thinking required"
+ confidence = random.uniform(55.0, 75.0)
+ else:
+ signal = "bearish"
+ recommendation = "AVOID - Fails rational analysis"
+ confidence = random.uniform(40.0, 65.0)
+
+ analysis = {
+ "ticker": ticker,
+ "signal": signal,
+ "confidence": round(confidence, 2),
+ "total_score": round(total_score, 2),
+ "reasoning": f"""
+Charlie Munger Multidisciplinary Analysis for {ticker}
+{context_adjustment}
+📊 Overall Score: {total_score:.1f}/10 - {signal.upper()}
+
+Psychology & Human Behavior (Score: {psychology_score:.1f}/10):
+{'✓' if psychology_score >= 7 else '⚠'} Management incentive alignment
+{'✓' if psychology_score >= 7 else '⚠'} Avoiding cognitive biases in decision-making
+{'✓' if psychology_score >= 7 else '⚠'} Understanding customer psychology
+
+Incentive Systems (Score: {incentives_score:.1f}/10):
+{'✓' if incentives_score >= 7 else '⚠'} Executive compensation structure
+{'✓' if incentives_score >= 7 else '⚠'} Sales force incentives alignment
+{'✓' if incentives_score >= 7 else '⚠'} Stakeholder incentive compatibility
+
+Competitive Position (Score: {competitive_position_score:.1f}/10):
+{'✓' if competitive_position_score >= 7 else '⚠'} Lollapalooza effects (multiple advantages)
+{'✓' if competitive_position_score >= 7 else '⚠'} Network effects and scale advantages
+{'✓' if competitive_position_score >= 7 else '⚠'} Brand moat strength
+
+Mental Models Application (Score: {mental_models_score:.1f}/10):
+{'✓' if mental_models_score >= 7 else '⚠'} Physics: Leverage and critical mass
+{'✓' if mental_models_score >= 7 else '⚠'} Biology: Survival of the fittest
+{'✓' if mental_models_score >= 7 else '⚠'} Psychology: Social proof and reciprocity
+
+Margin of Safety (Score: {margin_of_safety_score:.1f}/10):
+{'✓' if margin_of_safety_score >= 6 else '⚠'} Price below intrinsic value
+{'✓' if margin_of_safety_score >= 6 else '⚠'} Multiple scenarios considered
+
+💡 Recommendation: {recommendation}
+📈 Confidence Level: {confidence:.1f}%
+
+"All I want to know is where I'm going to die, so I'll never go there." - Charlie Munger
+ """.strip(),
+ "metrics": {
+ "psychology_score": round(psychology_score, 2),
+ "incentives_score": round(incentives_score, 2),
+ "competitive_position_score": round(competitive_position_score, 2),
+ "mental_models_score": round(mental_models_score, 2),
+ "margin_of_safety_score": round(margin_of_safety_score, 2)
+ }
+ }
+
+ return analysis
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Main agent execution function"""
+ try:
+ tickers = parameters.get("tickers", ["AAPL"])
+ end_date = parameters.get("end_date", "2024-12-31")
+
+ if isinstance(tickers, str):
+ tickers = [tickers]
+
+ # Extract mediated context from inputs
+ mediated_context = None
+ if inputs:
+ # Check for mediated analysis from Agent Mediator
+ if isinstance(inputs, dict):
+ mediated_context = inputs.get("mediated_analysis")
+ # Also try to get it from direct string input
+ if not mediated_context and isinstance(inputs, str):
+ mediated_context = inputs
+
+ results = {}
+ for ticker in tickers:
+ # Pass mediated context to analysis
+ analysis = analyze_stock_munger_style(ticker, parameters, mediated_context)
+ results[ticker] = analysis
+
+ # Build response
+ response = {
+ "success": True,
+ "agent": "charlie_munger",
+ "execution_date": end_date,
+ "tickers_analyzed": len(tickers),
+ "signals": {ticker: results[ticker]["signal"] for ticker in results},
+ "analysis": results
+ }
+
+ # Include metadata about previous context
+ if mediated_context:
+ response["used_previous_context"] = True
+ response["context_source"] = inputs.get("source_agent") if isinstance(inputs, dict) else "unknown"
+ else:
+ response["used_previous_context"] = False
+
+ return response
+
+ except Exception as e:
+ return {
+ "success": False,
+ "error": str(e),
+ "agent": "charlie_munger"
+ }
+
+def main():
+ """CLI entry point"""
+ parser = argparse.ArgumentParser(description='Charlie Munger Agent - Multidisciplinary Analysis')
+ parser.add_argument('--parameters', type=str, required=True, help='JSON string of parameters')
+ parser.add_argument('--inputs', type=str, required=True, help='JSON string of inputs')
+
+ args = parser.parse_args()
+
+ try:
+ parameters = json.loads(args.parameters)
+ inputs = json.loads(args.inputs)
+ result = execute_agent(parameters, inputs)
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+
+ except json.JSONDecodeError as e:
+ error_result = {
+ "success": False,
+ "error": f"JSON parse error: {str(e)}",
+ "agent": "charlie_munger"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+ except Exception as e:
+ error_result = {
+ "success": False,
+ "error": f"Agent execution error: {str(e)}",
+ "agent": "charlie_munger"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/david_einhorn_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/david_einhorn_agent_cli.py
new file mode 100644
index 000000000..875b23339
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/david_einhorn_agent_cli.py
@@ -0,0 +1,160 @@
+#!/usr/bin/env python3
+"""
+David Einhorn Agent - CLI Version
+Forensic accounting + value/short analysis
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any
+import random
+
+def analyze_stock_einhorn_style(ticker: str, parameters: Dict[str, Any], previous_context: str = None) -> Dict[str, Any]:
+ """
+ David Einhorn-style forensic accounting and value/short analysis
+ Focus: Accounting quality, earnings vs cash flow, red flags, short opportunities
+ """
+ ticker_hash = sum(ord(c) for c in ticker)
+ random.seed(ticker_hash)
+
+ accounting_quality = random.uniform(4.0, 9.0)
+ earnings_quality = random.uniform(5.0, 9.5)
+ valuation_score = random.uniform(3.0, 8.0)
+ red_flags_score = random.uniform(6.0, 10.0) # Higher is better (fewer red flags)
+ fundamental_value = random.uniform(4.0, 8.5)
+
+ context_adjustment = ""
+ if previous_context:
+ context_adjustment = f"\n\n🔗 Building on Previous Analysis:\n{previous_context[:500]}...\n"
+ accounting_quality *= 1.02
+ earnings_quality *= 1.01
+
+ total_score = (
+ accounting_quality * 0.25 +
+ earnings_quality * 0.25 +
+ fundamental_value * 0.20 +
+ valuation_score * 0.20 +
+ red_flags_score * 0.10
+ )
+
+ # Einhorn's strong conviction framework
+ if total_score >= 7.5:
+ signal = "bullish"
+ recommendation = "BUY - Clean accounting at attractive valuation"
+ confidence = random.uniform(75.0, 92.0)
+ elif total_score <= 3.5:
+ signal = "bearish"
+ recommendation = "SHORT - Accounting red flags and overvaluation"
+ confidence = random.uniform(70.0, 88.0)
+ else:
+ signal = "neutral"
+ recommendation = "HOLD - Mixed signals, wait for clearer setup"
+ confidence = random.uniform(50.0, 70.0)
+
+ analysis = {
+ "ticker": ticker,
+ "signal": signal,
+ "confidence": round(confidence, 2),
+ "total_score": round(total_score, 2),
+ "reasoning": f"""
+David Einhorn Forensic Accounting Analysis for {ticker}
+{context_adjustment}
+📊 Overall Score: {total_score:.1f}/10 - {signal.upper()}
+
+Accounting Quality (Score: {accounting_quality:.1f}/10):
+{'✓' if accounting_quality >= 7 else '⚠'} Revenue recognition practices
+{'✓' if accounting_quality >= 7 else '⚠'} Receivables and inventory management
+{'✓' if accounting_quality >= 7 else '⚠'} Asset growth vs revenue growth
+
+Earnings Quality (Score: {earnings_quality:.1f}/10):
+{'✓' if earnings_quality >= 7 else '⚠'} Earnings vs free cash flow alignment
+{'✓' if earnings_quality >= 7 else '⚠'} Low accruals relative to earnings
+{'✓' if earnings_quality >= 7 else '⚠'} Consistent cash generation
+
+Red Flags Analysis (Score: {red_flags_score:.1f}/10):
+{'✓' if red_flags_score >= 7 else '🚩'} Financial statement irregularities
+{'✓' if red_flags_score >= 7 else '🚩'} Margin compression analysis
+{'✓' if red_flags_score >= 7 else '🚩'} Cash flow consistency
+
+Fundamental Valuation (Score: {fundamental_value:.1f}/10):
+{'✓' if fundamental_value >= 6 else '⚠'} Price to book value
+{'✓' if fundamental_value >= 6 else '⚠'} Free cash flow yield
+{'✓' if fundamental_value >= 6 else '⚠'} Asset-based valuation
+
+Valuation vs Reality (Score: {valuation_score:.1f}/10):
+{'✓' if valuation_score >= 6 else '⚠'} Market price vs intrinsic value
+{'✓' if valuation_score >= 6 else '⚠'} PEG ratio assessment
+
+💡 Recommendation: {recommendation}
+📈 Confidence Level: {confidence:.1f}%
+
+"The market can stay irrational longer than you can stay solvent." - David Einhorn
+ """.strip(),
+ "metrics": {
+ "accounting_quality": round(accounting_quality, 2),
+ "earnings_quality": round(earnings_quality, 2),
+ "valuation_score": round(valuation_score, 2),
+ "red_flags_score": round(red_flags_score, 2),
+ "fundamental_value": round(fundamental_value, 2)
+ }
+ }
+
+ return analysis
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Main agent execution"""
+ try:
+ tickers = parameters.get("tickers", ["AAPL"])
+ end_date = parameters.get("end_date", "2024-12-31")
+
+ if isinstance(tickers, str):
+ tickers = [tickers]
+
+ mediated_context = None
+ if inputs and isinstance(inputs, dict):
+ mediated_context = inputs.get("mediated_analysis")
+ if not mediated_context and isinstance(inputs, str):
+ mediated_context = inputs
+
+ results = {}
+ for ticker in tickers:
+ analysis = analyze_stock_einhorn_style(ticker, parameters, mediated_context)
+ results[ticker] = analysis
+
+ response = {
+ "success": True,
+ "agent": "david_einhorn",
+ "execution_date": end_date,
+ "tickers_analyzed": len(tickers),
+ "signals": {ticker: results[ticker]["signal"] for ticker in results},
+ "analysis": results
+ }
+
+ if mediated_context:
+ response["used_previous_context"] = True
+ response["context_source"] = inputs.get("source_agent") if isinstance(inputs, dict) else "unknown"
+ else:
+ response["used_previous_context"] = False
+
+ return response
+
+ except Exception as e:
+ return {"success": False, "error": str(e), "agent": "david_einhorn"}
+
+def main():
+ parser = argparse.ArgumentParser(description='David Einhorn Agent - Forensic Accounting Analysis')
+ parser.add_argument('--parameters', type=str, required=True)
+ parser.add_argument('--inputs', type=str, required=True)
+ args = parser.parse_args()
+
+ try:
+ result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+ except Exception as e:
+ print(json.dumps({"success": False, "error": str(e), "agent": "david_einhorn"}), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/howard_marks_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/howard_marks_agent_cli.py
new file mode 100644
index 000000000..b3424101b
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/howard_marks_agent_cli.py
@@ -0,0 +1,164 @@
+#!/usr/bin/env python3
+"""
+Howard Marks Agent - CLI Version
+Market cycles and second-level thinking
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any, List
+
+def analyze_stock_marks_style(ticker: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Howard Marks-style cycle and sentiment analysis
+ Focus: Market cycles, investor psychology, contrarian opportunities
+ """
+ import random
+
+ ticker_hash = sum(ord(c) for c in ticker)
+ random.seed(ticker_hash + 4)
+
+ # Marks' cycle-aware criteria
+ cycle_position_score = random.uniform(5.0, 9.0)
+ sentiment_analysis_score = random.uniform(5.5, 9.5)
+ second_level_thinking_score = random.uniform(6.0, 9.0)
+ risk_assessment_score = random.uniform(6.5, 9.5)
+ contrarian_opportunity_score = random.uniform(4.5, 9.0)
+
+ total_score = (
+ cycle_position_score * 0.25 +
+ sentiment_analysis_score * 0.25 +
+ second_level_thinking_score * 0.20 +
+ risk_assessment_score * 0.20 +
+ contrarian_opportunity_score * 0.10
+ )
+
+ if total_score >= 7.5:
+ signal = "bullish"
+ recommendation = "BUY - Cycle positioning favorable"
+ confidence = random.uniform(70.0, 90.0)
+ elif total_score >= 6.0:
+ signal = "neutral"
+ recommendation = "HOLD - Cycle awareness required"
+ confidence = random.uniform(50.0, 70.0)
+ else:
+ signal = "bearish"
+ recommendation = "AVOID - Cycle headwinds present"
+ confidence = random.uniform(35.0, 60.0)
+
+ analysis = {
+ "ticker": ticker,
+ "signal": signal,
+ "confidence": round(confidence, 2),
+ "total_score": round(total_score, 2),
+ "reasoning": f"""
+Howard Marks Market Cycle Analysis for {ticker}
+
+📊 Overall Score: {total_score:.1f}/10 - {signal.upper()}
+
+Market Cycle Position (Score: {cycle_position_score:.1f}/10):
+{'✓' if cycle_position_score >= 7 else '⚠'} Current phase identification
+{'✓' if cycle_position_score >= 7 else '⚠'} Historical cycle comparison
+{'✓' if cycle_position_score >= 7 else '⚠'} Positioning for next phase
+
+Sentiment Analysis (Score: {sentiment_analysis_score:.1f}/10):
+{'✓' if sentiment_analysis_score >= 7 else '⚠'} Investor mood assessment
+{'✓' if sentiment_analysis_score >= 7 else '⚠'} Greed vs fear indicators
+{'✓' if sentiment_analysis_score >= 7 else '⚠'} Consensus vs reality gap
+
+Second-Level Thinking (Score: {second_level_thinking_score:.1f}/10):
+{'✓' if second_level_thinking_score >= 7 else '⚠'} Beyond obvious conclusions
+{'✓' if second_level_thinking_score >= 7 else '⚠'} Non-consensus correct insights
+{'✓' if second_level_thinking_score >= 7 else '⚠'} What's priced in vs reality
+
+Risk Assessment (Score: {risk_assessment_score:.1f}/10):
+{'✓' if risk_assessment_score >= 7 else '⚠'} Risk vs uncertainty distinction
+{'✓' if risk_assessment_score >= 7 else '⚠'} Probability distribution of outcomes
+{'✓' if risk_assessment_score >= 7 else '⚠'} Tail risk consideration
+
+Contrarian Opportunity (Score: {contrarian_opportunity_score:.1f}/10):
+{'✓' if contrarian_opportunity_score >= 6 else '⚠'} Crowd behavior extremes
+{'✓' if contrarian_opportunity_score >= 6 else '⚠'} Unreasonable pessimism/optimism
+
+💡 Recommendation: {recommendation}
+📈 Confidence Level: {confidence:.1f}%
+
+"The most dangerous thing is to buy something at the top of its popularity." - Howard Marks
+ """.strip(),
+ "metrics": {
+ "cycle_position_score": round(cycle_position_score, 2),
+ "sentiment_analysis_score": round(sentiment_analysis_score, 2),
+ "second_level_thinking_score": round(second_level_thinking_score, 2),
+ "risk_assessment_score": round(risk_assessment_score, 2),
+ "contrarian_opportunity_score": round(contrarian_opportunity_score, 2)
+ }
+ }
+
+ return analysis
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Main agent execution function"""
+ try:
+ tickers = parameters.get("tickers", ["AAPL"])
+ end_date = parameters.get("end_date", "2024-12-31")
+
+ if isinstance(tickers, str):
+ tickers = [tickers]
+
+ results = {}
+ for ticker in tickers:
+ analysis = analyze_stock_marks_style(ticker, parameters)
+ results[ticker] = analysis
+
+ return {
+ "success": True,
+ "agent": "howard_marks",
+ "execution_date": end_date,
+ "tickers_analyzed": len(tickers),
+ "signals": {ticker: results[ticker]["signal"] for ticker in results},
+ "analysis": results
+ }
+
+ except Exception as e:
+ return {
+ "success": False,
+ "error": str(e),
+ "agent": "howard_marks"
+ }
+
+def main():
+ """CLI entry point"""
+ parser = argparse.ArgumentParser(description='Howard Marks Agent - Market Cycle Analysis')
+ parser.add_argument('--parameters', type=str, required=True, help='JSON string of parameters')
+ parser.add_argument('--inputs', type=str, required=True, help='JSON string of inputs')
+
+ args = parser.parse_args()
+
+ try:
+ parameters = json.loads(args.parameters)
+ inputs = json.loads(args.inputs)
+ result = execute_agent(parameters, inputs)
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+
+ except json.JSONDecodeError as e:
+ error_result = {
+ "success": False,
+ "error": f"JSON parse error: {str(e)}",
+ "agent": "howard_marks"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+ except Exception as e:
+ error_result = {
+ "success": False,
+ "error": f"Agent execution error: {str(e)}",
+ "agent": "howard_marks"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/jean_marie_eveillard_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/jean_marie_eveillard_agent_cli.py
new file mode 100644
index 000000000..763681622
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/jean_marie_eveillard_agent_cli.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python3
+"""
+Jean-Marie Eveillard Agent - CLI Version
+Global deep value investing
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any
+import random
+
+def analyze_stock_eveillard_style(ticker: str, parameters: Dict[str, Any], previous_context: str = None) -> Dict[str, Any]:
+ """
+ Jean-Marie Eveillard-style global deep value investing
+ Focus: International value, patient capital, deep discount to intrinsic value
+ """
+ ticker_hash = sum(ord(c) for c in ticker)
+ random.seed(ticker_hash)
+
+ deep_value_discount = random.uniform(4.0, 9.5)
+ balance_sheet_strength = random.uniform(6.0, 9.0)
+ management_quality = random.uniform(5.0, 8.5)
+ business_understanding = random.uniform(6.0, 9.0)
+ margin_of_safety = random.uniform(5.0, 9.5)
+
+ context_adjustment = ""
+ if previous_context:
+ context_adjustment = f"\n\n🔗 Building on Previous Analysis:\n{previous_context[:500]}...\n"
+ deep_value_discount *= 1.02
+ margin_of_safety *= 1.03
+
+ total_score = (
+ deep_value_discount * 0.30 +
+ margin_of_safety * 0.25 +
+ balance_sheet_strength * 0.20 +
+ business_understanding * 0.15 +
+ management_quality * 0.10
+ )
+
+ # Eveillard's patient value approach
+ if total_score >= 8.0:
+ signal = "bullish"
+ recommendation = "BUY - Deep value with strong margin of safety"
+ confidence = random.uniform(75.0, 90.0)
+ elif total_score <= 4.5:
+ signal = "bearish"
+ recommendation = "PASS - Insufficient value or safety margin"
+ confidence = random.uniform(55.0, 70.0)
+ else:
+ signal = "neutral"
+ recommendation = "WATCH - Value emerging, need more safety margin"
+ confidence = random.uniform(45.0, 65.0)
+
+ analysis = {
+ "ticker": ticker,
+ "signal": signal,
+ "confidence": round(confidence, 2),
+ "total_score": round(total_score, 2),
+ "reasoning": f"""
+Jean-Marie Eveillard Global Deep Value Analysis for {ticker}
+{context_adjustment}
+📊 Overall Score: {total_score:.1f}/10 - {signal.upper()}
+
+Deep Value Discount (Score: {deep_value_discount:.1f}/10):
+{'✓' if deep_value_discount >= 7 else '⚠'} Significant discount to intrinsic value
+{'✓' if deep_value_discount >= 7 else '⚠'} Asset backing and tangible value
+{'✓' if deep_value_discount >= 7 else '⚠'} Hidden or undervalued assets
+
+Margin of Safety (Score: {margin_of_safety:.1f}/10):
+{'✓' if margin_of_safety >= 7 else '⚠'} Multiple valuation approaches converge
+{'✓' if margin_of_safety >= 7 else '⚠'} Downside protection adequate
+{'✓' if margin_of_safety >= 7 else '⚠'} Risk-reward ratio favorable
+
+Balance Sheet Strength (Score: {balance_sheet_strength:.1f}/10):
+{'✓' if balance_sheet_strength >= 7 else '⚠'} Conservative capital structure
+{'✓' if balance_sheet_strength >= 7 else '⚠'} High quality assets
+{'✓' if balance_sheet_strength >= 7 else '⚠'} Financial flexibility maintained
+
+Business Understanding (Score: {business_understanding:.1f}/10):
+{'✓' if business_understanding >= 7 else '⚠'} Simple, understandable business model
+{'✓' if business_understanding >= 7 else '⚠'} Sustainable competitive position
+{'✓' if business_understanding >= 7 else '⚠'} Predictable cash flows
+
+Management Quality (Score: {management_quality:.1f}/10):
+{'✓' if management_quality >= 6 else '⚠'} Rational capital allocation
+{'✓' if management_quality >= 6 else '⚠'} Shareholder-oriented decisions
+{'✓' if management_quality >= 6 else '⚠'} Conservative accounting practices
+
+💡 Recommendation: {recommendation}
+📈 Confidence Level: {confidence:.1f}%
+
+"We are not trying to be brilliant, we are trying to be careful." - Jean-Marie Eveillard
+ """.strip(),
+ "metrics": {
+ "deep_value_discount": round(deep_value_discount, 2),
+ "balance_sheet_strength": round(balance_sheet_strength, 2),
+ "management_quality": round(management_quality, 2),
+ "business_understanding": round(business_understanding, 2),
+ "margin_of_safety": round(margin_of_safety, 2)
+ }
+ }
+
+ return analysis
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Main agent execution"""
+ try:
+ tickers = parameters.get("tickers", ["AAPL"])
+ end_date = parameters.get("end_date", "2024-12-31")
+
+ if isinstance(tickers, str):
+ tickers = [tickers]
+
+ mediated_context = None
+ if inputs and isinstance(inputs, dict):
+ mediated_context = inputs.get("mediated_analysis")
+
+ results = {}
+ for ticker in tickers:
+ analysis = analyze_stock_eveillard_style(ticker, parameters, mediated_context)
+ results[ticker] = analysis
+
+ response = {
+ "success": True,
+ "agent": "jean_marie_eveillard",
+ "execution_date": end_date,
+ "tickers_analyzed": len(tickers),
+ "signals": {ticker: results[ticker]["signal"] for ticker in results},
+ "analysis": results
+ }
+
+ if mediated_context:
+ response["used_previous_context"] = True
+
+ return response
+
+ except Exception as e:
+ return {"success": False, "error": str(e), "agent": "jean_marie_eveillard"}
+
+def main():
+ parser = argparse.ArgumentParser(description='Jean-Marie Eveillard Agent - Global Deep Value')
+ parser.add_argument('--parameters', type=str, required=True)
+ parser.add_argument('--inputs', type=str, required=True)
+ args = parser.parse_args()
+
+ try:
+ result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+ except Exception as e:
+ print(json.dumps({"success": False, "error": str(e), "agent": "jean_marie_eveillard"}), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/joel_greenblatt_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/joel_greenblatt_agent_cli.py
new file mode 100644
index 000000000..f81fb373a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/joel_greenblatt_agent_cli.py
@@ -0,0 +1,167 @@
+#!/usr/bin/env python3
+"""
+Joel Greenblatt Agent - CLI Version
+Magic formula: high returns on capital at low prices
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any, List
+
+def analyze_stock_greenblatt_style(ticker: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Joel Greenblatt's Magic Formula analysis
+ Focus: High ROIC + High earnings yield = Magic combination
+ """
+ import random
+
+ ticker_hash = sum(ord(c) for c in ticker)
+ random.seed(ticker_hash + 5)
+
+ # Magic Formula components
+ return_on_capital_score = random.uniform(5.0, 10.0)
+ earnings_yield_score = random.uniform(4.5, 9.5)
+ capital_efficiency_score = random.uniform(6.0, 9.0)
+ competitive_advantage_score = random.uniform(5.5, 9.0)
+ business_quality_score = random.uniform(6.0, 8.5)
+
+ # Magic Formula combined score
+ magic_formula_rank = (return_on_capital_score * 0.40) + (earnings_yield_score * 0.40)
+ total_score = (
+ magic_formula_rank * 0.60 +
+ capital_efficiency_score * 0.15 +
+ competitive_advantage_score * 0.15 +
+ business_quality_score * 0.10
+ )
+
+ if total_score >= 7.5:
+ signal = "bullish"
+ recommendation = "BUY - Magic Formula champion"
+ confidence = random.uniform(75.0, 92.0)
+ elif total_score >= 6.0:
+ signal = "neutral"
+ recommendation = "HOLD - Moderate formula score"
+ confidence = random.uniform(55.0, 75.0)
+ else:
+ signal = "bearish"
+ recommendation = "AVOID - Poor formula metrics"
+ confidence = random.uniform(40.0, 65.0)
+
+ analysis = {
+ "ticker": ticker,
+ "signal": signal,
+ "confidence": round(confidence, 2),
+ "total_score": round(total_score, 2),
+ "reasoning": f"""
+Joel Greenblatt Magic Formula Analysis for {ticker}
+
+📊 Overall Score: {total_score:.1f}/10 - {signal.upper()}
+✨ Magic Formula Rank: {magic_formula_rank:.1f}/10
+
+Return on Capital (Score: {return_on_capital_score:.1f}/10):
+{'✓' if return_on_capital_score >= 7 else '⚠'} EBIT / (Net Working Capital + Net Fixed Assets)
+{'✓' if return_on_capital_score >= 7 else '⚠'} High returns indicate competitive advantage
+{'✓' if return_on_capital_score >= 7 else '⚠'} Consistency of high ROIC over time
+
+Earnings Yield (Score: {earnings_yield_score:.1f}/10):
+{'✓' if earnings_yield_score >= 6 else '⚠'} EBIT / Enterprise Value
+{'✓' if earnings_yield_score >= 6 else '⚠'} High yield = cheap price
+{'✓' if earnings_yield_score >= 6 else '⚠'} Comparison to market alternatives
+
+Capital Efficiency (Score: {capital_efficiency_score:.1f}/10):
+{'✓' if capital_efficiency_score >= 7 else '⚠'} Low capital intensity
+{'✓' if capital_efficiency_score >= 7 else '⚠'} High free cash flow generation
+{'✓' if capital_efficiency_score >= 7 else '⚠'} Reinvestment opportunities
+
+Competitive Advantage Period (Score: {competitive_advantage_score:.1f}/10):
+{'✓' if competitive_advantage_score >= 7 else '⚠'} Sustainable high returns
+{'✓' if competitive_advantage_score >= 7 else '⚠'} Barriers to entry strength
+{'✓' if competitive_advantage_score >= 7 else '⚠'} Market position durability
+
+Business Quality (Score: {business_quality_score:.1f}/10):
+{'✓' if business_quality_score >= 6 else '⚠'} Simple, understandable business
+{'✓' if business_quality_score >= 6 else '⚠'} Strong unit economics
+
+💡 Recommendation: {recommendation}
+📈 Confidence Level: {confidence:.1f}%
+
+"Buy good companies at cheap prices." - Joel Greenblatt
+ """.strip(),
+ "metrics": {
+ "return_on_capital_score": round(return_on_capital_score, 2),
+ "earnings_yield_score": round(earnings_yield_score, 2),
+ "magic_formula_rank": round(magic_formula_rank, 2),
+ "capital_efficiency_score": round(capital_efficiency_score, 2),
+ "competitive_advantage_score": round(competitive_advantage_score, 2),
+ "business_quality_score": round(business_quality_score, 2)
+ }
+ }
+
+ return analysis
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Main agent execution function"""
+ try:
+ tickers = parameters.get("tickers", ["AAPL"])
+ end_date = parameters.get("end_date", "2024-12-31")
+
+ if isinstance(tickers, str):
+ tickers = [tickers]
+
+ results = {}
+ for ticker in tickers:
+ analysis = analyze_stock_greenblatt_style(ticker, parameters)
+ results[ticker] = analysis
+
+ return {
+ "success": True,
+ "agent": "joel_greenblatt",
+ "execution_date": end_date,
+ "tickers_analyzed": len(tickers),
+ "signals": {ticker: results[ticker]["signal"] for ticker in results},
+ "analysis": results
+ }
+
+ except Exception as e:
+ return {
+ "success": False,
+ "error": str(e),
+ "agent": "joel_greenblatt"
+ }
+
+def main():
+ """CLI entry point"""
+ parser = argparse.ArgumentParser(description='Joel Greenblatt Agent - Magic Formula Analysis')
+ parser.add_argument('--parameters', type=str, required=True, help='JSON string of parameters')
+ parser.add_argument('--inputs', type=str, required=True, help='JSON string of inputs')
+
+ args = parser.parse_args()
+
+ try:
+ parameters = json.loads(args.parameters)
+ inputs = json.loads(args.inputs)
+ result = execute_agent(parameters, inputs)
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+
+ except json.JSONDecodeError as e:
+ error_result = {
+ "success": False,
+ "error": f"JSON parse error: {str(e)}",
+ "agent": "joel_greenblatt"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+ except Exception as e:
+ error_result = {
+ "success": False,
+ "error": f"Agent execution error: {str(e)}",
+ "agent": "joel_greenblatt"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/marty_whitman_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/marty_whitman_agent_cli.py
new file mode 100644
index 000000000..478502f10
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/marty_whitman_agent_cli.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python3
+"""
+Marty Whitman Agent - CLI Version
+Distressed value + safe & cheap investing
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any
+import random
+
+def analyze_stock_whitman_style(ticker: str, parameters: Dict[str, Any], previous_context: str = None) -> Dict[str, Any]:
+ """
+ Marty Whitman-style distressed value investing
+ Focus: Safe & cheap, credit analysis, resource conversion, distressed opportunities
+ """
+ ticker_hash = sum(ord(c) for c in ticker)
+ random.seed(ticker_hash)
+
+ credit_analysis = random.uniform(5.0, 9.5)
+ asset_coverage = random.uniform(6.0, 9.0)
+ resource_conversion = random.uniform(4.0, 8.5)
+ going_concern_value = random.uniform(5.0, 9.0)
+ distressed_opportunity = random.uniform(3.0, 9.0)
+
+ context_adjustment = ""
+ if previous_context:
+ context_adjustment = f"\n\n🔗 Building on Previous Analysis:\n{previous_context[:500]}...\n"
+ credit_analysis *= 1.02
+ asset_coverage *= 1.03
+
+ total_score = (
+ credit_analysis * 0.30 +
+ asset_coverage * 0.25 +
+ going_concern_value * 0.20 +
+ resource_conversion * 0.15 +
+ distressed_opportunity * 0.10
+ )
+
+ # Whitman's safe & cheap approach
+ if total_score >= 7.5:
+ signal = "bullish"
+ recommendation = "BUY - Safe & cheap with asset backing"
+ confidence = random.uniform(70.0, 88.0)
+ elif total_score <= 4.0:
+ signal = "bearish"
+ recommendation = "AVOID - Credit concerns or overvalued"
+ confidence = random.uniform(60.0, 75.0)
+ else:
+ signal = "neutral"
+ recommendation = "MONITOR - Developing situation, watch credit"
+ confidence = random.uniform(45.0, 65.0)
+
+ analysis = {
+ "ticker": ticker,
+ "signal": signal,
+ "confidence": round(confidence, 2),
+ "total_score": round(total_score, 2),
+ "reasoning": f"""
+Marty Whitman Safe & Cheap Analysis for {ticker}
+{context_adjustment}
+📊 Overall Score: {total_score:.1f}/10 - {signal.upper()}
+
+Credit Analysis (Score: {credit_analysis:.1f}/10):
+{'✓' if credit_analysis >= 7 else '⚠'} Strong creditworthiness and solvency
+{'✓' if credit_analysis >= 7 else '⚠'} Manageable debt levels
+{'✓' if credit_analysis >= 7 else '⚠'} Adequate interest coverage
+
+Asset Coverage (Score: {asset_coverage:.1f}/10):
+{'✓' if asset_coverage >= 7 else '⚠'} Hard assets backing equity value
+{'✓' if asset_coverage >= 7 else '⚠'} Liquidation value exceeds price
+{'✓' if asset_coverage >= 7 else '⚠'} Working capital adequacy
+
+Going Concern Value (Score: {going_concern_value:.1f}/10):
+{'✓' if going_concern_value >= 7 else '⚠'} Business value as operating entity
+{'✓' if going_concern_value >= 7 else '⚠'} Franchise value and market position
+{'✓' if going_concern_value >= 7 else '⚠'} Sustainable earnings power
+
+Resource Conversion (Score: {resource_conversion:.1f}/10):
+{'✓' if resource_conversion >= 6 else '⚠'} Ability to monetize assets
+{'✓' if resource_conversion >= 6 else '⚠'} Management capital allocation skill
+{'✓' if resource_conversion >= 6 else '⚠'} Value realization potential
+
+Distressed Opportunity (Score: {distressed_opportunity:.1f}/10):
+{'✓' if distressed_opportunity >= 6 else '⚠'} Temporary distress vs permanent impairment
+{'✓' if distressed_opportunity >= 6 else '⚠'} Catalyst for value realization
+{'✓' if distressed_opportunity >= 6 else '⚠'} Risk-reward in restructuring scenario
+
+💡 Recommendation: {recommendation}
+📈 Confidence Level: {confidence:.1f}%
+
+"Buy a business that's worth more dead than alive, then you can't lose." - Marty Whitman
+ """.strip(),
+ "metrics": {
+ "credit_analysis": round(credit_analysis, 2),
+ "asset_coverage": round(asset_coverage, 2),
+ "resource_conversion": round(resource_conversion, 2),
+ "going_concern_value": round(going_concern_value, 2),
+ "distressed_opportunity": round(distressed_opportunity, 2)
+ }
+ }
+
+ return analysis
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Main agent execution"""
+ try:
+ tickers = parameters.get("tickers", ["AAPL"])
+ end_date = parameters.get("end_date", "2024-12-31")
+
+ if isinstance(tickers, str):
+ tickers = [tickers]
+
+ mediated_context = None
+ if inputs and isinstance(inputs, dict):
+ mediated_context = inputs.get("mediated_analysis")
+
+ results = {}
+ for ticker in tickers:
+ analysis = analyze_stock_whitman_style(ticker, parameters, mediated_context)
+ results[ticker] = analysis
+
+ response = {
+ "success": True,
+ "agent": "marty_whitman",
+ "execution_date": end_date,
+ "tickers_analyzed": len(tickers),
+ "signals": {ticker: results[ticker]["signal"] for ticker in results},
+ "analysis": results
+ }
+
+ if mediated_context:
+ response["used_previous_context"] = True
+
+ return response
+
+ except Exception as e:
+ return {"success": False, "error": str(e), "agent": "marty_whitman"}
+
+def main():
+ parser = argparse.ArgumentParser(description='Marty Whitman Agent - Safe & Cheap Distressed Value')
+ parser.add_argument('--parameters', type=str, required=True)
+ parser.add_argument('--inputs', type=str, required=True)
+ args = parser.parse_args()
+
+ try:
+ result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+ except Exception as e:
+ print(json.dumps({"success": False, "error": str(e), "agent": "marty_whitman"}), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/seth_klarman_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/seth_klarman_agent_cli.py
new file mode 100644
index 000000000..754958683
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/seth_klarman_agent_cli.py
@@ -0,0 +1,164 @@
+#!/usr/bin/env python3
+"""
+Seth Klarman Agent - CLI Version
+Risk management and distressed value opportunities
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any, List
+
+def analyze_stock_klarman_style(ticker: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Seth Klarman-style risk-focused analysis
+ Focus: Downside protection, asymmetric opportunities, catalysts
+ """
+ import random
+
+ ticker_hash = sum(ord(c) for c in ticker)
+ random.seed(ticker_hash + 3)
+
+ # Klarman's risk-focused criteria
+ downside_protection_score = random.uniform(6.0, 9.5)
+ catalyst_potential_score = random.uniform(5.0, 8.5)
+ asymmetric_payoff_score = random.uniform(5.5, 9.0)
+ liquidity_risk_score = random.uniform(6.5, 9.0)
+ valuation_discipline_score = random.uniform(5.0, 9.5)
+
+ total_score = (
+ downside_protection_score * 0.30 +
+ catalyst_potential_score * 0.20 +
+ asymmetric_payoff_score * 0.25 +
+ liquidity_risk_score * 0.15 +
+ valuation_discipline_score * 0.10
+ )
+
+ if total_score >= 7.5:
+ signal = "bullish"
+ recommendation = "BUY - Compelling risk/reward asymmetry"
+ confidence = random.uniform(70.0, 90.0)
+ elif total_score >= 6.0:
+ signal = "neutral"
+ recommendation = "HOLD - Risk not adequately compensated"
+ confidence = random.uniform(50.0, 70.0)
+ else:
+ signal = "bearish"
+ recommendation = "AVOID - Excessive downside risk"
+ confidence = random.uniform(35.0, 60.0)
+
+ analysis = {
+ "ticker": ticker,
+ "signal": signal,
+ "confidence": round(confidence, 2),
+ "total_score": round(total_score, 2),
+ "reasoning": f"""
+Seth Klarman Risk Management Analysis for {ticker}
+
+📊 Overall Score: {total_score:.1f}/10 - {signal.upper()}
+
+Downside Protection (Score: {downside_protection_score:.1f}/10):
+{'✓' if downside_protection_score >= 7 else '⚠'} Asset backing and liquidation value
+{'✓' if downside_protection_score >= 7 else '⚠'} Balance sheet fortress
+{'✓' if downside_protection_score >= 7 else '⚠'} Multiple scenarios downside limited
+
+Catalyst Potential (Score: {catalyst_potential_score:.1f}/10):
+{'✓' if catalyst_potential_score >= 6 else '⚠'} Management change possibility
+{'✓' if catalyst_potential_score >= 6 else '⚠'} Asset sale or spin-off potential
+{'✓' if catalyst_potential_score >= 6 else '⚠'} Industry consolidation trends
+
+Asymmetric Payoff (Score: {asymmetric_payoff_score:.1f}/10):
+{'✓' if asymmetric_payoff_score >= 7 else '⚠'} 3:1 or better upside/downside ratio
+{'✓' if asymmetric_payoff_score >= 7 else '⚠'} Limited further deterioration risk
+{'✓' if asymmetric_payoff_score >= 7 else '⚠'} Multiple paths to value realization
+
+Liquidity Risk (Score: {liquidity_risk_score:.1f}/10):
+{'✓' if liquidity_risk_score >= 7 else '⚠'} Adequate trading volume
+{'✓' if liquidity_risk_score >= 7 else '⚠'} Exit strategy viability
+{'✓' if liquidity_risk_score >= 7 else '⚠'} Market depth assessment
+
+Valuation Discipline (Score: {valuation_discipline_score:.1f}/10):
+{'✓' if valuation_discipline_score >= 6 else '⚠'} Conservative valuation assumptions
+{'✓' if valuation_discipline_score >= 6 else '⚠'} Margin of safety present
+
+💡 Recommendation: {recommendation}
+📈 Confidence Level: {confidence:.1f}%
+
+"The trick of successful investors is to sell when they want to, not when they have to." - Seth Klarman
+ """.strip(),
+ "metrics": {
+ "downside_protection_score": round(downside_protection_score, 2),
+ "catalyst_potential_score": round(catalyst_potential_score, 2),
+ "asymmetric_payoff_score": round(asymmetric_payoff_score, 2),
+ "liquidity_risk_score": round(liquidity_risk_score, 2),
+ "valuation_discipline_score": round(valuation_discipline_score, 2)
+ }
+ }
+
+ return analysis
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Main agent execution function"""
+ try:
+ tickers = parameters.get("tickers", ["AAPL"])
+ end_date = parameters.get("end_date", "2024-12-31")
+
+ if isinstance(tickers, str):
+ tickers = [tickers]
+
+ results = {}
+ for ticker in tickers:
+ analysis = analyze_stock_klarman_style(ticker, parameters)
+ results[ticker] = analysis
+
+ return {
+ "success": True,
+ "agent": "seth_klarman",
+ "execution_date": end_date,
+ "tickers_analyzed": len(tickers),
+ "signals": {ticker: results[ticker]["signal"] for ticker in results},
+ "analysis": results
+ }
+
+ except Exception as e:
+ return {
+ "success": False,
+ "error": str(e),
+ "agent": "seth_klarman"
+ }
+
+def main():
+ """CLI entry point"""
+ parser = argparse.ArgumentParser(description='Seth Klarman Agent - Risk Management Analysis')
+ parser.add_argument('--parameters', type=str, required=True, help='JSON string of parameters')
+ parser.add_argument('--inputs', type=str, required=True, help='JSON string of inputs')
+
+ args = parser.parse_args()
+
+ try:
+ parameters = json.loads(args.parameters)
+ inputs = json.loads(args.inputs)
+ result = execute_agent(parameters, inputs)
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+
+ except json.JSONDecodeError as e:
+ error_result = {
+ "success": False,
+ "error": f"JSON parse error: {str(e)}",
+ "agent": "seth_klarman"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+ except Exception as e:
+ error_result = {
+ "success": False,
+ "error": f"Agent execution error: {str(e)}",
+ "agent": "seth_klarman"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/warren_buffett_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/warren_buffett_agent_cli.py
new file mode 100644
index 000000000..1967dced2
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/warren_buffett_agent_cli.py
@@ -0,0 +1,217 @@
+#!/usr/bin/env python3
+"""
+Warren Buffett Agent - CLI Version
+Simplified for Node Editor integration
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any, List
+
+def analyze_stock_buffett_style(ticker: str, parameters: Dict[str, Any], previous_context: str = None) -> Dict[str, Any]:
+ """
+ Warren Buffett-style value investing analysis
+ Focuses on: Economic moats, predictable earnings, financial strength, management quality
+ Can incorporate insights from previous agents if provided
+ """
+ import random
+
+ # Simulate varying analysis based on ticker (for demo purposes)
+ # In production, replace with actual API calls to financial data providers
+ ticker_hash = sum(ord(c) for c in ticker)
+ random.seed(ticker_hash)
+
+ moat_score = random.uniform(5.0, 9.5)
+ earnings_score = random.uniform(6.0, 9.0)
+ financial_score = random.uniform(7.0, 10.0)
+ management_score = random.uniform(5.5, 8.5)
+ valuation_score = random.uniform(4.0, 8.0)
+
+ # Adjust scores if we have previous context
+ context_adjustment = ""
+ if previous_context:
+ context_adjustment = f"\n\n🔗 Building on Previous Analysis:\n{previous_context[:500]}...\n"
+ # Slightly improve scores when informed by other agents
+ moat_score *= 1.03
+ financial_score *= 1.02
+
+ total_score = (
+ moat_score * 0.30 +
+ earnings_score * 0.25 +
+ financial_score * 0.20 +
+ management_score * 0.15 +
+ valuation_score * 0.10
+ )
+
+ # Determine signal based on Buffett's criteria
+ if total_score >= 8.0:
+ signal = "bullish"
+ recommendation = "BUY - Wonderful business at a fair price"
+ confidence = random.uniform(75.0, 95.0)
+ elif total_score >= 6.5:
+ signal = "neutral"
+ recommendation = "HOLD - Good business, but wait for better price"
+ confidence = random.uniform(55.0, 75.0)
+ else:
+ signal = "bearish"
+ recommendation = "PASS - Does not meet quality criteria"
+ confidence = random.uniform(40.0, 65.0)
+
+ analysis = {
+ "ticker": ticker,
+ "signal": signal,
+ "confidence": round(confidence, 2),
+ "total_score": round(total_score, 2),
+ "reasoning": f"""
+Warren Buffett Value Investment Analysis for {ticker}
+{context_adjustment}
+📊 Overall Score: {total_score:.1f}/10 - {signal.upper()}
+
+Economic Moat Analysis (Score: {moat_score:.1f}/10):
+{'✓' if moat_score >= 7 else '⚠'} Brand strength and competitive advantages
+{'✓' if moat_score >= 7 else '⚠'} Pricing power in the market
+{'✓' if moat_score >= 7 else '⚠'} High barriers to entry for competitors
+
+Earnings Predictability (Score: {earnings_score:.1f}/10):
+{'✓' if earnings_score >= 7 else '⚠'} Consistent profitability track record
+{'✓' if earnings_score >= 7 else '⚠'} Stable and growing earnings trend
+{'✓' if earnings_score >= 7 else '⚠'} Low earnings volatility
+
+Financial Fortress (Score: {financial_score:.1f}/10):
+{'✓' if financial_score >= 7 else '⚠'} Conservative debt levels
+{'✓' if financial_score >= 7 else '⚠'} Strong balance sheet
+{'✓' if financial_score >= 7 else '⚠'} Reliable cash flow generation
+
+Management Quality (Score: {management_score:.1f}/10):
+{'✓' if management_score >= 7 else '⚠'} Effective capital allocation
+{'✓' if management_score >= 7 else '⚠'} Shareholder-friendly policies
+{'✓' if management_score >= 7 else '⚠'} Long-term value creation focus
+
+Valuation Assessment (Score: {valuation_score:.1f}/10):
+{'✓' if valuation_score >= 6 else '⚠'} Current market price vs intrinsic value
+{'✓' if valuation_score >= 6 else '⚠'} Margin of safety consideration
+
+💡 Recommendation: {recommendation}
+📈 Confidence Level: {confidence:.1f}%
+
+"Price is what you pay, value is what you get." - Warren Buffett
+ """.strip(),
+ "metrics": {
+ "moat_score": round(moat_score, 2),
+ "earnings_score": round(earnings_score, 2),
+ "financial_score": round(financial_score, 2),
+ "management_score": round(management_score, 2),
+ "valuation_score": round(valuation_score, 2)
+ }
+ }
+
+ return analysis
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Main agent execution function
+
+ Args:
+ parameters: {
+ "tickers": ["AAPL", "GOOGL"],
+ "end_date": "2024-12-31"
+ }
+ inputs: Data from connected nodes (if any)
+
+ Returns:
+ {
+ "success": true,
+ "signals": {...},
+ "analysis": {...}
+ }
+ """
+ try:
+ tickers = parameters.get("tickers", ["AAPL"])
+ end_date = parameters.get("end_date", "2024-12-31")
+
+ # Ensure tickers is a list
+ if isinstance(tickers, str):
+ tickers = [tickers]
+
+ # Extract mediated context from inputs
+ mediated_context = None
+ if inputs:
+ if isinstance(inputs, dict):
+ mediated_context = inputs.get("mediated_analysis")
+ if not mediated_context and isinstance(inputs, str):
+ mediated_context = inputs
+
+ results = {}
+
+ for ticker in tickers:
+ # Pass mediated context to analysis
+ analysis = analyze_stock_buffett_style(ticker, parameters, mediated_context)
+ results[ticker] = analysis
+
+ # Build response
+ response = {
+ "success": True,
+ "agent": "warren_buffett",
+ "execution_date": end_date,
+ "tickers_analyzed": len(tickers),
+ "signals": {ticker: results[ticker]["signal"] for ticker in results},
+ "analysis": results
+ }
+
+ # Include metadata about previous context
+ if mediated_context:
+ response["used_previous_context"] = True
+ response["context_source"] = inputs.get("source_agent") if isinstance(inputs, dict) else "unknown"
+ else:
+ response["used_previous_context"] = False
+
+ return response
+
+ except Exception as e:
+ return {
+ "success": False,
+ "error": str(e),
+ "agent": "warren_buffett"
+ }
+
+def main():
+ """CLI entry point"""
+ parser = argparse.ArgumentParser(description='Warren Buffett Agent - Value Investing Analysis')
+ parser.add_argument('--parameters', type=str, required=True, help='JSON string of parameters')
+ parser.add_argument('--inputs', type=str, required=True, help='JSON string of inputs')
+
+ args = parser.parse_args()
+
+ try:
+ # Parse JSON inputs
+ parameters = json.loads(args.parameters)
+ inputs = json.loads(args.inputs)
+
+ # Execute agent
+ result = execute_agent(parameters, inputs)
+
+ # Output JSON to stdout
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+
+ except json.JSONDecodeError as e:
+ error_result = {
+ "success": False,
+ "error": f"JSON parse error: {str(e)}",
+ "agent": "warren_buffett"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+ except Exception as e:
+ error_result = {
+ "success": False,
+ "error": f"Agent execution error: {str(e)}",
+ "agent": "warren_buffett"
+ }
+ print(json.dumps(error_result), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/.claude/settings.local.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/.claude/settings.local.json
deleted file mode 100644
index 7b274cbff..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/World_Order_Agents/.claude/settings.local.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "permissions": {
- "allow": [
- "Bash(git add:*)"
- ],
- "deny": [],
- "ask": []
- }
-}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/hedge_fund_agent_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/hedge_fund_agent_cli.py
new file mode 100644
index 000000000..c36e276cf
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/hedge_fund_agent_cli.py
@@ -0,0 +1,314 @@
+#!/usr/bin/env python3
+"""
+Hedge Fund Agent CLI - Unified Interface
+Analyzes markets through famous hedge fund strategies
+"""
+
+import sys
+import json
+import argparse
+from typing import Dict, Any
+import random
+
+# Hedge Fund Strategy Definitions
+
+HEDGE_FUND_FIRMS = {
+ "bridgewater": {
+ "name": "Bridgewater Associates",
+ "founder": "Ray Dalio",
+ "strategy": "All Weather Portfolio + Economic Machine",
+ "focus": ["risk_parity", "macro_analysis", "debt_cycles", "diversification"],
+ "philosophy": "Balance across economic environments"
+ },
+ "citadel": {
+ "name": "Citadel",
+ "founder": "Ken Griffin",
+ "strategy": "Multi-Strategy Global Macro",
+ "focus": ["quantitative_trading", "market_making", "multi_strategy", "technology"],
+ "philosophy": "Data-driven systematic approach"
+ },
+ "renaissance": {
+ "name": "Renaissance Technologies",
+ "founder": "Jim Simons",
+ "strategy": "Quantitative + Mathematical Models",
+ "focus": ["statistical_arbitrage", "pattern_recognition", "algorithmic_trading", "big_data"],
+ "philosophy": "Pure mathematical models"
+ },
+ "two_sigma": {
+ "name": "Two Sigma",
+ "founder": "D.E. Shaw Alumni",
+ "strategy": "Data Science + Machine Learning",
+ "focus": ["machine_learning", "artificial_intelligence", "data_science", "quantitative"],
+ "philosophy": "Technology-driven investing"
+ },
+ "de_shaw": {
+ "name": "D.E. Shaw",
+ "founder": "David Shaw",
+ "strategy": "Computational Finance",
+ "focus": ["computational_methods", "statistical_models", "systematic_trading", "technology"],
+ "philosophy": "Scientific approach to markets"
+ },
+ "elliott": {
+ "name": "Elliott Management",
+ "founder": "Paul Singer",
+ "strategy": "Activist + Distressed Debt",
+ "focus": ["activist_campaigns", "distressed_debt", "special_situations", "event_driven"],
+ "philosophy": "Value creation through activism"
+ },
+ "pershing_square": {
+ "name": "Pershing Square",
+ "founder": "Bill Ackman",
+ "strategy": "Concentrated Activist Value",
+ "focus": ["activist_investing", "concentrated_positions", "public_campaigns", "corporate_change"],
+ "philosophy": "High-conviction activist approach"
+ },
+ "arq_capital": {
+ "name": "ARQ Capital",
+ "founder": "Multi-Strategy",
+ "strategy": "Quantitative Multi-Strategy",
+ "focus": ["quantitative_models", "risk_management", "multi_strategy", "systematic"],
+ "philosophy": "Systematic risk-managed approach"
+ }
+}
+
+MULTI_STRATEGY_AGENTS = {
+ "macro_cycle": {
+ "name": "Macro Cycle Agent",
+ "focus": "Business cycle analysis and economic phase identification",
+ "indicators": ["gdp", "employment", "inflation", "industrial_production"],
+ "output": "Economic cycle phase + sector rotation"
+ },
+ "central_bank": {
+ "name": "Central Bank Agent",
+ "focus": "Monetary policy analysis and interest rate forecasting",
+ "indicators": ["interest_rates", "money_supply", "inflation", "policy_statements"],
+ "output": "Policy direction + rate trajectory"
+ },
+ "behavioral": {
+ "name": "Behavioral Agent",
+ "focus": "Market psychology and sentiment analysis",
+ "indicators": ["vix", "put_call_ratio", "sentiment_surveys", "positioning"],
+ "output": "Sentiment extreme identification"
+ },
+ "institutional_flow": {
+ "name": "Institutional Flow Agent",
+ "focus": "Smart money tracking and institutional positioning",
+ "indicators": ["13f_filings", "insider_trading", "fund_flows", "positioning"],
+ "output": "Institutional trend identification"
+ },
+ "innovation": {
+ "name": "Innovation Agent",
+ "focus": "Disruptive technology and innovation analysis",
+ "indicators": ["rd_spending", "patent_filings", "technology_adoption", "market_disruption"],
+ "output": "Innovation leader identification"
+ },
+ "geopolitical": {
+ "name": "Geopolitical Agent",
+ "focus": "Geopolitical risk and opportunity analysis",
+ "indicators": ["political_events", "trade_tensions", "sanctions", "conflicts"],
+ "output": "Geopolitical risk assessment"
+ },
+ "currency": {
+ "name": "Currency Agent",
+ "focus": "FX markets and currency dynamics",
+ "indicators": ["interest_rate_differentials", "trade_balances", "capital_flows", "fx_reserves"],
+ "output": "Currency trend forecasts"
+ },
+ "supply_chain": {
+ "name": "Supply Chain Agent",
+ "focus": "Supply chain disruptions and logistics",
+ "indicators": ["shipping_rates", "inventory_levels", "lead_times", "bottlenecks"],
+ "output": "Supply chain risk + opportunities"
+ },
+ "sentiment": {
+ "name": "Sentiment Agent",
+ "focus": "News and social media sentiment tracking",
+ "indicators": ["news_sentiment", "social_media", "search_trends", "media_coverage"],
+ "output": "Sentiment-driven trading signals"
+ },
+ "regulatory": {
+ "name": "Regulatory Agent",
+ "focus": "Regulatory changes and compliance impact",
+ "indicators": ["policy_changes", "regulatory_filings", "compliance_costs", "legal_risks"],
+ "output": "Regulatory impact assessment"
+ }
+}
+
+def analyze_hedge_fund_firm(agent_type: str, ticker: str, parameters: Dict[str, Any], previous_context: str = None) -> Dict[str, Any]:
+ """Analyze through hedge fund firm strategy"""
+
+ firm_info = HEDGE_FUND_FIRMS.get(agent_type, {})
+ focus_areas = firm_info.get("focus", [])
+
+ random.seed(sum(ord(c) for c in ticker))
+
+ # Simulate hedge fund analysis
+ focus_scores = {area: random.uniform(0.5, 0.95) for area in focus_areas}
+ strategy_effectiveness = random.uniform(0.65, 0.92)
+ risk_adjusted_return = random.uniform(0.60, 0.88)
+
+ total_score = (sum(focus_scores.values()) / len(focus_scores) + strategy_effectiveness + risk_adjusted_return) / 3
+
+ if total_score >= 0.75:
+ signal = "bullish"
+ confidence = random.uniform(75, 92)
+ elif total_score <= 0.45:
+ signal = "bearish"
+ confidence = random.uniform(70, 88)
+ else:
+ signal = "neutral"
+ confidence = random.uniform(50, 70)
+
+ context_note = f"\n\n🔗 Building on Previous Context:\n{previous_context[:300]}..." if previous_context else ""
+
+ return {
+ "agent": firm_info.get("name"),
+ "founder": firm_info.get("founder"),
+ "strategy": firm_info.get("strategy"),
+ "philosophy": firm_info.get("philosophy"),
+ "ticker": ticker,
+ "signal": signal,
+ "confidence": round(confidence, 2),
+ "analysis": f"""
+{firm_info.get('name')} Analysis for {ticker}
+{context_note}
+
+🏢 Hedge Fund Strategy: {firm_info.get('strategy')}
+📊 Overall Assessment: {total_score:.1%}
+
+Focus Area Analysis:
+{chr(10).join(f" • {area.replace('_', ' ').title()}: {score:.1%}" for area, score in focus_scores.items())}
+
+Performance Metrics:
+ ✓ Strategy Effectiveness: {strategy_effectiveness:.1%}
+ ✓ Risk-Adjusted Return Potential: {risk_adjusted_return:.1%}
+ ✓ Philosophy Alignment: {total_score:.1%}
+
+Signal: {signal.upper()}
+Confidence: {confidence:.1f}%
+
+"{firm_info.get('philosophy')}" - {firm_info.get('founder')}
+ """.strip(),
+ "focus_scores": focus_scores,
+ "strategy_effectiveness": round(strategy_effectiveness, 3),
+ "risk_adjusted_return": round(risk_adjusted_return, 3)
+ }
+
+def analyze_multi_strategy(agent_type: str, ticker: str, parameters: Dict[str, Any], previous_context: str = None) -> Dict[str, Any]:
+ """Analyze through multi-strategy agent"""
+
+ agent_info = MULTI_STRATEGY_AGENTS.get(agent_type, {})
+ indicators = agent_info.get("indicators", [])
+
+ random.seed(sum(ord(c) for c in ticker + agent_type))
+
+ # Simulate multi-strategy analysis
+ indicator_scores = {ind: random.uniform(0.45, 0.90) for ind in indicators}
+ signal_strength = random.uniform(0.55, 0.88)
+ conviction_level = random.uniform(0.50, 0.85)
+
+ total_score = (sum(indicator_scores.values()) / len(indicator_scores) + signal_strength + conviction_level) / 3
+
+ if total_score >= 0.70:
+ signal = "bullish"
+ confidence = random.uniform(70, 88)
+ elif total_score <= 0.45:
+ signal = "bearish"
+ confidence = random.uniform(65, 82)
+ else:
+ signal = "neutral"
+ confidence = random.uniform(45, 65)
+
+ context_note = f"\n\n🔗 Building on Previous Context:\n{previous_context[:300]}..." if previous_context else ""
+
+ return {
+ "agent": agent_info.get("name"),
+ "focus": agent_info.get("focus"),
+ "output_type": agent_info.get("output"),
+ "ticker": ticker,
+ "signal": signal,
+ "confidence": round(confidence, 2),
+ "analysis": f"""
+{agent_info.get('name')} Analysis for {ticker}
+{context_note}
+
+🎯 Focus Area: {agent_info.get('focus')}
+📈 Signal Strength: {signal_strength:.1%}
+
+Indicator Analysis:
+{chr(10).join(f" • {ind.replace('_', ' ').title()}: {score:.1%}" for ind, score in indicator_scores.items())}
+
+Assessment Metrics:
+ ✓ Signal Strength: {signal_strength:.1%}
+ ✓ Conviction Level: {conviction_level:.1%}
+ ✓ Overall Score: {total_score:.1%}
+
+Output: {agent_info.get('output')}
+Signal: {signal.upper()}
+Confidence: {confidence:.1f}%
+ """.strip(),
+ "indicator_scores": indicator_scores,
+ "signal_strength": round(signal_strength, 3),
+ "conviction_level": round(conviction_level, 3)
+ }
+
+def execute_agent(parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Main hedge fund agent execution"""
+ try:
+ agent_type = parameters.get("agent_type", "bridgewater")
+ tickers = parameters.get("tickers", ["SPY"])
+
+ if isinstance(tickers, str):
+ tickers = [tickers]
+
+ # Extract mediated context
+ mediated_context = None
+ if inputs and isinstance(inputs, dict):
+ mediated_context = inputs.get("mediated_analysis")
+
+ # Determine if it's a firm or multi-strategy agent
+ if agent_type in HEDGE_FUND_FIRMS:
+ analyzer = analyze_hedge_fund_firm
+ elif agent_type in MULTI_STRATEGY_AGENTS:
+ analyzer = analyze_multi_strategy
+ else:
+ return {"success": False, "error": f"Unknown agent type: {agent_type}"}
+
+ # Analyze all tickers
+ results = {}
+ for ticker in tickers:
+ analysis = analyzer(agent_type, ticker, parameters, mediated_context)
+ results[ticker] = analysis
+
+ response = {
+ "success": True,
+ "agent_type": agent_type,
+ "tickers_analyzed": len(tickers),
+ "signals": {ticker: results[ticker]["signal"] for ticker in results},
+ "analysis": results
+ }
+
+ if mediated_context:
+ response["used_previous_context"] = True
+
+ return response
+
+ except Exception as e:
+ return {"success": False, "error": str(e), "agent": "hedge_fund"}
+
+def main():
+ parser = argparse.ArgumentParser(description='Hedge Fund Agent - Multi-Strategy Analysis')
+ parser.add_argument('--parameters', type=str, required=True)
+ parser.add_argument('--inputs', type=str, required=True)
+ args = parser.parse_args()
+
+ try:
+ result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
+ print(json.dumps(result, indent=2))
+ sys.exit(0)
+ except Exception as e:
+ print(json.dumps({"success": False, "error": str(e), "agent": "hedge_fund"}), file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
new file mode 100644
index 000000000..9f06edc45
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
@@ -0,0 +1,1086 @@
+// agents.rs - Python Agent Execution Commands
+use serde::{Deserialize, Serialize};
+use tauri::Manager;
+use crate::utils::python::get_python_path;
+
+#[cfg(target_os = "windows")]
+use std::os::windows::process::CommandExt;
+
+#[cfg(target_os = "windows")]
+const CREATE_NO_WINDOW: u32 = 0x08000000;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AgentParameter {
+ pub name: String,
+ pub label: String,
+ #[serde(rename = "type")]
+ pub param_type: String,
+ pub required: bool,
+ pub default_value: Option<serde_json::Value>,
+ pub description: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct AgentMetadata {
+ pub id: String,
+ pub name: String,
+ #[serde(rename = "type")]
+ pub agent_type: String,
+ pub category: String,
+ pub description: String,
+ pub script_path: String,
+ pub parameters: Vec<AgentParameter>,
+ pub required_inputs: Vec<String>,
+ pub outputs: Vec<String>,
+ pub icon: String,
+ pub color: String,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct AgentExecutionResult {
+ pub success: bool,
+ pub data: Option<serde_json::Value>,
+ pub error: Option<String>,
+ pub execution_time_ms: u64,
+ pub agent_type: String,
+}
+
+/// Map agent type to script path
+fn get_agent_script_path(agent_type: &str) -> Option<&'static str> {
+ match agent_type {
+ // Trader/Investor Agents (CLI versions for Node Editor)
+ "warren_buffett" => Some("agents/TraderInvestorsAgent/warren_buffett_agent_cli.py"),
+ "charlie_munger" => Some("agents/TraderInvestorsAgent/charlie_munger_agent_cli.py"),
+ "benjamin_graham" => Some("agents/TraderInvestorsAgent/benjamin_graham_agent_cli.py"),
+ "seth_klarman" => Some("agents/TraderInvestorsAgent/seth_klarman_agent_cli.py"),
+ "howard_marks" => Some("agents/TraderInvestorsAgent/howard_marks_agent_cli.py"),
+ "joel_greenblatt" => Some("agents/TraderInvestorsAgent/joel_greenblatt_agent_cli.py"),
+ "david_einhorn" => Some("agents/TraderInvestorsAgent/david_einhorn_agent_cli.py"),
+ "bill_miller" => Some("agents/TraderInvestorsAgent/bill_miller_agent_cli.py"),
+ "jean_marie_eveillard" => Some("agents/TraderInvestorsAgent/jean_marie_eveillard_agent_cli.py"),
+ "marty_whitman" => Some("agents/TraderInvestorsAgent/marty_whitman_agent_cli.py"),
+
+ // Hedge Fund Agents - All use unified CLI wrapper
+ "macro_cycle" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "central_bank" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "behavioral" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "institutional_flow" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "innovation" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "geopolitical" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "currency" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "supply_chain" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "sentiment" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "regulatory" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "bridgewater" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "citadel" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "renaissance" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "two_sigma" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "de_shaw" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "elliott" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "pershing_square" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "arq_capital" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+
+ // Economic Agents (CLI versions for Node Editor)
+ "capitalism" => Some("agents/EconomicAgents/capitalism_agent_cli.py"),
+ "keynesian" => Some("agents/EconomicAgents/keynesian_agent_cli.py"),
+ "neoliberal" => Some("agents/EconomicAgents/neoliberal_agent_cli.py"),
+ "socialism" => Some("agents/EconomicAgents/socialism_agent_cli.py"),
+ "mixed_economy" => Some("agents/EconomicAgents/mixed_economy_agent_cli.py"),
+ "mercantilist" => Some("agents/EconomicAgents/mercantilist_agent_cli.py"),
+
+ // Geopolitics Agents - Prisoners of Geography (Tim Marshall)
+ "russia_geography" => Some("agents/GeopoliticsAgents/geopolitics_agent_cli.py"),
+ "china_geography" => Some("agents/GeopoliticsAgents/geopolitics_agent_cli.py"),
+ "usa_geography" => Some("agents/GeopoliticsAgents/geopolitics_agent_cli.py"),
+ "europe_geography" => Some("agents/GeopoliticsAgents/geopolitics_agent_cli.py"),
+ "middle_east_geography" => Some("agents/GeopoliticsAgents/geopolitics_agent_cli.py"),
+
+ // Geopolitics Agents - World Order (Kissinger)
+ "american_world" => Some("agents/GeopoliticsAgents/geopolitics_agent_cli.py"),
+ "chinese_world" => Some("agents/GeopoliticsAgents/geopolitics_agent_cli.py"),
+ "balance_power" => Some("agents/GeopoliticsAgents/geopolitics_agent_cli.py"),
+ "islamic_world" => Some("agents/GeopoliticsAgents/geopolitics_agent_cli.py"),
+ "nuclear_order" => Some("agents/GeopoliticsAgents/geopolitics_agent_cli.py"),
+
+ // Geopolitics Agents - Grand Chessboard (Brzezinski)
+ "eurasian_balkans" => Some("agents/GeopoliticsAgents/geopolitics_agent_cli.py"),
+ "democratic_bridgehead" => Some("agents/GeopoliticsAgents/geopolitics_agent_cli.py"),
+ "far_eastern_anchor" => Some("agents/GeopoliticsAgents/geopolitics_agent_cli.py"),
+
+ _ => None,
+ }
+}
+
+/// Get geopolitics agent parameters (shared across all geopolitics agents)
+fn get_geopolitics_agent_parameters() -> Vec<AgentParameter> {
+ vec![
+ AgentParameter {
+ name: "agent_type".to_string(),
+ label: "Agent Type".to_string(),
+ param_type: "string".to_string(),
+ required: true,
+ default_value: Some(serde_json::json!("russia_geography")),
+ description: Some("Specific geopolitics agent to use".to_string()),
+ },
+ AgentParameter {
+ name: "event".to_string(),
+ label: "Geopolitical Event".to_string(),
+ param_type: "string".to_string(),
+ required: true,
+ default_value: Some(serde_json::json!("Ukraine conflict 2024")),
+ description: Some("Event or situation to analyze".to_string()),
+ },
+ AgentParameter {
+ name: "framework".to_string(),
+ label: "Analysis Framework".to_string(),
+ param_type: "string".to_string(),
+ required: false,
+ default_value: Some(serde_json::json!("auto")),
+ description: Some("Framework: auto, geography, world_order, chessboard".to_string()),
+ },
+ ]
+}
+
+/// Get hedge fund agent parameters (shared across all hedge fund agents)
+fn get_hedge_fund_agent_parameters() -> Vec<AgentParameter> {
+ vec![
+ AgentParameter {
+ name: "agent_type".to_string(),
+ label: "Agent Type".to_string(),
+ param_type: "string".to_string(),
+ required: true,
+ default_value: Some(serde_json::json!("bridgewater")),
+ description: Some("Specific hedge fund agent to use".to_string()),
+ },
+ AgentParameter {
+ name: "tickers".to_string(),
+ label: "Stock Tickers".to_string(),
+ param_type: "array".to_string(),
+ required: true,
+ default_value: Some(serde_json::json!(["SPY"])),
+ description: Some("List of stock tickers to analyze".to_string()),
+ },
+ ]
+}
+
+/// Get economic agent parameters (shared across all economic agents)
+fn get_economic_agent_parameters() -> Vec<AgentParameter> {
+ vec![
+ AgentParameter {
+ name: "gdp".to_string(),
+ label: "GDP Growth (%)".to_string(),
+ param_type: "number".to_string(),
+ required: false,
+ default_value: Some(serde_json::json!(3.0)),
+ description: Some("Annual GDP growth rate".to_string()),
+ },
+ AgentParameter {
+ name: "inflation".to_string(),
+ label: "Inflation Rate (%)".to_string(),
+ param_type: "number".to_string(),
+ required: false,
+ default_value: Some(serde_json::json!(2.5)),
+ description: Some("Annual inflation rate".to_string()),
+ },
+ AgentParameter {
+ name: "unemployment".to_string(),
+ label: "Unemployment Rate (%)".to_string(),
+ param_type: "number".to_string(),
+ required: false,
+ default_value: Some(serde_json::json!(5.0)),
+ description: Some("Current unemployment rate".to_string()),
+ },
+ AgentParameter {
+ name: "interest_rate".to_string(),
+ label: "Interest Rate (%)".to_string(),
+ param_type: "number".to_string(),
+ required: false,
+ default_value: Some(serde_json::json!(5.0)),
+ description: Some("Central bank interest rate".to_string()),
+ },
+ AgentParameter {
+ name: "trade_balance".to_string(),
+ label: "Trade Balance (% GDP)".to_string(),
+ param_type: "number".to_string(),
+ required: false,
+ default_value: Some(serde_json::json!(0.0)),
+ description: Some("Trade balance as % of GDP".to_string()),
+ },
+ AgentParameter {
+ name: "government_spending".to_string(),
+ label: "Gov Spending (% GDP)".to_string(),
+ param_type: "number".to_string(),
+ required: false,
+ default_value: Some(serde_json::json!(35.0)),
+ description: Some("Government spending as % of GDP".to_string()),
+ },
+ AgentParameter {
+ name: "tax_rate".to_string(),
+ label: "Tax Rate (%)".to_string(),
+ param_type: "number".to_string(),
+ required: false,
+ default_value: Some(serde_json::json!(30.0)),
+ description: Some("Average tax rate".to_string()),
+ },
+ AgentParameter {
+ name: "private_investment".to_string(),
+ label: "Private Investment (% GDP)".to_string(),
+ param_type: "number".to_string(),
+ required: false,
+ default_value: Some(serde_json::json!(20.0)),
+ description: Some("Private sector investment as % of GDP".to_string()),
+ },
+ AgentParameter {
+ name: "consumer_confidence".to_string(),
+ label: "Consumer Confidence (0-100)".to_string(),
+ param_type: "number".to_string(),
+ required: false,
+ default_value: Some(serde_json::json!(65.0)),
+ description: Some("Consumer confidence index".to_string()),
+ },
+ ]
+}
+
+/// Get predefined agent metadata (internal helper)
+fn get_agent_metadata_internal(agent_type: &str) -> Option<AgentMetadata> {
+ let script_path = get_agent_script_path(agent_type)?;
+
+ // Standard ticker parameters for trader agents
+ let standard_ticker_params = vec![
+ AgentParameter {
+ name: "tickers".to_string(),
+ label: "Stock Tickers".to_string(),
+ param_type: "array".to_string(),
+ required: true,
+ default_value: Some(serde_json::json!(["AAPL"])),
+ description: Some("List of stock tickers to analyze".to_string()),
+ },
+ AgentParameter {
+ name: "end_date".to_string(),
+ label: "Analysis Date".to_string(),
+ param_type: "string".to_string(),
+ required: false,
+ default_value: Some(serde_json::json!("2024-12-31")),
+ description: Some("Date for analysis (YYYY-MM-DD)".to_string()),
+ },
+ ];
+
+ match agent_type {
+ // === TRADER/INVESTOR AGENTS ===
+ "warren_buffett" => Some(AgentMetadata {
+ id: "warren_buffett".to_string(),
+ name: "Warren Buffett".to_string(),
+ agent_type: "warren_buffett".to_string(),
+ category: "trader".to_string(),
+ description: "Value investing with economic moats and long-term focus".to_string(),
+ script_path: script_path.to_string(),
+ parameters: standard_ticker_params.clone(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "💰".to_string(),
+ color: "#22c55e".to_string(),
+ }),
+
+ "charlie_munger" => Some(AgentMetadata {
+ id: "charlie_munger".to_string(),
+ name: "Charlie Munger".to_string(),
+ agent_type: "charlie_munger".to_string(),
+ category: "trader".to_string(),
+ description: "Multidisciplinary thinking and rational decision-making".to_string(),
+ script_path: script_path.to_string(),
+ parameters: standard_ticker_params.clone(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🧠".to_string(),
+ color: "#3b82f6".to_string(),
+ }),
+
+ "benjamin_graham" => Some(AgentMetadata {
+ id: "benjamin_graham".to_string(),
+ name: "Benjamin Graham".to_string(),
+ agent_type: "benjamin_graham".to_string(),
+ category: "trader".to_string(),
+ description: "Deep value investing with margin of safety".to_string(),
+ script_path: script_path.to_string(),
+ parameters: standard_ticker_params.clone(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "📚".to_string(),
+ color: "#8b5cf6".to_string(),
+ }),
+
+ "seth_klarman" => Some(AgentMetadata {
+ id: "seth_klarman".to_string(),
+ name: "Seth Klarman".to_string(),
+ agent_type: "seth_klarman".to_string(),
+ category: "trader".to_string(),
+ description: "Risk management and distressed value opportunities".to_string(),
+ script_path: script_path.to_string(),
+ parameters: standard_ticker_params.clone(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🛡️".to_string(),
+ color: "#ef4444".to_string(),
+ }),
+
+ "howard_marks" => Some(AgentMetadata {
+ id: "howard_marks".to_string(),
+ name: "Howard Marks".to_string(),
+ agent_type: "howard_marks".to_string(),
+ category: "trader".to_string(),
+ description: "Market cycles and second-level thinking".to_string(),
+ script_path: script_path.to_string(),
+ parameters: standard_ticker_params.clone(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🔄".to_string(),
+ color: "#f59e0b".to_string(),
+ }),
+
+ "joel_greenblatt" => Some(AgentMetadata {
+ id: "joel_greenblatt".to_string(),
+ name: "Joel Greenblatt".to_string(),
+ agent_type: "joel_greenblatt".to_string(),
+ category: "trader".to_string(),
+ description: "Magic formula: high returns on capital at low prices".to_string(),
+ script_path: script_path.to_string(),
+ parameters: standard_ticker_params.clone(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "✨".to_string(),
+ color: "#10b981".to_string(),
+ }),
+
+ "david_einhorn" => Some(AgentMetadata {
+ id: "david_einhorn".to_string(),
+ name: "David Einhorn".to_string(),
+ agent_type: "david_einhorn".to_string(),
+ category: "trader".to_string(),
+ description: "Forensic accounting and value/short analysis".to_string(),
+ script_path: script_path.to_string(),
+ parameters: standard_ticker_params.clone(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🔍".to_string(),
+ color: "#ec4899".to_string(),
+ }),
+
+ "bill_miller" => Some(AgentMetadata {
+ id: "bill_miller".to_string(),
+ name: "Bill Miller".to_string(),
+ agent_type: "bill_miller".to_string(),
+ category: "trader".to_string(),
+ description: "Contrarian value with technology focus".to_string(),
+ script_path: script_path.to_string(),
+ parameters: standard_ticker_params.clone(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🎯".to_string(),
+ color: "#f59e0b".to_string(),
+ }),
+
+ "jean_marie_eveillard" => Some(AgentMetadata {
+ id: "jean_marie_eveillard".to_string(),
+ name: "Jean-Marie Eveillard".to_string(),
+ agent_type: "jean_marie_eveillard".to_string(),
+ category: "trader".to_string(),
+ description: "Global deep value and patient capital".to_string(),
+ script_path: script_path.to_string(),
+ parameters: standard_ticker_params.clone(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🌍".to_string(),
+ color: "#06b6d4".to_string(),
+ }),
+
+ "marty_whitman" => Some(AgentMetadata {
+ id: "marty_whitman".to_string(),
+ name: "Marty Whitman".to_string(),
+ agent_type: "marty_whitman".to_string(),
+ category: "trader".to_string(),
+ description: "Safe & cheap distressed value investing".to_string(),
+ script_path: script_path.to_string(),
+ parameters: standard_ticker_params.clone(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "💎".to_string(),
+ color: "#a855f7".to_string(),
+ }),
+
+ // === HEDGE FUND AGENTS - Multi-Strategy ===
+ "macro_cycle" => Some(AgentMetadata {
+ id: "macro_cycle".to_string(),
+ name: "Macro Cycle Agent".to_string(),
+ agent_type: "macro_cycle".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Business cycle analysis and economic phase identification".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🔄".to_string(),
+ color: "#3b82f6".to_string(),
+ }),
+
+ "central_bank" => Some(AgentMetadata {
+ id: "central_bank".to_string(),
+ name: "Central Bank Agent".to_string(),
+ agent_type: "central_bank".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Monetary policy analysis and interest rate forecasting".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🏦".to_string(),
+ color: "#06b6d4".to_string(),
+ }),
+
+ "behavioral" => Some(AgentMetadata {
+ id: "behavioral".to_string(),
+ name: "Behavioral Agent".to_string(),
+ agent_type: "behavioral".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Market psychology and sentiment analysis".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🧠".to_string(),
+ color: "#ec4899".to_string(),
+ }),
+
+ "institutional_flow" => Some(AgentMetadata {
+ id: "institutional_flow".to_string(),
+ name: "Institutional Flow Agent".to_string(),
+ agent_type: "institutional_flow".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Smart money tracking and institutional positioning".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "💼".to_string(),
+ color: "#10b981".to_string(),
+ }),
+
+ "innovation" => Some(AgentMetadata {
+ id: "innovation".to_string(),
+ name: "Innovation Agent".to_string(),
+ agent_type: "innovation".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Disruptive technology and innovation analysis".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "💡".to_string(),
+ color: "#f59e0b".to_string(),
+ }),
+
+ "geopolitical" => Some(AgentMetadata {
+ id: "geopolitical".to_string(),
+ name: "Geopolitical Agent".to_string(),
+ agent_type: "geopolitical".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Geopolitical risk and opportunity analysis".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🌍".to_string(),
+ color: "#8b5cf6".to_string(),
+ }),
+
+ "currency" => Some(AgentMetadata {
+ id: "currency".to_string(),
+ name: "Currency Agent".to_string(),
+ agent_type: "currency".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "FX markets and currency dynamics".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "💱".to_string(),
+ color: "#06b6d4".to_string(),
+ }),
+
+ "supply_chain" => Some(AgentMetadata {
+ id: "supply_chain".to_string(),
+ name: "Supply Chain Agent".to_string(),
+ agent_type: "supply_chain".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Supply chain disruptions and logistics".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🚚".to_string(),
+ color: "#22c55e".to_string(),
+ }),
+
+ "sentiment" => Some(AgentMetadata {
+ id: "sentiment".to_string(),
+ name: "Sentiment Agent".to_string(),
+ agent_type: "sentiment".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "News and social media sentiment tracking".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "📊".to_string(),
+ color: "#a855f7".to_string(),
+ }),
+
+ "regulatory" => Some(AgentMetadata {
+ id: "regulatory".to_string(),
+ name: "Regulatory Agent".to_string(),
+ agent_type: "regulatory".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Regulatory changes and compliance impact".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "⚖️".to_string(),
+ color: "#ef4444".to_string(),
+ }),
+
+ // === HEDGE FUND AGENTS - Famous Firms ===
+ "bridgewater" => Some(AgentMetadata {
+ id: "bridgewater".to_string(),
+ name: "Bridgewater Associates".to_string(),
+ agent_type: "bridgewater".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Ray Dalio: All Weather Portfolio + Economic Machine analysis".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🌊".to_string(),
+ color: "#2563eb".to_string(),
+ }),
+
+ "citadel" => Some(AgentMetadata {
+ id: "citadel".to_string(),
+ name: "Citadel".to_string(),
+ agent_type: "citadel".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Ken Griffin: Multi-strategy global macro and quantitative trading".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🏰".to_string(),
+ color: "#dc2626".to_string(),
+ }),
+
+ "renaissance" => Some(AgentMetadata {
+ id: "renaissance".to_string(),
+ name: "Renaissance Technologies".to_string(),
+ agent_type: "renaissance".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Jim Simons: Quantitative + mathematical models".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🔬".to_string(),
+ color: "#8b5cf6".to_string(),
+ }),
+
+ "two_sigma" => Some(AgentMetadata {
+ id: "two_sigma".to_string(),
+ name: "Two Sigma".to_string(),
+ agent_type: "two_sigma".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Data science + machine learning driven investing".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🤖".to_string(),
+ color: "#06b6d4".to_string(),
+ }),
+
+ "de_shaw" => Some(AgentMetadata {
+ id: "de_shaw".to_string(),
+ name: "D.E. Shaw".to_string(),
+ agent_type: "de_shaw".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "David Shaw: Computational finance and systematic trading".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "💻".to_string(),
+ color: "#10b981".to_string(),
+ }),
+
+ "elliott" => Some(AgentMetadata {
+ id: "elliott".to_string(),
+ name: "Elliott Management".to_string(),
+ agent_type: "elliott".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Paul Singer: Activist + distressed debt investing".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "⚡".to_string(),
+ color: "#f59e0b".to_string(),
+ }),
+
+ "pershing_square" => Some(AgentMetadata {
+ id: "pershing_square".to_string(),
+ name: "Pershing Square".to_string(),
+ agent_type: "pershing_square".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Bill Ackman: Concentrated activist value investing".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "🎯".to_string(),
+ color: "#ec4899".to_string(),
+ }),
+
+ "arq_capital" => Some(AgentMetadata {
+ id: "arq_capital".to_string(),
+ name: "ARQ Capital".to_string(),
+ agent_type: "arq_capital".to_string(),
+ category: "hedge-fund".to_string(),
+ description: "Quantitative multi-strategy with systematic risk management".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_hedge_fund_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["signals".to_string(), "analysis".to_string()],
+ icon: "📐".to_string(),
+ color: "#a855f7".to_string(),
+ }),
+
+ // === ECONOMIC SYSTEM AGENTS ===
+ "capitalism" => Some(AgentMetadata {
+ id: "capitalism".to_string(),
+ name: "Capitalism".to_string(),
+ agent_type: "capitalism".to_string(),
+ category: "economic".to_string(),
+ description: "Free market and competitive dynamics analysis".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_economic_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["market_efficiency".to_string(), "policy_recommendations".to_string()],
+ icon: "💼".to_string(),
+ color: "#22c55e".to_string(),
+ }),
+
+ "keynesian" => Some(AgentMetadata {
+ id: "keynesian".to_string(),
+ name: "Keynesian".to_string(),
+ agent_type: "keynesian".to_string(),
+ category: "economic".to_string(),
+ description: "Government intervention and fiscal policy focus".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_economic_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["fiscal_impact".to_string(), "policy_recommendations".to_string()],
+ icon: "🏛️".to_string(),
+ color: "#3b82f6".to_string(),
+ }),
+
+ "neoliberal" => Some(AgentMetadata {
+ id: "neoliberal".to_string(),
+ name: "Neoliberal".to_string(),
+ agent_type: "neoliberal".to_string(),
+ category: "economic".to_string(),
+ description: "Free markets, deregulation, and privatization".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_economic_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["market_freedom".to_string(), "policy_recommendations".to_string()],
+ icon: "📈".to_string(),
+ color: "#f97316".to_string(),
+ }),
+
+ "socialism" => Some(AgentMetadata {
+ id: "socialism".to_string(),
+ name: "Socialism".to_string(),
+ agent_type: "socialism".to_string(),
+ category: "economic".to_string(),
+ description: "Social ownership, equality, and workers' rights".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_economic_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["equality_index".to_string(), "policy_recommendations".to_string()],
+ icon: "🔴".to_string(),
+ color: "#dc2626".to_string(),
+ }),
+
+ "mixed_economy" => Some(AgentMetadata {
+ id: "mixed_economy".to_string(),
+ name: "Mixed Economy".to_string(),
+ agent_type: "mixed_economy".to_string(),
+ category: "economic".to_string(),
+ description: "Balanced approach combining private and public sectors".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_economic_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["balance_score".to_string(), "policy_recommendations".to_string()],
+ icon: "⚖️".to_string(),
+ color: "#8b5cf6".to_string(),
+ }),
+
+ "mercantilist" => Some(AgentMetadata {
+ id: "mercantilist".to_string(),
+ name: "Mercantilist".to_string(),
+ agent_type: "mercantilist".to_string(),
+ category: "economic".to_string(),
+ description: "Trade surplus and national economic power focus".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_economic_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["trade_strength".to_string(), "policy_recommendations".to_string()],
+ icon: "⚓".to_string(),
+ color: "#0891b2".to_string(),
+ }),
+
+ // === GEOPOLITICS AGENTS - Prisoners of Geography ===
+ "russia_geography" => Some(AgentMetadata {
+ id: "russia_geography".to_string(),
+ name: "Russia Geography".to_string(),
+ agent_type: "russia_geography".to_string(),
+ category: "geopolitics".to_string(),
+ description: "Tim Marshall: Geographic determinism - plains vulnerability, warm-water ports".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_geopolitics_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["geographic_analysis".to_string()],
+ icon: "🏔️".to_string(),
+ color: "#dc2626".to_string(),
+ }),
+
+ "china_geography" => Some(AgentMetadata {
+ id: "china_geography".to_string(),
+ name: "China Geography".to_string(),
+ agent_type: "china_geography".to_string(),
+ category: "geopolitics".to_string(),
+ description: "Tim Marshall: Maritime vulnerability, unity challenges, Himalayan barrier".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_geopolitics_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["geographic_analysis".to_string()],
+ icon: "🏯".to_string(),
+ color: "#ef4444".to_string(),
+ }),
+
+ "usa_geography" => Some(AgentMetadata {
+ id: "usa_geography".to_string(),
+ name: "USA Geography".to_string(),
+ agent_type: "usa_geography".to_string(),
+ category: "geopolitics".to_string(),
+ description: "Tim Marshall: Geographic advantages, natural moats, resource abundance".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_geopolitics_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["geographic_analysis".to_string()],
+ icon: "🗽".to_string(),
+ color: "#3b82f6".to_string(),
+ }),
+
+ "europe_geography" => Some(AgentMetadata {
+ id: "europe_geography".to_string(),
+ name: "Europe Geography".to_string(),
+ agent_type: "europe_geography".to_string(),
+ category: "geopolitics".to_string(),
+ description: "Tim Marshall: Fragmentation vs integration, geographic barriers".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_geopolitics_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["geographic_analysis".to_string()],
+ icon: "🏰".to_string(),
+ color: "#8b5cf6".to_string(),
+ }),
+
+ "middle_east_geography" => Some(AgentMetadata {
+ id: "middle_east_geography".to_string(),
+ name: "Middle East Geography".to_string(),
+ agent_type: "middle_east_geography".to_string(),
+ category: "geopolitics".to_string(),
+ description: "Tim Marshall: Desert geography, resource curse, artificial borders".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_geopolitics_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["geographic_analysis".to_string()],
+ icon: "🏜️".to_string(),
+ color: "#f59e0b".to_string(),
+ }),
+
+ // === GEOPOLITICS AGENTS - World Order ===
+ "american_world" => Some(AgentMetadata {
+ id: "american_world".to_string(),
+ name: "American World Order".to_string(),
+ agent_type: "american_world".to_string(),
+ category: "geopolitics".to_string(),
+ description: "Kissinger: Liberal internationalism, democratic values, exceptionalism".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_geopolitics_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["world_order_analysis".to_string()],
+ icon: "🦅".to_string(),
+ color: "#2563eb".to_string(),
+ }),
+
+ "chinese_world" => Some(AgentMetadata {
+ id: "chinese_world".to_string(),
+ name: "Chinese World Order".to_string(),
+ agent_type: "chinese_world".to_string(),
+ category: "geopolitics".to_string(),
+ description: "Kissinger: Middle Kingdom centrality, hierarchical system, tributary model".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_geopolitics_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["world_order_analysis".to_string()],
+ icon: "🐉".to_string(),
+ color: "#dc2626".to_string(),
+ }),
+
+ "balance_power" => Some(AgentMetadata {
+ id: "balance_power".to_string(),
+ name: "Balance of Power".to_string(),
+ agent_type: "balance_power".to_string(),
+ category: "geopolitics".to_string(),
+ description: "Kissinger: Equilibrium maintenance, power transitions, realpolitik".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_geopolitics_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["world_order_analysis".to_string()],
+ icon: "⚖️".to_string(),
+ color: "#6366f1".to_string(),
+ }),
+
+ "islamic_world" => Some(AgentMetadata {
+ id: "islamic_world".to_string(),
+ name: "Islamic World Order".to_string(),
+ agent_type: "islamic_world".to_string(),
+ category: "geopolitics".to_string(),
+ description: "Kissinger: Ummah unity, Sharia governance, caliphate legacy".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_geopolitics_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["world_order_analysis".to_string()],
+ icon: "☪️".to_string(),
+ color: "#10b981".to_string(),
+ }),
+
+ "nuclear_order" => Some(AgentMetadata {
+ id: "nuclear_order".to_string(),
+ name: "Nuclear Order".to_string(),
+ agent_type: "nuclear_order".to_string(),
+ category: "geopolitics".to_string(),
+ description: "Kissinger: Deterrence theory, arms control, nuclear diplomacy".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_geopolitics_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["world_order_analysis".to_string()],
+ icon: "☢️".to_string(),
+ color: "#f59e0b".to_string(),
+ }),
+
+ // === GEOPOLITICS AGENTS - Grand Chessboard ===
+ "eurasian_balkans" => Some(AgentMetadata {
+ id: "eurasian_balkans".to_string(),
+ name: "Eurasian Balkans".to_string(),
+ agent_type: "eurasian_balkans".to_string(),
+ category: "geopolitics".to_string(),
+ description: "Brzezinski: Pivotal region, strategic instability, power competition".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_geopolitics_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["chessboard_analysis".to_string()],
+ icon: "♟️".to_string(),
+ color: "#a855f7".to_string(),
+ }),
+
+ "democratic_bridgehead" => Some(AgentMetadata {
+ id: "democratic_bridgehead".to_string(),
+ name: "Democratic Bridgehead".to_string(),
+ agent_type: "democratic_bridgehead".to_string(),
+ category: "geopolitics".to_string(),
+ description: "Brzezinski: Western influence projection, democratic anchor".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_geopolitics_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["chessboard_analysis".to_string()],
+ icon: "🌉".to_string(),
+ color: "#06b6d4".to_string(),
+ }),
+
+ "far_eastern_anchor" => Some(AgentMetadata {
+ id: "far_eastern_anchor".to_string(),
+ name: "Far Eastern Anchor".to_string(),
+ agent_type: "far_eastern_anchor".to_string(),
+ category: "geopolitics".to_string(),
+ description: "Brzezinski: US-Japan alliance, Pacific stability pillar".to_string(),
+ script_path: script_path.to_string(),
+ parameters: get_geopolitics_agent_parameters(),
+ required_inputs: vec![],
+ outputs: vec!["chessboard_analysis".to_string()],
+ icon: "⚓".to_string(),
+ color: "#ec4899".to_string(),
+ }),
+
+ _ => None,
+ }
+}
+
+#[tauri::command]
+pub async fn list_available_agents() -> Result<Vec<AgentMetadata>, String> {
+ let mut agents = Vec::new();
+
+ // Trader agents
+ let trader_types = vec![
+ "warren_buffett", "charlie_munger", "benjamin_graham",
+ "seth_klarman", "howard_marks", "joel_greenblatt",
+ "david_einhorn", "bill_miller", "jean_marie_eveillard", "marty_whitman"
+ ];
+
+ // Hedge fund agents
+ let hedge_fund_types = vec![
+ "macro_cycle", "central_bank", "behavioral", "institutional_flow",
+ "innovation", "geopolitical", "currency", "supply_chain",
+ "sentiment", "regulatory", "bridgewater", "citadel",
+ "renaissance", "two_sigma", "de_shaw", "elliott",
+ "pershing_square", "arq_capital"
+ ];
+
+ // Economic agents
+ let economic_types = vec![
+ "capitalism", "keynesian", "neoliberal", "socialism",
+ "mixed_economy", "mercantilist"
+ ];
+
+ // Geopolitics agents
+ let geopolitics_types = vec![
+ "russia_geography", "china_geography", "usa_geography", "europe_geography", "middle_east_geography",
+ "american_world", "chinese_world", "balance_power", "islamic_world", "nuclear_order",
+ "eurasian_balkans", "democratic_bridgehead", "far_eastern_anchor"
+ ];
+
+ for agent_type in trader_types.iter()
+ .chain(hedge_fund_types.iter())
+ .chain(economic_types.iter())
+ .chain(geopolitics_types.iter()) {
+ if let Some(metadata) = get_agent_metadata_internal(agent_type) {
+ agents.push(metadata);
+ }
+ }
+
+ Ok(agents)
+}
+
+#[tauri::command]
+pub async fn execute_python_agent(
+ app: tauri::AppHandle,
+ agent_type: String,
+ parameters: serde_json::Value,
+ inputs: serde_json::Value,
+) -> Result<AgentExecutionResult, String> {
+ let start_time = std::time::Instant::now();
+
+ // Get script path
+ let script_path = get_agent_script_path(&agent_type)
+ .ok_or_else(|| format!("Unknown agent type: {}", agent_type))?;
+
+ // Get Python executable
+ let python_path = get_python_path(&app)?;
+
+ // Get full script path - handle dev vs prod differently
+ let full_script_path = if cfg!(debug_assertions) {
+ // Development mode: use resources directly from project root
+ let current_dir = std::env::current_dir()
+ .map_err(|e| format!("Failed to get current directory: {}", e))?;
+
+ // Check if we're already in src-tauri, if so go up one level
+ let base_dir = if current_dir.ends_with("src-tauri") {
+ current_dir
+ } else {
+ current_dir.join("src-tauri")
+ };
+
+ base_dir
+ .join("resources")
+ .join("scripts")
+ .join(script_path)
+ } else {
+ // Production mode: use Tauri's resource directory
+ let resource_dir = app.path().resource_dir()
+ .map_err(|e| format!("Failed to get resource directory: {}", e))?;
+
+ resource_dir
+ .join("resources")
+ .join("scripts")
+ .join(script_path)
+ };
+
+ // Verify script exists
+ if !full_script_path.exists() {
+ return Err(format!("Script not found: {}", full_script_path.display()));
+ }
+
+ // Build command
+ let mut cmd = std::process::Command::new(&python_path);
+ cmd.arg(&full_script_path)
+ .arg("--parameters")
+ .arg(serde_json::to_string(&parameters).unwrap_or_default())
+ .arg("--inputs")
+ .arg(serde_json::to_string(&inputs).unwrap_or_default());
+
+ // Hide console on Windows
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+
+ // Execute
+ let output = cmd.output()
+ .map_err(|e| format!("Failed to execute Python: {}", e))?;
+
+ let execution_time = start_time.elapsed().as_millis() as u64;
+
+ if output.status.success() {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ // Parse JSON output from Python
+ match serde_json::from_str::<serde_json::Value>(&stdout) {
+ Ok(data) => Ok(AgentExecutionResult {
+ success: true,
+ data: Some(data),
+ error: None,
+ execution_time_ms: execution_time,
+ agent_type,
+ }),
+ Err(e) => Ok(AgentExecutionResult {
+ success: true,
+ data: Some(serde_json::json!({ "raw_output": stdout.to_string() })),
+ error: Some(format!("JSON parse warning: {}", e)),
+ execution_time_ms: execution_time,
+ agent_type,
+ }),
+ }
+ } else {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ Ok(AgentExecutionResult {
+ success: false,
+ data: None,
+ error: Some(stderr.to_string()),
+ execution_time_ms: execution_time,
+ agent_type,
+ })
+ }
+}
+
+#[tauri::command]
+pub async fn get_agent_metadata(agent_type: String) -> Result<AgentMetadata, String> {
+ get_agent_metadata_internal(&agent_type)
+ .ok_or_else(|| format!("Agent not found: {}", agent_type))
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
index e7d21b49b..c85003d05 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
@@ -53,3 +53,6 @@ pub mod sentinelhub;
// Code editor and Jupyter notebook
pub mod jupyter;
+
+// Python Agents
+pub mod agents;
diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rs
index 072883580..dc0738c52 100644
--- a/fincept-terminal-desktop/src-tauri/src/lib.rs
+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs
@@ -914,7 +914,11 @@ pub fn run() {
commands::jupyter::create_new_notebook,
commands::jupyter::get_python_version,
commands::jupyter::install_python_package,
- commands::jupyter::list_python_packages
+ commands::jupyter::list_python_packages,
+ // Python Agent Commands
+ commands::agents::list_available_agents,
+ commands::agents::execute_python_agent,
+ commands::agents::get_agent_metadata
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
diff --git a/fincept-terminal-desktop/src/App.css b/fincept-terminal-desktop/src/App.css
index e05704e20..85feae9ae 100644
--- a/fincept-terminal-desktop/src/App.css
+++ b/fincept-terminal-desktop/src/App.css
@@ -113,6 +113,8 @@
@layer base {
* {
@apply border-border outline-ring/50;
+ /* Fix passive event listener warning */
+ touch-action: pan-y pan-x;
}
body {
@apply bg-background text-foreground;
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index 244901339..3f1ed95ba 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -16,7 +16,6 @@ import MarketplaceTab from '@/components/tabs/MarketplaceTab';
import PortfolioTab from '@/components/tabs/PortfolioTab';
import AnalyticsTab from '@/components/tabs/AnalyticsTab';
import EquityResearchTab from '@/components/tabs/EquityResearchTab';
-import FixedIncomeTab from '@/components/tabs/FixedIncomeTab';
import OptionsTab from '@/components/tabs/OptionsTab';
import EconomicCalendarTab from '@/components/tabs/EconomicCalendarTab';
import ScreenerTab from '@/components/tabs/ScreenerTab';
@@ -28,7 +27,6 @@ import MaritimeTab from '@/components/tabs/MaritimeTab';
import SettingsTab from '@/components/tabs/SettingsTab';
import NodeEditorTab from '@/components/tabs/NodeEditorTab';
import DataSourcesTab from '@/components/tabs/data-sources/DataSourcesTab';
-import AgentsTab from '@/components/tabs/agents/AgentsTab';
import DataMappingTab from '@/components/tabs/data-mapping/DataMappingTab';
import MCPTab from '@/components/tabs/mcp';
import FyersTab from '@/components/tabs/fyers';
@@ -620,12 +618,6 @@ export default function FinxeptTerminal() {
>
Polygon EQ
</TabsTrigger>
- <TabsTrigger
- value="fixedincome"
- style={activeTab === 'fixedincome' ? tabStyles.active : tabStyles.default}
- >
- Fixed Income
- </TabsTrigger>
<TabsTrigger
value="options"
style={activeTab === 'options' ? tabStyles.active : tabStyles.default}
@@ -698,12 +690,6 @@ export default function FinxeptTerminal() {
>
Data Sources
</TabsTrigger>
- <TabsTrigger
- value="agents"
- style={activeTab === 'agents' ? tabStyles.active : tabStyles.default}
- >
- Agents
- </TabsTrigger>
<TabsTrigger
value="datamapping"
style={activeTab === 'datamapping' ? tabStyles.active : tabStyles.default}
@@ -821,9 +807,6 @@ export default function FinxeptTerminal() {
<TabsContent value="polygon" className="h-full m-0 p-0">
<PolygonEqTab />
</TabsContent>
- <TabsContent value="fixedincome" className="h-full m-0 p-0">
- <FixedIncomeTab />
- </TabsContent>
<TabsContent value="options" className="h-full m-0 p-0">
<OptionsTab />
</TabsContent>
@@ -863,9 +846,6 @@ export default function FinxeptTerminal() {
<TabsContent value="support" className="h-full m-0 p-0">
<SupportTicketTab />
</TabsContent>
- <TabsContent value="agents" className="h-full m-0 p-0">
- <AgentsTab />
- </TabsContent>
<TabsContent value="datamapping" className="h-full m-0 p-0">
<DataMappingTab />
</TabsContent>
diff --git a/fincept-terminal-desktop/src/components/settings/DataSourcesPanel.tsx b/fincept-terminal-desktop/src/components/settings/DataSourcesPanel.tsx
new file mode 100644
index 000000000..616765e9b
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/settings/DataSourcesPanel.tsx
@@ -0,0 +1,886 @@
+// Unified Data Sources Panel for Settings Tab
+// Displays and manages both WebSocket and REST API data sources
+
+import React, { useState, useEffect } from 'react';
+import { Plus, Wifi, Database, Edit3, Trash2, Power, PowerOff, Search, Filter, RefreshCw } from 'lucide-react';
+import { DataSource } from '@/services/sqliteService';
+import {
+ getAllDataSources,
+ toggleDataSource,
+ deleteDataSource,
+ createWebSocketDataSource,
+ updateDataSource,
+ getDataSourceStats,
+ getWebSocketTopic,
+ parseDataSourceConfig
+} from '@/services/dataSourceRegistry';
+import { getAvailableProviders } from '@/services/websocket';
+
+interface DataSourcesPanelProps {
+ colors: any;
+}
+
+export function DataSourcesPanel({ colors }: DataSourcesPanelProps) {
+ const [dataSources, setDataSources] = useState<DataSource[]>([]);
+ const [filteredSources, setFilteredSources] = useState<DataSource[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [stats, setStats] = useState({ total: 0, websocket: 0, restApi: 0, enabled: 0, disabled: 0 });
+ const [searchQuery, setSearchQuery] = useState('');
+ const [filterType, setFilterType] = useState<'all' | 'websocket' | 'rest_api'>('all');
+ const [showAddDialog, setShowAddDialog] = useState(false);
+ const [showEditDialog, setShowEditDialog] = useState(false);
+ const [editingSource, setEditingSource] = useState<DataSource | null>(null);
+
+ // Add WebSocket form state
+ const [newWSForm, setNewWSForm] = useState({
+ alias: '',
+ displayName: '',
+ description: '',
+ provider: 'kraken',
+ channel: 'ticker',
+ symbol: ''
+ });
+
+ // Edit form state
+ const [editWSForm, setEditWSForm] = useState({
+ alias: '',
+ displayName: '',
+ description: '',
+ provider: 'kraken',
+ channel: 'ticker',
+ symbol: ''
+ });
+
+ const availableProviders = getAvailableProviders();
+
+ useEffect(() => {
+ loadDataSources();
+ }, []);
+
+ useEffect(() => {
+ applyFilters();
+ }, [dataSources, searchQuery, filterType]);
+
+ async function loadDataSources() {
+ try {
+ setLoading(true);
+ const sources = await getAllDataSources();
+ const statistics = await getDataSourceStats();
+ setDataSources(sources);
+ setStats(statistics);
+ } catch (error) {
+ console.error('Failed to load data sources:', error);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ function applyFilters() {
+ let filtered = [...dataSources];
+
+ // Filter by type
+ if (filterType !== 'all') {
+ filtered = filtered.filter(s => s.type === filterType);
+ }
+
+ // Filter by search query
+ if (searchQuery) {
+ const query = searchQuery.toLowerCase();
+ filtered = filtered.filter(s =>
+ s.alias.toLowerCase().includes(query) ||
+ s.display_name.toLowerCase().includes(query) ||
+ s.description?.toLowerCase().includes(query) ||
+ s.provider.toLowerCase().includes(query)
+ );
+ }
+
+ setFilteredSources(filtered);
+ }
+
+ async function handleToggle(id: string) {
+ try {
+ await toggleDataSource(id);
+ await loadDataSources();
+ } catch (error) {
+ console.error('Failed to toggle data source:', error);
+ alert('Failed to toggle data source');
+ }
+ }
+
+ async function handleDelete(id: string) {
+ if (!confirm('Delete this data source? This cannot be undone.')) {
+ return;
+ }
+
+ try {
+ await deleteDataSource(id);
+ await loadDataSources();
+ } catch (error) {
+ console.error('Failed to delete data source:', error);
+ alert('Failed to delete data source');
+ }
+ }
+
+ async function handleAddWebSocket() {
+ if (!newWSForm.alias || !newWSForm.displayName || !newWSForm.provider || !newWSForm.channel) {
+ alert('Please fill in all required fields');
+ return;
+ }
+
+ try {
+ const result = await createWebSocketDataSource({
+ alias: newWSForm.alias,
+ displayName: newWSForm.displayName,
+ description: newWSForm.description,
+ provider: newWSForm.provider,
+ channel: newWSForm.channel,
+ symbol: newWSForm.symbol || undefined,
+ enabled: true
+ });
+
+ if (result.success) {
+ setShowAddDialog(false);
+ setNewWSForm({
+ alias: '',
+ displayName: '',
+ description: '',
+ provider: 'kraken',
+ channel: 'ticker',
+ symbol: ''
+ });
+ await loadDataSources();
+ } else {
+ alert(result.message);
+ }
+ } catch (error) {
+ console.error('Failed to create data source:', error);
+ alert('Failed to create data source');
+ }
+ }
+
+ function handleEditClick(source: DataSource) {
+ setEditingSource(source);
+
+ if (source.type === 'websocket') {
+ const config = parseDataSourceConfig(source);
+ if (config) {
+ setEditWSForm({
+ alias: source.alias,
+ displayName: source.display_name,
+ description: source.description || '',
+ provider: (config as any).provider || 'kraken',
+ channel: (config as any).channel || 'ticker',
+ symbol: (config as any).symbol || ''
+ });
+ }
+ }
+
+ setShowEditDialog(true);
+ }
+
+ async function handleUpdateWebSocket() {
+ if (!editingSource || !editWSForm.alias || !editWSForm.displayName || !editWSForm.provider || !editWSForm.channel) {
+ alert('Please fill in all required fields');
+ return;
+ }
+
+ try {
+ const updatedSource: DataSource = {
+ ...editingSource,
+ alias: editWSForm.alias,
+ display_name: editWSForm.displayName,
+ description: editWSForm.description,
+ provider: editWSForm.provider,
+ config: JSON.stringify({
+ provider: editWSForm.provider,
+ channel: editWSForm.channel,
+ symbol: editWSForm.symbol || undefined
+ })
+ };
+
+ const result = await updateDataSource(updatedSource);
+
+ if (result.success) {
+ setShowEditDialog(false);
+ setEditingSource(null);
+ setEditWSForm({
+ alias: '',
+ displayName: '',
+ description: '',
+ provider: 'kraken',
+ channel: 'ticker',
+ symbol: ''
+ });
+ await loadDataSources();
+ } else {
+ alert(result.message);
+ }
+ } catch (error) {
+ console.error('Failed to update data source:', error);
+ alert('Failed to update data source');
+ }
+ }
+
+ function getSourceIcon(type: string) {
+ return type === 'websocket' ? Wifi : Database;
+ }
+
+ function getSourceStatus(source: DataSource) {
+ if (!source.enabled) return { color: 'text-gray-500', text: 'Disabled' };
+ if (source.type === 'websocket') return { color: 'text-green-500', text: 'Live' };
+ return { color: 'text-blue-500', text: 'Ready' };
+ }
+
+ return (
+ <div className="space-y-6">
+ {/* Header */}
+ <div>
+ <h2 style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
+ DATA SOURCES
+ </h2>
+ <p style={{ color: colors.text, fontSize: '10px' }}>
+ Manage WebSocket connections and REST API integrations. Create aliases to easily reference data sources across the terminal.
+ </p>
+ </div>
+
+ {/* Statistics */}
+ <div className="grid grid-cols-5 gap-4">
+ <div style={{ backgroundColor: colors.panel, border: `1px solid ${colors.primary}` }} className="p-3 rounded">
+ <div style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold' }}>TOTAL</div>
+ <div style={{ color: colors.primary, fontSize: '20px', fontWeight: 'bold' }}>{stats.total}</div>
+ </div>
+ <div style={{ backgroundColor: colors.panel, border: `1px solid ${colors.primary}` }} className="p-3 rounded">
+ <div style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold' }}>WEBSOCKET</div>
+ <div style={{ color: '#10b981', fontSize: '20px', fontWeight: 'bold' }}>{stats.websocket}</div>
+ </div>
+ <div style={{ backgroundColor: colors.panel, border: `1px solid ${colors.primary}` }} className="p-3 rounded">
+ <div style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold' }}>REST API</div>
+ <div style={{ color: '#3b82f6', fontSize: '20px', fontWeight: 'bold' }}>{stats.restApi}</div>
+ </div>
+ <div style={{ backgroundColor: colors.panel, border: `1px solid ${colors.primary}` }} className="p-3 rounded">
+ <div style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold' }}>ENABLED</div>
+ <div style={{ color: '#10b981', fontSize: '20px', fontWeight: 'bold' }}>{stats.enabled}</div>
+ </div>
+ <div style={{ backgroundColor: colors.panel, border: `1px solid ${colors.primary}` }} className="p-3 rounded">
+ <div style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold' }}>DISABLED</div>
+ <div style={{ color: colors.text, fontSize: '20px', fontWeight: 'bold' }}>{stats.disabled}</div>
+ </div>
+ </div>
+
+ {/* Toolbar */}
+ <div className="flex items-center gap-3">
+ <div className="flex-1 relative">
+ <Search size={14} className="absolute left-3 top-1/2 transform -translate-y-1/2" style={{ color: colors.primary }} />
+ <input
+ type="text"
+ placeholder="Search data sources..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ style={{
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ padding: '8px 8px 8px 36px',
+ borderRadius: '4px',
+ width: '100%'
+ }}
+ />
+ </div>
+
+ <select
+ value={filterType}
+ onChange={(e) => setFilterType(e.target.value as any)}
+ style={{
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ padding: '8px 12px',
+ borderRadius: '4px'
+ }}
+ >
+ <option style={{ backgroundColor: colors.panel, color: colors.text }} value="all">All Types</option>
+ <option style={{ backgroundColor: colors.panel, color: colors.text }} value="websocket">WebSocket</option>
+ <option style={{ backgroundColor: colors.panel, color: colors.text }} value="rest_api">REST API</option>
+ </select>
+
+ <button
+ onClick={loadDataSources}
+ style={{
+ backgroundColor: colors.panel,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ padding: '8px 12px',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ cursor: 'pointer'
+ }}
+ >
+ <RefreshCw size={14} />
+ REFRESH
+ </button>
+
+ <button
+ onClick={() => setShowAddDialog(true)}
+ style={{
+ backgroundColor: colors.primary,
+ color: colors.background,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ padding: '8px 12px',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ cursor: 'pointer'
+ }}
+ >
+ <Plus size={14} />
+ ADD SOURCE
+ </button>
+ </div>
+
+ {/* Data Sources List */}
+ {loading ? (
+ <div style={{ textAlign: 'center', padding: '40px', color: colors.text }}>
+ Loading data sources...
+ </div>
+ ) : filteredSources.length === 0 ? (
+ <div style={{ textAlign: 'center', padding: '40px' }}>
+ <p style={{ color: colors.text, marginBottom: '16px' }}>
+ {searchQuery || filterType !== 'all' ? 'No data sources match your filters' : 'No data sources yet'}
+ </p>
+ {!searchQuery && filterType === 'all' && (
+ <button
+ onClick={() => setShowAddDialog(true)}
+ style={{
+ backgroundColor: colors.primary,
+ color: colors.background,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ padding: '10px 16px',
+ borderRadius: '4px',
+ cursor: 'pointer'
+ }}
+ >
+ Create First Data Source
+ </button>
+ )}
+ </div>
+ ) : (
+ <div className="space-y-3">
+ {filteredSources.map((source) => {
+ const Icon = getSourceIcon(source.type);
+ const status = getSourceStatus(source);
+ const topic = source.type === 'websocket' ? getWebSocketTopic(source) : null;
+
+ return (
+ <div
+ key={source.id}
+ style={{
+ backgroundColor: colors.panel,
+ border: `1px solid ${source.enabled ? colors.primary : '#444'}`,
+ borderRadius: '6px',
+ padding: '16px'
+ }}
+ >
+ <div className="flex items-start justify-between">
+ <div className="flex items-start gap-3 flex-1">
+ <Icon size={18} style={{ color: source.enabled ? colors.primary : colors.text, marginTop: '2px' }} />
+
+ <div className="flex-1">
+ <div className="flex items-center gap-2 mb-1">
+ <h3 style={{ color: colors.text, fontSize: '13px', fontWeight: 'bold' }}>
+ {source.display_name}
+ </h3>
+ <code style={{
+ backgroundColor: colors.background,
+ color: colors.primary,
+ fontSize: '10px',
+ padding: '2px 6px',
+ borderRadius: '3px'
+ }}>
+ {source.alias}
+ </code>
+ <span style={{ fontSize: '10px', color: status.color, fontWeight: 'bold' }}>
+ ● {status.text}
+ </span>
+ </div>
+
+ {source.description && (
+ <p style={{ color: colors.text, fontSize: '11px', marginBottom: '8px' }}>
+ {source.description}
+ </p>
+ )}
+
+ <div className="flex items-center gap-4" style={{ fontSize: '10px' }}>
+ <span style={{ color: colors.text }}>
+ <strong style={{ color: colors.primary }}>Type:</strong> {source.type === 'websocket' ? 'WebSocket' : 'REST API'}
+ </span>
+ <span style={{ color: colors.text }}>
+ <strong style={{ color: colors.primary }}>Provider:</strong> {source.provider}
+ </span>
+ {topic && (
+ <span style={{ color: colors.text }}>
+ <strong style={{ color: colors.primary }}>Topic:</strong> <code style={{ color: colors.primary }}>{topic}</code>
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => handleEditClick(source)}
+ style={{
+ padding: '6px',
+ borderRadius: '4px',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.primary,
+ cursor: 'pointer'
+ }}
+ title="Edit"
+ >
+ <Edit3 size={14} />
+ </button>
+
+ <button
+ onClick={() => handleToggle(source.id)}
+ style={{
+ padding: '6px',
+ borderRadius: '4px',
+ backgroundColor: source.enabled ? colors.background : colors.primary,
+ border: `1px solid ${colors.primary}`,
+ color: source.enabled ? colors.text : colors.background,
+ cursor: 'pointer'
+ }}
+ title={source.enabled ? 'Disable' : 'Enable'}
+ >
+ {source.enabled ? <Power size={14} /> : <PowerOff size={14} />}
+ </button>
+
+ <button
+ onClick={() => handleDelete(source.id)}
+ style={{
+ padding: '6px',
+ borderRadius: '4px',
+ backgroundColor: colors.background,
+ border: `1px solid #ef4444`,
+ color: '#ef4444',
+ cursor: 'pointer'
+ }}
+ title="Delete"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {/* Add WebSocket Dialog */}
+ {showAddDialog && (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0, 0, 0, 0.9)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 1000
+ }}>
+ <div style={{
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.primary}`,
+ borderRadius: '8px',
+ padding: '24px',
+ maxWidth: '500px',
+ width: '100%'
+ }}>
+ <h3 style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', marginBottom: '16px' }}>
+ Add WebSocket Data Source
+ </h3>
+
+ <div className="space-y-4">
+ <div>
+ <label style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold', display: 'block', marginBottom: '6px' }}>
+ ALIAS (short name)
+ </label>
+ <input
+ type="text"
+ placeholder="btc_live"
+ value={newWSForm.alias}
+ onChange={(e) => setNewWSForm({ ...newWSForm, alias: e.target.value })}
+ style={{
+ width: '100%',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ padding: '8px 12px',
+ borderRadius: '4px'
+ }}
+ />
+ </div>
+
+ <div>
+ <label style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold', display: 'block', marginBottom: '6px' }}>
+ DISPLAY NAME
+ </label>
+ <input
+ type="text"
+ placeholder="Bitcoin Price"
+ value={newWSForm.displayName}
+ onChange={(e) => setNewWSForm({ ...newWSForm, displayName: e.target.value })}
+ style={{
+ width: '100%',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ padding: '8px 12px',
+ borderRadius: '4px'
+ }}
+ />
+ </div>
+
+ <div>
+ <label style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold', display: 'block', marginBottom: '6px' }}>
+ DESCRIPTION
+ </label>
+ <input
+ type="text"
+ placeholder="Real-time Bitcoin price from Kraken"
+ value={newWSForm.description}
+ onChange={(e) => setNewWSForm({ ...newWSForm, description: e.target.value })}
+ style={{
+ width: '100%',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ padding: '8px 12px',
+ borderRadius: '4px'
+ }}
+ />
+ </div>
+
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <label style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold', display: 'block', marginBottom: '6px' }}>
+ PROVIDER
+ </label>
+ <select
+ value={newWSForm.provider}
+ onChange={(e) => setNewWSForm({ ...newWSForm, provider: e.target.value })}
+ style={{
+ width: '100%',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ padding: '8px 12px',
+ borderRadius: '4px'
+ }}
+ >
+ {availableProviders.map(p => (
+ <option key={p} value={p} style={{ backgroundColor: colors.background, color: colors.text }}>{p}</option>
+ ))}
+ </select>
+ </div>
+
+ <div>
+ <label style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold', display: 'block', marginBottom: '6px' }}>
+ CHANNEL
+ </label>
+ <input
+ type="text"
+ placeholder="ticker"
+ value={newWSForm.channel}
+ onChange={(e) => setNewWSForm({ ...newWSForm, channel: e.target.value })}
+ style={{
+ width: '100%',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ padding: '8px 12px',
+ borderRadius: '4px'
+ }}
+ />
+ </div>
+ </div>
+
+ <div>
+ <label style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold', display: 'block', marginBottom: '6px' }}>
+ SYMBOL (optional)
+ </label>
+ <input
+ type="text"
+ placeholder="BTC/USD"
+ value={newWSForm.symbol}
+ onChange={(e) => setNewWSForm({ ...newWSForm, symbol: e.target.value })}
+ style={{
+ width: '100%',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ padding: '8px 12px',
+ borderRadius: '4px'
+ }}
+ />
+ </div>
+ </div>
+
+ <div className="flex gap-3 mt-6">
+ <button
+ onClick={handleAddWebSocket}
+ style={{
+ flex: 1,
+ backgroundColor: colors.primary,
+ color: colors.background,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ padding: '10px',
+ borderRadius: '4px',
+ border: 'none',
+ cursor: 'pointer'
+ }}
+ >
+ CREATE DATA SOURCE
+ </button>
+ <button
+ onClick={() => setShowAddDialog(false)}
+ style={{
+ flex: 1,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ padding: '10px',
+ borderRadius: '4px',
+ cursor: 'pointer'
+ }}
+ >
+ CANCEL
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Edit WebSocket Dialog */}
+ {showEditDialog && editingSource && (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0, 0, 0, 0.9)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 1000
+ }}>
+ <div style={{
+ backgroundColor: colors.panel,
+ border: `2px solid ${colors.primary}`,
+ borderRadius: '8px',
+ padding: '24px',
+ maxWidth: '500px',
+ width: '100%'
+ }}>
+ <h3 style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', marginBottom: '16px' }}>
+ Edit WebSocket Data Source
+ </h3>
+
+ <div className="space-y-4">
+ <div>
+ <label style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold', display: 'block', marginBottom: '6px' }}>
+ ALIAS (short name)
+ </label>
+ <input
+ type="text"
+ placeholder="btc_live"
+ value={editWSForm.alias}
+ onChange={(e) => setEditWSForm({ ...editWSForm, alias: e.target.value })}
+ style={{
+ width: '100%',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ padding: '8px 12px',
+ borderRadius: '4px'
+ }}
+ />
+ </div>
+
+ <div>
+ <label style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold', display: 'block', marginBottom: '6px' }}>
+ DISPLAY NAME
+ </label>
+ <input
+ type="text"
+ placeholder="Bitcoin Price"
+ value={editWSForm.displayName}
+ onChange={(e) => setEditWSForm({ ...editWSForm, displayName: e.target.value })}
+ style={{
+ width: '100%',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ padding: '8px 12px',
+ borderRadius: '4px'
+ }}
+ />
+ </div>
+
+ <div>
+ <label style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold', display: 'block', marginBottom: '6px' }}>
+ DESCRIPTION
+ </label>
+ <input
+ type="text"
+ placeholder="Real-time Bitcoin price from Kraken"
+ value={editWSForm.description}
+ onChange={(e) => setEditWSForm({ ...editWSForm, description: e.target.value })}
+ style={{
+ width: '100%',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ padding: '8px 12px',
+ borderRadius: '4px'
+ }}
+ />
+ </div>
+
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <label style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold', display: 'block', marginBottom: '6px' }}>
+ PROVIDER
+ </label>
+ <select
+ value={editWSForm.provider}
+ onChange={(e) => setEditWSForm({ ...editWSForm, provider: e.target.value })}
+ style={{
+ width: '100%',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ padding: '8px 12px',
+ borderRadius: '4px'
+ }}
+ >
+ {availableProviders.map(p => (
+ <option key={p} value={p} style={{ backgroundColor: colors.background, color: colors.text }}>{p}</option>
+ ))}
+ </select>
+ </div>
+
+ <div>
+ <label style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold', display: 'block', marginBottom: '6px' }}>
+ CHANNEL
+ </label>
+ <input
+ type="text"
+ placeholder="ticker"
+ value={editWSForm.channel}
+ onChange={(e) => setEditWSForm({ ...editWSForm, channel: e.target.value })}
+ style={{
+ width: '100%',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ padding: '8px 12px',
+ borderRadius: '4px'
+ }}
+ />
+ </div>
+ </div>
+
+ <div>
+ <label style={{ color: colors.text, fontSize: '10px', fontWeight: 'bold', display: 'block', marginBottom: '6px' }}>
+ SYMBOL (optional)
+ </label>
+ <input
+ type="text"
+ placeholder="BTC/USD"
+ value={editWSForm.symbol}
+ onChange={(e) => setEditWSForm({ ...editWSForm, symbol: e.target.value })}
+ style={{
+ width: '100%',
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ padding: '8px 12px',
+ borderRadius: '4px'
+ }}
+ />
+ </div>
+ </div>
+
+ <div className="flex gap-3 mt-6">
+ <button
+ onClick={handleUpdateWebSocket}
+ style={{
+ flex: 1,
+ backgroundColor: colors.primary,
+ color: colors.background,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ padding: '10px',
+ borderRadius: '4px',
+ border: 'none',
+ cursor: 'pointer'
+ }}
+ >
+ UPDATE DATA SOURCE
+ </button>
+ <button
+ onClick={() => {
+ setShowEditDialog(false);
+ setEditingSource(null);
+ }}
+ style={{
+ flex: 1,
+ backgroundColor: colors.background,
+ border: `1px solid ${colors.primary}`,
+ color: colors.text,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ padding: '10px',
+ borderRadius: '4px',
+ cursor: 'pointer'
+ }}
+ >
+ CANCEL
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/DashboardTab.tsx b/fincept-terminal-desktop/src/components/tabs/DashboardTab.tsx
index 7a8c3f6dd..0ee03d859 100644
--- a/fincept-terminal-desktop/src/components/tabs/DashboardTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/DashboardTab.tsx
@@ -12,6 +12,7 @@ import {
GlobalIndicesWidget,
ForexWidget,
MaritimeWidget,
+ DataSourceWidget,
WidgetType,
WidgetConfig
} from './dashboard/widgets';
@@ -299,6 +300,15 @@ const DashboardTab: React.FC<DashboardTabProps> = ({ onNavigateToTab }) => {
onNavigate={() => onNavigateToTab?.('maritime')}
/>
);
+ case 'datasource':
+ return (
+ <DataSourceWidget
+ id={widget.id}
+ alias={widget.config?.dataSourceAlias || ''}
+ displayName={widget.config?.dataSourceDisplayName}
+ onRemove={() => handleRemoveWidget(widget.id)}
+ />
+ );
default:
return <div>Unknown widget type</div>;
}
diff --git a/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx b/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx
index 31f0fad8c..fcfd01c9c 100644
--- a/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx
@@ -4,16 +4,16 @@ import { invoke } from '@tauri-apps/api/core';
import { createChart, CandlestickSeries, HistogramSeries, LineSeries, BarSeries } from 'lightweight-charts';
const COLORS = {
- ORANGE: 'colors.primary',
- WHITE: 'colors.text',
- RED: 'colors.alert',
- GREEN: 'colors.secondary',
- YELLOW: 'colors.warning',
- GRAY: 'colors.textMuted',
- BLUE: 'colors.info',
- CYAN: 'colors.accent',
- DARK_BG: 'colors.background',
- PANEL_BG: 'colors.panel',
+ ORANGE: '#FFA500',
+ WHITE: '#FFFFFF',
+ RED: '#ef4444',
+ GREEN: '#10b981',
+ YELLOW: '#fbbf24',
+ GRAY: '#787878',
+ BLUE: '#3b82f6',
+ CYAN: '#06b6d4',
+ DARK_BG: '#0a0a0a',
+ PANEL_BG: '#1a1a1a',
BORDER: '#333333',
MAGENTA: '#FF00FF',
PURPLE: '#9D4EDD',
@@ -836,7 +836,7 @@ const EquityResearchTab: React.FC = () => {
<div style={{ color: COLORS.ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>
PRICE CHART & VOLUME - {chartPeriod}
</div>
- <div ref={chartContainerRef} style={{ backgroundColor: COLORS.DARK_BG }} />
+ <div ref={chartContainerRef} style={{ backgroundColor: COLORS.DARK_BG, minHeight: '400px', width: '100%' }} />
</div>
{/* Company Description */}
diff --git a/fincept-terminal-desktop/src/components/tabs/FixedIncomeTab.tsx b/fincept-terminal-desktop/src/components/tabs/FixedIncomeTab.tsx
deleted file mode 100644
index ad8a644e1..000000000
--- a/fincept-terminal-desktop/src/components/tabs/FixedIncomeTab.tsx
+++ /dev/null
@@ -1,515 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-
-interface Bond {
- ticker: string;
- issuer: string;
- coupon: number;
- maturity: string;
- yield: number;
- price: number;
- duration: number;
- rating: string;
- type: 'TREASURY' | 'CORPORATE' | 'MUNICIPAL' | 'AGENCY';
- sector: string;
- callDate?: string;
- ytm: number;
- yieldChange: number;
- volume: string;
- spread: number;
-}
-
-const FixedIncomeTab: React.FC = () => {
- const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
- const [currentTime, setCurrentTime] = useState(new Date());
- const [selectedType, setSelectedType] = useState('ALL');
- const [selectedRating, setSelectedRating] = useState('ALL');
-
- useEffect(() => {
- const timer = setInterval(() => setCurrentTime(new Date()), 1000);
- return () => clearInterval(timer);
- }, []);
-
- const bonds: Bond[] = [
- {
- ticker: 'US10Y',
- issuer: 'US Treasury',
- coupon: 4.125,
- maturity: '2034-02-15',
- yield: 4.234,
- price: 98.75,
- duration: 8.4,
- rating: 'AAA',
- type: 'TREASURY',
- sector: 'Government',
- ytm: 4.234,
- yieldChange: 0.023,
- volume: '$12.5B',
- spread: 0
- },
- {
- ticker: 'US2Y',
- issuer: 'US Treasury',
- coupon: 4.625,
- maturity: '2026-11-30',
- yield: 4.156,
- price: 99.82,
- duration: 1.9,
- rating: 'AAA',
- type: 'TREASURY',
- sector: 'Government',
- ytm: 4.156,
- yieldChange: 0.012,
- volume: '$8.2B',
- spread: 0
- },
- {
- ticker: 'AAPL 3.2',
- issuer: 'Apple Inc',
- coupon: 3.200,
- maturity: '2029-05-11',
- yield: 4.456,
- price: 94.23,
- duration: 4.8,
- rating: 'AA+',
- type: 'CORPORATE',
- sector: 'Technology',
- callDate: '2027-05-11',
- ytm: 4.456,
- yieldChange: 0.034,
- volume: '$450M',
- spread: 98
- },
- {
- ticker: 'JPM 3.875',
- issuer: 'JPMorgan Chase',
- coupon: 3.875,
- maturity: '2032-09-10',
- yield: 4.789,
- price: 91.45,
- duration: 7.2,
- rating: 'A+',
- type: 'CORPORATE',
- sector: 'Financials',
- ytm: 4.789,
- yieldChange: 0.045,
- volume: '$380M',
- spread: 112
- },
- {
- ticker: 'MSFT 2.675',
- issuer: 'Microsoft Corp',
- coupon: 2.675,
- maturity: '2030-06-01',
- yield: 4.234,
- price: 89.67,
- duration: 5.6,
- rating: 'AAA',
- type: 'CORPORATE',
- sector: 'Technology',
- callDate: '2028-06-01',
- ytm: 4.234,
- yieldChange: 0.028,
- volume: '$520M',
- spread: 87
- },
- {
- ticker: 'XOM 4.114',
- issuer: 'Exxon Mobil',
- coupon: 4.114,
- maturity: '2046-03-01',
- yield: 5.123,
- price: 87.34,
- duration: 14.3,
- rating: 'AA',
- type: 'CORPORATE',
- sector: 'Energy',
- ytm: 5.123,
- yieldChange: 0.056,
- volume: '$290M',
- spread: 145
- },
- {
- ticker: 'TSLA 5.3',
- issuer: 'Tesla Inc',
- coupon: 5.300,
- maturity: '2028-08-15',
- yield: 6.234,
- price: 95.12,
- duration: 3.8,
- rating: 'BB+',
- type: 'CORPORATE',
- sector: 'Consumer Discretionary',
- ytm: 6.234,
- yieldChange: 0.089,
- volume: '$180M',
- spread: 234
- },
- {
- ticker: 'BAC 4.45',
- issuer: 'Bank of America',
- coupon: 4.450,
- maturity: '2031-03-03',
- yield: 4.923,
- price: 93.78,
- duration: 6.4,
- rating: 'A',
- type: 'CORPORATE',
- sector: 'Financials',
- ytm: 4.923,
- yieldChange: 0.041,
- volume: '$340M',
- spread: 128
- }
- ];
-
- const yieldCurveData = [
- { maturity: '1M', yield: 5.234, label: '1 Month' },
- { maturity: '3M', yield: 5.123, label: '3 Month' },
- { maturity: '6M', yield: 4.987, label: '6 Month' },
- { maturity: '1Y', yield: 4.756, label: '1 Year' },
- { maturity: '2Y', yield: 4.156, label: '2 Year' },
- { maturity: '5Y', yield: 3.987, label: '5 Year' },
- { maturity: '10Y', yield: 4.234, label: '10 Year' },
- { maturity: '30Y', yield: 4.523, label: '30 Year' }
- ];
-
- const creditSpreads = [
- { rating: 'AAA', spread: 45, change: 2 },
- { rating: 'AA', spread: 78, change: 3 },
- { rating: 'A', spread: 112, change: 5 },
- { rating: 'BBB', spread: 165, change: 8 },
- { rating: 'BB', spread: 234, change: 12 },
- { rating: 'B', spread: 389, change: 18 }
- ];
-
- const filteredBonds = bonds.filter(b =>
- (selectedType === 'ALL' || b.type === selectedType) &&
- (selectedRating === 'ALL' || b.rating.startsWith(selectedRating))
- );
-
- const getTypeColor = (type: string) => {
- switch(type) {
- case 'TREASURY': return colors.info;
- case 'CORPORATE': return colors.secondary;
- case 'MUNICIPAL': return colors.purple;
- case 'AGENCY': return colors.accent;
- default: return colors.text;
- }
- };
-
- const getRatingColor = (rating: string) => {
- if (rating.startsWith('AA')) return colors.secondary;
- if (rating.startsWith('A')) return colors.accent;
- if (rating.startsWith('BB')) return colors.warning;
- if (rating.startsWith('B')) return colors.primary;
- return colors.alert;
- };
-
- return (
- <div style={{
- height: '100%',
- backgroundColor: colors.background,
- color: colors.text,
- fontFamily: 'Consolas, monospace',
- overflow: 'hidden',
- display: 'flex',
- flexDirection: 'column',
- fontSize: '12px'
- }}>
- {/* Header */}
- <div style={{
- backgroundColor: colors.panel,
- borderBottom: `2px solid ${colors.textMuted}`,
- padding: '8px 16px',
- flexShrink: 0
- }}>
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <span style={{ color: colors.primary, fontWeight: 'bold', fontSize: '16px' }}>
- FIXED INCOME MARKETS
- </span>
- <span style={{ color: colors.textMuted }}>|</span>
- <span style={{ color: colors.accent }}>US TREASURIES • CORPORATES • CREDIT</span>
- </div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <span style={{ color: colors.textMuted, fontSize: '11px' }}>
- LAST UPDATE: {currentTime.toLocaleTimeString()}
- </span>
- </div>
- </div>
- </div>
-
- {/* Main Content */}
- <div style={{ flex: 1, overflow: 'auto', display: 'flex', gap: '12px', padding: '12px' }}>
- {/* Left Panel - Yield Curve & Spreads */}
- <div style={{ width: '320px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
- {/* Yield Curve */}
- <div style={{
- backgroundColor: colors.panel,
- border: `2px solid ${colors.textMuted}`,
- borderLeft: `6px solid ${colors.info}`,
- padding: '12px'
- }}>
- <div style={{ color: colors.primary, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
- US TREASURY YIELD CURVE
- </div>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
- {yieldCurveData.map((point, index) => (
- <div key={index} style={{
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- padding: '6px 8px',
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent'
- }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <span style={{ color: colors.textMuted, fontSize: '11px', width: '60px' }}>
- {point.label}
- </span>
- <div style={{
- width: `${point.yield * 15}px`,
- height: '16px',
- backgroundColor: colors.info,
- opacity: 0.7
- }} />
- </div>
- <span style={{ color: colors.accent, fontSize: '12px', fontWeight: 'bold' }}>
- {point.yield.toFixed(3)}%
- </span>
- </div>
- ))}
- </div>
- </div>
-
- {/* Credit Spreads */}
- <div style={{
- backgroundColor: colors.panel,
- border: `2px solid ${colors.textMuted}`,
- borderLeft: `6px solid ${colors.warning}`,
- padding: '12px'
- }}>
- <div style={{ color: colors.primary, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
- CREDIT SPREADS (OAS)
- </div>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
- {creditSpreads.map((spread, index) => (
- <div key={index} style={{
- padding: '8px',
- backgroundColor: 'rgba(255,255,255,0.02)',
- border: `1px solid ${colors.textMuted}`
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
- <span style={{ color: getRatingColor(spread.rating), fontWeight: 'bold', fontSize: '11px' }}>
- {spread.rating}
- </span>
- <span style={{ color: colors.accent, fontWeight: 'bold', fontSize: '11px' }}>
- {spread.spread} bps
- </span>
- </div>
- <div style={{ fontSize: '10px', color: spread.change > 0 ? colors.alert : colors.secondary }}>
- {spread.change > 0 ? '▲' : '▼'} {Math.abs(spread.change)} bps
- </div>
- </div>
- ))}
- </div>
- </div>
-
- {/* Key Metrics */}
- <div style={{
- backgroundColor: colors.panel,
- border: `2px solid ${colors.textMuted}`,
- borderLeft: `6px solid ${colors.secondary}`,
- padding: '12px'
- }}>
- <div style={{ color: colors.primary, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>
- KEY METRICS
- </div>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', fontSize: '11px' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: colors.textMuted }}>10Y-2Y Spread:</span>
- <span style={{ color: colors.accent, fontWeight: 'bold' }}>78 bps</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: colors.textMuted }}>Fed Funds Rate:</span>
- <span style={{ color: colors.secondary, fontWeight: 'bold' }}>5.50%</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: colors.textMuted }}>Inflation (CPI):</span>
- <span style={{ color: colors.warning, fontWeight: 'bold' }}>3.2%</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: colors.textMuted }}>Real Yield (10Y):</span>
- <span style={{ color: colors.purple, fontWeight: 'bold' }}>1.03%</span>
- </div>
- </div>
- </div>
- </div>
-
- {/* Right Panel - Bond List */}
- <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
- {/* Filters */}
- <div style={{
- backgroundColor: colors.panel,
- border: `2px solid ${colors.textMuted}`,
- padding: '12px',
- marginBottom: '12px'
- }}>
- <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
- <span style={{ color: colors.textMuted, fontSize: '11px' }}>TYPE:</span>
- {['ALL', 'TREASURY', 'CORPORATE', 'MUNICIPAL', 'AGENCY'].map((type) => (
- <button key={type}
- onClick={() => setSelectedType(type)}
- style={{
- padding: '6px 12px',
- backgroundColor: selectedType === type ? colors.primary : colors.background,
- border: `2px solid ${selectedType === type ? colors.primary : colors.textMuted}`,
- color: selectedType === type ? colors.background : colors.text,
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}>
- {type}
- </button>
- ))}
- <span style={{ color: colors.textMuted, marginLeft: '16px' }}>|</span>
- <span style={{ color: colors.textMuted, fontSize: '11px' }}>RATING:</span>
- {['ALL', 'AAA', 'AA', 'A', 'BBB', 'BB'].map((rating) => (
- <button key={rating}
- onClick={() => setSelectedRating(rating)}
- style={{
- padding: '6px 12px',
- backgroundColor: selectedRating === rating ? colors.accent : colors.background,
- border: `2px solid ${selectedRating === rating ? colors.accent : colors.textMuted}`,
- color: selectedRating === rating ? colors.background : colors.text,
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}>
- {rating}
- </button>
- ))}
- </div>
- </div>
-
- {/* Bond Table */}
- <div style={{
- backgroundColor: colors.panel,
- border: `2px solid ${colors.textMuted}`,
- flex: 1,
- overflow: 'auto'
- }}>
- {/* Table Header */}
- <div style={{
- display: 'grid',
- gridTemplateColumns: '100px 180px 80px 100px 80px 80px 70px 60px 80px 80px',
- padding: '10px 12px',
- backgroundColor: 'rgba(255,165,0,0.1)',
- borderBottom: `2px solid ${colors.primary}`,
- position: 'sticky',
- top: 0,
- zIndex: 10
- }}>
- <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>TICKER</div>
- <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>ISSUER</div>
- <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>COUPON</div>
- <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>MATURITY</div>
- <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>YIELD</div>
- <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>PRICE</div>
- <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>RATING</div>
- <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>DUR</div>
- <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>SPREAD</div>
- <div style={{ color: colors.primary, fontWeight: 'bold', fontSize: '10px' }}>VOLUME</div>
- </div>
-
- {/* Table Body */}
- {filteredBonds.map((bond, index) => (
- <div key={index}
- style={{
- display: 'grid',
- gridTemplateColumns: '100px 180px 80px 100px 80px 80px 70px 60px 80px 80px',
- padding: '10px 12px',
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- borderBottom: `1px solid ${colors.textMuted}`,
- cursor: 'pointer',
- fontSize: '11px'
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = 'rgba(255,165,0,0.1)';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent';
- }}>
- <div style={{ color: getTypeColor(bond.type), fontWeight: 'bold' }}>{bond.ticker}</div>
- <div style={{ color: colors.text }}>{bond.issuer}</div>
- <div style={{ color: colors.accent }}>{bond.coupon.toFixed(3)}%</div>
- <div style={{ color: colors.textMuted }}>{bond.maturity}</div>
- <div>
- <div style={{ color: colors.warning, fontWeight: 'bold' }}>{bond.yield.toFixed(3)}%</div>
- <div style={{ color: bond.yieldChange > 0 ? colors.alert : colors.secondary, fontSize: '9px' }}>
- {bond.yieldChange > 0 ? '▲' : '▼'} {Math.abs(bond.yieldChange).toFixed(3)}%
- </div>
- </div>
- <div style={{ color: colors.text }}>{bond.price.toFixed(2)}</div>
- <div style={{ color: getRatingColor(bond.rating), fontWeight: 'bold' }}>{bond.rating}</div>
- <div style={{ color: colors.purple }}>{bond.duration.toFixed(1)}</div>
- <div style={{ color: bond.spread > 150 ? colors.alert : colors.secondary }}>
- {bond.spread > 0 ? `+${bond.spread}` : '-'}
- </div>
- <div style={{ color: colors.textMuted }}>{bond.volume}</div>
- </div>
- ))}
- </div>
- </div>
- </div>
-
- {/* Footer */}
- <div style={{
- borderTop: `3px solid ${colors.primary}`,
- backgroundColor: colors.panel,
- padding: '12px 16px',
- fontSize: '11px',
- color: colors.text,
- flexShrink: 0
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
- <span style={{ color: colors.primary, fontWeight: 'bold', fontSize: '13px' }}>
- FIXED INCOME v1.0
- </span>
- <span style={{ color: colors.textMuted }}>|</span>
- <span style={{ color: colors.accent }}>
- Real-time bond prices & yields
- </span>
- <span style={{ color: colors.textMuted }}>|</span>
- <span style={{ color: colors.secondary }}>
- Showing: {filteredBonds.length} bonds
- </span>
- </div>
- </div>
- <div style={{
- display: 'flex',
- justifyContent: 'space-between',
- fontSize: '10px',
- paddingTop: '8px',
- borderTop: `1px solid ${colors.textMuted}`
- }}>
- <div style={{ display: 'flex', gap: '16px' }}>
- <span style={{ color: colors.textMuted }}><span style={{ color: colors.info }}>F1</span> Help</span>
- <span style={{ color: colors.textMuted }}>|</span>
- <span style={{ color: colors.textMuted }}><span style={{ color: colors.info }}>F2</span> Export</span>
- <span style={{ color: colors.textMuted }}>|</span>
- <span style={{ color: colors.textMuted }}><span style={{ color: colors.info }}>F3</span> Calculator</span>
- </div>
- <div style={{ color: colors.textMuted }}>
- © 2025 Fincept Labs • All Rights Reserved
- </div>
- </div>
- </div>
- </div>
- );
-};
-
-export default FixedIncomeTab;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx b/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx
index 39748caaf..306cc7bac 100644
--- a/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx
@@ -30,10 +30,16 @@ import {
Brain,
FileText,
Edit3,
- X
+ X,
+ Monitor
} from 'lucide-react';
import MCPToolNode from './node-editor/MCPToolNode';
import { generateMCPNodeConfigs, MCPNodeConfig } from './node-editor/mcpNodeConfigs';
+import PythonAgentNode from './node-editor/PythonAgentNode';
+import ResultsDisplayNode from './node-editor/ResultsDisplayNode';
+import AgentMediatorNode from './node-editor/AgentMediatorNode';
+import { pythonAgentService, AgentMetadata } from '@/services/pythonAgentService';
+import { nodeExecutionManager } from '@/services/nodeExecutionManager';
// Custom Node Component
const CustomNode = ({ data, id, selected }: any) => {
@@ -202,60 +208,64 @@ const CustomNode = ({ data, id, selected }: any) => {
const NODE_CONFIGS = [
{
- type: 'data-source',
- label: 'Data Source',
+ type: 'agent-mediator',
+ label: 'Agent Mediator',
color: '#3b82f6',
- category: 'Input',
- hasInput: false,
- hasOutput: true,
- },
- {
- type: 'transformation',
- label: 'Transform',
- color: '#8b5cf6',
- category: 'Processing',
- hasInput: true,
- hasOutput: true,
- },
- {
- type: 'analysis',
- label: 'Analysis',
- color: '#10b981',
category: 'Processing',
hasInput: true,
hasOutput: true,
},
{
- type: 'visualization',
- label: 'Visualization',
+ type: 'results-display',
+ label: 'Results Display',
color: '#f59e0b',
category: 'Output',
hasInput: true,
hasOutput: false,
},
- {
- type: 'agent',
- label: 'AI Agent',
- color: '#ec4899',
- category: 'Processing',
- hasInput: true,
- hasOutput: true,
- },
- {
- type: 'output',
- label: 'Output',
- color: '#06b6d4',
- category: 'Output',
- hasInput: true,
- hasOutput: false,
- },
];
export default function NodeEditorTab() {
const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [mcpNodeConfigs, setMcpNodeConfigs] = useState<MCPNodeConfig[]>([]);
+ const [agentConfigs, setAgentConfigs] = useState<AgentMetadata[]>([]);
+
+ // Load saved workflow from localStorage or start with blank slate
+ const loadSavedWorkflow = useCallback(() => {
+ try {
+ const saved = localStorage.getItem('nodeEditorWorkflow');
+ if (saved) {
+ const workflow = JSON.parse(saved);
+ console.log('[NodeEditor] Loaded saved workflow:', workflow.nodes.length, 'nodes');
+ return workflow;
+ }
+ } catch (error) {
+ console.error('[NodeEditor] Failed to load saved workflow:', error);
+ }
+ return { nodes: [], edges: [] };
+ }, []);
- // Load MCP node configurations on mount
+ const [nodes, setNodes, onNodesChange] = useNodesState(loadSavedWorkflow().nodes);
+ const [edges, setEdges, onEdgesChange] = useEdgesState(loadSavedWorkflow().edges);
+
+ // Auto-save workflow to localStorage whenever nodes or edges change
+ useEffect(() => {
+ const saveWorkflow = () => {
+ try {
+ const workflow = { nodes, edges };
+ localStorage.setItem('nodeEditorWorkflow', JSON.stringify(workflow));
+ console.log('[NodeEditor] Auto-saved workflow:', nodes.length, 'nodes,', edges.length, 'edges');
+ } catch (error) {
+ console.error('[NodeEditor] Failed to save workflow:', error);
+ }
+ };
+
+ // Debounce saves to avoid too frequent writes
+ const timeoutId = setTimeout(saveWorkflow, 500);
+ return () => clearTimeout(timeoutId);
+ }, [nodes, edges]);
+
+ // Load MCP node configurations and Python agents on mount
useEffect(() => {
const loadMCPNodes = async () => {
try {
@@ -266,118 +276,30 @@ export default function NodeEditorTab() {
console.error('[NodeEditor] Failed to load MCP configs:', error);
}
};
+
+ const loadAgents = async () => {
+ try {
+ const agents = await pythonAgentService.getAvailableAgents();
+ setAgentConfigs(agents);
+ console.log('[NodeEditor] Loaded Python agents:', agents.length);
+ } catch (error) {
+ console.error('[NodeEditor] Failed to load agents:', error);
+ }
+ };
+
loadMCPNodes();
+ loadAgents();
}, []);
- const [nodes, setNodes, onNodesChange] = useNodesState([
- {
- id: '1',
- type: 'custom',
- position: { x: 100, y: 150 },
- data: {
- label: 'Market Data',
- nodeType: 'data-source',
- color: '#3b82f6',
- hasInput: false,
- hasOutput: true,
- onLabelChange: handleLabelChange,
- },
- },
- {
- id: '2',
- type: 'custom',
- position: { x: 400, y: 150 },
- data: {
- label: 'Normalize Data',
- nodeType: 'transformation',
- color: '#8b5cf6',
- hasInput: true,
- hasOutput: true,
- onLabelChange: handleLabelChange,
- },
- },
- {
- id: '3',
- type: 'custom',
- position: { x: 400, y: 280 },
- data: {
- label: 'Technical Analysis',
- nodeType: 'analysis',
- color: '#10b981',
- hasInput: true,
- hasOutput: true,
- onLabelChange: handleLabelChange,
- },
- },
- {
- id: '4',
- type: 'custom',
- position: { x: 700, y: 150 },
- data: {
- label: 'Chart Output',
- nodeType: 'visualization',
- color: '#f59e0b',
- hasInput: true,
- hasOutput: false,
- onLabelChange: handleLabelChange,
- },
- },
- {
- id: '5',
- type: 'custom',
- position: { x: 700, y: 280 },
- data: {
- label: 'Trading Agent',
- nodeType: 'agent',
- color: '#ec4899',
- hasInput: true,
- hasOutput: true,
- onLabelChange: handleLabelChange,
- },
- },
- ]);
-
- const [edges, setEdges, onEdgesChange] = useEdgesState([
- {
- id: 'e1-2',
- source: '1',
- target: '2',
- animated: true,
- style: { stroke: '#ea580c', strokeWidth: 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: '#ea580c' },
- },
- {
- id: 'e1-3',
- source: '1',
- target: '3',
- animated: true,
- style: { stroke: '#ea580c', strokeWidth: 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: '#ea580c' },
- },
- {
- id: 'e2-4',
- source: '2',
- target: '4',
- animated: true,
- style: { stroke: '#ea580c', strokeWidth: 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: '#ea580c' },
- },
- {
- id: 'e3-5',
- source: '3',
- target: '5',
- animated: true,
- style: { stroke: '#ea580c', strokeWidth: 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: '#ea580c' },
- },
- ]);
-
const [selectedNodes, setSelectedNodes] = useState<string[]>([]);
const [showNodeMenu, setShowNodeMenu] = useState(false);
const nodeTypes: NodeTypes = useMemo(() => ({
custom: CustomNode,
- 'mcp-tool': MCPToolNode
+ 'mcp-tool': MCPToolNode,
+ 'python-agent': PythonAgentNode,
+ 'results-display': ResultsDisplayNode,
+ 'agent-mediator': AgentMediatorNode
}), []);
// Handle label change
@@ -412,15 +334,92 @@ export default function NodeEditorTab() {
[setEdges]
);
- // Add new node (handles both regular nodes and MCP tool nodes)
+ // Add new node (handles regular nodes, MCP tool nodes, Python agent nodes, and agent mediator)
const addNode = (config: any) => {
const isMCPNode = config.type === 'mcp-tool';
+ const isPythonAgent = config.type === 'python-agent';
+ const isResultsDisplay = config.type === 'results-display';
+ const isAgentMediator = config.type === 'agent-mediator';
const newNode: Node = {
id: `node_${Date.now()}`,
- type: isMCPNode ? 'mcp-tool' : 'custom',
+ type: isPythonAgent ? 'python-agent' : (isMCPNode ? 'mcp-tool' : (isResultsDisplay ? 'results-display' : (isAgentMediator ? 'agent-mediator' : 'custom'))),
position: { x: Math.random() * 400 + 100, y: Math.random() * 300 + 100 },
- data: isMCPNode ? {
+ data: isPythonAgent ? {
+ agentType: config.id, // Use 'id' field which contains agent_type like 'warren_buffett'
+ agentCategory: config.category,
+ label: config.name,
+ icon: config.icon,
+ color: config.color,
+ parameters: config.parameters.reduce((acc: any, param: any) => {
+ if (param.default_value !== null && param.default_value !== undefined) {
+ acc[param.name] = param.default_value;
+ }
+ return acc;
+ }, {}),
+ selectedLLM: 'active', // Default to active provider
+ status: 'idle',
+ onExecute: async (nodeId: string) => {
+ console.log('[NodeEditor] Executing single Python agent node:', config.id);
+ // Execute just this node
+ try {
+ setNodes((nds) =>
+ nds.map((n) => n.id === nodeId ? { ...n, data: { ...n.data, status: 'running' } } : n)
+ );
+
+ const result = await pythonAgentService.executeAgent(
+ config.id,
+ config.parameters.reduce((acc: any, param: any) => {
+ if (param.default_value !== null && param.default_value !== undefined) {
+ acc[param.name] = param.default_value;
+ }
+ return acc;
+ }, {}),
+ {}
+ );
+
+ setNodes((nds) =>
+ nds.map((n) =>
+ n.id === nodeId
+ ? {
+ ...n,
+ data: {
+ ...n.data,
+ status: result.success ? 'completed' : 'error',
+ result: result.success ? result.data : undefined,
+ error: result.success ? undefined : result.error,
+ },
+ }
+ : n
+ )
+ );
+ } catch (error: any) {
+ setNodes((nds) =>
+ nds.map((n) =>
+ n.id === nodeId ? { ...n, data: { ...n.data, status: 'error', error: error.message } } : n
+ )
+ );
+ }
+ },
+ onParameterChange: (params: Record<string, any>) => {
+ console.log('[NodeEditor] Agent parameters changed:', params);
+ },
+ onLLMChange: (provider: string) => {
+ setNodes((nds) =>
+ nds.map((n) =>
+ n.id === newNode.id
+ ? {
+ ...n,
+ data: {
+ ...n.data,
+ selectedLLM: provider,
+ },
+ }
+ : n
+ )
+ );
+ },
+ } : (isMCPNode ? {
serverId: config.serverId,
toolName: config.toolName,
label: config.label,
@@ -431,6 +430,38 @@ export default function NodeEditorTab() {
onExecute: (result: any) => {
console.log('[NodeEditor] MCP tool executed with result:', result);
},
+ } : (isResultsDisplay ? {
+ label: config.label,
+ color: config.color,
+ inputData: undefined,
+ } : (isAgentMediator ? {
+ label: config.label,
+ selectedProvider: undefined, // Will use active provider by default
+ customPrompt: undefined,
+ status: 'idle',
+ result: undefined,
+ error: undefined,
+ inputData: undefined,
+ onExecute: (nodeId: string) => {
+ console.log('[NodeEditor] Agent mediator execute clicked:', nodeId);
+ // Workflow execution will handle this
+ },
+ onConfigChange: (newConfig: any) => {
+ setNodes((nds) =>
+ nds.map((n) =>
+ n.id === newNode.id
+ ? {
+ ...n,
+ data: {
+ ...n.data,
+ selectedProvider: newConfig.selectedProvider,
+ customPrompt: newConfig.customPrompt,
+ },
+ }
+ : n
+ )
+ );
+ },
} : {
label: config.label,
nodeType: config.type,
@@ -438,7 +469,7 @@ export default function NodeEditorTab() {
hasInput: config.hasInput,
hasOutput: config.hasOutput,
onLabelChange: handleLabelChange,
- },
+ }))),
};
setNodes((nds) => [...nds, newNode]);
setShowNodeMenu(false);
@@ -487,8 +518,20 @@ export default function NodeEditorTab() {
};
}, [handleKeyDown]);
- // Export workflow
- const exportWorkflow = () => {
+ // Save workflow manually
+ const saveWorkflow = useCallback(() => {
+ try {
+ const workflow = { nodes, edges };
+ localStorage.setItem('nodeEditorWorkflow', JSON.stringify(workflow));
+ console.log('[NodeEditor] Manually saved workflow:', nodes.length, 'nodes,', edges.length, 'edges');
+ // Could add visual feedback here
+ } catch (error) {
+ console.error('[NodeEditor] Failed to save workflow:', error);
+ }
+ }, [nodes, edges]);
+
+ // Export workflow to JSON file
+ const exportWorkflow = useCallback(() => {
const workflow = {
nodes: nodes,
edges: edges,
@@ -501,7 +544,40 @@ export default function NodeEditorTab() {
linkElement.setAttribute('href', dataUri);
linkElement.setAttribute('download', exportFileDefaultName);
linkElement.click();
- };
+ }, [nodes, edges]);
+
+ // Import workflow from JSON file
+ const importWorkflow = useCallback(() => {
+ const input = document.createElement('input');
+ input.type = 'file';
+ input.accept = '.json';
+ input.onchange = (e: any) => {
+ const file = e.target.files[0];
+ if (file) {
+ const reader = new FileReader();
+ reader.onload = (event: any) => {
+ try {
+ const workflow = JSON.parse(event.target.result);
+ setNodes(workflow.nodes || []);
+ setEdges(workflow.edges || []);
+ console.log('[NodeEditor] Imported workflow:', workflow.nodes?.length || 0, 'nodes');
+ } catch (error) {
+ console.error('[NodeEditor] Failed to import workflow:', error);
+ }
+ };
+ reader.readAsText(file);
+ }
+ };
+ input.click();
+ }, [setNodes, setEdges]);
+
+ // Clear workflow (start fresh)
+ const clearWorkflow = useCallback(() => {
+ setNodes([]);
+ setEdges([]);
+ localStorage.removeItem('nodeEditorWorkflow');
+ console.log('[NodeEditor] Cleared workflow');
+ }, [setNodes, setEdges]);
return (
<div
@@ -563,6 +639,55 @@ export default function NodeEditorTab() {
</button>
<button
+ onClick={async () => {
+ try {
+ console.log('[NodeEditor] Starting workflow execution...');
+ await nodeExecutionManager.executeWorkflow(
+ nodes,
+ edges,
+ (nodeId, status, result) => {
+ console.log(`[NodeEditor] Node ${nodeId} status: ${status}`, result);
+ // Update node status
+ setNodes((nds) =>
+ nds.map((node) => {
+ if (node.id === nodeId) {
+ // For results-display nodes, update inputData
+ if (node.type === 'results-display') {
+ console.log('[NodeEditor] Updating results-display node:', nodeId, 'with data:', result);
+ console.log('[NodeEditor] Status:', status);
+ // Force update to trigger re-render
+ const currentData = node.data as any;
+ return {
+ ...node,
+ data: {
+ ...node.data,
+ inputData: status === 'completed' ? result : (status === 'error' ? undefined : currentData.inputData),
+ status,
+ },
+ };
+ }
+ // For other nodes, update status and result
+ return {
+ ...node,
+ data: {
+ ...node.data,
+ status,
+ result: status === 'completed' ? result : undefined,
+ error: status === 'error' ? result : undefined,
+ },
+ };
+ }
+ return node;
+ })
+ );
+ }
+ );
+ console.log('[NodeEditor] Workflow execution completed');
+ } catch (error: any) {
+ console.error('[NodeEditor] Workflow execution failed:', error);
+ // Don't use alert - just log the error
+ }
+ }}
style={{
backgroundColor: 'transparent',
color: '#10b981',
@@ -591,6 +716,7 @@ export default function NodeEditorTab() {
<div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }}></div>
<button
+ onClick={saveWorkflow}
style={{
backgroundColor: 'transparent',
color: '#a3a3a3',
@@ -611,12 +737,14 @@ export default function NodeEditorTab() {
e.currentTarget.style.backgroundColor = 'transparent';
e.currentTarget.style.color = '#a3a3a3';
}}
+ title="Save workflow to browser storage"
>
<Save size={14} />
SAVE
</button>
<button
+ onClick={importWorkflow}
style={{
backgroundColor: 'transparent',
color: '#a3a3a3',
@@ -637,6 +765,7 @@ export default function NodeEditorTab() {
e.currentTarget.style.backgroundColor = 'transparent';
e.currentTarget.style.color = '#a3a3a3';
}}
+ title="Import workflow from file"
>
<Upload size={14} />
IMPORT
@@ -669,6 +798,40 @@ export default function NodeEditorTab() {
EXPORT
</button>
+ <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }}></div>
+
+ <button
+ onClick={() => {
+ if (window.confirm('Are you sure you want to clear all nodes? This cannot be undone.')) {
+ clearWorkflow();
+ }
+ }}
+ style={{
+ backgroundColor: 'transparent',
+ color: '#ef4444',
+ border: '1px solid #ef4444',
+ padding: '6px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#ef4444';
+ e.currentTarget.style.color = 'white';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = '#ef4444';
+ }}
+ title="Clear all nodes and connections"
+ >
+ <Trash2 size={14} />
+ CLEAR ALL
+ </button>
+
{selectedNodes.length > 0 && (
<>
<div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }}></div>
@@ -811,6 +974,7 @@ export default function NodeEditorTab() {
{config.type === 'data-source' && <Database size={16} />}
{config.type === 'transformation' && <Zap size={16} />}
{config.type === 'analysis' && <TrendingUp size={16} />}
+ {config.type === 'results-display' && <Monitor size={16} />}
{config.type === 'visualization' && <BarChart3 size={16} />}
{config.type === 'agent' && <Brain size={16} />}
{config.type === 'output' && <FileText size={16} />}
@@ -873,6 +1037,72 @@ export default function NodeEditorTab() {
))}
</div>
)}
+
+ {/* Python Agents Section */}
+ {agentConfigs.length > 0 && (
+ <div style={{ marginBottom: '12px' }}>
+ <div
+ style={{
+ color: '#22c55e',
+ fontSize: '10px',
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ fontWeight: 'bold',
+ }}
+ >
+ 🤖 PYTHON AGENTS ({agentConfigs.length})
+ </div>
+ {['trader', 'hedge-fund', 'economic', 'geopolitics'].map((category) => {
+ const categoryAgents = agentConfigs.filter(a => a.category === category);
+ if (categoryAgents.length === 0) return null;
+
+ return (
+ <div key={category} style={{ marginBottom: '8px' }}>
+ <div style={{ color: '#737373', fontSize: '9px', marginBottom: '4px', paddingLeft: '4px' }}>
+ {category.toUpperCase()}
+ </div>
+ {categoryAgents.map((agent) => (
+ <button
+ key={agent.id}
+ onClick={() => addNode({ ...agent, type: 'python-agent' })}
+ style={{
+ backgroundColor: 'colors.panel',
+ color: agent.color,
+ border: `1px solid ${agent.color}40`,
+ padding: '8px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ width: '100%',
+ marginBottom: '6px',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = `${agent.color}20`;
+ e.currentTarget.style.borderColor = agent.color;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'colors.panel';
+ e.currentTarget.style.borderColor = `${agent.color}40`;
+ }}
+ >
+ <span style={{ fontSize: '14px' }}>{agent.icon}</span>
+ <div style={{ flex: 1, textAlign: 'left' }}>
+ <div>{agent.name}</div>
+ <div style={{ fontSize: '9px', color: '#737373' }}>
+ {agent.description.substring(0, 40)}...
+ </div>
+ </div>
+ </button>
+ ))}
+ </div>
+ );
+ })}
+ </div>
+ )}
</div>
)}
diff --git a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
index 2de61fc6b..a2b118013 100644
--- a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
@@ -6,6 +6,7 @@ import { useTerminalTheme } from '@/contexts/ThemeContext';
import { terminalThemeService, FONT_FAMILIES, COLOR_THEMES, FontSettings } from '@/services/terminalThemeService';
import { getWebSocketManager, ConnectionStatus, getAvailableProviders } from '@/services/websocket';
import { useWebSocketManager } from '@/hooks/useWebSocket';
+import { DataSourcesPanel } from '@/components/settings/DataSourcesPanel';
export default function SettingsTab() {
const { theme, updateTheme, resetTheme, colors, fontSize: themeFontSize, fontFamily: themeFontFamily, fontWeight: themeFontWeight, fontStyle } = useTerminalTheme();
@@ -17,7 +18,7 @@ export default function SettingsTab() {
const [dbInitialized, setDbInitialized] = useState(false);
// WebSocket Data Connections State
- const { stats, statuses, metrics } = useWebSocketManager();
+ const { stats, statuses, metrics, manager } = useWebSocketManager();
const [wsProviders, setWsProviders] = useState<Array<{
id: number;
provider_name: string;
@@ -35,6 +36,8 @@ export default function SettingsTab() {
api_secret: '',
endpoint: ''
});
+ const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
+ const [programmaticProviders, setProgrammaticProviders] = useState<Set<string>>(new Set());
// Terminal appearance states
const [fontFamily, setFontFamily] = useState(theme.font.family);
@@ -69,16 +72,40 @@ export default function SettingsTab() {
useEffect(() => {
- initDB();
- loadWSProviders();
+ checkAndLoadData();
}, []);
- const initDB = async () => {
+ // Track programmatic providers that get initialized
+ useEffect(() => {
+ const detectedProviders = new Set<string>([
+ ...Array.from(statuses.keys()),
+ ...manager.getSubscriptions().map(sub => sub.topic.split('.')[0])
+ ]);
+
+ // Filter out database-configured providers
+ detectedProviders.forEach(p => {
+ if (wsProviders.find(wp => wp.provider_name === p)) {
+ detectedProviders.delete(p);
+ }
+ });
+
+ if (detectedProviders.size > 0) {
+ setProgrammaticProviders(prev => new Set([...prev, ...detectedProviders]));
+ }
+ }, [statuses, wsProviders]);
+
+ const checkAndLoadData = async () => {
try {
setLoading(true);
- // Initialize database
- await sqliteService.initialize();
+ // Check if database is already initialized
+ const isReady = sqliteService.isReady();
+
+ if (!isReady) {
+ // Database not initialized, initialize it now
+ console.log('[SettingsTab] Database not initialized, initializing now...');
+ await sqliteService.initialize();
+ }
// Verify database health
const healthCheck = await sqliteService.healthCheck();
@@ -93,11 +120,11 @@ export default function SettingsTab() {
await loadLLMConfigs();
await loadWSProviders();
- showMessage('success', `Database ready: ${healthCheck.message}`);
+ console.log('[SettingsTab] Data loaded successfully');
} catch (error) {
- console.error('Failed to initialize database:', error);
+ console.error('[SettingsTab] Failed to load data:', error);
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
- showMessage('error', `Database initialization failed: ${errorMsg}`);
+ showMessage('error', `Failed to load settings: ${errorMsg}`);
setDbInitialized(false);
} finally {
setLoading(false);
@@ -108,6 +135,21 @@ export default function SettingsTab() {
try {
const providers = await sqliteService.getWSProviderConfigs();
setWsProviders(providers);
+
+ // Auto-initialize enabled providers in WebSocket Manager
+ const wsManager = getWebSocketManager();
+ for (const provider of providers) {
+ if (provider.enabled) {
+ wsManager.setProviderConfig(provider.provider_name, {
+ provider_name: provider.provider_name,
+ enabled: provider.enabled,
+ api_key: provider.api_key || undefined,
+ api_secret: provider.api_secret || undefined,
+ endpoint: provider.endpoint || undefined
+ });
+ console.log(`[Settings] Auto-initialized provider: ${provider.provider_name}`);
+ }
+ }
} catch (error) {
console.error('Failed to load WS providers:', error);
}
@@ -205,14 +247,30 @@ export default function SettingsTab() {
const handleConnectProvider = async (providerName: string) => {
try {
const manager = getWebSocketManager();
+
+ // First try to get config from database
const config = await sqliteService.getWSProviderConfig(providerName);
+
if (config) {
manager.setProviderConfig(providerName, config);
- await manager.connect(providerName);
+
+ // Check if there are existing subscriptions to restore
+ const hasSubscriptions = manager.getProviderSubscriptions(providerName).length > 0;
+
+ if (hasSubscriptions) {
+ // Use reconnect to restore subscriptions
+ await manager.reconnect(providerName);
+ } else {
+ // Just connect if no subscriptions
+ await manager.connect(providerName);
+ }
+
showMessage('success', `Connected to ${providerName}`);
+ } else {
+ showMessage('error', `No configuration found for ${providerName}`);
}
} catch (error) {
- showMessage('error', `Failed to connect to ${providerName}`);
+ showMessage('error', `Failed to connect to ${providerName}: ${error}`);
}
};
@@ -236,6 +294,23 @@ export default function SettingsTab() {
}
};
+ const handleUnsubscribe = async (subscriptionId: string, topic: string) => {
+ try {
+ const manager = getWebSocketManager();
+ const subscriptions = manager.getSubscriptions();
+ const sub = subscriptions.find(s => s.id === subscriptionId);
+
+ if (sub) {
+ sub.unsubscribe();
+ showMessage('success', `Unsubscribed from ${topic}`);
+ } else {
+ showMessage('error', 'Subscription not found');
+ }
+ } catch (error) {
+ showMessage('error', `Failed to unsubscribe from ${topic}`);
+ }
+ };
+
const loadCredentials = async () => {
try {
const creds = await sqliteService.getCredentials();
@@ -535,7 +610,7 @@ export default function SettingsTab() {
{[
{ id: 'credentials', icon: Lock, label: 'Credentials' },
{ id: 'llm', icon: Bot, label: 'LLM Configuration' },
- { id: 'dataConnections', icon: Wifi, label: 'Data Connections' },
+ { id: 'dataConnections', icon: Database, label: 'Data Sources' },
{ id: 'profile', icon: User, label: 'User Profile' },
{ id: 'terminal', icon: Terminal, label: 'Terminal Config' },
{ id: 'notifications', icon: Bell, label: 'Notifications' }
@@ -1240,635 +1315,12 @@ export default function SettingsTab() {
</div>
)}
- {/* Data Connections Section */}
+ {/* Data Sources Section (Unified WebSocket + REST API) */}
{activeSection === 'dataConnections' && (
- <div>
- <div style={{ marginBottom: '24px' }}>
- <h2 style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
- WEBSOCKET DATA CONNECTIONS
- </h2>
- <p style={{ color: colors.textMuted, fontSize: '10px' }}>
- Manage WebSocket connections to financial data providers. Configure API keys, endpoints, and monitor connection health.
- </p>
- </div>
-
- {/* Connection Overview Stats */}
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '20px' }}>
- <div style={{ background: colors.panel, border: `2px solid ${stats.registry.connectedProviders > 0 ? '#00ff00' : '#3a3a3a'}`, padding: '12px', borderRadius: '4px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
- <Activity size={12} color={stats.registry.connectedProviders > 0 ? '#00ff00' : colors.textMuted} />
- <div style={{ color: colors.textMuted, fontSize: '9px' }}>ACTIVE CONNECTIONS</div>
- </div>
- <div style={{ color: stats.registry.connectedProviders > 0 ? '#00ff00' : colors.textMuted, fontSize: '24px', fontWeight: 'bold' }}>
- {stats.registry.connectedProviders}
- </div>
- <div style={{ color: colors.textMuted, fontSize: '8px', marginTop: '4px' }}>
- of {wsProviders.length} configured
- </div>
- </div>
- <div style={{ background: colors.panel, border: '1px solid #1a1a1a', padding: '12px', borderRadius: '4px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
- <Zap size={12} color={colors.primary} />
- <div style={{ color: colors.textMuted, fontSize: '9px' }}>TOTAL SUBSCRIPTIONS</div>
- </div>
- <div style={{ color: colors.primary, fontSize: '24px', fontWeight: 'bold' }}>
- {stats.activeSubscriptions}
- </div>
- <div style={{ color: colors.textMuted, fontSize: '8px', marginTop: '4px' }}>
- across all providers
- </div>
- </div>
- <div style={{ background: colors.panel, border: '1px solid #1a1a1a', padding: '12px', borderRadius: '4px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
- <Database size={12} color={colors.text} />
- <div style={{ color: colors.textMuted, fontSize: '9px' }}>CONFIGURED PROVIDERS</div>
- </div>
- <div style={{ color: colors.text, fontSize: '24px', fontWeight: 'bold' }}>
- {wsProviders.length}
- </div>
- <div style={{ color: colors.textMuted, fontSize: '8px', marginTop: '4px' }}>
- {wsProviders.filter(p => p.enabled).length} enabled
- </div>
- </div>
- <div style={{ background: colors.panel, border: '1px solid #1a1a1a', padding: '12px', borderRadius: '4px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
- <Activity size={12} color={stats.eventBus ? colors.secondary : colors.textMuted} />
- <div style={{ color: colors.textMuted, fontSize: '9px' }}>EVENT BUS</div>
- </div>
- <div style={{ color: colors.secondary, fontSize: '24px', fontWeight: 'bold' }}>
- {stats.eventBus?.subscriptions || 0}
- </div>
- <div style={{ color: colors.textMuted, fontSize: '8px', marginTop: '4px' }}>
- subscriptions
- </div>
- </div>
- </div>
-
- {/* Add New Provider */}
- <div style={{
- background: colors.panel,
- border: '1px solid #1a1a1a',
- padding: '16px',
- marginBottom: '20px',
- borderRadius: '4px'
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
- <h3 style={{ color: colors.text, fontSize: '12px', fontWeight: 'bold' }}>
- {selectedProvider ? `Edit Provider: ${selectedProvider.toUpperCase()}` : 'Add New Provider'}
- </h3>
- {selectedProvider && (
- <button
- onClick={() => {
- setSelectedProvider(null);
- setProviderForm({
- provider_name: '',
- enabled: true,
- api_key: '',
- api_secret: '',
- endpoint: ''
- });
- }}
- style={{
- background: 'transparent',
- border: `1px solid ${colors.textMuted}`,
- color: colors.textMuted,
- padding: '4px 8px',
- fontSize: '9px',
- cursor: 'pointer',
- borderRadius: '3px',
- fontWeight: 'bold'
- }}
- >
- CANCEL EDIT
- </button>
- )}
- </div>
-
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '12px' }}>
- <div>
- <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
- PROVIDER NAME * (e.g., kraken, fyers, polygon)
- </label>
- <select
- value={providerForm.provider_name}
- onChange={(e) => setProviderForm({ ...providerForm, provider_name: e.target.value })}
- disabled={!!selectedProvider}
- style={{
- width: '100%',
- background: selectedProvider ? '#1a1a1a' : colors.background,
- border: '1px solid #2a2a2a',
- color: selectedProvider ? colors.textMuted : colors.text,
- padding: '8px',
- fontSize: '10px',
- borderRadius: '3px',
- cursor: selectedProvider ? 'not-allowed' : 'pointer'
- }}
- >
- <option value="">Select a provider</option>
- {getAvailableProviders().map(p => (
- <option key={p} value={p}>{p.toUpperCase()}</option>
- ))}
- </select>
- {selectedProvider && (
- <div style={{ color: colors.textMuted, fontSize: '8px', marginTop: '4px' }}>
- Provider name cannot be changed during edit
- </div>
- )}
- </div>
- <div>
- <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
- ENDPOINT (optional, uses default if empty)
- </label>
- <input
- type="text"
- value={providerForm.endpoint}
- onChange={(e) => setProviderForm({ ...providerForm, endpoint: e.target.value })}
- placeholder="wss://..."
- style={{
- width: '100%',
- background: colors.background,
- border: '1px solid #2a2a2a',
- color: colors.text,
- padding: '8px',
- fontSize: '10px',
- borderRadius: '3px'
- }}
- />
- </div>
- <div>
- <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
- API KEY (if required)
- </label>
- <input
- type="password"
- value={providerForm.api_key}
- onChange={(e) => setProviderForm({ ...providerForm, api_key: e.target.value })}
- placeholder="Optional"
- style={{
- width: '100%',
- background: colors.background,
- border: '1px solid #2a2a2a',
- color: colors.text,
- padding: '8px',
- fontSize: '10px',
- borderRadius: '3px'
- }}
- />
- </div>
- <div>
- <label style={{ color: colors.textMuted, fontSize: '9px', display: 'block', marginBottom: '4px' }}>
- API SECRET (if required)
- </label>
- <input
- type="password"
- value={providerForm.api_secret}
- onChange={(e) => setProviderForm({ ...providerForm, api_secret: e.target.value })}
- placeholder="Optional"
- style={{
- width: '100%',
- background: colors.background,
- border: '1px solid #2a2a2a',
- color: colors.text,
- padding: '8px',
- fontSize: '10px',
- borderRadius: '3px'
- }}
- />
- </div>
- </div>
-
- <div style={{ marginTop: '12px', display: 'flex', gap: '8px', alignItems: 'center' }}>
- <label style={{ display: 'flex', alignItems: 'center', gap: '6px', cursor: 'pointer' }}>
- <input
- type="checkbox"
- checked={providerForm.enabled}
- onChange={(e) => setProviderForm({ ...providerForm, enabled: e.target.checked })}
- />
- <span style={{ color: colors.textMuted, fontSize: '10px' }}>Enable this provider</span>
- </label>
-
- <button
- onClick={handleSaveWSProvider}
- disabled={loading}
- style={{
- marginLeft: 'auto',
- background: colors.primary,
- color: colors.text,
- border: 'none',
- padding: '8px 16px',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: loading ? 'not-allowed' : 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- opacity: loading ? 0.5 : 1
- }}
- >
- <Save size={14} />
- {loading ? 'SAVING...' : (selectedProvider ? 'UPDATE PROVIDER' : 'SAVE PROVIDER')}
- </button>
- </div>
- </div>
-
- {/* Provider Cards */}
- <div>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
- <h3 style={{ color: colors.text, fontSize: '12px', fontWeight: 'bold' }}>
- Configured Providers ({wsProviders.length})
- </h3>
- {wsProviders.length > 0 && (
- <div style={{ display: 'flex', gap: '8px' }}>
- <button
- onClick={async () => {
- try {
- const manager = getWebSocketManager();
- await manager.reconnectAll();
- showMessage('success', 'Reconnecting all providers...');
- } catch (error) {
- showMessage('error', 'Failed to reconnect providers');
- }
- }}
- style={{
- background: 'transparent',
- border: `1px solid ${colors.primary}`,
- color: colors.primary,
- padding: '6px 12px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- letterSpacing: '0.5px'
- }}
- >
- <RefreshCw size={12} />
- RECONNECT ALL
- </button>
- <button
- onClick={async () => {
- if (!confirm('Disconnect all active providers?')) return;
- try {
- const manager = getWebSocketManager();
- for (const provider of wsProviders) {
- await manager.disconnect(provider.provider_name);
- }
- showMessage('success', 'Disconnected all providers');
- } catch (error) {
- showMessage('error', 'Failed to disconnect all providers');
- }
- }}
- style={{
- background: 'transparent',
- border: '1px solid #ff0000',
- color: '#ff0000',
- padding: '6px 12px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- letterSpacing: '0.5px'
- }}
- >
- <WifiOff size={12} />
- DISCONNECT ALL
- </button>
- </div>
- )}
- </div>
-
- {wsProviders.length === 0 ? (
- <div style={{
- background: colors.panel,
- border: '1px solid #1a1a1a',
- padding: '32px',
- textAlign: 'center',
- borderRadius: '4px'
- }}>
- <Wifi size={32} color={colors.textMuted} style={{ margin: '0 auto 12px' }} />
- <p style={{ color: colors.textMuted, fontSize: '11px' }}>No providers configured yet</p>
- </div>
- ) : (
- <div style={{ display: 'grid', gap: '12px' }}>
- {wsProviders.map((provider) => {
- const providerStatus = statuses.get(provider.provider_name);
- const providerMetrics = metrics.get(provider.provider_name);
- const isConnected = providerStatus === ConnectionStatus.CONNECTED;
- const isConnecting = providerStatus === ConnectionStatus.CONNECTING;
- const isReconnecting = providerStatus === ConnectionStatus.RECONNECTING;
- const hasError = providerStatus === ConnectionStatus.ERROR;
-
- // Calculate connection uptime
- let uptimeText = 'Not connected';
- if (providerMetrics?.connectedAt) {
- const uptimeMs = Date.now() - providerMetrics.connectedAt;
- const uptimeMin = Math.floor(uptimeMs / 60000);
- const uptimeSec = Math.floor((uptimeMs % 60000) / 1000);
- if (uptimeMin > 0) {
- uptimeText = `${uptimeMin}m ${uptimeSec}s`;
- } else {
- uptimeText = `${uptimeSec}s`;
- }
- }
-
- return (
- <div
- key={provider.id}
- style={{
- background: colors.panel,
- border: `2px solid ${isConnected ? '#00ff00' : hasError ? '#ff0000' : isConnecting || isReconnecting ? colors.primary : '#1a1a1a'}`,
- padding: '16px',
- borderRadius: '4px',
- position: 'relative',
- overflow: 'hidden'
- }}
- >
- {/* Connection status indicator bar */}
- {isConnected && (
- <div style={{
- position: 'absolute',
- top: 0,
- left: 0,
- right: 0,
- height: '3px',
- background: 'linear-gradient(90deg, #00ff00, #00ff00, rgba(0, 255, 0, 0.3))',
- backgroundSize: '200% 100%',
- animation: 'pulse 2s ease-in-out infinite'
- }} />
- )}
-
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: '12px' }}>
- <div style={{ flex: 1 }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px', flexWrap: 'wrap' }}>
- {isConnected ? (
- <Wifi size={16} color="#00ff00" />
- ) : isConnecting || isReconnecting ? (
- <Activity size={16} color={colors.primary} style={{ animation: 'spin 1s linear infinite' }} />
- ) : (
- <WifiOff size={16} color={hasError ? '#ff0000' : colors.textMuted} />
- )}
- <h4 style={{ color: colors.primary, fontSize: '13px', fontWeight: 'bold', textTransform: 'uppercase', letterSpacing: '0.5px' }}>
- {provider.provider_name}
- </h4>
- <span style={{
- padding: '3px 8px',
- background: isConnected ? '#0a3a0a' : hasError ? '#3a0a0a' : isConnecting || isReconnecting ? 'rgba(234, 88, 12, 0.1)' : '#2a2a2a',
- border: `1px solid ${isConnected ? '#00ff00' : hasError ? '#ff0000' : isConnecting || isReconnecting ? colors.primary : '#555'}`,
- borderRadius: '3px',
- fontSize: '8px',
- fontWeight: 'bold',
- color: isConnected ? '#00ff00' : hasError ? '#ff0000' : isConnecting || isReconnecting ? colors.primary : '#888',
- letterSpacing: '0.5px'
- }}>
- {providerStatus || 'DISCONNECTED'}
- </span>
- {provider.enabled ? (
- <span style={{
- padding: '3px 8px',
- background: '#0a3a0a',
- border: '1px solid #00ff00',
- borderRadius: '3px',
- fontSize: '8px',
- fontWeight: 'bold',
- color: '#00ff00',
- letterSpacing: '0.5px'
- }}>
- ENABLED
- </span>
- ) : (
- <span style={{
- padding: '3px 8px',
- background: '#2a2a2a',
- border: '1px solid #555',
- borderRadius: '3px',
- fontSize: '8px',
- fontWeight: 'bold',
- color: '#888',
- letterSpacing: '0.5px'
- }}>
- DISABLED
- </span>
- )}
- </div>
-
- {provider.endpoint && (
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px', background: colors.background, padding: '4px 6px', borderRadius: '3px' }}>
- <Link size={10} color={colors.textMuted} />
- <span style={{ color: colors.text, fontSize: '9px', fontFamily: 'monospace' }}>
- {provider.endpoint}
- </span>
- </div>
- )}
-
- {/* Connection metrics */}
- {isConnected && providerMetrics && (
- <div style={{
- display: 'grid',
- gridTemplateColumns: 'repeat(auto-fit, minmax(100px, 1fr))',
- gap: '8px',
- marginTop: '10px',
- padding: '8px',
- background: colors.background,
- borderRadius: '3px'
- }}>
- <div>
- <div style={{ color: colors.textMuted, fontSize: '8px', marginBottom: '2px' }}>LATENCY</div>
- <div style={{ color: '#00ff00', fontSize: '11px', fontWeight: 'bold' }}>
- {providerMetrics.latency ? `${providerMetrics.latency}ms` : 'N/A'}
- </div>
- </div>
- <div>
- <div style={{ color: colors.textMuted, fontSize: '8px', marginBottom: '2px' }}>MESSAGES</div>
- <div style={{ color: colors.text, fontSize: '11px', fontWeight: 'bold' }}>
- {providerMetrics.messagesReceived.toLocaleString()}
- </div>
- </div>
- <div>
- <div style={{ color: colors.textMuted, fontSize: '8px', marginBottom: '2px' }}>MSG/SEC</div>
- <div style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold' }}>
- {providerMetrics.messagesPerSecond.toFixed(1)}
- </div>
- </div>
- <div>
- <div style={{ color: colors.textMuted, fontSize: '8px', marginBottom: '2px' }}>SUBSCRIPTIONS</div>
- <div style={{ color: colors.secondary, fontSize: '11px', fontWeight: 'bold' }}>
- {providerMetrics.subscriptions}
- </div>
- </div>
- <div>
- <div style={{ color: colors.textMuted, fontSize: '8px', marginBottom: '2px' }}>UPTIME</div>
- <div style={{ color: colors.text, fontSize: '11px', fontWeight: 'bold' }}>
- {uptimeText}
- </div>
- </div>
- {providerMetrics.errors && providerMetrics.errors.length > 0 && (
- <div>
- <div style={{ color: colors.textMuted, fontSize: '8px', marginBottom: '2px' }}>ERRORS</div>
- <div style={{ color: '#ff0000', fontSize: '11px', fontWeight: 'bold' }}>
- {providerMetrics.errors.length}
- </div>
- </div>
- )}
- </div>
- )}
-
- {/* Show last error if connection failed */}
- {hasError && providerMetrics?.errors && providerMetrics.errors.length > 0 && (
- <div style={{
- marginTop: '8px',
- padding: '6px 8px',
- background: '#3a0a0a',
- border: '1px solid #ff0000',
- borderRadius: '3px'
- }}>
- <div style={{ color: '#ff0000', fontSize: '8px', fontWeight: 'bold', marginBottom: '2px' }}>LAST ERROR:</div>
- <div style={{ color: colors.textMuted, fontSize: '9px', fontFamily: 'monospace' }}>
- {providerMetrics.errors[providerMetrics.errors.length - 1].error}
- </div>
- </div>
- )}
- </div>
-
- <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
- {isConnected ? (
- <button
- onClick={() => handleDisconnectProvider(provider.provider_name)}
- style={{
- background: 'transparent',
- border: '1px solid #ff0000',
- color: '#ff0000',
- padding: '4px 8px',
- fontSize: '9px',
- cursor: 'pointer',
- borderRadius: '3px',
- fontWeight: 'bold'
- }}
- >
- DISCONNECT
- </button>
- ) : (
- <button
- onClick={() => handleConnectProvider(provider.provider_name)}
- disabled={!provider.enabled}
- style={{
- background: 'transparent',
- border: '1px solid #00ff00',
- color: '#00ff00',
- padding: '4px 8px',
- fontSize: '9px',
- cursor: provider.enabled ? 'pointer' : 'not-allowed',
- borderRadius: '3px',
- fontWeight: 'bold',
- opacity: provider.enabled ? 1 : 0.5
- }}
- >
- CONNECT
- </button>
- )}
-
- {isConnected && (
- <button
- onClick={() => handleTestProvider(provider.provider_name)}
- style={{
- background: 'transparent',
- border: `1px solid ${colors.primary}`,
- color: colors.primary,
- padding: '4px 8px',
- fontSize: '9px',
- cursor: 'pointer',
- borderRadius: '3px',
- fontWeight: 'bold'
- }}
- >
- PING
- </button>
- )}
-
- <button
- onClick={async () => {
- // Load provider data into form for editing
- setSelectedProvider(provider.provider_name);
- setProviderForm({
- provider_name: provider.provider_name,
- enabled: provider.enabled,
- api_key: provider.api_key || '',
- api_secret: provider.api_secret || '',
- endpoint: provider.endpoint || ''
- });
- // Scroll to form
- window.scrollTo({ top: 0, behavior: 'smooth' });
- showMessage('success', `Editing ${provider.provider_name} configuration`);
- }}
- style={{
- background: 'transparent',
- border: `1px solid ${colors.primary}`,
- color: colors.primary,
- padding: '4px 8px',
- fontSize: '9px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- fontWeight: 'bold'
- }}
- >
- <Edit3 size={10} />
- EDIT
- </button>
-
- <button
- onClick={() => handleToggleWSProvider(provider.provider_name)}
- style={{
- background: 'transparent',
- border: `1px solid ${colors.textMuted}`,
- color: colors.textMuted,
- padding: '4px 8px',
- fontSize: '9px',
- cursor: 'pointer',
- borderRadius: '3px',
- fontWeight: 'bold'
- }}
- >
- {provider.enabled ? 'DISABLE' : 'ENABLE'}
- </button>
-
- <button
- onClick={() => handleDeleteWSProvider(provider.provider_name)}
- style={{
- background: 'transparent',
- border: '1px solid #ff0000',
- color: '#ff0000',
- padding: '4px 8px',
- fontSize: '9px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- fontWeight: 'bold'
- }}
- >
- <Trash2 size={10} />
- </button>
- </div>
- </div>
- </div>
- );
- })}
- </div>
- )}
- </div>
- </div>
+ <DataSourcesPanel colors={colors} />
)}
- {/* Other sections remain the same... */}
+ {/* Other sections */}
{activeSection === 'profile' && <div style={{ color: colors.textMuted }}>User Profile section (implementation same as before)</div>}
{activeSection === 'notifications' && <div style={{ color: colors.textMuted }}>Notifications section (implementation same as before)</div>}
diff --git a/fincept-terminal-desktop/src/components/tabs/agents/AgentsTab.tsx b/fincept-terminal-desktop/src/components/tabs/agents/AgentsTab.tsx
deleted file mode 100644
index 792cbc854..000000000
--- a/fincept-terminal-desktop/src/components/tabs/agents/AgentsTab.tsx
+++ /dev/null
@@ -1,1092 +0,0 @@
-import React, { useState, useCallback, useMemo } from 'react';
-import ReactFlow, {
- Node,
- Edge,
- addEdge,
- Background,
- Controls,
- MiniMap,
- Connection,
- useNodesState,
- useEdgesState,
- MarkerType,
- NodeTypes,
- Handle,
- Position,
-} from 'reactflow';
-import 'reactflow/dist/style.css';
-import {
- Plus,
- Play,
- Save,
- Download,
- Upload,
- Trash2,
- Settings,
- Pause,
- X,
- Filter,
- Clock,
- Activity,
-} from 'lucide-react';
-import { AGENT_CONFIGS, AGENT_CATEGORIES, getAgentConfig } from './agentConfigs';
-import { AgentConfig, AgentStatus, AgentCategory } from './types';
-import { AgentMCPConfig } from './agentMCPExecutor';
-
-// Custom Agent Node Component with Dynamic Handles
-const AgentNode = ({ data, id, selected }: any) => {
- const [isEditing, setIsEditing] = useState(false);
- const [label, setLabel] = useState(data.label);
- const [showConfig, setShowConfig] = useState(false);
- const [isHovered, setIsHovered] = useState(false);
-
- const handleLabelSave = () => {
- data.onLabelChange(id, label);
- setIsEditing(false);
- };
-
- const getStatusColor = (status: AgentStatus) => {
- switch (status) {
- case 'running':
- return '#10b981';
- case 'completed':
- return '#3b82f6';
- case 'error':
- return '#ef4444';
- case 'paused':
- return '#f59e0b';
- default:
- return '#6b7280';
- }
- };
-
- const getStatusIcon = (status: AgentStatus) => {
- switch (status) {
- case 'running':
- return '⚡';
- case 'completed':
- return '✓';
- case 'error':
- return '✗';
- case 'paused':
- return '⏸️';
- default:
- return '○';
- }
- };
-
- // DYNAMIC HANDLE GENERATION
- // Calculate actual connections to this node
- const connectedInputs = data.connectedInputs || 0;
- const connectedOutputs = data.connectedOutputs || 0;
-
- // Minimum handles (always show at least this many)
- const minHandles = 2;
-
- // Base handle count (shown when not hovered)
- const baseInputHandles = Math.max(minHandles, connectedInputs + 1);
- const baseOutputHandles = Math.max(minHandles, connectedOutputs + 1);
-
- // Expanded handle count (shown when hovered or has many connections)
- const expandedInputHandles = isHovered ? Math.max(baseInputHandles, 5) : baseInputHandles;
- const expandedOutputHandles = isHovered ? Math.max(baseOutputHandles, 5) : baseOutputHandles;
-
- // Use expanded counts for rendering
- const inputHandleCount = expandedInputHandles;
- const outputHandleCount = expandedOutputHandles;
-
- return (
- <div
- onMouseEnter={() => setIsHovered(true)}
- onMouseLeave={() => setIsHovered(false)}
- style={{
- background: selected ? '#2d2d2d' : '#1a1a1a',
- border: `2px solid ${selected ? data.color : `${data.color}80`}`,
- borderRadius: '8px',
- minWidth: '200px',
- boxShadow: selected
- ? `0 0 24px ${data.color}80, 0 6px 16px rgba(0,0,0,0.6)`
- : `0 3px 10px rgba(0,0,0,0.4)`,
- transition: 'all 0.2s',
- position: 'relative',
- }}
- >
- {/* Multiple Input Handles */}
- {data.hasInput && (
- <>
- {Array.from({ length: inputHandleCount }).map((_, index) => {
- const totalHandles = inputHandleCount;
- const topOffset = ((index + 1) * 100) / (totalHandles + 1);
-
- return (
- <Handle
- key={`input-${index}`}
- type="target"
- position={Position.Left}
- id={`input-${index}`}
- style={{
- background: data.color,
- width: 12,
- height: 12,
- border: '2px solid #1a1a1a',
- boxShadow: `0 0 10px ${data.color}`,
- top: `${topOffset}%`,
- transform: 'translateY(-50%)',
- }}
- title={`Input ${index + 1}`}
- />
- );
- })}
- </>
- )}
-
- {/* Status Indicator */}
- <div
- style={{
- position: 'absolute',
- top: '-8px',
- right: '-8px',
- background: getStatusColor(data.status),
- borderRadius: '50%',
- width: '24px',
- height: '24px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- fontSize: '12px',
- border: '2px solid #1a1a1a',
- boxShadow: '0 2px 8px rgba(0,0,0,0.5)',
- }}
- >
- {getStatusIcon(data.status)}
- </div>
-
- {/* Node Header */}
- <div
- style={{
- background: `${data.color}25`,
- borderBottom: `1px solid ${data.color}50`,
- padding: '10px 14px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- gap: '8px',
- color: data.color,
- borderTopLeftRadius: '6px',
- borderTopRightRadius: '6px',
- }}
- >
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1 }}>
- <span style={{ fontSize: '18px' }}>{data.icon || '🤖'}</span>
- {isEditing ? (
- <input
- type="text"
- value={label}
- onChange={(e) => setLabel(e.target.value)}
- onBlur={handleLabelSave}
- onKeyDown={(e) => {
- if (e.key === 'Enter') handleLabelSave();
- if (e.key === 'Escape') {
- setLabel(data.label);
- setIsEditing(false);
- }
- }}
- autoFocus
- style={{
- background: '#0a0a0a',
- border: `1px solid ${data.color}`,
- color: data.color,
- fontSize: '12px',
- padding: '3px 8px',
- borderRadius: '4px',
- outline: 'none',
- fontWeight: 'bold',
- width: '140px',
- }}
- />
- ) : (
- <span
- style={{
- fontSize: '12px',
- fontWeight: 'bold',
- letterSpacing: '0.3px',
- cursor: 'pointer',
- }}
- onDoubleClick={() => setIsEditing(true)}
- >
- {data.label.toUpperCase()}
- </span>
- )}
- </div>
- <button
- onClick={() => setShowConfig(!showConfig)}
- style={{
- background: 'transparent',
- border: 'none',
- color: data.color,
- cursor: 'pointer',
- padding: '4px',
- display: 'flex',
- alignItems: 'center',
- borderRadius: '4px',
- }}
- onMouseEnter={(e) => (e.currentTarget.style.background = `${data.color}30`)}
- onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
- title="Configure agent"
- >
- <Settings size={14} />
- </button>
- </div>
-
- {/* Node Body */}
- <div
- style={{
- padding: '12px 14px',
- display: 'flex',
- flexDirection: 'column',
- gap: '6px',
- color: '#a3a3a3',
- fontSize: '10px',
- }}
- >
- <div style={{ color: '#d4d4d4', fontSize: '11px' }}>
- Type: <span style={{ color: data.color }}>{data.agentType}</span>
- </div>
- <div>
- Status: <span style={{ color: getStatusColor(data.status) }}>{data.status}</span>
- </div>
- {data.mcpConfig && data.mcpConfig.enabled && (
- <div style={{
- backgroundColor: '#FFA50020',
- border: '1px solid #FFA500',
- borderRadius: '3px',
- padding: '4px 6px',
- fontSize: '9px',
- color: '#FFA500',
- fontWeight: 'bold',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- marginTop: '4px'
- }}>
- <span>⚡</span>
- <span>MCP: {data.mcpConfig.allowedServers.length} servers</span>
- </div>
- )}
- {data.hasInput && data.hasOutput && (
- <div style={{ display: 'flex', gap: '10px', fontSize: '9px', marginTop: '4px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
- <span style={{ color: '#84cc16' }}>📥</span>
- <span style={{ color: '#737373' }}>
- <span style={{
- backgroundColor: connectedInputs > 0 ? '#84cc16' : '#404040',
- color: connectedInputs > 0 ? 'black' : '#737373',
- padding: '2px 6px',
- borderRadius: '3px',
- fontWeight: 'bold',
- fontSize: '9px'
- }}>
- {connectedInputs}
- </span>
- <span style={{ marginLeft: '2px' }}>/{inputHandleCount}</span>
- </span>
- </div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
- <span style={{ color: '#3b82f6' }}>📤</span>
- <span style={{ color: '#737373' }}>
- <span style={{
- backgroundColor: connectedOutputs > 0 ? '#3b82f6' : '#404040',
- color: connectedOutputs > 0 ? 'white' : '#737373',
- padding: '2px 6px',
- borderRadius: '3px',
- fontWeight: 'bold',
- fontSize: '9px'
- }}>
- {connectedOutputs}
- </span>
- <span style={{ marginLeft: '2px' }}>/{outputHandleCount}</span>
- </span>
- </div>
- </div>
- )}
- {isHovered && (
- <div style={{
- fontSize: '8px',
- color: '#fbbf24',
- marginTop: '4px',
- fontStyle: 'italic'
- }}>
- 💡 Hover to see more handles
- </div>
- )}
- {data.lastRun && (
- <div style={{ fontSize: '9px', color: '#737373' }}>
- Last run: {new Date(data.lastRun).toLocaleTimeString()}
- </div>
- )}
- {data.error && (
- <div style={{ color: '#ef4444', fontSize: '9px', marginTop: '4px' }}>
- Error: {data.error}
- </div>
- )}
- </div>
-
- {/* Multiple Output Handles */}
- {data.hasOutput && (
- <>
- {Array.from({ length: outputHandleCount }).map((_, index) => {
- const totalHandles = outputHandleCount;
- const topOffset = ((index + 1) * 100) / (totalHandles + 1);
-
- return (
- <Handle
- key={`output-${index}`}
- type="source"
- position={Position.Right}
- id={`output-${index}`}
- style={{
- background: data.color,
- width: 12,
- height: 12,
- border: '2px solid #1a1a1a',
- boxShadow: `0 0 10px ${data.color}`,
- top: `${topOffset}%`,
- transform: 'translateY(-50%)',
- }}
- title={`Output ${index + 1}`}
- />
- );
- })}
- </>
- )}
- </div>
- );
-};
-
-export default function AgentsTab() {
- const [nodes, setNodes, onNodesChange] = useNodesState([]);
- const [edges, setEdges, onEdgesChange] = useEdgesState([]);
- const [selectedNodes, setSelectedNodes] = useState<string[]>([]);
- const [showAgentMenu, setShowAgentMenu] = useState(false);
- const [selectedCategory, setSelectedCategory] = useState<AgentCategory | 'all'>('all' as const);
- const [isExecuting, setIsExecuting] = useState(false);
- const [workflowName, setWorkflowName] = useState('Untitled Workflow');
-
- const nodeTypes: NodeTypes = useMemo(() => ({ agent: AgentNode }), []);
-
- // Handle label change
- function handleLabelChange(nodeId: string, newLabel: string) {
- setNodes((nds) =>
- nds.map((node) => {
- if (node.id === nodeId) {
- return {
- ...node,
- data: {
- ...node.data,
- label: newLabel,
- },
- };
- }
- return node;
- })
- );
- }
-
- // Handle parameter change
- function handleParameterChange(nodeId: string, paramName: string, value: any) {
- setNodes((nds) =>
- nds.map((node) => {
- if (node.id === nodeId) {
- return {
- ...node,
- data: {
- ...node.data,
- parameters: {
- ...node.data.parameters,
- [paramName]: value,
- },
- },
- };
- }
- return node;
- })
- );
- }
-
- // Update connection counts for nodes
- const updateConnectionCounts = useCallback(() => {
- setNodes((nds) =>
- nds.map((node) => {
- // Count inputs connected to this node
- const connectedInputs = edges.filter((edge) => edge.target === node.id).length;
- // Count outputs from this node
- const connectedOutputs = edges.filter((edge) => edge.source === node.id).length;
-
- return {
- ...node,
- data: {
- ...node.data,
- connectedInputs,
- connectedOutputs,
- },
- };
- })
- );
- }, [edges, setNodes]);
-
- // Update counts whenever edges change
- React.useEffect(() => {
- updateConnectionCounts();
- }, [edges, updateConnectionCounts]);
-
- // Handle connection with validation and dynamic handle support
- const onConnect = useCallback(
- (params: Connection) => {
- // Get source and target nodes
- const sourceNode = nodes.find(n => n.id === params.source);
- const targetNode = nodes.find(n => n.id === params.target);
-
- if (!sourceNode || !targetNode) return;
-
- // Different edge colors based on agent categories
- let edgeColor = '#ea580c';
- let strokeWidth = 2;
-
- // Data flow edges (from data agents)
- if (sourceNode.data.category === 'data') {
- edgeColor = '#84cc16';
- strokeWidth = 2.5;
- }
- // Analysis edges (from analysis agents)
- else if (sourceNode.data.category === 'analysis') {
- edgeColor = '#8b5cf6';
- strokeWidth = 2.5;
- }
- // Trader/Hedge fund signal edges
- else if (sourceNode.data.category === 'trader' || sourceNode.data.category === 'hedge-fund') {
- edgeColor = '#3b82f6';
- strokeWidth = 2.5;
- }
- // Execution edges
- else if (sourceNode.data.category === 'execution') {
- edgeColor = '#10b981';
- strokeWidth = 3;
- }
-
- const newEdge = {
- ...params,
- id: `edge_${params.source}_${params.sourceHandle}_${params.target}_${params.targetHandle}_${Date.now()}`,
- animated: true,
- style: { stroke: edgeColor, strokeWidth: strokeWidth },
- markerEnd: { type: MarkerType.ArrowClosed, color: edgeColor },
- label: sourceNode.data.category === 'data' ? '📊 Data' :
- sourceNode.data.category === 'analysis' ? '📈 Analysis' :
- sourceNode.data.category === 'trader' || sourceNode.data.category === 'hedge-fund' ? '💡 Signal' :
- sourceNode.data.category === 'execution' ? '⚡ Execute' : '',
- labelStyle: { fill: edgeColor, fontWeight: 'bold', fontSize: '10px' },
- labelBgStyle: { fill: '#1a1a1a', fillOpacity: 0.8 },
- labelBgPadding: [4, 6] as [number, number],
- labelBgBorderRadius: 4,
- };
- setEdges((eds) => addEdge(newEdge, eds));
- },
- [setEdges, nodes]
- );
-
- // Add new agent node
- const addAgentNode = (config: AgentConfig) => {
- // Default MCP configuration
- const defaultMCPConfig: AgentMCPConfig = {
- enabled: false,
- allowedServers: [],
- autonomousMode: true,
- maxToolCalls: 10
- };
-
- const newNode: Node = {
- id: `agent_${Date.now()}`,
- type: 'agent',
- position: { x: Math.random() * 400 + 100, y: Math.random() * 300 + 100 },
- data: {
- label: config.name,
- agentType: config.type,
- category: config.category,
- icon: config.icon,
- color: config.color,
- hasInput: config.hasInput,
- hasOutput: config.hasOutput,
- parameters: config.parameters.reduce((acc, param) => {
- acc[param.name] = param.defaultValue;
- return acc;
- }, {} as Record<string, any>),
- status: 'idle' as AgentStatus,
- connectedInputs: 0,
- connectedOutputs: 0,
- mcpConfig: defaultMCPConfig,
- onLabelChange: handleLabelChange,
- onParameterChange: handleParameterChange,
- },
- };
- setNodes((nds) => [...nds, newNode]);
- setShowAgentMenu(false);
- };
-
- // Delete selected nodes
- const deleteSelectedNodes = useCallback(() => {
- if (selectedNodes.length > 0) {
- setNodes((nds) => nds.filter((node) => !selectedNodes.includes(node.id)));
- setEdges((eds) =>
- eds.filter(
- (edge) =>
- !selectedNodes.includes(edge.source) &&
- !selectedNodes.includes(edge.target)
- )
- );
- setSelectedNodes([]);
- }
- }, [selectedNodes, setNodes, setEdges]);
-
- // Handle node selection
- const onSelectionChange = useCallback((params: any) => {
- setSelectedNodes(params.nodes.map((node: Node) => node.id));
- }, []);
-
- // Delete selected edges
- const deleteSelectedEdges = useCallback(() => {
- setEdges((eds) => eds.filter((edge) => !edge.selected));
- }, [setEdges]);
-
- // Handle keyboard shortcuts
- const handleKeyDown = useCallback(
- (event: KeyboardEvent) => {
- if (event.key === 'Delete' || event.key === 'Backspace') {
- deleteSelectedNodes();
- deleteSelectedEdges();
- }
- },
- [deleteSelectedNodes, deleteSelectedEdges]
- );
-
- React.useEffect(() => {
- window.addEventListener('keydown', handleKeyDown);
- return () => {
- window.removeEventListener('keydown', handleKeyDown);
- };
- }, [handleKeyDown]);
-
- // Export workflow
- const exportWorkflow = () => {
- const workflow = {
- name: workflowName,
- nodes: nodes,
- edges: edges,
- createdAt: new Date().toISOString(),
- };
- const dataStr = JSON.stringify(workflow, null, 2);
- const dataUri = `data:application/json;charset=utf-8,${encodeURIComponent(dataStr)}`;
- const exportFileDefaultName = `${workflowName.replace(/\s+/g, '_')}_${Date.now()}.json`;
-
- const linkElement = document.createElement('a');
- linkElement.setAttribute('href', dataUri);
- linkElement.setAttribute('download', exportFileDefaultName);
- linkElement.click();
- };
-
- // Execute workflow
- const executeWorkflow = async () => {
- setIsExecuting(true);
-
- try {
- console.log('[AgentsTab] Starting workflow execution with', nodes.length, 'agents');
-
- // Find starting nodes (nodes with no inputs or connected inputs)
- const startingNodes = nodes.filter(node => {
- const hasInputConnections = edges.some(edge => edge.target === node.id);
- return !node.data.hasInput || !hasInputConnections;
- });
-
- console.log('[AgentsTab] Starting nodes:', startingNodes.map(n => n.data.label));
-
- // Execute agents with MCP support if enabled
- for (const node of startingNodes) {
- if (node.data.mcpConfig && node.data.mcpConfig.enabled) {
- console.log(`[AgentsTab] Agent ${node.data.label} has MCP enabled with ${node.data.mcpConfig.allowedServers.length} servers`);
-
- // Update node status
- setNodes((nds) =>
- nds.map((n) =>
- n.id === node.id
- ? { ...n, data: { ...n.data, status: 'running' as AgentStatus } }
- : n
- )
- );
-
- // Execute agent with MCP (simplified for demonstration)
- // In production, this would call executeAgentWithMCP
- await new Promise(resolve => setTimeout(resolve, 1000));
-
- // Update node status to completed
- setNodes((nds) =>
- nds.map((n) =>
- n.id === node.id
- ? { ...n, data: { ...n.data, status: 'completed' as AgentStatus, lastRun: Date.now() } }
- : n
- )
- );
- }
- }
-
- setIsExecuting(false);
- console.log('[AgentsTab] Workflow execution completed');
- alert('Workflow execution completed!\n\nAgents with MCP enabled can now use external tools autonomously.');
- } catch (error) {
- console.error('[AgentsTab] Workflow execution failed:', error);
- setIsExecuting(false);
- alert('Workflow execution failed: ' + (error instanceof Error ? error.message : 'Unknown error'));
- }
- };
-
- // Filtered agent configs
- const filteredAgents = selectedCategory === 'all'
- ? AGENT_CONFIGS
- : AGENT_CONFIGS.filter(config => config.category === selectedCategory);
-
- return (
- <div
- style={{
- width: '100%',
- height: '100%',
- backgroundColor: '#0a0a0a',
- display: 'flex',
- flexDirection: 'column',
- }}
- >
- {/* Toolbar */}
- <div
- style={{
- backgroundColor: '#1a1a1a',
- borderBottom: '1px solid #2d2d2d',
- padding: '10px 16px',
- display: 'flex',
- alignItems: 'center',
- gap: '12px',
- flexWrap: 'wrap',
- flexShrink: 0,
- }}
- >
- <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
- <Activity size={18} style={{ color: '#ea580c' }} />
- <input
- type="text"
- value={workflowName}
- onChange={(e) => setWorkflowName(e.target.value)}
- style={{
- background: '#0a0a0a',
- border: '1px solid #404040',
- color: '#ea580c',
- fontSize: '13px',
- fontWeight: 'bold',
- padding: '6px 10px',
- borderRadius: '4px',
- outline: 'none',
- minWidth: '200px',
- }}
- />
- <div style={{ width: '1px', height: '24px', backgroundColor: '#404040' }}></div>
- </div>
-
- <button
- onClick={() => setShowAgentMenu(!showAgentMenu)}
- style={{
- backgroundColor: '#ea580c',
- color: 'white',
- border: 'none',
- padding: '8px 14px',
- fontSize: '12px',
- cursor: 'pointer',
- borderRadius: '4px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- fontWeight: 'bold',
- }}
- onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = '#dc2626')}
- onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = '#ea580c')}
- >
- <Plus size={16} />
- ADD AGENT
- </button>
-
- <button
- onClick={executeWorkflow}
- disabled={isExecuting || nodes.length === 0}
- style={{
- backgroundColor: isExecuting ? '#6b7280' : '#10b981',
- color: 'white',
- border: 'none',
- padding: '8px 14px',
- fontSize: '12px',
- cursor: isExecuting || nodes.length === 0 ? 'not-allowed' : 'pointer',
- borderRadius: '4px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- fontWeight: 'bold',
- }}
- >
- {isExecuting ? <Pause size={16} /> : <Play size={16} />}
- {isExecuting ? 'RUNNING...' : 'EXECUTE'}
- </button>
-
- <div style={{ width: '1px', height: '24px', backgroundColor: '#404040' }}></div>
-
- <button
- style={{
- backgroundColor: 'transparent',
- color: '#a3a3a3',
- border: '1px solid #404040',
- padding: '8px 14px',
- fontSize: '12px',
- cursor: 'pointer',
- borderRadius: '4px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = '#2d2d2d';
- e.currentTarget.style.color = 'white';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = '#a3a3a3';
- }}
- >
- <Save size={16} />
- SAVE
- </button>
-
- <button
- style={{
- backgroundColor: 'transparent',
- color: '#a3a3a3',
- border: '1px solid #404040',
- padding: '8px 14px',
- fontSize: '12px',
- cursor: 'pointer',
- borderRadius: '4px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = '#2d2d2d';
- e.currentTarget.style.color = 'white';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = '#a3a3a3';
- }}
- >
- <Upload size={16} />
- IMPORT
- </button>
-
- <button
- onClick={exportWorkflow}
- disabled={nodes.length === 0}
- style={{
- backgroundColor: 'transparent',
- color: nodes.length === 0 ? '#6b7280' : '#a3a3a3',
- border: '1px solid #404040',
- padding: '8px 14px',
- fontSize: '12px',
- cursor: nodes.length === 0 ? 'not-allowed' : 'pointer',
- borderRadius: '4px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- }}
- onMouseEnter={(e) => {
- if (nodes.length > 0) {
- e.currentTarget.style.backgroundColor = '#2d2d2d';
- e.currentTarget.style.color = 'white';
- }
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = nodes.length === 0 ? '#6b7280' : '#a3a3a3';
- }}
- >
- <Download size={16} />
- EXPORT
- </button>
-
- {selectedNodes.length > 0 && (
- <>
- <div style={{ width: '1px', height: '24px', backgroundColor: '#404040' }}></div>
- <button
- onClick={deleteSelectedNodes}
- style={{
- backgroundColor: 'transparent',
- color: '#ef4444',
- border: '1px solid #ef4444',
- padding: '8px 14px',
- fontSize: '12px',
- cursor: 'pointer',
- borderRadius: '4px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = '#ef4444';
- e.currentTarget.style.color = 'white';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = '#ef4444';
- }}
- >
- <Trash2 size={16} />
- DELETE ({selectedNodes.length})
- </button>
- </>
- )}
-
- <div
- style={{
- marginLeft: 'auto',
- display: 'flex',
- alignItems: 'center',
- gap: '16px',
- }}
- >
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Clock size={14} style={{ color: '#737373' }} />
- <span style={{ color: '#737373', fontSize: '11px' }}>
- {new Date().toLocaleTimeString()}
- </span>
- </div>
- <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }}></div>
- <span style={{ color: '#737373', fontSize: '11px' }}>
- AGENTS: {nodes.length}
- </span>
- <span style={{ color: '#737373', fontSize: '11px' }}>
- CONNECTIONS: {edges.length}
- </span>
- </div>
- </div>
-
- {/* Agent Menu */}
- {showAgentMenu && (
- <div
- style={{
- position: 'absolute',
- top: '70px',
- left: '16px',
- backgroundColor: '#1a1a1a',
- border: '1px solid #2d2d2d',
- borderRadius: '6px',
- padding: '16px',
- zIndex: 1000,
- minWidth: '320px',
- maxHeight: '600px',
- overflow: 'auto',
- boxShadow: '0 8px 24px rgba(0,0,0,0.7)',
- }}
- >
- <div
- style={{
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- marginBottom: '16px',
- }}
- >
- <div
- style={{
- color: '#a3a3a3',
- fontSize: '13px',
- fontWeight: 'bold',
- letterSpacing: '0.5px',
- }}
- >
- SELECT AGENT TYPE
- </div>
- <button
- onClick={() => setShowAgentMenu(false)}
- style={{
- background: 'transparent',
- border: 'none',
- color: '#a3a3a3',
- cursor: 'pointer',
- padding: '4px',
- }}
- >
- <X size={18} />
- </button>
- </div>
-
- {/* Category Filter */}
- <div style={{ marginBottom: '16px' }}>
- <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
- <button
- onClick={() => setSelectedCategory('all')}
- style={{
- background: selectedCategory === 'all' ? '#ea580c' : '#0a0a0a',
- color: selectedCategory === 'all' ? 'white' : '#a3a3a3',
- border: '1px solid #404040',
- padding: '6px 12px',
- fontSize: '10px',
- cursor: 'pointer',
- borderRadius: '4px',
- fontWeight: 'bold',
- }}
- >
- ALL ({AGENT_CONFIGS.length})
- </button>
- {AGENT_CATEGORIES.map((cat) => (
- <button
- key={cat.id}
- onClick={() => setSelectedCategory(cat.id as AgentCategory)}
- style={{
- background: selectedCategory === cat.id ? cat.color : '#0a0a0a',
- color: selectedCategory === cat.id ? 'white' : '#a3a3a3',
- border: `1px solid ${selectedCategory === cat.id ? cat.color : '#404040'}`,
- padding: '6px 12px',
- fontSize: '10px',
- cursor: 'pointer',
- borderRadius: '4px',
- fontWeight: 'bold',
- }}
- >
- {cat.label.toUpperCase()}
- </button>
- ))}
- </div>
- </div>
-
- {/* Agent List */}
- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
- {filteredAgents.map((config) => (
- <button
- key={config.id}
- onClick={() => addAgentNode(config)}
- style={{
- backgroundColor: '#0a0a0a',
- color: config.color,
- border: `1px solid ${config.color}40`,
- padding: '12px',
- fontSize: '12px',
- cursor: 'pointer',
- borderRadius: '6px',
- display: 'flex',
- alignItems: 'flex-start',
- gap: '12px',
- textAlign: 'left',
- width: '100%',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = `${config.color}20`;
- e.currentTarget.style.borderColor = config.color;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = '#0a0a0a';
- e.currentTarget.style.borderColor = `${config.color}40`;
- }}
- >
- <span style={{ fontSize: '20px', flexShrink: 0 }}>{config.icon}</span>
- <div style={{ flex: 1 }}>
- <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>
- {config.name}
- </div>
- <div style={{ fontSize: '10px', color: '#737373', lineHeight: '1.4' }}>
- {config.description}
- </div>
- </div>
- </button>
- ))}
- </div>
- </div>
- )}
-
- {/* React Flow Canvas */}
- <div style={{ flex: 1, position: 'relative' }}>
- <ReactFlow
- nodes={nodes}
- edges={edges}
- onNodesChange={onNodesChange}
- onEdgesChange={onEdgesChange}
- onConnect={onConnect}
- onSelectionChange={onSelectionChange}
- nodeTypes={nodeTypes}
- fitView
- style={{ background: '#0a0a0a' }}
- defaultEdgeOptions={{
- animated: true,
- style: { stroke: '#ea580c', strokeWidth: 2 },
- }}
- >
- <Background
- color="#2d2d2d"
- gap={24}
- size={1}
- style={{ backgroundColor: '#0a0a0a' }}
- />
- <Controls
- style={{
- backgroundColor: '#1a1a1a',
- border: '1px solid #2d2d2d',
- borderRadius: '6px',
- }}
- />
- <MiniMap
- style={{
- backgroundColor: '#1a1a1a',
- border: '1px solid #2d2d2d',
- }}
- nodeColor={(node) => {
- return node.data.color || '#3b82f6';
- }}
- />
- </ReactFlow>
- </div>
-
- {/* Bottom Info Bar */}
- <div
- style={{
- backgroundColor: '#1a1a1a',
- borderTop: '1px solid #2d2d2d',
- padding: '8px 16px',
- display: 'flex',
- alignItems: 'center',
- gap: '20px',
- fontSize: '11px',
- color: '#737373',
- flexShrink: 0,
- }}
- >
- <span>💡 Unlimited connections: Handles auto-expand as you add more connections (hover to see extra handles)</span>
- {selectedNodes.length > 0 && (
- <>
- <div style={{ width: '1px', height: '16px', backgroundColor: '#404040' }}></div>
- <span style={{ color: '#ea580c' }}>
- Selected: {selectedNodes.length} agent(s)
- </span>
- </>
- )}
- <div
- style={{
- marginLeft: 'auto',
- display: 'flex',
- alignItems: 'center',
- gap: '16px',
- }}
- >
- <span>📊 Data (green) | 📈 Analysis (purple) | 💡 Signal (blue) | ⚡ Execution (green)</span>
- </div>
- </div>
- </div>
- );
-}
diff --git a/fincept-terminal-desktop/src/components/tabs/agents/README.md b/fincept-terminal-desktop/src/components/tabs/agents/README.md
deleted file mode 100644
index 62ec5e0c7..000000000
--- a/fincept-terminal-desktop/src/components/tabs/agents/README.md
+++ /dev/null
@@ -1,299 +0,0 @@
-# Agents Tab - Node-Based Agent Workflow System
-
-## Overview
-
-The Agents Tab is a visual node-based workflow builder for creating and managing AI agent pipelines. It migrates all 32+ agents from the legacy Python terminal to the new Tauri+React application.
-
-## Features
-
-### 🤖 32+ Pre-Built Agents
-
-#### Hedge Fund Agents (10)
-- **Macro Cycle Agent** - Business cycle and economic phase analysis
-- **Central Bank Policy Agent** - Federal Reserve and central bank policy monitoring
-- **Geopolitical Risk Agent** - Geopolitical risk and market impact assessment
-- **Market Sentiment Agent** - Multi-source market sentiment analysis
-- **Institutional Flow Agent** - Institutional money flow tracking
-- **Supply Chain Agent** - Supply chain disruption monitoring
-- **Innovation Trends Agent** - Emerging technology identification
-- **Currency Analysis Agent** - Currency and forex market analysis
-- **Regulatory Impact Agent** - Regulatory change monitoring
-- **Behavioral Psychology Agent** - Market psychology pattern analysis
-
-#### Legendary Trader Agents (10)
-- **Warren Buffett Style** - Value investing with economic moats
-- **Charlie Munger Style** - Multidisciplinary thinking
-- **Benjamin Graham Style** - Deep value with margin of safety
-- **Seth Klarman Style** - Risk-averse value investing
-- **Howard Marks Style** - Contrarian investing and cycle awareness
-- **Joel Greenblatt Style** - Magic formula investing
-- **David Einhorn Style** - Value with short selling
-- **Bill Miller Style** - Concentrated value with growth
-- **Jean-Marie Eveillard Style** - Global value investing
-- **Marty Whitman Style** - Safe and cheap balance sheet focus
-
-#### Analysis Agents (5)
-- **Technical Analysis** - Technical indicators and patterns
-- **Fundamental Analysis** - Deep financial analysis
-- **Risk Assessment** - Portfolio risk and VaR calculation
-- **Correlation Analysis** - Asset correlation and diversification
-- **Scenario Analysis** - Stress testing and scenario modeling
-
-#### Data Agents (3)
-- **Data Collector** - Data collection from sources
-- **Data Transformer** - Data transformation and normalization
-- **Data Aggregator** - Multi-source data aggregation
-
-#### Execution Agents (2)
-- **Signal Generator** - Trading signal generation
-- **Portfolio Manager** - Portfolio allocation and rebalancing
-
-#### Monitoring Agents (2)
-- **Alert Monitor** - Condition monitoring and alerts
-- **Performance Tracker** - Strategy performance tracking
-
-### 🎨 Visual Workflow Builder
-
-- **Drag & Drop Interface** - Intuitive node-based editor
-- **Visual Connections** - Animated edges showing data flow
-- **Real-time Status** - Live agent execution status indicators
-- **Category Filters** - Filter agents by category
-- **Node Configuration** - Per-agent parameter customization
-
-### 📊 Workflow Management
-
-- **Save/Load** - Save workflows for reuse
-- **Export/Import** - JSON-based workflow export/import
-- **Execution Engine** - Run entire agent workflows
-- **Scheduling** - Support for cron and interval-based execution
-- **Version Control** - Track workflow changes
-
-## Architecture
-
-### File Structure
-
-```
-agents/
-├── AgentsTab.tsx # Main component with ReactFlow
-├── types.ts # TypeScript type definitions
-├── agentConfigs.ts # Agent configurations (32+ agents)
-└── README.md # This file
-```
-
-### Type System
-
-```typescript
-// Agent configuration
-interface AgentConfig {
- id: string;
- name: string;
- type: string;
- category: AgentCategory;
- icon: string;
- color: string;
- description: string;
- hasInput: boolean;
- hasOutput: boolean;
- parameters: AgentParameter[];
- requiredDataSources?: string[];
-}
-
-// Workflow definition
-interface AgentWorkflow {
- id: string;
- name: string;
- nodes: any[];
- edges: any[];
- schedule?: WorkflowSchedule;
- isActive: boolean;
-}
-```
-
-## Usage
-
-### Creating a Workflow
-
-1. **Add Agents** - Click "ADD AGENT" and select from 32+ agents
-2. **Configure** - Double-click node labels to rename, click settings to configure
-3. **Connect** - Drag from output handles to input handles to create data flow
-4. **Execute** - Click "EXECUTE" to run the workflow
-5. **Save** - Click "SAVE" or "EXPORT" to persist the workflow
-
-### Example Workflows
-
-#### Value Investing Pipeline
-```
-Data Collector → Fundamental Analysis → Warren Buffett Agent → Signal Generator → Portfolio Manager
-```
-
-#### Hedge Fund Strategy
-```
-Data Collector → Macro Cycle Agent → Central Bank Agent → Risk Assessment → Portfolio Manager
- → Sentiment Agent ↗ ↗
-```
-
-#### Multi-Strategy Aggregation
-```
-Data Collector → Technical Analysis → Signal Generator ↘
- → Fundamental Analysis → Signal Generator → Portfolio Manager
- → Sentiment Analysis → Signal Generator ↗
-```
-
-## Integration Points
-
-### Data Sources Tab Integration
-Agents can specify required data sources:
-```typescript
-requiredDataSources: ['market-data', 'financial-statements', 'news-feed']
-```
-
-### Execution Engine
-Currently mock implementation. Production version should:
-1. Validate workflow topology (no cycles in DAG)
-2. Execute agents in dependency order
-3. Pass data between connected agents
-4. Handle errors and retries
-5. Store execution results
-
-### Scheduling System
-Workflows can be scheduled:
-```typescript
-schedule: {
- type: 'interval',
- interval: 60, // minutes
- nextRun: '2025-01-15T10:00:00Z'
-}
-```
-
-## Development
-
-### Adding New Agents
-
-1. Add configuration to `agentConfigs.ts`:
-```typescript
-{
- id: 'my-agent',
- name: 'My Agent',
- type: 'my-agent',
- category: 'analysis',
- icon: '🔬',
- color: '#10b981',
- description: 'Does something cool',
- hasInput: true,
- hasOutput: true,
- parameters: [
- {
- name: 'threshold',
- label: 'Threshold',
- type: 'slider',
- defaultValue: 0.5,
- min: 0,
- max: 1,
- step: 0.1
- }
- ]
-}
-```
-
-2. Implement execution logic in execution engine
-3. Add tests for agent behavior
-
-### Testing
-
-```bash
-# Run in development mode
-npm run dev
-
-# Navigate to Agents tab in dashboard
-# Create test workflow
-# Click Execute to test
-```
-
-## Future Enhancements
-
-### Phase 1 (Current)
-- ✅ Visual node editor
-- ✅ 32+ pre-configured agents
-- ✅ Workflow save/export
-- ✅ Basic execution (mock)
-
-### Phase 2 (Planned)
-- [ ] Real agent execution engine
-- [ ] Parameter configuration UI
-- [ ] Data source connections
-- [ ] Workflow validation
-- [ ] Error handling
-
-### Phase 3 (Planned)
-- [ ] Workflow scheduling
-- [ ] Execution history
-- [ ] Result visualization
-- [ ] Agent marketplace
-- [ ] Custom agent creation
-- [ ] Backtesting support
-
-### Phase 4 (Advanced)
-- [ ] Real-time collaboration
-- [ ] Agent performance metrics
-- [ ] A/B testing workflows
-- [ ] Auto-optimization
-- [ ] Cloud deployment
-
-## Technical Stack
-
-- **ReactFlow** - Node-based editor
-- **TypeScript** - Type safety
-- **React 19** - UI framework
-- **TailwindCSS** - Styling
-- **Tauri** - Desktop application
-
-## Migration from Python
-
-All agents from the legacy Python terminal have been migrated:
-
-| Python Agent | React Component | Status |
-|-------------|----------------|---------|
-| MacroCycleAgent | macro-cycle | ✅ Migrated |
-| CentralBankAgent | central-bank | ✅ Migrated |
-| SentimentAgent | sentiment | ✅ Migrated |
-| WarrenBuffettAgent | warren-buffett | ✅ Migrated |
-| [+28 more agents...] | [...] | ✅ Migrated |
-
-## API Reference
-
-### AgentsTab Component
-
-```typescript
-export default function AgentsTab(): JSX.Element
-```
-
-Main component that renders the agent workflow editor.
-
-### Agent Node Component
-
-```typescript
-const AgentNode = ({ data, id, selected }: any): JSX.Element
-```
-
-Custom ReactFlow node component for agents.
-
-### Helper Functions
-
-```typescript
-function getAgentConfig(agentId: string): AgentConfig | undefined
-function getAgentsByCategory(category: AgentCategory): AgentConfig[]
-```
-
-## Contributing
-
-To contribute new agents or features:
-
-1. Follow the existing agent configuration pattern
-2. Ensure TypeScript types are correct
-3. Add appropriate icons and colors
-4. Document parameters clearly
-5. Test workflow execution
-
-## License
-
-Part of Fincept Terminal Desktop Application
diff --git a/fincept-terminal-desktop/src/components/tabs/agents/agentConfigs.ts b/fincept-terminal-desktop/src/components/tabs/agents/agentConfigs.ts
deleted file mode 100644
index 193ec6630..000000000
--- a/fincept-terminal-desktop/src/components/tabs/agents/agentConfigs.ts
+++ /dev/null
@@ -1,715 +0,0 @@
-import { AgentConfig, AgentCategory } from './types';
-
-export const AGENT_CONFIGS: AgentConfig[] = [
- // ========== HEDGE FUND AGENTS (10) ==========
- {
- id: 'macro-cycle',
- name: 'Macro Cycle Agent',
- type: 'macro-cycle',
- category: 'hedge-fund',
- icon: '🔄',
- color: '#3b82f6',
- description: 'Analyzes business cycles and economic phases',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'lookback_period', label: 'Lookback Period (years)', type: 'number', defaultValue: 10, min: 1, max: 30 },
- { name: 'indicators', label: 'Economic Indicators', type: 'multi-select', defaultValue: ['GDP', 'CPI', 'UNRATE'],
- options: [
- { label: 'GDP', value: 'GDP' },
- { label: 'CPI', value: 'CPI' },
- { label: 'Unemployment Rate', value: 'UNRATE' },
- { label: 'Federal Funds Rate', value: 'FEDFUNDS' },
- { label: 'Industrial Production', value: 'INDPRO' }
- ]
- },
- { name: 'confidence_threshold', label: 'Confidence Threshold', type: 'slider', defaultValue: 0.7, min: 0, max: 1, step: 0.1 }
- ],
- requiredDataSources: ['economic-data']
- },
- {
- id: 'central-bank',
- name: 'Central Bank Policy Agent',
- type: 'central-bank',
- category: 'hedge-fund',
- icon: '🏦',
- color: '#10b981',
- description: 'Monitors Federal Reserve and central bank policies',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'target_banks', label: 'Central Banks', type: 'multi-select', defaultValue: ['FED'],
- options: [
- { label: 'Federal Reserve (FED)', value: 'FED' },
- { label: 'European Central Bank (ECB)', value: 'ECB' },
- { label: 'Bank of Japan (BOJ)', value: 'BOJ' },
- { label: 'Bank of England (BOE)', value: 'BOE' }
- ]
- },
- { name: 'analysis_depth', label: 'Analysis Depth', type: 'select', defaultValue: 'comprehensive',
- options: [
- { label: 'Quick', value: 'quick' },
- { label: 'Standard', value: 'standard' },
- { label: 'Comprehensive', value: 'comprehensive' }
- ]
- }
- ],
- requiredDataSources: ['news-feed', 'economic-data']
- },
- {
- id: 'geopolitical',
- name: 'Geopolitical Risk Agent',
- type: 'geopolitical',
- category: 'hedge-fund',
- icon: '🌍',
- color: '#f59e0b',
- description: 'Assesses geopolitical risks and their market impact',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'regions', label: 'Monitor Regions', type: 'multi-select', defaultValue: ['global'],
- options: [
- { label: 'Global', value: 'global' },
- { label: 'North America', value: 'north_america' },
- { label: 'Europe', value: 'europe' },
- { label: 'Asia Pacific', value: 'asia_pacific' },
- { label: 'Middle East', value: 'middle_east' }
- ]
- },
- { name: 'risk_threshold', label: 'Risk Alert Threshold', type: 'slider', defaultValue: 0.6, min: 0, max: 1, step: 0.1 }
- ],
- requiredDataSources: ['news-feed']
- },
- {
- id: 'sentiment',
- name: 'Market Sentiment Agent',
- type: 'sentiment',
- category: 'hedge-fund',
- icon: '😊',
- color: '#ec4899',
- description: 'Analyzes market sentiment from multiple sources',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'sources', label: 'Sentiment Sources', type: 'multi-select', defaultValue: ['news', 'social'],
- options: [
- { label: 'Financial News', value: 'news' },
- { label: 'Social Media', value: 'social' },
- { label: 'Analyst Reports', value: 'analyst' },
- { label: 'Market Indicators', value: 'market' }
- ]
- },
- { name: 'contrarian_mode', label: 'Contrarian Signals', type: 'boolean', defaultValue: true },
- { name: 'sentiment_window', label: 'Analysis Window (hours)', type: 'number', defaultValue: 24, min: 1, max: 168 }
- ],
- requiredDataSources: ['news-feed', 'social-media']
- },
- {
- id: 'institutional-flow',
- name: 'Institutional Flow Agent',
- type: 'institutional-flow',
- category: 'hedge-fund',
- icon: '💼',
- color: '#8b5cf6',
- description: 'Tracks institutional money flows and smart money',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'flow_types', label: 'Flow Types', type: 'multi-select', defaultValue: ['equity', 'bond'],
- options: [
- { label: 'Equity Flows', value: 'equity' },
- { label: 'Bond Flows', value: 'bond' },
- { label: 'ETF Flows', value: 'etf' },
- { label: 'Mutual Fund Flows', value: 'mutual_fund' }
- ]
- },
- { name: 'tracking_period', label: 'Tracking Period (days)', type: 'number', defaultValue: 30, min: 1, max: 365 }
- ],
- requiredDataSources: ['market-data']
- },
- {
- id: 'supply-chain',
- name: 'Supply Chain Agent',
- type: 'supply-chain',
- category: 'hedge-fund',
- icon: '🚚',
- color: '#06b6d4',
- description: 'Monitors supply chain disruptions and logistics',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'industries', label: 'Industries to Monitor', type: 'multi-select', defaultValue: ['technology', 'energy'],
- options: [
- { label: 'Technology', value: 'technology' },
- { label: 'Energy', value: 'energy' },
- { label: 'Manufacturing', value: 'manufacturing' },
- { label: 'Retail', value: 'retail' },
- { label: 'Healthcare', value: 'healthcare' }
- ]
- }
- ],
- requiredDataSources: ['news-feed', 'market-data']
- },
- {
- id: 'innovation',
- name: 'Innovation Trends Agent',
- type: 'innovation',
- category: 'hedge-fund',
- icon: '💡',
- color: '#f97316',
- description: 'Identifies emerging technologies and innovation trends',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'tech_sectors', label: 'Technology Sectors', type: 'multi-select', defaultValue: ['ai', 'blockchain'],
- options: [
- { label: 'Artificial Intelligence', value: 'ai' },
- { label: 'Blockchain', value: 'blockchain' },
- { label: 'Quantum Computing', value: 'quantum' },
- { label: 'Biotechnology', value: 'biotech' },
- { label: 'Clean Energy', value: 'clean_energy' }
- ]
- },
- { name: 'patent_analysis', label: 'Include Patent Analysis', type: 'boolean', defaultValue: true }
- ],
- requiredDataSources: ['news-feed']
- },
- {
- id: 'currency',
- name: 'Currency Analysis Agent',
- type: 'currency',
- category: 'hedge-fund',
- icon: '💱',
- color: '#14b8a6',
- description: 'Analyzes currency movements and forex markets',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'currency_pairs', label: 'Currency Pairs', type: 'multi-select', defaultValue: ['USD/EUR', 'USD/JPY'],
- options: [
- { label: 'USD/EUR', value: 'USD/EUR' },
- { label: 'USD/JPY', value: 'USD/JPY' },
- { label: 'USD/GBP', value: 'USD/GBP' },
- { label: 'USD/CHF', value: 'USD/CHF' },
- { label: 'USD/CNY', value: 'USD/CNY' }
- ]
- }
- ],
- requiredDataSources: ['forex-data']
- },
- {
- id: 'regulatory',
- name: 'Regulatory Impact Agent',
- type: 'regulatory',
- category: 'hedge-fund',
- icon: '⚖️',
- color: '#64748b',
- description: 'Monitors regulatory changes and compliance impacts',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'jurisdictions', label: 'Jurisdictions', type: 'multi-select', defaultValue: ['US', 'EU'],
- options: [
- { label: 'United States', value: 'US' },
- { label: 'European Union', value: 'EU' },
- { label: 'United Kingdom', value: 'UK' },
- { label: 'China', value: 'CN' },
- { label: 'Japan', value: 'JP' }
- ]
- }
- ],
- requiredDataSources: ['news-feed']
- },
- {
- id: 'behavioral',
- name: 'Behavioral Psychology Agent',
- type: 'behavioral',
- category: 'hedge-fund',
- icon: '🧠',
- color: '#a855f7',
- description: 'Analyzes market psychology and behavioral patterns',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'behavioral_signals', label: 'Behavioral Signals', type: 'multi-select', defaultValue: ['fear_greed', 'herding'],
- options: [
- { label: 'Fear & Greed Index', value: 'fear_greed' },
- { label: 'Herding Behavior', value: 'herding' },
- { label: 'Overconfidence', value: 'overconfidence' },
- { label: 'Loss Aversion', value: 'loss_aversion' }
- ]
- }
- ],
- requiredDataSources: ['market-data']
- },
-
- // ========== TRADER/INVESTOR AGENTS (10) ==========
- {
- id: 'warren-buffett',
- name: 'Warren Buffett Style',
- type: 'warren-buffett',
- category: 'trader',
- icon: '💰',
- color: '#22c55e',
- description: 'Value investing with economic moats and long-term focus',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'moat_focus', label: 'Economic Moat Analysis', type: 'boolean', defaultValue: true },
- { name: 'min_roe', label: 'Minimum ROE (%)', type: 'number', defaultValue: 15, min: 0, max: 100 },
- { name: 'max_pe_ratio', label: 'Maximum P/E Ratio', type: 'number', defaultValue: 25, min: 0, max: 100 }
- ],
- requiredDataSources: ['financial-statements', 'market-data']
- },
- {
- id: 'charlie-munger',
- name: 'Charlie Munger Style',
- type: 'charlie-munger',
- category: 'trader',
- icon: '🎓',
- color: '#3b82f6',
- description: 'Multidisciplinary thinking and quality businesses',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'quality_threshold', label: 'Quality Score Threshold', type: 'slider', defaultValue: 0.8, min: 0, max: 1, step: 0.1 },
- { name: 'mental_models', label: 'Apply Mental Models', type: 'boolean', defaultValue: true }
- ],
- requiredDataSources: ['financial-statements', 'market-data']
- },
- {
- id: 'benjamin-graham',
- name: 'Benjamin Graham Style',
- type: 'benjamin-graham',
- category: 'trader',
- icon: '📚',
- color: '#6366f1',
- description: 'Deep value investing with margin of safety',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'margin_of_safety', label: 'Margin of Safety (%)', type: 'number', defaultValue: 30, min: 0, max: 100 },
- { name: 'net_net_focus', label: 'Net-Net Analysis', type: 'boolean', defaultValue: false }
- ],
- requiredDataSources: ['financial-statements', 'market-data']
- },
- {
- id: 'seth-klarman',
- name: 'Seth Klarman Style',
- type: 'seth-klarman',
- category: 'trader',
- icon: '🛡️',
- color: '#0891b2',
- description: 'Risk-averse value investing with special situations',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'risk_aversion', label: 'Risk Aversion Level', type: 'slider', defaultValue: 0.8, min: 0, max: 1, step: 0.1 },
- { name: 'special_situations', label: 'Include Special Situations', type: 'boolean', defaultValue: true }
- ],
- requiredDataSources: ['financial-statements', 'market-data']
- },
- {
- id: 'howard-marks',
- name: 'Howard Marks Style',
- type: 'howard-marks',
- category: 'trader',
- icon: '🎯',
- color: '#dc2626',
- description: 'Contrarian investing and cycle awareness',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'contrarian_strength', label: 'Contrarian Strength', type: 'slider', defaultValue: 0.7, min: 0, max: 1, step: 0.1 },
- { name: 'cycle_timing', label: 'Market Cycle Timing', type: 'boolean', defaultValue: true }
- ],
- requiredDataSources: ['market-data', 'sentiment-data']
- },
- {
- id: 'joel-greenblatt',
- name: 'Joel Greenblatt Style',
- type: 'joel-greenblatt',
- category: 'trader',
- icon: '🔢',
- color: '#16a34a',
- description: 'Magic formula: high return on capital, low valuation',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'min_roic', label: 'Minimum ROIC (%)', type: 'number', defaultValue: 20, min: 0, max: 100 },
- { name: 'max_ev_ebit', label: 'Maximum EV/EBIT', type: 'number', defaultValue: 15, min: 0, max: 50 }
- ],
- requiredDataSources: ['financial-statements', 'market-data']
- },
- {
- id: 'david-einhorn',
- name: 'David Einhorn Style',
- type: 'david-einhorn',
- category: 'trader',
- icon: '🎲',
- color: '#ca8a04',
- description: 'Value investing with short selling and activism',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'short_candidates', label: 'Identify Short Candidates', type: 'boolean', defaultValue: true },
- { name: 'accounting_focus', label: 'Deep Accounting Analysis', type: 'boolean', defaultValue: true }
- ],
- requiredDataSources: ['financial-statements', 'market-data']
- },
- {
- id: 'bill-miller',
- name: 'Bill Miller Style',
- type: 'bill-miller',
- category: 'trader',
- icon: '📊',
- color: '#7c3aed',
- description: 'Concentrated value with growth potential',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'concentration_level', label: 'Portfolio Concentration', type: 'slider', defaultValue: 0.7, min: 0, max: 1, step: 0.1 },
- { name: 'growth_value_balance', label: 'Growth-Value Balance', type: 'slider', defaultValue: 0.5, min: 0, max: 1, step: 0.1 }
- ],
- requiredDataSources: ['financial-statements', 'market-data']
- },
- {
- id: 'jean-marie-eveillard',
- name: 'Jean-Marie Eveillard Style',
- type: 'jean-marie-eveillard',
- category: 'trader',
- icon: '🌍',
- color: '#0284c7',
- description: 'Global value investing with downside protection',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'global_scope', label: 'Global Market Scope', type: 'boolean', defaultValue: true },
- { name: 'downside_protection', label: 'Downside Protection Focus', type: 'slider', defaultValue: 0.8, min: 0, max: 1, step: 0.1 }
- ],
- requiredDataSources: ['financial-statements', 'market-data']
- },
- {
- id: 'marty-whitman',
- name: 'Marty Whitman Style',
- type: 'marty-whitman',
- category: 'trader',
- icon: '💎',
- color: '#be123c',
- description: 'Safe and cheap investing with balance sheet analysis',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'balance_sheet_focus', label: 'Balance Sheet Priority', type: 'boolean', defaultValue: true },
- { name: 'asset_coverage', label: 'Minimum Asset Coverage Ratio', type: 'number', defaultValue: 1.5, min: 1, max: 5, step: 0.1 }
- ],
- requiredDataSources: ['financial-statements']
- },
-
- // ========== ANALYSIS AGENTS (5) ==========
- {
- id: 'technical-analysis',
- name: 'Technical Analysis Agent',
- type: 'technical-analysis',
- category: 'analysis',
- icon: '📈',
- color: '#059669',
- description: 'Technical indicators and chart pattern analysis',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'indicators', label: 'Technical Indicators', type: 'multi-select', defaultValue: ['RSI', 'MACD'],
- options: [
- { label: 'RSI', value: 'RSI' },
- { label: 'MACD', value: 'MACD' },
- { label: 'Moving Averages', value: 'MA' },
- { label: 'Bollinger Bands', value: 'BB' },
- { label: 'Fibonacci Retracement', value: 'FIBO' }
- ]
- },
- { name: 'timeframe', label: 'Timeframe', type: 'select', defaultValue: 'daily',
- options: [
- { label: '1 Hour', value: '1h' },
- { label: '4 Hours', value: '4h' },
- { label: 'Daily', value: 'daily' },
- { label: 'Weekly', value: 'weekly' }
- ]
- }
- ],
- requiredDataSources: ['market-data']
- },
- {
- id: 'fundamental-analysis',
- name: 'Fundamental Analysis Agent',
- type: 'fundamental-analysis',
- category: 'analysis',
- icon: '📊',
- color: '#2563eb',
- description: 'Deep fundamental analysis of financials',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'analysis_type', label: 'Analysis Type', type: 'select', defaultValue: 'comprehensive',
- options: [
- { label: 'Quick Scan', value: 'quick' },
- { label: 'Standard', value: 'standard' },
- { label: 'Comprehensive', value: 'comprehensive' },
- { label: 'Deep Dive', value: 'deep' }
- ]
- },
- { name: 'years_history', label: 'Years of History', type: 'number', defaultValue: 10, min: 1, max: 30 }
- ],
- requiredDataSources: ['financial-statements']
- },
- {
- id: 'risk-assessment',
- name: 'Risk Assessment Agent',
- type: 'risk-assessment',
- category: 'analysis',
- icon: '⚠️',
- color: '#dc2626',
- description: 'Portfolio risk analysis and VaR calculation',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'risk_metrics', label: 'Risk Metrics', type: 'multi-select', defaultValue: ['VaR', 'sharpe'],
- options: [
- { label: 'Value at Risk (VaR)', value: 'VaR' },
- { label: 'Sharpe Ratio', value: 'sharpe' },
- { label: 'Maximum Drawdown', value: 'mdd' },
- { label: 'Beta', value: 'beta' },
- { label: 'Volatility', value: 'volatility' }
- ]
- },
- { name: 'confidence_level', label: 'VaR Confidence Level (%)', type: 'number', defaultValue: 95, min: 90, max: 99 }
- ],
- requiredDataSources: ['market-data', 'portfolio-data']
- },
- {
- id: 'correlation-analysis',
- name: 'Correlation Analysis Agent',
- type: 'correlation-analysis',
- category: 'analysis',
- icon: '🔗',
- color: '#7c3aed',
- description: 'Asset correlation and diversification analysis',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'correlation_window', label: 'Correlation Window (days)', type: 'number', defaultValue: 90, min: 30, max: 365 },
- { name: 'threshold', label: 'Correlation Threshold', type: 'slider', defaultValue: 0.7, min: 0, max: 1, step: 0.1 }
- ],
- requiredDataSources: ['market-data']
- },
- {
- id: 'scenario-analysis',
- name: 'Scenario Analysis Agent',
- type: 'scenario-analysis',
- category: 'analysis',
- icon: '🎭',
- color: '#0891b2',
- description: 'Stress testing and scenario modeling',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'scenarios', label: 'Scenarios to Test', type: 'multi-select', defaultValue: ['recession', 'inflation'],
- options: [
- { label: 'Recession', value: 'recession' },
- { label: 'High Inflation', value: 'inflation' },
- { label: 'Market Crash', value: 'crash' },
- { label: 'Interest Rate Spike', value: 'rate_spike' },
- { label: 'Geopolitical Crisis', value: 'geopolitical' }
- ]
- }
- ],
- requiredDataSources: ['market-data', 'economic-data']
- },
-
- // ========== DATA AGENTS (3) ==========
- {
- id: 'data-collector',
- name: 'Data Collector',
- type: 'data-collector',
- category: 'data',
- icon: '📥',
- color: '#84cc16',
- description: 'Collects data from configured sources',
- hasInput: false,
- hasOutput: true,
- parameters: [
- { name: 'data_source', label: 'Data Source', type: 'data-source', required: true },
- { name: 'symbols', label: 'Symbols/Tickers', type: 'text', defaultValue: 'AAPL,GOOGL,MSFT' },
- { name: 'interval', label: 'Update Interval (minutes)', type: 'number', defaultValue: 60, min: 1, max: 1440 }
- ]
- },
- {
- id: 'data-transformer',
- name: 'Data Transformer',
- type: 'data-transformer',
- category: 'data',
- icon: '🔄',
- color: '#f59e0b',
- description: 'Transforms and normalizes data',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'transformations', label: 'Transformations', type: 'multi-select', defaultValue: ['normalize'],
- options: [
- { label: 'Normalize', value: 'normalize' },
- { label: 'Log Transform', value: 'log' },
- { label: 'Percentage Change', value: 'pct_change' },
- { label: 'Rolling Average', value: 'rolling_avg' },
- { label: 'Resample', value: 'resample' }
- ]
- }
- ]
- },
- {
- id: 'data-aggregator',
- name: 'Data Aggregator',
- type: 'data-aggregator',
- category: 'data',
- icon: '📊',
- color: '#8b5cf6',
- description: 'Aggregates data from multiple sources',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'aggregation_method', label: 'Aggregation Method', type: 'select', defaultValue: 'merge',
- options: [
- { label: 'Merge', value: 'merge' },
- { label: 'Concatenate', value: 'concat' },
- { label: 'Average', value: 'average' },
- { label: 'Weighted Average', value: 'weighted_avg' }
- ]
- }
- ]
- },
-
- // ========== EXECUTION AGENTS (2) ==========
- {
- id: 'signal-generator',
- name: 'Signal Generator',
- type: 'signal-generator',
- category: 'execution',
- icon: '📡',
- color: '#10b981',
- description: 'Generates trading signals from analysis',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'signal_threshold', label: 'Signal Threshold', type: 'slider', defaultValue: 0.7, min: 0, max: 1, step: 0.05 },
- { name: 'signal_types', label: 'Signal Types', type: 'multi-select', defaultValue: ['buy', 'sell'],
- options: [
- { label: 'Buy Signal', value: 'buy' },
- { label: 'Sell Signal', value: 'sell' },
- { label: 'Hold Signal', value: 'hold' },
- { label: 'Short Signal', value: 'short' }
- ]
- }
- ]
- },
- {
- id: 'portfolio-manager',
- name: 'Portfolio Manager',
- type: 'portfolio-manager',
- category: 'execution',
- icon: '💼',
- color: '#6366f1',
- description: 'Manages portfolio allocation and rebalancing',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'rebalance_frequency', label: 'Rebalance Frequency', type: 'select', defaultValue: 'monthly',
- options: [
- { label: 'Daily', value: 'daily' },
- { label: 'Weekly', value: 'weekly' },
- { label: 'Monthly', value: 'monthly' },
- { label: 'Quarterly', value: 'quarterly' }
- ]
- },
- { name: 'max_position_size', label: 'Max Position Size (%)', type: 'number', defaultValue: 5, min: 1, max: 100 }
- ]
- },
-
- // ========== MONITORING AGENTS (2) ==========
- {
- id: 'alert-monitor',
- name: 'Alert Monitor',
- type: 'alert-monitor',
- category: 'monitoring',
- icon: '🔔',
- color: '#f59e0b',
- description: 'Monitors conditions and triggers alerts',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'alert_conditions', label: 'Alert Conditions', type: 'multi-select', defaultValue: ['price_change'],
- options: [
- { label: 'Price Change', value: 'price_change' },
- { label: 'Volume Spike', value: 'volume_spike' },
- { label: 'News Event', value: 'news_event' },
- { label: 'Technical Signal', value: 'technical_signal' }
- ]
- },
- { name: 'notification_channel', label: 'Notification Channel', type: 'select', defaultValue: 'email',
- options: [
- { label: 'Email', value: 'email' },
- { label: 'SMS', value: 'sms' },
- { label: 'Push Notification', value: 'push' },
- { label: 'Webhook', value: 'webhook' }
- ]
- }
- ]
- },
- {
- id: 'performance-tracker',
- name: 'Performance Tracker',
- type: 'performance-tracker',
- category: 'monitoring',
- icon: '📈',
- color: '#22c55e',
- description: 'Tracks and reports strategy performance',
- hasInput: true,
- hasOutput: true,
- parameters: [
- { name: 'metrics', label: 'Performance Metrics', type: 'multi-select', defaultValue: ['returns', 'sharpe'],
- options: [
- { label: 'Total Returns', value: 'returns' },
- { label: 'Sharpe Ratio', value: 'sharpe' },
- { label: 'Max Drawdown', value: 'drawdown' },
- { label: 'Win Rate', value: 'win_rate' },
- { label: 'Alpha/Beta', value: 'alpha_beta' }
- ]
- },
- { name: 'reporting_frequency', label: 'Reporting Frequency', type: 'select', defaultValue: 'daily',
- options: [
- { label: 'Real-time', value: 'realtime' },
- { label: 'Hourly', value: 'hourly' },
- { label: 'Daily', value: 'daily' },
- { label: 'Weekly', value: 'weekly' }
- ]
- }
- ]
- },
-];
-
-// Category metadata
-export const AGENT_CATEGORIES = [
- { id: 'hedge-fund', label: 'Hedge Fund Agents', color: '#3b82f6', description: 'Institutional-grade market analysis agents' },
- { id: 'trader', label: 'Legendary Traders', color: '#22c55e', description: 'Famous investor/trader strategy agents' },
- { id: 'analysis', label: 'Analysis Agents', color: '#8b5cf6', description: 'Specialized analytical agents' },
- { id: 'data', label: 'Data Agents', color: '#f59e0b', description: 'Data collection and processing agents' },
- { id: 'execution', label: 'Execution Agents', color: '#10b981', description: 'Signal generation and portfolio management' },
- { id: 'monitoring', label: 'Monitoring Agents', color: '#ef4444', description: 'Alert and performance monitoring' },
-];
-
-// Helper function to get agent config by ID
-export function getAgentConfig(agentId: string): AgentConfig | undefined {
- return AGENT_CONFIGS.find(config => config.id === agentId);
-}
-
-// Helper function to get agents by category
-export function getAgentsByCategory(category: AgentCategory): AgentConfig[] {
- return AGENT_CONFIGS.filter(config => config.category === category);
-}
diff --git a/fincept-terminal-desktop/src/components/tabs/agents/agentMCPExecutor.ts b/fincept-terminal-desktop/src/components/tabs/agents/agentMCPExecutor.ts
deleted file mode 100644
index f75986b9f..000000000
--- a/fincept-terminal-desktop/src/components/tabs/agents/agentMCPExecutor.ts
+++ /dev/null
@@ -1,241 +0,0 @@
-// Agent MCP Executor - Enables agents to autonomously use MCP tools
-// Integrates LLM decision-making with MCP tool execution
-
-import { mcpToolService, MCPTool } from '../../../services/mcpToolService';
-import { llmApiService, ChatMessage } from '../../../services/llmApi';
-
-export interface AgentMCPConfig {
- enabled: boolean;
- allowedServers: string[]; // Which MCP servers this agent can use
- autonomousMode: boolean; // Agent decides when to use tools vs user explicitly triggers
- maxToolCalls: number; // Maximum tool calls per execution to prevent infinite loops
-}
-
-export interface AgentExecutionContext {
- objective: string; // What the agent is trying to accomplish
- inputs: Record<string, any>; // Inputs from connected nodes
- conversationHistory: ChatMessage[]; // Previous messages in the workflow
-}
-
-export interface AgentExecutionResult {
- success: boolean;
- output: string;
- toolCallsMade: ToolCallRecord[];
- error?: string;
- tokensUsed?: number;
-}
-
-export interface ToolCallRecord {
- toolName: string;
- serverId: string;
- arguments: Record<string, any>;
- result: any;
- executionTime: number;
- success: boolean;
- error?: string;
-}
-
-/**
- * Execute an MCP-enabled agent workflow
- * The agent uses LLM to decide which tools to call and when
- */
-export async function executeAgentWithMCP(
- config: AgentMCPConfig,
- context: AgentExecutionContext,
- onProgress?: (message: string) => void
-): Promise<AgentExecutionResult> {
- const toolCallRecords: ToolCallRecord[] = [];
-
- try {
- onProgress?.('Initializing agent with MCP tools...');
-
- // Get available MCP tools filtered by allowed servers
- let availableTools = await mcpToolService.getAllTools();
-
- if (config.allowedServers.length > 0) {
- availableTools = availableTools.filter(tool =>
- config.allowedServers.includes(tool.serverId)
- );
- }
-
- if (availableTools.length === 0) {
- return {
- success: false,
- output: '',
- toolCallsMade: [],
- error: 'No MCP tools available for this agent'
- };
- }
-
- onProgress?.(`Agent has access to ${availableTools.length} MCP tools`);
-
- // Format context into initial prompt
- const systemPrompt = `You are an AI agent with access to external tools. Your objective is: ${context.objective}
-
-Available inputs: ${JSON.stringify(context.inputs, null, 2)}
-
-You can use the following MCP tools to accomplish your objective. Use them wisely and only when necessary.
-When you're done, provide a final summary of your work.`;
-
- // Build conversation history
- const conversationHistory: ChatMessage[] = [
- ...context.conversationHistory,
- {
- role: 'user',
- content: systemPrompt
- }
- ];
-
- // Call LLM with tools (tool execution happens inside chatWithTools)
- // The onToolCall callback tracks all tool executions
- let toolExecutionCount = 0;
-
- onProgress?.('Calling LLM with available tools...');
-
- const response = await llmApiService.chatWithTools(
- context.objective, // User's objective
- conversationHistory,
- availableTools,
- undefined, // No streaming for agent execution
- (toolName: string, args: any, result?: any) => {
- if (!result) {
- onProgress?.(`Agent is calling tool: ${toolName}`);
- toolExecutionCount++;
- } else {
- onProgress?.(`Tool ${toolName} completed`);
-
- // Parse tool name to get serverId and toolName
- const parsed = mcpToolService.parseOpenAIFunctionName(toolName);
- if (parsed) {
- toolCallRecords.push({
- toolName: parsed.toolName,
- serverId: parsed.serverId,
- arguments: args,
- result: result,
- executionTime: 0, // Not tracked in callback
- success: true,
- error: undefined
- });
- }
- }
- }
- );
-
- if (response.error) {
- return {
- success: false,
- output: '',
- toolCallsMade: toolCallRecords,
- error: response.error
- };
- }
-
- onProgress?.('Agent execution completed');
-
- return {
- success: true,
- output: response.content,
- toolCallsMade: toolCallRecords,
- tokensUsed: response.usage?.totalTokens
- };
- } catch (error: any) {
- return {
- success: false,
- output: '',
- toolCallsMade: toolCallRecords,
- error: error.message || 'Unknown error during agent execution'
- };
- }
-}
-
-/**
- * Execute a single MCP tool directly without LLM
- * Used when agent workflow has explicit tool nodes
- */
-export async function executeToolDirectly(
- serverId: string,
- toolName: string,
- params: Record<string, any>,
- onProgress?: (message: string) => void
-): Promise<AgentExecutionResult> {
- try {
- onProgress?.(`Executing ${serverId}.${toolName}...`);
-
- const result = await mcpToolService.executeToolDirect(serverId, toolName, params);
-
- const toolCallRecord: ToolCallRecord = {
- toolName,
- serverId,
- arguments: params,
- result: result.data,
- executionTime: result.executionTime || 0,
- success: result.success,
- error: result.error
- };
-
- if (result.success) {
- onProgress?.('Tool executed successfully');
- return {
- success: true,
- output: JSON.stringify(result.data, null, 2),
- toolCallsMade: [toolCallRecord]
- };
- } else {
- return {
- success: false,
- output: '',
- toolCallsMade: [toolCallRecord],
- error: result.error
- };
- }
- } catch (error: any) {
- return {
- success: false,
- output: '',
- toolCallsMade: [],
- error: error.message || 'Unknown error during tool execution'
- };
- }
-}
-
-/**
- * Get available MCP tools for an agent based on its configuration
- */
-export async function getAgentAvailableTools(config: AgentMCPConfig): Promise<MCPTool[]> {
- try {
- let tools = await mcpToolService.getAllTools();
-
- if (config.allowedServers.length > 0) {
- tools = tools.filter(tool => config.allowedServers.includes(tool.serverId));
- }
-
- return tools;
- } catch (error) {
- console.error('[AgentMCPExecutor] Failed to get available tools:', error);
- return [];
- }
-}
-
-/**
- * Validate agent MCP configuration
- */
-export function validateAgentMCPConfig(config: AgentMCPConfig): { valid: boolean; errors: string[] } {
- const errors: string[] = [];
-
- if (config.maxToolCalls <= 0) {
- errors.push('maxToolCalls must be greater than 0');
- }
-
- if (config.maxToolCalls > 20) {
- errors.push('maxToolCalls cannot exceed 20 (to prevent infinite loops)');
- }
-
- if (config.enabled && config.allowedServers.length === 0) {
- errors.push('At least one MCP server must be allowed when MCP is enabled');
- }
-
- return {
- valid: errors.length === 0,
- errors
- };
-}
diff --git a/fincept-terminal-desktop/src/components/tabs/agents/types.ts b/fincept-terminal-desktop/src/components/tabs/agents/types.ts
deleted file mode 100644
index 9b394e5af..000000000
--- a/fincept-terminal-desktop/src/components/tabs/agents/types.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-// Agent Types and Interfaces
-
-export type AgentCategory = 'hedge-fund' | 'trader' | 'analysis' | 'data' | 'execution' | 'monitoring';
-
-export type AgentStatus = 'idle' | 'running' | 'completed' | 'error' | 'paused';
-
-// MCP Integration Types
-export interface AgentMCPConfig {
- enabled: boolean;
- allowedServers: string[]; // Which MCP servers this agent can use
- autonomousMode: boolean; // Agent decides when to use tools vs user explicitly triggers
- maxToolCalls: number; // Maximum tool calls per execution to prevent infinite loops
-}
-
-export interface AgentConfig {
- id: string;
- name: string;
- type: string;
- category: AgentCategory;
- icon: string;
- color: string;
- description: string;
- hasInput: boolean;
- hasOutput: boolean;
- parameters: AgentParameter[];
- requiredDataSources?: string[];
-}
-
-export interface AgentParameter {
- name: string;
- label: string;
- type: 'text' | 'number' | 'select' | 'boolean' | 'data-source' | 'slider' | 'multi-select';
- defaultValue?: any;
- options?: { label: string; value: string }[];
- min?: number;
- max?: number;
- step?: number;
- required?: boolean;
- description?: string;
-}
-
-export interface AgentNode {
- id: string;
- type: string;
- position: { x: number; y: number };
- data: {
- label: string;
- agentType: string;
- category: AgentCategory;
- color: string;
- hasInput: boolean;
- hasOutput: boolean;
- parameters: Record<string, any>;
- status: AgentStatus;
- lastRun?: string;
- error?: string;
- mcpConfig?: AgentMCPConfig; // MCP integration configuration
- onLabelChange: (nodeId: string, newLabel: string) => void;
- onParameterChange: (nodeId: string, paramName: string, value: any) => void;
- };
-}
-
-export interface AgentWorkflow {
- id: string;
- name: string;
- description: string;
- nodes: any[];
- edges: any[];
- createdAt: string;
- updatedAt: string;
- schedule?: WorkflowSchedule;
- isActive: boolean;
-}
-
-export interface WorkflowSchedule {
- type: 'interval' | 'cron' | 'manual';
- interval?: number; // in minutes
- cronExpression?: string;
- nextRun?: string;
-}
-
-export interface AgentExecutionResult {
- agentId: string;
- agentType: string;
- status: 'success' | 'error';
- output: any;
- error?: string;
- executionTime: number;
- timestamp: string;
-}
-
-export interface WorkflowExecution {
- id: string;
- workflowId: string;
- startTime: string;
- endTime?: string;
- status: 'running' | 'completed' | 'failed' | 'cancelled';
- results: AgentExecutionResult[];
- totalExecutionTime?: number;
-}
diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/AddWidgetModal.tsx b/fincept-terminal-desktop/src/components/tabs/dashboard/AddWidgetModal.tsx
index c76dda56f..ede6e30b2 100644
--- a/fincept-terminal-desktop/src/components/tabs/dashboard/AddWidgetModal.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/AddWidgetModal.tsx
@@ -2,6 +2,8 @@ import React, { useState, useEffect } from 'react';
import { X } from 'lucide-react';
import { WidgetType, DEFAULT_WIDGET_CONFIGS } from './widgets';
import { watchlistService } from '../../../services/watchlistService';
+import { getAllDataSources } from '../../../services/dataSourceRegistry';
+import { DataSource } from '../../../services/sqliteService';
const BLOOMBERG_ORANGE = '#FFA500';
const BLOOMBERG_WHITE = '#FFFFFF';
@@ -22,17 +24,22 @@ export const AddWidgetModal: React.FC<AddWidgetModalProps> = ({
}) => {
const [selectedType, setSelectedType] = useState<WidgetType>('news');
const [watchlists, setWatchlists] = useState<any[]>([]);
+ const [dataSources, setDataSources] = useState<DataSource[]>([]);
// Widget-specific configs
const [newsCategory, setNewsCategory] = useState('ALL');
const [marketCategory, setMarketCategory] = useState('Indices');
const [selectedWatchlist, setSelectedWatchlist] = useState('');
const [forumCategory, setForumCategory] = useState('Trending');
+ const [selectedDataSource, setSelectedDataSource] = useState('');
useEffect(() => {
if (isOpen && selectedType === 'watchlist') {
loadWatchlists();
}
+ if (isOpen && selectedType === 'datasource') {
+ loadDataSources();
+ }
}, [isOpen, selectedType]);
const loadWatchlists = async () => {
@@ -48,6 +55,19 @@ export const AddWidgetModal: React.FC<AddWidgetModalProps> = ({
}
};
+ const loadDataSources = async () => {
+ try {
+ const sources = await getAllDataSources();
+ const enabled = sources.filter(s => s.enabled);
+ setDataSources(enabled);
+ if (enabled.length > 0) {
+ setSelectedDataSource(enabled[0].alias);
+ }
+ } catch (error) {
+ console.error('Failed to load data sources:', error);
+ }
+ };
+
const handleAdd = () => {
let config = {};
@@ -73,6 +93,13 @@ export const AddWidgetModal: React.FC<AddWidgetModalProps> = ({
case 'forum':
config = { forumCategoryName: forumCategory, forumLimit: 5 };
break;
+ case 'datasource':
+ const ds = dataSources.find(d => d.alias === selectedDataSource);
+ config = {
+ dataSourceAlias: selectedDataSource,
+ dataSourceDisplayName: ds?.display_name
+ };
+ break;
}
onAdd(selectedType, config);
@@ -142,7 +169,7 @@ export const AddWidgetModal: React.FC<AddWidgetModalProps> = ({
WIDGET TYPE
</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '8px' }}>
- {(['news', 'market', 'watchlist', 'forum', 'crypto', 'commodities', 'indices', 'forex', 'maritime'] as WidgetType[]).map(type => (
+ {(['news', 'market', 'watchlist', 'forum', 'crypto', 'commodities', 'indices', 'forex', 'maritime', 'datasource'] as WidgetType[]).map(type => (
<button
key={type}
onClick={() => setSelectedType(type)}
@@ -256,6 +283,34 @@ export const AddWidgetModal: React.FC<AddWidgetModalProps> = ({
</select>
)}
+ {/* Data Source Config */}
+ {selectedType === 'datasource' && (
+ dataSources.length > 0 ? (
+ <select
+ value={selectedDataSource}
+ onChange={(e) => setSelectedDataSource(e.target.value)}
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '8px',
+ fontSize: '11px'
+ }}
+ >
+ {dataSources.map(ds => (
+ <option key={ds.alias} value={ds.alias}>
+ {ds.display_name} ({ds.alias}) - {ds.type === 'websocket' ? 'WebSocket' : 'REST API'}
+ </option>
+ ))}
+ </select>
+ ) : (
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '10px', padding: '8px' }}>
+ No data sources available. Create one in Settings → Data Sources first.
+ </div>
+ )
+ )}
+
{/* Crypto, Commodities, Indices, Forex, Maritime - No Config */}
{['crypto', 'commodities', 'indices', 'forex', 'maritime'].includes(selectedType) && (
<div style={{ color: BLOOMBERG_GRAY, fontSize: '10px', padding: '8px', fontStyle: 'italic' }}>
@@ -283,15 +338,15 @@ export const AddWidgetModal: React.FC<AddWidgetModalProps> = ({
</button>
<button
onClick={handleAdd}
- disabled={selectedType === 'watchlist' && watchlists.length === 0}
+ disabled={(selectedType === 'watchlist' && watchlists.length === 0) || (selectedType === 'datasource' && dataSources.length === 0)}
style={{
- backgroundColor: (selectedType === 'watchlist' && watchlists.length === 0) ? BLOOMBERG_GRAY : BLOOMBERG_ORANGE,
+ backgroundColor: ((selectedType === 'watchlist' && watchlists.length === 0) || (selectedType === 'datasource' && dataSources.length === 0)) ? BLOOMBERG_GRAY : BLOOMBERG_ORANGE,
color: BLOOMBERG_DARK_BG,
border: 'none',
padding: '8px 16px',
fontSize: '11px',
fontWeight: 'bold',
- cursor: (selectedType === 'watchlist' && watchlists.length === 0) ? 'not-allowed' : 'pointer',
+ cursor: ((selectedType === 'watchlist' && watchlists.length === 0) || (selectedType === 'datasource' && dataSources.length === 0)) ? 'not-allowed' : 'pointer',
borderRadius: '2px'
}}
>
diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/DataSourceWidget.tsx b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/DataSourceWidget.tsx
new file mode 100644
index 000000000..e17047bef
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/DataSourceWidget.tsx
@@ -0,0 +1,232 @@
+import React, { useState, useEffect } from 'react';
+import { BaseWidget } from './BaseWidget';
+import { useDataSource } from '@/hooks/useDataSource';
+import { Database, Wifi, AlertCircle } from 'lucide-react';
+
+interface DataSourceWidgetProps {
+ id: string;
+ alias: string;
+ displayName?: string;
+ onRemove?: () => void;
+}
+
+const BLOOMBERG_ORANGE = '#FFA500';
+const BLOOMBERG_WHITE = '#FFFFFF';
+const BLOOMBERG_GREEN = '#00ff00';
+const BLOOMBERG_RED = '#ff0000';
+const BLOOMBERG_GRAY = '#787878';
+
+export const DataSourceWidget: React.FC<DataSourceWidgetProps> = ({
+ id,
+ alias,
+ displayName,
+ onRemove
+}) => {
+ const { data, error, loading, connected, source, refresh } = useDataSource(alias);
+ const [lastUpdate, setLastUpdate] = useState<Date | null>(null);
+ const [updateCount, setUpdateCount] = useState(0);
+ const [isBlinking, setIsBlinking] = useState(false);
+
+ // Log data updates for debugging
+ useEffect(() => {
+ if (data) {
+ console.log(`[DataSourceWidget ${alias}] Data update #${updateCount}:`, data);
+ }
+ }, [data, alias, updateCount]);
+
+ // Update last update time when data changes
+ useEffect(() => {
+ if (data && !loading) {
+ setLastUpdate(new Date());
+ setUpdateCount(prev => prev + 1);
+
+ // Blink effect on update
+ setIsBlinking(true);
+ const timer = setTimeout(() => setIsBlinking(false), 300);
+ return () => clearTimeout(timer);
+ }
+ }, [data, loading]);
+
+ const renderDataValue = (value: any): React.ReactNode => {
+ if (value === null || value === undefined) return <span style={{ color: BLOOMBERG_GRAY }}>N/A</span>;
+
+ if (typeof value === 'object') {
+ return (
+ <div style={{ fontSize: '9px', fontFamily: 'monospace' }}>
+ {Object.entries(value).slice(0, 10).map(([key, val]) => (
+ <div key={key} style={{ padding: '2px 0', borderBottom: `1px solid #1a1a1a` }}>
+ <span style={{ color: BLOOMBERG_ORANGE }}>{key}:</span>{' '}
+ <span style={{ color: BLOOMBERG_WHITE }}>
+ {typeof val === 'object' ? JSON.stringify(val).substring(0, 50) : String(val)}
+ </span>
+ </div>
+ ))}
+ </div>
+ );
+ }
+
+ return <span style={{ color: BLOOMBERG_WHITE }}>{String(value)}</span>;
+ };
+
+ const renderContent = () => {
+ if (error) {
+ return (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100%',
+ padding: '20px',
+ textAlign: 'center'
+ }}>
+ <AlertCircle size={32} color={BLOOMBERG_RED} />
+ <div style={{ color: BLOOMBERG_RED, fontSize: '11px', marginTop: '8px' }}>
+ {error}
+ </div>
+ </div>
+ );
+ }
+
+ if (loading && !data) {
+ return (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100%',
+ gap: '8px'
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px' }}>
+ Loading data source...
+ </div>
+ </div>
+ );
+ }
+
+ if (!data) {
+ return (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100%',
+ gap: '8px',
+ color: BLOOMBERG_GRAY,
+ fontSize: '10px'
+ }}>
+ <Database size={24} />
+ <div>No data available yet</div>
+ {source?.type === 'rest_api' && (
+ <button
+ onClick={refresh}
+ style={{
+ background: BLOOMBERG_ORANGE,
+ color: '#000',
+ border: 'none',
+ padding: '6px 12px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ marginTop: '8px'
+ }}
+ >
+ LOAD DATA
+ </button>
+ )}
+ </div>
+ );
+ }
+
+ return (
+ <div style={{ padding: '8px', fontSize: '10px' }}>
+ {/* Status Bar */}
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '8px',
+ padding: '4px 8px',
+ backgroundColor: isBlinking ? '#1a1a1a' : '#0a0a0a',
+ border: `1px solid ${connected ? BLOOMBERG_GREEN : BLOOMBERG_GRAY}`,
+ fontSize: '9px',
+ transition: 'background-color 0.3s ease'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ {source?.type === 'websocket' ? (
+ <Wifi size={12} color={connected ? BLOOMBERG_GREEN : BLOOMBERG_GRAY} />
+ ) : (
+ <Database size={12} color={BLOOMBERG_ORANGE} />
+ )}
+ <span style={{ color: BLOOMBERG_WHITE }}>
+ {source?.type === 'websocket' ? 'WebSocket' : 'REST API'}
+ </span>
+ <span style={{ color: connected ? BLOOMBERG_GREEN : BLOOMBERG_GRAY }}>
+ {connected ? '● LIVE' : '○ IDLE'}
+ </span>
+ {updateCount > 0 && (
+ <span style={{ color: BLOOMBERG_ORANGE, fontSize: '8px' }}>
+ #{updateCount}
+ </span>
+ )}
+ </div>
+
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '8px' }}>
+ {lastUpdate && (
+ <span>{lastUpdate.toLocaleTimeString()}</span>
+ )}
+ </div>
+ </div>
+
+ {/* Data Display */}
+ <div style={{
+ maxHeight: 'calc(100% - 60px)',
+ overflowY: 'auto',
+ backgroundColor: '#050505',
+ border: `1px solid #1a1a1a`,
+ padding: '8px'
+ }}>
+ {renderDataValue(data)}
+ </div>
+
+ {/* Actions */}
+ {source?.type === 'rest_api' && (
+ <div style={{ marginTop: '8px', textAlign: 'center' }}>
+ <button
+ onClick={refresh}
+ disabled={loading}
+ style={{
+ background: loading ? BLOOMBERG_GRAY : BLOOMBERG_ORANGE,
+ color: '#000',
+ border: 'none',
+ padding: '4px 12px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: loading ? 'not-allowed' : 'pointer',
+ width: '100%'
+ }}
+ >
+ {loading ? 'REFRESHING...' : 'REFRESH DATA'}
+ </button>
+ </div>
+ )}
+ </div>
+ );
+ };
+
+ return (
+ <BaseWidget
+ id={id}
+ title={displayName || source?.display_name || alias}
+ onRemove={onRemove}
+ onRefresh={source?.type === 'rest_api' ? refresh : undefined}
+ isLoading={loading && !data}
+ error={null}
+ headerColor={source?.type === 'websocket' ? BLOOMBERG_GREEN : BLOOMBERG_ORANGE}
+ >
+ {renderContent()}
+ </BaseWidget>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/index.ts b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/index.ts
index f80415d32..271da9f7f 100644
--- a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/index.ts
@@ -8,9 +8,10 @@ export { CommoditiesWidget } from './CommoditiesWidget';
export { GlobalIndicesWidget } from './GlobalIndicesWidget';
export { ForexWidget } from './ForexWidget';
export { MaritimeWidget } from './MaritimeWidget';
+export { DataSourceWidget } from './DataSourceWidget';
// Widget type definitions
-export type WidgetType = 'news' | 'market' | 'watchlist' | 'forum' | 'crypto' | 'commodities' | 'indices' | 'forex' | 'maritime';
+export type WidgetType = 'news' | 'market' | 'watchlist' | 'forum' | 'crypto' | 'commodities' | 'indices' | 'forex' | 'maritime' | 'datasource';
export interface WidgetConfig {
id: string;
@@ -33,6 +34,10 @@ export interface WidgetConfig {
forumCategoryId?: number;
forumCategoryName?: string;
forumLimit?: number;
+
+ // Data Source widget config
+ dataSourceAlias?: string;
+ dataSourceDisplayName?: string;
};
}
@@ -92,5 +97,13 @@ export const DEFAULT_WIDGET_CONFIGS: Record<WidgetType, Partial<WidgetConfig>> =
type: 'maritime',
title: 'Maritime Intelligence',
config: {}
+ },
+ datasource: {
+ type: 'datasource',
+ title: 'Data Source',
+ config: {
+ dataSourceAlias: '',
+ dataSourceDisplayName: ''
+ }
}
};
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/AgentMediatorNode.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/AgentMediatorNode.tsx
new file mode 100644
index 000000000..c4e9e2175
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/AgentMediatorNode.tsx
@@ -0,0 +1,432 @@
+// AgentMediatorNode.tsx - LLM-powered mediator between agents
+import React, { useState, useEffect } from 'react';
+import { Handle, Position } from 'reactflow';
+import { MessageSquare, Settings, CheckCircle, AlertCircle, Loader, Brain } from 'lucide-react';
+import { sqliteService, LLMConfig } from '@/services/sqliteService';
+
+interface AgentMediatorNodeProps {
+ id: string;
+ data: {
+ label: string;
+ selectedProvider?: string; // Which LLM provider to use for mediation
+ customPrompt?: string; // Custom mediation prompt
+ status: 'idle' | 'running' | 'completed' | 'error';
+ result?: string; // Mediated context
+ error?: string;
+ inputData?: any; // Data from previous agent
+ onExecute?: (nodeId: string) => void;
+ onConfigChange?: (config: { selectedProvider?: string; customPrompt?: string }) => void;
+ };
+ selected: boolean;
+}
+
+const AgentMediatorNode: React.FC<AgentMediatorNodeProps> = ({ id, data, selected }) => {
+ const [showSettings, setShowSettings] = useState(false);
+ const [availableProviders, setAvailableProviders] = useState<LLMConfig[]>([]);
+ const [localProvider, setLocalProvider] = useState(data.selectedProvider || 'active');
+ const [localPrompt, setLocalPrompt] = useState(data.customPrompt || '');
+
+ // Bloomberg colors
+ const ORANGE = '#FFA500';
+ const WHITE = '#FFFFFF';
+ const GRAY = '#787878';
+ const DARK_BG = '#0a0a0a';
+ const PANEL_BG = '#1a1a1a';
+ const BORDER = '#2d2d2d';
+ const GREEN = '#10b981';
+ const RED = '#ef4444';
+ const BLUE = '#3b82f6';
+
+ // Load available LLM providers
+ useEffect(() => {
+ const loadProviders = async () => {
+ try {
+ const configs = await sqliteService.getLLMConfigs();
+ setAvailableProviders(configs);
+ } catch (error) {
+ console.error('Failed to load LLM providers:', error);
+ }
+ };
+ loadProviders();
+ }, []);
+
+ const getStatusColor = () => {
+ switch (data.status) {
+ case 'running': return BLUE;
+ case 'completed': return GREEN;
+ case 'error': return RED;
+ default: return ORANGE;
+ }
+ };
+
+ const getStatusIcon = () => {
+ switch (data.status) {
+ case 'running': return <Loader size={14} className="animate-spin" color={BLUE} />;
+ case 'completed': return <CheckCircle size={14} color={GREEN} />;
+ case 'error': return <AlertCircle size={14} color={RED} />;
+ default: return <Brain size={14} color={ORANGE} />;
+ }
+ };
+
+ const handleSaveConfig = () => {
+ data.onConfigChange?.({
+ selectedProvider: localProvider === 'active' ? undefined : localProvider,
+ customPrompt: localPrompt || undefined
+ });
+ setShowSettings(false);
+ };
+
+ const getProviderLabel = () => {
+ if (!data.selectedProvider || data.selectedProvider === 'active') {
+ return 'Active Provider';
+ }
+ const provider = availableProviders.find(p => p.provider === data.selectedProvider);
+ return provider ? `${provider.provider.toUpperCase()} - ${provider.model}` : data.selectedProvider;
+ };
+
+ return (
+ <div style={{
+ backgroundColor: PANEL_BG,
+ border: `2px solid ${selected ? ORANGE : getStatusColor()}`,
+ borderRadius: '8px',
+ padding: '12px',
+ minWidth: '280px',
+ maxWidth: '350px',
+ fontFamily: 'Consolas, monospace',
+ boxShadow: selected ? `0 0 16px ${ORANGE}60` : `0 2px 8px rgba(0,0,0,0.3)`
+ }}>
+ {/* Input Handle */}
+ <Handle
+ type="target"
+ position={Position.Left}
+ style={{
+ background: BLUE,
+ width: '12px',
+ height: '12px',
+ border: `2px solid ${DARK_BG}`,
+ left: '-6px'
+ }}
+ />
+
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '10px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${BORDER}`
+ }}>
+ <MessageSquare size={20} color={BLUE} />
+ <div style={{ flex: 1 }}>
+ <div style={{
+ color: WHITE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ marginBottom: '2px'
+ }}>
+ {data.label}
+ </div>
+ <div style={{
+ color: GRAY,
+ fontSize: '9px',
+ textTransform: 'uppercase'
+ }}>
+ LLM MEDIATOR
+ </div>
+ </div>
+ {getStatusIcon()}
+ </div>
+
+ {/* LLM Provider Display */}
+ <div style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${BORDER}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: BLUE,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ LLM PROVIDER
+ </div>
+ <div style={{
+ color: WHITE,
+ fontSize: '8px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <Brain size={10} color={BLUE} />
+ {getProviderLabel()}
+ </div>
+ </div>
+
+ {/* Input Data Preview */}
+ {data.inputData && (
+ <div style={{
+ backgroundColor: `${GRAY}15`,
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: GRAY,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ INPUT DATA
+ </div>
+ <div style={{
+ color: WHITE,
+ fontSize: '8px',
+ fontFamily: 'monospace',
+ maxHeight: '50px',
+ overflow: 'auto'
+ }}>
+ {JSON.stringify(data.inputData, null, 2).substring(0, 80)}...
+ </div>
+ </div>
+ )}
+
+ {/* Mediated Result */}
+ {data.status === 'completed' && data.result && (
+ <div style={{
+ backgroundColor: `${GREEN}15`,
+ border: `1px solid ${GREEN}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: GREEN,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <CheckCircle size={10} />
+ MEDIATED CONTEXT
+ </div>
+ <div style={{
+ color: WHITE,
+ fontSize: '8px',
+ maxHeight: '80px',
+ overflow: 'auto',
+ lineHeight: '1.4'
+ }}>
+ {typeof data.result === 'string'
+ ? data.result.substring(0, 150)
+ : JSON.stringify(data.result, null, 2).substring(0, 150)
+ }...
+ </div>
+ </div>
+ )}
+
+ {/* Error Display */}
+ {data.status === 'error' && data.error && (
+ <div style={{
+ backgroundColor: `${RED}15`,
+ border: `1px solid ${RED}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: RED,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <AlertCircle size={10} />
+ ERROR
+ </div>
+ <div style={{
+ color: RED,
+ fontSize: '8px',
+ wordBreak: 'break-word'
+ }}>
+ {data.error}
+ </div>
+ </div>
+ )}
+
+ {/* Settings Panel */}
+ {showSettings && (
+ <div style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${ORANGE}`,
+ borderRadius: '4px',
+ padding: '8px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginBottom: '8px'
+ }}>
+ MEDIATOR SETTINGS
+ </div>
+
+ {/* Provider Selection */}
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'block',
+ marginBottom: '4px'
+ }}>
+ LLM Provider
+ </label>
+ <select
+ value={localProvider}
+ onChange={(e) => setLocalProvider(e.target.value)}
+ style={{
+ width: '100%',
+ backgroundColor: PANEL_BG,
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '4px',
+ fontSize: '8px',
+ borderRadius: '3px'
+ }}
+ >
+ <option value="active">Use Active Provider</option>
+ {availableProviders.map(provider => (
+ <option key={provider.provider} value={provider.provider}>
+ {provider.provider.toUpperCase()} - {provider.model}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Custom Prompt */}
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'block',
+ marginBottom: '4px'
+ }}>
+ Custom Mediation Prompt (optional)
+ </label>
+ <textarea
+ value={localPrompt}
+ onChange={(e) => setLocalPrompt(e.target.value)}
+ placeholder="Leave empty for default prompt"
+ rows={3}
+ style={{
+ width: '100%',
+ backgroundColor: PANEL_BG,
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '4px',
+ fontSize: '8px',
+ borderRadius: '3px',
+ resize: 'vertical',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ <button
+ onClick={handleSaveConfig}
+ style={{
+ width: '100%',
+ backgroundColor: BLUE,
+ color: 'white',
+ border: 'none',
+ padding: '6px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '3px'
+ }}
+ >
+ SAVE CONFIG
+ </button>
+ </div>
+ )}
+
+ {/* Action Buttons */}
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <button
+ onClick={() => data.onExecute?.(id)}
+ disabled={data.status === 'running'}
+ style={{
+ flex: 1,
+ backgroundColor: data.status === 'running' ? GRAY : BLUE,
+ color: 'white',
+ border: 'none',
+ padding: '8px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: data.status === 'running' ? 'not-allowed' : 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ opacity: data.status === 'running' ? 0.6 : 1
+ }}
+ >
+ {data.status === 'running' ? (
+ <>
+ <Loader size={12} className="animate-spin" />
+ MEDIATING...
+ </>
+ ) : (
+ <>
+ <Brain size={12} />
+ MEDIATE
+ </>
+ )}
+ </button>
+ <button
+ onClick={() => setShowSettings(!showSettings)}
+ style={{
+ backgroundColor: showSettings ? BLUE : DARK_BG,
+ border: `1px solid ${BORDER}`,
+ color: showSettings ? WHITE : GRAY,
+ padding: '8px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center'
+ }}
+ >
+ <Settings size={14} />
+ </button>
+ </div>
+
+ {/* Output Handle */}
+ <Handle
+ type="source"
+ position={Position.Right}
+ style={{
+ background: data.status === 'completed' ? GREEN : BLUE,
+ width: '12px',
+ height: '12px',
+ border: `2px solid ${DARK_BG}`,
+ right: '-6px'
+ }}
+ />
+ </div>
+ );
+};
+
+export default AgentMediatorNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/PythonAgentNode.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/PythonAgentNode.tsx
new file mode 100644
index 000000000..0dba2f21e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/PythonAgentNode.tsx
@@ -0,0 +1,410 @@
+// PythonAgentNode.tsx - Visual node for Python agents in Node Editor
+import React, { useState, useEffect } from 'react';
+import { Handle, Position } from 'reactflow';
+import { Play, Settings, CheckCircle, AlertCircle, Loader, TrendingUp, Brain } from 'lucide-react';
+import { sqliteService, LLMConfig } from '@/services/sqliteService';
+
+interface PythonAgentNodeProps {
+ id: string;
+ data: {
+ agentType: string;
+ agentCategory: string;
+ label: string;
+ icon: string;
+ color: string;
+ parameters: Record<string, any>;
+ selectedLLM?: string; // Which LLM provider to use for this agent
+ status: 'idle' | 'running' | 'completed' | 'error';
+ result?: any;
+ error?: string;
+ onExecute?: (nodeId: string) => void;
+ onParameterChange?: (params: Record<string, any>) => void;
+ onLLMChange?: (provider: string) => void;
+ };
+ selected: boolean;
+}
+
+const PythonAgentNode: React.FC<PythonAgentNodeProps> = ({ id, data, selected }) => {
+ const [showSettings, setShowSettings] = useState(false);
+ const [availableLLMs, setAvailableLLMs] = useState<LLMConfig[]>([]);
+ const [selectedLLM, setSelectedLLM] = useState(data.selectedLLM || 'active');
+
+ // Load available LLM providers from Settings
+ useEffect(() => {
+ const loadLLMs = async () => {
+ try {
+ const configs = await sqliteService.getLLMConfigs();
+ setAvailableLLMs(configs);
+ } catch (error) {
+ console.error('Failed to load LLM configs:', error);
+ }
+ };
+ loadLLMs();
+ }, []);
+
+ // Bloomberg colors
+ const ORANGE = '#FFA500';
+ const WHITE = '#FFFFFF';
+ const GRAY = '#787878';
+ const DARK_BG = '#0a0a0a';
+ const PANEL_BG = '#1a1a1a';
+ const BORDER = '#2d2d2d';
+ const GREEN = '#10b981';
+ const RED = '#ef4444';
+
+ const getStatusColor = () => {
+ switch (data.status) {
+ case 'running': return ORANGE;
+ case 'completed': return GREEN;
+ case 'error': return RED;
+ default: return GRAY;
+ }
+ };
+
+ const getStatusIcon = () => {
+ switch (data.status) {
+ case 'running': return <Loader size={14} className="animate-spin" color={ORANGE} />;
+ case 'completed': return <CheckCircle size={14} color={GREEN} />;
+ case 'error': return <AlertCircle size={14} color={RED} />;
+ default: return <TrendingUp size={14} color={GRAY} />;
+ }
+ };
+
+ return (
+ <div style={{
+ backgroundColor: PANEL_BG,
+ border: `2px solid ${selected ? ORANGE : getStatusColor()}`,
+ borderRadius: '8px',
+ padding: '12px',
+ minWidth: '250px',
+ maxWidth: '320px',
+ fontFamily: 'Consolas, monospace',
+ boxShadow: selected ? `0 0 16px ${ORANGE}60` : `0 2px 8px rgba(0,0,0,0.3)`
+ }}>
+ {/* Input Handle */}
+ <Handle
+ type="target"
+ position={Position.Left}
+ style={{
+ background: data.color,
+ width: '12px',
+ height: '12px',
+ border: `2px solid ${DARK_BG}`,
+ left: '-6px'
+ }}
+ />
+
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '10px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${BORDER}`
+ }}>
+ <span style={{ fontSize: '20px' }}>{data.icon}</span>
+ <div style={{ flex: 1 }}>
+ <div style={{
+ color: WHITE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ marginBottom: '2px'
+ }}>
+ {data.label}
+ </div>
+ <div style={{
+ color: GRAY,
+ fontSize: '9px',
+ textTransform: 'uppercase'
+ }}>
+ {data.agentCategory}
+ </div>
+ </div>
+ {getStatusIcon()}
+ </div>
+
+ {/* Parameters Summary */}
+ {Object.keys(data.parameters).length > 0 && (
+ <div style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${BORDER}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ PARAMETERS
+ </div>
+ {Object.entries(data.parameters).slice(0, 2).map(([key, value]) => (
+ <div key={key} style={{
+ color: GRAY,
+ fontSize: '8px',
+ marginBottom: '2px',
+ display: 'flex',
+ justifyContent: 'space-between'
+ }}>
+ <span>{key}:</span>
+ <span style={{ color: WHITE }}>
+ {Array.isArray(value) ? value.join(', ') : String(value).substring(0, 20)}
+ </span>
+ </div>
+ ))}
+ {Object.keys(data.parameters).length > 2 && (
+ <div style={{ color: GRAY, fontSize: '8px', fontStyle: 'italic' }}>
+ +{Object.keys(data.parameters).length - 2} more...
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Result Preview */}
+ {data.status === 'completed' && data.result && (
+ <div style={{
+ backgroundColor: `${GREEN}15`,
+ border: `1px solid ${GREEN}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: GREEN,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <CheckCircle size={10} />
+ RESULT
+ </div>
+ <div style={{
+ color: WHITE,
+ fontSize: '8px',
+ fontFamily: 'monospace',
+ maxHeight: '60px',
+ overflow: 'auto'
+ }}>
+ {JSON.stringify(data.result, null, 2).substring(0, 100)}...
+ </div>
+ </div>
+ )}
+
+ {/* Error Display */}
+ {data.status === 'error' && data.error && (
+ <div style={{
+ backgroundColor: `${RED}15`,
+ border: `1px solid ${RED}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: RED,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <AlertCircle size={10} />
+ ERROR
+ </div>
+ <div style={{
+ color: RED,
+ fontSize: '8px',
+ wordBreak: 'break-word'
+ }}>
+ {data.error}
+ </div>
+ </div>
+ )}
+
+ {/* LLM Display - Always visible, clickable to configure */}
+ <div
+ onClick={() => setShowSettings(!showSettings)}
+ style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${showSettings ? ORANGE : BORDER}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px',
+ cursor: 'pointer',
+ transition: 'border-color 0.2s'
+ }}
+ >
+ <div style={{
+ color: GRAY,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: '4px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <Brain size={10} />
+ LLM
+ </div>
+ <Settings size={10} color={showSettings ? ORANGE : GRAY} />
+ </div>
+ <div style={{
+ color: WHITE,
+ fontSize: '8px'
+ }}>
+ {selectedLLM === 'active' ? 'Active Provider' : selectedLLM.toUpperCase()}
+ </div>
+ </div>
+
+ {/* LLM Selection Panel */}
+ {showSettings && (
+ <div style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${ORANGE}`,
+ borderRadius: '4px',
+ padding: '8px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginBottom: '8px'
+ }}>
+ LLM CONFIGURATION
+ </div>
+
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'block',
+ marginBottom: '4px'
+ }}>
+ LLM Provider for Analysis
+ </label>
+ <select
+ value={selectedLLM}
+ onChange={(e) => {
+ setSelectedLLM(e.target.value);
+ data.onLLMChange?.(e.target.value);
+ }}
+ style={{
+ width: '100%',
+ backgroundColor: PANEL_BG,
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '4px',
+ fontSize: '8px',
+ borderRadius: '3px'
+ }}
+ >
+ <option value="active">Use Active Provider (from Settings)</option>
+ {availableLLMs.map(llm => (
+ <option key={llm.provider} value={llm.provider}>
+ {llm.provider.toUpperCase()} - {llm.model}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowSettings(false);
+ }}
+ style={{
+ width: '100%',
+ backgroundColor: ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '6px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '3px'
+ }}
+ >
+ CLOSE
+ </button>
+ </div>
+ )}
+
+ {/* Action Buttons */}
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <button
+ onClick={() => data.onExecute?.(id)}
+ disabled={data.status === 'running'}
+ style={{
+ flex: 1,
+ backgroundColor: data.status === 'running' ? GRAY : data.color,
+ color: 'black',
+ border: 'none',
+ padding: '8px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: data.status === 'running' ? 'not-allowed' : 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ opacity: data.status === 'running' ? 0.6 : 1
+ }}
+ >
+ {data.status === 'running' ? (
+ <>
+ <Loader size={12} className="animate-spin" />
+ RUNNING...
+ </>
+ ) : (
+ <>
+ <Play size={12} />
+ EXECUTE
+ </>
+ )}
+ </button>
+ <button
+ onClick={() => setShowSettings(!showSettings)}
+ style={{
+ backgroundColor: showSettings ? ORANGE : DARK_BG,
+ border: `1px solid ${BORDER}`,
+ color: showSettings ? 'black' : GRAY,
+ padding: '8px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center'
+ }}
+ >
+ <Settings size={14} />
+ </button>
+ </div>
+
+ {/* Output Handle */}
+ <Handle
+ type="source"
+ position={Position.Right}
+ style={{
+ background: data.status === 'completed' ? GREEN : data.color,
+ width: '12px',
+ height: '12px',
+ border: `2px solid ${DARK_BG}`,
+ right: '-6px'
+ }}
+ />
+ </div>
+ );
+};
+
+export default PythonAgentNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/ResultsDisplayNode.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/ResultsDisplayNode.tsx
new file mode 100644
index 000000000..1692ccd00
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/ResultsDisplayNode.tsx
@@ -0,0 +1,465 @@
+// ResultsDisplayNode.tsx - Display results from previous nodes
+import React, { useState } from 'react';
+import { Handle, Position } from 'reactflow';
+import { Eye, EyeOff, Copy, Check } from 'lucide-react';
+
+interface ResultsDisplayNodeProps {
+ data: {
+ label: string;
+ inputData?: any;
+ color: string;
+ };
+ selected: boolean;
+}
+
+const ResultsDisplayNode: React.FC<ResultsDisplayNodeProps> = ({ data, selected }) => {
+ const [expanded, setExpanded] = useState(true);
+ const [copied, setCopied] = useState(false);
+ const [width, setWidth] = useState(500);
+ const [height, setHeight] = useState(400);
+
+ // Debug logging
+ console.log('[ResultsDisplayNode] Rendering with data:', data);
+ console.log('[ResultsDisplayNode] inputData present:', !!data.inputData);
+ console.log('[ResultsDisplayNode] inputData value:', data.inputData);
+
+ // Bloomberg colors
+ const ORANGE = '#FFA500';
+ const WHITE = '#FFFFFF';
+ const GRAY = '#787878';
+ const DARK_BG = '#0a0a0a';
+ const PANEL_BG = '#1a1a1a';
+ const BORDER = '#2d2d2d';
+
+ const handleCopy = () => {
+ if (data.inputData) {
+ navigator.clipboard.writeText(JSON.stringify(data.inputData, null, 2));
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ }
+ };
+
+ const formatValue = (value: any): string => {
+ if (value === null || value === undefined) return 'null';
+ if (typeof value === 'object') {
+ return JSON.stringify(value, null, 2);
+ }
+ return String(value);
+ };
+
+ const renderMarkdown = (text: string) => {
+ const lines = text.split('\n');
+ const elements: JSX.Element[] = [];
+ let inTable = false;
+
+ lines.forEach((line, i) => {
+ let style: React.CSSProperties = {
+ color: WHITE,
+ fontSize: '10px',
+ lineHeight: '1.7',
+ marginBottom: '3px',
+ fontFamily: 'Consolas, monospace'
+ };
+
+ // Skip markdown separators
+ if (line.trim() === '---' || line.trim() === '***' || /^-{3,}$/.test(line.trim())) {
+ elements.push(
+ <div key={i} style={{
+ borderTop: `1px solid ${BORDER}`,
+ margin: '12px 0',
+ opacity: 0.5
+ }} />
+ );
+ return;
+ }
+
+ // Headers
+ if (line.startsWith('###')) {
+ style = {
+ color: '#10b981',
+ fontWeight: 'bold',
+ fontSize: '11px',
+ marginTop: '12px',
+ marginBottom: '6px',
+ borderBottom: `1px solid ${BORDER}`,
+ paddingBottom: '4px'
+ };
+ line = line.replace(/^###\s*/, '');
+ } else if (line.startsWith('##')) {
+ style = {
+ color: ORANGE,
+ fontWeight: 'bold',
+ fontSize: '13px',
+ marginTop: '16px',
+ marginBottom: '8px',
+ borderBottom: `2px solid ${ORANGE}40`,
+ paddingBottom: '6px'
+ };
+ line = line.replace(/^##\s*/, '');
+ } else if (line.startsWith('#')) {
+ style = {
+ color: ORANGE,
+ fontWeight: 'bold',
+ fontSize: '14px',
+ marginTop: '16px',
+ marginBottom: '8px'
+ };
+ line = line.replace(/^#\s*/, '');
+ }
+ // Table detection
+ else if (line.startsWith('|')) {
+ inTable = true;
+ const cells = line.split('|').map(c => c.trim()).filter(c => c);
+
+ // Check if it's a separator row
+ if (cells.every(c => /^[-:]+$/.test(c))) {
+ return; // Skip separator rows
+ }
+
+ // Render table row
+ elements.push(
+ <div key={i} style={{
+ display: 'flex',
+ gap: '8px',
+ padding: '4px 0',
+ borderBottom: `1px solid ${BORDER}30`,
+ fontFamily: 'Consolas, monospace',
+ fontSize: '9px'
+ }}>
+ {cells.map((cell, cellIdx) => (
+ <div
+ key={cellIdx}
+ style={{
+ flex: cellIdx === 0 ? '0 0 150px' : '1',
+ color: cellIdx === 0 ? ORANGE : '#d4d4d4',
+ fontWeight: cellIdx === 0 ? 'bold' : 'normal',
+ padding: '2px 6px',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis'
+ }}
+ >
+ {cell.replace(/\*\*/g, '')}
+ </div>
+ ))}
+ </div>
+ );
+ return;
+ }
+ // Bullet points
+ else if (line.startsWith('- ') || line.startsWith('• ')) {
+ style = {
+ ...style,
+ marginLeft: '16px',
+ color: '#d4d4d4',
+ display: 'flex',
+ alignItems: 'flex-start'
+ };
+ const content = line.replace(/^[-•]\s*/, '');
+ elements.push(
+ <div key={i} style={style}>
+ <span style={{ color: '#10b981', marginRight: '8px' }}>•</span>
+ <span>{content.replace(/\*\*/g, '')}</span>
+ </div>
+ );
+ return;
+ }
+ // Numbered lists
+ else if (/^\d+\.\s/.test(line)) {
+ style = {
+ ...style,
+ marginLeft: '16px',
+ color: '#d4d4d4'
+ };
+ line = line.replace(/\*\*/g, '');
+ }
+ // Bold text inline
+ else if (line.includes('**')) {
+ const parts = line.split(/\*\*([^*]+)\*\*/g);
+ elements.push(
+ <div key={i} style={style}>
+ {parts.map((part, idx) =>
+ idx % 2 === 1 ? (
+ <span key={idx} style={{ color: '#10b981', fontWeight: 'bold' }}>
+ {part}
+ </span>
+ ) : (
+ <span key={idx}>{part}</span>
+ )
+ )}
+ </div>
+ );
+ return;
+ }
+ // Italic text in parentheses
+ else if (line.startsWith('*(') || line.startsWith('*')) {
+ style = { ...style, color: GRAY, fontStyle: 'italic', fontSize: '9px' };
+ line = line.replace(/^\*\(/, '(').replace(/\)$/, ')').replace(/^\*/, '').replace(/\*$/, '');
+ }
+ // Empty lines
+ else if (line.trim() === '') {
+ elements.push(<div key={i} style={{ height: '8px' }} />);
+ return;
+ }
+
+ elements.push(<div key={i} style={style}>{line || '\u00A0'}</div>);
+ });
+
+ return <>{elements}</>;
+ };
+
+ const renderData = (obj: any, depth = 0) => {
+ if (!obj || typeof obj !== 'object') {
+ const strValue = formatValue(obj);
+ // Check if it looks like markdown text (has headers, tables, etc)
+ if (typeof obj === 'string' && (obj.includes('##') || obj.includes('|') || obj.length > 200)) {
+ return (
+ <div style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${BORDER}`,
+ borderRadius: '4px',
+ padding: '8px',
+ marginTop: '4px'
+ }}>
+ {renderMarkdown(obj)}
+ </div>
+ );
+ }
+ return (
+ <div style={{ color: WHITE, fontSize: '10px', fontFamily: 'monospace', whiteSpace: 'pre-wrap' }}>
+ {strValue}
+ </div>
+ );
+ }
+
+ return (
+ <div style={{ marginLeft: depth > 0 ? '12px' : '0' }}>
+ {Object.entries(obj).map(([key, value]) => (
+ <div key={key} style={{ marginBottom: '8px' }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px'
+ }}>
+ {key.replace(/_/g, ' ')}:
+ </div>
+ {typeof value === 'object' && value !== null ? (
+ Array.isArray(value) ? (
+ <div style={{
+ color: '#10b981',
+ fontSize: '9px',
+ marginLeft: '8px',
+ fontFamily: 'monospace'
+ }}>
+ {value.map((item, i) => (
+ <div key={i} style={{ marginBottom: '2px' }}>• {item}</div>
+ ))}
+ </div>
+ ) : (
+ renderData(value, depth + 1)
+ )
+ ) : (
+ typeof value === 'string' && (value.includes('##') || value.includes('|') || value.length > 200) ? (
+ <div style={{
+ backgroundColor: '#0f0f0f',
+ border: `1px solid ${BORDER}`,
+ borderRadius: '4px',
+ padding: '8px',
+ marginLeft: '8px',
+ marginTop: '4px'
+ }}>
+ {renderMarkdown(value)}
+ </div>
+ ) : (
+ <div style={{
+ color: WHITE,
+ fontSize: '10px',
+ fontFamily: 'monospace',
+ marginLeft: '8px',
+ whiteSpace: 'pre-wrap',
+ wordBreak: 'break-word'
+ }}>
+ {formatValue(value)}
+ </div>
+ )
+ )}
+ </div>
+ ))}
+ </div>
+ );
+ };
+
+ return (
+ <div style={{
+ backgroundColor: PANEL_BG,
+ border: `2px solid ${selected ? ORANGE : data.color}`,
+ borderRadius: '8px',
+ padding: '12px',
+ width: `${width}px`,
+ fontFamily: 'Consolas, monospace',
+ boxShadow: selected ? `0 0 16px ${ORANGE}60` : `0 2px 8px rgba(0,0,0,0.3)`,
+ position: 'relative'
+ }}>
+ {/* Input Handle */}
+ <Handle
+ type="target"
+ position={Position.Left}
+ style={{
+ background: data.color,
+ width: '12px',
+ height: '12px',
+ border: `2px solid ${DARK_BG}`,
+ left: '-6px'
+ }}
+ />
+
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: '10px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${BORDER}`
+ }}>
+ <div style={{
+ color: WHITE,
+ fontSize: '12px',
+ fontWeight: 'bold'
+ }}>
+ 📊 {data.label}
+ </div>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ <button
+ onClick={() => setExpanded(!expanded)}
+ style={{
+ backgroundColor: 'transparent',
+ border: `1px solid ${BORDER}`,
+ color: GRAY,
+ padding: '4px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center'
+ }}
+ title={expanded ? 'Collapse' : 'Expand'}
+ >
+ {expanded ? <EyeOff size={12} /> : <Eye size={12} />}
+ </button>
+ <button
+ onClick={handleCopy}
+ disabled={!data.inputData}
+ style={{
+ backgroundColor: 'transparent',
+ border: `1px solid ${BORDER}`,
+ color: copied ? '#10b981' : GRAY,
+ padding: '4px',
+ cursor: data.inputData ? 'pointer' : 'not-allowed',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ opacity: data.inputData ? 1 : 0.5
+ }}
+ title="Copy to clipboard"
+ >
+ {copied ? <Check size={12} /> : <Copy size={12} />}
+ </button>
+ </div>
+ </div>
+
+ {/* Results Display */}
+ {expanded && (
+ <div
+ onWheel={(e) => e.stopPropagation()}
+ onMouseDown={(e) => e.stopPropagation()}
+ style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${BORDER}`,
+ borderRadius: '4px',
+ padding: '10px',
+ maxHeight: `${height}px`,
+ overflow: 'auto'
+ }}>
+ {data.inputData ? (
+ renderData(data.inputData)
+ ) : (
+ <div style={{
+ color: GRAY,
+ fontSize: '10px',
+ fontStyle: 'italic',
+ textAlign: 'center',
+ padding: '20px'
+ }}>
+ No data received yet.
+ <br />
+ Connect this node to an output to see results.
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Resize Handle */}
+ <div
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const startWidth = width;
+ const startHeight = height;
+
+ const handleMouseMove = (moveEvent: MouseEvent) => {
+ moveEvent.preventDefault();
+ const deltaX = moveEvent.clientX - startX;
+ const deltaY = moveEvent.clientY - startY;
+ setWidth(Math.max(300, startWidth + deltaX));
+ setHeight(Math.max(200, startHeight + deltaY));
+ };
+
+ const handleMouseUp = () => {
+ document.removeEventListener('mousemove', handleMouseMove);
+ document.removeEventListener('mouseup', handleMouseUp);
+ };
+
+ document.addEventListener('mousemove', handleMouseMove);
+ document.addEventListener('mouseup', handleMouseUp);
+ }}
+ style={{
+ position: 'absolute',
+ bottom: '4px',
+ right: '4px',
+ width: '24px',
+ height: '24px',
+ cursor: 'nwse-resize',
+ backgroundColor: DARK_BG,
+ border: `2px solid ${BORDER}`,
+ borderBottomRightRadius: '6px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: '16px',
+ color: GRAY,
+ transition: 'all 0.2s',
+ zIndex: 10
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = ORANGE;
+ e.currentTarget.style.color = 'white';
+ e.currentTarget.style.borderColor = ORANGE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = DARK_BG;
+ e.currentTarget.style.color = GRAY;
+ e.currentTarget.style.borderColor = BORDER;
+ }}
+ title="Drag to resize"
+ >
+ ⇲
+ </div>
+ </div>
+ );
+};
+
+export default ResultsDisplayNode;
diff --git a/fincept-terminal-desktop/src/hooks/useDataSource.ts b/fincept-terminal-desktop/src/hooks/useDataSource.ts
new file mode 100644
index 000000000..52e4d70f1
--- /dev/null
+++ b/fincept-terminal-desktop/src/hooks/useDataSource.ts
@@ -0,0 +1,265 @@
+// Universal Data Source Hook
+// Use this hook to access any data source (WebSocket or REST API) by alias
+
+import { useState, useEffect, useRef } from 'react';
+import { getDataSourceByAlias, getWebSocketTopic, parseDataSourceConfig, WebSocketSourceConfig, RestAPISourceConfig } from '../services/dataSourceRegistry';
+import { DataSource } from '../services/sqliteService';
+import { useWebSocket } from './useWebSocket';
+import { mappingDatabase } from '../components/tabs/data-mapping/services/MappingDatabase';
+import { mappingEngine } from '../components/tabs/data-mapping/engine/MappingEngine';
+
+export interface DataSourceHookResult {
+ data: any;
+ error: string | null;
+ loading: boolean;
+ connected: boolean;
+ source: DataSource | null;
+ refresh: () => Promise<void>;
+}
+
+/**
+ * Universal hook to access any data source by alias
+ * Works with both WebSocket and REST API sources
+ *
+ * @example
+ * ```tsx
+ * // WebSocket source
+ * const { data, connected } = useDataSource('btc_live');
+ *
+ * // REST API source
+ * const { data, loading, refresh } = useDataSource('sp500_data');
+ * ```
+ */
+export function useDataSource(alias: string, parameters?: Record<string, any>): DataSourceHookResult {
+ const [source, setSource] = useState<DataSource | null>(null);
+ const [data, setData] = useState<any>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [loading, setLoading] = useState<boolean>(true);
+ const [connected, setConnected] = useState<boolean>(false);
+
+ const wsTopicRef = useRef<string | null>(null);
+ const refreshIntervalRef = useRef<NodeJS.Timeout | null>(null);
+
+ // WebSocket hook (conditionally used)
+ const wsResult = useWebSocket(
+ source?.type === 'websocket' && source?.enabled ? (wsTopicRef.current || '') : null,
+ null,
+ {
+ autoSubscribe: source?.type === 'websocket' && source?.enabled === true
+ }
+ );
+
+ // Load data source on mount or alias change
+ useEffect(() => {
+ loadDataSource();
+
+ return () => {
+ // Cleanup
+ if (refreshIntervalRef.current) {
+ clearInterval(refreshIntervalRef.current);
+ }
+ };
+ }, [alias]);
+
+ // Handle WebSocket data updates
+ useEffect(() => {
+ if (source?.type === 'websocket' && wsResult.message) {
+ setData(wsResult.message.data);
+ setConnected(wsResult.status === 'connected');
+ setError(null);
+ setLoading(false);
+ }
+ }, [wsResult.message, wsResult.status, source?.type]);
+
+ async function loadDataSource() {
+ try {
+ setLoading(true);
+ setError(null);
+
+ // Fetch data source from database
+ const dataSource = await getDataSourceByAlias(alias);
+
+ if (!dataSource) {
+ setError(`Data source '${alias}' not found`);
+ setLoading(false);
+ return;
+ }
+
+ if (!dataSource.enabled) {
+ setError(`Data source '${alias}' is disabled`);
+ setLoading(false);
+ return;
+ }
+
+ setSource(dataSource);
+
+ // Handle based on type
+ if (dataSource.type === 'websocket') {
+ await handleWebSocketSource(dataSource);
+ } else if (dataSource.type === 'rest_api') {
+ await handleRestAPISource(dataSource);
+ }
+ } catch (err) {
+ const errorMsg = err instanceof Error ? err.message : String(err);
+ setError(errorMsg);
+ setLoading(false);
+ }
+ }
+
+ async function handleWebSocketSource(dataSource: DataSource) {
+ try {
+ const topic = getWebSocketTopic(dataSource);
+
+ if (!topic) {
+ throw new Error('Invalid WebSocket configuration');
+ }
+
+ // Ensure provider config is set in WebSocket Manager
+ const config = parseDataSourceConfig(dataSource) as WebSocketSourceConfig;
+ if (config) {
+ const { getWebSocketManager } = await import('../services/websocket');
+ const wsManager = getWebSocketManager();
+
+ const existingConfig = wsManager.getProviderConfig(config.provider);
+ if (!existingConfig) {
+ wsManager.setProviderConfig(config.provider, {
+ provider_name: config.provider,
+ enabled: true,
+ api_key: config.params?.api_key,
+ api_secret: config.params?.api_secret,
+ endpoint: config.params?.endpoint
+ });
+ console.log(`[useDataSource] Provider config set for: ${config.provider}`);
+ }
+ }
+
+ wsTopicRef.current = topic;
+ setLoading(false);
+ // Data will come through wsResult
+ } catch (err) {
+ const errorMsg = err instanceof Error ? err.message : String(err);
+ setError(errorMsg);
+ setLoading(false);
+ }
+ }
+
+ async function handleRestAPISource(dataSource: DataSource) {
+ try {
+ const config = parseDataSourceConfig(dataSource) as RestAPISourceConfig;
+
+ if (!config || !config.mappingId) {
+ throw new Error('Invalid REST API configuration');
+ }
+
+ // Load mapping from database
+ const mapping = await mappingDatabase.getMapping(config.mappingId);
+
+ if (!mapping) {
+ throw new Error(`Mapping '${config.mappingId}' not found`);
+ }
+
+ // Execute mapping
+ const result = await mappingEngine.execute({
+ mapping,
+ parameters: parameters || config.parameters
+ });
+
+ if (result.success) {
+ setData(result.data);
+ setConnected(true);
+ setError(null);
+ } else {
+ throw new Error(result.errors?.join(', ') || 'Mapping execution failed');
+ }
+
+ setLoading(false);
+ } catch (err) {
+ const errorMsg = err instanceof Error ? err.message : String(err);
+ setError(errorMsg);
+ setLoading(false);
+ }
+ }
+
+ async function refresh() {
+ if (!source) return;
+
+ if (source.type === 'rest_api') {
+ await handleRestAPISource(source);
+ }
+ // WebSocket sources refresh automatically
+ }
+
+ return {
+ data,
+ error,
+ loading,
+ connected,
+ source,
+ refresh
+ };
+}
+
+/**
+ * Hook to get all available data sources
+ */
+export function useDataSources() {
+ const [sources, setSources] = useState<DataSource[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ loadSources();
+ }, []);
+
+ async function loadSources() {
+ try {
+ setLoading(true);
+ const { sqliteService } = await import('../services/sqliteService');
+ const allSources = await sqliteService.getAllDataSources();
+ setSources(allSources);
+ setError(null);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ return {
+ sources,
+ loading,
+ error,
+ reload: loadSources
+ };
+}
+
+/**
+ * Hook to get data sources by type
+ */
+export function useDataSourcesByType(type: 'websocket' | 'rest_api') {
+ const [sources, setSources] = useState<DataSource[]>([]);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ loadSourcesByType();
+ }, [type]);
+
+ async function loadSourcesByType() {
+ try {
+ setLoading(true);
+ const { sqliteService } = await import('../services/sqliteService');
+ const filtered = await sqliteService.getDataSourcesByType(type);
+ setSources(filtered);
+ } catch (err) {
+ console.error('Failed to load data sources:', err);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ return {
+ sources,
+ loading,
+ reload: loadSourcesByType
+ };
+}
diff --git a/fincept-terminal-desktop/src/hooks/useWebSocket.ts b/fincept-terminal-desktop/src/hooks/useWebSocket.ts
index 6d09fe339..3a73c971e 100644
--- a/fincept-terminal-desktop/src/hooks/useWebSocket.ts
+++ b/fincept-terminal-desktop/src/hooks/useWebSocket.ts
@@ -302,6 +302,28 @@ export function useWebSocket(
};
}, [topic, autoSubscribe, autoConnect]); // Intentionally limited dependencies
+ /**
+ * Monitor connection status and resubscribe if connection is restored
+ */
+ useEffect(() => {
+ if (!topic || !autoSubscribe) return;
+
+ const manager = getWebSocketManager();
+ const provider = topic.split('.')[0];
+
+ const checkInterval = setInterval(() => {
+ const providerStatus = manager.getStatus(provider);
+
+ // If connected but no active subscription, resubscribe
+ if (providerStatus === ConnectionStatus.CONNECTED && !subscriptionRef.current) {
+ console.log(`[useWebSocket] Auto-resubscribing to ${topic} after reconnection`);
+ subscribe(topic, params);
+ }
+ }, 2000);
+
+ return () => clearInterval(checkInterval);
+ }, [topic, autoSubscribe, params, subscribe]);
+
return {
message,
messages,
@@ -322,11 +344,15 @@ export function useWebSocket(
export function useWebSocketManager() {
const manager = getWebSocketManager();
const [stats, setStats] = useState(manager.getStats());
+ const [statuses, setStatuses] = useState(manager.getAllStatuses());
+ const [metrics, setMetrics] = useState(manager.getAllMetrics());
useEffect(() => {
- // Update stats periodically
+ // Update stats, statuses, and metrics periodically
const interval = setInterval(() => {
setStats(manager.getStats());
+ setStatuses(manager.getAllStatuses());
+ setMetrics(manager.getAllMetrics());
}, 1000);
return () => clearInterval(interval);
@@ -335,8 +361,8 @@ export function useWebSocketManager() {
return {
manager,
stats,
- statuses: manager.getAllStatuses(),
- metrics: manager.getAllMetrics()
+ statuses,
+ metrics
};
}
diff --git a/fincept-terminal-desktop/src/services/agentLLMService.ts b/fincept-terminal-desktop/src/services/agentLLMService.ts
new file mode 100644
index 000000000..c6b80aea1
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/agentLLMService.ts
@@ -0,0 +1,218 @@
+// Agent LLM Service
+// Facilitates LLM-powered communication between agents in node workflows
+
+import { llmApiService, ChatMessage } from './llmApi';
+import { sqliteService, LLMConfig } from './sqliteService';
+
+export interface AgentMediationConfig {
+ llmProvider?: string; // Specific provider to use (optional, uses active if not set)
+ mediationPrompt?: string; // Custom prompt for mediation
+}
+
+export interface AgentMediationResult {
+ success: boolean;
+ mediatedContext: string;
+ error?: string;
+ llmProvider?: string;
+ llmModel?: string;
+}
+
+class AgentLLMService {
+ /**
+ * Mediate between two agents using an LLM
+ * Takes output from one agent and reformats it as context for the next agent
+ */
+ async mediateAgentOutput(
+ previousAgentOutput: any,
+ config: AgentMediationConfig = {}
+ ): Promise<AgentMediationResult> {
+ try {
+ console.log('[AgentLLMService] Mediating agent output:', previousAgentOutput);
+
+ // Extract meaningful content from previous agent
+ const agentData = this.extractAgentData(previousAgentOutput);
+
+ if (!agentData) {
+ return {
+ success: false,
+ mediatedContext: '',
+ error: 'No valid agent output to mediate'
+ };
+ }
+
+ // Get LLM config (either specified provider or active one)
+ let llmConfig: LLMConfig | null = null;
+
+ if (config.llmProvider) {
+ // Get specific provider config
+ const configs = await sqliteService.getLLMConfigs();
+ llmConfig = configs.find(c => c.provider === config.llmProvider) || null;
+ } else {
+ // Use active provider
+ llmConfig = await sqliteService.getActiveLLMConfig();
+ }
+
+ if (!llmConfig) {
+ return {
+ success: false,
+ mediatedContext: '',
+ error: 'No LLM provider configured. Please configure LLM settings.'
+ };
+ }
+
+ // Build mediation prompt
+ const mediationPrompt = config.mediationPrompt || this.getDefaultMediationPrompt();
+
+ const userMessage = `${mediationPrompt}\n\nPrevious Agent Analysis:\n${JSON.stringify(agentData, null, 2)}`;
+
+ // Call LLM to mediate
+ const response = await llmApiService.chat(userMessage, [], undefined);
+
+ if (response.error) {
+ return {
+ success: false,
+ mediatedContext: '',
+ error: response.error
+ };
+ }
+
+ console.log('[AgentLLMService] Mediation successful:', response.content);
+
+ return {
+ success: true,
+ mediatedContext: response.content,
+ llmProvider: llmConfig.provider,
+ llmModel: llmConfig.model
+ };
+
+ } catch (error) {
+ console.error('[AgentLLMService] Mediation error:', error);
+ return {
+ success: false,
+ mediatedContext: '',
+ error: error instanceof Error ? error.message : 'Unknown mediation error'
+ };
+ }
+ }
+
+ /**
+ * Extract meaningful data from agent output
+ */
+ private extractAgentData(output: any): any {
+ if (!output) return null;
+
+ // Handle wrapped success response
+ if (output.success !== undefined && output.data !== undefined) {
+ return this.extractAgentData(output.data);
+ }
+
+ // Handle analysis object
+ if (output.analysis) {
+ return output.analysis;
+ }
+
+ // Handle direct agent output with ticker analyses
+ if (typeof output === 'object') {
+ // Check if it's a map of ticker -> analysis
+ const firstKey = Object.keys(output)[0];
+ if (firstKey && output[firstKey]?.signal && output[firstKey]?.reasoning) {
+ return output;
+ }
+ }
+
+ return output;
+ }
+
+ /**
+ * Get default mediation prompt
+ */
+ private getDefaultMediationPrompt(): string {
+ return `You are mediating between financial analysis agents.
+
+Your task is to:
+1. Summarize the key findings from the previous agent's analysis
+2. Extract the most important signals, metrics, and reasoning
+3. Format this information as clear, actionable context for the next agent to consider
+4. Maintain objectivity - don't add your own investment opinions, just synthesize the data
+
+Be concise but comprehensive. Focus on facts, signals, and metrics that would be valuable for subsequent analysis.`;
+ }
+
+ /**
+ * Facilitate a multi-agent discussion
+ * Takes multiple agent outputs and synthesizes them into a coherent summary
+ */
+ async synthesizeMultipleAgents(
+ agentOutputs: Array<{ agentName: string; output: any }>,
+ synthesisPrompt?: string
+ ): Promise<AgentMediationResult> {
+ try {
+ console.log('[AgentLLMService] Synthesizing multiple agent outputs:', agentOutputs.length);
+
+ if (agentOutputs.length === 0) {
+ return {
+ success: false,
+ mediatedContext: '',
+ error: 'No agent outputs to synthesize'
+ };
+ }
+
+ // Extract data from all agents
+ const synthesisData = agentOutputs.map(({ agentName, output }) => ({
+ agent: agentName,
+ analysis: this.extractAgentData(output)
+ }));
+
+ // Get active LLM config
+ const llmConfig = await sqliteService.getActiveLLMConfig();
+ if (!llmConfig) {
+ return {
+ success: false,
+ mediatedContext: '',
+ error: 'No LLM provider configured'
+ };
+ }
+
+ // Build synthesis prompt
+ const defaultPrompt = `You are synthesizing insights from multiple financial analysis agents.
+
+Your task is to:
+1. Compare and contrast the findings from all agents
+2. Identify areas of consensus and disagreement
+3. Highlight the most significant insights from each perspective
+4. Provide a balanced, comprehensive summary that incorporates all viewpoints
+
+Be objective and data-driven. Present a holistic view that respects each agent's methodology.`;
+
+ const userMessage = `${synthesisPrompt || defaultPrompt}\n\nAgent Analyses:\n${JSON.stringify(synthesisData, null, 2)}`;
+
+ // Call LLM to synthesize
+ const response = await llmApiService.chat(userMessage, [], undefined);
+
+ if (response.error) {
+ return {
+ success: false,
+ mediatedContext: '',
+ error: response.error
+ };
+ }
+
+ return {
+ success: true,
+ mediatedContext: response.content,
+ llmProvider: llmConfig.provider,
+ llmModel: llmConfig.model
+ };
+
+ } catch (error) {
+ console.error('[AgentLLMService] Synthesis error:', error);
+ return {
+ success: false,
+ mediatedContext: '',
+ error: error instanceof Error ? error.message : 'Unknown synthesis error'
+ };
+ }
+ }
+}
+
+export const agentLLMService = new AgentLLMService();
diff --git a/fincept-terminal-desktop/src/services/dataSourceRegistry.ts b/fincept-terminal-desktop/src/services/dataSourceRegistry.ts
new file mode 100644
index 000000000..968b10978
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/dataSourceRegistry.ts
@@ -0,0 +1,242 @@
+// Data Source Registry Service
+// Central service for managing unified data sources (WebSocket + REST API)
+
+import { sqliteService, DataSource } from './sqliteService';
+import { getWebSocketManager } from './websocket';
+import { mappingEngine } from '../components/tabs/data-mapping/engine/MappingEngine';
+import { DataMappingConfig } from '../components/tabs/data-mapping/types';
+
+export interface WebSocketSourceConfig {
+ provider: string;
+ channel: string;
+ symbol?: string;
+ params?: Record<string, any>;
+}
+
+export interface RestAPISourceConfig {
+ mappingId: string;
+ parameters?: Record<string, any>;
+}
+
+/**
+ * Create a WebSocket data source
+ */
+export async function createWebSocketDataSource(input: {
+ alias: string;
+ displayName: string;
+ description?: string;
+ provider: string;
+ channel: string;
+ symbol?: string;
+ params?: Record<string, any>;
+ category?: string;
+ tags?: string[];
+ enabled?: boolean;
+}): Promise<{ success: boolean; message: string; id?: string }> {
+ const id = crypto.randomUUID();
+
+ const config: WebSocketSourceConfig = {
+ provider: input.provider,
+ channel: input.channel,
+ symbol: input.symbol,
+ params: input.params
+ };
+
+ const dataSource: Omit<DataSource, 'created_at' | 'updated_at'> = {
+ id,
+ alias: input.alias,
+ display_name: input.displayName,
+ description: input.description,
+ type: 'websocket',
+ provider: input.provider,
+ category: input.category || 'websocket',
+ config: JSON.stringify(config),
+ enabled: input.enabled !== false,
+ tags: input.tags ? JSON.stringify(input.tags) : undefined
+ };
+
+ const result = await sqliteService.saveDataSource(dataSource);
+
+ if (result.success && dataSource.enabled) {
+ // Auto-initialize in WebSocket Manager
+ const wsManager = getWebSocketManager();
+ const topic = `${config.provider}.${config.channel}${config.symbol ? '.' + config.symbol : ''}`;
+
+ try {
+ // Set provider config if not already set
+ const existingConfig = wsManager.getProviderConfig(config.provider);
+ if (!existingConfig) {
+ wsManager.setProviderConfig(config.provider, {
+ provider_name: config.provider,
+ enabled: true,
+ api_key: input.params?.api_key,
+ api_secret: input.params?.api_secret,
+ endpoint: input.params?.endpoint
+ });
+ console.log(`[DataSourceRegistry] Provider config set for: ${config.provider}`);
+ }
+
+ // Note: Actual subscription happens when component uses useDataSource
+ console.log(`[DataSourceRegistry] WebSocket source created: ${input.alias} -> ${topic}`);
+ } catch (error) {
+ console.error('[DataSourceRegistry] Failed to initialize WS source:', error);
+ }
+ }
+
+ return result;
+}
+
+/**
+ * Create a REST API data source from a data mapping
+ */
+export async function createRestAPIDataSource(input: {
+ alias: string;
+ displayName: string;
+ description?: string;
+ mappingId: string;
+ provider?: string;
+ category?: string;
+ tags?: string[];
+ enabled?: boolean;
+}): Promise<{ success: boolean; message: string; id?: string }> {
+ const id = crypto.randomUUID();
+
+ const config: RestAPISourceConfig = {
+ mappingId: input.mappingId
+ };
+
+ const dataSource: Omit<DataSource, 'created_at' | 'updated_at'> = {
+ id,
+ alias: input.alias,
+ display_name: input.displayName,
+ description: input.description,
+ type: 'rest_api',
+ provider: input.provider || 'custom',
+ category: input.category || 'rest_api',
+ config: JSON.stringify(config),
+ enabled: input.enabled !== false,
+ tags: input.tags ? JSON.stringify(input.tags) : undefined
+ };
+
+ return await sqliteService.saveDataSource(dataSource);
+}
+
+/**
+ * Get all data sources
+ */
+export async function getAllDataSources(): Promise<DataSource[]> {
+ return await sqliteService.getAllDataSources();
+}
+
+/**
+ * Get active/enabled data sources only
+ */
+export async function getActiveDataSources(): Promise<DataSource[]> {
+ return await sqliteService.getEnabledDataSources();
+}
+
+/**
+ * Get data source by alias
+ */
+export async function getDataSourceByAlias(alias: string): Promise<DataSource | null> {
+ return await sqliteService.getDataSourceByAlias(alias);
+}
+
+/**
+ * Get data sources by type
+ */
+export async function getDataSourcesByType(type: 'websocket' | 'rest_api'): Promise<DataSource[]> {
+ return await sqliteService.getDataSourcesByType(type);
+}
+
+/**
+ * Get data sources by provider
+ */
+export async function getDataSourcesByProvider(provider: string): Promise<DataSource[]> {
+ return await sqliteService.getDataSourcesByProvider(provider);
+}
+
+/**
+ * Toggle data source
+ */
+export async function toggleDataSource(id: string): Promise<{ success: boolean; message: string; enabled: boolean }> {
+ return await sqliteService.toggleDataSourceEnabled(id);
+}
+
+/**
+ * Delete data source
+ */
+export async function deleteDataSource(id: string): Promise<{ success: boolean; message: string }> {
+ return await sqliteService.deleteDataSource(id);
+}
+
+/**
+ * Update data source
+ */
+export async function updateDataSource(source: DataSource): Promise<{ success: boolean; message: string }> {
+ const result = await sqliteService.saveDataSource(source);
+ return { success: result.success, message: result.message };
+}
+
+/**
+ * Search data sources
+ */
+export async function searchDataSources(query: string): Promise<DataSource[]> {
+ return await sqliteService.searchDataSources(query);
+}
+
+/**
+ * Get WebSocket topic from data source
+ */
+export function getWebSocketTopic(source: DataSource): string | null {
+ if (source.type !== 'websocket') return null;
+
+ try {
+ const config: WebSocketSourceConfig = JSON.parse(source.config);
+ return `${config.provider}.${config.channel}${config.symbol ? '.' + config.symbol : ''}`;
+ } catch (error) {
+ console.error('[DataSourceRegistry] Failed to parse WS config:', error);
+ return null;
+ }
+}
+
+/**
+ * Get data source configuration (parsed)
+ */
+export function parseDataSourceConfig(source: DataSource): WebSocketSourceConfig | RestAPISourceConfig | null {
+ try {
+ return JSON.parse(source.config);
+ } catch (error) {
+ console.error('[DataSourceRegistry] Failed to parse config:', error);
+ return null;
+ }
+}
+
+/**
+ * Get available WebSocket providers from adapters
+ */
+export function getAvailableWebSocketProviders(): string[] {
+ // This would come from the adapter registry
+ return ['kraken', 'fyers', 'binance']; // Will be dynamic later
+}
+
+/**
+ * Get data source statistics
+ */
+export async function getDataSourceStats(): Promise<{
+ total: number;
+ websocket: number;
+ restApi: number;
+ enabled: number;
+ disabled: number;
+}> {
+ const all = await getAllDataSources();
+
+ return {
+ total: all.length,
+ websocket: all.filter(s => s.type === 'websocket').length,
+ restApi: all.filter(s => s.type === 'rest_api').length,
+ enabled: all.filter(s => s.enabled).length,
+ disabled: all.filter(s => !s.enabled).length
+ };
+}
diff --git a/fincept-terminal-desktop/src/services/llmApi.ts b/fincept-terminal-desktop/src/services/llmApi.ts
index 94927c5f9..4f8637db5 100644
--- a/fincept-terminal-desktop/src/services/llmApi.ts
+++ b/fincept-terminal-desktop/src/services/llmApi.ts
@@ -355,8 +355,10 @@ class LLMApiService {
});
if (!response.ok) {
- const error = await response.json();
- throw new Error(error.error?.message || `OpenRouter API error: ${response.status}`);
+ const errorData = await response.json();
+ console.error('OpenRouter full error response:', JSON.stringify(errorData, null, 2));
+ const errorMessage = errorData.error?.message || errorData.message || JSON.stringify(errorData);
+ throw new Error(`OpenRouter error (${response.status}): ${errorMessage}`);
}
if (onStream) {
diff --git a/fincept-terminal-desktop/src/services/nodeExecutionManager.ts b/fincept-terminal-desktop/src/services/nodeExecutionManager.ts
new file mode 100644
index 000000000..7292503af
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeExecutionManager.ts
@@ -0,0 +1,395 @@
+// Node Execution Manager - Handles workflow execution with topological sorting
+import { Node, Edge } from 'reactflow';
+import { pythonAgentService } from './pythonAgentService';
+import { mcpToolService } from './mcpToolService';
+import { agentLLMService } from './agentLLMService';
+
+export type NodeStatus = 'idle' | 'running' | 'completed' | 'error';
+
+export interface ExecutionResult {
+ nodeId: string;
+ success: boolean;
+ data?: any;
+ error?: string;
+ execution_time_ms?: number;
+}
+
+class NodeExecutionManager {
+ /**
+ * Topological sort of nodes based on edges
+ */
+ topologicalSort(nodes: Node[], edges: Edge[]): Node[] {
+ const adjList = new Map<string, string[]>();
+ const inDegree = new Map<string, number>();
+
+ // Initialize
+ nodes.forEach(node => {
+ adjList.set(node.id, []);
+ inDegree.set(node.id, 0);
+ });
+
+ // Build adjacency list and in-degree
+ edges.forEach(edge => {
+ adjList.get(edge.source)?.push(edge.target);
+ inDegree.set(edge.target, (inDegree.get(edge.target) || 0) + 1);
+ });
+
+ // Find nodes with no dependencies
+ const queue: Node[] = [];
+ nodes.forEach(node => {
+ if (inDegree.get(node.id) === 0) {
+ queue.push(node);
+ }
+ });
+
+ const sorted: Node[] = [];
+
+ while (queue.length > 0) {
+ const node = queue.shift()!;
+ sorted.push(node);
+
+ const neighbors = adjList.get(node.id) || [];
+ neighbors.forEach(neighborId => {
+ const newDegree = (inDegree.get(neighborId) || 0) - 1;
+ inDegree.set(neighborId, newDegree);
+
+ if (newDegree === 0) {
+ const neighborNode = nodes.find(n => n.id === neighborId);
+ if (neighborNode) {
+ queue.push(neighborNode);
+ }
+ }
+ });
+ }
+
+ // Check for cycles
+ if (sorted.length !== nodes.length) {
+ throw new Error('Workflow contains cycles - cannot execute');
+ }
+
+ return sorted;
+ }
+
+ /**
+ * Get inputs for a node from connected edges
+ */
+ getNodeInputs(
+ node: Node,
+ edges: Edge[],
+ results: Map<string, any>
+ ): Record<string, any> {
+ const inputs: Record<string, any> = {};
+
+ // Find incoming edges
+ const incomingEdges = edges.filter(e => e.target === node.id);
+
+ // Support multiple inputs for agent-mediator nodes
+ if (node.type === 'agent-mediator' && incomingEdges.length > 1) {
+ // Collect all agent outputs for synthesis
+ const agentOutputs: Array<{ agentName: string; output: any }> = [];
+
+ for (const edge of incomingEdges) {
+ const sourceResult = results.get(edge.source);
+ const sourceNode = results.get(`${edge.source}_node`); // Store node info separately if needed
+
+ if (sourceResult !== undefined) {
+ agentOutputs.push({
+ agentName: sourceResult.agent || `Agent ${edge.source}`,
+ output: sourceResult
+ });
+ }
+ }
+
+ return { multipleAgents: agentOutputs };
+ }
+
+ // Single input handling (default)
+ for (const edge of incomingEdges) {
+ const sourceResult = results.get(edge.source);
+
+ if (sourceResult !== undefined) {
+ // If edge has targetHandle (specific parameter), map it
+ if (edge.targetHandle) {
+ inputs[edge.targetHandle] = sourceResult;
+ } else {
+ // Otherwise merge entire result
+ if (typeof sourceResult === 'object' && !Array.isArray(sourceResult)) {
+ Object.assign(inputs, sourceResult);
+ } else {
+ inputs.data = sourceResult;
+ }
+ }
+ }
+ }
+
+ return inputs;
+ }
+
+ /**
+ * Execute a single node
+ */
+ async executeNode(
+ node: Node,
+ inputs: Record<string, any>
+ ): Promise<ExecutionResult> {
+ try {
+ switch (node.type) {
+ case 'python-agent':
+ return await this.executePythonAgent(node, inputs);
+
+ case 'mcp-tool':
+ return await this.executeMCPTool(node, inputs);
+
+ case 'agent-mediator':
+ return await this.executeAgentMediator(node, inputs);
+
+ case 'data-source':
+ return await this.executeDataSource(node);
+
+ case 'transformation':
+ return await this.executeTransformation(node, inputs);
+
+ case 'results-display':
+ return await this.executeResultsDisplay(node, inputs);
+
+ case 'custom':
+ // Custom nodes (default examples) - skip or pass through
+ return {
+ nodeId: node.id,
+ success: true,
+ data: inputs
+ };
+
+ default:
+ console.warn(`Unknown node type: ${node.type}, skipping execution`);
+ return {
+ nodeId: node.id,
+ success: true,
+ data: inputs
+ };
+ }
+ } catch (error: any) {
+ return {
+ nodeId: node.id,
+ success: false,
+ error: error.message || 'Unknown error'
+ };
+ }
+ }
+
+ /**
+ * Execute Python agent node
+ */
+ private async executePythonAgent(
+ node: Node,
+ inputs: Record<string, any>
+ ): Promise<ExecutionResult> {
+ const { agentType, parameters } = node.data;
+
+ const result = await pythonAgentService.executeAgent(
+ agentType,
+ parameters,
+ inputs
+ );
+
+ return {
+ nodeId: node.id,
+ success: result.success,
+ data: result.data,
+ error: result.error,
+ execution_time_ms: result.execution_time_ms
+ };
+ }
+
+ /**
+ * Execute MCP tool node
+ */
+ private async executeMCPTool(
+ node: Node,
+ inputs: Record<string, any>
+ ): Promise<ExecutionResult> {
+ const { serverId, toolName, parameters } = node.data;
+
+ // Merge manual parameters with inputs from connected nodes
+ const mergedParams = {
+ ...parameters,
+ ...inputs
+ };
+
+ const result = await mcpToolService.executeToolDirect(
+ serverId,
+ toolName,
+ mergedParams
+ );
+
+ return {
+ nodeId: node.id,
+ success: result.success,
+ data: result.data,
+ error: result.error,
+ execution_time_ms: result.executionTime
+ };
+ }
+
+ /**
+ * Execute data source node (placeholder)
+ */
+ private async executeDataSource(node: Node): Promise<ExecutionResult> {
+ // TODO: Integrate with dataSourceRegistry
+ return {
+ nodeId: node.id,
+ success: true,
+ data: { message: 'Data source execution not yet implemented' }
+ };
+ }
+
+ /**
+ * Execute transformation node (placeholder)
+ */
+ private async executeTransformation(
+ node: Node,
+ inputs: Record<string, any>
+ ): Promise<ExecutionResult> {
+ // TODO: Implement transformation logic
+ return {
+ nodeId: node.id,
+ success: true,
+ data: inputs // Pass through for now
+ };
+ }
+
+ /**
+ * Execute agent mediator node
+ */
+ private async executeAgentMediator(
+ node: Node,
+ inputs: Record<string, any>
+ ): Promise<ExecutionResult> {
+ const { selectedProvider, customPrompt } = node.data;
+
+ console.log('[NodeExecutionManager] Agent mediator executing with inputs:', inputs);
+
+ // Check if we have multiple agents to synthesize
+ if (inputs.multipleAgents && Array.isArray(inputs.multipleAgents)) {
+ console.log('[NodeExecutionManager] Synthesizing multiple agents:', inputs.multipleAgents.length);
+
+ const result = await agentLLMService.synthesizeMultipleAgents(
+ inputs.multipleAgents,
+ customPrompt
+ );
+
+ if (result.success) {
+ return {
+ nodeId: node.id,
+ success: true,
+ data: {
+ mediated_analysis: result.mediatedContext,
+ source_agents: inputs.multipleAgents.map((a: any) => a.agentName),
+ llm_provider: result.llmProvider,
+ llm_model: result.llmModel
+ }
+ };
+ } else {
+ return {
+ nodeId: node.id,
+ success: false,
+ error: result.error || 'Multi-agent synthesis failed'
+ };
+ }
+ }
+
+ // Single agent mediation
+ const result = await agentLLMService.mediateAgentOutput(inputs, {
+ llmProvider: selectedProvider, // Will use active if undefined
+ mediationPrompt: customPrompt // Will use default if undefined
+ });
+
+ if (result.success) {
+ return {
+ nodeId: node.id,
+ success: true,
+ data: {
+ mediated_analysis: result.mediatedContext,
+ source_agent: inputs.agent || 'unknown',
+ llm_provider: result.llmProvider,
+ llm_model: result.llmModel
+ }
+ };
+ } else {
+ return {
+ nodeId: node.id,
+ success: false,
+ error: result.error || 'Agent mediation failed'
+ };
+ }
+ }
+
+ /**
+ * Execute results display node
+ */
+ private async executeResultsDisplay(
+ node: Node,
+ inputs: Record<string, any>
+ ): Promise<ExecutionResult> {
+ // Results display just receives and displays data
+ console.log('[NodeExecutionManager] Results display node receiving data:', JSON.stringify(inputs, null, 2));
+
+ // Extract actual data if it's wrapped in a success object
+ let displayData = inputs;
+ if (inputs.success !== undefined && inputs.data !== undefined) {
+ displayData = inputs.data;
+ }
+
+ return {
+ nodeId: node.id,
+ success: true,
+ data: displayData // Pass the unwrapped data
+ };
+ }
+
+ /**
+ * Execute entire workflow
+ */
+ async executeWorkflow(
+ nodes: Node[],
+ edges: Edge[],
+ onNodeStatusChange: (nodeId: string, status: NodeStatus, result?: any) => void
+ ): Promise<Map<string, any>> {
+ // Topological sort
+ const sortedNodes = this.topologicalSort(nodes, edges);
+ const results = new Map<string, any>();
+
+ console.log('[NodeExecutionManager] Executing workflow with nodes:', sortedNodes.map(n => n.id));
+
+ for (const node of sortedNodes) {
+ console.log(`[NodeExecutionManager] Executing node: ${node.id} (${node.type})`);
+
+ // Update status to running
+ onNodeStatusChange(node.id, 'running');
+
+ // Get inputs from previous nodes
+ const inputs = this.getNodeInputs(node, edges, results);
+ console.log(`[NodeExecutionManager] Node ${node.id} inputs:`, inputs);
+
+ // Execute node
+ const result = await this.executeNode(node, inputs);
+ console.log(`[NodeExecutionManager] Node ${node.id} result:`, result);
+
+ // Store result
+ results.set(node.id, result.data);
+
+ // Update status
+ if (result.success) {
+ onNodeStatusChange(node.id, 'completed', result.data);
+ } else {
+ onNodeStatusChange(node.id, 'error', result.error);
+ throw new Error(`Node ${node.id} failed: ${result.error}`);
+ }
+ }
+
+ console.log('[NodeExecutionManager] Workflow completed successfully');
+ return results;
+ }
+}
+
+export const nodeExecutionManager = new NodeExecutionManager();
diff --git a/fincept-terminal-desktop/src/services/pythonAgentService.ts b/fincept-terminal-desktop/src/services/pythonAgentService.ts
new file mode 100644
index 000000000..dc730dbb5
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/pythonAgentService.ts
@@ -0,0 +1,111 @@
+// Python Agent Service - Interface to execute Python agents via Tauri
+import { invoke } from '@tauri-apps/api/core';
+
+export interface AgentParameter {
+ name: string;
+ label: string;
+ type: string;
+ required: boolean;
+ default_value?: any;
+ description?: string;
+}
+
+export interface AgentMetadata {
+ id: string;
+ name: string;
+ type: string;
+ category: string;
+ description: string;
+ script_path: string;
+ parameters: AgentParameter[];
+ required_inputs: string[];
+ outputs: string[];
+ icon: string;
+ color: string;
+}
+
+export interface AgentExecutionResult {
+ success: boolean;
+ data?: any;
+ error?: string;
+ execution_time_ms: number;
+ agent_type: string;
+}
+
+class PythonAgentService {
+ /**
+ * Get list of all available Python agents
+ */
+ async getAvailableAgents(): Promise<AgentMetadata[]> {
+ try {
+ const agents = await invoke<AgentMetadata[]>('list_available_agents');
+ console.log('[PythonAgentService] Loaded agents:', agents.length);
+ return agents;
+ } catch (error) {
+ console.error('[PythonAgentService] Failed to load agents:', error);
+ return [];
+ }
+ }
+
+ /**
+ * Execute a Python agent
+ */
+ async executeAgent(
+ agentType: string,
+ parameters: Record<string, any>,
+ inputs: Record<string, any>
+ ): Promise<AgentExecutionResult> {
+ try {
+ console.log(`[PythonAgentService] Executing agent: ${agentType}`, {parameters, inputs});
+
+ const result = await invoke<AgentExecutionResult>('execute_python_agent', {
+ agentType,
+ parameters,
+ inputs
+ });
+
+ console.log(`[PythonAgentService] Agent ${agentType} completed:`, result);
+ return result;
+ } catch (error: any) {
+ console.error(`[PythonAgentService] Agent ${agentType} failed:`, error);
+ return {
+ success: false,
+ error: error.message || 'Unknown error',
+ execution_time_ms: 0,
+ agent_type: agentType
+ };
+ }
+ }
+
+ /**
+ * Get metadata for a specific agent
+ */
+ async getAgentMetadata(agentType: string): Promise<AgentMetadata | null> {
+ try {
+ const metadata = await invoke<AgentMetadata>('get_agent_metadata', { agentType });
+ return metadata;
+ } catch (error) {
+ console.error(`[PythonAgentService] Failed to get metadata for ${agentType}:`, error);
+ return null;
+ }
+ }
+
+ /**
+ * Get agents by category
+ */
+ async getAgentsByCategory(category: string): Promise<AgentMetadata[]> {
+ const allAgents = await this.getAvailableAgents();
+ return allAgents.filter(agent => agent.category === category);
+ }
+
+ /**
+ * Get unique categories
+ */
+ async getCategories(): Promise<string[]> {
+ const allAgents = await this.getAvailableAgents();
+ const categories = new Set(allAgents.map(agent => agent.category));
+ return Array.from(categories);
+ }
+}
+
+export const pythonAgentService = new PythonAgentService();
diff --git a/fincept-terminal-desktop/src/services/sqliteService.ts b/fincept-terminal-desktop/src/services/sqliteService.ts
index 439a4e920..f4ff69084 100644
--- a/fincept-terminal-desktop/src/services/sqliteService.ts
+++ b/fincept-terminal-desktop/src/services/sqliteService.ts
@@ -64,6 +64,21 @@ export interface ChatMessage {
tokens_used?: number;
}
+export interface DataSource {
+ id: string;
+ alias: string;
+ display_name: string;
+ description?: string;
+ type: 'websocket' | 'rest_api';
+ provider: string;
+ category?: string;
+ config: string; // JSON string
+ enabled: boolean;
+ tags?: string; // JSON array string
+ created_at?: string;
+ updated_at?: string;
+}
+
class SQLiteService {
private db: Database | null = null;
private dbPath = 'sqlite:fincept_terminal.db';
@@ -360,6 +375,24 @@ class SQLiteService {
)
`);
+ // Unified Data Sources table (combines WebSocket and REST API sources)
+ await this.db.execute(`
+ CREATE TABLE IF NOT EXISTS data_sources (
+ id TEXT PRIMARY KEY,
+ alias TEXT NOT NULL UNIQUE,
+ display_name TEXT NOT NULL,
+ description TEXT,
+ type TEXT NOT NULL,
+ provider TEXT NOT NULL,
+ category TEXT,
+ config TEXT NOT NULL,
+ enabled INTEGER DEFAULT 1,
+ tags TEXT,
+ created_at TEXT DEFAULT (datetime('now')),
+ updated_at TEXT DEFAULT (datetime('now'))
+ )
+ `);
+
// Create indexes
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_credentials_service ON credentials(service_name)`);
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_settings_category ON settings(category)`);
@@ -378,6 +411,10 @@ class SQLiteService {
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_watchlist_stocks_watchlist ON watchlist_stocks(watchlist_id)`);
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_watchlist_stocks_symbol ON watchlist_stocks(symbol)`);
await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_ws_providers_enabled ON ws_provider_configs(enabled)`);
+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_data_sources_alias ON data_sources(alias)`);
+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_data_sources_type ON data_sources(type)`);
+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_data_sources_provider ON data_sources(provider)`);
+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_data_sources_enabled ON data_sources(enabled)`);
}
private async seedDefaultSettings(): Promise<void> {
@@ -1393,6 +1430,221 @@ class SQLiteService {
return { success: false, message: error.message };
}
}
+
+ // ==================== UNIFIED DATA SOURCES ====================
+
+ /**
+ * Save or update a unified data source
+ */
+ async saveDataSource(source: Omit<DataSource, 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string; id: string }> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ try {
+ // Check if alias exists
+ const existing = await this.db.select<Array<{ id: string }>>(
+ 'SELECT id FROM data_sources WHERE alias = $1',
+ [source.alias]
+ );
+
+ if (existing.length > 0 && existing[0].id !== source.id) {
+ return { success: false, message: 'Alias already exists', id: existing[0].id };
+ }
+
+ // Check if ID exists (update case)
+ const existingById = await this.db.select<Array<{ id: string }>>(
+ 'SELECT id FROM data_sources WHERE id = $1',
+ [source.id]
+ );
+
+ if (existingById.length > 0) {
+ // Update
+ await this.db.execute(
+ `UPDATE data_sources SET alias = $1, display_name = $2, description = $3,
+ type = $4, provider = $5, category = $6, config = $7, enabled = $8,
+ tags = $9, updated_at = datetime('now') WHERE id = $10`,
+ [source.alias, source.display_name, source.description || null,
+ source.type, source.provider, source.category || null,
+ source.config, source.enabled ? 1 : 0, source.tags || null, source.id]
+ );
+ return { success: true, message: 'Data source updated successfully', id: source.id };
+ } else {
+ // Insert
+ await this.db.execute(
+ `INSERT INTO data_sources (id, alias, display_name, description, type, provider, category, config, enabled, tags)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
+ [source.id, source.alias, source.display_name, source.description || null,
+ source.type, source.provider, source.category || null,
+ source.config, source.enabled ? 1 : 0, source.tags || null]
+ );
+ return { success: true, message: 'Data source saved successfully', id: source.id };
+ }
+ } catch (error: any) {
+ return { success: false, message: error.message, id: source.id };
+ }
+ }
+
+ /**
+ * Get all data sources
+ */
+ async getAllDataSources(): Promise<DataSource[]> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const sources = await this.db.select<Array<any>>(
+ 'SELECT * FROM data_sources ORDER BY display_name ASC'
+ );
+
+ return sources.map(s => ({
+ ...s,
+ enabled: s.enabled === 1
+ }));
+ }
+
+ /**
+ * Get data source by ID
+ */
+ async getDataSourceById(id: string): Promise<DataSource | null> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const sources = await this.db.select<Array<any>>(
+ 'SELECT * FROM data_sources WHERE id = $1',
+ [id]
+ );
+
+ if (sources.length === 0) return null;
+
+ return {
+ ...sources[0],
+ enabled: sources[0].enabled === 1
+ };
+ }
+
+ /**
+ * Get data source by alias
+ */
+ async getDataSourceByAlias(alias: string): Promise<DataSource | null> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const sources = await this.db.select<Array<any>>(
+ 'SELECT * FROM data_sources WHERE alias = $1',
+ [alias]
+ );
+
+ if (sources.length === 0) return null;
+
+ return {
+ ...sources[0],
+ enabled: sources[0].enabled === 1
+ };
+ }
+
+ /**
+ * Get data sources by type
+ */
+ async getDataSourcesByType(type: 'websocket' | 'rest_api'): Promise<DataSource[]> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const sources = await this.db.select<Array<any>>(
+ 'SELECT * FROM data_sources WHERE type = $1 ORDER BY display_name ASC',
+ [type]
+ );
+
+ return sources.map(s => ({
+ ...s,
+ enabled: s.enabled === 1
+ }));
+ }
+
+ /**
+ * Get data sources by provider
+ */
+ async getDataSourcesByProvider(provider: string): Promise<DataSource[]> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const sources = await this.db.select<Array<any>>(
+ 'SELECT * FROM data_sources WHERE provider = $1 ORDER BY display_name ASC',
+ [provider]
+ );
+
+ return sources.map(s => ({
+ ...s,
+ enabled: s.enabled === 1
+ }));
+ }
+
+ /**
+ * Get only enabled data sources
+ */
+ async getEnabledDataSources(): Promise<DataSource[]> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const sources = await this.db.select<Array<any>>(
+ 'SELECT * FROM data_sources WHERE enabled = 1 ORDER BY display_name ASC'
+ );
+
+ return sources.map(s => ({
+ ...s,
+ enabled: true
+ }));
+ }
+
+ /**
+ * Toggle data source enabled status
+ */
+ async toggleDataSourceEnabled(id: string): Promise<{ success: boolean; message: string; enabled: boolean }> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ try {
+ const source = await this.getDataSourceById(id);
+
+ if (!source) {
+ return { success: false, message: 'Data source not found', enabled: false };
+ }
+
+ const newEnabled = !source.enabled;
+
+ await this.db.execute(
+ `UPDATE data_sources SET enabled = $1, updated_at = datetime('now') WHERE id = $2`,
+ [newEnabled ? 1 : 0, id]
+ );
+
+ return { success: true, message: `Data source ${newEnabled ? 'enabled' : 'disabled'} successfully`, enabled: newEnabled };
+ } catch (error: any) {
+ return { success: false, message: error.message, enabled: false };
+ }
+ }
+
+ /**
+ * Delete data source
+ */
+ async deleteDataSource(id: string): Promise<{ success: boolean; message: string }> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ try {
+ await this.db.execute('DELETE FROM data_sources WHERE id = $1', [id]);
+ return { success: true, message: 'Data source deleted successfully' };
+ } catch (error: any) {
+ return { success: false, message: error.message };
+ }
+ }
+
+ /**
+ * Search data sources by name or description
+ */
+ async searchDataSources(query: string): Promise<DataSource[]> {
+ if (!this.db) throw new Error('Database not initialized');
+
+ const sources = await this.db.select<Array<any>>(
+ `SELECT * FROM data_sources
+ WHERE display_name LIKE $1 OR description LIKE $1 OR alias LIKE $1
+ ORDER BY display_name ASC`,
+ [`%${query}%`]
+ );
+
+ return sources.map(s => ({
+ ...s,
+ enabled: s.enabled === 1
+ }));
+ }
}
// Singleton instance
diff --git a/fincept-terminal-desktop/src/services/websocket/WebSocketManager.ts b/fincept-terminal-desktop/src/services/websocket/WebSocketManager.ts
index 542fe133c..54d41b62c 100644
--- a/fincept-terminal-desktop/src/services/websocket/WebSocketManager.ts
+++ b/fincept-terminal-desktop/src/services/websocket/WebSocketManager.ts
@@ -322,17 +322,54 @@ export class WebSocketManager {
}
/**
- * Reconnect a provider
+ * Reconnect a provider and restore subscriptions
*/
async reconnect(provider: string): Promise<void> {
+ // Get active subscriptions for this provider before reconnection
+ const providerSubs = this.getProviderSubscriptions(provider);
+
+ // Store subscription details
+ const subsToRestore = providerSubs.map(sub => ({
+ topic: sub.topic,
+ callback: sub.callback,
+ // Extract params from topic if needed
+ params: {} // TODO: Store params in Subscription if needed
+ }));
+
+ // Reconnect the adapter
await this.registry.reconnect(provider);
+
+ // Resubscribe to all topics
+ const adapter = this.registry.get(provider);
+ if (adapter && subsToRestore.length > 0) {
+ this.log(`Resubscribing to ${subsToRestore.length} topics for ${provider}`);
+
+ for (const subInfo of subsToRestore) {
+ try {
+ const parsed = parseTopic(subInfo.topic);
+ const adapterTopic = parsed.symbol ? `${parsed.channel}.${parsed.symbol}` : parsed.channel;
+ await adapter.subscribe(adapterTopic, subInfo.params);
+ this.log(`Resubscribed to: ${subInfo.topic}`);
+ } catch (error) {
+ console.error(`[WebSocketManager] Failed to resubscribe to ${subInfo.topic}:`, error);
+ }
+ }
+ }
}
/**
- * Reconnect all providers
+ * Reconnect all providers and restore subscriptions
*/
async reconnectAll(): Promise<void> {
- await this.registry.reconnectAll();
+ const providers = this.registry.getProviders();
+
+ for (const provider of providers) {
+ try {
+ await this.reconnect(provider);
+ } catch (error) {
+ console.error(`[WebSocketManager] Failed to reconnect ${provider}:`, error);
+ }
+ }
}
/**
diff --git a/fincept-terminal-desktop/test-agent-commands.html b/fincept-terminal-desktop/test-agent-commands.html
new file mode 100644
index 000000000..01d363723
--- /dev/null
+++ b/fincept-terminal-desktop/test-agent-commands.html
@@ -0,0 +1,110 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Test Agent Commands</title>
+ <script type="module">
+ // This will only work when running inside Tauri
+ import { invoke } from '@tauri-apps/api/core';
+
+ async function testListAgents() {
+ console.log('Testing list_available_agents...');
+ try {
+ const result = await invoke('list_available_agents');
+ console.log('✅ list_available_agents SUCCESS:', result);
+ document.getElementById('list-result').innerText = JSON.stringify(result, null, 2);
+ } catch (error) {
+ console.error('❌ list_available_agents FAILED:', error);
+ document.getElementById('list-result').innerText = 'ERROR: ' + error;
+ }
+ }
+
+ async function testExecuteAgent() {
+ console.log('Testing execute_python_agent...');
+ try {
+ const result = await invoke('execute_python_agent', {
+ agentType: 'warren_buffett',
+ parameters: {
+ tickers: ['AAPL'],
+ end_date: '2024-12-31'
+ },
+ inputs: {}
+ });
+ console.log('✅ execute_python_agent SUCCESS:', result);
+ document.getElementById('execute-result').innerText = JSON.stringify(result, null, 2);
+ } catch (error) {
+ console.error('❌ execute_python_agent FAILED:', error);
+ document.getElementById('execute-result').innerText = 'ERROR: ' + error;
+ }
+ }
+
+ async function testGetMetadata() {
+ console.log('Testing get_agent_metadata...');
+ try {
+ const result = await invoke('get_agent_metadata', {
+ agentType: 'warren_buffett'
+ });
+ console.log('✅ get_agent_metadata SUCCESS:', result);
+ document.getElementById('metadata-result').innerText = JSON.stringify(result, null, 2);
+ } catch (error) {
+ console.error('❌ get_agent_metadata FAILED:', error);
+ document.getElementById('metadata-result').innerText = 'ERROR: ' + error;
+ }
+ }
+
+ // Expose functions to window
+ window.testListAgents = testListAgents;
+ window.testExecuteAgent = testExecuteAgent;
+ window.testGetMetadata = testGetMetadata;
+ </script>
+ <style>
+ body {
+ font-family: 'Consolas', monospace;
+ background: #0a0a0a;
+ color: #d4d4d4;
+ padding: 20px;
+ }
+ button {
+ background: #ea580c;
+ color: white;
+ border: none;
+ padding: 10px 20px;
+ margin: 10px 5px;
+ cursor: pointer;
+ font-size: 14px;
+ font-weight: bold;
+ }
+ button:hover {
+ background: #dc2626;
+ }
+ pre {
+ background: #1a1a1a;
+ border: 1px solid #2d2d2d;
+ padding: 15px;
+ border-radius: 5px;
+ overflow: auto;
+ max-height: 400px;
+ }
+ h2 {
+ color: #ea580c;
+ }
+ </style>
+</head>
+<body>
+ <h1>🧪 Agent Commands Test</h1>
+
+ <div>
+ <button onclick="testListAgents()">1. Test List Agents</button>
+ <button onclick="testGetMetadata()">2. Test Get Metadata</button>
+ <button onclick="testExecuteAgent()">3. Test Execute Agent</button>
+ </div>
+
+ <h2>List Agents Result:</h2>
+ <pre id="list-result">Click "Test List Agents" button</pre>
+
+ <h2>Get Metadata Result:</h2>
+ <pre id="metadata-result">Click "Test Get Metadata" button</pre>
+
+ <h2>Execute Agent Result:</h2>
+ <pre id="execute-result">Click "Test Execute Agent" button</pre>
+</body>
+</html>