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.

clean up

tilakpatel22b2b0b50014be
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/base_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/base_agent.py
deleted file mode 100644
index c71677037..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/base_agent.py
+++ /dev/null
@@ -1,74 +0,0 @@
-"""
-Base Economic Agent Class
-Provides common functionality for all economic ideology agents
-"""
-
-from abc import ABC, abstractmethod
-from typing import Dict, List, Any, Optional
-from dataclasses import dataclass
-from datetime import datetime
-import json
-
-@dataclass
-class EconomicData:
- """Structure for economic data points"""
- gdp: float
- inflation: float
- unemployment: float
- interest_rate: float
- trade_balance: float
- government_spending: float
- tax_rate: float
- private_investment: float
- consumer_confidence: float
- timestamp: datetime
-
-@dataclass
-class PolicyRecommendation:
- """Structure for policy recommendations"""
- title: str
- description: str
- priority: str # high, medium, low
- expected_impact: str
- implementation_time: str
- risk_level: str
-
-class EconomicAgent(ABC):
- """Abstract base class for economic ideology agents"""
-
- def __init__(self, name: str, description: str):
- self.name = name
- self.description = description
- self.principles = []
- self.priorities = []
-
- @abstractmethod
- def analyze_economy(self, data: EconomicData) -> Dict[str, Any]:
- """Analyze economic data from the perspective of this ideology"""
- pass
-
- @abstractmethod
- def get_policy_recommendations(self, data: EconomicData, analysis: Dict[str, Any]) -> List[PolicyRecommendation]:
- """Generate policy recommendations based on economic analysis"""
- pass
-
- @abstractmethod
- def evaluate_policy(self, policy: Dict[str, Any], data: EconomicData) -> Dict[str, Any]:
- """Evaluate a specific policy from this ideology's perspective"""
- pass
-
- def calculate_health_score(self, data: EconomicData) -> float:
- """Calculate overall economic health score (0-100)"""
- # Base implementation - can be overridden by specific agents
- gdp_score = min(max(data.gdp / 100 * 50, 0), 50) # GDP growth contribution
- employment_score = max(50 - data.unemployment * 2, 0) # Employment contribution
- inflation_score = max(25 - abs(data.inflation - 2) * 10, 0) # Inflation contribution (target 2%)
-
- return min(gdp_score + employment_score + inflation_score, 100)
-
- def format_analysis(self, analysis: Dict[str, Any]) -> str:
- """Format analysis results for human-readable output"""
- return json.dumps(analysis, indent=2, default=str)
-
- def __str__(self):
- return f"{self.name}: {self.description}"
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/capitalism_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/capitalism_agent.py
deleted file mode 100644
index f6f030bfa..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/capitalism_agent.py
+++ /dev/null
@@ -1,282 +0,0 @@
-"""
-Capitalism Economic Agent
-Processes economic data through the lens of capitalist economic principles
-"""
-
-from typing import Dict, List, Any
-from base_agent import EconomicAgent, EconomicData, PolicyRecommendation
-
-class CapitalismAgent(EconomicAgent):
- """Capitalist economic analysis agent focusing on free markets and private enterprise"""
-
- def __init__(self):
- super().__init__(
- "Capitalism Agent",
- "Analyzes economic data through free-market principles emphasizing private property, competition, and minimal government intervention"
- )
- self.principles = [
- "Private property rights",
- "Free market competition",
- "Profit motive",
- "Limited government intervention",
- "Voluntary exchange",
- "Capital accumulation"
- ]
- self.priorities = [
- "Economic freedom",
- "Market efficiency",
- "Innovation and entrepreneurship",
- "Wealth creation",
- "Competitive markets"
- ]
-
- def analyze_economy(self, data: EconomicData) -> Dict[str, Any]:
- """Analyze economy from capitalist perspective"""
-
- # Calculate capitalism-specific metrics
- market_efficiency = self._calculate_market_efficiency(data)
- investment_attractiveness = self._calculate_investment_attractiveness(data)
- economic_freedom_score = self._calculate_economic_freedom(data)
- competitiveness_score = self._calculate_competitiveness(data)
-
- # Identify strengths and concerns
- strengths = []
- concerns = []
-
- if data.gdp > 3.0:
- strengths.append("Strong GDP growth indicating productive investment")
- if data.unemployment < 5.0:
- strengths.append("Low unemployment showing efficient labor markets")
- if data.tax_rate < 30:
- strengths.append("Favorable tax environment for business growth")
- if data.private_investment > 20:
- strengths.append("High private investment driving innovation")
-
- if data.government_spending > 40:
- concerns.append("High government spending may crowd out private investment")
- if data.inflation > 4:
- concerns.append("High inflation erodes purchasing power and savings")
- if data.tax_rate > 40:
- concerns.append("High tax rates may discourage investment and entrepreneurship")
- if data.interest_rate > 8:
- concerns.append("High interest rates increase cost of capital")
-
- # Calculate overall capitalist health score
- health_score = (
- market_efficiency * 0.3 +
- investment_attractiveness * 0.25 +
- economic_freedom_score * 0.25 +
- competitiveness_score * 0.2
- )
-
- return {
- "ideology": "capitalism",
- "market_efficiency": market_efficiency,
- "investment_attractiveness": investment_attractiveness,
- "economic_freedom_score": economic_freedom_score,
- "competitiveness_score": competitiveness_score,
- "overall_health_score": health_score,
- "strengths": strengths,
- "concerns": concerns,
- "assessment": self._generate_assessment(health_score, strengths, concerns),
- "key_indicators": {
- "gdp_growth": data.gdp,
- "unemployment_rate": data.unemployment,
- "inflation_rate": data.inflation,
- "tax_burden": data.tax_rate,
- "private_investment_share": data.private_investment
- }
- }
-
- def get_policy_recommendations(self, data: EconomicData, analysis: Dict[str, Any]) -> List[PolicyRecommendation]:
- """Generate capitalist policy recommendations"""
- recommendations = []
-
- # Tax policy recommendations
- if data.tax_rate > 35:
- recommendations.append(PolicyRecommendation(
- title="Reduce Corporate and Personal Tax Rates",
- description="Lower taxes to stimulate investment, entrepreneurship, and economic growth",
- priority="high",
- expected_impact="Increased private investment and GDP growth",
- implementation_time="6-12 months",
- risk_level="medium"
- ))
-
- # Deregulation recommendations
- if analysis["economic_freedom_score"] < 70:
- recommendations.append(PolicyRecommendation(
- title="Reduce Regulatory Burden",
- description="Eliminate unnecessary regulations that hinder business formation and growth",
- priority="high",
- expected_impact="Improved business climate and increased competition",
- implementation_time="12-24 months",
- risk_level="low"
- ))
-
- # Government spending recommendations
- if data.government_spending > 40:
- recommendations.append(PolicyRecommendation(
- title="Reduce Government Spending",
- description="Cut government expenditure to reduce tax burden and allow private sector growth",
- priority="medium",
- expected_impact="More efficient resource allocation through markets",
- implementation_time="12-36 months",
- risk_level="medium"
- ))
-
- # Trade policy recommendations
- if data.trade_balance < -5:
- recommendations.append(PolicyRecommendation(
- title="Promote Free Trade",
- description="Remove trade barriers and negotiate favorable trade agreements",
- priority="medium",
- expected_impact="Increased export competitiveness and economic efficiency",
- implementation_time="6-18 months",
- risk_level="low"
- ))
-
- # Monetary policy recommendations
- if data.interest_rate > 7:
- recommendations.append(PolicyRecommendation(
- title="Implement Sound Monetary Policy",
- description="Maintain stable currency and moderate interest rates to encourage investment",
- priority="high",
- expected_impact="Stable environment for long-term investment",
- implementation_time="3-6 months",
- risk_level="low"
- ))
-
- # Property rights recommendations
- recommendations.append(PolicyRecommendation(
- title="Strengthen Property Rights",
- description="Enhance legal protection for private property and intellectual property",
- priority="medium",
- expected_impact="Increased investment and innovation",
- implementation_time="12-24 months",
- risk_level="low"
- ))
-
- return recommendations
-
- def evaluate_policy(self, policy: Dict[str, Any], data: EconomicData) -> Dict[str, Any]:
- """Evaluate policy from capitalist perspective"""
- policy_name = policy.get("name", "Unknown Policy")
- policy_type = policy.get("type", "unknown")
-
- # Scoring criteria for capitalist evaluation
- scores = {
- "market_impact": 0, # How it affects free markets
- "investment_incentive": 0, # How it encourages private investment
- "economic_freedom": 0, # How it affects economic freedom
- "competitiveness": 0, # How it affects competition
- "property_rights": 0 # How it affects property rights
- }
-
- # Evaluate based on policy type
- if policy_type == "tax_cut":
- scores["investment_incentive"] = 85
- scores["economic_freedom"] = 80
- scores["market_impact"] = 75
- elif policy_type == "deregulation":
- scores["economic_freedom"] = 90
- scores["market_impact"] = 85
- scores["competitiveness"] = 80
- elif policy_type == "trade_agreement":
- scores["competitiveness"] = 85
- scores["market_impact"] = 80
- elif policy_type == "spending_increase":
- scores["market_impact"] = -50
- scores["economic_freedom"] = -40
- elif policy_type == "price_control":
- scores["market_impact"] = -70
- scores["economic_freedom"] = -60
-
- overall_score = sum(scores.values()) / len(scores)
-
- return {
- "policy_name": policy_name,
- "capitalist_score": overall_score,
- "detailed_scores": scores,
- "recommendation": self._get_policy_recommendation(overall_score),
- "justification": self._generate_policy_justification(scores, policy_type)
- }
-
- def _calculate_market_efficiency(self, data: EconomicData) -> float:
- """Calculate market efficiency score (0-100)"""
- # Factors: low unemployment, moderate inflation, reasonable interest rates
- unemployment_score = max(100 - data.unemployment * 10, 0)
- inflation_score = max(100 - abs(data.inflation - 2.5) * 20, 0)
- interest_score = max(100 - abs(data.interest_rate - 5) * 10, 0)
-
- return (unemployment_score + inflation_score + interest_score) / 3
-
- def _calculate_investment_attractiveness(self, data: EconomicData) -> float:
- """Calculate investment attractiveness score (0-100)"""
- # Factors: GDP growth, interest rates, tax burden, private investment
- gdp_score = min(data.gdp * 10, 100)
- interest_score = max(100 - data.interest_rate * 8, 0)
- tax_score = max(100 - data.tax_rate * 2, 0)
- investment_score = min(data.private_investment * 3, 100)
-
- return (gdp_score + interest_score + tax_score + investment_score) / 4
-
- def _calculate_economic_freedom(self, data: EconomicData) -> float:
- """Calculate economic freedom score (0-100)"""
- # Factors: low tax rates, low government spending, low regulation (assumed)
- tax_score = max(100 - data.tax_rate * 2.5, 0)
- spending_score = max(100 - data.government_spending, 0)
-
- return (tax_score + spending_score) / 2
-
- def _calculate_competitiveness(self, data: EconomicData) -> float:
- """Calculate economic competitiveness score (0-100)"""
- # Factors: productivity (GDP growth), trade balance, innovation (private investment)
- productivity_score = min(data.gdp * 15, 100)
- trade_score = max(100 - abs(data.trade_balance) * 10, 0)
- innovation_score = min(data.private_investment * 4, 100)
-
- return (productivity_score + trade_score + innovation_score) / 3
-
- def _generate_assessment(self, health_score: float, strengths: List[str], concerns: List[str]) -> str:
- """Generate overall assessment"""
- if health_score >= 80:
- return f"Excellent economic health (Score: {health_score:.1f}/100). Strong capitalist fundamentals with minimal concerns."
- elif health_score >= 60:
- return f"Good economic health (Score: {health_score:.1f}/100). Solid market performance with some areas for improvement."
- elif health_score >= 40:
- return f"Moderate economic health (Score: {health_score:.1f}/100). Mixed performance with significant policy challenges."
- else:
- return f"Poor economic health (Score: {health_score:.1f}/100). Major obstacles to prosperity requiring significant reforms."
-
- def _get_policy_recommendation(self, score: float) -> str:
- """Get policy recommendation based on score"""
- if score >= 70:
- return "Highly Recommended"
- elif score >= 40:
- return "Moderately Recommended"
- elif score >= 0:
- return "Not Recommended"
- else:
- return "Strongly Opposed"
-
- def _generate_policy_justification(self, scores: Dict[str, float], policy_type: str) -> str:
- """Generate justification for policy evaluation"""
- justification = []
-
- if scores["market_impact"] > 50:
- justification.append("Supports free market efficiency")
- elif scores["market_impact"] < -20:
- justification.append("Hinders market efficiency")
-
- if scores["investment_incentive"] > 50:
- justification.append("Encourages private investment")
- elif scores["investment_incentive"] < -20:
- justification.append("Discourages private investment")
-
- if scores["economic_freedom"] > 50:
- justification.append("Enhances economic freedom")
- elif scores["economic_freedom"] < -20:
- justification.append("Restricts economic freedom")
-
- return "; ".join(justification) if justification else "Mixed effects on economic outcomes"
\ 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
deleted file mode 100644
index 5009b320f..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/capitalism_agent_cli.py
+++ /dev/null
@@ -1,154 +0,0 @@
-#!/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(argv=None):
- """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(argv)
-
- try:
- parameters = json.loads(args.parameters)
- inputs = json.loads(args.inputs)
-
- result = execute_agent(parameters, inputs)
-
- result_json = json.dumps(result, indent=2)
- print(result_json)
- return result_json
- 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/cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/cli.py
deleted file mode 100644
index 1a32de4c2..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/cli.py
+++ /dev/null
@@ -1,588 +0,0 @@
-"""
-Command Line Interface for Economic Agents
-"""
-
-import argparse
-import sys
-import json
-from typing import Dict, List, Any
-from datetime import datetime
-from pathlib import Path
-
-from base_agent import EconomicData
-from data_processor import EconomicDataProcessor
-from comparison import EconomicAgentComparator
-from utils import export_to_json, export_to_csv
-
-class EconomicCLI:
- """Command line interface for economic agent analysis"""
-
- def __init__(self):
- self.processor = EconomicDataProcessor()
- self.comparator = EconomicAgentComparator()
-
- def create_parser(self):
- """Create argument parser"""
- parser = argparse.ArgumentParser(
- description="Economic Agents CLI - Analyze economic data through different ideological perspectives",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="""
-Examples:
- # Analyze single data point with specific agent
- python cli.py analyze --agent capitalism --data "{'gdp': 3.2, 'inflation': 2.1, 'unemployment': 5.5}"
-
- # Load data from file and compare all agents
- python cli.py compare --file data.json --all-agents
-
- # Load CSV data and generate report
- python cli.py report --file economic_data.csv --output report.json
-
- # Interactive mode
- python cli.py interactive
-
- # List available agents
- python cli.py list-agents
- """
- )
-
- subparsers = parser.add_subparsers(dest='command', help='Available commands')
-
- # Analyze command
- analyze_parser = subparsers.add_parser('analyze', help='Analyze economic data with specific agent')
- analyze_parser.add_argument('--agent', '-a', required=True,
- help='Agent name (capitalism, socialism, mixed_economy, keynesian, neoliberal, mercantilism)')
- analyze_parser.add_argument('--data', '-d', help='JSON string of economic data')
- analyze_parser.add_argument('--file', '-f', help='File containing economic data')
- analyze_parser.add_argument('--output', '-o', help='Output file for results')
- analyze_parser.add_argument('--format', choices=['json', 'csv', 'text'], default='text',
- help='Output format')
-
- # Compare command
- compare_parser = subparsers.add_parser('compare', help='Compare multiple agents')
- compare_parser.add_argument('--file', '-f', help='File containing economic data')
- compare_parser.add_argument('--data', '-d', help='JSON string of economic data')
- compare_parser.add_argument('--all-agents', action='store_true', help='Compare all available agents')
- compare_parser.add_argument('--agents', nargs='+', help='Specific agents to compare')
- compare_parser.add_argument('--output', '-o', help='Output file for comparison results')
- compare_parser.add_argument('--format', choices=['json', 'csv', 'text'], default='text',
- help='Output format')
-
- # Report command
- report_parser = subparsers.add_parser('report', help='Generate comprehensive economic report')
- report_parser.add_argument('--file', '-f', required=True,
- help='File containing economic time series data')
- report_parser.add_argument('--output', '-o', help='Output file for report')
- report_parser.add_argument('--format', choices=['json', 'html', 'text'], default='text',
- help='Output format')
- report_parser.add_argument('--agents', nargs='+', help='Agents to include in report')
-
- # Policy command
- policy_parser = subparsers.add_parser('policies', help='Get policy recommendations')
- policy_parser.add_argument('--agent', '-a', required=True,
- help='Agent name for policy recommendations')
- policy_parser.add_argument('--data', '-d', help='JSON string of economic data')
- policy_parser.add_argument('--file', '-f', help='File containing economic data')
- policy_parser.add_argument('--priority', choices=['high', 'medium', 'low'],
- help='Filter by priority level')
- policy_parser.add_argument('--output', '-o', help='Output file for policies')
-
- # Validate command
- validate_parser = subparsers.add_parser('validate', help='Validate economic data')
- validate_parser.add_argument('--file', '-f', help='File containing economic data')
- validate_parser.add_argument('--data', '-d', help='JSON string of economic data')
-
- # List agents command
- list_parser = subparsers.add_parser('list-agents', help='List available economic agents')
-
- # Interactive mode
- interactive_parser = subparsers.add_parser('interactive', help='Interactive analysis mode')
-
- return parser
-
- def run(self, args=None):
- """Run the CLI with provided arguments"""
- parser = self.create_parser()
-
- if args is None:
- args = parser.parse_args(argv)
- else:
- args = parser.parse_args(args)
-
- if not args.command:
- parser.print_help()
- return
-
- try:
- if args.command == 'analyze':
- self.handle_analyze(args)
- elif args.command == 'compare':
- self.handle_compare(args)
- elif args.command == 'report':
- self.handle_report(args)
- elif args.command == 'policies':
- self.handle_policies(args)
- elif args.command == 'validate':
- self.handle_validate(args)
- elif args.command == 'list-agents':
- self.handle_list_agents(args)
- elif args.command == 'interactive':
- self.handle_interactive(args)
- except Exception as e:
- print(f"Error: {e}")
- sys.exit(1)
-
- def handle_analyze(self, args):
- """Handle analyze command"""
- from __init__ import get_agent
-
- # Load data
- data = self._load_data(args.data, args.file)
- if data is None:
- print("Error: No data provided")
- return
-
- # Get agent
- try:
- agent = get_agent(args.agent)
- except ValueError as e:
- print(f"Error: {e}")
- return
-
- # Perform analysis
- analysis = agent.analyze_economy(data)
-
- # Output results
- self._output_results(analysis, args.output, args.format)
-
- def handle_compare(self, args):
- """Handle compare command"""
- from __init__ import get_all_agents
-
- # Load data
- data = self._load_data(args.data, args.file)
- if data is None:
- print("Error: No data provided")
- return
-
- # Get agents to compare
- if args.all_agents:
- agents = get_all_agents()
- elif args.agents:
- agents = {}
- for agent_name in args.agents:
- try:
- agents[agent_name] = get_agent(agent_name)
- except ValueError as e:
- print(f"Warning: {e}")
- else:
- print("Error: Must specify --all-agents or --agents")
- return
-
- # Perform comparison
- comparison = self.comparator.compare_agents(agents, data)
-
- # Output results
- self._output_results(comparison, args.output, args.format)
-
- def handle_report(self, args):
- """Handle report command"""
- from __init__ import get_all_agents
-
- # Load time series data
- if not args.file:
- print("Error: Must specify file for report generation")
- return
-
- try:
- data_points = self.processor.load_from_json(args.file)
- if isinstance(data_points, dict):
- data_points = [data_points]
- except:
- try:
- data_points = self.processor.load_from_csv(args.file)
- except Exception as e:
- print(f"Error loading data file: {e}")
- return
-
- if not data_points:
- print("Error: No data loaded")
- return
-
- # Get agents
- all_agents = get_all_agents()
- if args.agents:
- agents = {name: all_agents[name] for name in args.agents if name in all_agents}
- else:
- agents = all_agents
-
- # Generate comprehensive report
- report = self._generate_comprehensive_report(agents, data_points)
-
- # Output report
- self._output_results(report, args.output, args.format)
-
- def handle_policies(self, args):
- """Handle policies command"""
- from __init__ import get_agent
-
- # Load data
- data = self._load_data(args.data, args.file)
- if data is None:
- print("Error: No data provided")
- return
-
- # Get agent
- try:
- agent = get_agent(args.agent)
- except ValueError as e:
- print(f"Error: {e}")
- return
-
- # Get analysis and policies
- analysis = agent.analyze_economy(data)
- policies = agent.get_policy_recommendations(data, analysis)
-
- # Filter by priority if specified
- if args.priority:
- policies = [p for p in policies if p.priority == args.priority]
-
- # Output results
- result = {
- 'agent': args.agent,
- 'analysis_summary': {
- 'overall_health_score': analysis.get('overall_health_score', 0),
- 'assessment': analysis.get('assessment', 'No assessment available')
- },
- 'policy_recommendations': [
- {
- 'title': p.title,
- 'description': p.description,
- 'priority': p.priority,
- 'expected_impact': p.expected_impact,
- 'implementation_time': p.implementation_time,
- 'risk_level': p.risk_level
- }
- for p in policies
- ]
- }
-
- self._output_results(result, args.output, 'json')
-
- def handle_validate(self, args):
- """Handle validate command"""
- # Load data
- data = self._load_data(args.data, args.file)
- if data is None:
- print("Error: No data provided")
- return
-
- # Validate data
- from utils import validate_economic_data
- issues = validate_economic_data(data)
-
- if not issues:
- print("✓ Data validation passed")
- else:
- print("✗ Data validation failed:")
- for issue in issues:
- print(f" - {issue}")
-
- # Additional validation for consistency
- if isinstance(data, list):
- is_valid, consistency_issues = self.processor.validate_data_consistency(data)
- if not is_valid:
- print("✗ Data consistency issues:")
- for issue in consistency_issues:
- print(f" - {issue}")
-
- def handle_list_agents(self, args):
- """Handle list-agents command"""
- from __init__ import list_agents
-
- agents = list_agents()
- print("Available Economic Agents:")
- print("-" * 40)
-
- agent_descriptions = {
- 'capitalism': 'Free market capitalism with minimal government intervention',
- 'socialism': 'Social ownership and economic equality',
- 'mixed_economy': 'Balance of public and private sectors',
- 'keynesian': 'Demand management and counter-cyclical policies',
- 'neoliberal': 'Deregulation and free market fundamentalism',
- 'mercantilism': 'Trade surplus and national wealth accumulation'
- }
-
- for agent in agents:
- description = agent_descriptions.get(agent, 'No description available')
- print(f" {agent:<15} - {description}")
-
- print("-" * 40)
- print(f"Total: {len(agents)} agents available")
-
- def handle_interactive(self, args):
- """Handle interactive mode"""
- print("=" * 60)
- print("ECONOMIC AGENTS INTERACTIVE MODE")
- print("=" * 60)
- print("Type 'help' for available commands, 'quit' to exit")
-
- from __init__ import get_agent, get_all_agents
-
- while True:
- try:
- command = input("\n> ").strip().lower()
-
- if command in ['quit', 'exit', 'q']:
- break
- elif command == 'help':
- print("\nAvailable commands:")
- print(" analyze <agent> - Analyze current data with specified agent")
- print(" compare [agents...] - Compare agents with current data")
- print(" data <json> - Set economic data for analysis")
- print(" load <file> - Load data from file")
- print(" policies <agent> - Get policy recommendations")
- print(" validate - Validate current data")
- print(" status - Show current data and settings")
- print(" help - Show this help")
- print(" quit - Exit interactive mode")
- elif command.startswith('data '):
- try:
- data_json = command[5:]
- self.current_data = self._parse_data_string(data_json)
- print("Data loaded successfully")
- except Exception as e:
- print(f"Error loading data: {e}")
- elif command.startswith('load '):
- try:
- filename = command[5:]
- self.current_data = self._load_data(None, filename)
- print(f"Data loaded from {filename}")
- except Exception as e:
- print(f"Error loading file: {e}")
- elif command.startswith('analyze '):
- if not hasattr(self, 'current_data'):
- print("No data loaded. Use 'data' or 'load' command first")
- continue
-
- agent_name = command[8:].strip()
- try:
- agent = get_agent(agent_name)
- analysis = agent.analyze_economy(self.current_data)
- print(f"\nAnalysis from {agent_name} agent:")
- print(f"Health Score: {analysis.get('overall_health_score', 0):.1f}/100")
- print(f"Assessment: {analysis.get('assessment', 'N/A')}")
- except Exception as e:
- print(f"Error: {e}")
- elif command == 'status':
- if hasattr(self, 'current_data'):
- print("\nCurrent economic data:")
- print(f" GDP Growth: {self.current_data.gdp}%")
- print(f" Inflation: {self.current_data.inflation}%")
- print(f" Unemployment: {self.current_data.unemployment}%")
- print(f" Interest Rate: {self.current_data.interest_rate}%")
- print(f" Trade Balance: {self.current_data.trade_balance}%")
- print(f" Government Spending: {self.current_data.government_spending}%")
- print(f" Tax Rate: {self.current_data.tax_rate}%")
- print(f" Private Investment: {self.current_data.private_investment}%")
- print(f" Consumer Confidence: {self.current_data.consumer_confidence}")
- else:
- print("No data currently loaded")
- else:
- print("Unknown command. Type 'help' for available commands")
-
- except KeyboardInterrupt:
- break
- except EOFError:
- break
-
- print("\nGoodbye!")
-
- def _load_data(self, data_string: str, file_path: str):
- """Load data from string or file"""
- if data_string:
- return self._parse_data_string(data_string)
- elif file_path:
- file_path = Path(file_path)
- if file_path.suffix == '.json':
- data = self.processor.load_from_json(str(file_path))
- return data if isinstance(data, EconomicData) else data[0] if data else None
- elif file_path.suffix == '.csv':
- data_points = self.processor.load_from_csv(str(file_path))
- return data_points[0] if data_points else None
- else:
- raise ValueError(f"Unsupported file format: {file_path.suffix}")
- else:
- return None
-
- def _parse_data_string(self, data_string: str) -> EconomicData:
- """Parse data string into EconomicData object"""
- try:
- data_dict = json.loads(data_string)
- return EconomicData(
- gdp=float(data_dict.get('gdp', 0)),
- inflation=float(data_dict.get('inflation', 0)),
- unemployment=float(data_dict.get('unemployment', 0)),
- interest_rate=float(data_dict.get('interest_rate', 0)),
- trade_balance=float(data_dict.get('trade_balance', 0)),
- government_spending=float(data_dict.get('government_spending', 0)),
- tax_rate=float(data_dict.get('tax_rate', 0)),
- private_investment=float(data_dict.get('private_investment', 0)),
- consumer_confidence=float(data_dict.get('consumer_confidence', 0)),
- timestamp=datetime.now()
- )
- except Exception as e:
- raise ValueError(f"Invalid data format: {e}")
-
- def _output_results(self, results: Any, output_file: str = None, format_type: str = 'text'):
- """Output results in specified format"""
- if format_type == 'json':
- output = json.dumps(results, indent=2, default=str)
- elif format_type == 'csv' and isinstance(results, list):
- # Convert list of dicts to CSV format
- import csv
- import io
- output = io.StringIO()
- if results:
- writer = csv.DictWriter(output, fieldnames=results[0].keys())
- writer.writeheader()
- writer.writerows(results)
- output = output.getvalue()
- else:
- output = "No data to export"
- else: # text format
- output = self._format_as_text(results)
-
- if output_file:
- with open(output_file, 'w') as f:
- f.write(output)
- print(f"Results saved to {output_file}")
- else:
- print(output)
-
- def _format_as_text(self, results: Any) -> str:
- """Format results as readable text"""
- if isinstance(results, dict):
- output = []
- for key, value in results.items():
- if isinstance(value, dict):
- output.append(f"\n{key.upper()}:")
- for subkey, subvalue in value.items():
- output.append(f" {subkey}: {subvalue}")
- elif isinstance(value, list):
- output.append(f"\n{key.upper()}:")
- for i, item in enumerate(value, 1):
- output.append(f" {i}. {item}")
- else:
- output.append(f"{key}: {value}")
- return "\n".join(output)
- elif isinstance(results, list):
- return "\n".join(f"{i+1}. {item}" for i, item in enumerate(results))
- else:
- return str(results)
-
- def _generate_comprehensive_report(self, agents: Dict, data_points: List) -> Dict[str, Any]:
- """Generate comprehensive economic report"""
- if not data_points:
- return {"error": "No data provided"}
-
- # Get latest data point for current analysis
- latest_data = max(data_points, key=lambda x: x.timestamp)
-
- # Analyze with all agents
- current_analyses = {}
- for name, agent in agents.items():
- try:
- current_analyses[name] = agent.analyze_economy(latest_data)
- except Exception as e:
- current_analyses[name] = {"error": str(e)}
-
- # Compare agents
- comparison = self.comparator.compare_agents(agents, latest_data)
-
- # Analyze trends over time
- from utils import create_economic_summary
- trends = create_economic_summary(data_points)
-
- # Generate report
- report = {
- "report_metadata": {
- "generated_at": datetime.now().isoformat(),
- "data_points_analyzed": len(data_points),
- "date_range": trends["date_range"],
- "agents_included": list(agents.keys())
- },
- "current_situation": {
- "latest_data": {
- "timestamp": latest_data.timestamp.isoformat(),
- "gdp": latest_data.gdp,
- "inflation": latest_data.inflation,
- "unemployment": latest_data.unemployment,
- "interest_rate": latest_data.interest_rate,
- "trade_balance": latest_data.trade_balance,
- "government_spending": latest_data.government_spending,
- "tax_rate": latest_data.tax_rate,
- "private_investment": latest_data.private_investment,
- "consumer_confidence": latest_data.consumer_confidence
- },
- "agent_analyses": current_analyses
- },
- "comparative_analysis": comparison,
- "trend_analysis": trends,
- "policy_recommendations": self.comparator.compare_policy_recommendations(agents, latest_data),
- "executive_summary": self._generate_executive_summary(comparison, trends)
- }
-
- return report
-
- def _generate_executive_summary(self, comparison: Dict, trends: Dict) -> str:
- """Generate executive summary"""
- avg_health = comparison.get('comparison_metrics', {}).get('average_health_score', 0)
- diversity = comparison.get('comparison_metrics', {}).get('ideological_diversity', 0)
-
- # Determine overall economic trend
- gdp_trend = trends.get('indicators', {}).get('gdp', {}).get('trend', 'neutral')
- unemployment_trend = trends.get('indicators', {}).get('unemployment', {}).get('trend', 'neutral')
-
- summary = f"""
-Executive Summary:
-
-Overall Economic Health: {avg_health:.1f}/100
-Ideological Agreement: {100 - diversity:.1f}% average consensus
-
-Economic Trends:
-- GDP Growth: {gdp_trend}
-- Unemployment: {unemployment_trend}
-
-Key Findings:
-{comparison.get('summary', 'Unable to generate summary')}
-
-Recommendations:
-{self._get_top_recommendations(comparison.get('policy_comparison', {}))}
- """.strip()
-
- return summary
-
- def _get_top_recommendations(self, policy_comparison: Dict) -> str:
- """Extract top policy recommendations"""
- if not policy_comparison or 'recommendations' not in policy_comparison:
- return "No specific recommendations available."
-
- top_recommendations = policy_comparison['recommendations'][:3]
- recommendations_text = []
-
- for rec in top_recommendations:
- category = rec.get('category', 'Unknown')
- support = rec.get('support_level', 0)
- recommendations_text.append(f"- Consider {category}-focused policies (support: {support:.1f}%)")
-
- return "\n".join(recommendations_text)
-
-
-def main(argv=None):
- """Main entry point for CLI"""
- cli = EconomicCLI()
- cli.run()
-
-
-if __name__ == '__main__':
- main()
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/comparison.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/comparison.py
deleted file mode 100644
index 44e408413..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/comparison.py
+++ /dev/null
@@ -1,604 +0,0 @@
-"""
-Comparison module for analyzing and comparing different economic ideology agents
-"""
-
-from typing import Dict, List, Any, Tuple, Optional
-from collections import defaultdict
-import statistics
-from base_agent import EconomicAgent, EconomicData
-from utils import calculate_composite_score, clamp_value
-
-class EconomicAgentComparator:
- """Compares analyses from different economic ideology agents"""
-
- def __init__(self):
- self.comparison_weights = {
- 'health_score': 0.3,
- 'policy_alignment': 0.25,
- 'consistency': 0.2,
- 'feasibility': 0.15,
- 'stability': 0.1
- }
-
- def compare_agents(self, agents: Dict[str, EconomicAgent], data: EconomicData) -> Dict[str, Any]:
- """
- Compare multiple economic agents on the same data
-
- Args:
- agents (Dict[str, EconomicAgent]): Dictionary of agents to compare
- data (EconomicData): Economic data to analyze
-
- Returns:
- Dict[str, Any]: Comprehensive comparison results
- """
- # Get analyses from all agents
- analyses = {}
- for name, agent in agents.items():
- try:
- analyses[name] = agent.analyze_economy(data)
- except Exception as e:
- print(f"Error analyzing with {name}: {e}")
- analyses[name] = {'error': str(e)}
-
- # Calculate comparison metrics
- comparison_metrics = self._calculate_comparison_metrics(analyses, data)
-
- # Rank agents by different criteria
- rankings = self._rank_agents(analyses, comparison_metrics)
-
- # Identify consensus and divergences
- consensus = self._identify_consensus(analyses)
- divergences = self._identify_divergences(analyses)
-
- # Generate policy comparison
- policy_comparison = self._compare_policies(agents, data, analyses)
-
- return {
- 'agent_analyses': analyses,
- 'comparison_metrics': comparison_metrics,
- 'rankings': rankings,
- 'consensus': consensus,
- 'divergences': divergences,
- 'policy_comparison': policy_comparison,
- 'summary': self._generate_comparison_summary(analyses, comparison_metrics)
- }
-
- def compare_policy_recommendations(self, agents: Dict[str, EconomicAgent], data: EconomicData) -> Dict[str, Any]:
- """
- Compare policy recommendations from different agents
-
- Args:
- agents (Dict[str, EconomicAgent]): Dictionary of agents to compare
- data (EconomicData): Economic data to analyze
-
- Returns:
- Dict[str, Any]: Policy comparison results
- """
- all_policies = {}
- policy_categories = defaultdict(list)
-
- # Collect all policies from all agents
- for name, agent in agents.items():
- try:
- analysis = agent.analyze_economy(data)
- policies = agent.get_policy_recommendations(data, analysis)
- all_policies[name] = policies
-
- # Categorize policies
- for policy in policies:
- category = self._categorize_policy(policy.title)
- policy_categories[category].append({
- 'agent': name,
- 'policy': policy
- })
- except Exception as e:
- print(f"Error getting policies from {name}: {e}")
-
- # Analyze policy overlaps and conflicts
- overlaps = self._find_policy_overlaps(policy_categories)
- conflicts = self._find_policy_conflicts(policy_categories)
-
- # Calculate support for each policy category
- category_support = self._calculate_policy_support(policy_categories, len(agents))
-
- return {
- 'all_policies': all_policies,
- 'policy_categories': dict(policy_categories),
- 'overlaps': overlaps,
- 'conflicts': conflicts,
- 'category_support': category_support,
- 'recommendations': self._synthesize_policy_recommendations(policy_categories, category_support)
- }
-
- def evaluate_economic_scenarios(self, agents: Dict[str, EconomicAgent], scenarios: List[EconomicData]) -> Dict[str, Any]:
- """
- Evaluate different economic scenarios with all agents
-
- Args:
- agents (Dict[str, EconomicAgent]): Dictionary of agents to evaluate
- scenarios (List[EconomicData]): Different economic scenarios to test
-
- Returns:
- Dict[str, Any]: Scenario evaluation results
- """
- scenario_results = {}
-
- for i, scenario in enumerate(scenarios):
- scenario_name = f"Scenario_{i+1}"
- scenario_results[scenario_name] = {
- 'data': scenario,
- 'analyses': {},
- 'metrics': {}
- }
-
- # Get analysis from each agent for this scenario
- for name, agent in agents.items():
- try:
- analysis = agent.analyze_economy(scenario)
- scenario_results[scenario_name]['analyses'][name] = analysis
- except Exception as e:
- print(f"Error analyzing {scenario_name} with {name}: {e}")
-
- # Calculate metrics for this scenario
- scenario_results[scenario_name]['metrics'] = self._calculate_scenario_metrics(
- scenario_results[scenario_name]['analyses']
- )
-
- # Compare agent performance across scenarios
- agent_performance = self._compare_agent_performance(scenario_results)
-
- # Identify best performing agents for different scenarios
- best_performers = self._identify_best_performers(scenario_results)
-
- return {
- 'scenario_results': scenario_results,
- 'agent_performance': agent_performance,
- 'best_performers': best_performers,
- 'summary': self._generate_scenario_summary(scenario_results)
- }
-
- def calculate_ideology_alignment(self, agent1_analysis: Dict, agent2_analysis: Dict) -> float:
- """
- Calculate alignment score between two ideological analyses
-
- Args:
- agent1_analysis (Dict): Analysis from first agent
- agent2_analysis (Dict): Analysis from second agent
-
- Returns:
- float: Alignment score (0-100)
- """
- if 'error' in agent1_analysis or 'error' in agent2_analysis:
- return 0.0
-
- alignment_factors = []
-
- # Health score alignment
- if 'overall_health_score' in agent1_analysis and 'overall_health_score' in agent2_analysis:
- score_diff = abs(agent1_analysis['overall_health_score'] - agent2_analysis['overall_health_score'])
- alignment_factors.append(max(0, 100 - score_diff))
-
- # Strengths overlap
- if 'strengths' in agent1_analysis and 'strengths' in agent2_analysis:
- strengths_overlap = self._calculate_text_overlap(
- agent1_analysis['strengths'],
- agent2_analysis['strengths']
- )
- alignment_factors.append(strengths_overlap)
-
- # Concerns overlap
- if 'concerns' in agent1_analysis and 'concerns' in agent2_analysis:
- concerns_overlap = self._calculate_text_overlap(
- agent1_analysis['concerns'],
- agent2_analysis['concerns']
- )
- alignment_factors.append(concerns_overlap)
-
- return statistics.mean(alignment_factors) if alignment_factors else 0.0
-
- def _calculate_comparison_metrics(self, analyses: Dict[str, Any], data: EconomicData) -> Dict[str, Any]:
- """Calculate comparison metrics across all agent analyses"""
- metrics = {
- 'health_scores': {},
- 'average_health_score': 0,
- 'health_score_variance': 0,
- 'most_optimistic': None,
- 'most_pessimistic': None,
- 'ideological_diversity': 0
- }
-
- health_scores = []
- for name, analysis in analyses.items():
- if 'error' not in analysis and 'overall_health_score' in analysis:
- score = analysis['overall_health_score']
- health_scores.append(score)
- metrics['health_scores'][name] = score
-
- if health_scores:
- metrics['average_health_score'] = statistics.mean(health_scores)
- metrics['health_score_variance'] = statistics.stdev(health_scores) if len(health_scores) > 1 else 0
-
- # Find most optimistic and pessimistic
- max_score_agent = max(metrics['health_scores'], key=metrics['health_scores'].get)
- min_score_agent = min(metrics['health_scores'], key=metrics['health_scores'].get)
- metrics['most_optimistic'] = max_score_agent
- metrics['most_pessimistic'] = min_score_agent
-
- # Calculate ideological diversity (based on score variance)
- metrics['ideological_diversity'] = clamp_value(metrics['health_score_variance'] * 10, 0, 100)
-
- return metrics
-
- def _rank_agents(self, analyses: Dict[str, Any], metrics: Dict[str, Any]) -> Dict[str, List[str]]:
- """Rank agents by different criteria"""
- rankings = {}
-
- if 'health_scores' in metrics and metrics['health_scores']:
- # Rank by health score
- health_ranking = sorted(metrics['health_scores'].items(), key=lambda x: x[1], reverse=True)
- rankings['by_health_score'] = [name for name, _ in health_ranking]
-
- # Rank by stability (inverse of variance in scores)
- stability_scores = {}
- for name in analyses.keys():
- # For simplicity, use ideology-specific stability indicators
- if name.lower() in ['mixed_economy', 'keynesian']:
- stability_scores[name] = 80
- elif name.lower() in ['capitalism', 'neoliberal']:
- stability_scores[name] = 70
- else:
- stability_scores[name] = 60
-
- stability_ranking = sorted(stability_scores.items(), key=lambda x: x[1], reverse=True)
- rankings['by_stability'] = [name for name, _ in stability_ranking]
-
- return rankings
-
- def _identify_consensus(self, analyses: Dict[str, Any]) -> Dict[str, Any]:
- """Identify areas of consensus among agents"""
- consensus = {
- 'economic_conditions': [],
- 'policy_priorities': [],
- 'key_concerns': []
- }
-
- all_strengths = []
- all_concerns = []
-
- for name, analysis in analyses.items():
- if 'error' not in analysis:
- all_strengths.extend(analysis.get('strengths', []))
- all_concerns.extend(analysis.get('concerns', []))
-
- # Find common themes
- consensus['economic_conditions'] = self._find_common_themes(all_strengths, threshold=0.4)
- consensus['key_concerns'] = self._find_common_themes(all_concerns, threshold=0.3)
-
- return consensus
-
- def _identify_divergences(self, analyses: Dict[str, Any]) -> Dict[str, Any]:
- """Identify major divergences between agents"""
- divergences = {
- 'health_score_divergence': 0,
- 'ideological_gaps': [],
- 'policy_conflicts': []
- }
-
- health_scores = []
- for name, analysis in analyses.items():
- if 'error' not in analysis and 'overall_health_score' in analysis:
- health_scores.append(analysis['overall_health_score'])
-
- if len(health_scores) > 1:
- divergences['health_score_divergence'] = max(health_scores) - min(health_scores)
-
- # Identify ideological gaps
- divergences['ideological_gaps'] = self._find_ideological_gaps(analyses)
-
- return divergences
-
- def _compare_policies(self, agents: Dict[str, EconomicAgent], data: EconomicData, analyses: Dict[str, Any]) -> Dict[str, Any]:
- """Compare policy recommendations across agents"""
- policy_comparison = {
- 'common_recommendations': [],
- 'conflicting_recommendations': [],
- 'unique_recommendations': {}
- }
-
- all_policies = {}
- for name, agent in agents.items():
- if name in analyses and 'error' not in analyses[name]:
- try:
- policies = agent.get_policy_recommendations(data, analyses[name])
- all_policies[name] = [p.title for p in policies]
- except Exception as e:
- print(f"Error getting policies from {name}: {e}")
- all_policies[name] = []
-
- # Find common recommendations
- if all_policies:
- policy_sets = [set(policies) for policies in all_policies.values()]
- if policy_sets:
- common = set.intersection(*policy_sets)
- policy_comparison['common_recommendations'] = list(common)
-
- # Find unique recommendations for each agent
- for name, policies in all_policies.items():
- other_policies = set()
- for other_name, other_policies_list in all_policies.items():
- if other_name != name:
- other_policies.update(other_policies_list)
-
- unique = set(policies) - other_policies
- if unique:
- policy_comparison['unique_recommendations'][name] = list(unique)
-
- return policy_comparison
-
- def _categorize_policy(self, policy_title: str) -> str:
- """Categorize policy based on keywords in title"""
- title_lower = policy_title.lower()
-
- if any(word in title_lower for word in ['tax', 'revenue', 'fiscal']):
- return 'fiscal'
- elif any(word in title_lower for word in ['spending', 'investment', 'infrastructure']):
- return 'expenditure'
- elif any(word in title_lower for word in ['trade', 'tariff', 'import', 'export']):
- return 'trade'
- elif any(word in title_lower for word in ['regulation', 'deregulation', 'compliance']):
- return 'regulation'
- elif any(word in title_lower for word in ['monetary', 'interest', 'inflation']):
- return 'monetary'
- elif any(word in title_lower for word in ['labor', 'employment', 'wage']):
- return 'labor'
- elif any(word in title_lower for word in ['social', 'welfare', 'healthcare', 'education']):
- return 'social'
- else:
- return 'other'
-
- def _find_policy_overlaps(self, policy_categories: Dict[str, List]) -> List[Dict[str, Any]]:
- """Find overlapping policy recommendations"""
- overlaps = []
-
- for category, policies in policy_categories.items():
- if len(policies) > 1:
- # Multiple agents recommend similar policies in this category
- overlaps.append({
- 'category': category,
- 'supporting_agents': [p['agent'] for p in policies],
- 'policy_count': len(policies),
- 'example_policies': [p['policy'].title for p in policies[:3]]
- })
-
- return overlaps
-
- def _find_policy_conflicts(self, policy_categories: Dict[str, List]) -> List[Dict[str, Any]]:
- """Find conflicting policy recommendations"""
- conflicts = []
-
- # Check for classic policy conflicts
- conflict_pairs = [
- ('fiscal', 'monetary'), # Tax increases vs interest rate cuts
- ('trade', 'expenditure'), # Trade barriers vs spending
- ]
-
- for category1, category2 in conflict_pairs:
- if category1 in policy_categories and category2 in policy_categories:
- agents1 = set(p['agent'] for p in policy_categories[category1])
- agents2 = set(p['agent'] for p in policy_categories[category2])
-
- common_agents = agents1.intersection(agents2)
- if common_agents:
- conflicts.append({
- 'type': f'{category1}_vs_{category2}',
- 'conflicting_categories': [category1, category2],
- 'agents_with_conflicts': list(common_agents)
- })
-
- return conflicts
-
- def _calculate_policy_support(self, policy_categories: Dict[str, List], total_agents: int) -> Dict[str, float]:
- """Calculate support percentage for each policy category"""
- support = {}
-
- for category, policies in policy_categories.items():
- supporting_agents = set(p['agent'] for p in policies)
- support_percentage = (len(supporting_agents) / total_agents) * 100
- support[category] = support_percentage
-
- return support
-
- def _synthesize_policy_recommendations(self, policy_categories: Dict[str, List], support: Dict[str, float]) -> List[Dict[str, Any]]:
- """Synthesize policy recommendations based on agent consensus"""
- synthesized = []
-
- for category, support_level in support.items():
- if support_level >= 50: # Majority support
- synthesized.append({
- 'category': category,
- 'support_level': support_level,
- 'recommendation': f"Strong consideration for {category}-focused policies",
- 'priority': 'high' if support_level >= 75 else 'medium'
- })
- elif support_level >= 33: # Significant minority
- synthesized.append({
- 'category': category,
- 'support_level': support_level,
- 'recommendation': f"Consider {category}-policies for balanced approach",
- 'priority': 'medium'
- })
-
- return sorted(synthesized, key=lambda x: x['support_level'], reverse=True)
-
- def _calculate_scenario_metrics(self, analyses: Dict[str, Any]) -> Dict[str, Any]:
- """Calculate metrics for a specific scenario"""
- metrics = {
- 'agent_count': len(analyses),
- 'average_health_score': 0,
- 'health_score_range': 0,
- 'consensus_level': 0
- }
-
- health_scores = []
- for name, analysis in analyses.items():
- if 'error' not in analysis and 'overall_health_score' in analysis:
- health_scores.append(analysis['overall_health_score'])
-
- if health_scores:
- metrics['average_health_score'] = statistics.mean(health_scores)
- metrics['health_score_range'] = max(health_scores) - min(health_scores)
- metrics['consensus_level'] = 100 - (metrics['health_score_range'] / 2) # Simple consensus measure
-
- return metrics
-
- def _compare_agent_performance(self, scenario_results: Dict[str, Any]) -> Dict[str, Dict[str, float]]:
- """Compare agent performance across all scenarios"""
- agent_performance = {}
-
- # Collect performance data for each agent
- for scenario_name, scenario_data in scenario_results.items():
- for agent_name, analysis in scenario_data['analyses'].items():
- if 'error' not in analysis and 'overall_health_score' in analysis:
- if agent_name not in agent_performance:
- agent_performance[agent_name] = []
- agent_performance[agent_name].append(analysis['overall_health_score'])
-
- # Calculate performance statistics
- performance_summary = {}
- for agent_name, scores in agent_performance.items():
- performance_summary[agent_name] = {
- 'average_score': statistics.mean(scores),
- 'score_variance': statistics.stdev(scores) if len(scores) > 1 else 0,
- 'max_score': max(scores),
- 'min_score': min(scores),
- 'scenario_count': len(scores)
- }
-
- return performance_summary
-
- def _identify_best_performers(self, scenario_results: Dict[str, Any]) -> Dict[str, List[str]]:
- """Identify best performing agents for different criteria"""
- best_performers = {}
-
- # Best average performer
- agent_performance = self._compare_agent_performance(scenario_results)
- if agent_performance:
- best_average = max(agent_performance.items(), key=lambda x: x[1]['average_score'])
- best_performers['best_average'] = [best_average[0]]
-
- # Most consistent (lowest variance)
- most_consistent = min(agent_performance.items(), key=lambda x: x[1]['score_variance'])
- best_performers['most_consistent'] = [most_consistent[0]]
-
- # Best individual scenario performance
- best_scenario_scores = {}
- for scenario_name, scenario_data in scenario_results.items():
- best_agent = None
- best_score = -1
- for agent_name, analysis in scenario_data['analyses'].items():
- if 'error' not in analysis and 'overall_health_score' in analysis:
- if analysis['overall_health_score'] > best_score:
- best_score = analysis['overall_health_score']
- best_agent = agent_name
- if best_agent:
- if best_agent not in best_scenario_scores:
- best_scenario_scores[best_agent] = 0
- best_scenario_scores[best_agent] += 1
-
- if best_scenario_scores:
- best_overall = max(best_scenario_scores.items(), key=lambda x: x[1])
- best_performers['best_scenario_performance'] = [best_overall[0]]
-
- return best_performers
-
- def _generate_scenario_summary(self, scenario_results: Dict[str, Any]) -> str:
- """Generate a summary of scenario analysis"""
- total_scenarios = len(scenario_results)
- agent_performance = self._compare_agent_performance(scenario_results)
-
- if not agent_performance:
- return "Unable to generate scenario summary due to lack of valid analyses."
-
- best_agent = max(agent_performance.items(), key=lambda x: x[1]['average_score'])
- most_consistent = min(agent_performance.items(), key=lambda x: x[1]['score_variance'])
-
- return (f"Analyzed {total_scenarios} scenarios. "
- f"Best overall performer: {best_agent[0]} "
- f"(avg score: {best_agent[1]['average_score']:.1f}). "
- f"Most consistent: {most_consistent[0]} "
- f"(variance: {most_consistent[1]['score_variance']:.1f}).")
-
- def _generate_comparison_summary(self, analyses: Dict[str, Any], metrics: Dict[str, Any]) -> str:
- """Generate a summary of the comparison"""
- if not analyses:
- return "No valid analyses available for comparison."
-
- avg_health = metrics.get('average_health_score', 0)
- diversity = metrics.get('ideological_diversity', 0)
-
- summary = f"Comparison of {len(analyses)} economic ideologies. "
- summary += f"Average health score: {avg_health:.1f}/100. "
- summary += f"Ideological diversity: {diversity:.1f}/100. "
-
- if metrics.get('most_optimistic'):
- summary += f"Most optimistic: {metrics['most_optimistic']}. "
- if metrics.get('most_pessimistic'):
- summary += f"Most pessimistic: {metrics['most_pessimistic']}."
-
- return summary
-
- def _calculate_text_overlap(self, list1: List[str], list2: List[str]) -> float:
- """Calculate percentage overlap between two text lists"""
- set1 = set(list1)
- set2 = set(list2)
-
- if not set1 and not set2:
- return 100.0
- if not set1 or not set2:
- return 0.0
-
- intersection = set1.intersection(set2)
- union = set1.union(set2)
-
- return (len(intersection) / len(union)) * 100 if union else 0.0
-
- def _find_common_themes(self, text_list: List[str], threshold: float = 0.3) -> List[str]:
- """Find common themes in a list of text items"""
- if not text_list:
- return []
-
- # Count frequency of key terms
- term_frequency = defaultdict(int)
- for text in text_list:
- # Simple keyword extraction (could be made more sophisticated)
- words = text.lower().split()
- for word in words:
- if len(word) > 3: # Ignore short words
- term_frequency[word] += 1
-
- # Find terms that appear in at least threshold proportion of texts
- common_terms = [
- term for term, count in term_frequency.items()
- if count >= len(text_list) * threshold
- ]
-
- return sorted(common_terms, key=lambda x: term_frequency[x], reverse=True)[:5]
-
- def _find_ideological_gaps(self, analyses: Dict[str, Any]) -> List[str]:
- """Find major ideological gaps between analyses"""
- gaps = []
-
- health_scores = []
- for name, analysis in analyses.items():
- if 'error' not in analysis and 'overall_health_score' in analysis:
- health_scores.append((name, analysis['overall_health_score']))
-
- if len(health_scores) >= 2:
- health_scores.sort(key=lambda x: x[1])
- min_score = health_scores[0][1]
- max_score = health_scores[-1][1]
-
- if max_score - min_score > 30:
- gaps.append(f"Significant divergence in economic health assessment ({max_score - min_score:.1f} points)")
-
- return gaps
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/config.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/config.py
deleted file mode 100644
index a67b3d970..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/config.py
+++ /dev/null
@@ -1,431 +0,0 @@
-"""
-Configuration Manager for Economic Agents
-"""
-
-import json
-import os
-from typing import Dict, Any, Optional
-from pathlib import Path
-import yaml
-
-class EconomicConfig:
- """Configuration manager for economic agent settings"""
-
- def __init__(self, config_file: Optional[str] = None):
- self.config_file = config_file or self._get_default_config_path()
- self.config = self._load_default_config()
- self.load_config()
-
- def _get_default_config_path(self) -> str:
- """Get default configuration file path"""
- # Try multiple locations
- possible_paths = [
- os.path.expanduser("~/.economic_agents/config.json"),
- os.path.join(os.getcwd(), "config.json"),
- os.path.join(os.path.dirname(__file__), "default_config.json")
- ]
-
- for path in possible_paths:
- if os.path.exists(path):
- return path
-
- # Return the first one for creation
- return possible_paths[0]
-
- def _load_default_config(self) -> Dict[str, Any]:
- """Load default configuration"""
- return {
- "analysis": {
- "default_weights": {
- "market_efficiency": 0.25,
- "social_welfare": 0.25,
- "economic_stability": 0.25,
- "growth_potential": 0.25
- },
- "scoring_ranges": {
- "gdp_growth": {"min": -10, "max": 20},
- "inflation": {"min": -5, "max": 25},
- "unemployment": {"min": 0, "max": 30},
- "interest_rate": {"min": 0, "max": 25},
- "tax_rate": {"min": 0, "max": 80},
- "government_spending": {"min": 0, "max": 100},
- "private_investment": {"min": 0, "max": 80},
- "consumer_confidence": {"min": 0, "max": 150}
- },
- "thresholds": {
- "excellent": 80,
- "good": 60,
- "moderate": 40,
- "poor": 0
- }
- },
- "agents": {
- "capitalism": {
- "enabled": True,
- "weights": {
- "market_efficiency": 0.4,
- "investment_attractiveness": 0.3,
- "economic_freedom": 0.2,
- "competitiveness": 0.1
- },
- "parameters": {
- "optimal_tax_rate": 25,
- "optimal_spending": 20,
- "inflation_target": 2.5
- }
- },
- "socialism": {
- "enabled": True,
- "weights": {
- "equality_index": 0.3,
- "social_welfare": 0.3,
- "workers_protection": 0.2,
- "public_services": 0.2
- },
- "parameters": {
- "optimal_tax_rate": 45,
- "optimal_spending": 40,
- "unemployment_target": 4
- }
- },
- "mixed_economy": {
- "enabled": True,
- "weights": {
- "balance_score": 0.3,
- "stability_score": 0.25,
- "efficiency_equity": 0.25,
- "regulatory_effectiveness": 0.2
- },
- "parameters": {
- "optimal_tax_rate": 30,
- "optimal_spending": 35,
- "inflation_target": 2.5
- }
- },
- "keynesian": {
- "enabled": True,
- "weights": {
- "aggregate_demand": 0.3,
- "fiscal_stance": 0.25,
- "monetary_stance": 0.25,
- "employment_gap": 0.2
- },
- "parameters": {
- "target_unemployment": 5,
- "target_inflation": 2.5,
- "recession_threshold": 1.5
- }
- },
- "neoliberal": {
- "enabled": True,
- "weights": {
- "market_freedom": 0.35,
- "liberalization": 0.25,
- "fiscal_discipline": 0.25,
- "globalization": 0.15
- },
- "parameters": {
- "optimal_tax_rate": 20,
- "optimal_spending": 15,
- "inflation_target": 2
- }
- },
- "mercantilism": {
- "enabled": True,
- "weights": {
- "trade_balance": 0.35,
- "self_sufficiency": 0.25,
- "protection_score": 0.25,
- "national_accumulation": 0.15
- },
- "parameters": {
- "optimal_trade_surplus": 5,
- "target_self_sufficiency": 70
- }
- }
- },
- "data_sources": {
- "default_format": "json",
- "date_format": "%Y-%m-%d",
- "interpolation_method": "linear",
- "validation_level": "standard"
- },
- "output": {
- "default_format": "text",
- "decimal_places": 2,
- "include_timestamps": True,
- "color_output": True
- },
- "comparison": {
- "weights": {
- "health_score": 0.3,
- "policy_alignment": 0.25,
- "consistency": 0.2,
- "feasibility": 0.15,
- "stability": 0.1
- },
- "consensus_threshold": 60,
- "divergence_threshold": 30
- },
- "api": {
- "default_timeout": 30,
- "retry_attempts": 3,
- "rate_limit": 100
- }
- }
-
- def load_config(self):
- """Load configuration from file"""
- if not os.path.exists(self.config_file):
- self.save_config() # Create default config file
- return
-
- try:
- with open(self.config_file, 'r') as f:
- if self.config_file.endswith('.yaml') or self.config_file.endswith('.yml'):
- file_config = yaml.safe_load(f)
- else:
- file_config = json.load(f)
-
- # Merge with default config
- self._deep_update(self.config, file_config)
-
- except Exception as e:
- print(f"Warning: Could not load config file {self.config_file}: {e}")
- print("Using default configuration.")
-
- def save_config(self):
- """Save current configuration to file"""
- # Create directory if it doesn't exist
- os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
-
- try:
- with open(self.config_file, 'w') as f:
- if self.config_file.endswith('.yaml') or self.config_file.endswith('.yml'):
- yaml.dump(self.config, f, default_flow_style=False, indent=2)
- else:
- json.dump(self.config, f, indent=2)
-
- except Exception as e:
- print(f"Error saving config file: {e}")
-
- def get(self, key: str, default: Any = None) -> Any:
- """Get configuration value using dot notation"""
- keys = key.split('.')
- value = self.config
-
- for k in keys:
- if isinstance(value, dict) and k in value:
- value = value[k]
- else:
- return default
-
- return value
-
- def set(self, key: str, value: Any):
- """Set configuration value using dot notation"""
- keys = key.split('.')
- config = self.config
-
- for k in keys[:-1]:
- if k not in config:
- config[k] = {}
- config = config[k]
-
- config[keys[-1]] = value
-
- def get_agent_config(self, agent_name: str) -> Dict[str, Any]:
- """Get configuration for specific agent"""
- return self.get(f'agents.{agent_name}', {})
-
- def get_agent_weights(self, agent_name: str) -> Dict[str, float]:
- """Get weights for specific agent"""
- agent_config = self.get_agent_config(agent_name)
- return agent_config.get('weights', {})
-
- def get_agent_parameters(self, agent_name: str) -> Dict[str, Any]:
- """Get parameters for specific agent"""
- agent_config = self.get_agent_config(agent_name)
- return agent_config.get('parameters', {})
-
- def is_agent_enabled(self, agent_name: str) -> bool:
- """Check if agent is enabled"""
- return self.get(f'agents.{agent_name}.enabled', True)
-
- def enable_agent(self, agent_name: str):
- """Enable specific agent"""
- self.set(f'agents.{agent_name}.enabled', True)
-
- def disable_agent(self, agent_name: str):
- """Disable specific agent"""
- self.set(f'agents.{agent_name}.enabled', False)
-
- def update_agent_weights(self, agent_name: str, weights: Dict[str, float]):
- """Update weights for specific agent"""
- self.set(f'agents.{agent_name}.weights', weights)
-
- def update_agent_parameters(self, agent_name: str, parameters: Dict[str, Any]):
- """Update parameters for specific agent"""
- self.set(f'agents.{agent_name}.parameters', parameters)
-
- def get_output_config(self) -> Dict[str, Any]:
- """Get output configuration"""
- return self.get('output', {})
-
- def set_output_config(self, config: Dict[str, Any]):
- """Set output configuration"""
- for key, value in config.items():
- self.set(f'output.{key}', value)
-
- def get_data_source_config(self) -> Dict[str, Any]:
- """Get data source configuration"""
- return self.get('data_sources', {})
-
- def set_data_source_config(self, config: Dict[str, Any]):
- """Set data source configuration"""
- for key, value in config.items():
- self.set(f'data_sources.{key}', value)
-
- def get_comparison_config(self) -> Dict[str, Any]:
- """Get comparison configuration"""
- return self.get('comparison', {})
-
- def get_analysis_config(self) -> Dict[str, Any]:
- """Get analysis configuration"""
- return self.get('analysis', {})
-
- def reset_to_defaults(self):
- """Reset configuration to defaults"""
- self.config = self._load_default_config()
-
- def validate_config(self) -> List[str]:
- """Validate configuration and return list of issues"""
- issues = []
-
- # Check agent configurations
- for agent_name in ['capitalism', 'socialism', 'mixed_economy', 'keynesian', 'neoliberal', 'mercantilism']:
- agent_config = self.get_agent_config(agent_name)
-
- if not agent_config:
- issues.append(f"Missing configuration for agent: {agent_name}")
- continue
-
- # Check weights sum to 1.0 (approximately)
- weights = agent_config.get('weights', {})
- if weights:
- weight_sum = sum(weights.values())
- if abs(weight_sum - 1.0) > 0.1:
- issues.append(f"Agent {agent_name} weights don't sum to 1.0: {weight_sum}")
-
- # Check required parameters exist
- required_params = self._get_required_parameters(agent_name)
- parameters = agent_config.get('parameters', {})
- for param in required_params:
- if param not in parameters:
- issues.append(f"Agent {agent_name} missing required parameter: {param}")
-
- # Check analysis configuration
- analysis_config = self.get_analysis_config()
- thresholds = analysis_config.get('thresholds', {})
- if not thresholds:
- issues.append("Missing analysis thresholds configuration")
-
- # Check data source configuration
- data_config = self.get_data_source_config()
- if not data_config.get('default_format'):
- issues.append("Missing default data format configuration")
-
- return issues
-
- def _get_required_parameters(self, agent_name: str) -> List[str]:
- """Get list of required parameters for agent"""
- required_params = {
- 'capitalism': ['optimal_tax_rate', 'optimal_spending'],
- 'socialism': ['optimal_tax_rate', 'optimal_spending'],
- 'mixed_economy': ['optimal_tax_rate', 'optimal_spending'],
- 'keynesian': ['target_unemployment', 'target_inflation'],
- 'neoliberal': ['optimal_tax_rate', 'optimal_spending'],
- 'mercantilism': ['optimal_trade_surplus']
- }
- return required_params.get(agent_name, [])
-
- def _deep_update(self, base_dict: Dict, update_dict: Dict):
- """Deep update dictionary"""
- for key, value in update_dict.items():
- if key in base_dict and isinstance(base_dict[key], dict) and isinstance(value, dict):
- self._deep_update(base_dict[key], value)
- else:
- base_dict[key] = value
-
- def export_config(self, filepath: str):
- """Export configuration to file"""
- try:
- with open(filepath, 'w') as f:
- if filepath.endswith('.yaml') or filepath.endswith('.yml'):
- yaml.dump(self.config, f, default_flow_style=False, indent=2)
- else:
- json.dump(self.config, f, indent=2)
- print(f"Configuration exported to {filepath}")
- except Exception as e:
- print(f"Error exporting configuration: {e}")
-
- def import_config(self, filepath: str):
- """Import configuration from file"""
- try:
- with open(filepath, 'r') as f:
- if filepath.endswith('.yaml') or filepath.endswith('.yml'):
- imported_config = yaml.safe_load(f)
- else:
- imported_config = json.load(f)
-
- self._deep_update(self.config, imported_config)
- print(f"Configuration imported from {filepath}")
- except Exception as e:
- print(f"Error importing configuration: {e}")
-
- def get_summary(self) -> str:
- """Get configuration summary"""
- summary = []
- summary.append("Economic Agents Configuration Summary:")
- summary.append("-" * 40)
-
- # Enabled agents
- enabled_agents = []
- for agent_name in ['capitalism', 'socialism', 'mixed_economy', 'keynesian', 'neoliberal', 'mercantilism']:
- if self.is_agent_enabled(agent_name):
- enabled_agents.append(agent_name)
-
- summary.append(f"Enabled Agents: {', '.join(enabled_agents)}")
- summary.append(f"Config File: {self.config_file}")
- summary.append(f"Default Output Format: {self.get('output.default_format', 'text')}")
- summary.append(f"Default Data Format: {self.get('data_sources.default_format', 'json')}")
- summary.append(f"Analysis Thresholds: Excellent={self.get('analysis.thresholds.excellent')}, "
- f"Good={self.get('analysis.thresholds.good')}, "
- f"Moderate={self.get('analysis.thresholds.moderate')}")
-
- return "\n".join(summary)
-
-
-# Global configuration instance
-_config_instance = None
-
-def get_config() -> EconomicConfig:
- """Get global configuration instance"""
- global _config_instance
- if _config_instance is None:
- _config_instance = EconomicConfig()
- return _config_instance
-
-def reload_config():
- """Reload global configuration"""
- global _config_instance
- if _config_instance is not None:
- _config_instance.load_config()
- else:
- _config_instance = EconomicConfig()
-
-def save_config():
- """Save global configuration"""
- global _config_instance
- if _config_instance is not None:
- _config_instance.save_config()
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/data_processor.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/data_processor.py
deleted file mode 100644
index 333a147f7..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/data_processor.py
+++ /dev/null
@@ -1,488 +0,0 @@
-"""
-Data processor for handling different economic data formats and sources
-"""
-
-import json
-import csv
-import xml.etree.ElementTree as ET
-import pandas as pd
-from typing import Dict, List, Any, Union, Optional, Tuple
-from datetime import datetime, date
-from pathlib import Path
-import requests
-import sqlite3
-from base_agent import EconomicData
-
-class EconomicDataProcessor:
- """Processes economic data from various sources and formats"""
-
- def __init__(self):
- self.supported_formats = ['json', 'csv', 'xml', 'excel', 'sqlite', 'api']
- self.data_cache = {}
-
- def load_from_json(self, filepath: str) -> Union[EconomicData, List[EconomicData]]:
- """
- Load economic data from JSON file
-
- Args:
- filepath (str): Path to JSON file
-
- Returns:
- Union[EconomicData, List[EconomicData]]: Loaded economic data
- """
- try:
- with open(filepath, 'r') as f:
- data = json.load(f)
-
- if isinstance(data, dict):
- return self._dict_to_economic_data(data)
- elif isinstance(data, list):
- return [self._dict_to_economic_data(item) for item in data]
- else:
- raise ValueError("Invalid JSON structure")
-
- except Exception as e:
- raise Exception(f"Error loading JSON file: {e}")
-
- def load_from_csv(self, filepath: str, date_column: str = "timestamp") -> List[EconomicData]:
- """
- Load economic data from CSV file
-
- Args:
- filepath (str): Path to CSV file
- date_column (str): Name of the date column
-
- Returns:
- List[EconomicData]: List of economic data points
- """
- try:
- df = pd.read_csv(filepath)
- data_points = []
-
- for _, row in df.iterrows():
- try:
- # Handle date parsing
- timestamp = self._parse_date(row[date_column]) if date_column in row else datetime.now()
-
- data_point = EconomicData(
- gdp=float(row.get('gdp', 0)),
- inflation=float(row.get('inflation', 0)),
- unemployment=float(row.get('unemployment', 0)),
- interest_rate=float(row.get('interest_rate', 0)),
- trade_balance=float(row.get('trade_balance', 0)),
- government_spending=float(row.get('government_spending', 0)),
- tax_rate=float(row.get('tax_rate', 0)),
- private_investment=float(row.get('private_investment', 0)),
- consumer_confidence=float(row.get('consumer_confidence', 0)),
- timestamp=timestamp
- )
- data_points.append(data_point)
- except (ValueError, KeyError) as e:
- print(f"Skipping invalid row: {e}")
- continue
-
- return data_points
-
- except Exception as e:
- raise Exception(f"Error loading CSV file: {e}")
-
- def load_from_xml(self, filepath: str) -> List[EconomicData]:
- """
- Load economic data from XML file
-
- Args:
- filepath (str): Path to XML file
-
- Returns:
- List[EconomicData]: List of economic data points
- """
- try:
- tree = ET.parse(filepath)
- root = tree.getroot()
- data_points = []
-
- for data_point in root.findall('data_point'):
- try:
- data = EconomicData(
- gdp=float(data_point.find('gdp').text) if data_point.find('gdp') is not None else 0,
- inflation=float(data_point.find('inflation').text) if data_point.find('inflation') is not None else 0,
- unemployment=float(data_point.find('unemployment').text) if data_point.find('unemployment') is not None else 0,
- interest_rate=float(data_point.find('interest_rate').text) if data_point.find('interest_rate') is not None else 0,
- trade_balance=float(data_point.find('trade_balance').text) if data_point.find('trade_balance') is not None else 0,
- government_spending=float(data_point.find('government_spending').text) if data_point.find('government_spending') is not None else 0,
- tax_rate=float(data_point.find('tax_rate').text) if data_point.find('tax_rate') is not None else 0,
- private_investment=float(data_point.find('private_investment').text) if data_point.find('private_investment') is not None else 0,
- consumer_confidence=float(data_point.find('consumer_confidence').text) if data_point.find('consumer_confidence') is not None else 0,
- timestamp=self._parse_date(data_point.find('timestamp').text) if data_point.find('timestamp') is not None else datetime.now()
- )
- data_points.append(data)
- except (ValueError, AttributeError) as e:
- print(f"Skipping invalid XML element: {e}")
- continue
-
- return data_points
-
- except Exception as e:
- raise Exception(f"Error loading XML file: {e}")
-
- def load_from_excel(self, filepath: str, sheet_name: str = "EconomicData") -> List[EconomicData]:
- """
- Load economic data from Excel file
-
- Args:
- filepath (str): Path to Excel file
- sheet_name (str): Name of the sheet containing data
-
- Returns:
- List[EconomicData]: List of economic data points
- """
- try:
- df = pd.read_excel(filepath, sheet_name=sheet_name)
- # Convert DataFrame to CSV format for processing
- csv_data = df.to_csv(index=False)
-
- # Save temporary CSV and use CSV loader
- import tempfile
- with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as tmp:
- tmp.write(csv_data)
- tmp_path = tmp.name
-
- try:
- data = self.load_from_csv(tmp_path)
- return data
- finally:
- Path(tmp_path).unlink() # Clean up temporary file
-
- except Exception as e:
- raise Exception(f"Error loading Excel file: {e}")
-
- def load_from_sqlite(self, db_path: str, table_name: str = "economic_data") -> List[EconomicData]:
- """
- Load economic data from SQLite database
-
- Args:
- db_path (str): Path to SQLite database
- table_name (str): Name of the table containing economic data
-
- Returns:
- List[EconomicData]: List of economic data points
- """
- try:
- conn = sqlite3.connect(db_path)
- cursor = conn.cursor()
-
- query = f"SELECT * FROM {table_name}"
- cursor.execute(query)
- rows = cursor.fetchall()
- columns = [desc[0] for desc in cursor.description]
- conn.close()
-
- data_points = []
- for row in rows:
- row_dict = dict(zip(columns, row))
- data_point = EconomicData(
- gdp=float(row_dict.get('gdp', 0)),
- inflation=float(row_dict.get('inflation', 0)),
- unemployment=float(row_dict.get('unemployment', 0)),
- interest_rate=float(row_dict.get('interest_rate', 0)),
- trade_balance=float(row_dict.get('trade_balance', 0)),
- government_spending=float(row_dict.get('government_spending', 0)),
- tax_rate=float(row_dict.get('tax_rate', 0)),
- private_investment=float(row_dict.get('private_investment', 0)),
- consumer_confidence=float(row_dict.get('consumer_confidence', 0)),
- timestamp=self._parse_date(row_dict.get('timestamp')) if row_dict.get('timestamp') else datetime.now()
- )
- data_points.append(data_point)
-
- return data_points
-
- except Exception as e:
- raise Exception(f"Error loading from SQLite: {e}")
-
- def fetch_from_api(self, api_url: str, api_key: Optional[str] = None, headers: Optional[Dict] = None) -> Dict[str, Any]:
- """
- Fetch economic data from API
-
- Args:
- api_url (str): API endpoint URL
- api_key (Optional[str]): API authentication key
- headers (Optional[Dict]): Additional headers
-
- Returns:
- Dict[str, Any]: API response data
- """
- try:
- if headers is None:
- headers = {}
-
- if api_key:
- headers['Authorization'] = f'Bearer {api_key}'
-
- response = requests.get(api_url, headers=headers, timeout=30)
- response.raise_for_status()
-
- return response.json()
-
- except Exception as e:
- raise Exception(f"Error fetching from API: {e}")
-
- def save_to_json(self, data: Union[EconomicData, List[EconomicData]], filepath: str) -> bool:
- """
- Save economic data to JSON file
-
- Args:
- data: Economic data to save
- filepath (str): Output file path
-
- Returns:
- bool: Success status
- """
- try:
- if isinstance(data, EconomicData):
- json_data = self._economic_data_to_dict(data)
- else:
- json_data = [self._economic_data_to_dict(item) for item in data]
-
- with open(filepath, 'w') as f:
- json.dump(json_data, f, indent=2, default=str)
-
- return True
-
- except Exception as e:
- print(f"Error saving to JSON: {e}")
- return False
-
- def save_to_csv(self, data: List[EconomicData], filepath: str) -> bool:
- """
- Save economic data to CSV file
-
- Args:
- data: List of economic data points
- filepath (str): Output file path
-
- Returns:
- bool: Success status
- """
- try:
- data_dicts = [self._economic_data_to_dict(item) for item in data]
-
- with open(filepath, 'w', newline='') as csvfile:
- fieldnames = ['timestamp', 'gdp', 'inflation', 'unemployment',
- 'interest_rate', 'trade_balance', 'government_spending',
- 'tax_rate', 'private_investment', 'consumer_confidence']
- writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
- writer.writeheader()
- writer.writerows(data_dicts)
-
- return True
-
- except Exception as e:
- print(f"Error saving to CSV: {e}")
- return False
-
- def validate_data_consistency(self, data: List[EconomicData]) -> Tuple[bool, List[str]]:
- """
- Validate consistency of economic data
-
- Args:
- data: List of economic data points
-
- Returns:
- Tuple[bool, List[str]]: (is_valid, list of issues)
- """
- issues = []
-
- if not data:
- issues.append("No data provided")
- return False, issues
-
- # Check for duplicate timestamps
- timestamps = [dp.timestamp for dp in data]
- if len(timestamps) != len(set(timestamps)):
- issues.append("Duplicate timestamps found")
-
- # Check data ranges for each point
- for i, dp in enumerate(data):
- from utils import validate_economic_data
- data_issues = validate_economic_data(dp)
- for issue in data_issues:
- issues.append(f"Data point {i}: {issue}")
-
- # Check for logical inconsistencies
- for i, dp in enumerate(data):
- # Government spending + private investment shouldn't exceed 100% of GDP
- if dp.government_spending + dp.private_investment > 100:
- issues.append(f"Data point {i}: Sum of government spending and private investment exceeds 100%")
-
- # Tax rate should be reasonable for government spending level
- if dp.government_spending > 30 and dp.tax_rate < 15:
- issues.append(f"Data point {i}: Low tax rate for high government spending")
-
- return len(issues) == 0, issues
-
- def interpolate_missing_data(self, data: List[EconomicData], method: str = "linear") -> List[EconomicData]:
- """
- Interpolate missing data points
-
- Args:
- data: List of economic data points
- method (str): Interpolation method ('linear', 'forward_fill', 'backward_fill')
-
- Returns:
- List[EconomicData]: Data with interpolated values
- """
- if len(data) < 2:
- return data
-
- # Sort data by timestamp
- sorted_data = sorted(data, key=lambda x: x.timestamp)
-
- # Convert to DataFrame for easier interpolation
- df = pd.DataFrame([self._economic_data_to_dict(dp) for dp in sorted_data])
-
- # Set timestamp as index
- df['timestamp'] = pd.to_datetime(df['timestamp'])
- df.set_index('timestamp', inplace=True)
-
- # Interpolate missing values
- if method == "linear":
- df.interpolate(method='linear', inplace=True)
- elif method == "forward_fill":
- df.fillna(method='ffill', inplace=True)
- elif method == "backward_fill":
- df.fillna(method='bfill', inplace=True)
-
- # Convert back to EconomicData objects
- result = []
- for idx, row in df.iterrows():
- data_point = EconomicData(
- gdp=float(row['gdp']),
- inflation=float(row['inflation']),
- unemployment=float(row['unemployment']),
- interest_rate=float(row['interest_rate']),
- trade_balance=float(row['trade_balance']),
- government_spending=float(row['government_spending']),
- tax_rate=float(row['tax_rate']),
- private_investment=float(row['private_investment']),
- consumer_confidence=float(row['consumer_confidence']),
- timestamp=idx.to_pydatetime()
- )
- result.append(data_point)
-
- return result
-
- def aggregate_data_by_period(self, data: List[EconomicData], period: str = "monthly") -> List[EconomicData]:
- """
- Aggregate economic data by time period
-
- Args:
- data: List of economic data points
- period (str): Aggregation period ('daily', 'weekly', 'monthly', 'quarterly', 'yearly')
-
- Returns:
- List[EconomicData]: Aggregated data
- """
- if not data:
- return []
-
- # Convert to DataFrame
- df = pd.DataFrame([self._economic_data_to_dict(dp) for dp in data])
- df['timestamp'] = pd.to_datetime(df['timestamp'])
- df.set_index('timestamp', inplace=True)
-
- # Define aggregation functions
- agg_functions = {
- 'gdp': 'mean',
- 'inflation': 'mean',
- 'unemployment': 'mean',
- 'interest_rate': 'mean',
- 'trade_balance': 'mean',
- 'government_spending': 'mean',
- 'tax_rate': 'mean',
- 'private_investment': 'mean',
- 'consumer_confidence': 'mean'
- }
-
- # Group by period and aggregate
- if period == "daily":
- resampled = df.resample('D').agg(agg_functions)
- elif period == "weekly":
- resampled = df.resample('W').agg(agg_functions)
- elif period == "monthly":
- resampled = df.resample('M').agg(agg_functions)
- elif period == "quarterly":
- resampled = df.resample('Q').agg(agg_functions)
- elif period == "yearly":
- resampled = df.resample('Y').agg(agg_functions)
- else:
- raise ValueError(f"Unsupported period: {period}")
-
- # Convert back to EconomicData objects
- result = []
- for idx, row in resampled.iterrows():
- if not pd.isna(row['gdp']): # Skip empty periods
- data_point = EconomicData(
- gdp=float(row['gdp']),
- inflation=float(row['inflation']),
- unemployment=float(row['unemployment']),
- interest_rate=float(row['interest_rate']),
- trade_balance=float(row['trade_balance']),
- government_spending=float(row['government_spending']),
- tax_rate=float(row['tax_rate']),
- private_investment=float(row['private_investment']),
- consumer_confidence=float(row['consumer_confidence']),
- timestamp=idx.to_pydatetime()
- )
- result.append(data_point)
-
- return result
-
- def _dict_to_economic_data(self, data_dict: Dict) -> EconomicData:
- """Convert dictionary to EconomicData object"""
- return EconomicData(
- gdp=float(data_dict.get('gdp', 0)),
- inflation=float(data_dict.get('inflation', 0)),
- unemployment=float(data_dict.get('unemployment', 0)),
- interest_rate=float(data_dict.get('interest_rate', 0)),
- trade_balance=float(data_dict.get('trade_balance', 0)),
- government_spending=float(data_dict.get('government_spending', 0)),
- tax_rate=float(data_dict.get('tax_rate', 0)),
- private_investment=float(data_dict.get('private_investment', 0)),
- consumer_confidence=float(data_dict.get('consumer_confidence', 0)),
- timestamp=self._parse_date(data_dict.get('timestamp')) if data_dict.get('timestamp') else datetime.now()
- )
-
- def _economic_data_to_dict(self, data: EconomicData) -> Dict:
- """Convert EconomicData object to dictionary"""
- return {
- 'timestamp': data.timestamp.isoformat(),
- 'gdp': data.gdp,
- 'inflation': data.inflation,
- 'unemployment': data.unemployment,
- 'interest_rate': data.interest_rate,
- 'trade_balance': data.trade_balance,
- 'government_spending': data.government_spending,
- 'tax_rate': data.tax_rate,
- 'private_investment': data.private_investment,
- 'consumer_confidence': data.consumer_confidence
- }
-
- def _parse_date(self, date_value: Any) -> datetime:
- """Parse date from various formats"""
- if isinstance(date_value, datetime):
- return date_value
- elif isinstance(date_value, date):
- return datetime.combine(date_value, datetime.min.time())
- elif isinstance(date_value, str):
- try:
- return datetime.fromisoformat(date_value)
- except ValueError:
- try:
- return datetime.strptime(date_value, "%Y-%m-%d")
- except ValueError:
- try:
- return datetime.strptime(date_value, "%Y-%m-%d %H:%M:%S")
- except ValueError:
- return datetime.now()
- else:
- return datetime.now()
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/example_usage.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/example_usage.py
deleted file mode 100644
index 36409166f..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/example_usage.py
+++ /dev/null
@@ -1,179 +0,0 @@
-"""
-Example Usage of Economic Agents
-Demonstrates how to use different economic ideology agents to analyze the same economic data
-"""
-
-from datetime import datetime
-from base_agent import EconomicData
-from capitalism_agent import CapitalismAgent
-from socialism_agent import SocialismAgent
-from mixed_economy_agent import MixedEconomyAgent
-from keynesian_agent import KeynesianAgent
-from neoliberal_agent import NeoliberalAgent
-from mercantilist_agent import MercantilistAgent
-
-def main():
- """Example usage of all economic agents"""
-
- # Create sample economic data
- sample_data = EconomicData(
- gdp=3.2, # GDP growth rate (%)
- inflation=2.8, # Inflation rate (%)
- unemployment=5.5, # Unemployment rate (%)
- interest_rate=4.2, # Interest rate (%)
- trade_balance=2.1, # Trade balance (% of GDP, positive = surplus)
- government_spending=32.5, # Government spending (% of GDP)
- tax_rate=28.0, # Average tax rate (%)
- private_investment=22.3, # Private investment (% of GDP)
- consumer_confidence=67.8, # Consumer confidence index (0-100)
- timestamp=datetime.now()
- )
-
- # Initialize all agents
- agents = {
- "Capitalism": CapitalismAgent(),
- "Socialism": SocialismAgent(),
- "Mixed Economy": MixedEconomyAgent(),
- "Keynesian": KeynesianAgent(),
- "Neoliberal": NeoliberalAgent(),
- "Mercantilism": MercantilistAgent()
- }
-
- print("=" * 80)
- print("ECONOMIC ANALYSIS USING DIFFERENT IDEOLOGICAL PERSPECTIVES")
- print("=" * 80)
- print(f"\nAnalyzing economic data from {sample_data.timestamp.strftime('%Y-%m-%d %H:%M:%S')}")
- print(f"GDP Growth: {sample_data.gdp}%")
- print(f"Inflation: {sample_data.inflation}%")
- print(f"Unemployment: {sample_data.unemployment}%")
- print(f"Trade Balance: {sample_data.trade_balance}% of GDP")
- print(f"Government Spending: {sample_data.government_spending}% of GDP")
- print(f"Tax Rate: {sample_data.tax_rate}%")
- print(f"Private Investment: {sample_data.private_investment}% of GDP")
- print("-" * 80)
-
- # Analyze with each agent
- results = {}
- for name, agent in agents.items():
- print(f"\n{name.upper()} PERSPECTIVE:")
- print("-" * 40)
-
- # Get analysis
- analysis = agent.analyze_economy(sample_data)
- results[name] = analysis
-
- # Print key results
- print(f"Overall Health Score: {analysis['overall_health_score']:.1f}/100")
- print(f"Assessment: {analysis['assessment']}")
-
- # Print strengths
- if analysis['strengths']:
- print("\nStrengths:")
- for strength in analysis['strengths']:
- print(f" ✓ {strength}")
-
- # Print concerns
- if analysis['concerns']:
- print("\nConcerns:")
- for concern in analysis['concerns']:
- print(f" ⚠ {concern}")
-
- # Get top policy recommendations
- policies = agent.get_policy_recommendations(sample_data, analysis)
- if policies:
- print("\nTop Policy Recommendations:")
- for i, policy in enumerate(policies[:3], 1):
- print(f" {i}. {policy.title}")
- print(f" Priority: {policy.priority.upper()}")
- print(f" Expected Impact: {policy.expected_impact}")
-
- # Compare policy evaluation
- print("\n" + "=" * 80)
- print("POLICY EVALUATION COMPARISON")
- print("=" * 80)
-
- test_policies = [
- {"name": "Tax Cuts for Businesses", "type": "tax_cut"},
- {"name": "Increase Infrastructure Spending", "type": "infrastructure_spending"},
- {"name": "Implement Trade Tariffs", "type": "import_tariff"},
- {"name": "Free Trade Agreement", "type": "trade_liberalization"}
- ]
-
- for policy in test_policies:
- print(f"\nPolicy: {policy['name']}")
- print("-" * 50)
-
- for name, agent in agents.items():
- evaluation = agent.evaluate_policy(policy, sample_data)
- print(f"{name:12}: {evaluation['recommendation']:20} (Score: {evaluation['agent_specific_score']:.1f})")
-
- # Summary comparison
- print("\n" + "=" * 80)
- print("IDEOLOGY COMPARISON SUMMARY")
- print("=" * 80)
- print(f"{'Ideology':<15} {'Health Score':<15} {'Key Focus':<50}")
- print("-" * 80)
-
- focus_areas = {
- "Capitalism": "Market efficiency, private investment, economic freedom",
- "Socialism": "Economic equality, social welfare, workers' protection",
- "Mixed Economy": "Balance of public and private sectors, stability",
- "Keynesian": "Demand management, counter-cyclical policies",
- "Neoliberal": "Deregulation, privatization, minimal government",
- "Mercantilism": "Trade surplus, protectionism, national wealth"
- }
-
- for name, analysis in results.items():
- health_score = analysis['overall_health_score']
- focus = focus_areas.get(name, "")
- print(f"{name:<15} {health_score:<15.1f} {focus:<50}")
-
-def compare_specific_scenario():
- """Compare agents on a specific economic scenario"""
-
- print("\n" + "=" * 80)
- print("RECESSION SCENARIO ANALYSIS")
- print("=" * 80)
-
- # Create recession data
- recession_data = EconomicData(
- gdp=1.2, # Low growth
- inflation=1.5, # Low inflation
- unemployment=8.5, # High unemployment
- interest_rate=1.8, # Low interest rates
- trade_balance=-4.2, # Trade deficit
- government_spending=38.5, # High government spending
- tax_rate=35.0, # High taxes
- private_investment=15.3, # Low private investment
- consumer_confidence=42.1, # Low confidence
- timestamp=datetime.now()
- )
-
- print(f"\nRecession Scenario Data:")
- print(f"GDP Growth: {recession_data.gdp}% (Low)")
- print(f"Unemployment: {recession_data.unemployment}% (High)")
- print(f"Private Investment: {recession_data.private_investment}% (Low)")
- print(f"Consumer Confidence: {recession_data.consumer_confidence} (Low)")
- print("-" * 80)
-
- # Get Keynesian analysis specifically for recession
- keynesian = KeynesianAgent()
- keynesian_analysis = keynesian.analyze_economy(recession_data)
-
- print(f"\nKeynesian Analysis for Recession:")
- print(f"Economic Phase: {keynesian_analysis['economic_phase']}")
- print(f"Overall Score: {keynesian_analysis['overall_health_score']:.1f}/100")
-
- # Get recession-specific policies
- policies = keynesian.get_policy_recommendations(recession_data, keynesian_analysis)
- print("\nKeynesian Policy Recommendations for Recession:")
- for i, policy in enumerate(policies, 1):
- print(f"\n{i}. {policy.title}")
- print(f" {policy.description}")
- print(f" Priority: {policy.priority.upper()}")
- print(f" Expected Impact: {policy.expected_impact}")
- print(f" Implementation Time: {policy.implementation_time}")
-
-if __name__ == "__main__":
- main()
- compare_specific_scenario()
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/keynesian_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/keynesian_agent.py
deleted file mode 100644
index dfe4e266f..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/keynesian_agent.py
+++ /dev/null
@@ -1,449 +0,0 @@
-"""
-Keynesian Economics Agent
-Processes economic data through the lens of Keynesian economic principles
-"""
-
-from typing import Dict, List, Any
-from base_agent import EconomicAgent, EconomicData, PolicyRecommendation
-
-class KeynesianAgent(EconomicAgent):
- """Keynesian economics agent focusing on demand management and counter-cyclical policies"""
-
- def __init__(self):
- super().__init__(
- "Keynesian Agent",
- "Analyzes economic data through Keynesian principles emphasizing demand management, fiscal stimulus, and counter-cyclical policies"
- )
- self.principles = [
- "Aggregate demand management",
- "Counter-cyclical fiscal policy",
- "Government intervention during downturns",
- "Multiplier effect of spending",
- "Liquidity preference theory",
- "Active monetary policy"
- ]
- self.priorities = [
- "Full employment",
- "Economic stability",
- "Demand management",
- "Fiscal stimulus when needed",
- "Monetary accommodation",
- "Growth and investment"
- ]
-
- def analyze_economy(self, data: EconomicData) -> Dict[str, Any]:
- """Analyze economy from Keynesian perspective"""
-
- # Calculate Keynesian-specific metrics
- aggregate_demand_score = self._calculate_aggregate_demand_score(data)
- fiscal_stance_score = self._calculate_fiscal_stance_score(data)
- monetary_stance_score = self._calculate_monetary_stance_score(data)
- employment_gap_score = self._calculate_employment_gap_score(data)
-
- # Identify economic phase and needs
- economic_phase = self._determine_economic_phase(data)
- strengths = []
- concerns = []
-
- # Analyze based on economic phase
- if economic_phase == "recession":
- if data.government_spending > 35:
- strengths.append("Adequate government spending for stimulus")
- if data.interest_rate < 4:
- strengths.append("Accommodative monetary policy")
- if data.unemployment > 7:
- concerns.append("High unemployment requires stimulus")
- if data.consumer_confidence < 50:
- concerns.append("Weak consumer demand needs boosting")
-
- elif economic_phase == "expansion":
- if data.inflation > 4:
- concerns.append("Rising inflation requires cooling measures")
- if data.unemployment < 4:
- concerns.append("Very low unemployment may cause overheating")
- if data.government_spending > 40:
- concerns.append("Excessive spending may fuel inflation")
-
- elif economic_phase == "stable":
- if 2 <= data.inflation <= 3:
- strengths.append("Price stability maintained")
- if 4 <= data.unemployment <= 6:
- strengths.append("Sustainable employment levels")
- if data.gdp > 2 and data.gdp < 4:
- strengths.append("Stable economic growth")
-
- # General concerns
- if data.trade_balance < -8:
- concerns.append("Trade deficit may drain aggregate demand")
- if data.consumer_confidence < 60:
- concerns.append("Weak consumer confidence limits demand")
-
- # Calculate overall Keynesian health score
- health_score = (
- aggregate_demand_score * 0.3 +
- fiscal_stance_score * 0.25 +
- monetary_stance_score * 0.25 +
- employment_gap_score * 0.2
- )
-
- return {
- "ideology": "keynesian",
- "economic_phase": economic_phase,
- "aggregate_demand_score": aggregate_demand_score,
- "fiscal_stance_score": fiscal_stance_score,
- "monetary_stance_score": monetary_stance_score,
- "employment_gap_score": employment_gap_score,
- "overall_health_score": health_score,
- "strengths": strengths,
- "concerns": concerns,
- "assessment": self._generate_assessment(health_score, economic_phase, strengths, concerns),
- "key_indicators": {
- "economic_phase": economic_phase,
- "gdp_growth": data.gdp,
- "unemployment_rate": data.unemployment,
- "inflation_rate": data.inflation,
- "fiscal_stance": self._calculate_fiscal_stance(data),
- "monetary_stance": self._calculate_monetary_stance(data)
- }
- }
-
- def get_policy_recommendations(self, data: EconomicData, analysis: Dict[str, Any]) -> List[PolicyRecommendation]:
- """Generate Keynesian policy recommendations"""
- recommendations = []
- economic_phase = analysis["economic_phase"]
-
- # Recession-phase recommendations
- if economic_phase == "recession":
- recommendations.append(PolicyRecommendation(
- title="Implement Fiscal Stimulus",
- description="Increase government spending on infrastructure and public works to boost aggregate demand",
- priority="high",
- expected_impact="Increased GDP and employment through multiplier effect",
- implementation_time="3-6 months",
- risk_level="medium"
- ))
-
- recommendations.append(PolicyRecommendation(
- title="Tax Cuts for Middle and Lower Income",
- description="Targeted tax reductions to increase consumption and aggregate demand",
- priority="high",
- expected_impact="Immediate boost to consumer spending and economic activity",
- implementation_time="1-3 months",
- risk_level="low"
- ))
-
- recommendations.append(PolicyRecommendation(
- title="Expand Automatic Stabilizers",
- description="Strengthen unemployment benefits and progressive tax system",
- priority="medium",
- expected_impact="Automatic demand stabilization during downturns",
- implementation_time="6-12 months",
- risk_level="low"
- ))
-
- if data.interest_rate > 2:
- recommendations.append(PolicyRecommendation(
- title="Accommodative Monetary Policy",
- description="Lower interest rates to stimulate investment and consumption",
- priority="high",
- expected_impact="Increased private sector investment and borrowing",
- implementation_time="1-2 months",
- risk_level="low"
- ))
-
- # Expansion-phase recommendations
- elif economic_phase == "expansion":
- if data.inflation > 4:
- recommendations.append(PolicyRecommendation(
- title="Implement Fiscal Consolidation",
- description="Reduce government spending to cool overheating economy",
- priority="medium",
- expected_impact="Reduced inflationary pressures",
- implementation_time="6-18 months",
- risk_level="medium"
- ))
-
- recommendations.append(PolicyRecommendation(
- title="Tighten Monetary Policy",
- description="Raise interest rates to control inflation",
- priority="high",
- expected_impact="Reduced inflation and asset price bubbles",
- implementation_time="1-3 months",
- risk_level="medium"
- ))
-
- # Stable economy recommendations
- else:
- recommendations.append(PolicyRecommendation(
- title="Maintain Counter-Cyclical Policies",
- description="Maintain fiscal and monetary tools ready for economic fluctuations",
- priority="medium",
- expected_impact="Preparedness for future economic cycles",
- implementation_time="ongoing",
- risk_level="low"
- ))
-
- # Always recommend structural investments
- recommendations.append(PolicyRecommendation(
- title="Invest in Productive Infrastructure",
- description="Long-term infrastructure investment to increase productive capacity",
- priority="medium",
- expected_impact="Improved long-term growth potential",
- implementation_time="24-60 months",
- risk_level="medium"
- ))
-
- # Trade balance concerns
- if data.trade_balance < -8:
- recommendations.append(PolicyRecommendation(
- title="Manage Trade Balance",
- description="Policies to improve net exports and reduce trade deficit",
- priority="medium",
- expected_impact="Improved aggregate demand and economic stability",
- implementation_time="12-36 months",
- risk_level="medium"
- ))
-
- return recommendations
-
- def evaluate_policy(self, policy: Dict[str, Any], data: EconomicData) -> Dict[str, Any]:
- """Evaluate policy from Keynesian perspective"""
- policy_name = policy.get("name", "Unknown Policy")
- policy_type = policy.get("type", "unknown")
-
- # Scoring criteria for Keynesian evaluation
- scores = {
- "demand_impact": 0, # How it affects aggregate demand
- "employment_effect": 0, # How it affects employment
- "stabilization": 0, # How it contributes to economic stability
- "multiplier_effect": 0, # Fiscal multiplier potential
- "counter_cyclical": 0 # How well it works counter-cyclically
- }
-
- economic_phase = self._determine_economic_phase(data)
-
- # Evaluate based on policy type and economic context
- if policy_type == "fiscal_stimulus":
- if economic_phase == "recession":
- scores["demand_impact"] = 90
- scores["employment_effect"] = 85
- scores["stabilization"] = 80
- scores["multiplier_effect"] = 95
- scores["counter_cyclical"] = 100
- else:
- scores["demand_impact"] = 20
- scores["employment_effect"] = 30
- scores["stabilization"] = -40
- scores["multiplier_effect"] = 50
- scores["counter_cyclical"] = -60
-
- elif policy_type == "tax_cut":
- if economic_phase == "recession":
- scores["demand_impact"] = 75
- scores["employment_effect"] = 70
- scores["stabilization"] = 65
- scores["multiplier_effect"] = 80
- scores["counter_cyclical"] = 85
- else:
- scores["demand_impact"] = 40
- scores["employment_effect"] = 45
- scores["stabilization"] = -30
- scores["counter_cyclical"] = -40
-
- elif policy_type == "infrastructure_spending":
- scores["demand_impact"] = 80
- scores["employment_effect"] = 85
- scores["stabilization"] = 75
- scores["multiplier_effect"] = 90
- scores["counter_cyclical"] = 70
-
- elif policy_type == "monetary_easing":
- if economic_phase == "recession":
- scores["demand_impact"] = 70
- scores["employment_effect"] = 65
- scores["stabilization"] = 75
- scores["multiplier_effect"] = 60
- scores["counter_cyclical"] = 80
- else:
- scores["demand_impact"] = 30
- scores["employment_effect"] = 35
- scores["stabilization"] = -20
- scores["counter_cyclical"] = -30
-
- elif policy_type == "austerity":
- if economic_phase == "recession":
- scores["demand_impact"] = -80
- scores["employment_effect"] = -75
- scores["stabilization"] = -70
- scores["multiplier_effect"] = -90
- scores["counter_cyclical"] = -100
- elif economic_phase == "expansion":
- scores["demand_impact"] = 50
- scores["employment_effect"] = 45
- scores["stabilization"] = 70
- scores["multiplier_effect"] = 40
- scores["counter_cyclical"] = 80
-
- overall_score = sum(scores.values()) / len(scores)
-
- return {
- "policy_name": policy_name,
- "keynesian_score": overall_score,
- "detailed_scores": scores,
- "recommendation": self._get_policy_recommendation(overall_score),
- "justification": self._generate_policy_justification(scores, policy_type, economic_phase)
- }
-
- def _determine_economic_phase(self, data: EconomicData) -> str:
- """Determine current economic phase"""
- if data.gdp < 1.5 and data.unemployment > 7:
- return "recession"
- elif data.gdp > 4.0 or data.inflation > 4:
- return "expansion"
- else:
- return "stable"
-
- def _calculate_aggregate_demand_score(self, data: EconomicData) -> float:
- """Calculate aggregate demand score (0-100)"""
- # Consumer demand (confidence, employment)
- consumer_score = (data.consumer_confidence + max(100 - data.unemployment * 10, 0)) / 2
-
- # Investment demand (interest rates, GDP growth)
- investment_score = (max(100 - data.interest_rate * 8, 0) + min(data.gdp * 15, 100)) / 2
-
- # Government demand (spending)
- gov_score = min(data.government_spending * 2, 100)
-
- # Net exports (trade balance)
- trade_score = max(100 - abs(data.trade_balance) * 8, 0)
-
- return (consumer_score + investment_score + gov_score + trade_score) / 4
-
- def _calculate_fiscal_stance_score(self, data: EconomicData) -> float:
- """Calculate appropriate fiscal stance score (0-100)"""
- economic_phase = self._determine_economic_phase(data)
- current_stance = self._calculate_fiscal_stance(data)
-
- if economic_phase == "recession":
- # Need expansionary fiscal policy
- if current_stance == "expansionary":
- return 90
- elif current_stance == "neutral":
- return 60
- else:
- return 30
- elif economic_phase == "expansion":
- # Need contractionary fiscal policy
- if current_stance == "contractionary":
- return 90
- elif current_stance == "neutral":
- return 70
- else:
- return 40
- else:
- # Neutral is fine
- return 80
-
- def _calculate_monetary_stance_score(self, data: EconomicData) -> float:
- """Calculate appropriate monetary stance score (0-100)"""
- economic_phase = self._determine_economic_phase(data)
- current_stance = self._calculate_monetary_stance(data)
-
- if economic_phase == "recession":
- # Need accommodative monetary policy
- if current_stance == "accommodative":
- return 90
- elif current_stance == "neutral":
- return 65
- else:
- return 35
- elif economic_phase == "expansion":
- # Need tight monetary policy
- if current_stance == "tight":
- return 85
- elif current_stance == "neutral":
- return 70
- else:
- return 45
- else:
- # Neutral is good
- return 85
-
- def _calculate_employment_gap_score(self, data: EconomicData) -> float:
- """Calculate employment gap score (0-100)"""
- # Target unemployment around 5%
- target_unemployment = 5.0
- unemployment_gap = abs(data.unemployment - target_unemployment)
- return max(100 - unemployment_gap * 15, 0)
-
- def _calculate_fiscal_stance(self, data: EconomicData) -> str:
- """Determine current fiscal stance"""
- if data.government_spending > 40:
- return "expansionary"
- elif data.government_spending < 25:
- return "contractionary"
- else:
- return "neutral"
-
- def _calculate_monetary_stance(self, data: EconomicData) -> str:
- """Determine current monetary stance"""
- if data.interest_rate < 3:
- return "accommodative"
- elif data.interest_rate > 6:
- return "tight"
- else:
- return "neutral"
-
- def _generate_assessment(self, health_score: float, economic_phase: str, strengths: List[str], concerns: List[str]) -> str:
- """Generate overall assessment"""
- phase_description = {
- "recession": "in recession",
- "expansion": "in expansion",
- "stable": "stable"
- }
-
- if health_score >= 80:
- return f"Excellent Keynesian management (Score: {health_score:.1f}/100). Appropriate policies for current {phase_description[economic_phase]} phase."
- elif health_score >= 60:
- return f"Good policy approach (Score: {health_score:.1f}/100). Generally appropriate policies for current economic conditions."
- elif health_score >= 40:
- return f"Moderate policy effectiveness (Score: {health_score:.1f}/100). Some policy adjustments needed for better management."
- else:
- return f"Poor policy alignment (Score: {health_score:.1f}/100). Significant policy reforms needed for current economic phase."
-
- def _get_policy_recommendation(self, score: float) -> str:
- """Get policy recommendation based on score"""
- if score >= 70:
- return "Strongly Recommended"
- elif score >= 40:
- return "Recommended"
- elif score >= 0:
- return "Not Recommended"
- else:
- return "Strongly Opposed"
-
- def _generate_policy_justification(self, scores: Dict[str, float], policy_type: str, economic_phase: str) -> str:
- """Generate justification for policy evaluation"""
- justification = []
-
- if scores["demand_impact"] > 60:
- justification.append("Boosts aggregate demand")
- elif scores["demand_impact"] < -20:
- justification.append("Reduces aggregate demand")
-
- if scores["employment_effect"] > 60:
- justification.append("Supports full employment")
- elif scores["employment_effect"] < -20:
- justification.append("Harmful to employment")
-
- if scores["counter_cyclical"] > 60:
- justification.append("Appropriate for economic cycle")
- elif scores["counter_cyclical"] < -20:
- justification.append("Wrong timing for economic cycle")
-
- if scores["multiplier_effect"] > 60:
- justification.append("Strong multiplier effects")
- elif scores["multiplier_effect"] < 0:
- justification.append("Negative multiplier effects")
-
- return "; ".join(justification) if justification else "Mixed effects on Keynesian objectives"
\ No newline at end of file
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
deleted file mode 100644
index 2f80ad5d9..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/keynesian_agent_cli.py
+++ /dev/null
@@ -1,144 +0,0 @@
-#!/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(argv=None):
- """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(argv)
-
- try:
- parameters = json.loads(args.parameters)
- inputs = json.loads(args.inputs)
-
- result = execute_agent(parameters, inputs)
-
- result_json = json.dumps(result, indent=2)
- print(result_json)
- return result_json
- 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.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/mercantilist_agent.py
deleted file mode 100644
index 8e5aa5736..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/mercantilist_agent.py
+++ /dev/null
@@ -1,374 +0,0 @@
-"""
-Mercantilist Economic Agent
-Processes economic data through the lens of mercantilist economic principles
-"""
-
-from typing import Dict, List, Any
-from base_agent import EconomicAgent, EconomicData, PolicyRecommendation
-
-class MercantilistAgent(EconomicAgent):
- """Mercantilist economic analysis agent emphasizing trade surpluses, national wealth accumulation, and protectionism"""
-
- def __init__(self):
- super().__init__(
- "Mercantilist Agent",
- "Analyzes economic data through mercantilist principles emphasizing trade surpluses, protectionism, and national wealth accumulation"
- )
- self.principles = [
- "Trade surplus as wealth measure",
- "Export promotion",
- "Import substitution",
- "Protectionism and tariffs",
- "National self-sufficiency",
- "Colonial resource acquisition",
- "Bullion/specie accumulation"
- ]
- self.priorities = [
- "Trade surplus maximization",
- "Domestic industry protection",
- "National wealth accumulation",
- "Export competitiveness",
- "Import reduction",
- "Resource self-sufficiency"
- ]
-
- def analyze_economy(self, data: EconomicData) -> Dict[str, Any]:
- """Analyze economy from mercantilist perspective"""
-
- # Calculate mercantilist-specific metrics
- trade_balance_score = self._calculate_trade_balance_score(data)
- self_sufficiency_score = self._calculate_self_sufficiency_score(data)
- protection_score = self._calculate_protection_score(data)
- national_accumulation_score = self._calculate_national_accumulation_score(data)
-
- # Identify strengths and concerns
- strengths = []
- concerns = []
-
- # Trade performance strengths
- if data.trade_balance > 5:
- strengths.append("Strong trade surplus indicating wealth accumulation")
- if data.government_spending > 30:
- strengths.append("Strong government support for domestic industries")
- if data.private_investment > 25:
- strengths.append("Robust domestic investment in productive capacity")
-
- # National wealth strengths
- if data.gdp > 3:
- strengths.append("Strong national output and productivity")
- if data.consumer_confidence > 60:
- strengths.append("Strong domestic demand supporting national industries")
-
- # Mercantilist concerns
- if data.trade_balance < -5:
- concerns.append("Trade deficit indicates wealth outflow and dependency")
- if data.trade_balance < -10:
- concerns.append("Severe trade deficit undermining national wealth")
- if data.government_spending < 25:
- concerns.append("Insufficient government support for domestic industries")
- if data.private_investment < 20:
- concerns.append("Low domestic investment threatens self-sufficiency")
- if data.inflation > 5:
- concerns.append("High inflation erodes national wealth and competitiveness")
-
- # Import dependency concerns (inferred from negative trade balance)
- if data.trade_balance < 0:
- concerns.append(f"Import dependency costing {-data.trade_balance}% of GDP")
-
- # Calculate overall mercantilist health score
- health_score = (
- trade_balance_score * 0.35 +
- self_sufficiency_score * 0.25 +
- protection_score * 0.25 +
- national_accumulation_score * 0.15
- )
-
- return {
- "ideology": "mercantilism",
- "trade_balance_score": trade_balance_score,
- "self_sufficiency_score": self_sufficiency_score,
- "protection_score": protection_score,
- "national_accumulation_score": national_accumulation_score,
- "overall_health_score": health_score,
- "strengths": strengths,
- "concerns": concerns,
- "assessment": self._generate_assessment(health_score, strengths, concerns),
- "key_indicators": {
- "trade_surplus": data.trade_balance,
- "export_orientation": max(0, data.trade_balance),
- "import_dependency": max(0, -data.trade_balance),
- "national_productivity": data.gdp,
- "government_support": data.government_spending,
- "domestic_investment": data.private_investment
- }
- }
-
- def get_policy_recommendations(self, data: EconomicData, analysis: Dict[str, Any]) -> List[PolicyRecommendation]:
- """Generate mercantilist policy recommendations"""
- recommendations = []
-
- # Trade surplus recommendations
- if data.trade_balance < 5:
- recommendations.append(PolicyRecommendation(
- title="Implement Export Promotion Policies",
- description="Subsidies and incentives for export-oriented industries",
- priority="high",
- expected_impact="Increased exports and improved trade balance",
- implementation_time="6-18 months",
- risk_level="medium"
- ))
-
- if data.trade_balance < 0:
- recommendations.append(PolicyRecommendation(
- title="Impose Import Restrictions",
- description="Tariffs and quotas to reduce import dependency",
- priority="high",
- expected_impact="Reduced imports and improved trade balance",
- implementation_time="3-6 months",
- risk_level="low"
- ))
-
- # Industrial development recommendations
- if data.private_investment < 30:
- recommendations.append(PolicyRecommendation(
- title="Develop Domestic Industries",
- description="Government support and protection for strategic industries",
- priority="high",
- expected_impact="Increased self-sufficiency and reduced imports",
- implementation_time="24-60 months",
- risk_level="medium"
- ))
-
- # Protectionism recommendations
- recommendations.append(PolicyRecommendation(
- title="Implement Protectionist Trade Policies",
- description="Comprehensive tariff structure to protect domestic industries",
- priority="medium",
- expected_impact="Domestic industry growth and employment",
- implementation_time="3-12 months",
- risk_level="low"
- ))
-
- # Currency manipulation recommendations
- recommendations.append(PolicyRecommendation(
- title="Maintain Favorable Exchange Rate",
- description="Monetary policy to keep currency undervalued for export competitiveness",
- priority="medium",
- expected_impact="Improved export competitiveness",
- implementation_time="1-6 months",
- risk_level="medium"
- ))
-
- # Strategic resource acquisition
- recommendations.append(PolicyRecommendation(
- title="Secure Strategic Resources",
- description="Government-led acquisition of critical resources and supply chains",
- priority="medium",
- expected_impact="Reduced foreign dependency and increased security",
- implementation_time="12-48 months",
- risk_level="medium"
- ))
-
- # Colonial/resource expansion recommendations
- if data.trade_balance < -8:
- recommendations.append(PolicyRecommendation(
- title="Expand Resource Access",
- description="Secure foreign sources of raw materials and resources",
- priority="high",
- expected_impact="Reduced import dependency and cost control",
- implementation_time="24-72 months",
- risk_level="high"
- ))
-
- # Domestic savings and capital accumulation
- if data.consumer_confidence > 80:
- recommendations.append(PolicyRecommendation(
- title("Promote Domestic Savings"),
- description="Policies to increase national savings and capital accumulation",
- priority="medium",
- expected_impact="Increased domestic capital formation",
- implementation_time="12-24 months",
- risk_level="low"
- ))
-
- return recommendations
-
- def evaluate_policy(self, policy: Dict[str, Any], data: EconomicData) -> Dict[str, Any]:
- """Evaluate policy from mercantilist perspective"""
- policy_name = policy.get("name", "Unknown Policy")
- policy_type = policy.get("type", "unknown")
-
- # Scoring criteria for mercantilist evaluation
- scores = {
- "trade_balance_impact": 0, # How it affects trade balance
- "national_wealth": 0, # How it affects national wealth accumulation
- "self_sufficiency": 0, # How it affects self-sufficiency
- "domestic_industry": 0, # How it helps domestic industries
- "resource_control": 0 # How it increases resource control
- }
-
- # Evaluate based on policy type
- if policy_type == "export_subsidy":
- scores["trade_balance_impact"] = 90
- scores["domestic_industry"] = 85
- scores["national_wealth"] = 80
- scores["self_sufficiency"] = 75
- elif policy_type == "import_tariff":
- scores["trade_balance_impact"] = 85
- scores["self_sufficiency"] = 90
- scores["domestic_industry"] = 80
- scores["resource_control"] = 70
- elif policy_type == "import_quota":
- scores["trade_balance_impact"] = 80
- scores["self_sufficiency"] = 95
- scores["domestic_industry"] = 85
- scores["resource_control"] = 75
- elif policy_type == "industrial_subsidy":
- scores["domestic_industry"] = 95
- scores["self_sufficiency"] = 85
- scores["trade_balance_impact"] = 75
- scores["national_wealth"] = 70
- elif policy_type == "currency_devaluation":
- scores["trade_balance_impact"] = 85
- scores["domestic_industry"] = 80
- scores["national_wealth"] = 60
- elif policy_type == "free_trade":
- scores["trade_balance_impact"] = -80
- scores["self_sufficiency"] = -90
- scores["domestic_industry"] = -70
- scores["resource_control"] = -60
- elif policy_type == "trade_liberalization":
- scores["trade_balance_impact"] = -70
- scores["self_sufficiency"] = -80
- scores["domestic_industry"] = -65
- scores["resource_control"] = -55
- elif policy_type == "foreign_aid":
- scores["national_wealth"] = -40
- scores["resource_control"] = -30
-
- overall_score = sum(scores.values()) / len(scores)
-
- return {
- "policy_name": policy_name,
- "mercantilist_score": overall_score,
- "detailed_scores": scores,
- "recommendation": self._get_policy_recommendation(overall_score),
- "justification": self._generate_policy_justification(scores, policy_type)
- }
-
- def _calculate_trade_balance_score(self, data: EconomicData) -> float:
- """Calculate trade balance score (0-100)"""
- # Positive trade balance is good for mercantilism
- if data.trade_balance >= 10:
- return 100
- elif data.trade_balance >= 5:
- return 80
- elif data.trade_balance >= 0:
- return 60
- elif data.trade_balance >= -5:
- return 40
- elif data.trade_balance >= -10:
- return 20
- else:
- return max(0, 10 + data.trade_balance) # Negative but not below zero
-
- def _calculate_self_sufficiency_score(self, data: EconomicData) -> float:
- """Calculate self-sufficiency score (0-100)"""
- # High domestic investment indicates self-sufficiency efforts
- investment_score = min(data.private_investment * 3, 100)
-
- # Government support for domestic industries
- government_score = min(data.government_spending * 2.5, 100)
-
- # Trade balance affects self-sufficiency
- trade_score = self._calculate_trade_balance_score(data)
-
- # Low unemployment indicates strong domestic economy
- employment_score = max(100 - data.unemployment * 10, 0)
-
- return (investment_score + government_score + trade_score + employment_score) / 4
-
- def _calculate_protection_score(self, data: EconomicData) -> float:
- """Calculate protection score (0-100)"""
- # This would ideally include actual protectionist policy data
- # Using proxy indicators that might suggest protectionist stance
-
- # Higher government spending might indicate industrial policy
- industrial_policy = min(data.government_spending * 2, 100)
-
- # Negative trade balance might trigger protectionism
- protection_need = max(0, -data.trade_balance * 10)
-
- # GDP growth suggests strength to implement policies
- economic_strength = min(data.gdp * 20, 100)
-
- return (industrial_policy + protection_need + economic_strength) / 3
-
- def _calculate_national_accumulation_score(self, data: EconomicData) -> float:
- """Calculate national wealth accumulation score (0-100)"""
- # GDP strength
- gdp_score = min(data.gdp * 25, 100)
-
- # Investment in productive capacity
- investment_score = min(data.private_investment * 3, 100)
-
- # Government capacity to accumulate wealth
- government_score = min(data.government_spending * 2.5, 100)
-
- # Price stability preserves wealth
- price_stability = max(100 - data.inflation * 15, 0)
-
- return (gdp_score + investment_score + government_score + price_stability) / 4
-
- def _generate_assessment(self, health_score: float, strengths: List[str], concerns: List[str]) -> str:
- """Generate overall assessment"""
- if health_score >= 80:
- return f"Excellent mercantilist performance (Score: {health_score:.1f}/100). Strong trade surplus and national wealth accumulation."
- elif health_score >= 60:
- return f"Good mercantilist indicators (Score: {health_score:.1f}/100). Positive trade performance with room for improvement."
- elif health_score >= 40:
- return f"Moderate mercantilist success (Score: {health_score:.1f}/100). Mixed performance requiring stronger trade policies."
- else:
- return f"Poor mercantilist outcomes (Score: {health_score:.1f}/100). Trade deficits undermining national wealth accumulation."
-
- def _get_policy_recommendation(self, score: float) -> str:
- """Get policy recommendation based on score"""
- if score >= 70:
- return "Strongly Recommended"
- elif score >= 40:
- return "Recommended"
- elif score >= 0:
- return "Not Recommended"
- else:
- return "Strongly Opposed"
-
- def _generate_policy_justification(self, scores: Dict[str, float], policy_type: str) -> str:
- """Generate justification for policy evaluation"""
- justification = []
-
- if scores["trade_balance_impact"] > 60:
- justification.append("Improves trade balance")
- elif scores["trade_balance_impact"] < -20:
- justification.append("Worsens trade balance")
-
- if scores["self_sufficiency"] > 60:
- justification.append("Increases self-sufficiency")
- elif scores["self_sufficiency"] < -20:
- justification.append("Reduces self-sufficiency")
-
- if scores["domestic_industry"] > 60:
- justification.append("Supports domestic industries")
- elif scores["domestic_industry"] < -20:
- justification.append("Harms domestic industries")
-
- if scores["national_wealth"] > 60:
- justification.append("Accumulates national wealth")
- elif scores["national_wealth"] < -20:
- justification.append("Reduces national wealth")
-
- if scores["resource_control"] > 60:
- justification.append("Increases resource control")
- elif scores["resource_control"] < -20:
- justification.append("Reduces resource control"
-
- return "; ".join(justification) if justification else "Mixed effects on mercantilist objectives"
\ No newline at end of file
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
deleted file mode 100644
index e579d000a..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/mercantilist_agent_cli.py
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/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(argv=None):
- 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(argv)
-
- try:
- result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
- result_json = json.dumps(result, indent=2)
- print(result_json)
- return result_json
- 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.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/mixed_economy_agent.py
deleted file mode 100644
index 9f4f1cebf..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/mixed_economy_agent.py
+++ /dev/null
@@ -1,376 +0,0 @@
-"""
-Mixed Economy Economic Agent
-Processes economic data through the lens of mixed economy principles combining market and government elements
-"""
-
-from typing import Dict, List, Any
-from base_agent import EconomicAgent, EconomicData, PolicyRecommendation
-
-class MixedEconomyAgent(EconomicAgent):
- """Mixed economy agent balancing private enterprise with government intervention"""
-
- def __init__(self):
- super().__init__(
- "Mixed Economy Agent",
- "Analyzes economic data through mixed economy principles balancing market efficiency with social welfare"
- )
- self.principles = [
- "Balance of private and public sectors",
- "Market efficiency with government regulation",
- "Economic freedom with social responsibility",
- "Competition with safety nets",
- "Innovation with stability",
- "Individual prosperity with collective welfare"
- ]
- self.priorities = [
- "Economic stability",
- "Balanced growth",
- "Social safety net",
- "Market efficiency",
- "Regulatory framework",
- "Inclusive prosperity"
- ]
-
- def analyze_economy(self, data: EconomicData) -> Dict[str, Any]:
- """Analyze economy from mixed economy perspective"""
-
- # Calculate mixed economy specific metrics
- balance_score = self._calculate_balance_score(data)
- stability_score = self._calculate_stability_score(data)
- efficiency_equity_ratio = self._calculate_efficiency_equity_ratio(data)
- regulatory_effectiveness = self._calculate_regulatory_effectiveness(data)
-
- # Identify strengths and concerns
- strengths = []
- concerns = []
-
- # Market strengths
- if data.gdp > 2.5:
- strengths.append("Healthy GDP growth indicating productive market activity")
- if data.private_investment > 15 and data.private_investment < 35:
- strengths.append("Balanced private investment level")
- if data.unemployment < 6:
- strengths.append("Reasonable unemployment showing effective labor market")
-
- # Government strengths
- if data.government_spending > 20 and data.government_spending < 40:
- strengths.append("Balanced government spending providing stability without crowding out")
- if data.tax_rate > 20 and data.tax_rate < 40:
- strengths.append("Moderate tax burden supporting public services")
- if 1 < data.inflation < 4:
- strengths.append("Controlled inflation indicating effective monetary policy")
-
- # Imbalance concerns
- if data.government_spending > 50:
- concerns.append("Excessive government spending may crowd out private sector")
- if data.government_spending < 15:
- concerns.append("Insufficient government spending may lack social safety nets")
- if data.private_investment > 50:
- concerns.append("Over-reliance on private sector may increase inequality")
- if data.private_investment < 10:
- concerns.append("Insufficient private investment may limit growth and innovation")
- if data.tax_rate > 50:
- concerns.append("High tax rates may discourage private enterprise")
- if data.tax_rate < 15:
- concerns.append("Low tax rates may inadequately fund public services")
-
- # Calculate overall mixed economy health score
- health_score = (
- balance_score * 0.3 +
- stability_score * 0.25 +
- efficiency_equity_ratio * 0.25 +
- regulatory_effectiveness * 0.2
- )
-
- return {
- "ideology": "mixed_economy",
- "balance_score": balance_score,
- "stability_score": stability_score,
- "efficiency_equity_ratio": efficiency_equity_ratio,
- "regulatory_effectiveness": regulatory_effectiveness,
- "overall_health_score": health_score,
- "strengths": strengths,
- "concerns": concerns,
- "assessment": self._generate_assessment(health_score, strengths, concerns),
- "key_indicators": {
- "public_private_balance": abs(50 - data.government_spending),
- "gdp_growth": data.gdp,
- "unemployment_rate": data.unemployment,
- "inflation_rate": data.inflation,
- "tax_burden": data.tax_rate,
- "private_investment_share": data.private_investment
- }
- }
-
- def get_policy_recommendations(self, data: EconomicData, analysis: Dict[str, Any]) -> List[PolicyRecommendation]:
- """Generate mixed economy policy recommendations"""
- recommendations = []
-
- # Balance correction recommendations
- if data.government_spending > 45:
- recommendations.append(PolicyRecommendation(
- title="Reduce Government Spending",
- description="Moderate reduction in government expenditure to improve private sector participation",
- priority="medium",
- expected_impact="Improved economic efficiency and growth",
- implementation_time="12-24 months",
- risk_level="medium"
- ))
- elif data.government_spending < 20:
- recommendations.append(PolicyRecommendation(
- title="Increase Government Spending",
- description="Targeted increase in government spending on essential services and infrastructure",
- priority="medium",
- expected_impact="Enhanced social welfare and economic stability",
- implementation_time="12-24 months",
- risk_level="medium"
- ))
-
- # Tax balance recommendations
- if data.tax_rate > 45:
- recommendations.append(PolicyRecommendation(
- title="Reform Tax System",
- description="Implement moderate tax cuts while maintaining progressive structure",
- priority="medium",
- expected_impact="Balanced revenue generation with economic incentives",
- implementation_time="6-18 months",
- risk_level="low"
- ))
- elif data.tax_rate < 20:
- recommendations.append(PolicyRecommendation(
- title="Enhance Tax Revenue",
- description="Implement progressive tax reforms to fund essential services",
- priority="medium",
- expected_impact="Improved public service provision",
- implementation_time="6-12 months",
- risk_level="low"
- ))
-
- # Regulatory recommendations
- recommendations.append(PolicyRecommendation(
- title="Optimize Regulatory Framework",
- description="Review and streamline regulations to balance protection with efficiency",
- priority="medium",
- expected_impact="Improved business climate with necessary protections",
- implementation_time="12-30 months",
- risk_level="low"
- ))
-
- # Social safety net recommendations
- if data.unemployment > 7:
- recommendations.append(PolicyRecommendation(
- title="Strengthen Social Safety Net",
- description="Enhance unemployment benefits and job training programs",
- priority="high",
- expected_impact="Reduced hardship and better workforce preparedness",
- implementation_time="6-18 months",
- risk_level="low"
- ))
-
- # Infrastructure investment recommendations
- recommendations.append(PolicyRecommendation(
- title="Strategic Infrastructure Investment",
- description="Public-private partnerships for infrastructure development",
- priority="medium",
- expected_impact="Improved productivity and competitiveness",
- implementation_time="24-60 months",
- risk_level="medium"
- ))
-
- # Economic stabilization recommendations
- if data.inflation > 5:
- recommendations.append(PolicyRecommendation(
- title="Implement Anti-Inflation Measures",
- description="Monetary and fiscal policies to control inflation",
- priority="high",
- expected_impact="Price stability and purchasing power protection",
- implementation_time="3-12 months",
- risk_level="medium"
- ))
-
- # Innovation and entrepreneurship recommendations
- if data.private_investment < 15:
- recommendations.append(PolicyRecommendation(
- title="Promote Innovation and Entrepreneurship",
- description="Government support for R&D and small business development",
- priority="medium",
- expected_impact="Increased innovation and job creation",
- implementation_time="12-24 months",
- risk_level="low"
- ))
-
- return recommendations
-
- def evaluate_policy(self, policy: Dict[str, Any], data: EconomicData) -> Dict[str, Any]:
- """Evaluate policy from mixed economy perspective"""
- policy_name = policy.get("name", "Unknown Policy")
- policy_type = policy.get("type", "unknown")
-
- # Scoring criteria for mixed economy evaluation
- scores = {
- "economic_efficiency": 0, # How it affects market efficiency
- "social_welfare": 0, # How it affects social welfare
- "economic_balance": 0, # How it maintains public-private balance
- "economic_stability": 0, # How it affects economic stability
- "long_term_growth": 0 # How it affects sustainable growth
- }
-
- # Evaluate based on policy type
- if policy_type == "moderate_tax_change":
- scores["economic_balance"] = 85
- scores["economic_stability"] = 80
- scores["long_term_growth"] = 75
- elif policy_type == "infrastructure_investment":
- scores["economic_efficiency"] = 80
- scores["long_term_growth"] = 85
- scores["social_welfare"] = 70
- elif policy_type == "education_spending":
- scores["social_welfare"] = 85
- scores["long_term_growth"] = 80
- scores["economic_efficiency"] = 75
- elif policy_type == "healthcare_reform":
- scores["social_welfare"] = 90
- scores["economic_stability"] = 80
- scores["economic_balance"] = 75
- elif policy_type == "extreme_austerity":
- scores["economic_balance"] = -40
- scores["social_welfare"] = -60
- scores["economic_stability"] = -30
- elif policy_type == "excessive_spending":
- scores["economic_balance"] = -50
- scores["economic_efficiency"] = -40
- scores["economic_stability"] = -35
- elif policy_type == "deregulation":
- scores["economic_efficiency"] = 75
- scores["economic_balance"] = 50
- scores["social_welfare"] = 40
-
- overall_score = sum(scores.values()) / len(scores)
-
- return {
- "policy_name": policy_name,
- "mixed_economy_score": overall_score,
- "detailed_scores": scores,
- "recommendation": self._get_policy_recommendation(overall_score),
- "justification": self._generate_policy_justification(scores, policy_type)
- }
-
- def _calculate_balance_score(self, data: EconomicData) -> float:
- """Calculate public-private sector balance score (0-100)"""
- # Ideal balance is around 40% government spending, 60% private
- ideal_gov_spending = 40
- balance_penalty = abs(data.government_spending - ideal_gov_spending) * 2
- balance_score = max(100 - balance_penalty, 0)
-
- # Tax balance (ideal around 30%)
- ideal_tax_rate = 30
- tax_penalty = abs(data.tax_rate - ideal_tax_rate) * 1.5
- tax_score = max(100 - tax_penalty, 0)
-
- # Investment balance (ideal around 25% private)
- ideal_private_investment = 25
- investment_penalty = abs(data.private_investment - ideal_private_investment) * 2
- investment_score = max(100 - investment_penalty, 0)
-
- return (balance_score + tax_score + investment_score) / 3
-
- def _calculate_stability_score(self, data: EconomicData) -> float:
- """Calculate economic stability score (0-100)"""
- # Inflation stability (ideal 2-3%)
- if 2 <= data.inflation <= 3:
- inflation_score = 100
- else:
- inflation_score = max(100 - abs(data.inflation - 2.5) * 15, 0)
-
- # Unemployment stability (ideal 4-6%)
- if 4 <= data.unemployment <= 6:
- unemployment_score = 100
- else:
- unemployment_score = max(100 - abs(data.unemployment - 5) * 10, 0)
-
- # GDP growth stability (ideal 2-4%)
- if 2 <= data.gdp <= 4:
- gdp_score = 100
- else:
- gdp_score = max(100 - abs(data.gdp - 3) * 10, 0)
-
- return (inflation_score + unemployment_score + gdp_score) / 3
-
- def _calculate_efficiency_equity_ratio(self, data: EconomicData) -> float:
- """Calculate efficiency-equity balance ratio (0-100)"""
- # Efficiency indicators (private investment, moderate taxes)
- efficiency_score = min(data.private_investment * 3, 100) + max(100 - data.tax_rate * 2, 0)
- efficiency_score = efficiency_score / 2
-
- # Equity indicators (government spending, progressive taxation)
- equity_score = min(data.government_spending * 2.5, 100) + min(data.tax_rate * 2, 100)
- equity_score = equity_score / 2
-
- # Balance the two
- if abs(efficiency_score - equity_score) < 20:
- return (efficiency_score + equity_score) / 2
- else:
- # Penalize extreme imbalance
- return (efficiency_score + equity_score) / 2 - abs(efficiency_score - equity_score) / 4
-
- def _calculate_regulatory_effectiveness(self, data: EconomicData) -> float:
- """Calculate regulatory effectiveness score (0-100)"""
- # Balance between freedom and protection
- # Moderate government spending suggests balanced regulation
- regulation_balance = max(100 - abs(data.government_spending - 35) * 2, 0)
-
- # Consumer confidence reflects regulatory trust
- confidence_score = min(data.consumer_confidence * 1.2, 100)
-
- # Economic stability reflects regulatory effectiveness
- stability_score = max(100 - abs(data.inflation - 2.5) * 20, 0)
-
- return (regulation_balance + confidence_score + stability_score) / 3
-
- def _generate_assessment(self, health_score: float, strengths: List[str], concerns: List[str]) -> str:
- """Generate overall assessment"""
- if health_score >= 80:
- return f"Excellent mixed economy balance (Score: {health_score:.1f}/100). Optimal public-private balance."
- elif health_score >= 60:
- return f"Good mixed economy performance (Score: {health_score:.1f}/100). Well-balanced with minor adjustments needed."
- elif health_score >= 40:
- return f"Moderate mixed economy health (Score: {health_score:.1f}/100). Some imbalance requiring policy correction."
- else:
- return f"Poor mixed economy balance (Score: {health_score:.1f}/100). Significant rebalancing needed."
-
- def _get_policy_recommendation(self, score: float) -> str:
- """Get policy recommendation based on score"""
- if score >= 70:
- return "Highly Recommended"
- elif score >= 40:
- return "Recommended"
- elif score >= 0:
- return "Conditionally Recommended"
- else:
- return "Not Recommended"
-
- def _generate_policy_justification(self, scores: Dict[str, float], policy_type: str) -> str:
- """Generate justification for policy evaluation"""
- justification = []
-
- if scores["economic_balance"] > 60:
- justification.append("Maintains public-private balance")
- elif scores["economic_balance"] < -20:
- justification.append("Disrupts economic balance")
-
- if scores["economic_efficiency"] > 60:
- justification.append("Promotes market efficiency")
- elif scores["economic_efficiency"] < -20:
- justification.append("Reduces economic efficiency")
-
- if scores["social_welfare"] > 60:
- justification.append("Enhances social welfare")
- elif scores["social_welfare"] < -20:
- justification.append("Reduces social protection")
-
- if scores["economic_stability"] > 60:
- justification.append("Supports economic stability")
- elif scores["economic_stability"] < -20:
- justification.append("Creates economic instability"
-
- return "; ".join(justification) if justification else "Mixed effects on mixed economy objectives"
\ No newline at end of file
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
deleted file mode 100644
index 13e992acd..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/mixed_economy_agent_cli.py
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/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(argv=None):
- 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(argv)
-
- try:
- result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
- result_json = json.dumps(result, indent=2)
- print(result_json)
- return result_json
- 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.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/neoliberal_agent.py
deleted file mode 100644
index 2bbcbd145..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/neoliberal_agent.py
+++ /dev/null
@@ -1,367 +0,0 @@
-"""
-Neoliberal Economic Agent
-Processes economic data through the lens of neoliberal economic principles
-"""
-
-from typing import Dict, List, Any
-from base_agent import EconomicAgent, EconomicData, PolicyRecommendation
-
-class NeoliberalAgent(EconomicAgent):
- """Neoliberal economic analysis agent emphasizing free markets, deregulation, and minimal government"""
-
- def __init__(self):
- super().__init__(
- "Neoliberal Agent",
- "Analyzes economic data through neoliberal principles emphasizing free markets, deregulation, privatization, and minimal government intervention"
- )
- self.principles = [
- "Free market fundamentalism",
- "Deregulation and liberalization",
- "Privatization of state enterprises",
- "Minimal government intervention",
- "Globalization and free trade",
- "Supply-side economics",
- "Monetary stability"
- ]
- self.priorities = [
- "Economic liberalization",
- "Market efficiency",
- "Private sector growth",
- "Fiscal discipline",
- "Monetary stability",
- "International trade integration"
- ]
-
- def analyze_economy(self, data: EconomicData) -> Dict[str, Any]:
- """Analyze economy from neoliberal perspective"""
-
- # Calculate neoliberal-specific metrics
- market_freedom_score = self._calculate_market_freedom_score(data)
- liberalization_score = self._calculate_liberalization_score(data)
- fiscal_discipline_score = self._calculate_fiscal_discipline_score(data)
- globalization_score = self._calculate_globalization_score(data)
-
- # Identify strengths and concerns
- strengths = []
- concerns = []
-
- # Market freedom strengths
- if data.tax_rate < 25:
- strengths.append("Low tax burden encouraging investment")
- if data.government_spending < 25:
- strengths.append("Limited government intervention in economy")
- if data.private_investment > 40:
- strengths.append("Strong private sector driving growth")
- if data.unemployment < 5:
- strengths.append("Flexible labor markets with low unemployment")
-
- # Regulatory strengths (assumed from data patterns)
- if data.gdp > 3:
- strengths.append("Strong economic growth indicating business-friendly environment")
-
- # Market efficiency strengths
- if data.inflation < 3:
- strengths.append("Price stability through sound monetary policy")
-
- # Concerns from neoliberal perspective
- if data.government_spending > 35:
- concerns.append("Excessive government spending crowding out private sector")
- if data.tax_rate > 35:
- concerns.append("High tax rates discouraging investment and entrepreneurship")
- if data.government_spending > 50:
- concerns.append("Overly large public sector reducing economic freedom")
- if data.private_investment < 20:
- concerns.append("Insufficient private investment and economic dynamism")
- if data.inflation > 5:
- concerns.append("High inflation eroding purchasing power and investment confidence")
-
- # Calculate overall neoliberal health score
- health_score = (
- market_freedom_score * 0.3 +
- liberalization_score * 0.25 +
- fiscal_discipline_score * 0.25 +
- globalization_score * 0.2
- )
-
- return {
- "ideology": "neoliberal",
- "market_freedom_score": market_freedom_score,
- "liberalization_score": liberalization_score,
- "fiscal_discipline_score": fiscal_discipline_score,
- "globalization_score": globalization_score,
- "overall_health_score": health_score,
- "strengths": strengths,
- "concerns": concerns,
- "assessment": self._generate_assessment(health_score, strengths, concerns),
- "key_indicators": {
- "tax_burden": data.tax_rate,
- "government_spending_share": data.government_spending,
- "private_investment_share": data.private_investment,
- "market_openness": max(0, 100 - data.tax_rate - data.government_spending/2),
- "economic_freedom": self._calculate_economic_freedom_index(data)
- }
- }
-
- def get_policy_recommendations(self, data: EconomicData, analysis: Dict[str, Any]) -> List[PolicyRecommendation]:
- """Generate neoliberal policy recommendations"""
- recommendations = []
-
- # Tax reduction recommendations
- if data.tax_rate > 30:
- recommendations.append(PolicyRecommendation(
- title="Implement Supply-Side Tax Cuts",
- description="Reduce marginal tax rates on individuals and corporations to stimulate investment and growth",
- priority="high",
- expected_impact="Increased investment, job creation, and economic growth",
- implementation_time="3-6 months",
- risk_level="low"
- ))
-
- # Privatization recommendations
- if data.government_spending > 40:
- recommendations.append(PolicyRecommendation(
- title="Accelerate Privatization Program",
- description="Sell state-owned enterprises to improve efficiency and reduce government size",
- priority="high",
- expected_impact="Improved productivity and reduced fiscal burden",
- implementation_time="12-36 months",
- risk_level="medium"
- ))
-
- # Deregulation recommendations
- recommendations.append(PolicyRecommendation(
- title="Comprehensive Deregulation",
- description="Eliminate unnecessary regulations that hinder business and market efficiency",
- priority="high",
- expected_impact="Increased business activity and economic efficiency",
- implementation_time="12-24 months",
- risk_level="low"
- ))
-
- # Government spending reduction
- if data.government_spending > 35:
- recommendations.append(PolicyRecommendation(
- title="Reduce Government Spending",
- description("Cut government expenditures and eliminate wasteful programs"),
- priority="high",
- expected_impact="Reduced tax burden and increased private sector growth",
- implementation_time="12-48 months",
- risk_level="medium"
- ))
-
- # Trade liberalization
- recommendations.append(PolicyRecommendation(
- title="Expand Trade Liberalization",
- description="Remove trade barriers and negotiate free trade agreements",
- priority="medium",
- expected_impact="Increased competition and economic efficiency",
- implementation_time="6-18 months",
- risk_level="low"
- ))
-
- # Labor market flexibility
- recommendations.append(PolicyRecommendation(
- title="Increase Labor Market Flexibility",
- description="Reduce labor regulations and make hiring/firing easier",
- priority="medium",
- expected_impact("Improved employment and economic adaptability"),
- implementation_time="6-12 months",
- risk_level="medium"
- ))
-
- # Monetary stability
- if data.inflation > 3:
- recommendations.append(PolicyRecommendation(
- title="Ensure Monetary Stability",
- description="Implement strict monetary policy to control inflation",
- priority="high",
- expected_impact="Price stability and investment confidence",
- implementation_time="1-3 months",
- risk_level="low"
- ))
-
- # Financial liberalization
- recommendations.append(PolicyRecommendation(
- title="Liberalize Financial Markets",
- description="Remove capital controls and financial regulations",
- priority="medium",
- expected_impact="Increased capital flow and investment",
- implementation_time="6-18 months",
- risk_level="medium"
- ))
-
- return recommendations
-
- def evaluate_policy(self, policy: Dict[str, Any], data: EconomicData) -> Dict[str, Any]:
- """Evaluate policy from neoliberal perspective"""
- policy_name = policy.get("name", "Unknown Policy")
- policy_type = policy.get("type", "unknown")
-
- # Scoring criteria for neoliberal evaluation
- scores = {
- "market_efficiency": 0, # How it affects market efficiency
- "economic_freedom": 0, # How it affects economic freedom
- "private_sector": 0, # How it benefits private sector
- "fiscal_responsibility": 0, # How it affects fiscal discipline
- "global_integration": 0 # How it affects global integration
- }
-
- # Evaluate based on policy type
- if policy_type == "tax_cut":
- scores["economic_freedom"] = 95
- scores["market_efficiency"] = 85
- scores["private_sector"] = 90
- scores["fiscal_responsibility"] = 70
- elif policy_type == "privatization":
- scores["private_sector"] = 100
- scores["market_efficiency"] = 90
- scores["economic_freedom"] = 85
- scores["fiscal_responsibility"] = 80
- elif policy_type == "deregulation":
- scores["economic_freedom"] = 100
- scores["market_efficiency"] = 95
- scores["private_sector"] = 90
- elif policy_type == "trade_liberalization":
- scores["global_integration"] = 100
- scores["market_efficiency"] = 85
- scores["economic_freedom"] = 80
- elif policy_type == "spending_cut":
- scores["fiscal_responsibility"] = 90
- scores["private_sector"] = 75
- scores["economic_freedom"] = 70
- elif policy_type == "government_intervention":
- scores["market_efficiency"] = -80
- scores["economic_freedom"] = -90
- scores["private_sector"] = -70
- scores["fiscal_responsibility"] = -60
- elif policy_type == "price_controls":
- scores["market_efficiency"] = -90
- scores["economic_freedom"] = -85
- scores["private_sector"] = -80
- elif policy_type == "trade_barriers":
- scores["global_integration"] = -85
- scores["market_efficiency"] = -75
- scores["economic_freedom"] = -70
-
- overall_score = sum(scores.values()) / len(scores)
-
- return {
- "policy_name": policy_name,
- "neoliberal_score": overall_score,
- "detailed_scores": scores,
- "recommendation": self._get_policy_recommendation(overall_score),
- "justification": self._generate_policy_justification(scores, policy_type)
- }
-
- def _calculate_market_freedom_score(self, data: EconomicData) -> float:
- """Calculate market freedom score (0-100)"""
- # Low taxes = more freedom
- tax_freedom = max(100 - data.tax_rate * 2.5, 0)
-
- # Low government spending = more freedom
- spending_freedom = max(100 - data.government_spending * 2, 0)
-
- # High private investment = market freedom
- investment_freedom = min(data.private_investment * 2.5, 100)
-
- # Price stability = market freedom
- price_stability = max(100 - data.inflation * 10, 0)
-
- return (tax_freedom + spending_freedom + investment_freedom + price_stability) / 4
-
- def _calculate_liberalization_score(self, data: EconomicData) -> float:
- """Calculate economic liberalization score (0-100)"""
- # Trade openness (inferred from data patterns)
- trade_openness = max(100 - abs(data.trade_balance) * 8, 0)
-
- # Investment liberalization
- investment_liberalization = min(data.private_investment * 3, 100)
-
- # Financial liberalization (low inflation and stable interest rates)
- financial_liberalization = max(100 - abs(data.interest_rate - 5) * 10 - data.inflation * 10, 0)
-
- # Business freedom (low unemployment indicates flexible markets)
- business_freedom = max(100 - data.unemployment * 8, 0)
-
- return (trade_openness + investment_liberalization + financial_liberalization + business_freedom) / 4
-
- def _calculate_fiscal_discipline_score(self, data: EconomicData) -> float:
- """Calculate fiscal discipline score (0-100)"""
- # Low government spending = discipline
- spending_discipline = max(100 - data.government_spending * 2.5, 0)
-
- # Reasonable tax rates = discipline
- tax_discipline = max(100 - abs(data.tax_rate - 25) * 3, 0)
-
- # Balanced approach (not too low to starve essential functions)
- balance_score = 80 if 15 < data.tax_rate < 35 and 20 < data.government_spending < 40 else 60
-
- return (spending_discipline + tax_discipline + balance_score) / 3
-
- def _calculate_globalization_score(self, data: EconomicData) -> float:
- """Calculate globalization integration score (0-100)"""
- # Trade integration
- trade_integration = max(100 - abs(data.trade_balance) * 10, 0)
-
- # Investment openness
- investment_openness = min(data.private_investment * 3, 100)
-
- # Economic openness (low barriers assumed from market indicators)
- economic_openness = max(100 - data.tax_rate - data.government_spending/3, 0)
-
- # Financial integration (stable indicators)
- financial_integration = max(100 - abs(data.interest_rate - 4) * 15 - data.inflation * 15, 0)
-
- return (trade_integration + investment_openness + economic_openness + financial_integration) / 4
-
- def _calculate_economic_freedom_index(self, data: EconomicData) -> float:
- """Calculate comprehensive economic freedom index"""
- return self._calculate_market_freedom_score(data)
-
- def _generate_assessment(self, health_score: float, strengths: List[str], concerns: List[str]) -> str:
- """Generate overall assessment"""
- if health_score >= 80:
- return f"Excellent neoliberal economic conditions (Score: {health_score:.1f}/100). Strong market freedom and minimal government intervention."
- elif health_score >= 60:
- return f"Good market-oriented economy (Score: {health_score:.1f}/100). Generally favorable conditions with room for more reforms."
- elif health_score >= 40:
- return f"Moderate economic freedom (Score: {health_score:.1f}/100). Mixed conditions requiring significant liberalization."
- else:
- return f"Poor market conditions (Score: {health_score:.1f}/100). Excessive government intervention requiring radical reforms."
-
- def _get_policy_recommendation(self, score: float) -> str:
- """Get policy recommendation based on score"""
- if score >= 70:
- return "Strongly Recommended"
- elif score >= 40:
- return "Recommended"
- elif score >= 0:
- return "Not Recommended"
- else:
- return "Strongly Opposed"
-
- def _generate_policy_justification(self, scores: Dict[str, float], policy_type: str) -> str:
- """Generate justification for policy evaluation"""
- justification = []
-
- if scores["market_efficiency"] > 60:
- justification.append("Increases market efficiency")
- elif scores["market_efficiency"] < -20:
- justification.append("Reduces market efficiency")
-
- if scores["economic_freedom"] > 60:
- justification.append("Enhances economic freedom")
- elif scores["economic_freedom"] < -20:
- justification.append("Restricts economic freedom")
-
- if scores["private_sector"] > 60:
- justification.append("Benefits private sector")
- elif scores["private_sector"] < -20:
- justification.append("Harms private sector")
-
- if scores["fiscal_responsibility"] > 60:
- justification.append("Promotes fiscal discipline")
- elif scores["fiscal_responsibility"] < -20:
- justification.append("Undermines fiscal responsibility")
-
- return "; ".join(justification) if justification else "Mixed effects on neoliberal objectives"
\ No newline at end of file
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
deleted file mode 100644
index e54d88cc1..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/neoliberal_agent_cli.py
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/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(argv=None):
- 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(argv)
-
- try:
- result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
- result_json = json.dumps(result, indent=2)
- print(result_json)
- return result_json
- 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.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/socialism_agent.py
deleted file mode 100644
index 6a16ffcaa..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/socialism_agent.py
+++ /dev/null
@@ -1,325 +0,0 @@
-"""
-Socialism Economic Agent
-Processes economic data through the lens of socialist economic principles
-"""
-
-from typing import Dict, List, Any
-from base_agent import EconomicAgent, EconomicData, PolicyRecommendation
-
-class SocialismAgent(EconomicAgent):
- """Socialist economic analysis agent focusing on social ownership and equality"""
-
- def __init__(self):
- super().__init__(
- "Socialism Agent",
- "Analyzes economic data through socialist principles emphasizing social ownership, economic equality, and workers' rights"
- )
- self.principles = [
- "Social ownership of means of production",
- "Economic equality and social welfare",
- "Workers' rights and labor protection",
- "Democratic economic planning",
- "Redistribution of wealth",
- "Universal access to essential services"
- ]
- self.priorities = [
- "Economic equality",
- "Social welfare",
- "Workers' protection",
- "Public services",
- "Economic democracy",
- "Environmental sustainability"
- ]
-
- def analyze_economy(self, data: EconomicData) -> Dict[str, Any]:
- """Analyze economy from socialist perspective"""
-
- # Calculate socialism-specific metrics
- equality_index = self._calculate_equality_index(data)
- social_welfare_score = self._calculate_social_welfare_score(data)
- workers_protection_score = self._calculate_workers_protection(data)
- public_services_score = self._calculate_public_services_score(data)
-
- # Identify strengths and concerns
- strengths = []
- concerns = []
-
- if data.government_spending > 30:
- strengths.append("Strong government investment in public services")
- if data.unemployment < 6:
- strengths.append("Low unemployment showing economic security")
- if data.inflation < 3:
- strengths.append("Price stability protecting vulnerable populations")
- if data.consumer_confidence > 60:
- strengths.append("Strong consumer confidence indicating economic security")
-
- if data.unemployment > 8:
- concerns.append("High unemployment affecting workers' security")
- if data.tax_rate < 25:
- concerns.append("Insufficient tax revenue for social programs")
- if data.government_spending < 25:
- concerns.append("Inadequate public investment in essential services")
- if data.trade_balance < -10:
- concerns.append("Trade deficit may harm domestic industries and workers")
- if data.private_investment > 40:
- concerns.append("Excessive privatization may undermine social ownership")
-
- # Calculate overall socialist health score
- health_score = (
- equality_index * 0.3 +
- social_welfare_score * 0.25 +
- workers_protection_score * 0.25 +
- public_services_score * 0.2
- )
-
- return {
- "ideology": "socialism",
- "equality_index": equality_index,
- "social_welfare_score": social_welfare_score,
- "workers_protection_score": workers_protection_score,
- "public_services_score": public_services_score,
- "overall_health_score": health_score,
- "strengths": strengths,
- "concerns": concerns,
- "assessment": self._generate_assessment(health_score, strengths, concerns),
- "key_indicators": {
- "unemployment_rate": data.unemployment,
- "inflation_rate": data.inflation,
- "government_spending_share": data.government_spending,
- "tax_progression": data.tax_rate,
- "public_investment_ratio": max(0, 100 - data.private_investment)
- }
- }
-
- def get_policy_recommendations(self, data: EconomicData, analysis: Dict[str, Any]) -> List[PolicyRecommendation]:
- """Generate socialist policy recommendations"""
- recommendations = []
-
- # Progressive taxation recommendations
- if data.tax_rate < 35:
- recommendations.append(PolicyRecommendation(
- title="Implement Progressive Taxation",
- description="Increase tax rates on wealthy individuals and corporations to fund social programs",
- priority="high",
- expected_impact="Reduced inequality and increased funding for public services",
- implementation_time="6-12 months",
- risk_level="low"
- ))
-
- # Social spending recommendations
- if data.government_spending < 35:
- recommendations.append(PolicyRecommendation(
- title="Increase Social Spending",
- description="Expand government investment in healthcare, education, and social security",
- priority="high",
- expected_impact="Improved social welfare and economic equality",
- implementation_time="12-24 months",
- risk_level="medium"
- ))
-
- # Worker protection recommendations
- if data.unemployment > 6:
- recommendations.append(PolicyRecommendation(
- title="Strengthen Workers' Rights",
- description="Implement stronger labor protections, minimum wage increases, and union rights",
- priority="high",
- expected_impact="Better working conditions and reduced exploitation",
- implementation_time="6-18 months",
- risk_level="low"
- ))
-
- # Public ownership recommendations
- if data.private_investment > 60:
- recommendations.append(PolicyRecommendation(
- title="Expand Public Ownership",
- description="Nationalize key industries and utilities to ensure social control",
- priority="medium",
- expected_impact="Democratic control of essential services",
- implementation_time="24-48 months",
- risk_level="medium"
- ))
-
- # Economic planning recommendations
- recommendations.append(PolicyRecommendation(
- title="Implement Democratic Economic Planning",
- description="Create democratic institutions for economic planning and resource allocation",
- priority="medium",
- expected_impact="More equitable resource distribution",
- implementation_time="18-36 months",
- risk_level="medium"
- ))
-
- # Universal basic services recommendations
- recommendations.append(PolicyRecommendation(
- title="Provide Universal Basic Services",
- description="Ensure universal access to healthcare, education, housing, and utilities",
- priority="high",
- expected_impact="Elimination of poverty and improved quality of life",
- implementation_time="24-60 months",
- risk_level="medium"
- ))
-
- # Wealth redistribution recommendations
- if analysis["equality_index"] < 60:
- recommendations.append(PolicyRecommendation(
- title="Implement Wealth Redistribution",
- description="Policies to redistribute wealth through taxes and social programs",
- priority="high",
- expected_impact="Reduced economic inequality",
- implementation_time="12-36 months",
- risk_level="medium"
- ))
-
- return recommendations
-
- def evaluate_policy(self, policy: Dict[str, Any], data: EconomicData) -> Dict[str, Any]:
- """Evaluate policy from socialist perspective"""
- policy_name = policy.get("name", "Unknown Policy")
- policy_type = policy.get("type", "unknown")
-
- # Scoring criteria for socialist evaluation
- scores = {
- "equality_impact": 0, # How it affects economic equality
- "social_welfare": 0, # How it affects social welfare
- "workers_benefits": 0, # How it benefits workers
- "public_control": 0, # How it increases public ownership
- "economic_security": 0 # How it provides economic security
- }
-
- # Evaluate based on policy type
- if policy_type == "tax_increase":
- scores["equality_impact"] = 80
- scores["social_welfare"] = 85
- scores["economic_security"] = 75
- elif policy_type == "universal_healthcare":
- scores["social_welfare"] = 95
- scores["equality_impact"] = 85
- scores["economic_security"] = 80
- elif policy_type == "minimum_wage":
- scores["workers_benefits"] = 90
- scores["equality_impact"] = 75
- scores["economic_security"] = 70
- elif policy_type == "nationalization":
- scores["public_control"] = 95
- scores["equality_impact"] = 80
- scores["social_welfare"] = 75
- elif policy_type == "social_spending":
- scores["social_welfare"] = 90
- scores["equality_impact"] = 80
- scores["economic_security"] = 85
- elif policy_type == "tax_cut":
- scores["equality_impact"] = -60
- scores["social_welfare"] = -50
- scores["economic_security"] = -40
- elif policy_type == "privatization":
- scores["public_control"] = -80
- scores["equality_impact"] = -60
- scores["social_welfare"] = -70
-
- overall_score = sum(scores.values()) / len(scores)
-
- return {
- "policy_name": policy_name,
- "socialist_score": overall_score,
- "detailed_scores": scores,
- "recommendation": self._get_policy_recommendation(overall_score),
- "justification": self._generate_policy_justification(scores, policy_type)
- }
-
- def _calculate_equality_index(self, data: EconomicData) -> float:
- """Calculate economic equality index (0-100)"""
- # Higher government spending and tax rates indicate more redistribution
- spending_score = min(data.government_spending * 2.5, 100)
- tax_score = min(data.tax_rate * 2.5, 100)
-
- # Lower unemployment indicates better economic security
- employment_score = max(100 - data.unemployment * 8, 0)
-
- return (spending_score + tax_score + employment_score) / 3
-
- def _calculate_social_welfare_score(self, data: EconomicData) -> float:
- """Calculate social welfare score (0-100)"""
- # Higher government spending indicates more social programs
- spending_score = min(data.government_spending * 2.8, 100)
-
- # Lower unemployment indicates better welfare
- unemployment_score = max(100 - data.unemployment * 10, 0)
-
- # Lower inflation protects purchasing power of the poor
- inflation_score = max(100 - data.inflation * 15, 0)
-
- return (spending_score + unemployment_score + inflation_score) / 3
-
- def _calculate_workers_protection(self, data: EconomicData) -> float:
- """Calculate workers' protection score (0-100)"""
- # Lower unemployment is better for workers
- employment_score = max(100 - data.unemployment * 12, 0)
-
- # Government spending often correlates with labor protection
- protection_score = min(data.government_spending * 2.2, 100)
-
- # Higher tax rates may indicate more labor regulations
- regulation_score = min(data.tax_rate * 2, 100)
-
- return (employment_score + protection_score + regulation_score) / 3
-
- def _calculate_public_services_score(self, data: EconomicData) -> float:
- """Calculate public services score (0-100)"""
- # Higher government spending means more public services
- services_score = min(data.government_spending * 3, 100)
-
- # Higher taxes provide funding for services
- funding_score = min(data.tax_rate * 2.5, 100)
-
- # Lower private investment may indicate more public ownership
- public_ownership_score = max(100 - data.private_investment * 1.5, 0)
-
- return (services_score + funding_score + public_ownership_score) / 3
-
- def _generate_assessment(self, health_score: float, strengths: List[str], concerns: List[str]) -> str:
- """Generate overall assessment"""
- if health_score >= 80:
- return f"Excellent socialist economic health (Score: {health_score:.1f}/100). Strong social protection and equality."
- elif health_score >= 60:
- return f"Good socialist economic health (Score: {health_score:.1f}/100). Solid social programs with room for improvement."
- elif health_score >= 40:
- return f"Moderate socialist economic health (Score: {health_score:.1f}/100). Mixed social outcomes requiring policy attention."
- else:
- return f"Poor socialist economic health (Score: {health_score:.1f}/100). Significant social and economic inequality issues."
-
- def _get_policy_recommendation(self, score: float) -> str:
- """Get policy recommendation based on score"""
- if score >= 70:
- return "Strongly Recommended"
- elif score >= 40:
- return "Recommended"
- elif score >= 0:
- return "Not Recommended"
- else:
- return "Strongly Opposed"
-
- def _generate_policy_justification(self, scores: Dict[str, float], policy_type: str) -> str:
- """Generate justification for policy evaluation"""
- justification = []
-
- if scores["equality_impact"] > 50:
- justification.append("Promotes economic equality")
- elif scores["equality_impact"] < -20:
- justification.append("Increases economic inequality")
-
- if scores["social_welfare"] > 50:
- justification.append("Improves social welfare")
- elif scores["social_welfare"] < -20:
- justification.append("Reduces social welfare")
-
- if scores["workers_benefits"] > 50:
- justification.append("Benefits working class")
- elif scores["workers_benefits"] < -20:
- justification.append("Harms workers")
-
- if scores["public_control"] > 50:
- justification.append("Increases democratic control")
- elif scores["public_control"] < -20:
- justification.append("Reduces public ownership")
-
- return "; ".join(justification) if justification else "Mixed effects on socialist objectives"
\ No newline at end of file
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
deleted file mode 100644
index 381064530..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/socialism_agent_cli.py
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/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(argv=None):
- 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(argv)
-
- try:
- result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
- result_json = json.dumps(result, indent=2)
- print(result_json)
- return result_json
- 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/EconomicAgents/utils.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/utils.py
deleted file mode 100644
index 540fac264..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/EconomicAgents/utils.py
+++ /dev/null
@@ -1,366 +0,0 @@
-"""
-Utility functions for economic agents
-"""
-
-import json
-import csv
-from typing import Dict, List, Any, Union, Optional
-from datetime import datetime, date
-import statistics
-import math
-
-def validate_economic_data(data) -> List[str]:
- """
- Validate economic data and return list of issues
-
- Args:
- data: EconomicData object to validate
-
- Returns:
- List[str]: List of validation issues
- """
- issues = []
-
- # GDP growth validation
- if data.gdp < -20 or data.gdp > 20:
- issues.append(f"Unrealistic GDP growth rate: {data.gdp}%")
-
- # Inflation validation
- if data.inflation < -10 or data.inflation > 50:
- issues.append(f"Unrealistic inflation rate: {data.inflation}%")
-
- # Unemployment validation
- if data.unemployment < 0 or data.unemployment > 50:
- issues.append(f"Unrealistic unemployment rate: {data.unemployment}%")
-
- # Interest rate validation
- if data.interest_rate < 0 or data.interest_rate > 50:
- issues.append(f"Unrealistic interest rate: {data.interest_rate}%")
-
- # Tax rate validation
- if data.tax_rate < 0 or data.tax_rate > 100:
- issues.append(f"Invalid tax rate: {data.tax_rate}%")
-
- # Government spending validation
- if data.government_spending < 0 or data.government_spending > 100:
- issues.append(f"Invalid government spending: {data.government_spending}% of GDP")
-
- # Private investment validation
- if data.private_investment < 0 or data.private_investment > 100:
- issues.append(f"Invalid private investment: {data.private_investment}% of GDP")
-
- # Consumer confidence validation
- if data.consumer_confidence < 0 or data.consumer_confidence > 100:
- issues.append(f"Invalid consumer confidence: {data.consumer_confidence}")
-
- return issues
-
-def calculate_growth_rate(current: float, previous: float) -> float:
- """
- Calculate growth rate between two values
-
- Args:
- current (float): Current value
- previous (float): Previous value
-
- Returns:
- float: Growth rate as percentage
- """
- if previous == 0:
- return 0.0
- return ((current - previous) / previous) * 100
-
-def normalize_score(value: float, min_val: float, max_val: float) -> float:
- """
- Normalize a value to 0-100 scale
-
- Args:
- value (float): Value to normalize
- min_val (float): Minimum possible value
- max_val (float): Maximum possible value
-
- Returns:
- float: Normalized value between 0 and 100
- """
- if max_val == min_val:
- return 50.0
- normalized = ((value - min_val) / (max_val - min_val)) * 100
- return max(0, min(100, normalized))
-
-def standardize_score(value: float, target: float, tolerance: float) -> float:
- """
- Standardize score based on distance from target value
-
- Args:
- value (float): Actual value
- target (float): Target value
- tolerance (float): Acceptable tolerance
-
- Returns:
- float: Score from 0-100 where target gets 100
- """
- distance = abs(value - target)
- if distance <= tolerance:
- return 100.0
- penalty = (distance - tolerance) * 10
- return max(0, 100 - penalty)
-
-def calculate_composite_score(scores: List[float], weights: Optional[List[float]] = None) -> float:
- """
- Calculate composite score from multiple components
-
- Args:
- scores (List[float]): List of individual scores
- weights (Optional[List[float]]): Optional weights for each score
-
- Returns:
- float: Composite score
- """
- if not scores:
- return 0.0
-
- if weights is None:
- return statistics.mean(scores)
-
- if len(scores) != len(weights):
- raise ValueError("Number of scores and weights must match")
-
- total_weight = sum(weights)
- if total_weight == 0:
- return statistics.mean(scores)
-
- weighted_sum = sum(score * weight for score, weight in zip(scores, weights))
- return weighted_sum / total_weight
-
-def format_currency(amount: float, currency: str = "USD") -> str:
- """
- Format currency amount
-
- Args:
- amount (float): Amount to format
- currency (str): Currency code
-
- Returns:
- str: Formatted currency string
- """
- if amount >= 1e12:
- return f"{currency}{amount/1e12:.2f}T"
- elif amount >= 1e9:
- return f"{currency}{amount/1e9:.2f}B"
- elif amount >= 1e6:
- return f"{currency}{amount/1e6:.2f}M"
- elif amount >= 1e3:
- return f"{currency}{amount/1e3:.2f}K"
- else:
- return f"{currency}{amount:.2f}"
-
-def calculate_trend(values: List[float]) -> Dict[str, Any]:
- """
- Calculate trend statistics for a series of values
-
- Args:
- values (List[float]): List of values
-
- Returns:
- Dict[str, Any]: Trend statistics
- """
- if len(values) < 2:
- return {
- "trend": "insufficient_data",
- "direction": "neutral",
- "change_rate": 0.0,
- "volatility": 0.0
- }
-
- # Calculate trend direction
- first_half = statistics.mean(values[:len(values)//2])
- second_half = statistics.mean(values[len(values)//2:])
-
- if second_half > first_half * 1.05:
- direction = "increasing"
- trend = "upward"
- elif second_half < first_half * 0.95:
- direction = "decreasing"
- trend = "downward"
- else:
- direction = "stable"
- trend = "neutral"
-
- # Calculate change rate
- change_rate = calculate_growth_rate(values[-1], values[0])
-
- # Calculate volatility (coefficient of variation)
- if statistics.mean(values) != 0:
- volatility = (statistics.stdev(values) / abs(statistics.mean(values))) * 100
- else:
- volatility = 0.0
-
- return {
- "trend": trend,
- "direction": direction,
- "change_rate": change_rate,
- "volatility": volatility,
- "mean": statistics.mean(values),
- "median": statistics.median(values)
- }
-
-def interpolate_data_point(start_value: float, end_value: float, steps: int, target_step: int) -> float:
- """
- Interpolate data point between two values
-
- Args:
- start_value (float): Starting value
- end_value (float): Ending value
- steps (int): Total number of steps
- target_step (int): Target step number
-
- Returns:
- float: Interpolated value
- """
- if steps <= 1:
- return start_value
-
- if target_step >= steps:
- return end_value
-
- ratio = target_step / (steps - 1)
- return start_value + (end_value - start_value) * ratio
-
-def calculate_risk_metrics(values: List[float]) -> Dict[str, float]:
- """
- Calculate risk metrics for a series of values
-
- Args:
- values (List[float]): List of values
-
- Returns:
- Dict[str, float]: Risk metrics
- """
- if len(values) < 2:
- return {
- "volatility": 0.0,
- "max_drawdown": 0.0,
- "sharpe_ratio": 0.0,
- "var_95": 0.0
- }
-
- mean_val = statistics.mean(values)
-
- # Volatility
- volatility = statistics.stdev(values) if len(values) > 1 else 0.0
-
- # Maximum drawdown
- max_val = max(values)
- min_val = min(values)
- max_drawdown = (max_val - min_val) / max_val * 100 if max_val != 0 else 0.0
-
- # Simplified Sharpe ratio (assuming risk-free rate = 0)
- sharpe_ratio = mean_val / volatility if volatility != 0 else 0.0
-
- # Value at Risk (95% confidence)
- sorted_values = sorted(values)
- var_index = int(0.05 * len(sorted_values))
- var_95 = sorted_values[var_index] if var_index < len(sorted_values) else sorted_values[0]
-
- return {
- "volatility": volatility,
- "max_drawdown": max_drawdown,
- "sharpe_ratio": sharpe_ratio,
- "var_95": var_95,
- "mean": mean_val,
- "median": statistics.median(values)
- }
-
-def create_economic_summary(data_points: List) -> Dict[str, Any]:
- """
- Create summary statistics for multiple economic data points
-
- Args:
- data_points (List): List of EconomicData objects
-
- Returns:
- Dict[str, Any]: Summary statistics
- """
- if not data_points:
- return {"error": "No data points provided"}
-
- # Extract values for each indicator
- gdp_values = [dp.gdp for dp in data_points]
- inflation_values = [dp.inflation for dp in data_points]
- unemployment_values = [dp.unemployment for dp in data_points]
- interest_values = [dp.interest_rate for dp in data_points]
-
- summary = {
- "data_points_count": len(data_points),
- "date_range": {
- "start": min(dp.timestamp for dp in data_points).strftime("%Y-%m-%d"),
- "end": max(dp.timestamp for dp in data_points).strftime("%Y-%m-%d")
- },
- "indicators": {
- "gdp": calculate_trend(gdp_values),
- "inflation": calculate_trend(inflation_values),
- "unemployment": calculate_trend(unemployment_values),
- "interest_rate": calculate_trend(interest_values)
- }
- }
-
- return summary
-
-def export_to_json(data: Any, filename: str, indent: int = 2) -> bool:
- """
- Export data to JSON file
-
- Args:
- data (Any): Data to export
- filename (str): Output filename
- indent (int): JSON indentation
-
- Returns:
- bool: Success status
- """
- try:
- with open(filename, 'w') as f:
- json.dump(data, f, indent=indent, default=str)
- return True
- except Exception as e:
- print(f"Error exporting to JSON: {e}")
- return False
-
-def export_to_csv(data: List[Dict], filename: str) -> bool:
- """
- Export data to CSV file
-
- Args:
- data (List[Dict]): List of dictionaries to export
- filename (str): Output filename
-
- Returns:
- bool: Success status
- """
- if not data:
- return False
-
- try:
- with open(filename, 'w', newline='') as csvfile:
- fieldnames = data[0].keys()
- writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
- writer.writeheader()
- writer.writerows(data)
- return True
- except Exception as e:
- print(f"Error exporting to CSV: {e}")
- return False
-
-def clamp_value(value: float, min_val: float, max_val: float) -> float:
- """
- Clamp a value between min and max bounds
-
- Args:
- value (float): Value to clamp
- min_val (float): Minimum bound
- max_val (float): Maximum bound
-
- Returns:
- float: Clamped value
- """
- return max(min_val, min(max_val, value))
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/bill_miller_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/bill_miller_agent.py
deleted file mode 100644
index 067eb8e12..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/bill_miller_agent.py
+++ /dev/null
@@ -1,393 +0,0 @@
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - ticker symbols (array)
-# - end_date (string)
-# - FINANCIAL_DATASETS_API_KEY
-#
-# OUTPUT:
-# - Financial metrics: ROE, D/E, Current Ratio
-# - Financial line items: Revenue, Net Income, FCF, Debt, Equity, Retained Earnings, Operating Margin, R&D, Shares
-# - Market Cap
-#
-# PARAMETERS:
-# - period="annual"
-# - limit=10 years
-"""
-
-from fincept_terminal.Agents.src.graph.state import AgentState, show_agent_reasoning
-from fincept_terminal.Agents.src.tools.api import get_financial_metrics, get_market_cap, search_line_items
-from langchain_core.prompts import ChatPromptTemplate
-from langchain_core.messages import HumanMessage
-from pydantic import BaseModel
-import json
-from typing_extensions import Literal
-from fincept_terminal.Agents.src.utils.progress import progress
-from fincept_terminal.Agents.src.utils.llm import call_llm
-from fincept_terminal.Agents.src.utils.api_key import get_api_key_from_state
-
-
-class MillerSignal(BaseModel):
- signal: Literal["bullish", "bearish", "neutral"]
- confidence: float
- reasoning: str
-
-
-def bill_miller_agent(state: AgentState, agent_id: str = "bill_miller_agent"):
- """
- Bill Miller: Concentrated value, contrarian timing
- Focus: Technology value plays, contrarian bets, concentrated positions
- """
- data = state["data"]
- end_date = data["end_date"]
- tickers = data["tickers"]
- api_key = get_api_key_from_state(state, "FINANCIAL_DATASETS_API_KEY")
- analysis_data = {}
- miller_analysis = {}
-
- for ticker in tickers:
- progress.update_status(agent_id, ticker, "Analyzing contrarian value opportunity")
- metrics = get_financial_metrics(ticker, end_date, period="annual", limit=7, api_key=api_key)
-
- financial_line_items = search_line_items(
- ticker,
- [
- "revenue", "net_income", "free_cash_flow", "total_assets",
- "shareholders_equity", "total_debt", "research_and_development",
- "operating_income", "outstanding_shares"
- ],
- end_date,
- period="annual",
- limit=7,
- api_key=api_key,
- )
-
- market_cap = get_market_cap(ticker, end_date, api_key=api_key)
-
- # Miller's analytical framework
- contrarian_opportunity = analyze_contrarian_setup(metrics, financial_line_items, market_cap)
- technology_value = analyze_technology_value_potential(financial_line_items, market_cap)
- long_term_drivers = analyze_long_term_growth_drivers(financial_line_items)
- market_misperception = identify_market_misperceptions(metrics, financial_line_items)
- concentration_worthiness = evaluate_concentration_candidate(metrics, financial_line_items, market_cap)
-
- # Miller's conviction-weighted scoring
- total_score = (
- contrarian_opportunity["score"] * 0.3 +
- concentration_worthiness["score"] * 0.25 +
- technology_value["score"] * 0.2 +
- long_term_drivers["score"] * 0.15 +
- market_misperception["score"] * 0.1
- )
-
- # Miller's high-conviction approach
- if total_score >= 8.0:
- signal = "bullish"
- elif total_score <= 4.0:
- signal = "bearish"
- else:
- signal = "neutral"
-
- analysis_data[ticker] = {
- "signal": signal,
- "score": total_score,
- "contrarian_opportunity": contrarian_opportunity,
- "technology_value": technology_value,
- "long_term_drivers": long_term_drivers,
- "market_misperception": market_misperception,
- "concentration_worthiness": concentration_worthiness
- }
-
- miller_output = generate_miller_output(ticker, analysis_data, state, agent_id)
-
- miller_analysis[ticker] = {
- "signal": miller_output.signal,
- "confidence": miller_output.confidence,
- "reasoning": miller_output.reasoning
- }
-
- progress.update_status(agent_id, ticker, "Done", analysis=miller_output.reasoning)
-
- message = HumanMessage(content=json.dumps(miller_analysis), name=agent_id)
-
- if state["metadata"]["show_reasoning"]:
- show_agent_reasoning(miller_analysis, "Bill Miller Agent")
-
- state["data"]["analyst_signals"][agent_id] = miller_analysis
- progress.update_status(agent_id, None, "Done")
-
- return {"messages": [message], "data": state["data"]}
-
-
-def analyze_contrarian_setup(metrics: list, financial_line_items: list, market_cap: float) -> dict:
- """Miller's contrarian opportunity identification"""
- score = 0
- details = []
-
- if not metrics or not financial_line_items:
- return {"score": 0, "details": "No contrarian data"}
-
- latest_metrics = metrics[0]
-
- # Extreme valuation as contrarian signal
- if latest_metrics.price_to_earnings:
- if latest_metrics.price_to_earnings < 8: # Extremely cheap
- score += 3
- details.append(f"Extreme valuation contrarian setup: {latest_metrics.price_to_earnings:.1f} P/E")
- elif latest_metrics.price_to_earnings < 12:
- score += 2
- details.append(f"Attractive contrarian valuation: {latest_metrics.price_to_earnings:.1f} P/E")
-
- # Market sentiment indicators
- if latest_metrics.price_to_book and latest_metrics.price_to_book < 1.0:
- score += 2
- details.append(f"Market pessimism: {latest_metrics.price_to_book:.2f} P/B below 1.0")
-
- # Temporary business challenges creating opportunity
- earnings = [item.net_income for item in financial_line_items if item.net_income]
- revenues = [item.revenue for item in financial_line_items if item.revenue]
-
- if len(earnings) >= 5 and len(revenues) >= 5:
- recent_earnings_decline = earnings[0] < earnings[2] # Current vs 2 years ago
- revenue_resilience = revenues[0] > revenues[2] * 0.9 # Revenue holding up
-
- if recent_earnings_decline and revenue_resilience:
- score += 2
- details.append("Temporary earnings pressure with revenue resilience - contrarian opportunity")
-
- # Technology disruption creating value
- rd_vals = [item.research_and_development for item in financial_line_items if item.research_and_development]
- if rd_vals and revenues:
- rd_intensity = sum(rd_vals[:3]) / sum(revenues[:3]) if len(revenues) >= 3 else 0
- if rd_intensity > 0.1: # 10%+ R&D intensity
- score += 1
- details.append(f"High R&D investment for future positioning: {rd_intensity:.1%}")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_technology_value_potential(financial_line_items: list, market_cap: float) -> dict:
- """Miller's technology value analysis"""
- score = 0
- details = []
-
- if not financial_line_items or not market_cap:
- return {"score": 0, "details": "No technology data"}
-
- latest = financial_line_items[0]
-
- # Asset-light technology model
- if latest.total_assets and latest.revenue:
- asset_turnover = latest.revenue / latest.total_assets
- if asset_turnover > 1.0: # Efficient asset utilization
- score += 2
- details.append(f"Asset-efficient model: {asset_turnover:.1f}x turnover")
-
- # Scalability indicators
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- margins = []
- for item in financial_line_items:
- if item.operating_income and item.revenue and item.revenue > 0:
- margins.append(item.operating_income / item.revenue)
-
- if len(revenues) >= 3 and len(margins) >= 3:
- revenue_growth = (revenues[0] / revenues[-1]) ** (1 / len(revenues)) - 1
- margin_expansion = margins[0] - margins[-1]
-
- if revenue_growth > 0.1 and margin_expansion > 0.02: # Growth with margin expansion
- score += 3
- details.append(f"Scalable growth: {revenue_growth:.1%} revenue CAGR with margin expansion")
-
- # R&D efficiency
- rd_vals = [item.research_and_development for item in financial_line_items if item.research_and_development]
- if rd_vals and revenues:
- rd_to_revenue = rd_vals[0] / revenues[0] if revenues[0] > 0 else 0
- if 0.05 <= rd_to_revenue <= 0.2: # 5-20% R&D ratio
- score += 1
- details.append(f"Strategic R&D investment: {rd_to_revenue:.1%} of revenue")
-
- # Network effects and switching costs (proxy)
- if latest.free_cash_flow and latest.free_cash_flow > 0:
- fcf_margin = latest.free_cash_flow / latest.revenue if latest.revenue > 0 else 0
- if fcf_margin > 0.2: # 20%+ FCF margin
- score += 2
- details.append(f"High-margin business model: {fcf_margin:.1%} FCF margin")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_long_term_growth_drivers(financial_line_items: list) -> dict:
- """Miller's long-term growth potential analysis"""
- score = 0
- details = []
-
- if not financial_line_items:
- return {"score": 0, "details": "No growth data"}
-
- # Consistent revenue growth trend
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if len(revenues) >= 5:
- growth_years = sum(1 for i in range(len(revenues) - 1) if revenues[i] >= revenues[i + 1])
- if growth_years >= len(revenues) * 0.8: # 80%+ growth years
- revenue_cagr = (revenues[0] / revenues[-1]) ** (1 / len(revenues)) - 1
- score += 2
- details.append(f"Consistent growth track record: {revenue_cagr:.1%} CAGR")
-
- # Reinvestment for growth
- rd_vals = [item.research_and_development for item in financial_line_items if item.research_and_development]
- if rd_vals and len(rd_vals) >= 3:
- rd_growth = (rd_vals[0] / rd_vals[-1]) ** (1 / len(rd_vals)) - 1
- if rd_growth > 0.1: # 10%+ R&D growth
- score += 1
- details.append(f"Growing R&D investment: {rd_growth:.1%} CAGR")
-
- # Market expansion capability
- if latest.total_assets and latest.shareholders_equity:
- leverage_capacity = (latest.total_assets - latest.shareholders_equity) / latest.shareholders_equity
- if leverage_capacity < 0.5: # Low leverage = expansion capacity
- score += 1
- details.append("Balance sheet capacity for growth investments")
-
- # Free cash flow reinvestment
- fcf_vals = [item.free_cash_flow for item in financial_line_items if item.free_cash_flow]
- if fcf_vals and revenues:
- positive_fcf_years = sum(1 for fcf in fcf_vals if fcf > 0)
- if positive_fcf_years >= len(fcf_vals) * 0.8: # Consistent cash generation
- score += 2
- details.append(f"Self-funding growth capability: {positive_fcf_years}/{len(fcf_vals)} positive FCF years")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def identify_market_misperceptions(metrics: list, financial_line_items: list) -> dict:
- """Miller's market misperception identification"""
- score = 0
- details = []
-
- if not metrics or not financial_line_items:
- return {"score": 0, "details": "No misperception data"}
-
- latest_metrics = metrics[0]
-
- # Quality company trading at value multiple
- if (latest_metrics.return_on_equity and latest_metrics.return_on_equity > 0.15 and
- latest_metrics.price_to_earnings and latest_metrics.price_to_earnings < 15):
- score += 3
- details.append(
- f"Quality-value disconnect: {latest_metrics.return_on_equity:.1%} ROE at {latest_metrics.price_to_earnings:.1f} P/E")
-
- # Growth company with temporary headwinds
- earnings = [item.net_income for item in financial_line_items if item.net_income and item.net_income > 0]
- revenues = [item.revenue for item in financial_line_items if item.revenue]
-
- if len(earnings) >= 5 and len(revenues) >= 5:
- historical_earnings_growth = (earnings[-1] / earnings[-3]) ** (1 / 2) - 1 # Earlier period growth
- recent_earnings_decline = earnings[0] < earnings[1]
- revenue_growth = (revenues[0] / revenues[-1]) ** (1 / len(revenues)) - 1
-
- if historical_earnings_growth > 0.15 and recent_earnings_decline and revenue_growth > 0.05:
- score += 2
- details.append("Historical growth company with temporary earnings setback")
-
- # Asset value not recognized
- if latest_metrics.price_to_book and latest_metrics.price_to_book < 1.2:
- latest_financial = financial_line_items[0]
- if latest_financial.total_assets and latest_financial.total_debt:
- tangible_assets = latest_financial.total_assets - latest_financial.total_debt
- if tangible_assets > 0:
- score += 1
- details.append(f"Asset value misperception: {latest_metrics.price_to_book:.2f} P/B")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def evaluate_concentration_candidate(metrics: list, financial_line_items: list, market_cap: float) -> dict:
- """Miller's concentrated portfolio candidate evaluation"""
- score = 0
- details = []
-
- if not metrics or not financial_line_items or not market_cap:
- return {"score": 0, "details": "No concentration data"}
-
- latest_metrics = metrics[0]
-
- # High conviction criteria
- # Strong competitive position
- if latest_metrics.return_on_equity and latest_metrics.return_on_equity > 0.18:
- score += 2
- details.append(f"Strong competitive position: {latest_metrics.return_on_equity:.1%} ROE")
-
- # Significant upside potential
- if latest_metrics.price_to_earnings and latest_metrics.price_to_earnings < 12:
- earnings = [item.net_income for item in financial_line_items if item.net_income and item.net_income > 0]
- if earnings:
- # Assume normal multiple of 18x
- upside_potential = (18 * earnings[0]) / market_cap - 1
- if upside_potential > 0.5: # 50%+ upside
- score += 3
- details.append(f"Significant upside potential: {upside_potential:.1%}")
-
- # Business model durability
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if revenues and len(revenues) >= 7:
- revenue_consistency = len([r for r in revenues if r > min(revenues) * 1.1]) / len(revenues)
- if revenue_consistency > 0.8: # 80%+ years above minimum
- score += 2
- details.append("Durable business model with consistent revenue growth")
-
- # Management execution track record
- if latest_metrics.return_on_invested_capital and latest_metrics.return_on_invested_capital > 0.12:
- score += 1
- details.append(f"Strong capital allocation: {latest_metrics.return_on_invested_capital:.1%} ROIC")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def generate_miller_output(ticker: str, analysis_data: dict, state: AgentState, agent_id: str) -> MillerSignal:
- """Generate Miller-style contrarian value decision"""
- template = ChatPromptTemplate.from_messages([
- ("system", """You are Bill Miller's AI agent, applying contrarian value investing with technology focus:
-
- 1. Contrarian timing: Buy when others are selling, especially in technology
- 2. Concentrated bets: Make large positions in high-conviction ideas
- 3. Technology value: Find undervalued technology and growth companies
- 4. Long-term perspective: Focus on 3-5 year value creation
- 5. Market misperceptions: Identify when market misprices quality companies
- 6. Fundamental analysis: Deep research into business models and competitive advantages
- 7. Patient opportunism: Wait for exceptional risk/reward opportunities
-
- Reasoning style:
- - Emphasize contrarian opportunities and market misperceptions
- - Focus on technology companies trading at value multiples
- - Discuss long-term growth drivers and competitive positioning
- - Consider concentration worthiness and conviction level
- - Express willingness to be different from consensus
- - Analyze both current challenges and future potential
- - Apply rigorous fundamental analysis
-
- Return bullish for high-conviction contrarian opportunities with significant upside potential."""),
-
- ("human", """Apply contrarian value analysis to {ticker}:
-
- {analysis_data}
-
- Provide investment signal in JSON format:
- {{
- "signal": "bullish" | "bearish" | "neutral",
- "confidence": float (0-100),
- "reasoning": "string"
- }}""")
- ])
-
- prompt = template.invoke({"analysis_data": json.dumps(analysis_data, indent=2), "ticker": ticker})
-
- def create_default_miller_signal():
- return MillerSignal(signal="neutral", confidence=0.0, reasoning="Analysis error, defaulting to neutral")
-
- return call_llm(
- prompt=prompt,
- pydantic_model=MillerSignal,
- agent_name=agent_id,
- state=state,
- default_factory=create_default_miller_signal,
- )
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/charlie_munger_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/charlie_munger_agent.py
deleted file mode 100644
index a798a2b4f..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/charlie_munger_agent.py
+++ /dev/null
@@ -1,391 +0,0 @@
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - ticker symbols (array)
-# - end_date (string)
-# - FINANCIAL_DATASETS_API_KEY
-#
-# OUTPUT:
-# - Financial metrics: ROE, D/E, Current Ratio
-# - Financial line items: Revenue, Net Income, FCF, Debt, Equity, Retained Earnings, Operating Margin, R&D, Shares
-# - Market Cap
-#
-# PARAMETERS:
-# - period="annual"
-# - limit=10 years
-"""
-
-from fincept_terminal.Agents.src.graph.state import AgentState, show_agent_reasoning
-from fincept_terminal.Agents.src.tools.api import get_financial_metrics, get_market_cap, search_line_items
-from langchain_core.prompts import ChatPromptTemplate
-from langchain_core.messages import HumanMessage
-from pydantic import BaseModel
-import json
-from typing_extensions import Literal
-from fincept_terminal.Agents.src.utils.progress import progress
-from fincept_terminal.Agents.src.utils.llm import call_llm
-from fincept_terminal.Agents.src.utils.api_key import get_api_key_from_state
-
-
-class MungerSignal(BaseModel):
- signal: Literal["bullish", "bearish", "neutral"]
- confidence: float
- reasoning: str
-
-
-def charlie_munger_agent(state: AgentState, agent_id: str = "charlie_munger_agent"):
- """
- Charlie Munger: Mental models, quality businesses, patience
- Focus: Multidisciplinary thinking, concentrated bets, long-term compounding
- """
- data = state["data"]
- end_date = data["end_date"]
- tickers = data["tickers"]
- api_key = get_api_key_from_state(state, "FINANCIAL_DATASETS_API_KEY")
- analysis_data = {}
- munger_analysis = {}
-
- for ticker in tickers:
- progress.update_status(agent_id, ticker, "Applying multidisciplinary mental models")
- metrics = get_financial_metrics(ticker, end_date, period="annual", limit=10, api_key=api_key)
-
- financial_line_items = search_line_items(
- ticker,
- [
- "revenue", "net_income", "free_cash_flow", "shareholders_equity",
- "total_debt", "retained_earnings", "operating_margin",
- "research_and_development", "outstanding_shares", "total_assets"
- ],
- end_date,
- period="annual",
- limit=10,
- api_key=api_key,
- )
-
- market_cap = get_market_cap(ticker, end_date, api_key=api_key)
-
- # Munger's mental model analyses
- business_quality = analyze_mental_model_quality(metrics, financial_line_items)
- moat_durability = analyze_competitive_moat_durability(metrics, financial_line_items)
- management_rationality = analyze_management_rationality(financial_line_items)
- compound_growth = analyze_compounding_potential(financial_line_items)
- incentive_alignment = analyze_incentive_structures(financial_line_items)
-
- # Munger's weighted approach (fewer, better decisions)
- total_score = (
- business_quality["score"] * 0.3 +
- moat_durability["score"] * 0.25 +
- management_rationality["score"] * 0.2 +
- compound_growth["score"] * 0.15 +
- incentive_alignment["score"] * 0.1
- )
-
- # Munger's high-conviction approach
- if total_score >= 8.5: # Very high bar
- signal = "bullish"
- elif total_score <= 3.0:
- signal = "bearish"
- else:
- signal = "neutral"
-
- analysis_data[ticker] = {
- "signal": signal,
- "score": total_score,
- "business_quality": business_quality,
- "moat_durability": moat_durability,
- "management_rationality": management_rationality,
- "compound_growth": compound_growth,
- "incentive_alignment": incentive_alignment
- }
-
- munger_output = generate_munger_output(ticker, analysis_data, state, agent_id)
-
- munger_analysis[ticker] = {
- "signal": munger_output.signal,
- "confidence": munger_output.confidence,
- "reasoning": munger_output.reasoning
- }
-
- progress.update_status(agent_id, ticker, "Done", analysis=munger_output.reasoning)
-
- message = HumanMessage(content=json.dumps(munger_analysis), name=agent_id)
-
- if state["metadata"]["show_reasoning"]:
- show_agent_reasoning(munger_analysis, "Charlie Munger Agent")
-
- state["data"]["analyst_signals"][agent_id] = munger_analysis
- progress.update_status(agent_id, None, "Done")
-
- return {"messages": [message], "data": state["data"]}
-
-
-def analyze_mental_model_quality(metrics: list, financial_line_items: list) -> dict:
- """Munger's multidisciplinary analysis of business quality"""
- score = 0
- details = []
-
- if not metrics or not financial_line_items:
- return {"score": 0, "details": "No data for quality analysis"}
-
- # Psychology model: Customer psychology and habits
- # Measured by revenue consistency and margin stability
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if revenues and len(revenues) >= 5:
- revenue_volatility = (max(revenues) - min(revenues)) / max(revenues)
- if revenue_volatility < 0.2: # Stable customer behavior
- score += 2
- details.append(f"Stable customer psychology: {revenue_volatility:.1%} revenue volatility")
-
- # Economics model: High return on capital
- roic_vals = [m.return_on_invested_capital for m in metrics if m.return_on_invested_capital]
- if roic_vals:
- avg_roic = sum(roic_vals) / len(roic_vals)
- if avg_roic > 0.15: # 15%+ ROIC consistently
- score += 3
- details.append(f"Superior capital efficiency: {avg_roic:.1%} avg ROIC")
-
- # Math model: Compound growth potential
- earnings = [item.net_income for item in financial_line_items if item.net_income and item.net_income > 0]
- if len(earnings) >= 5:
- cagr = (earnings[0] / earnings[-1]) ** (1 / len(earnings)) - 1
- if cagr > 0.1: # 10%+ earnings CAGR
- score += 2
- details.append(f"Compounding machine: {cagr:.1%} earnings CAGR")
-
- # Physics model: Competitive forces and market position
- margins = [item.operating_margin for item in financial_line_items if item.operating_margin]
- if margins:
- avg_margin = sum(margins) / len(margins)
- if avg_margin > 0.2: # 20%+ operating margins
- score += 2
- details.append(f"Pricing power evidence: {avg_margin:.1%} avg operating margin")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_competitive_moat_durability(metrics: list, financial_line_items: list) -> dict:
- """Munger's focus on durable competitive advantages"""
- score = 0
- details = []
-
- if not metrics:
- return {"score": 0, "details": "No metrics for moat analysis"}
-
- # Consistent high returns (sign of moat)
- roe_vals = [m.return_on_equity for m in metrics if m.return_on_equity]
- if roe_vals:
- high_roe_years = sum(1 for roe in roe_vals if roe > 0.15)
- if high_roe_years >= len(roe_vals) * 0.8: # 80% of years
- score += 3
- details.append(f"Durable high returns: {high_roe_years}/{len(roe_vals)} years ROE >15%")
-
- # Market share stability (revenue growth matching/exceeding market)
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if len(revenues) >= 5:
- growth_consistency = sum(1 for i in range(len(revenues) - 1) if revenues[i] >= revenues[i + 1])
- if growth_consistency >= len(revenues) * 0.7:
- score += 2
- details.append("Market position strength: consistent revenue progression")
-
- # R&D efficiency (innovation moat)
- rd_vals = [item.research_and_development for item in financial_line_items if item.research_and_development]
- if rd_vals and revenues:
- rd_intensity = sum(rd_vals) / sum(revenues[:len(rd_vals)])
- if 0.05 <= rd_intensity <= 0.15: # Efficient innovation spend
- score += 2
- details.append(f"Innovation moat: {rd_intensity:.1%} R&D efficiency")
-
- # Capital requirements (barrier to entry)
- assets = [item.total_assets for item in financial_line_items if item.total_assets]
- if assets and revenues:
- asset_turnover = revenues[0] / assets[0] if assets[0] > 0 else 0
- if asset_turnover > 1.5: # Asset-light model
- score += 1
- details.append(f"Capital-efficient model: {asset_turnover:.1f}x asset turnover")
- elif asset_turnover < 0.5: # High barriers
- score += 1
- details.append(f"High barriers to entry: {asset_turnover:.1f}x asset turnover")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_management_rationality(financial_line_items: list) -> dict:
- """Munger's assessment of management decision-making"""
- score = 0
- details = []
-
- if not financial_line_items:
- return {"score": 0, "details": "No data for management analysis"}
-
- # Capital allocation rationality
- fcf_vals = [item.free_cash_flow for item in financial_line_items if item.free_cash_flow]
- retained_earnings = [item.retained_earnings for item in financial_line_items if item.retained_earnings]
-
- if len(retained_earnings) >= 3:
- # Check if retained earnings are creating value
- re_growth = (retained_earnings[0] - retained_earnings[-1]) / abs(retained_earnings[-1])
- if re_growth > 0.5: # 50%+ growth in retained earnings
- score += 2
- details.append(f"Value-creating reinvestment: {re_growth:.1%} retained earnings growth")
-
- # Share buyback rationality (buying when cheap)
- shares = [item.outstanding_shares for item in financial_line_items if item.outstanding_shares]
- earnings = [item.net_income for item in financial_line_items if item.net_income and item.net_income > 0]
-
- if len(shares) >= 3 and len(earnings) >= 3:
- share_reduction = (shares[-1] - shares[0]) / shares[-1]
- earnings_growth = (earnings[0] - earnings[-1]) / earnings[-1]
-
- if share_reduction > 0.05 and earnings_growth > share_reduction:
- score += 2
- details.append("Rational buybacks: reducing shares while growing earnings")
-
- # Debt management
- debt_vals = [item.total_debt for item in financial_line_items if item.total_debt is not None]
- if debt_vals:
- if all(debt <= debt_vals[0] * 1.1 for debt in debt_vals): # Controlled debt growth
- score += 1
- details.append("Conservative debt management")
-
- # Dividend policy consistency
- # Note: Would need dividend data for full analysis
- if fcf_vals and all(fcf > 0 for fcf in fcf_vals):
- score += 1
- details.append("Consistent cash generation enables rational capital allocation")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_compounding_potential(financial_line_items: list) -> dict:
- """Munger's emphasis on long-term compounding"""
- score = 0
- details = []
-
- if not financial_line_items:
- return {"score": 0, "details": "No data for compounding analysis"}
-
- # Revenue compounding
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if len(revenues) >= 5:
- revenue_cagr = (revenues[0] / revenues[-1]) ** (1 / len(revenues)) - 1
- if revenue_cagr > 0.1:
- score += 2
- details.append(f"Revenue compounding: {revenue_cagr:.1%} CAGR")
-
- # Earnings compounding quality
- earnings = [item.net_income for item in financial_line_items if item.net_income and item.net_income > 0]
- if len(earnings) >= 5:
- earnings_cagr = (earnings[0] / earnings[-1]) ** (1 / len(earnings)) - 1
- if earnings_cagr > revenue_cagr if 'revenue_cagr' in locals() else 0.08:
- score += 2
- details.append(f"Earnings leverage: {earnings_cagr:.1%} CAGR")
-
- # Free cash flow compounding
- fcf_vals = [item.free_cash_flow for item in financial_line_items if item.free_cash_flow and item.free_cash_flow > 0]
- if len(fcf_vals) >= 3:
- fcf_growth = (fcf_vals[0] / fcf_vals[-1]) ** (1 / len(fcf_vals)) - 1
- if fcf_growth > 0.12: # 12%+ FCF growth
- score += 3
- details.append(f"Cash compounding: {fcf_growth:.1%} FCF CAGR")
-
- # Reinvestment rate efficiency
- if retained_earnings and len(retained_earnings) >= 3:
- reinvestment_efficiency = earnings_cagr / (
- retained_earnings[0] / revenues[0]) if 'earnings_cagr' in locals() and revenues else 0
- if reinvestment_efficiency > 2.0: # High returns on reinvestment
- score += 1
- details.append("Efficient reinvestment compounding")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_incentive_structures(financial_line_items: list) -> dict:
- """Munger's focus on proper incentive alignment"""
- score = 0
- details = []
-
- if not financial_line_items:
- return {"score": 0, "details": "No data for incentive analysis"}
-
- # Management ownership alignment (proxy through performance)
- # If management is aligned, we should see improving metrics over time
-
- # Consistent margin improvement (management efficiency)
- margins = [item.operating_margin for item in financial_line_items if item.operating_margin]
- if len(margins) >= 3:
- margin_trend = sum(1 for i in range(len(margins) - 1) if margins[i] >= margins[i + 1])
- if margin_trend >= len(margins) * 0.6:
- score += 2
- details.append("Management efficiency: improving operational margins")
-
- # Capital efficiency improvement
- assets = [item.total_assets for item in financial_line_items if item.total_assets]
- revenues = [item.revenue for item in financial_line_items if item.revenue]
-
- if len(assets) >= 3 and len(revenues) >= 3:
- recent_efficiency = revenues[0] / assets[0] if assets[0] > 0 else 0
- older_efficiency = revenues[-1] / assets[-1] if assets[-1] > 0 else 0
-
- if recent_efficiency > older_efficiency * 1.1:
- score += 1
- details.append("Improving capital efficiency over time")
-
- # Long-term value creation focus
- shareholders_equity = [item.shareholders_equity for item in financial_line_items if item.shareholders_equity]
- if len(shareholders_equity) >= 5:
- equity_cagr = (shareholders_equity[0] / shareholders_equity[-1]) ** (1 / len(shareholders_equity)) - 1
- if equity_cagr > 0.1:
- score += 2
- details.append(f"Shareholder value creation: {equity_cagr:.1%} equity CAGR")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def generate_munger_output(ticker: str, analysis_data: dict, state: AgentState, agent_id: str) -> MungerSignal:
- """Generate Munger-style investment decision using mental models"""
- template = ChatPromptTemplate.from_messages([
- ("system", """You are Charlie Munger's AI agent, applying multidisciplinary mental models to investing:
-
- 1. Mental Models: Psychology, economics, math, physics applied to business analysis
- 2. Quality over quantity: "It's better to buy a wonderful company at a fair price"
- 3. Long-term compounding: "The first rule of compounding is to never interrupt it unnecessarily"
- 4. Rational management: Assess capital allocation and incentive alignment
- 5. Durable moats: Sustainable competitive advantages over decades
- 6. Concentrated bets: "Diversification is protection against ignorance"
- 7. Patience and discipline: Wait for exceptional opportunities
-
- Reasoning style:
- - Use multidisciplinary frameworks and analogies
- - Emphasize long-term thinking and compounding
- - Focus on business quality and management rationality
- - Apply inverse thinking: "What could go wrong?"
- - Reference mental models and psychological biases
- - Express strong convictions when warranted
- - Admit when outside circle of competence
-
- Return bullish only for exceptional businesses with durable moats and rational management."""),
-
- ("human", """Apply multidisciplinary mental models to analyze {ticker}:
-
- {analysis_data}
-
- Provide investment signal in JSON format:
- {{
- "signal": "bullish" | "bearish" | "neutral",
- "confidence": float (0-100),
- "reasoning": "string"
- }}""")
- ])
-
- prompt = template.invoke({"analysis_data": json.dumps(analysis_data, indent=2), "ticker": ticker})
-
- def create_default_munger_signal():
- return MungerSignal(signal="neutral", confidence=0.0, reasoning="Analysis error, defaulting to neutral")
-
- return call_llm(
- prompt=prompt,
- pydantic_model=MungerSignal,
- agent_name=agent_id,
- state=state,
- default_factory=create_default_munger_signal,
- )
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/david_einhorn_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/david_einhorn_agent.py
deleted file mode 100644
index a322257fa..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/david_einhorn_agent.py
+++ /dev/null
@@ -1,427 +0,0 @@
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - ticker symbols (array)
-# - end_date (string)
-# - FINANCIAL_DATASETS_API_KEY
-#
-# OUTPUT:
-# - Financial metrics: ROE, D/E, Current Ratio
-# - Financial line items: Revenue, Net Income, FCF, Debt, Equity, Retained Earnings, Operating Margin, R&D, Shares
-# - Market Cap
-#
-# PARAMETERS:
-# - period="annual"
-# - limit=10 years
-"""
-
-from fincept_terminal.Agents.src.graph.state import AgentState, show_agent_reasoning
-from fincept_terminal.Agents.src.tools.api import get_financial_metrics, get_market_cap, search_line_items
-from langchain_core.prompts import ChatPromptTemplate
-from langchain_core.messages import HumanMessage
-from pydantic import BaseModel
-import json
-from typing_extensions import Literal
-from fincept_terminal.Agents.src.utils.progress import progress
-from fincept_terminal.Agents.src.utils.llm import call_llm
-from fincept_terminal.Agents.src.utils.api_key import get_api_key_from_state
-
-
-class EinhornSignal(BaseModel):
- signal: Literal["bullish", "bearish", "neutral"]
- confidence: float
- reasoning: str
-
-
-def david_einhorn_agent(state: AgentState, agent_id: str = "david_einhorn_agent"):
- """
- David Einhorn: Short selling + value, forensic accounting
- Focus: Accounting irregularities, overvalued shorts, undervalued longs
- """
- data = state["data"]
- end_date = data["end_date"]
- tickers = data["tickers"]
- api_key = get_api_key_from_state(state, "FINANCIAL_DATASETS_API_KEY")
- analysis_data = {}
- einhorn_analysis = {}
-
- for ticker in tickers:
- progress.update_status(agent_id, ticker, "Conducting forensic accounting analysis")
- metrics = get_financial_metrics(ticker, end_date, period="annual", limit=5, api_key=api_key)
-
- financial_line_items = search_line_items(
- ticker,
- [
- "revenue", "net_income", "operating_income", "free_cash_flow",
- "total_assets", "current_assets", "accounts_receivable",
- "inventory", "total_debt", "shareholders_equity", "depreciation"
- ],
- end_date,
- period="annual",
- limit=5,
- api_key=api_key,
- )
-
- market_cap = get_market_cap(ticker, end_date, api_key=api_key)
-
- # Einhorn's analytical framework
- accounting_quality = analyze_accounting_quality(financial_line_items)
- earnings_quality = analyze_earnings_vs_cash_flow(financial_line_items)
- valuation_vs_reality = analyze_valuation_disconnect(metrics, financial_line_items, market_cap)
- red_flags = identify_red_flags(financial_line_items)
- fundamental_value = calculate_fundamental_value(financial_line_items, market_cap)
-
- # Einhorn's long/short framework
- total_score = (
- accounting_quality["score"] * 0.25 +
- earnings_quality["score"] * 0.25 +
- fundamental_value["score"] * 0.2 +
- valuation_vs_reality["score"] * 0.2 +
- red_flags["score"] * 0.1
- )
-
- # Einhorn's approach: strong convictions both ways
- if total_score >= 7.5:
- signal = "bullish"
- elif total_score <= 3.5:
- signal = "bearish"
- else:
- signal = "neutral"
-
- analysis_data[ticker] = {
- "signal": signal,
- "score": total_score,
- "accounting_quality": accounting_quality,
- "earnings_quality": earnings_quality,
- "valuation_vs_reality": valuation_vs_reality,
- "red_flags": red_flags,
- "fundamental_value": fundamental_value
- }
-
- einhorn_output = generate_einhorn_output(ticker, analysis_data, state, agent_id)
-
- einhorn_analysis[ticker] = {
- "signal": einhorn_output.signal,
- "confidence": einhorn_output.confidence,
- "reasoning": einhorn_output.reasoning
- }
-
- progress.update_status(agent_id, ticker, "Done", analysis=einhorn_output.reasoning)
-
- message = HumanMessage(content=json.dumps(einhorn_analysis), name=agent_id)
-
- if state["metadata"]["show_reasoning"]:
- show_agent_reasoning(einhorn_analysis, "David Einhorn Agent")
-
- state["data"]["analyst_signals"][agent_id] = einhorn_analysis
- progress.update_status(agent_id, None, "Done")
-
- return {"messages": [message], "data": state["data"]}
-
-
-def analyze_accounting_quality(financial_line_items: list) -> dict:
- """Einhorn's forensic accounting analysis"""
- score = 0
- details = []
- red_flags = []
-
- if not financial_line_items:
- return {"score": 0, "details": "No accounting data"}
-
- # Revenue quality analysis
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- receivables = [item.accounts_receivable for item in financial_line_items if item.accounts_receivable]
-
- if len(revenues) >= 3 and len(receivables) >= 3:
- # Days sales outstanding trend
- recent_dso = (receivables[0] / revenues[0]) * 365 if revenues[0] > 0 else 0
- older_dso = (receivables[-1] / revenues[-1]) * 365 if revenues[-1] > 0 else 0
-
- if recent_dso > older_dso * 1.3: # 30%+ increase in DSO
- red_flags.append("Deteriorating receivables collection")
- score -= 2
- elif recent_dso < older_dso * 1.1: # Stable or improving
- score += 1
- details.append("Stable receivables management")
-
- # Inventory quality
- inventories = [item.inventory for item in financial_line_items if item.inventory]
- if len(inventories) >= 3 and len(revenues) >= 3:
- recent_inventory_turns = revenues[0] / inventories[0] if inventories[0] > 0 else 0
- older_inventory_turns = revenues[-1] / inventories[-1] if inventories[-1] > 0 else 0
-
- if recent_inventory_turns < older_inventory_turns * 0.8: # Slowing turns
- red_flags.append("Deteriorating inventory turns")
- score -= 1
- elif recent_inventory_turns > older_inventory_turns * 1.1:
- score += 1
- details.append("Improving inventory management")
-
- # Asset quality
- assets = [item.total_assets for item in financial_line_items if item.total_assets]
- if len(assets) >= 3:
- asset_growth = (assets[0] / assets[-1]) ** (1 / len(assets)) - 1
- revenue_growth = (revenues[0] / revenues[-1]) ** (1 / len(revenues)) - 1 if revenues else 0
-
- if asset_growth > revenue_growth * 1.5: # Assets growing much faster than revenue
- red_flags.append("Asset growth exceeds revenue growth")
- score -= 1
- else:
- score += 1
- details.append("Reasonable asset growth relative to revenue")
-
- if red_flags:
- details.append(f"Red flags: {'; '.join(red_flags)}")
-
- return {"score": score, "details": "; ".join(details), "red_flags": red_flags}
-
-
-def analyze_earnings_vs_cash_flow(financial_line_items: list) -> dict:
- """Einhorn's earnings quality through cash flow analysis"""
- score = 0
- details = []
-
- if not financial_line_items:
- return {"score": 0, "details": "No cash flow data"}
-
- # Earnings vs cash flow divergence
- earnings = [item.net_income for item in financial_line_items if item.net_income]
- cash_flows = [item.free_cash_flow for item in financial_line_items if item.free_cash_flow]
-
- if len(earnings) >= 3 and len(cash_flows) >= 3:
- # Compare cumulative earnings vs cash flow
- total_earnings = sum(earnings)
- total_cash_flow = sum(cash_flows)
-
- if total_cash_flow > total_earnings * 0.8: # FCF is 80%+ of earnings
- score += 2
- details.append(f"Strong cash conversion: FCF/Earnings = {total_cash_flow / total_earnings:.2f}")
- elif total_cash_flow < total_earnings * 0.5: # FCF is <50% of earnings
- score -= 2
- details.append(f"Poor cash conversion: FCF/Earnings = {total_cash_flow / total_earnings:.2f}")
-
- # Accruals analysis (simplified)
- if earnings and cash_flows:
- recent_accruals = earnings[0] - cash_flows[0] if len(earnings) > 0 and len(cash_flows) > 0 else 0
- if abs(recent_accruals) > abs(earnings[0]) * 0.3: # High accruals relative to earnings
- score -= 1
- details.append("High accruals relative to earnings - quality concern")
- else:
- score += 1
- details.append("Reasonable accruals level")
-
- # Consistency of cash generation
- if cash_flows:
- positive_fcf_years = sum(1 for fcf in cash_flows if fcf > 0)
- if positive_fcf_years == len(cash_flows):
- score += 2
- details.append(f"Consistent cash generation: {positive_fcf_years}/{len(cash_flows)} years")
- elif positive_fcf_years < len(cash_flows) * 0.6:
- score -= 1
- details.append("Inconsistent cash generation")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_valuation_disconnect(metrics: list, financial_line_items: list, market_cap: float) -> dict:
- """Einhorn's analysis of valuation vs fundamental reality"""
- score = 0
- details = []
-
- if not metrics or not financial_line_items or not market_cap:
- return {"score": 0, "details": "No valuation data"}
-
- latest_metrics = metrics[0]
- latest_financial = financial_line_items[0]
-
- # P/E vs growth analysis
- if latest_metrics.price_to_earnings and latest_metrics.price_to_earnings > 0:
- earnings = [item.net_income for item in financial_line_items if item.net_income and item.net_income > 0]
- if len(earnings) >= 3:
- earnings_growth = (earnings[0] / earnings[-1]) ** (1 / len(earnings)) - 1
- peg_ratio = latest_metrics.price_to_earnings / (earnings_growth * 100) if earnings_growth > 0 else float(
- 'inf')
-
- if peg_ratio < 1.0: # Undervalued relative to growth
- score += 2
- details.append(f"Attractive PEG ratio: {peg_ratio:.2f}")
- elif peg_ratio > 2.0: # Overvalued relative to growth
- score -= 2
- details.append(f"Expensive PEG ratio: {peg_ratio:.2f}")
-
- # Book value reality check
- if latest_metrics.price_to_book:
- if latest_metrics.price_to_book < 1.0: # Trading below book
- score += 1
- details.append(f"Trading below book value: {latest_metrics.price_to_book:.2f} P/B")
- elif latest_metrics.price_to_book > 3.0 and latest_metrics.return_on_equity and latest_metrics.return_on_equity < 0.15:
- score -= 2
- details.append(
- f"High P/B with mediocre ROE: {latest_metrics.price_to_book:.2f} P/B, {latest_metrics.return_on_equity:.1%} ROE")
-
- # Asset-based valuation
- if latest_financial.total_assets and latest_financial.total_debt:
- tangible_book = latest_financial.total_assets - latest_financial.total_debt
- if tangible_book > market_cap:
- score += 2
- details.append("Trading below tangible asset value")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def identify_red_flags(financial_line_items: list) -> dict:
- """Einhorn's red flag identification system"""
- score = 0
- details = []
- flags = []
-
- if not financial_line_items:
- return {"score": 0, "details": "No data for red flag analysis"}
-
- # Rapid asset growth without corresponding revenue growth
- assets = [item.total_assets for item in financial_line_items if item.total_assets]
- revenues = [item.revenue for item in financial_line_items if item.revenue]
-
- if len(assets) >= 3 and len(revenues) >= 3:
- asset_cagr = (assets[0] / assets[-1]) ** (1 / len(assets)) - 1
- revenue_cagr = (revenues[0] / revenues[-1]) ** (1 / len(revenues)) - 1
-
- if asset_cagr > revenue_cagr + 0.1: # Assets growing 10%+ faster than revenue
- flags.append("Asset growth exceeds revenue growth")
- score -= 2
-
- # Declining margins with flat/growing revenue
- margins = []
- for item in financial_line_items:
- if item.revenue and item.operating_income and item.revenue > 0:
- margins.append(item.operating_income / item.revenue)
-
- if len(margins) >= 3:
- margin_trend = margins[0] - margins[-1]
- if margin_trend < -0.05: # 5%+ margin decline
- flags.append("Significant margin compression")
- score -= 1
-
- # Inconsistent cash flow patterns
- cash_flows = [item.free_cash_flow for item in financial_line_items if item.free_cash_flow]
- if cash_flows:
- negative_years = sum(1 for fcf in cash_flows if fcf < 0)
- if negative_years > len(cash_flows) * 0.4: # >40% negative FCF years
- flags.append("Inconsistent cash generation")
- score -= 1
-
- # High receivables growth
- receivables = [item.accounts_receivable for item in financial_line_items if item.accounts_receivable]
- if len(receivables) >= 3 and len(revenues) >= 3:
- receivables_growth = (receivables[0] / receivables[-1]) ** (1 / len(receivables)) - 1
- revenue_growth = (revenues[0] / revenues[-1]) ** (1 / len(revenues)) - 1
-
- if receivables_growth > revenue_growth + 0.15: # Receivables growing 15%+ faster
- flags.append("Receivables growing faster than revenue")
- score -= 1
-
- if not flags:
- score += 2
- details.append("No major red flags identified")
- else:
- details.append(f"Red flags: {'; '.join(flags)}")
-
- return {"score": score, "details": "; ".join(details), "flags": flags}
-
-
-def calculate_fundamental_value(financial_line_items: list, market_cap: float) -> dict:
- """Einhorn's fundamental valuation analysis"""
- score = 0
- details = []
-
- if not financial_line_items or not market_cap:
- return {"score": 0, "details": "No fundamental data"}
-
- latest = financial_line_items[0]
-
- # Asset-based valuation
- if latest.total_assets and latest.total_debt:
- book_value = latest.total_assets - latest.total_debt
- pb_ratio = market_cap / book_value if book_value > 0 else float('inf')
-
- if pb_ratio < 1.0:
- score += 3
- details.append(f"Trading below book value: {pb_ratio:.2f} P/B")
- elif pb_ratio < 1.5:
- score += 1
- details.append(f"Reasonable book value: {pb_ratio:.2f} P/B")
-
- # Earnings-based valuation
- earnings = [item.net_income for item in financial_line_items if item.net_income and item.net_income > 0]
- if earnings:
- avg_earnings = sum(earnings) / len(earnings)
- pe_ratio = market_cap / avg_earnings
-
- if pe_ratio < 12:
- score += 2
- details.append(f"Low earnings multiple: {pe_ratio:.1f} P/E")
- elif pe_ratio > 25:
- score -= 1
- details.append(f"High earnings multiple: {pe_ratio:.1f} P/E")
-
- # Cash flow valuation
- if latest.free_cash_flow and latest.free_cash_flow > 0:
- fcf_yield = latest.free_cash_flow / market_cap
- if fcf_yield > 0.08: # 8%+ FCF yield
- score += 2
- details.append(f"Attractive FCF yield: {fcf_yield:.1%}")
- elif fcf_yield < 0.03: # <3% FCF yield
- score -= 1
- details.append(f"Low FCF yield: {fcf_yield:.1%}")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def generate_einhorn_output(ticker: str, analysis_data: dict, state: AgentState, agent_id: str) -> EinhornSignal:
- """Generate Einhorn-style forensic analysis decision"""
- template = ChatPromptTemplate.from_messages([
- ("system", """You are David Einhorn's AI agent, applying forensic accounting and value analysis:
-
- 1. Forensic accounting: Scrutinize financial statements for quality and red flags
- 2. Earnings quality: Compare earnings to cash flows, analyze accruals
- 3. Value vs. price: Identify disconnects between valuation and reality
- 4. Short candidates: Find overvalued companies with accounting issues
- 5. Long candidates: Find undervalued companies with clean accounting
- 6. Red flag detection: Identify warning signs of financial manipulation
- 7. Contrarian positioning: Take positions opposite to market sentiment
-
- Reasoning style:
- - Emphasize accounting quality and financial statement analysis
- - Focus on earnings vs. cash flow divergences
- - Identify specific red flags and warning signs
- - Discuss valuation relative to fundamental reality
- - Express skepticism toward popular stocks
- - Provide detailed forensic analysis
- - Consider both long and short opportunities
-
- Return bullish for undervalued companies with clean accounting, bearish for overvalued companies with red flags."""),
-
- ("human", """Apply forensic accounting analysis to {ticker}:
-
- {analysis_data}
-
- Provide investment signal in JSON format:
- {{
- "signal": "bullish" | "bearish" | "neutral",
- "confidence": float (0-100),
- "reasoning": "string"
- }}""")
- ])
-
- prompt = template.invoke({"analysis_data": json.dumps(analysis_data, indent=2), "ticker": ticker})
-
- def create_default_einhorn_signal():
- return EinhornSignal(signal="neutral", confidence=0.0, reasoning="Analysis error, defaulting to neutral")
-
- return call_llm(
- prompt=prompt,
- pydantic_model=EinhornSignal,
- agent_name=agent_id,
- state=state,
- default_factory=create_default_einhorn_signal,
- )
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/howard_marks_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/howard_marks_agent.py
deleted file mode 100644
index 8c5025168..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/howard_marks_agent.py
+++ /dev/null
@@ -1,413 +0,0 @@
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - ticker symbols (array)
-# - end_date (string)
-# - FINANCIAL_DATASETS_API_KEY
-#
-# OUTPUT:
-# - Financial metrics: ROE, D/E, Current Ratio
-# - Financial line items: Revenue, Net Income, FCF, Debt, Equity, Retained Earnings, Operating Margin, R&D, Shares
-# - Market Cap
-#
-# PARAMETERS:
-# - period="annual"
-# - limit=10 years
-"""
-
-from fincept_terminal.Agents.src.graph.state import AgentState, show_agent_reasoning
-from fincept_terminal.Agents.src.tools.api import get_financial_metrics, get_market_cap, search_line_items
-from langchain_core.prompts import ChatPromptTemplate
-from langchain_core.messages import HumanMessage
-from pydantic import BaseModel
-import json
-from typing_extensions import Literal
-from fincept_terminal.Agents.src.utils.progress import progress
-from fincept_terminal.Agents.src.utils.llm import call_llm
-from fincept_terminal.Agents.src.utils.api_key import get_api_key_from_state
-
-
-class MarksSignal(BaseModel):
- signal: Literal["bullish", "bearish", "neutral"]
- confidence: float
- reasoning: str
-
-
-def howard_marks_agent(state: AgentState, agent_id: str = "howard_marks_agent"):
- """
- Howard Marks: Second-level thinking, risk assessment, cycles
- Focus: Market psychology, risk-adjusted returns, contrarian positioning
- """
- data = state["data"]
- end_date = data["end_date"]
- tickers = data["tickers"]
- api_key = get_api_key_from_state(state, "FINANCIAL_DATASETS_API_KEY")
- analysis_data = {}
- marks_analysis = {}
-
- for ticker in tickers:
- progress.update_status(agent_id, ticker, "Applying second-level thinking")
- metrics = get_financial_metrics(ticker, end_date, period="annual", limit=7, api_key=api_key)
-
- financial_line_items = search_line_items(
- ticker,
- [
- "revenue", "net_income", "free_cash_flow", "total_debt",
- "shareholders_equity", "total_assets", "operating_margin",
- "current_assets", "current_liabilities"
- ],
- end_date,
- period="annual",
- limit=7,
- api_key=api_key,
- )
-
- market_cap = get_market_cap(ticker, end_date, api_key=api_key)
-
- # Marks' analytical framework
- risk_assessment = analyze_risk_factors(metrics, financial_line_items, market_cap)
- cycle_positioning = analyze_cycle_position(metrics, financial_line_items)
- second_level_thinking = apply_second_level_thinking(metrics, financial_line_items, market_cap)
- market_psychology = analyze_market_psychology_indicators(metrics, market_cap)
- asymmetric_returns = evaluate_asymmetric_opportunities(financial_line_items, market_cap)
-
- # Marks' risk-adjusted scoring
- total_score = (
- risk_assessment["score"] * 0.3 +
- second_level_thinking["score"] * 0.25 +
- asymmetric_returns["score"] * 0.2 +
- cycle_positioning["score"] * 0.15 +
- market_psychology["score"] * 0.1
- )
-
- # Marks' nuanced approach
- if total_score >= 7.5:
- signal = "bullish"
- elif total_score <= 4.5:
- signal = "bearish"
- else:
- signal = "neutral"
-
- analysis_data[ticker] = {
- "signal": signal,
- "score": total_score,
- "risk_assessment": risk_assessment,
- "cycle_positioning": cycle_positioning,
- "second_level_thinking": second_level_thinking,
- "market_psychology": market_psychology,
- "asymmetric_returns": asymmetric_returns
- }
-
- marks_output = generate_marks_output(ticker, analysis_data, state, agent_id)
-
- marks_analysis[ticker] = {
- "signal": marks_output.signal,
- "confidence": marks_output.confidence,
- "reasoning": marks_output.reasoning
- }
-
- progress.update_status(agent_id, ticker, "Done", analysis=marks_output.reasoning)
-
- message = HumanMessage(content=json.dumps(marks_analysis), name=agent_id)
-
- if state["metadata"]["show_reasoning"]:
- show_agent_reasoning(marks_analysis, "Howard Marks Agent")
-
- state["data"]["analyst_signals"][agent_id] = marks_analysis
- progress.update_status(agent_id, None, "Done")
-
- return {"messages": [message], "data": state["data"]}
-
-
-def analyze_risk_factors(metrics: list, financial_line_items: list, market_cap: float) -> dict:
- """Marks' comprehensive risk assessment framework"""
- score = 0
- details = []
- risk_factors = []
-
- if not metrics or not financial_line_items:
- return {"score": 0, "details": "No data for risk analysis"}
-
- latest_metrics = metrics[0]
- latest_financial = financial_line_items[0]
-
- # Financial leverage risk
- if latest_metrics.debt_to_equity:
- if latest_metrics.debt_to_equity < 0.3:
- score += 2
- details.append(f"Low leverage risk: {latest_metrics.debt_to_equity:.2f} D/E")
- elif latest_metrics.debt_to_equity > 1.0:
- risk_factors.append("High leverage risk")
- score -= 1
-
- # Earnings quality and sustainability
- earnings = [item.net_income for item in financial_line_items if item.net_income]
- if earnings and len(earnings) >= 5:
- earnings_volatility = (max(earnings) - min(earnings)) / max(abs(max(earnings)), abs(min(earnings)))
- if earnings_volatility < 0.5:
- score += 2
- details.append(f"Stable earnings pattern: {earnings_volatility:.2f} volatility")
- else:
- risk_factors.append("High earnings volatility")
-
- # Liquidity risk
- if latest_metrics.current_ratio:
- if latest_metrics.current_ratio > 1.5:
- score += 1
- details.append(f"Adequate liquidity: {latest_metrics.current_ratio:.1f} current ratio")
- elif latest_metrics.current_ratio < 1.0:
- risk_factors.append("Liquidity concerns")
- score -= 2
-
- # Business model sustainability
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if revenues and len(revenues) >= 5:
- revenue_trend = sum(1 for i in range(len(revenues) - 1) if revenues[i] >= revenues[i + 1])
- if revenue_trend >= len(revenues) * 0.7:
- score += 1
- details.append("Sustainable revenue pattern")
- else:
- risk_factors.append("Declining revenue trend")
-
- # Margin compression risk
- margins = [item.operating_margin for item in financial_line_items if item.operating_margin]
- if margins and len(margins) >= 3:
- margin_trend = margins[0] - margins[-1]
- if margin_trend > 0.02: # 2% margin improvement
- score += 1
- details.append("Improving margin profile")
- elif margin_trend < -0.05: # 5% margin decline
- risk_factors.append("Margin compression risk")
- score -= 1
-
- if risk_factors:
- details.append(f"Risk factors: {'; '.join(risk_factors)}")
-
- return {"score": score, "details": "; ".join(details), "risk_factors": risk_factors}
-
-
-def analyze_cycle_position(metrics: list, financial_line_items: list) -> dict:
- """Marks' cycle awareness analysis"""
- score = 0
- details = []
-
- if not metrics or not financial_line_items:
- return {"score": 0, "details": "No cycle data"}
-
- # Revenue cycle analysis
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if len(revenues) >= 5:
- # Analyze cyclical patterns
- recent_growth = (revenues[0] / revenues[2]) ** (1 / 2) - 1 # 2-year CAGR
- longer_growth = (revenues[0] / revenues[-1]) ** (1 / len(revenues)) - 1 # Full period CAGR
-
- if recent_growth < longer_growth * 0.5: # Significant slowdown
- score += 2 # Good time to buy in cycle
- details.append("Potential cyclical trough - contrarian opportunity")
- elif recent_growth > longer_growth * 2: # Acceleration
- score -= 1 # Potential cycle peak
- details.append("Potential cyclical peak - exercise caution")
-
- # Margin cycle analysis
- margins = [item.operating_margin for item in financial_line_items if item.operating_margin]
- if len(margins) >= 5:
- current_margin = margins[0]
- avg_margin = sum(margins) / len(margins)
-
- if current_margin < avg_margin * 0.8: # Below average margins
- score += 1
- details.append("Below-average margins suggest cycle opportunity")
-
- # Return on equity cycle
- roe_vals = [m.return_on_equity for m in metrics if m.return_on_equity]
- if len(roe_vals) >= 5:
- current_roe = roe_vals[0]
- avg_roe = sum(roe_vals) / len(roe_vals)
-
- if current_roe < avg_roe * 0.7: # Significantly below average
- score += 2
- details.append("Depressed ROE suggests cyclical opportunity")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def apply_second_level_thinking(metrics: list, financial_line_items: list, market_cap: float) -> dict:
- """Marks' second-level thinking analysis"""
- score = 0
- details = []
-
- if not metrics or not financial_line_items or not market_cap:
- return {"score": 0, "details": "No data for second-level analysis"}
-
- latest_metrics = metrics[0]
- latest_financial = financial_line_items[0]
-
- # What is the market NOT seeing?
- # Low valuation with improving fundamentals
- if latest_metrics.price_to_book and latest_metrics.price_to_book < 1.2:
- # Check if fundamentals are actually improving
- earnings = [item.net_income for item in financial_line_items if item.net_income]
- if len(earnings) >= 3 and earnings[0] > earnings[1] > 0:
- score += 3
- details.append("Market pessimism vs improving fundamentals - second-level opportunity")
-
- # Hidden asset value
- if latest_financial.total_assets and latest_financial.total_debt:
- net_asset_value = latest_financial.total_assets - latest_financial.total_debt
- if net_asset_value > market_cap * 1.3:
- score += 2
- details.append("Hidden asset value not reflected in price")
-
- # Temporary problems vs permanent impairment
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if len(revenues) >= 5:
- recent_decline = revenues[0] < revenues[1]
- historical_growth = revenues[-1] < revenues[-3] # Was growing historically
-
- if recent_decline and historical_growth:
- score += 1
- details.append("Temporary setback in historically growing business")
-
- # Quality company at cyclical low
- if latest_metrics.return_on_equity:
- historical_roe = [m.return_on_equity for m in metrics if m.return_on_equity]
- if len(historical_roe) >= 5:
- avg_roe = sum(historical_roe[1:]) / len(historical_roe[1:]) # Exclude current
- if avg_roe > 0.15 and latest_metrics.return_on_equity < avg_roe * 0.6:
- score += 2
- details.append("Quality company at cyclical low ROE")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_market_psychology_indicators(metrics: list, market_cap: float) -> dict:
- """Marks' market psychology assessment"""
- score = 0
- details = []
-
- if not metrics or not market_cap:
- return {"score": 0, "details": "No psychology indicators"}
-
- latest_metrics = metrics[0]
-
- # Extreme valuation as psychology indicator
- if latest_metrics.price_to_earnings:
- if latest_metrics.price_to_earnings < 8: # Extreme pessimism
- score += 2
- details.append(f"Market pessimism: {latest_metrics.price_to_earnings:.1f} P/E")
- elif latest_metrics.price_to_earnings > 30: # Extreme optimism
- score -= 2
- details.append(f"Market euphoria: {latest_metrics.price_to_earnings:.1f} P/E")
-
- # Book value psychology
- if latest_metrics.price_to_book:
- if latest_metrics.price_to_book < 0.8: # Trading below book
- score += 1
- details.append("Market pricing below book value - potential pessimism")
- elif latest_metrics.price_to_book > 3: # High premium
- score -= 1
- details.append("Market paying high premium - potential optimism")
-
- # Contrarian indicators (simplified)
- # Would typically incorporate sentiment data, analyst revisions, etc.
- if latest_metrics.debt_to_equity and latest_metrics.debt_to_equity > 0.8:
- score += 1 # High debt companies often overlooked
- details.append("High debt company - potential contrarian opportunity")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def evaluate_asymmetric_opportunities(financial_line_items: list, market_cap: float) -> dict:
- """Marks' asymmetric risk/return evaluation"""
- score = 0
- details = []
-
- if not financial_line_items or not market_cap:
- return {"score": 0, "details": "No asymmetric data"}
-
- latest = financial_line_items[0]
-
- # Downside protection analysis
- total_assets = latest.total_assets if latest.total_assets else 0
- total_debt = latest.total_debt if latest.total_debt else 0
-
- # Asset floor
- if total_assets > 0:
- net_assets = total_assets - total_debt
- if net_assets > market_cap * 0.8: # Strong asset backing
- score += 2
- details.append("Strong downside protection from asset backing")
-
- # Upside potential from normalized earnings
- earnings = [item.net_income for item in financial_line_items if item.net_income and item.net_income > 0]
- if earnings and len(earnings) >= 3:
- # Use best historical earnings as proxy for potential
- best_earnings = max(earnings)
- current_earnings = earnings[0] if earnings[0] > 0 else earnings[1] if len(earnings) > 1 else 0
-
- if best_earnings > current_earnings * 1.5: # Significant upside potential
- normalized_value = best_earnings * 15 # 15x multiple
- upside_ratio = normalized_value / market_cap
-
- if upside_ratio > 2: # 100%+ upside potential
- score += 3
- details.append(f"Significant upside potential: {upside_ratio:.1f}x from normalized earnings")
-
- # Free cash flow asymmetry
- if latest.free_cash_flow and latest.free_cash_flow > 0:
- fcf_yield = latest.free_cash_flow / market_cap
- if fcf_yield > 0.1: # 10%+ FCF yield
- score += 1
- details.append(f"Attractive FCF yield provides downside support: {fcf_yield:.1%}")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def generate_marks_output(ticker: str, analysis_data: dict, state: AgentState, agent_id: str) -> MarksSignal:
- """Generate Marks-style risk-aware investment decision"""
- template = ChatPromptTemplate.from_messages([
- ("system", """You are Howard Marks' AI agent, applying sophisticated risk-aware value investing:
-
- 1. Second-level thinking: "What is the market not seeing?"
- 2. Risk assessment: "Risk is the probability of loss, not volatility"
- 3. Cycle awareness: Understand where we are in the cycle
- 4. Market psychology: Recognize euphoria and pessimism
- 5. Asymmetric opportunities: Limited downside, significant upside
- 6. Contrarian positioning: Buy when others are selling
- 7. Risk-adjusted returns: Focus on risk-adjusted, not absolute returns
-
- Reasoning style:
- - Emphasize risk analysis and downside protection
- - Consider market psychology and sentiment
- - Apply second-level thinking to find hidden opportunities
- - Discuss cyclical positioning and timing
- - Focus on asymmetric risk/reward profiles
- - Express nuanced, probabilistic thinking
- - Acknowledge uncertainty and multiple scenarios
-
- Return bullish for asymmetric opportunities with limited downside and strong risk-adjusted returns."""),
-
- ("human", """Apply second-level thinking and risk analysis to {ticker}:
-
- {analysis_data}
-
- Provide investment signal in JSON format:
- {{
- "signal": "bullish" | "bearish" | "neutral",
- "confidence": float (0-100),
- "reasoning": "string"
- }}""")
- ])
-
- prompt = template.invoke({"analysis_data": json.dumps(analysis_data, indent=2), "ticker": ticker})
-
- def create_default_marks_signal():
- return MarksSignal(signal="neutral", confidence=0.0, reasoning="Analysis error, defaulting to neutral")
-
- return call_llm(
- prompt=prompt,
- pydantic_model=MarksSignal,
- agent_name=agent_id,
- state=state,
- default_factory=create_default_marks_signal,
- )
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/jean_marie_eveillard_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/jean_marie_eveillard_agent.py
deleted file mode 100644
index 34ec89b8f..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/jean_marie_eveillard_agent.py
+++ /dev/null
@@ -1,424 +0,0 @@
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - ticker symbols (array)
-# - end_date (string)
-# - FINANCIAL_DATASETS_API_KEY
-#
-# OUTPUT:
-# - Financial metrics: ROE, D/E, Current Ratio
-# - Financial line items: Revenue, Net Income, FCF, Debt, Equity, Retained Earnings, Operating Margin, R&D, Shares
-# - Market Cap
-#
-# PARAMETERS:
-# - period="annual"
-# - limit=10 years
-"""
-
-from fincept_terminal.Agents.src.graph.state import AgentState, show_agent_reasoning
-from fincept_terminal.Agents.src.tools.api import get_financial_metrics, get_market_cap, search_line_items
-from langchain_core.prompts import ChatPromptTemplate
-from langchain_core.messages import HumanMessage
-from pydantic import BaseModel
-import json
-from typing_extensions import Literal
-from fincept_terminal.Agents.src.utils.progress import progress
-from fincept_terminal.Agents.src.utils.llm import call_llm
-from fincept_terminal.Agents.src.utils.api_key import get_api_key_from_state
-
-
-class EveillardSignal(BaseModel):
- signal: Literal["bullish", "bearish", "neutral"]
- confidence: float
- reasoning: str
-
-
-def jean_marie_eveillard_agent(state: AgentState, agent_id: str = "jean_marie_eveillard_agent"):
- """
- Jean-Marie Eveillard: Global value, capital preservation
- Focus: Downside protection, global diversification, conservative value
- """
- data = state["data"]
- end_date = data["end_date"]
- tickers = data["tickers"]
- api_key = get_api_key_from_state(state, "FINANCIAL_DATASETS_API_KEY")
- analysis_data = {}
- eveillard_analysis = {}
-
- for ticker in tickers:
- progress.update_status(agent_id, ticker, "Analyzing capital preservation potential")
- metrics = get_financial_metrics(ticker, end_date, period="annual", limit=6, api_key=api_key)
-
- financial_line_items = search_line_items(
- ticker,
- [
- "revenue", "net_income", "free_cash_flow", "total_assets",
- "current_assets", "current_liabilities", "total_debt",
- "shareholders_equity", "cash_and_equivalents"
- ],
- end_date,
- period="annual",
- limit=6,
- api_key=api_key,
- )
-
- market_cap = get_market_cap(ticker, end_date, api_key=api_key)
-
- # Eveillard's conservative framework
- capital_preservation = analyze_capital_preservation(financial_line_items, market_cap)
- balance_sheet_quality = analyze_conservative_balance_sheet(financial_line_items)
- valuation_safety = analyze_valuation_margin_of_safety(metrics, financial_line_items, market_cap)
- business_predictability = analyze_business_predictability(financial_line_items)
- downside_protection = calculate_downside_protection(financial_line_items, market_cap)
-
- # Eveillard's conservative scoring
- total_score = (
- capital_preservation["score"] * 0.3 +
- balance_sheet_quality["score"] * 0.25 +
- downside_protection["score"] * 0.2 +
- valuation_safety["score"] * 0.15 +
- business_predictability["score"] * 0.1
- )
-
- # Eveillard's very conservative approach
- if total_score >= 8.5:
- signal = "bullish"
- elif total_score <= 5.0:
- signal = "bearish"
- else:
- signal = "neutral" # Often neutral - very selective
-
- analysis_data[ticker] = {
- "signal": signal,
- "score": total_score,
- "capital_preservation": capital_preservation,
- "balance_sheet_quality": balance_sheet_quality,
- "valuation_safety": valuation_safety,
- "business_predictability": business_predictability,
- "downside_protection": downside_protection
- }
-
- eveillard_output = generate_eveillard_output(ticker, analysis_data, state, agent_id)
-
- eveillard_analysis[ticker] = {
- "signal": eveillard_output.signal,
- "confidence": eveillard_output.confidence,
- "reasoning": eveillard_output.reasoning
- }
-
- progress.update_status(agent_id, ticker, "Done", analysis=eveillard_output.reasoning)
-
- message = HumanMessage(content=json.dumps(eveillard_analysis), name=agent_id)
-
- if state["metadata"]["show_reasoning"]:
- show_agent_reasoning(eveillard_analysis, "Jean-Marie Eveillard Agent")
-
- state["data"]["analyst_signals"][agent_id] = eveillard_analysis
- progress.update_status(agent_id, None, "Done")
-
- return {"messages": [message], "data": state["data"]}
-
-
-def analyze_capital_preservation(financial_line_items: list, market_cap: float) -> dict:
- """Eveillard's capital preservation analysis"""
- score = 0
- details = []
-
- if not financial_line_items or not market_cap:
- return {"score": 0, "details": "No capital preservation data"}
-
- latest = financial_line_items[0]
-
- # Strong cash position
- cash = latest.cash_and_equivalents if latest.cash_and_equivalents else 0
- if cash > market_cap * 0.1: # 10%+ cash relative to market cap
- score += 2
- details.append(f"Strong cash position: {(cash / market_cap):.1%} of market cap")
-
- # Asset backing
- if latest.total_assets and latest.total_debt:
- net_assets = latest.total_assets - latest.total_debt
- if net_assets > market_cap:
- score += 3
- details.append(f"Strong asset backing: {(net_assets / market_cap):.1f}x market cap")
- elif net_assets > market_cap * 0.7:
- score += 2
- details.append(f"Adequate asset backing: {(net_assets / market_cap):.1f}x market cap")
-
- # Working capital strength
- if latest.current_assets and latest.current_liabilities:
- working_capital = latest.current_assets - latest.current_liabilities
- if working_capital > market_cap * 0.2:
- score += 2
- details.append(f"Strong working capital: {(working_capital / market_cap):.1%} of market cap")
-
- # Dividend history (capital return)
- # Note: Would need dividend data, using profitability as proxy
- earnings = [item.net_income for item in financial_line_items if item.net_income]
- if earnings:
- positive_years = sum(1 for e in earnings if e > 0)
- if positive_years == len(earnings):
- score += 1
- details.append(f"Consistent profitability: {positive_years}/{len(earnings)} years")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_conservative_balance_sheet(financial_line_items: list) -> dict:
- """Eveillard's conservative balance sheet requirements"""
- score = 0
- details = []
-
- if not financial_line_items:
- return {"score": 0, "details": "No balance sheet data"}
-
- latest = financial_line_items[0]
-
- # Low debt levels
- if latest.total_debt and latest.shareholders_equity:
- debt_to_equity = latest.total_debt / latest.shareholders_equity
- if debt_to_equity < 0.2: # Very conservative
- score += 3
- details.append(f"Very low debt: {debt_to_equity:.2f} D/E")
- elif debt_to_equity < 0.4:
- score += 2
- details.append(f"Conservative debt: {debt_to_equity:.2f} D/E")
- elif debt_to_equity > 1.0:
- score -= 1
- details.append(f"High debt concern: {debt_to_equity:.2f} D/E")
-
- # Strong liquidity
- if latest.current_assets and latest.current_liabilities:
- current_ratio = latest.current_assets / latest.current_liabilities
- if current_ratio > 2.0:
- score += 2
- details.append(f"Strong liquidity: {current_ratio:.1f} current ratio")
- elif current_ratio < 1.2:
- score -= 1
- details.append(f"Liquidity concern: {current_ratio:.1f} current ratio")
-
- # Asset quality
- if latest.cash_and_equivalents and latest.current_assets:
- cash_ratio = latest.cash_and_equivalents / latest.current_assets
- if cash_ratio > 0.3: # 30%+ cash in current assets
- score += 1
- details.append(f"High-quality liquid assets: {cash_ratio:.1%} cash ratio")
-
- # Equity base stability
- equity_vals = [item.shareholders_equity for item in financial_line_items if item.shareholders_equity]
- if len(equity_vals) >= 3:
- equity_growth = (equity_vals[0] / equity_vals[-1]) ** (1 / len(equity_vals)) - 1
- if equity_growth > 0.05: # 5%+ equity growth
- score += 1
- details.append(f"Growing equity base: {equity_growth:.1%} CAGR")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_valuation_margin_of_safety(metrics: list, financial_line_items: list, market_cap: float) -> dict:
- """Eveillard's margin of safety requirements"""
- score = 0
- details = []
-
- if not metrics or not financial_line_items or not market_cap:
- return {"score": 0, "details": "No valuation data"}
-
- latest_metrics = metrics[0]
- latest_financial = financial_line_items[0]
-
- # Conservative P/E analysis
- if latest_metrics.price_to_earnings and latest_metrics.price_to_earnings > 0:
- if latest_metrics.price_to_earnings < 12:
- score += 3
- details.append(f"Conservative P/E: {latest_metrics.price_to_earnings:.1f}")
- elif latest_metrics.price_to_earnings < 18:
- score += 1
- details.append(f"Reasonable P/E: {latest_metrics.price_to_earnings:.1f}")
-
- # Book value safety
- if latest_metrics.price_to_book:
- if latest_metrics.price_to_book < 1.0:
- score += 3
- details.append(f"Trading below book: {latest_metrics.price_to_book:.2f} P/B")
- elif latest_metrics.price_to_book < 1.5:
- score += 2
- details.append(f"Conservative P/B: {latest_metrics.price_to_book:.2f}")
-
- # Free cash flow yield
- if latest_financial.free_cash_flow and latest_financial.free_cash_flow > 0:
- fcf_yield = latest_financial.free_cash_flow / market_cap
- if fcf_yield > 0.08: # 8%+ yield
- score += 2
- details.append(f"Attractive FCF yield: {fcf_yield:.1%}")
- elif fcf_yield > 0.05:
- score += 1
- details.append(f"Reasonable FCF yield: {fcf_yield:.1%}")
-
- # Dividend yield (simplified - would need actual dividend data)
- if latest_financial.net_income and latest_financial.net_income > 0:
- estimated_dividend_yield = (latest_financial.net_income * 0.3) / market_cap # Assume 30% payout
- if estimated_dividend_yield > 0.03: # 3%+ yield
- score += 1
- details.append(f"Potential dividend yield: {estimated_dividend_yield:.1%}")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_business_predictability(financial_line_items: list) -> dict:
- """Eveillard's preference for predictable businesses"""
- score = 0
- details = []
-
- if not financial_line_items:
- return {"score": 0, "details": "No predictability data"}
-
- # Revenue stability
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if len(revenues) >= 5:
- revenue_volatility = (max(revenues) - min(revenues)) / max(revenues)
- if revenue_volatility < 0.2: # Low volatility
- score += 2
- details.append(f"Stable revenue pattern: {revenue_volatility:.1%} volatility")
- elif revenue_volatility > 0.5:
- score -= 1
- details.append(f"High revenue volatility: {revenue_volatility:.1%}")
-
- # Earnings consistency
- earnings = [item.net_income for item in financial_line_items if item.net_income]
- if earnings:
- negative_years = sum(1 for e in earnings if e < 0)
- if negative_years == 0:
- score += 2
- details.append(f"No loss years in {len(earnings)} periods")
- elif negative_years <= 1:
- score += 1
- details.append(f"Only {negative_years} loss year(s)")
-
- # Cash flow predictability
- fcf_vals = [item.free_cash_flow for item in financial_line_items if item.free_cash_flow]
- if fcf_vals:
- positive_fcf_years = sum(1 for fcf in fcf_vals if fcf > 0)
- if positive_fcf_years >= len(fcf_vals) * 0.8: # 80%+ positive years
- score += 2
- details.append(f"Consistent cash generation: {positive_fcf_years}/{len(fcf_vals)} years")
-
- # Business model simplicity (proxy: stable margins)
- margins = []
- for item in financial_line_items:
- if item.net_income and item.revenue and item.revenue > 0:
- margins.append(item.net_income / item.revenue)
-
- if len(margins) >= 3:
- margin_stability = max(margins) - min(margins)
- if margin_stability < 0.05: # 5% margin range
- score += 1
- details.append(f"Stable profit margins: {margin_stability:.1%} range")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def calculate_downside_protection(financial_line_items: list, market_cap: float) -> dict:
- """Eveillard's downside protection calculation"""
- score = 0
- details = []
-
- if not financial_line_items or not market_cap:
- return {"score": 0, "details": "No downside protection data"}
-
- latest = financial_line_items[0]
-
- # Liquidation value analysis
- current_assets = latest.current_assets if latest.current_assets else 0
- cash = latest.cash_and_equivalents if latest.cash_and_equivalents else 0
-
- # Conservative liquidation values
- conservative_assets = cash + (current_assets - cash) * 0.7 # 70% recovery on non-cash
- current_liabilities = latest.current_liabilities if latest.current_liabilities else 0
- total_debt = latest.total_debt if latest.total_debt else 0
-
- net_liquidation_value = conservative_assets - current_liabilities - total_debt
-
- if net_liquidation_value > 0:
- liquidation_ratio = net_liquidation_value / market_cap
- if liquidation_ratio > 0.7: # 70%+ of market cap
- score += 4
- details.append(f"Excellent liquidation protection: {liquidation_ratio:.1%}")
- elif liquidation_ratio > 0.4:
- score += 2
- details.append(f"Good liquidation protection: {liquidation_ratio:.1%}")
- elif liquidation_ratio > 0.2:
- score += 1
- details.append(f"Some liquidation protection: {liquidation_ratio:.1%}")
-
- # Tangible book value protection
- if latest.shareholders_equity:
- book_protection = latest.shareholders_equity / market_cap
- if book_protection > 1.0:
- score += 2
- details.append(f"Trading below book value: {book_protection:.1f}x")
- elif book_protection > 0.8:
- score += 1
- details.append(f"Near book value protection: {book_protection:.1f}x")
-
- # Earnings floor
- earnings = [item.net_income for item in financial_line_items if item.net_income]
- if earnings:
- worst_earnings = min(earnings)
- if worst_earnings > 0:
- score += 2
- details.append("No historical losses provide earnings floor")
- elif worst_earnings > -market_cap * 0.03: # Small loss relative to market cap
- score += 1
- details.append("Limited historical downside from worst performance")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def generate_eveillard_output(ticker: str, analysis_data: dict, state: AgentState, agent_id: str) -> EveillardSignal:
- """Generate Eveillard-style capital preservation decision"""
- template = ChatPromptTemplate.from_messages([
- ("system", """You are Jean-Marie Eveillard's AI agent, applying global value investing with capital preservation focus:
-
- 1. Capital preservation: "Return of capital is more important than return on capital"
- 2. Conservative balance sheets: Low debt, strong liquidity, asset backing
- 3. Margin of safety: Buy with significant downside protection
- 4. Predictable businesses: Avoid complexity and volatility
- 5. Global perspective: Consider opportunities worldwide
- 6. Patient approach: Wait for exceptional opportunities
- 7. Risk awareness: Focus on what can go wrong
-
- Reasoning style:
- - Emphasize downside protection and risk management
- - Focus on balance sheet strength and financial conservatism
- - Discuss predictability and business simplicity
- - Consider liquidation values and asset backing
- - Express conservative skepticism
- - Require substantial margin of safety
- - Acknowledge when standards are not met
-
- Return bullish only for exceptionally safe investments with strong downside protection and reasonable upside."""),
-
- ("human", """Apply capital preservation analysis to {ticker}:
-
- {analysis_data}
-
- Provide investment signal in JSON format:
- {{
- "signal": "bullish" | "bearish" | "neutral",
- "confidence": float (0-100),
- "reasoning": "string"
- }}""")
- ])
-
- prompt = template.invoke({"analysis_data": json.dumps(analysis_data, indent=2), "ticker": ticker})
-
- def create_default_eveillard_signal():
- return EveillardSignal(signal="neutral", confidence=0.0, reasoning="Analysis error, defaulting to neutral")
-
- return call_llm(
- prompt=prompt,
- pydantic_model=EveillardSignal,
- agent_name=agent_id,
- state=state,
- default_factory=create_default_eveillard_signal,
- )
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/joel_greenblatt_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/joel_greenblatt_agent.py
deleted file mode 100644
index cc534703a..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/joel_greenblatt_agent.py
+++ /dev/null
@@ -1,372 +0,0 @@
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - ticker symbols (array)
-# - end_date (string)
-# - FINANCIAL_DATASETS_API_KEY
-#
-# OUTPUT:
-# - Financial metrics: ROE, D/E, Current Ratio
-# - Financial line items: Revenue, Net Income, FCF, Debt, Equity, Retained Earnings, Operating Margin, R&D, Shares
-# - Market Cap
-#
-# PARAMETERS:
-# - period="annual"
-# - limit=10 years
-"""
-
-from fincept_terminal.Agents.src.graph.state import AgentState, show_agent_reasoning
-from fincept_terminal.Agents.src.tools.api import get_financial_metrics, get_market_cap, search_line_items
-from langchain_core.prompts import ChatPromptTemplate
-from langchain_core.messages import HumanMessage
-from pydantic import BaseModel
-import json
-from typing_extensions import Literal
-from fincept_terminal.Agents.src.utils.progress import progress
-from fincept_terminal.Agents.src.utils.llm import call_llm
-from fincept_terminal.Agents.src.utils.api_key import get_api_key_from_state
-
-
-class GreenblattSignal(BaseModel):
- signal: Literal["bullish", "bearish", "neutral"]
- confidence: float
- reasoning: str
-
-
-def joel_greenblatt_agent(state: AgentState, agent_id: str = "joel_greenblatt_agent"):
- """
- Joel Greenblatt: Magic formula (high ROC + low P/E)
- Focus: Systematic value investing, high returns on capital, cheap valuations
- """
- data = state["data"]
- end_date = data["end_date"]
- tickers = data["tickers"]
- api_key = get_api_key_from_state(state, "FINANCIAL_DATASETS_API_KEY")
- analysis_data = {}
- greenblatt_analysis = {}
-
- for ticker in tickers:
- progress.update_status(agent_id, ticker, "Applying Magic Formula criteria")
- metrics = get_financial_metrics(ticker, end_date, period="annual", limit=5, api_key=api_key)
-
- financial_line_items = search_line_items(
- ticker,
- [
- "revenue", "net_income", "total_assets", "current_assets",
- "current_liabilities", "total_debt", "shareholders_equity",
- "operating_income", "interest_expense", "free_cash_flow"
- ],
- end_date,
- period="annual",
- limit=5,
- api_key=api_key,
- )
-
- market_cap = get_market_cap(ticker, end_date, api_key=api_key)
-
- # Greenblatt's Magic Formula components
- earnings_yield = calculate_earnings_yield(financial_line_items, market_cap)
- return_on_capital = calculate_return_on_capital(financial_line_items)
- magic_formula_rank = calculate_magic_formula_rank(earnings_yield, return_on_capital)
- business_quality = analyze_business_quality_greenblatt(metrics, financial_line_items)
- special_situations = analyze_special_situations(financial_line_items, market_cap)
-
- # Greenblatt's systematic scoring
- total_score = (
- magic_formula_rank["score"] * 0.4 +
- earnings_yield["score"] * 0.25 +
- return_on_capital["score"] * 0.25 +
- business_quality["score"] * 0.1
- )
-
- # Magic Formula approach: systematic and mechanical
- if total_score >= 8.0:
- signal = "bullish"
- elif total_score <= 4.0:
- signal = "bearish"
- else:
- signal = "neutral"
-
- analysis_data[ticker] = {
- "signal": signal,
- "score": total_score,
- "earnings_yield": earnings_yield,
- "return_on_capital": return_on_capital,
- "magic_formula_rank": magic_formula_rank,
- "business_quality": business_quality,
- "special_situations": special_situations
- }
-
- greenblatt_output = generate_greenblatt_output(ticker, analysis_data, state, agent_id)
-
- greenblatt_analysis[ticker] = {
- "signal": greenblatt_output.signal,
- "confidence": greenblatt_output.confidence,
- "reasoning": greenblatt_output.reasoning
- }
-
- progress.update_status(agent_id, ticker, "Done", analysis=greenblatt_output.reasoning)
-
- message = HumanMessage(content=json.dumps(greenblatt_analysis), name=agent_id)
-
- if state["metadata"]["show_reasoning"]:
- show_agent_reasoning(greenblatt_analysis, "Joel Greenblatt Agent")
-
- state["data"]["analyst_signals"][agent_id] = greenblatt_analysis
- progress.update_status(agent_id, None, "Done")
-
- return {"messages": [message], "data": state["data"]}
-
-
-def calculate_earnings_yield(financial_line_items: list, market_cap: float) -> dict:
- """Calculate Greenblatt's earnings yield (EBIT / Enterprise Value)"""
- score = 0
- details = []
-
- if not financial_line_items or not market_cap:
- return {"score": 0, "details": "No data for earnings yield", "value": None}
-
- latest = financial_line_items[0]
-
- # Calculate EBIT (Operating Income)
- ebit = latest.operating_income if latest.operating_income else 0
-
- # Calculate Enterprise Value
- total_debt = latest.total_debt if latest.total_debt else 0
- cash = latest.current_assets * 0.2 if latest.current_assets else 0 # Rough cash estimate
- enterprise_value = market_cap + total_debt - cash
-
- if enterprise_value > 0 and ebit > 0:
- earnings_yield = ebit / enterprise_value
-
- # Greenblatt's scoring system
- if earnings_yield > 0.15: # 15%+ earnings yield
- score = 10
- details.append(f"Exceptional earnings yield: {earnings_yield:.1%}")
- elif earnings_yield > 0.12:
- score = 8
- details.append(f"Strong earnings yield: {earnings_yield:.1%}")
- elif earnings_yield > 0.09:
- score = 6
- details.append(f"Good earnings yield: {earnings_yield:.1%}")
- elif earnings_yield > 0.06:
- score = 4
- details.append(f"Fair earnings yield: {earnings_yield:.1%}")
- else:
- score = 2
- details.append(f"Low earnings yield: {earnings_yield:.1%}")
- else:
- earnings_yield = 0
- details.append("No positive earnings yield")
-
- return {
- "score": score,
- "value": earnings_yield,
- "details": "; ".join(details)
- }
-
-
-def calculate_return_on_capital(financial_line_items: list) -> dict:
- """Calculate Greenblatt's return on invested capital"""
- score = 0
- details = []
-
- if not financial_line_items:
- return {"score": 0, "details": "No data for ROIC", "value": None}
-
- latest = financial_line_items[0]
-
- # Calculate ROIC = EBIT / (Net Working Capital + Net Fixed Assets)
- ebit = latest.operating_income if latest.operating_income else 0
-
- # Working Capital
- current_assets = latest.current_assets if latest.current_assets else 0
- current_liabilities = latest.current_liabilities if latest.current_liabilities else 0
- working_capital = current_assets - current_liabilities
-
- # Invested Capital (simplified)
- total_assets = latest.total_assets if latest.total_assets else 0
- invested_capital = max(working_capital + (total_assets - current_assets), total_assets * 0.5)
-
- if invested_capital > 0 and ebit > 0:
- roic = ebit / invested_capital
-
- # Greenblatt's ROIC scoring
- if roic > 0.25: # 25%+ ROIC
- score = 10
- details.append(f"Exceptional ROIC: {roic:.1%}")
- elif roic > 0.20:
- score = 8
- details.append(f"Strong ROIC: {roic:.1%}")
- elif roic > 0.15:
- score = 6
- details.append(f"Good ROIC: {roic:.1%}")
- elif roic > 0.10:
- score = 4
- details.append(f"Fair ROIC: {roic:.1%}")
- else:
- score = 2
- details.append(f"Low ROIC: {roic:.1%}")
- else:
- roic = 0
- details.append("No positive return on capital")
-
- return {
- "score": score,
- "value": roic,
- "details": "; ".join(details)
- }
-
-
-def calculate_magic_formula_rank(earnings_yield: dict, return_on_capital: dict) -> dict:
- """Combine earnings yield and ROIC for Magic Formula ranking"""
- score = 0
- details = []
-
- ey_score = earnings_yield.get("score", 0)
- roic_score = return_on_capital.get("score", 0)
-
- # Magic Formula combines both metrics
- combined_score = (ey_score + roic_score) / 2
-
- if combined_score >= 9:
- score = 10
- details.append("Magic Formula: Top tier (high ROIC + high earnings yield)")
- elif combined_score >= 7:
- score = 8
- details.append("Magic Formula: Strong candidate")
- elif combined_score >= 5:
- score = 6
- details.append("Magic Formula: Decent candidate")
- else:
- score = 3
- details.append("Magic Formula: Below average")
-
- # Bonus for exceptional combination
- ey_val = earnings_yield.get("value", 0)
- roic_val = return_on_capital.get("value", 0)
-
- if ey_val > 0.12 and roic_val > 0.20:
- score = min(10, score + 2)
- details.append("Exceptional Magic Formula combination")
-
- return {
- "score": score,
- "combined_score": combined_score,
- "details": "; ".join(details)
- }
-
-
-def analyze_business_quality_greenblatt(metrics: list, financial_line_items: list) -> dict:
- """Greenblatt's additional quality checks beyond Magic Formula"""
- score = 0
- details = []
-
- if not metrics or not financial_line_items:
- return {"score": 0, "details": "No data for quality analysis"}
-
- # Consistent profitability
- earnings = [item.net_income for item in financial_line_items if item.net_income]
- if earnings:
- positive_years = sum(1 for e in earnings if e > 0)
- if positive_years == len(earnings):
- score += 3
- details.append(f"Consistent profitability: {positive_years}/{len(earnings)} years")
-
- # Revenue growth
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if len(revenues) >= 3:
- revenue_growth = (revenues[0] / revenues[-1]) ** (1 / len(revenues)) - 1
- if revenue_growth > 0.05:
- score += 2
- details.append(f"Revenue growth: {revenue_growth:.1%} CAGR")
-
- # Free cash flow generation
- fcf_vals = [item.free_cash_flow for item in financial_line_items if item.free_cash_flow]
- if fcf_vals:
- positive_fcf = sum(1 for fcf in fcf_vals if fcf > 0)
- if positive_fcf >= len(fcf_vals) * 0.8:
- score += 2
- details.append(f"Strong FCF generation: {positive_fcf}/{len(fcf_vals)} years")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_special_situations(financial_line_items: list, market_cap: float) -> dict:
- """Greenblatt's special situation analysis"""
- score = 0
- details = []
-
- if not financial_line_items or not market_cap:
- return {"score": 0, "details": "No special situation data"}
-
- latest = financial_line_items[0]
-
- # Net cash position (special situation value)
- current_assets = latest.current_assets if latest.current_assets else 0
- total_debt = latest.total_debt if latest.total_debt else 0
-
- if current_assets > total_debt * 1.5:
- net_cash = current_assets - total_debt
- if net_cash > market_cap * 0.2:
- score += 2
- details.append(f"Net cash opportunity: {(net_cash / market_cap):.1%} of market cap")
-
- # Asset value relative to market cap
- if latest.total_assets:
- asset_ratio = latest.total_assets / market_cap
- if asset_ratio > 1.5:
- score += 1
- details.append(f"Asset value: {asset_ratio:.1f}x market cap")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def generate_greenblatt_output(ticker: str, analysis_data: dict, state: AgentState, agent_id: str) -> GreenblattSignal:
- """Generate Greenblatt-style Magic Formula investment decision"""
- template = ChatPromptTemplate.from_messages([
- ("system", """You are Joel Greenblatt's AI agent, implementing the Magic Formula strategy:
-
- 1. Magic Formula: High return on invested capital + High earnings yield
- 2. Systematic approach: Remove emotion, follow the formula mechanically
- 3. Value investing: Buy good businesses at cheap prices
- 4. Special situations: Spinoffs, mergers, bankruptcies for extra returns
- 5. Long-term perspective: Hold for 2-3 years minimum
- 6. Diversification: Own 20-30 positions to reduce risk
- 7. Patience: Trust the process even during underperformance
-
- Reasoning style:
- - Emphasize quantitative Magic Formula metrics
- - Focus on ROIC and earnings yield primarily
- - Discuss systematic, mechanical approach
- - Reference statistical advantages of the formula
- - Consider special situations as bonus opportunities
- - Express confidence in proven methodology
- - Acknowledge short-term volatility but long-term outperformance
-
- Return bullish for high Magic Formula scores (top quartile companies)."""),
-
- ("human", """Apply Magic Formula analysis to {ticker}:
-
- {analysis_data}
-
- Provide investment signal in JSON format:
- {{
- "signal": "bullish" | "bearish" | "neutral",
- "confidence": float (0-100),
- "reasoning": "string"
- }}""")
- ])
-
- prompt = template.invoke({"analysis_data": json.dumps(analysis_data, indent=2), "ticker": ticker})
-
- def create_default_greenblatt_signal():
- return GreenblattSignal(signal="neutral", confidence=0.0, reasoning="Analysis error, defaulting to neutral")
-
- return call_llm(
- prompt=prompt,
- pydantic_model=GreenblattSignal,
- agent_name=agent_id,
- state=state,
- default_factory=create_default_greenblatt_signal,
- )
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/marty_whitman_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/marty_whitman_agent.py
deleted file mode 100644
index 7855a90b3..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/marty_whitman_agent.py
+++ /dev/null
@@ -1,462 +0,0 @@
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - ticker symbols (array)
-# - end_date (string)
-# - FINANCIAL_DATASETS_API_KEY
-#
-# OUTPUT:
-# - Financial metrics: ROE, D/E, Current Ratio
-# - Financial line items: Revenue, Net Income, FCF, Debt, Equity, Retained Earnings, Operating Margin, R&D, Shares
-# - Market Cap
-#
-# PARAMETERS:
-# - period="annual"
-# - limit=10 years
-"""
-
-from fincept_terminal.Agents.src.graph.state import AgentState, show_agent_reasoning
-from fincept_terminal.Agents.src.tools.api import get_financial_metrics, get_market_cap, search_line_items
-from langchain_core.prompts import ChatPromptTemplate
-from langchain_core.messages import HumanMessage
-from pydantic import BaseModel
-import json
-from typing_extensions import Literal
-from fincept_terminal.Agents.src.utils.progress import progress
-from fincept_terminal.Agents.src.utils.llm import call_llm
-from fincept_terminal.Agents.src.utils.api_key import get_api_key_from_state
-
-
-class WhitmanSignal(BaseModel):
- signal: Literal["bullish", "bearish", "neutral"]
- confidence: float
- reasoning: str
-
-
-def marty_whitman_agent(state: AgentState, agent_id: str = "marty_whitman_agent"):
- """
- Marty Whitman: Safe & cheap, asset-based investing
- Focus: Balance sheet analysis, asset values, financial safety
- """
- data = state["data"]
- end_date = data["end_date"]
- tickers = data["tickers"]
- api_key = get_api_key_from_state(state, "FINANCIAL_DATASETS_API_KEY")
- analysis_data = {}
- whitman_analysis = {}
-
- for ticker in tickers:
- progress.update_status(agent_id, ticker, "Analyzing safe & cheap criteria")
- metrics = get_financial_metrics(ticker, end_date, period="annual", limit=5, api_key=api_key)
-
- financial_line_items = search_line_items(
- ticker,
- [
- "revenue", "net_income", "total_assets", "current_assets",
- "current_liabilities", "total_debt", "shareholders_equity",
- "cash_and_equivalents", "accounts_receivable", "inventory",
- "property_plant_equipment", "goodwill"
- ],
- end_date,
- period="annual",
- limit=5,
- api_key=api_key,
- )
-
- market_cap = get_market_cap(ticker, end_date, api_key=api_key)
-
- # Whitman's asset-focused framework
- asset_value_analysis = analyze_asset_values(financial_line_items, market_cap)
- financial_safety = analyze_financial_safety(financial_line_items)
- balance_sheet_strength = analyze_balance_sheet_quality(financial_line_items)
- safe_and_cheap = evaluate_safe_and_cheap_criteria(metrics, financial_line_items, market_cap)
- credit_worthiness = analyze_credit_worthiness(financial_line_items)
-
- # Whitman's asset-based scoring
- total_score = (
- asset_value_analysis["score"] * 0.3 +
- financial_safety["score"] * 0.25 +
- safe_and_cheap["score"] * 0.2 +
- balance_sheet_strength["score"] * 0.15 +
- credit_worthiness["score"] * 0.1
- )
-
- # Whitman's safety-first approach
- if total_score >= 8.0:
- signal = "bullish"
- elif total_score <= 4.5:
- signal = "bearish"
- else:
- signal = "neutral"
-
- analysis_data[ticker] = {
- "signal": signal,
- "score": total_score,
- "asset_value_analysis": asset_value_analysis,
- "financial_safety": financial_safety,
- "balance_sheet_strength": balance_sheet_strength,
- "safe_and_cheap": safe_and_cheap,
- "credit_worthiness": credit_worthiness
- }
-
- whitman_output = generate_whitman_output(ticker, analysis_data, state, agent_id)
-
- whitman_analysis[ticker] = {
- "signal": whitman_output.signal,
- "confidence": whitman_output.confidence,
- "reasoning": whitman_output.reasoning
- }
-
- progress.update_status(agent_id, ticker, "Done", analysis=whitman_output.reasoning)
-
- message = HumanMessage(content=json.dumps(whitman_analysis), name=agent_id)
-
- if state["metadata"]["show_reasoning"]:
- show_agent_reasoning(whitman_analysis, "Marty Whitman Agent")
-
- state["data"]["analyst_signals"][agent_id] = whitman_analysis
- progress.update_status(agent_id, None, "Done")
-
- return {"messages": [message], "data": state["data"]}
-
-
-def analyze_asset_values(financial_line_items: list, market_cap: float) -> dict:
- """Whitman's asset-based valuation analysis"""
- score = 0
- details = []
-
- if not financial_line_items or not market_cap:
- return {"score": 0, "details": "No asset data"}
-
- latest = financial_line_items[0]
-
- # Tangible asset value
- total_assets = latest.total_assets if latest.total_assets else 0
- goodwill = latest.goodwill if latest.goodwill else 0
- tangible_assets = total_assets - goodwill
- total_debt = latest.total_debt if latest.total_debt else 0
-
- if tangible_assets > 0:
- net_tangible_assets = tangible_assets - total_debt
- if net_tangible_assets > market_cap:
- score += 4
- details.append(f"Trading below tangible assets: {(net_tangible_assets / market_cap):.1f}x")
- elif net_tangible_assets > market_cap * 0.8:
- score += 3
- details.append(f"Strong tangible asset backing: {(net_tangible_assets / market_cap):.1f}x")
- elif net_tangible_assets > market_cap * 0.6:
- score += 2
- details.append(f"Adequate tangible asset backing: {(net_tangible_assets / market_cap):.1f}x")
-
- # Working capital value
- current_assets = latest.current_assets if latest.current_assets else 0
- current_liabilities = latest.current_liabilities if latest.current_liabilities else 0
- working_capital = current_assets - current_liabilities
-
- if working_capital > 0:
- wc_ratio = working_capital / market_cap
- if wc_ratio > 0.5:
- score += 2
- details.append(f"Strong working capital: {wc_ratio:.1%} of market cap")
- elif wc_ratio > 0.2:
- score += 1
- details.append(f"Positive working capital: {wc_ratio:.1%} of market cap")
-
- # Book value relationship
- shareholders_equity = latest.shareholders_equity if latest.shareholders_equity else 0
- if shareholders_equity > 0:
- price_to_book = market_cap / shareholders_equity
- if price_to_book < 0.8:
- score += 2
- details.append(f"Trading below 80% of book: {price_to_book:.2f} P/B")
- elif price_to_book < 1.2:
- score += 1
- details.append(f"Reasonable P/B ratio: {price_to_book:.2f}")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_financial_safety(financial_line_items: list) -> dict:
- """Whitman's financial safety analysis"""
- score = 0
- details = []
-
- if not financial_line_items:
- return {"score": 0, "details": "No safety data"}
-
- latest = financial_line_items[0]
-
- # Debt safety
- total_debt = latest.total_debt if latest.total_debt else 0
- shareholders_equity = latest.shareholders_equity if latest.shareholders_equity else 0
-
- if shareholders_equity > 0:
- debt_to_equity = total_debt / shareholders_equity
- if debt_to_equity < 0.3:
- score += 3
- details.append(f"Very safe debt level: {debt_to_equity:.2f} D/E")
- elif debt_to_equity < 0.6:
- score += 2
- details.append(f"Safe debt level: {debt_to_equity:.2f} D/E")
- elif debt_to_equity > 1.5:
- score -= 1
- details.append(f"High debt concern: {debt_to_equity:.2f} D/E")
-
- # Liquidity safety
- current_assets = latest.current_assets if latest.current_assets else 0
- current_liabilities = latest.current_liabilities if latest.current_liabilities else 0
-
- if current_liabilities > 0:
- current_ratio = current_assets / current_liabilities
- if current_ratio > 2.0:
- score += 2
- details.append(f"Strong liquidity: {current_ratio:.1f} current ratio")
- elif current_ratio > 1.5:
- score += 1
- details.append(f"Adequate liquidity: {current_ratio:.1f} current ratio")
- elif current_ratio < 1.0:
- score -= 2
- details.append(f"Liquidity concern: {current_ratio:.1f} current ratio")
-
- # Cash position
- cash = latest.cash_and_equivalents if latest.cash_and_equivalents else 0
- total_assets = latest.total_assets if latest.total_assets else 0
-
- if total_assets > 0:
- cash_ratio = cash / total_assets
- if cash_ratio > 0.15: # 15%+ cash
- score += 2
- details.append(f"Strong cash position: {cash_ratio:.1%} of assets")
- elif cash_ratio > 0.05:
- score += 1
- details.append(f"Reasonable cash position: {cash_ratio:.1%} of assets")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_balance_sheet_quality(financial_line_items: list) -> dict:
- """Whitman's balance sheet quality assessment"""
- score = 0
- details = []
-
- if not financial_line_items:
- return {"score": 0, "details": "No balance sheet data"}
-
- latest = financial_line_items[0]
-
- # Asset quality analysis
- current_assets = latest.current_assets if latest.current_assets else 0
- cash = latest.cash_and_equivalents if latest.cash_and_equivalents else 0
- receivables = latest.accounts_receivable if latest.accounts_receivable else 0
- inventory = latest.inventory if latest.inventory else 0
-
- # High-quality current assets
- if current_assets > 0:
- quality_assets = cash + receivables # Cash + receivables are higher quality
- quality_ratio = quality_assets / current_assets
- if quality_ratio > 0.7:
- score += 2
- details.append(f"High-quality current assets: {quality_ratio:.1%} cash+receivables")
- elif quality_ratio > 0.5:
- score += 1
- details.append(f"Reasonable asset quality: {quality_ratio:.1%} cash+receivables")
-
- # Fixed asset efficiency
- ppe = latest.property_plant_equipment if latest.property_plant_equipment else 0
- revenue = latest.revenue if latest.revenue else 0
-
- if ppe > 0 and revenue > 0:
- asset_turnover = revenue / ppe
- if asset_turnover > 3.0: # Efficient use of fixed assets
- score += 1
- details.append(f"Efficient fixed asset use: {asset_turnover:.1f}x turnover")
-
- # Goodwill concerns
- goodwill = latest.goodwill if latest.goodwill else 0
- total_assets = latest.total_assets if latest.total_assets else 0
-
- if total_assets > 0:
- goodwill_ratio = goodwill / total_assets
- if goodwill_ratio < 0.1: # Low goodwill
- score += 2
- details.append(f"Low goodwill risk: {goodwill_ratio:.1%} of assets")
- elif goodwill_ratio > 0.3: # High goodwill
- score -= 1
- details.append(f"High goodwill concern: {goodwill_ratio:.1%} of assets")
-
- # Equity growth
- equity_vals = [item.shareholders_equity for item in financial_line_items if item.shareholders_equity]
- if len(equity_vals) >= 3:
- equity_growth = (equity_vals[0] / equity_vals[-1]) ** (1 / len(equity_vals)) - 1
- if equity_growth > 0.08: # 8%+ equity growth
- score += 1
- details.append(f"Growing equity base: {equity_growth:.1%} CAGR")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def evaluate_safe_and_cheap_criteria(metrics: list, financial_line_items: list, market_cap: float) -> dict:
- """Whitman's 'safe and cheap' evaluation"""
- score = 0
- details = []
-
- if not metrics or not financial_line_items or not market_cap:
- return {"score": 0, "details": "No safe & cheap data"}
-
- latest_metrics = metrics[0]
- latest_financial = financial_line_items[0]
-
- # "Safe" criteria
- safety_score = 0
-
- # Low debt
- if latest_metrics.debt_to_equity and latest_metrics.debt_to_equity < 0.5:
- safety_score += 1
- details.append(f"Safe debt level: {latest_metrics.debt_to_equity:.2f} D/E")
-
- # Strong balance sheet
- if latest_metrics.current_ratio and latest_metrics.current_ratio > 1.5:
- safety_score += 1
- details.append(f"Safe liquidity: {latest_metrics.current_ratio:.1f} current ratio")
-
- # Asset backing
- if latest_financial.total_assets and latest_financial.total_debt:
- asset_coverage = latest_financial.total_assets / latest_financial.total_debt
- if asset_coverage > 3.0:
- safety_score += 1
- details.append(f"Safe asset coverage: {asset_coverage:.1f}x")
-
- # "Cheap" criteria
- cheap_score = 0
-
- # Low P/B
- if latest_metrics.price_to_book and latest_metrics.price_to_book < 1.5:
- cheap_score += 1
- details.append(f"Cheap P/B: {latest_metrics.price_to_book:.2f}")
-
- # Low P/E
- if latest_metrics.price_to_earnings and latest_metrics.price_to_earnings < 15:
- cheap_score += 1
- details.append(f"Cheap P/E: {latest_metrics.price_to_earnings:.1f}")
-
- # Asset value
- if latest_financial.shareholders_equity and latest_financial.shareholders_equity > market_cap:
- cheap_score += 1
- details.append("Cheap relative to book value")
-
- # Combined safe & cheap score
- if safety_score >= 2 and cheap_score >= 2:
- score = 10 # Perfect safe & cheap
- details.append("Meets Whitman's safe & cheap criteria")
- elif safety_score >= 2:
- score = 6 # Safe but not cheap
- details.append("Safe but not particularly cheap")
- elif cheap_score >= 2:
- score = 4 # Cheap but not safe
- details.append("Cheap but safety concerns")
- else:
- score = 2 # Neither safe nor cheap
- details.append("Does not meet safe & cheap criteria")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_credit_worthiness(financial_line_items: list) -> dict:
- """Whitman's credit analysis approach"""
- score = 0
- details = []
-
- if not financial_line_items:
- return {"score": 0, "details": "No credit data"}
-
- latest = financial_line_items[0]
-
- # Interest coverage capability
- operating_income = latest.net_income if latest.net_income else 0 # Simplified
- total_debt = latest.total_debt if latest.total_debt else 0
-
- if total_debt > 0:
- # Estimate interest expense at 5%
- estimated_interest = total_debt * 0.05
- if operating_income > estimated_interest * 3: # 3x coverage
- score += 2
- details.append("Strong estimated interest coverage")
- elif operating_income > estimated_interest:
- score += 1
- details.append("Adequate estimated interest coverage")
- elif total_debt == 0:
- score += 3
- details.append("No debt - excellent credit position")
-
- # Cash flow coverage
- free_cash_flow = latest.free_cash_flow if latest.free_cash_flow else 0
- if free_cash_flow > 0 and total_debt > 0:
- debt_paydown_years = total_debt / free_cash_flow
- if debt_paydown_years < 5:
- score += 2
- details.append(f"Can pay down debt in {debt_paydown_years:.1f} years")
- elif debt_paydown_years < 10:
- score += 1
- details.append(f"Reasonable debt paydown period: {debt_paydown_years:.1f} years")
-
- # Working capital strength
- current_assets = latest.current_assets if latest.current_assets else 0
- current_liabilities = latest.current_liabilities if latest.current_liabilities else 0
-
- if current_liabilities > 0:
- working_capital_ratio = current_assets / current_liabilities
- if working_capital_ratio > 2.0:
- score += 1
- details.append(f"Strong working capital for credit: {working_capital_ratio:.1f}x")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def generate_whitman_output(ticker: str, analysis_data: dict, state: AgentState, agent_id: str) -> WhitmanSignal:
- """Generate Whitman-style safe & cheap investment decision"""
- template = ChatPromptTemplate.from_messages([
- ("system", """You are Marty Whitman's AI agent, applying safe & cheap asset-based investing:
-
- 1. Safe & Cheap: Both criteria must be met - financial safety AND attractive valuation
- 2. Asset-based analysis: Focus on balance sheet values and asset backing
- 3. Financial safety: Low debt, strong liquidity, conservative capital structure
- 4. Credit analysis: Evaluate creditworthiness and financial flexibility
- 5. Tangible value: Prefer tangible assets over intangibles and goodwill
- 6. Balance sheet focus: Income statement is secondary to balance sheet strength
- 7. Risk management: Downside protection through asset values
-
- Reasoning style:
- - Emphasize balance sheet analysis and asset values
- - Focus on financial safety and conservative capital structure
- - Discuss tangible asset backing and liquidation values
- - Consider credit worthiness and debt capacity
- - Apply rigorous safe & cheap criteria
- - Express preference for asset-rich, debt-light companies
- - Acknowledge when safety or cheapness criteria are not met
-
- Return bullish only for companies that are both financially safe AND attractively cheap."""),
-
- ("human", """Apply safe & cheap asset-based analysis to {ticker}:
-
- {analysis_data}
-
- Provide investment signal in JSON format:
- {{
- "signal": "bullish" | "bearish" | "neutral",
- "confidence": float (0-100),
- "reasoning": "string"
- }}""")
- ])
-
- prompt = template.invoke({"analysis_data": json.dumps(analysis_data, indent=2), "ticker": ticker})
-
- def create_default_whitman_signal():
- return WhitmanSignal(signal="neutral", confidence=0.0, reasoning="Analysis error, defaulting to neutral")
-
- return call_llm(
- prompt=prompt,
- pydantic_model=WhitmanSignal,
- agent_name=agent_id,
- state=state,
- default_factory=create_default_whitman_signal,
- )
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/seth_klarman_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/seth_klarman_agent.py
deleted file mode 100644
index 00d0831bc..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/seth_klarman_agent.py
+++ /dev/null
@@ -1,412 +0,0 @@
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - ticker symbols (array)
-# - end_date (string)
-# - FINANCIAL_DATASETS_API_KEY
-#
-# OUTPUT:
-# - Financial metrics: ROE, D/E, Current Ratio
-# - Financial line items: Revenue, Net Income, FCF, Debt, Equity, Retained Earnings, Operating Margin, R&D, Shares
-# - Market Cap
-#
-# PARAMETERS:
-# - period="annual"
-# - limit=10 years
-"""
-
-from fincept_terminal.Agents.src.graph.state import AgentState, show_agent_reasoning
-from fincept_terminal.Agents.src.tools.api import get_financial_metrics, get_market_cap, search_line_items
-from langchain_core.prompts import ChatPromptTemplate
-from langchain_core.messages import HumanMessage
-from pydantic import BaseModel
-import json
-from typing_extensions import Literal
-from fincept_terminal.Agents.src.utils.progress import progress
-from fincept_terminal.Agents.src.utils.llm import call_llm
-from fincept_terminal.Agents.src.utils.api_key import get_api_key_from_state
-
-
-class KlarmanSignal(BaseModel):
- signal: Literal["bullish", "bearish", "neutral"]
- confidence: float
- reasoning: str
-
-
-def seth_klarman_agent(state: AgentState, agent_id: str = "seth_klarman_agent"):
- """
- Seth Klarman: Absolute return, risk-first approach, contrarian
- Focus: Capital preservation, asymmetric risk/reward, distressed opportunities
- """
- data = state["data"]
- end_date = data["end_date"]
- tickers = data["tickers"]
- api_key = get_api_key_from_state(state, "FINANCIAL_DATASETS_API_KEY")
- analysis_data = {}
- klarman_analysis = {}
-
- for ticker in tickers:
- progress.update_status(agent_id, ticker, "Analyzing downside protection")
- metrics = get_financial_metrics(ticker, end_date, period="annual", limit=5, api_key=api_key)
-
- financial_line_items = search_line_items(
- ticker,
- [
- "revenue", "net_income", "total_assets", "current_assets",
- "current_liabilities", "total_debt", "cash_and_equivalents",
- "shareholders_equity", "free_cash_flow", "operating_income"
- ],
- end_date,
- period="annual",
- limit=5,
- api_key=api_key,
- )
-
- market_cap = get_market_cap(ticker, end_date, api_key=api_key)
-
- # Klarman's risk-first analyses
- downside_protection = analyze_downside_protection(financial_line_items, market_cap)
- asymmetric_opportunity = analyze_asymmetric_risk_reward(metrics, financial_line_items, market_cap)
- contrarian_indicators = analyze_contrarian_opportunity(metrics, financial_line_items)
- balance_sheet_strength = analyze_balance_sheet_fortress(financial_line_items)
- margin_of_safety = calculate_klarman_margin_of_safety(financial_line_items, market_cap)
-
- # Klarman's conservative scoring (risk-adjusted)
- total_score = (
- downside_protection["score"] * 0.3 +
- balance_sheet_strength["score"] * 0.25 +
- margin_of_safety["score"] * 0.2 +
- asymmetric_opportunity["score"] * 0.15 +
- contrarian_indicators["score"] * 0.1
- )
-
- # Klarman's high bar for investment
- if total_score >= 8.0:
- signal = "bullish"
- elif total_score <= 4.0:
- signal = "bearish"
- else:
- signal = "neutral" # Most opportunities don't meet Klarman's standards
-
- analysis_data[ticker] = {
- "signal": signal,
- "score": total_score,
- "downside_protection": downside_protection,
- "asymmetric_opportunity": asymmetric_opportunity,
- "contrarian_indicators": contrarian_indicators,
- "balance_sheet_strength": balance_sheet_strength,
- "margin_of_safety": margin_of_safety
- }
-
- klarman_output = generate_klarman_output(ticker, analysis_data, state, agent_id)
-
- klarman_analysis[ticker] = {
- "signal": klarman_output.signal,
- "confidence": klarman_output.confidence,
- "reasoning": klarman_output.reasoning
- }
-
- progress.update_status(agent_id, ticker, "Done", analysis=klarman_output.reasoning)
-
- message = HumanMessage(content=json.dumps(klarman_analysis), name=agent_id)
-
- if state["metadata"]["show_reasoning"]:
- show_agent_reasoning(klarman_analysis, "Seth Klarman Agent")
-
- state["data"]["analyst_signals"][agent_id] = klarman_analysis
- progress.update_status(agent_id, None, "Done")
-
- return {"messages": [message], "data": state["data"]}
-
-
-def analyze_downside_protection(financial_line_items: list, market_cap: float) -> dict:
- """Klarman's obsession with downside protection"""
- score = 0
- details = []
-
- if not financial_line_items or not market_cap:
- return {"score": 0, "details": "No data for downside analysis"}
-
- latest = financial_line_items[0]
-
- # Asset coverage
- total_assets = latest.total_assets if latest.total_assets else 0
- total_debt = latest.total_debt if latest.total_debt else 0
-
- if total_assets > 0:
- asset_coverage = total_assets / market_cap
- if asset_coverage > 2.0:
- score += 3
- details.append(f"Strong asset coverage: {asset_coverage:.1f}x market cap")
- elif asset_coverage > 1.5:
- score += 2
- details.append(f"Adequate asset coverage: {asset_coverage:.1f}x market cap")
-
- # Liquidation value protection
- current_assets = latest.current_assets if latest.current_assets else 0
- current_liabilities = latest.current_liabilities if latest.current_liabilities else 0
-
- # Conservative liquidation values
- cash = latest.cash_and_equivalents if latest.cash_and_equivalents else 0
- liquidation_value = cash + (current_assets - cash) * 0.7 # 70% recovery on non-cash assets
- net_liquidation = liquidation_value - current_liabilities - total_debt
-
- if net_liquidation > 0:
- liquidation_ratio = net_liquidation / market_cap
- if liquidation_ratio > 0.5:
- score += 4
- details.append(f"Exceptional liquidation protection: {liquidation_ratio:.1%}")
- elif liquidation_ratio > 0.2:
- score += 2
- details.append(f"Good liquidation value: {liquidation_ratio:.1%}")
-
- # Earnings floor
- earnings = [item.net_income for item in financial_line_items if item.net_income]
- if earnings:
- worst_earnings = min(earnings)
- if worst_earnings > 0:
- score += 2
- details.append("No losses in available periods")
- elif worst_earnings > -market_cap * 0.05: # Small losses relative to market cap
- score += 1
- details.append("Limited downside from worst historical performance")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_asymmetric_risk_reward(metrics: list, financial_line_items: list, market_cap: float) -> dict:
- """Klarman's focus on asymmetric opportunities"""
- score = 0
- details = []
-
- if not financial_line_items or not market_cap:
- return {"score": 0, "details": "No data for asymmetric analysis"}
-
- latest = financial_line_items[0]
-
- # Upside potential vs downside risk
- # Calculate normalized earnings power
- earnings = [item.net_income for item in financial_line_items if item.net_income and item.net_income > 0]
- if earnings:
- avg_earnings = sum(earnings) / len(earnings)
- normalized_pe = market_cap / avg_earnings if avg_earnings > 0 else 0
-
- # If trading at low multiple with asset protection, asymmetric opportunity
- if normalized_pe < 12 and latest.total_assets and latest.total_assets > market_cap:
- score += 3
- details.append(f"Asymmetric setup: {normalized_pe:.1f} P/E with asset backing")
-
- # Free cash flow yield vs risk
- if latest.free_cash_flow and latest.free_cash_flow > 0:
- fcf_yield = latest.free_cash_flow / market_cap
- debt_ratio = (latest.total_debt / latest.total_assets) if latest.total_assets else 1
-
- # High FCF yield with low debt = good risk/reward
- if fcf_yield > 0.1 and debt_ratio < 0.3:
- score += 2
- details.append(f"Strong FCF yield ({fcf_yield:.1%}) with low debt")
-
- # Catalyst potential (simplified)
- # Look for companies with improving trends that market hasn't recognized
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if len(revenues) >= 3:
- recent_growth = (revenues[0] / revenues[1]) - 1
- if recent_growth > 0.1: # 10%+ recent growth
- score += 1
- details.append(f"Potential catalyst: {recent_growth:.1%} recent revenue growth")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_contrarian_opportunity(metrics: list, financial_line_items: list) -> dict:
- """Klarman's contrarian approach to investing"""
- score = 0
- details = []
-
- if not metrics or not financial_line_items:
- return {"score": 0, "details": "No data for contrarian analysis"}
-
- latest_metrics = metrics[0]
-
- # Low valuation multiples (contrarian indicator)
- if latest_metrics.price_to_book and latest_metrics.price_to_book < 1.0:
- score += 2
- details.append(f"Contrarian P/B: {latest_metrics.price_to_book:.2f}")
-
- if latest_metrics.price_to_earnings and latest_metrics.price_to_earnings < 10:
- score += 2
- details.append(f"Contrarian P/E: {latest_metrics.price_to_earnings:.1f}")
-
- # Temporary earnings depression
- earnings = [item.net_income for item in financial_line_items if item.net_income]
- if len(earnings) >= 3:
- recent_earnings = earnings[0]
- historical_avg = sum(earnings[1:]) / len(earnings[1:])
-
- if recent_earnings < historical_avg * 0.7 and recent_earnings > 0:
- score += 2
- details.append("Potential temporary earnings depression")
-
- # Industry or company-specific distress signals
- # (Would typically require more external data, simplified here)
- if latest_metrics.current_ratio and latest_metrics.current_ratio < 1.2:
- # Low current ratio might indicate distress (opportunity for contrarian)
- score += 1
- details.append("Potential distress situation for contrarian investment")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def analyze_balance_sheet_fortress(financial_line_items: list) -> dict:
- """Klarman's requirement for fortress balance sheets"""
- score = 0
- details = []
-
- if not financial_line_items:
- return {"score": 0, "details": "No balance sheet data"}
-
- latest = financial_line_items[0]
-
- # Cash and liquidity
- cash = latest.cash_and_equivalents if latest.cash_and_equivalents else 0
- current_assets = latest.current_assets if latest.current_assets else 0
- current_liabilities = latest.current_liabilities if latest.current_liabilities else 0
-
- if current_liabilities > 0:
- current_ratio = current_assets / current_liabilities
- if current_ratio > 2.0:
- score += 2
- details.append(f"Strong liquidity: {current_ratio:.1f} current ratio")
-
- # Debt levels
- total_debt = latest.total_debt if latest.total_debt else 0
- shareholders_equity = latest.shareholders_equity if latest.shareholders_equity else 0
-
- if shareholders_equity > 0:
- debt_to_equity = total_debt / shareholders_equity
- if debt_to_equity < 0.3:
- score += 3
- details.append(f"Conservative debt: {debt_to_equity:.2f} D/E")
- elif debt_to_equity < 0.5:
- score += 1
- details.append(f"Moderate debt: {debt_to_equity:.2f} D/E")
-
- # Working capital strength
- working_capital = current_assets - current_liabilities
- if working_capital > 0 and latest.total_assets:
- wc_ratio = working_capital / latest.total_assets
- if wc_ratio > 0.2:
- score += 2
- details.append(f"Strong working capital: {wc_ratio:.1%} of assets")
-
- # Interest coverage
- if latest.operating_income and total_debt > 0:
- # Simplified interest coverage (assume 5% interest rate)
- estimated_interest = total_debt * 0.05
- if latest.operating_income > estimated_interest * 5:
- score += 2
- details.append("Strong interest coverage capability")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def calculate_klarman_margin_of_safety(financial_line_items: list, market_cap: float) -> dict:
- """Klarman's conservative margin of safety calculation"""
- score = 0
- details = []
-
- if not financial_line_items or not market_cap:
- return {"score": 0, "details": "No data for margin of safety"}
-
- latest = financial_line_items[0]
-
- # Conservative asset-based valuation
- total_assets = latest.total_assets if latest.total_assets else 0
- total_debt = latest.total_debt if latest.total_debt else 0
-
- # Apply conservative haircuts to assets
- conservative_asset_value = total_assets * 0.7 # 30% haircut
- net_asset_value = conservative_asset_value - total_debt
-
- if net_asset_value > 0:
- asset_margin = (net_asset_value - market_cap) / market_cap
- if asset_margin > 0.5:
- score += 3
- details.append(f"Excellent asset margin of safety: {asset_margin:.1%}")
- elif asset_margin > 0.2:
- score += 2
- details.append(f"Good asset margin of safety: {asset_margin:.1%}")
-
- # Conservative earnings-based valuation
- earnings = [item.net_income for item in financial_line_items if item.net_income and item.net_income > 0]
- if earnings:
- # Use conservative multiple (10x) on average earnings
- avg_earnings = sum(earnings) / len(earnings)
- conservative_earnings_value = avg_earnings * 10
-
- earnings_margin = (conservative_earnings_value - market_cap) / market_cap
- if earnings_margin > 0.3:
- score += 2
- details.append(f"Earnings margin of safety: {earnings_margin:.1%}")
-
- # Free cash flow margin of safety
- if latest.free_cash_flow and latest.free_cash_flow > 0:
- # Conservative 12x FCF multiple
- fcf_value = latest.free_cash_flow * 12
- fcf_margin = (fcf_value - market_cap) / market_cap
-
- if fcf_margin > 0.25:
- score += 2
- details.append(f"FCF margin of safety: {fcf_margin:.1%}")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def generate_klarman_output(ticker: str, analysis_data: dict, state: AgentState, agent_id: str) -> KlarmanSignal:
- """Generate Klarman-style risk-first investment decision"""
- template = ChatPromptTemplate.from_messages([
- ("system", """You are Seth Klarman's AI agent, following absolute return value investing principles:
-
- 1. Risk first: "Return OF capital is more important than return ON capital"
- 2. Margin of safety: Buy with significant downside protection
- 3. Contrarian approach: Buy when others are selling
- 4. Asymmetric risk/reward: Limited downside, substantial upside
- 5. Balance sheet fortress: Strong financial position required
- 6. Patient opportunism: Wait for exceptional opportunities
- 7. Absolute return focus: Preserve capital above all else
-
- Reasoning style:
- - Emphasize downside protection and risk analysis first
- - Focus on balance sheet strength and asset coverage
- - Discuss margin of safety quantitatively
- - Consider contrarian and distressed opportunities
- - Express skepticism and conservatism
- - Require exceptional risk/reward ratios
- - Acknowledge when opportunities don't meet standards
-
- Return bullish only for exceptional risk/reward opportunities with substantial downside protection."""),
-
- ("human", """Apply risk-first value analysis to {ticker}:
-
- {analysis_data}
-
- Provide investment signal in JSON format:
- {{
- "signal": "bullish" | "bearish" | "neutral",
- "confidence": float (0-100),
- "reasoning": "string"
- }}""")
- ])
-
- prompt = template.invoke({"analysis_data": json.dumps(analysis_data, indent=2), "ticker": ticker})
-
- def create_default_klarman_signal():
- return KlarmanSignal(signal="neutral", confidence=0.0, reasoning="Analysis error, defaulting to neutral")
-
- return call_llm(
- prompt=prompt,
- pydantic_model=KlarmanSignal,
- agent_name=agent_id,
- state=state,
- default_factory=create_default_klarman_signal,
- )
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/warren_buffett_agent_v2.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/warren_buffett_agent_v2.py
deleted file mode 100644
index 74945487e..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/warren_buffett_agent_v2.py
+++ /dev/null
@@ -1,295 +0,0 @@
-"""
-Warren Buffett Agent - JSON-Driven Configuration
-Version 2.0 - Uses finagent_core and JSON config files
-
-User can customize via JSON:
-- Scoring weights
-- Thresholds
-- Data sources
-- Analysis rules
-"""
-
-import json
-import sys
-from pathlib import Path
-from typing import Dict, Any, List
-
-# Add parent directory to path
-sys.path.insert(0, str(Path(__file__).parent.parent.parent))
-
-from finagent_core.base_agent import AgentRegistry
-
-
-class WarrenBuffettAgent:
- """JSON-driven Warren Buffett investment analysis agent"""
-
- def __init__(self, config_path: Path = None):
- if config_path is None:
- config_path = Path(__file__).parent / "configs" / "agent_definitions.json"
-
- registry = AgentRegistry(config_path)
- self.config = registry.get_agent("warren_buffett_agent")
-
- if not self.config:
- raise ValueError("Warren Buffett agent config not found")
-
- # Extract configuration sections
- self.weights = self.config._raw_config.get("scoring_weights", {})
- self.thresholds = self.config._raw_config.get("thresholds", {})
- self.rules = self.config._raw_config.get("analysis_rules", {})
- self.data_sources = self.config._raw_config.get("data_sources", {})
-
- def analyze(self, tickers: List[str], end_date: str, api_key: str = None) -> Dict:
- """
- Analyze stocks using Buffett's methodology with JSON-driven parameters
-
- Args:
- tickers: List of stock symbols
- end_date: Analysis end date
- api_key: Financial datasets API key
-
- Returns:
- Dictionary of analysis results per ticker
- """
- results = {}
-
- for ticker in tickers:
- try:
- # Fetch data based on JSON config
- metrics = self._fetch_financial_metrics(ticker, end_date, api_key)
- line_items = self._fetch_line_items(ticker, end_date, api_key)
- market_cap = self._fetch_market_cap(ticker, end_date, api_key)
-
- # Run analyses with JSON-configured parameters
- moat_score = self._analyze_economic_moat(metrics, line_items)
- earnings_score = self._analyze_earnings_predictability(line_items)
- strength_score = self._analyze_financial_strength(metrics, line_items)
- management_score = self._analyze_management_quality(line_items)
- valuation_score = self._analyze_valuation(line_items, market_cap)
-
- # Calculate total score using JSON weights
- total_score = (
- moat_score["score"] * self.weights.get("moat_analysis", 0.3) +
- earnings_score["score"] * self.weights.get("earnings_predictability", 0.25) +
- strength_score["score"] * self.weights.get("financial_strength", 0.2) +
- management_score["score"] * self.weights.get("management_quality", 0.15) +
- valuation_score["score"] * self.weights.get("valuation", 0.1)
- )
-
- # Determine signal using JSON thresholds
- if total_score >= self.thresholds.get("bullish_score", 8.0):
- signal = "bullish"
- elif total_score <= self.thresholds.get("bearish_score", 4.0):
- signal = "bearish"
- else:
- signal = "neutral"
-
- results[ticker] = {
- "signal": signal,
- "total_score": total_score,
- "moat_analysis": moat_score,
- "earnings_predictability": earnings_score,
- "financial_strength": strength_score,
- "management_quality": management_score,
- "valuation_analysis": valuation_score,
- "configuration_used": {
- "weights": self.weights,
- "thresholds": self.thresholds
- }
- }
-
- except Exception as e:
- results[ticker] = {
- "signal": "error",
- "error": str(e)
- }
-
- return results
-
- def _analyze_economic_moat(self, metrics: List, line_items: List) -> Dict:
- """Analyze economic moat using JSON-configured rules"""
- score = 0
- details = []
-
- if not metrics:
- return {"score": 0, "details": "No metrics data"}
-
- # Get thresholds from JSON
- roe_threshold = self.thresholds.get("roe_excellence", 0.15)
- roe_years = self.thresholds.get("roe_years_required", 7)
- margin_stability = self.thresholds.get("margin_stability_max", 0.05)
- margin_min = self.thresholds.get("margin_minimum", 0.15)
-
- # Get points from JSON rules
- moat_rules = self.rules.get("moat_analysis", {})
- high_roe_points = moat_rules.get("high_roe_points", 3)
- good_roe_points = moat_rules.get("good_roe_points", 2)
- stable_margins_points = moat_rules.get("stable_margins_points", 2)
- steady_growth_points = moat_rules.get("steady_growth_points", 2)
-
- # High ROE analysis (JSON-configured)
- roe_vals = [m.get("return_on_equity") for m in metrics if m.get("return_on_equity")]
- if roe_vals:
- high_roe_count = sum(1 for roe in roe_vals if roe > roe_threshold)
- if high_roe_count >= roe_years:
- score += high_roe_points
- details.append(f"Exceptional ROE: {high_roe_count}/10 years >{roe_threshold:.0%}")
- elif high_roe_count >= 5:
- score += good_roe_points
- details.append(f"Good ROE: {high_roe_count}/10 years >{roe_threshold:.0%}")
-
- # Margin stability (JSON-configured)
- margins = [item.get("operating_margin") for item in line_items if item.get("operating_margin")]
- if margins and len(margins) >= 5:
- margin_vol = max(margins) - min(margins)
- avg_margin = sum(margins) / len(margins)
- if margin_vol < margin_stability and avg_margin > margin_min:
- score += stable_margins_points
- details.append(f"Stable margins: {avg_margin:.1%} avg")
-
- # Revenue growth (JSON-configured)
- revenues = [item.get("revenue") for item in line_items if item.get("revenue")]
- if len(revenues) >= 5:
- growth_min = self.thresholds.get("revenue_growth_min", 0.05)
- growth_max = self.thresholds.get("revenue_growth_max", 0.15)
- cagr = (revenues[0] / revenues[-1]) ** (1 / len(revenues)) - 1
- if growth_min <= cagr <= growth_max:
- score += steady_growth_points
- details.append(f"Steady growth: {cagr:.1%} CAGR")
-
- return {"score": score, "details": "; ".join(details)}
-
- def _analyze_earnings_predictability(self, line_items: List) -> Dict:
- """Analyze earnings predictability using JSON config"""
- score = 0
- details = []
-
- earnings = [item.get("net_income") for item in line_items if item.get("net_income")]
- if len(earnings) < 5:
- return {"score": 0, "details": "Insufficient data"}
-
- rules = self.rules.get("earnings_predictability", {})
- years_required = self.thresholds.get("positive_earnings_years", 8)
-
- # Consistent profitability
- positive_years = sum(1 for e in earnings if e > 0)
- if positive_years >= years_required:
- score += rules.get("consistent_profit_points", 3)
- details.append(f"Consistent: {positive_years}/10 years profitable")
-
- # Growth trend
- if len(earnings) >= 10:
- recent_avg = sum(earnings[:5]) / 5
- older_avg = sum(earnings[5:10]) / 5
- if recent_avg > older_avg * 1.5:
- score += rules.get("growth_trend_points", 2)
- details.append("Strong growth trend")
-
- # Low volatility
- if earnings:
- volatility = (max(earnings) - min(earnings)) / max(abs(max(earnings)), abs(min(earnings)))
- if volatility < 1.0:
- score += rules.get("low_volatility_points", 2)
- details.append(f"Low volatility: {volatility:.2f}")
-
- return {"score": score, "details": "; ".join(details)}
-
- def _analyze_financial_strength(self, metrics: List, line_items: List) -> Dict:
- """Analyze financial strength using JSON config"""
- score = 0
- details = []
-
- if not metrics or not line_items:
- return {"score": 0, "details": "No data"}
-
- latest = metrics[0] if metrics else {}
- rules = self.rules.get("financial_strength", {})
-
- # Low debt (JSON-configured)
- de_max = self.thresholds.get("debt_to_equity_max", 0.3)
- if latest.get("debt_to_equity") and latest["debt_to_equity"] < de_max:
- score += rules.get("low_debt_points", 3)
- details.append(f"Low debt: {latest['debt_to_equity']:.2f} D/E")
-
- # High liquidity (JSON-configured)
- cr_min = self.thresholds.get("current_ratio_min", 1.5)
- if latest.get("current_ratio") and latest["current_ratio"] > cr_min:
- score += rules.get("high_liquidity_points", 2)
- details.append(f"Strong liquidity: {latest['current_ratio']:.1f}")
-
- # Positive FCF (JSON-configured)
- fcf_vals = [item.get("free_cash_flow") for item in line_items if item.get("free_cash_flow")]
- fcf_years = self.thresholds.get("positive_fcf_years", 8)
- if fcf_vals:
- positive_fcf = sum(1 for fcf in fcf_vals if fcf > 0)
- if positive_fcf >= fcf_years:
- score += rules.get("positive_fcf_points", 2)
- details.append(f"Reliable FCF: {positive_fcf}/10 years")
-
- return {"score": score, "details": "; ".join(details)}
-
- def _analyze_management_quality(self, line_items: List) -> Dict:
- """Analyze management quality using JSON config"""
- score = 0
- details = []
-
- rules = self.rules.get("management_quality", {})
-
- # Share buybacks
- shares = [item.get("outstanding_shares") for item in line_items if item.get("outstanding_shares")]
- if len(shares) >= 5:
- reduction = (shares[-1] - shares[0]) / shares[-1]
- if reduction > 0.1:
- score += rules.get("buyback_points", 2)
- details.append(f"Buybacks: {reduction:.1%} reduction")
-
- # Retained earnings growth
- re_vals = [item.get("retained_earnings") for item in line_items if item.get("retained_earnings")]
- if len(re_vals) >= 5:
- re_growth = (re_vals[0] - re_vals[-1]) / abs(re_vals[-1])
- if re_growth > 0.5:
- score += rules.get("reinvestment_points", 2)
- details.append(f"Reinvestment: {re_growth:.1%} RE growth")
-
- return {"score": score, "details": "; ".join(details)}
-
- def _analyze_valuation(self, line_items: List, market_cap: float) -> Dict:
- """Placeholder for valuation analysis"""
- # User can add custom valuation logic
- return {"score": 5.0, "details": "Valuation analysis placeholder"}
-
- def _fetch_financial_metrics(self, ticker: str, end_date: str, api_key: str) -> List[Dict]:
- """Fetch metrics - placeholder for API integration"""
- # TODO: Integrate with actual financial API
- return []
-
- def _fetch_line_items(self, ticker: str, end_date: str, api_key: str) -> List[Dict]:
- """Fetch line items - placeholder for API integration"""
- # TODO: Integrate with actual financial API
- return []
-
- def _fetch_market_cap(self, ticker: str, end_date: str, api_key: str) -> float:
- """Fetch market cap - placeholder for API integration"""
- # TODO: Integrate with actual financial API
- return 0.0
-
-
-def main():
- """CLI entry point for testing"""
- import argparse
-
- parser = argparse.ArgumentParser(description="Warren Buffett Agent - JSON Configured")
- parser.add_argument("--tickers", nargs="+", required=True, help="Stock tickers")
- parser.add_argument("--end-date", default="2024-12-31", help="Analysis end date")
- parser.add_argument("--api-key", help="Financial datasets API key")
-
- args = parser.parse_args()
-
- agent = WarrenBuffettAgent()
- results = agent.analyze(args.tickers, args.end_date, args.api_key)
-
- print(json.dumps(results, indent=2))
-
-
-if __name__ == "__main__":
- main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/agent_orchestrator.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/agent_orchestrator.py
deleted file mode 100644
index b8ed686f8..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/agent_orchestrator.py
+++ /dev/null
@@ -1,579 +0,0 @@
-# -*- coding: utf-8 -*-
-# agent_orchestrator.py
-
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - ticker symbols (array)
-# - end_date (string)
-# - FINANCIAL_DATASETS_API_KEY
-#
-# OUTPUT:
-# - Financial metrics: ROE, D/E, Current Ratio
-# - Financial line items: Revenue, Net Income, FCF, Debt, Equity, Retained Earnings, Operating Margin, R&D, Shares
-# - Market Cap
-#
-# PARAMETERS:
-# - period="annual"
-# - limit=10 years
-"""
-
-import asyncio
-import json
-import logging
-import numpy as np
-from datetime import datetime
-from typing import Dict, List, Any, Optional
-from dataclasses import dataclass
-import google.generativeai as genai
-
-# Import all agents
-from fincept_terminal.Agents.fincept_hedge_fund.macro_cycle_agent import MacroCycleAgent
-from fincept_terminal.Agents.fincept_hedge_fund.central_bank_agent import CentralBankAgent
-from fincept_terminal.Agents.fincept_hedge_fund.geopolitical_agent import GeopoliticalAgent
-from fincept_terminal.Agents.fincept_hedge_fund.regulatory_agent import RegulatoryAgent
-from fincept_terminal.Agents.fincept_hedge_fund.sentiment_agent import SentimentAgent
-from fincept_terminal.Agents.fincept_hedge_fund.institutional_flow_agent import InstitutionalFlowAgent
-from fincept_terminal.Agents.fincept_hedge_fund.supply_chain_agent import SupplyChainAgent
-from fincept_terminal.Agents.fincept_hedge_fund.innovation_agent import InnovationAgent
-from fincept_terminal.Agents.fincept_hedge_fund.currency_agent import CurrencyAgent
-from fincept_terminal.Agents.fincept_hedge_fund.behavioral_agent import BehavioralAgent
-from config import CONFIG
-
-
-@dataclass
-class AgentDecision:
- """Standardized agent decision structure"""
- agent_name: str
- timestamp: datetime
- signal_strength: float # 0-1
- direction: str # bullish, bearish, neutral
- confidence: float
- key_insights: List[str]
- market_implications: Dict[str, float]
- time_horizon: str
- raw_analysis: Dict[str, Any]
-
-
-@dataclass
-class ConsensusDecision:
- """Final consensus decision from all agents"""
- timestamp: datetime
- overall_signal: str # strong_buy, buy, hold, sell, strong_sell
- conviction_level: float # 0-1
- asset_allocation: Dict[str, float]
- sector_weights: Dict[str, float]
- risk_level: float
- consensus_factors: List[str]
- dissenting_views: List[str]
- execution_priority: str
-
-
-class AgentOrchestrator:
- """Orchestrates multi-agent analysis with inter-agent communication"""
-
- def __init__(self, gemini_api_key: str):
- # Configure Gemini AI
- genai.configure(api_key=gemini_api_key)
- self.gemini_model = genai.GenerativeModel('gemini-pro')
-
- # Initialize all agents
- self.agents = {
- 'macro': MacroCycleAgent(),
- 'fed': CentralBankAgent(),
- 'geo': GeopoliticalAgent(),
- 'regulatory': RegulatoryAgent(),
- 'sentiment': SentimentAgent(),
- 'flows': InstitutionalFlowAgent(),
- 'supply': SupplyChainAgent(),
- 'innovation': InnovationAgent(),
- 'fx': CurrencyAgent(),
- 'behavioral': BehavioralAgent()
- }
-
- # Agent communication weights for decision making
- self.agent_weights = {
- 'macro': 0.20, # Highest weight - drives overall allocation
- 'fed': 0.18, # Critical for duration and rates
- 'geo': 0.15, # Major risk factor
- 'flows': 0.12, # Smart money indicator
- 'sentiment': 0.10, # Contrarian signals
- 'regulatory': 0.08, # Policy impacts
- 'supply': 0.07, # Sector-specific risks
- 'fx': 0.05, # Portfolio hedging
- 'behavioral': 0.03, # Market psychology
- 'innovation': 0.02 # Long-term trends
- }
-
- # Setup logging
- logging.basicConfig(level=logging.INFO,
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
- self.logger = logging.getLogger("AgentOrchestrator")
-
- async def run_comprehensive_analysis(self, target_assets: List[str] = None) -> ConsensusDecision:
- """Run comprehensive analysis with all agents and generate consensus decision"""
- self.logger.info("🚀 Starting comprehensive multi-agent analysis...")
-
- # Step 1: Run all agents concurrently
- agent_decisions = await self._execute_all_agents()
-
- # Step 2: Enable agent-to-agent communication
- enriched_decisions = await self._facilitate_agent_communication(agent_decisions)
-
- # Step 3: Generate consensus using Gemini AI
- consensus = await self._generate_consensus_decision(enriched_decisions, target_assets)
-
- # Step 4: Validate and refine decision
- final_decision = await self._validate_and_refine_decision(consensus, enriched_decisions)
-
- self.logger.info(f"✅ Analysis complete. Final signal: {final_decision.overall_signal}")
- return final_decision
-
- async def _execute_all_agents(self) -> Dict[str, AgentDecision]:
- """Execute all agents concurrently and standardize outputs"""
- self.logger.info("📊 Executing all agents concurrently...")
-
- async def run_single_agent(name: str, agent: Any) -> AgentDecision:
- try:
- # Get agent report
- if hasattr(agent, 'get_cycle_report'):
- report = await agent.get_cycle_report()
- elif hasattr(agent, 'get_policy_report'):
- report = await agent.get_policy_report()
- elif hasattr(agent, 'get_geopolitical_report'):
- report = await agent.get_geopolitical_report()
- elif hasattr(agent, 'get_regulatory_report'):
- report = await agent.get_regulatory_report()
- elif hasattr(agent, 'get_sentiment_report'):
- report = await agent.get_sentiment_report()
- elif hasattr(agent, 'get_flow_report'):
- report = await agent.get_flow_report()
- elif hasattr(agent, 'get_supply_chain_report'):
- report = await agent.get_supply_chain_report()
- elif hasattr(agent, 'get_innovation_report'):
- report = await agent.get_innovation_report()
- elif hasattr(agent, 'get_currency_report'):
- report = await agent.get_currency_report()
- elif hasattr(agent, 'get_behavioral_report'):
- report = await agent.get_behavioral_report()
- else:
- report = {"error": f"No report method found for {name}"}
-
- # Standardize the output
- return self._standardize_agent_output(name, report)
-
- except Exception as e:
- self.logger.error(f"❌ Error in agent {name}: {e}")
- return self._create_error_decision(name, str(e))
-
- # Run all agents concurrently
- tasks = [run_single_agent(name, agent) for name, agent in self.agents.items()]
- results = await asyncio.gather(*tasks, return_exceptions=True)
-
- # Combine results
- agent_decisions = {}
- for i, (name, agent) in enumerate(self.agents.items()):
- if i < len(results) and isinstance(results[i], AgentDecision):
- agent_decisions[name] = results[i]
- else:
- agent_decisions[name] = self._create_error_decision(name, "Execution failed")
-
- self.logger.info(f"📈 Completed analysis from {len(agent_decisions)} agents")
- return agent_decisions
-
- def _standardize_agent_output(self, agent_name: str, report: Dict[str, Any]) -> AgentDecision:
- """Standardize agent outputs into common decision format"""
- try:
- # Extract key metrics based on agent type
- signal_strength, direction, confidence, insights, implications = self._extract_agent_metrics(agent_name,
- report)
-
- return AgentDecision(
- agent_name=agent_name,
- timestamp=datetime.now(),
- signal_strength=signal_strength,
- direction=direction,
- confidence=confidence,
- key_insights=insights,
- market_implications=implications,
- time_horizon=self._determine_time_horizon(agent_name, report),
- raw_analysis=report
- )
-
- except Exception as e:
- self.logger.error(f"Error standardizing {agent_name} output: {e}")
- return self._create_error_decision(agent_name, str(e))
-
- def _extract_agent_metrics(self, agent_name: str, report: Dict) -> tuple:
- """Extract standardized metrics from agent reports"""
- # Default values
- signal_strength = 0.5
- direction = "neutral"
- confidence = 0.5
- insights = []
- implications = {}
-
- try:
- if agent_name == 'macro':
- cycle_analysis = report.get('cycle_analysis', {})
- phase = cycle_analysis.get('current_phase', 'expansion')
- signal_strength = cycle_analysis.get('strength', 0.5)
- direction = "bullish" if phase in ['expansion', 'trough'] else "bearish"
- confidence = cycle_analysis.get('confidence', 0.5)
- insights = [f"Business cycle: {phase}"]
- implications = report.get('investment_implications', {})
-
- elif agent_name == 'fed':
- fed_analysis = report.get('fed_analysis', {})
- stance = fed_analysis.get('policy_stance', 'neutral')
- signal_strength = fed_analysis.get('probability', 0.5)
- direction = "bearish" if stance == 'hawkish' else "bullish" if stance == 'dovish' else "neutral"
- confidence = fed_analysis.get('confidence', 0.5)
- insights = [f"Fed stance: {stance}", f"Rate direction: {fed_analysis.get('rate_direction', 'holding')}"]
- implications = report.get('market_impact', {})
-
- elif agent_name == 'geo':
- risk_assessment = report.get('global_risk_assessment', {})
- risk_level = risk_assessment.get('overall_risk_level', 5)
- signal_strength = min(risk_level / 10, 1.0)
- direction = "bearish" if risk_level > 6 else "neutral"
- confidence = 0.7
- top_risks = risk_assessment.get('top_risks', [])
- insights = [f"Geopolitical risk: {risk_level}/10"] + [risk.get('type', '') for risk in top_risks[:2]]
- implications = report.get('investment_implications', {})
-
- elif agent_name == 'sentiment':
- sentiment_analysis = report.get('sentiment_analysis', {})
- overall_sentiment = sentiment_analysis.get('overall_sentiment', 0)
- signal_strength = abs(overall_sentiment)
- direction = "bullish" if overall_sentiment > 0.2 else "bearish" if overall_sentiment < -0.2 else "neutral"
- confidence = 0.6
- insights = [f"Market sentiment: {sentiment_analysis.get('sentiment_classification', 'neutral')}"]
- contrarian_signals = report.get('contrarian_signals', [])
- if contrarian_signals:
- insights.append(f"Contrarian opportunities: {len(contrarian_signals)}")
- implications = {"sentiment_momentum": overall_sentiment}
-
- elif agent_name == 'flows':
- flow_analysis = report.get('flow_analysis', {})
- flow_sentiment = flow_analysis.get('overall_flow_sentiment', 0)
- signal_strength = abs(flow_sentiment)
- direction = "bullish" if flow_sentiment > 0.1 else "bearish" if flow_sentiment < -0.1 else "neutral"
- confidence = 0.8
- insights = [f"Institutional flows: {flow_analysis.get('flow_classification', 'balanced')}"]
- implications = {"flow_momentum": flow_sentiment}
-
- # Add similar extraction logic for other agents...
- else:
- # Generic extraction for other agents
- insights = ["Analysis completed"]
- implications = {"general_impact": 0.0}
-
- except Exception as e:
- self.logger.error(f"Error extracting metrics for {agent_name}: {e}")
-
- return signal_strength, direction, confidence, insights, implications
-
- def _determine_time_horizon(self, agent_name: str, report: Dict) -> str:
- """Determine time horizon based on agent type"""
- horizon_map = {
- 'macro': 'long_term',
- 'fed': 'medium_term',
- 'geo': 'medium_term',
- 'regulatory': 'long_term',
- 'sentiment': 'short_term',
- 'flows': 'short_term',
- 'supply': 'medium_term',
- 'innovation': 'long_term',
- 'fx': 'short_term',
- 'behavioral': 'short_term'
- }
- return horizon_map.get(agent_name, 'medium_term')
-
- async def _facilitate_agent_communication(self, decisions: Dict[str, AgentDecision]) -> Dict[str, AgentDecision]:
- """Enable agents to communicate and refine their decisions based on peer insights"""
- self.logger.info("🤝 Facilitating inter-agent communication...")
-
- # Create communication summary for each agent
- for agent_name, decision in decisions.items():
- # Get peer insights relevant to this agent
- peer_insights = self._get_relevant_peer_insights(agent_name, decisions)
-
- # Use Gemini to refine the decision based on peer insights
- if peer_insights:
- refined_decision = await self._refine_decision_with_peers(decision, peer_insights)
- decisions[agent_name] = refined_decision
-
- return decisions
-
- def _get_relevant_peer_insights(self, agent_name: str, decisions: Dict[str, AgentDecision]) -> Dict[str, str]:
- """Get insights from peer agents relevant to the current agent"""
- peer_insights = {}
-
- # Define agent relationships and relevant insights
- agent_relationships = {
- 'macro': ['fed', 'geo', 'flows'], # Macro affected by policy, geopolitics, flows
- 'fed': ['macro', 'sentiment', 'flows'], # Fed policy affects sentiment, flows
- 'geo': ['supply', 'fx', 'flows'], # Geopolitics affects supply chains, currency, flows
- 'sentiment': ['behavioral', 'flows', 'macro'], # Sentiment relates to behavior, flows, macro
- 'flows': ['sentiment', 'macro', 'fed'], # Flows influenced by sentiment, macro, policy
- 'supply': ['geo', 'innovation', 'regulatory'], # Supply chains affected by geopolitics, innovation
- 'regulatory': ['innovation', 'supply', 'flows'], # Regulation affects innovation, supply, flows
- 'fx': ['fed', 'geo', 'flows'], # Currency affected by policy, geopolitics, flows
- 'behavioral': ['sentiment', 'flows', 'macro'], # Behavior relates to sentiment, flows, macro
- 'innovation': ['regulatory', 'supply', 'macro'] # Innovation affected by regulation, supply, macro
- }
-
- relevant_agents = agent_relationships.get(agent_name, [])
-
- for peer_agent in relevant_agents:
- if peer_agent in decisions:
- peer_decision = decisions[peer_agent]
- insight_summary = f"{peer_decision.direction} signal ({peer_decision.signal_strength:.2f} strength) - {peer_decision.key_insights[0] if peer_decision.key_insights else 'No specific insights'}"
- peer_insights[peer_agent] = insight_summary
-
- return peer_insights
-
- async def _refine_decision_with_peers(self, original_decision: AgentDecision,
- peer_insights: Dict[str, str]) -> AgentDecision:
- """Use Gemini AI to refine agent decision based on peer insights"""
- try:
- peer_summary = "\n".join([f"{agent}: {insight}" for agent, insight in peer_insights.items()])
-
- prompt = f"""
- As the {original_decision.agent_name} agent, refine your analysis considering peer agent insights:
-
- Your Original Analysis:
- - Signal: {original_decision.direction} ({original_decision.signal_strength:.2f} strength)
- - Confidence: {original_decision.confidence:.2f}
- - Key Insights: {', '.join(original_decision.key_insights)}
-
- Peer Agent Insights:
- {peer_summary}
-
- Considering these peer insights, should you:
- 1. Maintain your original assessment
- 2. Increase/decrease signal strength
- 3. Change direction
- 4. Adjust confidence level
-
- Provide response in JSON format:
- {{
- "action": "maintain/strengthen/weaken/reverse",
- "new_signal_strength": 0.0-1.0,
- "new_direction": "bullish/bearish/neutral",
- "new_confidence": 0.0-1.0,
- "reasoning": "Brief explanation",
- "key_factors": ["factor1", "factor2"]
- }}
- """
-
- response = self.gemini_model.generate_content(prompt)
- refinement = json.loads(response.text)
-
- # Update decision based on Gemini's analysis
- original_decision.signal_strength = refinement.get("new_signal_strength", original_decision.signal_strength)
- original_decision.direction = refinement.get("new_direction", original_decision.direction)
- original_decision.confidence = refinement.get("new_confidence", original_decision.confidence)
- original_decision.key_insights.append(f"Peer-refined: {refinement.get('reasoning', 'No reasoning')}")
-
- return original_decision
-
- except Exception as e:
- self.logger.error(f"Error refining decision with Gemini: {e}")
- return original_decision
-
- async def _generate_consensus_decision(self, decisions: Dict[str, AgentDecision],
- target_assets: List[str] = None) -> ConsensusDecision:
- """Generate final consensus decision using Gemini AI"""
- self.logger.info("🧠 Generating consensus decision with Gemini AI...")
-
- # Prepare decision summary
- decision_summary = self._prepare_decision_summary(decisions)
-
- prompt = f"""
- As a senior portfolio manager, analyze these AI agent insights and create a final investment decision:
-
- Agent Analysis Summary:
- {decision_summary}
-
- Agent Weights for Decision Making:
- {json.dumps(self.agent_weights, indent=2)}
-
- Target Assets: {target_assets or "Broad market exposure"}
-
- Generate a comprehensive investment decision with:
- 1. Overall signal (strong_buy/buy/hold/sell/strong_sell)
- 2. Conviction level (0-1)
- 3. Asset allocation percentages
- 4. Sector weight recommendations
- 5. Risk level assessment (0-1)
- 6. Key consensus factors
- 7. Main dissenting views
- 8. Execution priority (immediate/gradual/wait)
-
- Consider:
- - Agent reliability and track record
- - Signal consistency across agents
- - Risk-adjusted returns
- - Current market regime
- - Diversification principles
-
- Provide response in JSON format with all requested fields.
- """
-
- try:
- response = self.gemini_model.generate_content(prompt)
- consensus_data = json.loads(response.text)
-
- return ConsensusDecision(
- timestamp=datetime.now(),
- overall_signal=consensus_data.get("overall_signal", "hold"),
- conviction_level=consensus_data.get("conviction_level", 0.5),
- asset_allocation=consensus_data.get("asset_allocation", {"stocks": 0.6, "bonds": 0.4}),
- sector_weights=consensus_data.get("sector_weights", {}),
- risk_level=consensus_data.get("risk_level", 0.5),
- consensus_factors=consensus_data.get("consensus_factors", []),
- dissenting_views=consensus_data.get("dissenting_views", []),
- execution_priority=consensus_data.get("execution_priority", "gradual")
- )
-
- except Exception as e:
- self.logger.error(f"Error generating consensus with Gemini: {e}")
- return self._create_default_consensus(decisions)
-
- def _prepare_decision_summary(self, decisions: Dict[str, AgentDecision]) -> str:
- """Prepare summary of all agent decisions"""
- summary_lines = []
-
- for agent_name, decision in decisions.items():
- weight = self.agent_weights.get(agent_name, 0.0)
- summary_lines.append(
- f"{agent_name.upper()} (Weight: {weight:.1%}): "
- f"{decision.direction} signal, "
- f"Strength: {decision.signal_strength:.2f}, "
- f"Confidence: {decision.confidence:.2f}, "
- f"Horizon: {decision.time_horizon}, "
- f"Key: {decision.key_insights[0] if decision.key_insights else 'N/A'}"
- )
-
- return "\n".join(summary_lines)
-
- async def _validate_and_refine_decision(self, consensus: ConsensusDecision,
- decisions: Dict[str, AgentDecision]) -> ConsensusDecision:
- """Validate and refine the final decision"""
- self.logger.info("✅ Validating and refining final decision...")
-
- # Risk checks
- if consensus.risk_level > 0.8:
- self.logger.warning("⚠️ High risk level detected, adjusting position sizes...")
- # Reduce allocation to risky assets
- for asset in ["stocks", "growth", "emerging_markets"]:
- if asset in consensus.asset_allocation:
- consensus.asset_allocation[asset] *= 0.8
-
- # Consistency checks
- bullish_agents = len([d for d in decisions.values() if d.direction == "bullish"])
- bearish_agents = len([d for d in decisions.values() if d.direction == "bearish"])
-
- if abs(bullish_agents - bearish_agents) <= 1:
- self.logger.info("📊 Mixed signals detected, reducing conviction...")
- consensus.conviction_level *= 0.8
- consensus.execution_priority = "gradual"
-
- return consensus
-
- def _create_error_decision(self, agent_name: str, error_msg: str) -> AgentDecision:
- """Create default decision for failed agents"""
- return AgentDecision(
- agent_name=agent_name,
- timestamp=datetime.now(),
- signal_strength=0.0,
- direction="neutral",
- confidence=0.0,
- key_insights=[f"Error: {error_msg}"],
- market_implications={},
- time_horizon="unknown",
- raw_analysis={"error": error_msg}
- )
-
- def _create_default_consensus(self, decisions: Dict[str, AgentDecision]) -> ConsensusDecision:
- """Create default consensus when Gemini fails"""
- # Simple weighted average approach
- total_weighted_signal = 0.0
- total_weight = 0.0
-
- for agent_name, decision in decisions.items():
- weight = self.agent_weights.get(agent_name, 0.0)
- signal_value = decision.signal_strength * (
- 1 if decision.direction == "bullish" else -1 if decision.direction == "bearish" else 0)
- total_weighted_signal += signal_value * weight
- total_weight += weight
-
- avg_signal = total_weighted_signal / total_weight if total_weight > 0 else 0.0
-
- if avg_signal > 0.3:
- overall_signal = "buy"
- elif avg_signal < -0.3:
- overall_signal = "sell"
- else:
- overall_signal = "hold"
-
- return ConsensusDecision(
- timestamp=datetime.now(),
- overall_signal=overall_signal,
- conviction_level=abs(avg_signal),
- asset_allocation={"stocks": 0.6, "bonds": 0.3, "cash": 0.1},
- sector_weights={},
- risk_level=0.5,
- consensus_factors=["Default consensus due to system error"],
- dissenting_views=[],
- execution_priority="gradual"
- )
-
-
-async def run_hedge_fund_analysis(gemini_api_key: str, target_assets: List[str] = None):
- """Main function to run complete hedge fund analysis"""
- orchestrator = AgentOrchestrator(gemini_api_key)
-
- print("🏦 AI HEDGE FUND - MULTI-AGENT ANALYSIS")
- print("=" * 50)
-
- # Run comprehensive analysis
- decision = await orchestrator.run_comprehensive_analysis(target_assets)
-
- # Display results
- print(f"\n📈 FINAL INVESTMENT DECISION")
- print(f"Signal: {decision.overall_signal.upper()}")
- print(f"Conviction: {decision.conviction_level:.1%}")
- print(f"Risk Level: {decision.risk_level:.1%}")
- print(f"Execution: {decision.execution_priority}")
-
- print(f"\n💼 ASSET ALLOCATION:")
- for asset, weight in decision.asset_allocation.items():
- print(f" {asset.capitalize()}: {weight:.1%}")
-
- print(f"\n🔍 KEY CONSENSUS FACTORS:")
- for factor in decision.consensus_factors[:3]:
- print(f" • {factor}")
-
- if decision.dissenting_views:
- print(f"\n⚠️ DISSENTING VIEWS:")
- for view in decision.dissenting_views[:2]:
- print(f" • {view}")
-
- return decision
-
-
-# Example usage
-if __name__ == "__main__":
- import os
-
- # Set your Gemini API key
- GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "your-gemini-api-key-here")
-
- # Define target assets (optional)
- TARGET_ASSETS = ["SPY", "QQQ", "TLT", "GLD", "VXX"]
-
- # Run the analysis
- asyncio.run(run_hedge_fund_analysis(GEMINI_API_KEY, TARGET_ASSETS))
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/behavioral_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/behavioral_agent.py
deleted file mode 100644
index 08f64a49c..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/behavioral_agent.py
+++ /dev/null
@@ -1,337 +0,0 @@
-# -*- coding: utf-8 -*-
-# agents/behavioral_agent.py - Behavioral Finance Analysis Agent
-
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - market sentiment data
-# - behavioral indicators
-# - psychological market patterns
-#
-# OUTPUT:
-# - Behavioral finance signals
-# - Market sentiment analysis
-# - Anomaly detection results
-# - Behavioral pattern recognition
-#
-# PARAMETERS:
-# - sentiment_data_sources
-# - behavioral_models
-# - anomaly_thresholds
-# - psychological_indicators
-"""
-
-import asyncio
-import numpy as np
-from datetime import datetime, timedelta
-from typing import Dict, List, Optional
-import logging
-from dataclasses import dataclass
-import openai
-
-from config import CONFIG
-from data_feeds import DataFeedManager
-
-
-@dataclass
-class BehaviorSignal:
- """Behavioral finance signal"""
- behavior_type: str
- intensity: float # 0-1
- market_impact: str # bullish, bearish, neutral
- contrarian_opportunity: bool
- affected_assets: List[str]
- confidence: float
-
-
-class BehavioralAgent:
- """Behavioral finance analysis - crowd psychology and market inefficiencies"""
-
- def __init__(self):
- self.name = "behavioral"
- self.data_manager = DataFeedManager()
- self.client = openai.OpenAI(api_key=CONFIG.api.openai_api_key)
-
- self.behavioral_patterns = {
- "herd_behavior": {
- "indicators": ["consensus_trades", "crowded_positions", "momentum_chasing"],
- "contrarian_threshold": 0.7
- },
- "overconfidence": {
- "indicators": ["excessive_trading", "narrow_spreads", "low_volatility"],
- "contrarian_threshold": 0.6
- },
- "loss_aversion": {
- "indicators": ["selling_pressure", "defensive_positioning", "cash_hoarding"],
- "contrarian_threshold": 0.8
- },
- "anchoring": {
- "indicators": ["resistance_levels", "round_numbers", "historical_highs"],
- "contrarian_threshold": 0.5
- },
- "recency_bias": {
- "indicators": ["trend_extrapolation", "momentum_investing", "recent_news_focus"],
- "contrarian_threshold": 0.6
- }
- }
-
- self.market_psychology_indicators = {
- "fear": ["VIX", "put_call_ratio", "safe_haven_flows"],
- "greed": ["margin_debt", "IPO_activity", "speculative_trading"],
- "complacency": ["low_volatility", "compressed_spreads", "leverage_buildup"],
- "panic": ["forced_selling", "liquidity_crisis", "correlation_spike"]
- }
-
- async def analyze_behavioral_patterns(self) -> List[BehaviorSignal]:
- """Analyze behavioral finance patterns in markets"""
- signals = []
-
- for pattern, config in self.behavioral_patterns.items():
- try:
- signal = await self._analyze_behavioral_pattern(pattern, config)
- if signal:
- signals.append(signal)
- except Exception as e:
- logging.error(f"Error analyzing {pattern}: {e}")
- continue
-
- return signals
-
- async def _analyze_behavioral_pattern(self, pattern: str, config: Dict) -> Optional[BehaviorSignal]:
- """Analyze specific behavioral pattern"""
- # Simulate behavioral pattern analysis
- # In production, would analyze actual market data for these patterns
-
- # Generate realistic behavioral intensity
- base_intensity = np.random.uniform(0.2, 0.8)
-
- # Adjust based on pattern type
- pattern_adjustments = {
- "herd_behavior": np.random.normal(0.1, 0.2),
- "overconfidence": np.random.normal(-0.1, 0.15),
- "loss_aversion": np.random.normal(0.05, 0.25),
- "anchoring": np.random.normal(0, 0.1),
- "recency_bias": np.random.normal(0.08, 0.18)
- }
-
- intensity = np.clip(base_intensity + pattern_adjustments.get(pattern, 0), 0, 1)
-
- # Determine market impact
- if pattern in ["herd_behavior", "overconfidence", "recency_bias"]:
- if intensity > 0.6:
- market_impact = "bearish" # Contrarian signal
- else:
- market_impact = "bullish"
- elif pattern == "loss_aversion":
- market_impact = "bullish" if intensity > 0.6 else "bearish"
- else:
- market_impact = "neutral"
-
- # Check for contrarian opportunity
- contrarian_opportunity = intensity > config["contrarian_threshold"]
-
- # Determine affected assets
- affected_assets = self._get_affected_assets(pattern, intensity)
-
- return BehaviorSignal(
- behavior_type=pattern,
- intensity=intensity,
- market_impact=market_impact,
- contrarian_opportunity=contrarian_opportunity,
- affected_assets=affected_assets,
- confidence=0.5 + intensity * 0.3 # Higher intensity = higher confidence
- )
-
- def _get_affected_assets(self, pattern: str, intensity: float) -> List[str]:
- """Determine which assets are affected by behavioral pattern"""
- if pattern == "herd_behavior":
- if intensity > 0.7:
- return ["momentum_stocks", "growth_stocks", "crypto"]
- else:
- return ["broad_market"]
- elif pattern == "overconfidence":
- return ["individual_stocks", "options", "leveraged_products"]
- elif pattern == "loss_aversion":
- return ["defensive_stocks", "bonds", "gold", "utilities"]
- elif pattern == "anchoring":
- return ["stocks_near_highs", "round_number_levels"]
- elif pattern == "recency_bias":
- return ["trending_sectors", "recent_winners"]
- else:
- return ["broad_market"]
-
- async def analyze_market_psychology(self) -> Dict[str, float]:
- """Analyze overall market psychology"""
- psychology_scores = {}
-
- for emotion, indicators in self.market_psychology_indicators.items():
- # Simulate psychology analysis
- # In production, would analyze actual market indicators
- score = np.random.uniform(0.2, 0.8)
-
- # Add some correlation between emotions
- if emotion == "fear" and "greed" in psychology_scores:
- score = max(0.1, 1.0 - psychology_scores["greed"] + np.random.normal(0, 0.1))
- elif emotion == "greed" and "fear" in psychology_scores:
- score = max(0.1, 1.0 - psychology_scores["fear"] + np.random.normal(0, 0.1))
-
- psychology_scores[emotion] = np.clip(score, 0, 1)
-
- return psychology_scores
-
- def _detect_behavioral_anomalies(self, signals: List[BehaviorSignal]) -> List[str]:
- """Detect behavioral anomalies in the market"""
- anomalies = []
-
- # High intensity behavioral patterns
- high_intensity_patterns = [s for s in signals if s.intensity > 0.7]
- if len(high_intensity_patterns) >= 2:
- anomalies.append("multiple_behavioral_extremes")
-
- # Strong contrarian opportunities
- contrarian_signals = [s for s in signals if s.contrarian_opportunity]
- if len(contrarian_signals) >= 3:
- anomalies.append("multiple_contrarian_opportunities")
-
- # Conflicting behavioral signals
- bullish_signals = [s for s in signals if s.market_impact == "bullish"]
- bearish_signals = [s for s in signals if s.market_impact == "bearish"]
-
- if len(bullish_signals) > 0 and len(bearish_signals) > 0:
- if abs(len(bullish_signals) - len(bearish_signals)) <= 1:
- anomalies.append("conflicting_behavioral_signals")
-
- return anomalies
-
- async def get_behavioral_report(self) -> Dict:
- """Generate comprehensive behavioral finance report"""
- # Analyze behavioral patterns
- behavioral_signals = await self.analyze_behavioral_patterns()
-
- # Analyze market psychology
- psychology_scores = await self.analyze_market_psychology()
-
- # Detect anomalies
- anomalies = self._detect_behavioral_anomalies(behavioral_signals)
-
- # Calculate overall behavioral sentiment
- overall_sentiment = self._calculate_behavioral_sentiment(behavioral_signals, psychology_scores)
-
- return {
- "timestamp": datetime.now().isoformat(),
- "agent": self.name,
- "behavioral_analysis": {
- "overall_sentiment": overall_sentiment,
- "sentiment_classification": self._classify_sentiment(overall_sentiment),
- "behavioral_patterns": [{
- "pattern": signal.behavior_type,
- "intensity": signal.intensity,
- "market_impact": signal.market_impact,
- "contrarian_opportunity": signal.contrarian_opportunity,
- "affected_assets": signal.affected_assets,
- "confidence": signal.confidence
- } for signal in behavioral_signals],
- "market_psychology": psychology_scores,
- "behavioral_anomalies": anomalies
- },
- "trading_implications": {
- "contrarian_opportunities": [s.behavior_type for s in behavioral_signals
- if s.contrarian_opportunity],
- "behavioral_momentum": [s.behavior_type for s in behavioral_signals
- if s.intensity > 0.6 and not s.contrarian_opportunity],
- "risk_management": self._get_behavioral_risk_management(behavioral_signals),
- "position_sizing": self._get_behavioral_position_sizing(behavioral_signals)
- },
- "monitoring_priorities": {
- "extreme_behaviors": [s.behavior_type for s in behavioral_signals if s.intensity > 0.7],
- "contrarian_signals": [s.behavior_type for s in behavioral_signals if s.contrarian_opportunity],
- "psychology_extremes": [emotion for emotion, score in psychology_scores.items()
- if score > 0.7 or score < 0.3]
- }
- }
-
- def _calculate_behavioral_sentiment(self, signals: List[BehaviorSignal],
- psychology: Dict[str, float]) -> float:
- """Calculate overall behavioral sentiment"""
- if not signals and not psychology:
- return 0.0
-
- # Weight behavioral signals
- signal_sentiment = 0.0
- if signals:
- bullish_weight = sum(s.intensity for s in signals if s.market_impact == "bullish")
- bearish_weight = sum(s.intensity for s in signals if s.market_impact == "bearish")
- total_weight = bullish_weight + bearish_weight
-
- if total_weight > 0:
- signal_sentiment = (bullish_weight - bearish_weight) / total_weight
-
- # Weight psychology scores
- psychology_sentiment = 0.0
- if psychology:
- greed_score = psychology.get("greed", 0.5)
- fear_score = psychology.get("fear", 0.5)
- psychology_sentiment = greed_score - fear_score
-
- # Combine (60% signals, 40% psychology)
- if signals and psychology:
- combined_sentiment = 0.6 * signal_sentiment + 0.4 * psychology_sentiment
- elif signals:
- combined_sentiment = signal_sentiment
- elif psychology:
- combined_sentiment = psychology_sentiment
- else:
- combined_sentiment = 0.0
-
- return np.clip(combined_sentiment, -1.0, 1.0)
-
- def _classify_sentiment(self, sentiment: float) -> str:
- """Classify behavioral sentiment"""
- if sentiment > 0.4:
- return "behavioral_euphoria"
- elif sentiment > 0.1:
- return "behavioral_optimism"
- elif sentiment > -0.1:
- return "behavioral_neutral"
- elif sentiment > -0.4:
- return "behavioral_pessimism"
- else:
- return "behavioral_despair"
-
- def _get_behavioral_risk_management(self, signals: List[BehaviorSignal]) -> List[str]:
- """Get behavioral risk management recommendations"""
- recommendations = []
-
- # Check for high-intensity patterns
- high_intensity = [s for s in signals if s.intensity > 0.7]
- if high_intensity:
- recommendations.append("Monitor for behavioral reversals")
- recommendations.append("Consider reducing position sizes")
-
- # Check for herd behavior
- herd_signals = [s for s in signals if s.behavior_type == "herd_behavior" and s.intensity > 0.6]
- if herd_signals:
- recommendations.append("Prepare for trend reversals")
- recommendations.append("Avoid momentum chasing")
-
- # Check for overconfidence
- overconfidence_signals = [s for s in signals if s.behavior_type == "overconfidence" and s.intensity > 0.5]
- if overconfidence_signals:
- recommendations.append("Increase due diligence")
- recommendations.append("Diversify more broadly")
-
- return recommendations or ["Standard behavioral risk monitoring"]
-
- def _get_behavioral_position_sizing(self, signals: List[BehaviorSignal]) -> str:
- """Get position sizing recommendation based on behavioral patterns"""
- contrarian_count = sum(1 for s in signals if s.contrarian_opportunity)
- high_intensity_count = sum(1 for s in signals if s.intensity > 0.7)
-
- if contrarian_count >= 2:
- return "reduce_size" # Multiple contrarian signals suggest caution
- elif high_intensity_count >= 2:
- return "reduce_size" # Multiple extreme behaviors suggest volatility
- elif contrarian_count == 1 and high_intensity_count == 0:
- return "increase_size" # Single contrarian opportunity with low extremes
- else:
- return "normal"
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/central_bank_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/central_bank_agent.py
deleted file mode 100644
index b5fd759a8..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/central_bank_agent.py
+++ /dev/null
@@ -1,770 +0,0 @@
-# -*- coding: utf-8 -*-
-# agents/central_bank_agent.py - Central Bank Policy Analysis Agent
-
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - central bank announcements
-# - monetary policy statements
-# - interest rate decisions
-# - economic indicators
-#
-# OUTPUT:
-# - Central bank policy signals
-# - Monetary policy stance analysis
-# - Interest rate forecasts
-# - Market impact assessments
-#
-# PARAMETERS:
-# - policy_indicators
-# - economic_data_sources
-# - central_bank_watchlist
-# - forecast_horizons
-"""
-
-import asyncio
-import numpy as np
-import pandas as pd
-from datetime import datetime, timedelta
-from typing import Dict, List, Optional, Tuple
-import logging
-from dataclasses import dataclass
-import openai
-import json
-import re
-from textblob import TextBlob
-
-from config import CONFIG
-from data_feeds import DataFeedManager, DataPoint
-
-
-@dataclass
-class PolicySignal:
- """Central bank policy signal structure"""
- bank: str
- policy_stance: str # dovish, neutral, hawkish
- rate_direction: str # cutting, holding, raising
- probability: float
- next_meeting_date: Optional[datetime]
- key_factors: List[str]
- market_impact: Dict[str, float]
- confidence: float
-
-
-class CentralBankAgent:
- """Advanced central bank policy analysis and prediction"""
-
- def __init__(self):
- self.name = "central_bank"
- self.data_manager = DataFeedManager()
- self.client = openai.OpenAI(api_key=CONFIG.api.openai_api_key)
-
- # Central bank meeting schedules (approximate)
- self.meeting_schedules = {
- "FED": [
- "2025-01-29", "2025-03-19", "2025-04-30", "2025-06-11",
- "2025-07-30", "2025-09-17", "2025-10-29", "2025-12-17"
- ],
- "ECB": [
- "2025-01-23", "2025-03-06", "2025-04-10", "2025-06-05",
- "2025-07-17", "2025-09-11", "2025-10-23", "2025-12-11"
- ],
- "BOJ": [
- "2025-01-23", "2025-03-19", "2025-04-28", "2025-06-14",
- "2025-07-31", "2025-09-20", "2025-10-31", "2025-12-19"
- ]
- }
-
- # Policy keywords and their sentiment weights
- self.policy_keywords = {
- "hawkish": {
- "aggressive", "tighten", "restrictive", "combat inflation",
- "rate hikes", "cooling", "overheating", "price pressures",
- "vigilant", "determined", "forceful", "anchor expectations"
- },
- "dovish": {
- "accommodate", "supportive", "gradual", "patient", "flexible",
- "employment", "growth", "stimulus", "easy", "cautious",
- "measured", "data dependent", "appropriate", "monitor"
- },
- "neutral": {
- "balanced", "assess", "evaluate", "conditions", "outlook",
- "appropriate", "meetings", "review", "consider", "analyze"
- }
- }
-
- # Economic indicators that influence policy
- self.policy_indicators = {
- "inflation": {
- "CPIAUCSL": 0.25, # CPI
- "CPILFESL": 0.25, # Core CPI
- "PCEPI": 0.20, # PCE Price Index
- "PCEPILFE": 0.20, # Core PCE
- "DFEDTARU": 0.10 # Fed Target Rate
- },
- "employment": {
- "UNRATE": 0.35, # Unemployment Rate
- "PAYEMS": 0.25, # Nonfarm Payrolls
- "AWHMAN": 0.15, # Average Weekly Hours
- "AHETPI": 0.25 # Average Hourly Earnings
- },
- "growth": {
- "GDPC1": 0.40, # Real GDP
- "INDPRO": 0.30, # Industrial Production
- "RSAFS": 0.30 # Retail Sales
- },
- "financial": {
- "GS10": 0.25, # 10-Year Treasury
- "GS2": 0.25, # 2-Year Treasury
- "VIXCLS": 0.20, # VIX
- "DEXUSEU": 0.15, # USD/EUR
- "DTWEXBGS": 0.15 # Trade Weighted USD
- }
- }
-
- # Market impact coefficients by asset class
- self.market_impact_coefficients = {
- "bonds": {
- "hawkish": -0.8, # Negative for bond prices
- "neutral": 0.0,
- "dovish": 0.6
- },
- "stocks": {
- "hawkish": -0.4, # Generally negative but less than bonds
- "neutral": 0.1,
- "dovish": 0.7
- },
- "dollar": {
- "hawkish": 0.9, # Strong positive for USD
- "neutral": 0.0,
- "dovish": -0.6
- },
- "gold": {
- "hawkish": -0.7, # Negative for gold
- "neutral": 0.0,
- "dovish": 0.5
- }
- }
-
- async def analyze_fed_policy(self) -> PolicySignal:
- """Comprehensive Federal Reserve policy analysis"""
- try:
- # Fetch economic indicators
- economic_data = await self._fetch_policy_indicators()
-
- # Get recent Fed communications
- fed_communications = await self._fetch_fed_communications()
-
- # Analyze policy stance from data
- data_stance = self._analyze_data_driven_stance(economic_data)
-
- # Analyze communications sentiment
- comm_stance = self._analyze_communication_sentiment(fed_communications)
-
- # Combine signals with weights
- combined_stance = self._combine_policy_signals(data_stance, comm_stance)
-
- # Predict rate direction
- rate_direction, probability = self._predict_rate_direction(economic_data, combined_stance)
-
- # Get next meeting date
- next_meeting = self._get_next_meeting_date("FED")
-
- # Calculate market impact
- market_impact = self._calculate_market_impact(combined_stance, rate_direction)
-
- # Generate LLM analysis
- llm_analysis = await self._generate_policy_analysis(economic_data, fed_communications, combined_stance)
-
- return PolicySignal(
- bank="FED",
- policy_stance=combined_stance["stance"],
- rate_direction=rate_direction,
- probability=probability,
- next_meeting_date=next_meeting,
- key_factors=llm_analysis.get("key_factors", []),
- market_impact=market_impact,
- confidence=combined_stance["confidence"]
- )
-
- except Exception as e:
- logging.error(f"Error in Fed policy analysis: {e}")
- return self._default_policy_signal("FED")
-
- async def _fetch_policy_indicators(self) -> Dict[str, pd.Series]:
- """Fetch economic indicators relevant to monetary policy"""
- data_requests = {}
-
- # Collect all indicators
- all_indicators = set()
- for category in self.policy_indicators.values():
- all_indicators.update(category.keys())
-
- # Create requests
- for indicator in all_indicators:
- data_requests[indicator] = {
- "series_id": indicator,
- "limit": 60 # 5 years of monthly data
- }
-
- try:
- raw_data = await self.data_manager.get_multi_source_data({
- "economic": data_requests
- })
-
- # Process into time series
- processed_data = {}
- economic_data = raw_data.get("economic", {})
-
- for key, data_points in economic_data.items():
- if data_points and len(data_points) > 0:
- # Create DataFrame from data points
- df_data = []
- for dp in data_points:
- df_data.append({
- 'date': dp.timestamp,
- 'value': dp.value
- })
-
- if df_data:
- df = pd.DataFrame(df_data)
- df['date'] = pd.to_datetime(df['date'])
- df = df.sort_values('date').set_index('date')
- processed_data[key] = df['value']
-
- return processed_data
-
- except Exception as e:
- logging.error(f"Error fetching policy indicators: {e}")
- return {}
-
- async def _fetch_fed_communications(self) -> List[DataPoint]:
- """Fetch recent Federal Reserve communications and speeches"""
- keywords = ["federal reserve", "jerome powell", "fed policy", "interest rates", "monetary policy"]
-
- communications = []
- try:
- for keyword in keywords:
- news_data = await self.data_manager.get_multi_source_data({
- "news": {
- "query": keyword,
- "sources": ["reuters", "bloomberg", "wsj"],
- "hours_back": 168 # 1 week
- }
- })
-
- if "news" in news_data and news_data["news"]:
- communications.extend(news_data["news"])
-
- # Filter for actual Fed communications
- fed_communications = []
- for comm in communications:
- if any(term in comm.value.lower() for term in ["fed", "federal reserve", "powell", "fomc"]):
- fed_communications.append(comm)
-
- return fed_communications
-
- except Exception as e:
- logging.error(f"Error fetching Fed communications: {e}")
- return []
-
- def _analyze_data_driven_stance(self, data: Dict[str, pd.Series]) -> Dict:
- """Analyze policy stance based on economic data"""
- stance_scores = []
- confidence_factors = []
-
- try:
- # Inflation analysis
- inflation_score = self._analyze_inflation_pressure(data)
- stance_scores.append(inflation_score * 0.4) # 40% weight
- confidence_factors.append(0.9 if inflation_score != 0 else 0.3)
-
- # Employment analysis
- employment_score = self._analyze_employment_conditions(data)
- stance_scores.append(employment_score * 0.3) # 30% weight
- confidence_factors.append(0.8 if employment_score != 0 else 0.3)
-
- # Growth analysis
- growth_score = self._analyze_growth_momentum(data)
- stance_scores.append(growth_score * 0.2) # 20% weight
- confidence_factors.append(0.7 if growth_score != 0 else 0.3)
-
- # Financial conditions
- financial_score = self._analyze_financial_conditions(data)
- stance_scores.append(financial_score * 0.1) # 10% weight
- confidence_factors.append(0.6 if financial_score != 0 else 0.3)
-
- # Calculate overall stance
- overall_score = np.sum(stance_scores)
- confidence = np.mean(confidence_factors)
-
- if overall_score > 0.3:
- stance = "hawkish"
- elif overall_score < -0.3:
- stance = "dovish"
- else:
- stance = "neutral"
-
- return {
- "stance": stance,
- "score": overall_score,
- "confidence": confidence,
- "components": {
- "inflation": inflation_score,
- "employment": employment_score,
- "growth": growth_score,
- "financial": financial_score
- }
- }
-
- except Exception as e:
- logging.error(f"Error in data-driven stance analysis: {e}")
- return {"stance": "neutral", "score": 0.0, "confidence": 0.3, "components": {}}
-
- def _analyze_inflation_pressure(self, data: Dict[str, pd.Series]) -> float:
- """Analyze inflation pressure for policy implications"""
- inflation_indicators = self.policy_indicators["inflation"]
- scores = []
-
- for indicator, weight in inflation_indicators.items():
- if indicator in data and not data[indicator].empty and len(data[indicator]) >= 12:
- series = data[indicator]
-
- # Calculate year-over-year change
- yoy_change = series.pct_change(12).iloc[-1] * 100
-
- # Fed target is typically around 2%
- if indicator in ["CPIAUCSL", "CPILFESL", "PCEPI", "PCEPILFE"]:
- if yoy_change > 3.0:
- score = 1.0 # Strong hawkish signal
- elif yoy_change > 2.5:
- score = 0.5 # Moderate hawkish
- elif yoy_change < 1.5:
- score = -0.5 # Moderate dovish
- elif yoy_change < 1.0:
- score = -1.0 # Strong dovish
- else:
- score = 0.0 # Neutral
- else:
- score = 0.0
-
- scores.append(score * weight)
-
- return np.sum(scores) if scores else 0.0
-
- def _analyze_employment_conditions(self, data: Dict[str, pd.Series]) -> float:
- """Analyze employment conditions for policy implications"""
- employment_indicators = self.policy_indicators["employment"]
- scores = []
-
- for indicator, weight in employment_indicators.items():
- if indicator in data and not data[indicator].empty:
- series = data[indicator]
-
- if indicator == "UNRATE":
- current_rate = series.iloc[-1]
- if current_rate < 3.5:
- score = 1.0 # Very tight labor market - hawkish
- elif current_rate < 4.0:
- score = 0.5 # Tight labor market
- elif current_rate > 5.5:
- score = -0.5 # Loose labor market - dovish
- elif current_rate > 6.5:
- score = -1.0 # Very loose labor market
- else:
- score = 0.0
- elif indicator == "PAYEMS":
- # Payroll growth
- if len(series) >= 3:
- avg_growth = series.pct_change().iloc[-3:].mean() * 100
- if avg_growth > 0.4: # >400k jobs/month
- score = 0.5 # Strong growth - slightly hawkish
- elif avg_growth < 0.1: # <100k jobs/month
- score = -0.5 # Weak growth - dovish
- else:
- score = 0.0
- else:
- score = 0.0
- else:
- score = 0.0
-
- scores.append(score * weight)
-
- return np.sum(scores) if scores else 0.0
-
- def _analyze_growth_momentum(self, data: Dict[str, pd.Series]) -> float:
- """Analyze economic growth momentum"""
- growth_indicators = self.policy_indicators["growth"]
- scores = []
-
- for indicator, weight in growth_indicators.items():
- if indicator in data and not data[indicator].empty and len(data[indicator]) >= 4:
- series = data[indicator]
-
- # Calculate quarterly growth rate
- quarterly_growth = series.pct_change(3).iloc[-1] * 100
-
- if indicator == "GDPC1":
- if quarterly_growth > 3.0:
- score = 0.5 # Strong growth - slightly hawkish
- elif quarterly_growth < 1.0:
- score = -0.5 # Weak growth - dovish
- elif quarterly_growth < 0:
- score = -1.0 # Contraction - very dovish
- else:
- score = 0.0
- else:
- # For other indicators, use similar logic
- if quarterly_growth > 2.0:
- score = 0.3
- elif quarterly_growth < 0:
- score = -0.5
- else:
- score = 0.0
-
- scores.append(score * weight)
-
- return np.sum(scores) if scores else 0.0
-
- def _analyze_financial_conditions(self, data: Dict[str, pd.Series]) -> float:
- """Analyze financial market conditions"""
- financial_indicators = self.policy_indicators["financial"]
- scores = []
-
- for indicator, weight in financial_indicators.items():
- if indicator in data and not data[indicator].empty:
- series = data[indicator]
-
- if indicator == "GS10":
- # 10-year treasury yield
- current_yield = series.iloc[-1]
- if current_yield > 5.0:
- score = 0.5 # High yields - less need for tightening
- elif current_yield < 3.0:
- score = -0.3 # Low yields - room for accommodation
- else:
- score = 0.0
- elif indicator == "VIXCLS":
- # VIX volatility index
- current_vix = series.iloc[-1]
- if current_vix > 30:
- score = -0.8 # High volatility - dovish signal
- elif current_vix < 15:
- score = 0.3 # Low volatility - can be hawkish
- else:
- score = 0.0
- else:
- score = 0.0
-
- scores.append(score * weight)
-
- return np.sum(scores) if scores else 0.0
-
- def _analyze_communication_sentiment(self, communications: List[DataPoint]) -> Dict:
- """Analyze sentiment from Fed communications"""
- if not communications:
- return {"stance": "neutral", "confidence": 0.2, "score": 0.0}
-
- stance_scores = []
- confidence_scores = []
-
- for comm in communications:
- text = comm.value.lower()
-
- # Count keyword occurrences
- hawkish_count = sum(1 for keyword in self.policy_keywords["hawkish"] if keyword in text)
- dovish_count = sum(1 for keyword in self.policy_keywords["dovish"] if keyword in text)
- neutral_count = sum(1 for keyword in self.policy_keywords["neutral"] if keyword in text)
-
- total_keywords = hawkish_count + dovish_count + neutral_count
-
- if total_keywords > 0:
- # Calculate sentiment score
- sentiment_score = (hawkish_count - dovish_count) / total_keywords
- stance_scores.append(sentiment_score * comm.confidence)
- confidence_scores.append(comm.confidence)
-
- if not stance_scores:
- return {"stance": "neutral", "confidence": 0.2, "score": 0.0}
-
- # Weight by confidence and recency
- weighted_score = np.average(stance_scores, weights=confidence_scores)
- avg_confidence = np.mean(confidence_scores)
-
- if weighted_score > 0.2:
- stance = "hawkish"
- elif weighted_score < -0.2:
- stance = "dovish"
- else:
- stance = "neutral"
-
- return {
- "stance": stance,
- "confidence": avg_confidence,
- "score": weighted_score
- }
-
- def _combine_policy_signals(self, data_stance: Dict, comm_stance: Dict) -> Dict:
- """Combine data-driven and communication-based policy signals"""
- # Weight data more heavily than communications
- data_weight = 0.7
- comm_weight = 0.3
-
- combined_score = (data_stance["score"] * data_weight +
- comm_stance["score"] * comm_weight)
-
- combined_confidence = (data_stance["confidence"] * data_weight +
- comm_stance["confidence"] * comm_weight)
-
- if combined_score > 0.25:
- stance = "hawkish"
- elif combined_score < -0.25:
- stance = "dovish"
- else:
- stance = "neutral"
-
- return {
- "stance": stance,
- "score": combined_score,
- "confidence": combined_confidence,
- "data_component": data_stance,
- "communication_component": comm_stance
- }
-
- def _predict_rate_direction(self, data: Dict[str, pd.Series], stance: Dict) -> Tuple[str, float]:
- """Predict rate direction and probability"""
- current_rate = 5.25 # Approximate current fed funds rate
-
- # Get current inflation and unemployment
- current_inflation = 0.0
- current_unemployment = 0.0
-
- if "CPIAUCSL" in data and not data["CPIAUCSL"].empty and len(data["CPIAUCSL"]) >= 12:
- current_inflation = data["CPIAUCSL"].pct_change(12).iloc[-1] * 100
-
- if "UNRATE" in data and not data["UNRATE"].empty:
- current_unemployment = data["UNRATE"].iloc[-1]
-
- # Decision logic based on dual mandate
- if stance["stance"] == "hawkish":
- if current_inflation > 3.0 or current_unemployment < 3.5:
- direction = "raising"
- probability = 0.75 + stance["confidence"] * 0.2
- else:
- direction = "holding"
- probability = 0.60 + stance["confidence"] * 0.15
- elif stance["stance"] == "dovish":
- if current_inflation < 1.5 or current_unemployment > 5.0:
- direction = "cutting"
- probability = 0.70 + stance["confidence"] * 0.2
- else:
- direction = "holding"
- probability = 0.55 + stance["confidence"] * 0.15
- else:
- direction = "holding"
- probability = 0.65 + stance["confidence"] * 0.1
-
- # Adjust for current rate level
- if current_rate > 6.0 and direction == "raising":
- probability *= 0.8 # Less likely to raise from high levels
- elif current_rate < 2.0 and direction == "cutting":
- probability *= 0.7 # Less room to cut from low levels
-
- return direction, min(probability, 0.95)
-
- def _get_next_meeting_date(self, bank: str) -> Optional[datetime]:
- """Get next central bank meeting date"""
- if bank not in self.meeting_schedules:
- return None
-
- today = datetime.now()
- try:
- meeting_dates = [datetime.strptime(date, "%Y-%m-%d") for date in self.meeting_schedules[bank]]
- future_meetings = [date for date in meeting_dates if date > today]
- return min(future_meetings) if future_meetings else None
- except Exception as e:
- logging.error(f"Error parsing meeting dates: {e}")
- return None
-
- def _calculate_market_impact(self, stance: Dict, rate_direction: str) -> Dict[str, float]:
- """Calculate expected market impact of policy stance"""
- stance_name = stance["stance"]
- impact_strength = abs(stance["score"]) * stance["confidence"]
-
- market_impacts = {}
-
- for asset_class, coefficients in self.market_impact_coefficients.items():
- base_impact = coefficients[stance_name]
-
- # Adjust for rate direction
- if rate_direction == "raising" and stance_name == "hawkish":
- base_impact *= 1.2
- elif rate_direction == "cutting" and stance_name == "dovish":
- base_impact *= 1.2
-
- # Scale by impact strength
- final_impact = base_impact * impact_strength
- market_impacts[asset_class] = np.clip(final_impact, -1.0, 1.0)
-
- return market_impacts
-
- async def _generate_policy_analysis(self, data: Dict[str, pd.Series],
- communications: List[DataPoint],
- stance: Dict) -> Dict:
- """Generate LLM-enhanced policy analysis"""
- try:
- # Prepare data summary
- data_summary = self._prepare_policy_data_summary(data)
- comm_summary = self._prepare_communication_summary(communications)
-
- prompt = f"""
- As a Federal Reserve policy expert, analyze the current monetary policy outlook.
-
- Current Policy Stance: {stance["stance"]} (confidence: {stance["confidence"]:.2f})
-
- Economic Data Summary:
- {data_summary}
-
- Recent Fed Communications:
- {comm_summary}
-
- Please provide:
- 1. Key factors driving current policy stance
- 2. Most important risks to monitor
- 3. Probability of policy error (too tight/loose)
- 4. Market positioning recommendations
- 5. Timeline for next major policy shift
-
- Format as JSON with keys: key_factors, risks, policy_error_risk, market_recommendations, timeline
- """
-
- response = self.client.chat.completions.create(
- model=CONFIG.llm.deep_think_model,
- messages=[{"role": "user", "content": prompt}],
- temperature=CONFIG.llm.temperature,
- max_tokens=CONFIG.llm.max_tokens
- )
-
- return json.loads(response.choices[0].message.content)
-
- except Exception as e:
- logging.error(f"Error in LLM policy analysis: {e}")
- return {
- "key_factors": ["Inflation trends", "Employment conditions"],
- "risks": ["Policy lag effects", "Market volatility"],
- "policy_error_risk": 0.3,
- "market_recommendations": "Maintain balanced positioning",
- "timeline": "Next 3-6 months"
- }
-
- def _prepare_policy_data_summary(self, data: Dict[str, pd.Series]) -> str:
- """Prepare policy-relevant data summary"""
- summary_lines = []
-
- # Key indicators for Fed policy
- key_indicators = {
- "CPIAUCSL": "Core Inflation",
- "UNRATE": "Unemployment Rate",
- "PAYEMS": "Job Growth",
- "GDPC1": "GDP Growth",
- "GS10": "10Y Treasury Yield"
- }
-
- for indicator, name in key_indicators.items():
- if indicator in data and not data[indicator].empty:
- latest = data[indicator].iloc[-1]
-
- if indicator in ["CPIAUCSL"] and len(data[indicator]) >= 12:
- yoy_change = data[indicator].pct_change(12).iloc[-1] * 100
- summary_lines.append(f"{name}: {yoy_change:.1f}% YoY")
- elif indicator == "PAYEMS" and len(data[indicator]) >= 1:
- monthly_change = data[indicator].diff().iloc[-1]
- summary_lines.append(f"{name}: {monthly_change:.0f}k (monthly)")
- else:
- summary_lines.append(f"{name}: {latest:.2f}")
-
- return "\n".join(summary_lines)
-
- def _prepare_communication_summary(self, communications: List[DataPoint]) -> str:
- """Prepare Fed communications summary"""
- if not communications:
- return "No recent Fed communications available"
-
- # Get most recent and relevant communications
- recent_comms = sorted(communications, key=lambda x: x.timestamp, reverse=True)[:5]
-
- summary_lines = []
- for comm in recent_comms:
- date_str = comm.timestamp.strftime("%Y-%m-%d")
- title = comm.value[:100] + "..." if len(comm.value) > 100 else comm.value
- summary_lines.append(f"{date_str}: {title}")
-
- return "\n".join(summary_lines)
-
- def _default_policy_signal(self, bank: str) -> PolicySignal:
- """Return default policy signal in case of errors"""
- return PolicySignal(
- bank=bank,
- policy_stance="neutral",
- rate_direction="holding",
- probability=0.5,
- next_meeting_date=self._get_next_meeting_date(bank),
- key_factors=["Data dependency", "Inflation monitoring"],
- market_impact={
- "bonds": 0.0,
- "stocks": 0.0,
- "dollar": 0.0,
- "gold": 0.0
- },
- confidence=0.3
- )
-
- async def get_policy_report(self) -> Dict:
- """Generate comprehensive central bank policy report"""
- fed_signal = await self.analyze_fed_policy()
-
- return {
- "timestamp": datetime.now().isoformat(),
- "agent": self.name,
- "fed_analysis": {
- "policy_stance": fed_signal.policy_stance,
- "rate_direction": fed_signal.rate_direction,
- "probability": fed_signal.probability,
- "confidence": fed_signal.confidence,
- "next_meeting": fed_signal.next_meeting_date.isoformat() if fed_signal.next_meeting_date else None,
- "key_factors": fed_signal.key_factors
- },
- "market_impact": fed_signal.market_impact,
- "trading_implications": {
- "duration_positioning": "short" if fed_signal.policy_stance == "hawkish" else "long",
- "sector_rotation": self._get_sector_implications(fed_signal),
- "currency_bias": "bullish_usd" if fed_signal.policy_stance == "hawkish" else "bearish_usd"
- },
- "risk_factors": {
- "policy_uncertainty": 1 - fed_signal.confidence,
- "communication_risk": 0.3,
- "market_reaction_risk": 0.4
- }
- }
-
- def _get_sector_implications(self, signal: PolicySignal) -> Dict[str, str]:
- """Get sector rotation implications from policy stance"""
- if signal.policy_stance == "hawkish":
- return {
- "financials": "bullish", # Higher rates benefit banks
- "technology": "bearish", # Higher discount rates hurt growth stocks
- "utilities": "bearish", # Rate-sensitive sector
- "real_estate": "bearish" # REITs hurt by higher rates
- }
- elif signal.policy_stance == "dovish":
- return {
- "technology": "bullish", # Lower rates help growth stocks
- "real_estate": "bullish", # REITs benefit from lower rates
- "utilities": "bullish", # Rate-sensitive sectors benefit
- "financials": "bearish" # Lower rates hurt bank margins
- }
- else:
- return {
- "balanced": "neutral",
- "defensive": "slight_overweight"
- }
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/config.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/config.py
deleted file mode 100644
index 75fc88cb8..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/config.py
+++ /dev/null
@@ -1,183 +0,0 @@
-# -*- coding: utf-8 -*-
-# config.py - Production Configuration for AI Hedge Fund System
-
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - ticker symbols (array)
-# - end_date (string)
-# - FINANCIAL_DATASETS_API_KEY
-#
-# OUTPUT:
-# - Financial metrics: ROE, D/E, Current Ratio
-# - Financial line items: Revenue, Net Income, FCF, Debt, Equity, Retained Earnings, Operating Margin, R&D, Shares
-# - Market Cap
-#
-# PARAMETERS:
-# - period="annual"
-# - limit=10 years
-"""
-
-import os
-from dataclasses import dataclass
-from typing import Dict, List, Optional
-import logging
-from pathlib import Path
-
-
-@dataclass
-class APIConfig:
- """API Configuration for external services"""
- openai_api_key: str = os.getenv("OPENAI_API_KEY", "")
- anthropic_api_key: str = os.getenv("ANTHROPIC_API_KEY", "")
- finnhub_api_key: str = os.getenv("FINNHUB_API_KEY", "")
- alpha_vantage_key: str = os.getenv("ALPHA_VANTAGE_API_KEY", "")
- fred_api_key: str = os.getenv("FRED_API_KEY", "")
- newsapi_key: str = os.getenv("NEWS_API_KEY", "")
- twitter_bearer_token: str = os.getenv("TWITTER_BEARER_TOKEN", "")
- reddit_client_id: str = os.getenv("REDDIT_CLIENT_ID", "")
- reddit_client_secret: str = os.getenv("REDDIT_CLIENT_SECRET", "")
- polygon_api_key: str = os.getenv("POLYGON_API_KEY", "")
-
-
-@dataclass
-class LLMConfig:
- """LLM Configuration for different thinking modes"""
- deep_think_model: str = "gpt-4o"
- quick_think_model: str = "gpt-4o-mini"
- temperature: float = 0.1
- max_tokens: int = 4000
- timeout: int = 30
- max_retries: int = 3
-
-
-@dataclass
-class AgentConfig:
- """Individual agent configuration"""
- confidence_threshold: float = 0.7
- update_frequency: int = 300 # seconds
- data_lookback_days: int = 30
- max_api_calls_per_hour: int = 100
- enable_caching: bool = True
- cache_ttl: int = 1800 # 30 minutes
-
-
-@dataclass
-class RiskConfig:
- """Risk management parameters"""
- max_position_size: float = 0.05 # 5% max per position
- max_sector_exposure: float = 0.25 # 25% max per sector
- max_country_exposure: float = 0.40 # 40% max per country
- stop_loss_threshold: float = 0.02 # 2% stop loss
- var_limit: float = 0.03 # 3% daily VaR limit
- correlation_limit: float = 0.8 # Max correlation between positions
-
-
-@dataclass
-class TradingConfig:
- """Trading execution parameters"""
- min_trade_size: float = 1000.0 # Minimum trade size USD
- max_trade_size: float = 1000000.0 # Maximum trade size USD
- slippage_assumption: float = 0.001 # 10 bps slippage
- commission_rate: float = 0.0005 # 5 bps commission
- market_impact_threshold: float = 0.01 # 1% of daily volume
-
-
-class Config:
- """Main configuration class"""
-
- def __init__(self):
- self.api = APIConfig()
- self.llm = LLMConfig()
- self.agent = AgentConfig()
- self.risk = RiskConfig()
- self.trading = TradingConfig()
-
- # Logging configuration
- self.log_level = logging.INFO
- self.log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
-
- # Data storage paths
- self.data_dir = Path("data")
- self.cache_dir = Path("cache")
- self.logs_dir = Path("logs")
-
- # Create directories if they don't exist
- for directory in [self.data_dir, self.cache_dir, self.logs_dir]:
- directory.mkdir(exist_ok=True)
-
- # Agent weights for decision aggregation
- self.agent_weights = {
- "macro_cycle": 0.15,
- "central_bank": 0.20,
- "geopolitical": 0.18,
- "regulatory": 0.12,
- "sentiment": 0.10,
- "institutional_flow": 0.15,
- "supply_chain": 0.05,
- "innovation": 0.03,
- "currency": 0.02,
- "behavioral": 0.00
- }
-
- # Market hours and trading sessions
- self.trading_sessions = {
- "US": {"open": "09:30", "close": "16:00", "timezone": "America/New_York"},
- "EU": {"open": "08:00", "close": "16:30", "timezone": "Europe/London"},
- "ASIA": {"open": "09:00", "close": "15:00", "timezone": "Asia/Tokyo"}
- }
-
- # Asset class mappings
- self.asset_classes = {
- "equities": ["SPY", "QQQ", "IWM", "EFA", "EEM"],
- "bonds": ["TLT", "IEF", "SHY", "LQD", "HYG"],
- "commodities": ["GLD", "SLV", "USO", "UNG", "DBA"],
- "currencies": ["UUP", "FXE", "FXY", "FXB", "EWZ"],
- "volatility": ["VIX", "UVXY", "SVXY"]
- }
-
- # Economic indicators to monitor
- self.economic_indicators = [
- "GDP", "CPI", "PPI", "UNRATE", "FEDFUNDS", "DGS10", "DGS2",
- "DEXUSEU", "DEXCHUS", "DEXJPUS", "DEXUSUK", "CPIAUCSL",
- "PAYEMS", "INDPRO", "HOUST", "RSAFS", "UMCSENT"
- ]
-
- # News sources and their reliability scores
- self.news_sources = {
- "reuters": 0.95,
- "bloomberg": 0.95,
- "wsj": 0.90,
- "ft": 0.90,
- "cnbc": 0.75,
- "marketwatch": 0.70,
- "yahoo_finance": 0.65
- }
-
- def validate_config(self) -> bool:
- """Validate configuration settings"""
- required_keys = [
- self.api.openai_api_key,
- self.api.finnhub_api_key,
- self.api.fred_api_key
- ]
-
- if not all(required_keys):
- raise ValueError("Missing required API keys. Check environment variables.")
-
- if sum(self.agent_weights.values()) != 1.0:
- raise ValueError("Agent weights must sum to 1.0")
-
- return True
-
- def get_market_hours(self, market: str) -> Dict[str, str]:
- """Get trading hours for specific market"""
- return self.trading_sessions.get(market.upper(), {})
-
- def get_asset_universe(self, asset_class: str) -> List[str]:
- """Get tradeable assets for asset class"""
- return self.asset_classes.get(asset_class.lower(), [])
-
-
-# Global configuration instance
-CONFIG = Config()
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/currency_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/currency_agent.py
deleted file mode 100644
index 70750c1f1..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/currency_agent.py
+++ /dev/null
@@ -1,158 +0,0 @@
-# -*- coding: utf-8 -*-
-# agents/currency_agent.py - Foreign Exchange Analysis Agent
-
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - currency pairs
-# - forex market data
-# - interest rate differentials
-# - geopolitical events
-#
-# OUTPUT:
-# - Currency trading signals
-# - FX market analysis
-# - Exchange rate forecasts
-# - Currency pair recommendations
-#
-# PARAMETERS:
-# - currency_pairs
-# - timeframes
-# - technical_indicators
-# - fundamental_factors
-"""
-
-import asyncio
-import numpy as np
-from datetime import datetime
-from typing import Dict, List, Optional
-import logging
-from dataclasses import dataclass
-import openai
-
-from config import CONFIG
-from data_feeds import DataFeedManager
-
-
-@dataclass
-class CurrencySignal:
- """Currency trading signal"""
- currency_pair: str
- direction: str # long, short, neutral
- strength: float # 0-1
- time_horizon: str
- drivers: List[str]
- confidence: float
-
-
-class CurrencyAgent:
- """Foreign exchange analysis and currency trading signals"""
-
- def __init__(self):
- self.name = "currency"
- self.data_manager = DataFeedManager()
- self.client = openai.OpenAI(api_key=CONFIG.api.openai_api_key)
-
- self.major_pairs = ["EURUSD", "GBPUSD", "USDJPY", "USDCAD", "AUDUSD", "USDCHF"]
-
- self.currency_drivers = {
- "interest_rate_differential": 0.30,
- "economic_growth": 0.25,
- "political_stability": 0.20,
- "trade_balance": 0.15,
- "risk_sentiment": 0.10
- }
-
- async def analyze_currency_trends(self) -> List[CurrencySignal]:
- """Analyze major currency trends"""
- signals = []
-
- for pair in self.major_pairs:
- try:
- signal = await self._analyze_currency_pair(pair)
- if signal:
- signals.append(signal)
- except Exception as e:
- logging.error(f"Error analyzing {pair}: {e}")
- continue
-
- return signals
-
- async def _analyze_currency_pair(self, pair: str) -> Optional[CurrencySignal]:
- """Analyze specific currency pair"""
- # Simulate currency analysis
- base_currency = pair[:3]
- quote_currency = pair[3:]
-
- # Simulate various factors
- rate_differential = np.random.normal(0, 0.5)
- economic_growth_diff = np.random.normal(0, 0.3)
- political_stability = np.random.uniform(-0.5, 0.5)
-
- # Combine factors
- signal_strength = (rate_differential * 0.4 +
- economic_growth_diff * 0.4 +
- political_stability * 0.2)
-
- if signal_strength > 0.2:
- direction = "long"
- strength = min(signal_strength, 1.0)
- elif signal_strength < -0.2:
- direction = "short"
- strength = min(abs(signal_strength), 1.0)
- else:
- direction = "neutral"
- strength = 0.1
-
- drivers = ["interest_rates", "economic_data"]
- if abs(political_stability) > 0.3:
- drivers.append("political_events")
-
- return CurrencySignal(
- currency_pair=pair,
- direction=direction,
- strength=strength,
- time_horizon="medium",
- drivers=drivers,
- confidence=0.6
- )
-
- async def get_currency_report(self) -> Dict:
- """Generate currency analysis report"""
- signals = await self.analyze_currency_trends()
-
- return {
- "timestamp": datetime.now().isoformat(),
- "agent": self.name,
- "currency_analysis": {
- "usd_outlook": self._assess_usd_outlook(signals),
- "currency_signals": [{
- "pair": signal.currency_pair,
- "direction": signal.direction,
- "strength": signal.strength,
- "time_horizon": signal.time_horizon,
- "key_drivers": signal.drivers,
- "confidence": signal.confidence
- } for signal in signals],
- "strongest_signals": [s.currency_pair for s in signals
- if s.strength > 0.6 and s.direction != "neutral"]
- }
- }
-
- def _assess_usd_outlook(self, signals: List[CurrencySignal]) -> str:
- """Assess overall USD outlook from currency signals"""
- usd_signals = [s for s in signals if "USD" in s.currency_pair]
-
- if not usd_signals:
- return "neutral"
-
- bullish_count = sum(1 for s in usd_signals
- if (s.currency_pair.startswith("USD") and s.direction == "long") or
- (s.currency_pair.endswith("USD") and s.direction == "short"))
-
- if bullish_count > len(usd_signals) * 0.6:
- return "bullish"
- elif bullish_count < len(usd_signals) * 0.4:
- return "bearish"
- else:
- return "neutral"
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/data_feeds.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/data_feeds.py
deleted file mode 100644
index bcd5282e4..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/data_feeds.py
+++ /dev/null
@@ -1,495 +0,0 @@
-# -*- coding: utf-8 -*-
-# data_feeds.py - Production Data Sources and Feed Management
-
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - ticker symbols (array)
-# - end_date (string)
-# - FINANCIAL_DATASETS_API_KEY
-#
-# OUTPUT:
-# - Financial metrics: ROE, D/E, Current Ratio
-# - Financial line items: Revenue, Net Income, FCF, Debt, Equity, Retained Earnings, Operating Margin, R&D, Shares
-# - Market Cap
-#
-# PARAMETERS:
-# - period="annual"
-# - limit=10 years
-"""
-
-import asyncio
-import aiohttp
-import pandas as pd
-import numpy as np
-from datetime import datetime, timedelta
-from typing import Dict, List, Optional, Any, Union
-import json
-import logging
-from dataclasses import dataclass
-import redis
-from config import CONFIG
-import time
-import hashlib
-
-
-@dataclass
-class DataPoint:
- """Standardized data point structure"""
- timestamp: datetime
- source: str
- data_type: str
- value: Union[float, str, Dict]
- confidence: float
- metadata: Dict[str, Any]
-
-
-class DataCache:
- """Redis-based caching for data feeds"""
-
- def __init__(self):
- self.redis_client = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
- self.default_ttl = CONFIG.agent.cache_ttl
-
- def get(self, key: str) -> Optional[Any]:
- """Get cached data"""
- try:
- data = self.redis_client.get(key)
- return json.loads(data) if data else None
- except Exception:
- return None
-
- def set(self, key: str, value: Any, ttl: Optional[int] = None) -> bool:
- """Set cached data"""
- try:
- ttl = ttl or self.default_ttl
- return self.redis_client.setex(key, ttl, json.dumps(value, default=str))
- except Exception:
- return False
-
- def generate_key(self, source: str, params: Dict) -> str:
- """Generate cache key from parameters"""
- param_str = json.dumps(params, sort_keys=True)
- return f"{source}:{hashlib.md5(param_str.encode()).hexdigest()}"
-
-
-class EconomicDataFeed:
- """Federal Reserve Economic Data (FRED) API integration"""
-
- def __init__(self):
- self.base_url = "https://api.stlouisfed.org/fred"
- self.api_key = CONFIG.api.fred_api_key
- self.cache = DataCache()
- self.session = None
-
- async def __aenter__(self):
- self.session = aiohttp.ClientSession()
- return self
-
- async def __aexit__(self, exc_type, exc_val, exc_tb):
- if self.session:
- await self.session.close()
-
- async def get_series(self, series_id: str, limit: int = 100) -> List[DataPoint]:
- """Get economic time series data"""
- cache_key = self.cache.generate_key("fred", {"series": series_id, "limit": limit})
- cached = self.cache.get(cache_key)
-
- if cached and CONFIG.agent.enable_caching:
- return [DataPoint(**dp) for dp in cached]
-
- url = f"{self.base_url}/series/observations"
- params = {
- "series_id": series_id,
- "api_key": self.api_key,
- "file_type": "json",
- "limit": limit,
- "sort_order": "desc"
- }
-
- try:
- async with self.session.get(url, params=params) as response:
- data = await response.json()
- observations = data.get("observations", [])
-
- data_points = []
- for obs in observations:
- if obs["value"] != ".":
- dp = DataPoint(
- timestamp=datetime.strptime(obs["date"], "%Y-%m-%d"),
- source="FRED",
- data_type=series_id,
- value=float(obs["value"]),
- confidence=0.95,
- metadata={"series_id": series_id}
- )
- data_points.append(dp)
-
- # Cache the results
- self.cache.set(cache_key, [dp.__dict__ for dp in data_points])
- return data_points
-
- except Exception as e:
- logging.error(f"Error fetching FRED data for {series_id}: {e}")
- return []
-
-
-class NewsDataFeed:
- """News API integration for sentiment and events"""
-
- def __init__(self):
- self.api_key = CONFIG.api.newsapi_key
- self.base_url = "https://newsapi.org/v2"
- self.cache = DataCache()
- self.session = None
-
- async def __aenter__(self):
- self.session = aiohttp.ClientSession()
- return self
-
- async def __aexit__(self, exc_type, exc_val, exc_tb):
- if self.session:
- await self.session.close()
-
- async def get_headlines(self, query: str, sources: List[str] = None,
- hours_back: int = 24) -> List[DataPoint]:
- """Get news headlines with relevance scoring"""
- cache_key = self.cache.generate_key("news", {
- "query": query,
- "sources": sources,
- "hours": hours_back
- })
- cached = self.cache.get(cache_key)
-
- if cached and CONFIG.agent.enable_caching:
- return [DataPoint(**dp) for dp in cached]
-
- from_date = (datetime.now() - timedelta(hours=hours_back)).isoformat()
-
- params = {
- "q": query,
- "from": from_date,
- "sortBy": "relevancy",
- "apiKey": self.api_key,
- "language": "en",
- "pageSize": 100
- }
-
- if sources:
- params["sources"] = ",".join(sources)
-
- try:
- async with self.session.get(f"{self.base_url}/everything", params=params) as response:
- data = await response.json()
- articles = data.get("articles", [])
-
- data_points = []
- for article in articles:
- # Calculate relevance confidence based on source reliability
- source_name = article.get("source", {}).get("name", "").lower()
- confidence = CONFIG.news_sources.get(source_name, 0.50)
-
- dp = DataPoint(
- timestamp=datetime.fromisoformat(article["publishedAt"].replace("Z", "+00:00")),
- source=source_name,
- data_type="news_headline",
- value=article["title"],
- confidence=confidence,
- metadata={
- "description": article.get("description", ""),
- "url": article.get("url", ""),
- "author": article.get("author", ""),
- "query": query
- }
- )
- data_points.append(dp)
-
- self.cache.set(cache_key, [dp.__dict__ for dp in data_points])
- return data_points
-
- except Exception as e:
- logging.error(f"Error fetching news data: {e}")
- return []
-
-
-class MarketDataFeed:
- """Financial market data from multiple sources"""
-
- def __init__(self):
- self.finnhub_key = CONFIG.api.finnhub_api_key
- self.polygon_key = CONFIG.api.polygon_api_key
- self.cache = DataCache()
- self.session = None
-
- async def __aenter__(self):
- self.session = aiohttp.ClientSession()
- return self
-
- async def __aexit__(self, exc_type, exc_val, exc_tb):
- if self.session:
- await self.session.close()
-
- async def get_institutional_trades(self, symbol: str) -> List[DataPoint]:
- """Get institutional trading data from Finnhub"""
- cache_key = self.cache.generate_key("institutional", {"symbol": symbol})
- cached = self.cache.get(cache_key)
-
- if cached and CONFIG.agent.enable_caching:
- return [DataPoint(**dp) for dp in cached]
-
- url = f"https://finnhub.io/api/v1/stock/institutional-portfolio"
- params = {
- "symbol": symbol,
- "token": self.finnhub_key
- }
-
- try:
- async with self.session.get(url, params=params) as response:
- data = await response.json()
-
- data_points = []
- for filing in data.get("data", []):
- dp = DataPoint(
- timestamp=datetime.now(),
- source="Finnhub",
- data_type="institutional_holding",
- value=filing.get("change", 0),
- confidence=0.85,
- metadata={
- "symbol": symbol,
- "institution": filing.get("name", ""),
- "shares": filing.get("share", 0),
- "portfolio_percent": filing.get("portfolioPercent", 0)
- }
- )
- data_points.append(dp)
-
- self.cache.set(cache_key, [dp.__dict__ for dp in data_points])
- return data_points
-
- except Exception as e:
- logging.error(f"Error fetching institutional data: {e}")
- return []
-
- async def get_insider_trades(self, symbol: str, days_back: int = 30) -> List[DataPoint]:
- """Get insider trading data"""
- cache_key = self.cache.generate_key("insider", {"symbol": symbol, "days": days_back})
- cached = self.cache.get(cache_key)
-
- if cached and CONFIG.agent.enable_caching:
- return [DataPoint(**dp) for dp in cached]
-
- from_date = (datetime.now() - timedelta(days=days_back)).strftime("%Y-%m-%d")
- to_date = datetime.now().strftime("%Y-%m-%d")
-
- url = f"https://finnhub.io/api/v1/stock/insider-transactions"
- params = {
- "symbol": symbol,
- "from": from_date,
- "to": to_date,
- "token": self.finnhub_key
- }
-
- try:
- async with self.session.get(url, params=params) as response:
- data = await response.json()
-
- data_points = []
- for trade in data.get("data", []):
- dp = DataPoint(
- timestamp=datetime.strptime(trade["transactionDate"], "%Y-%m-%d"),
- source="Finnhub",
- data_type="insider_trade",
- value=trade.get("change", 0),
- confidence=0.90,
- metadata={
- "symbol": symbol,
- "name": trade.get("name", ""),
- "share": trade.get("share", 0),
- "transaction_code": trade.get("transactionCode", ""),
- "transaction_price": trade.get("transactionPrice", 0)
- }
- )
- data_points.append(dp)
-
- self.cache.set(cache_key, [dp.__dict__ for dp in data_points])
- return data_points
-
- except Exception as e:
- logging.error(f"Error fetching insider data: {e}")
- return []
-
-
-class SentimentDataFeed:
- """Social media and sentiment data aggregation"""
-
- def __init__(self):
- self.reddit_id = CONFIG.api.reddit_client_id
- self.reddit_secret = CONFIG.api.reddit_client_secret
- self.twitter_token = CONFIG.api.twitter_bearer_token
- self.cache = DataCache()
- self.session = None
-
- async def __aenter__(self):
- self.session = aiohttp.ClientSession()
- return self
-
- async def __aexit__(self, exc_type, exc_val, exc_tb):
- if self.session:
- await self.session.close()
-
- async def get_reddit_sentiment(self, subreddits: List[str], keywords: List[str]) -> List[DataPoint]:
- """Get Reddit sentiment for specific keywords"""
- cache_key = self.cache.generate_key("reddit", {
- "subreddits": subreddits,
- "keywords": keywords
- })
- cached = self.cache.get(cache_key)
-
- if cached and CONFIG.agent.enable_caching:
- return [DataPoint(**dp) for dp in cached]
-
- # Reddit API implementation would go here
- # For now, return mock structure
- data_points = []
-
- try:
- # This would be actual Reddit API calls
- for subreddit in subreddits:
- for keyword in keywords:
- dp = DataPoint(
- timestamp=datetime.now(),
- source="Reddit",
- data_type="social_sentiment",
- value=np.random.uniform(-1, 1), # Placeholder sentiment score
- confidence=0.60,
- metadata={
- "subreddit": subreddit,
- "keyword": keyword,
- "post_count": np.random.randint(10, 100),
- "engagement_score": np.random.uniform(0, 1)
- }
- )
- data_points.append(dp)
-
- self.cache.set(cache_key, [dp.__dict__ for dp in data_points])
- return data_points
-
- except Exception as e:
- logging.error(f"Error fetching Reddit sentiment: {e}")
- return []
-
-
-class GeopoliticalDataFeed:
- """Geopolitical events and risk monitoring"""
-
- def __init__(self):
- self.cache = DataCache()
- self.session = None
-
- async def __aenter__(self):
- self.session = aiohttp.ClientSession()
- return self
-
- async def __aexit__(self, exc_type, exc_val, exc_tb):
- if self.session:
- await self.session.close()
-
- async def get_conflict_data(self) -> List[DataPoint]:
- """Get global conflict and tension data"""
- cache_key = self.cache.generate_key("geopolitical", {"type": "conflicts"})
- cached = self.cache.get(cache_key)
-
- if cached and CONFIG.agent.enable_caching:
- return [DataPoint(**dp) for dp in cached]
-
- # This would integrate with GDELT, ACLED, or similar sources
- # For production, you'd implement actual API calls
- data_points = []
-
- try:
- # Mock implementation - replace with real geopolitical data sources
- conflicts = ["Russia-Ukraine", "China-Taiwan", "Middle East", "North Korea"]
-
- for conflict in conflicts:
- dp = DataPoint(
- timestamp=datetime.now(),
- source="GDELT",
- data_type="geopolitical_tension",
- value=np.random.uniform(0, 10), # Tension score 0-10
- confidence=0.75,
- metadata={
- "conflict_region": conflict,
- "escalation_risk": np.random.choice(["low", "medium", "high"]),
- "affected_sectors": ["defense", "energy", "tech"],
- "sanctions_risk": np.random.uniform(0, 1)
- }
- )
- data_points.append(dp)
-
- self.cache.set(cache_key, [dp.__dict__ for dp in data_points])
- return data_points
-
- except Exception as e:
- logging.error(f"Error fetching geopolitical data: {e}")
- return []
-
-
-class DataFeedManager:
- """Central manager for all data feeds"""
-
- def __init__(self):
- self.feeds = {
- "economic": EconomicDataFeed(),
- "news": NewsDataFeed(),
- "market": MarketDataFeed(),
- "sentiment": SentimentDataFeed(),
- "geopolitical": GeopoliticalDataFeed()
- }
-
- async def get_multi_source_data(self, data_requests: Dict[str, Dict]) -> Dict[str, List[DataPoint]]:
- """Get data from multiple sources concurrently"""
- results = {}
-
- async def fetch_data(feed_name: str, feed_obj: Any, request_params: Dict):
- async with feed_obj as feed:
- if feed_name == "economic":
- data = await feed.get_series(**request_params)
- elif feed_name == "news":
- data = await feed.get_headlines(**request_params)
- elif feed_name == "market":
- if request_params.get("data_type") == "institutional":
- data = await feed.get_institutional_trades(request_params["symbol"])
- else:
- data = await feed.get_insider_trades(**request_params)
- elif feed_name == "sentiment":
- data = await feed.get_reddit_sentiment(**request_params)
- elif feed_name == "geopolitical":
- data = await feed.get_conflict_data()
- else:
- data = []
-
- results[feed_name] = data
-
- tasks = []
- for feed_name, request_params in data_requests.items():
- if feed_name in self.feeds:
- feed_obj = self.feeds[feed_name]
- tasks.append(fetch_data(feed_name, feed_obj, request_params))
-
- await asyncio.gather(*tasks, return_exceptions=True)
- return results
-
- def get_latest_data_summary(self) -> Dict[str, Any]:
- """Get summary of latest data availability"""
- summary = {
- "timestamp": datetime.now().isoformat(),
- "data_sources": list(self.feeds.keys()),
- "cache_status": "enabled" if CONFIG.agent.enable_caching else "disabled",
- "api_rate_limits": {
- "economic": f"{CONFIG.agent.max_api_calls_per_hour}/hour",
- "news": f"{CONFIG.agent.max_api_calls_per_hour}/hour",
- "market": f"{CONFIG.agent.max_api_calls_per_hour}/hour"
- }
- }
- return summary
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/geopolitical_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/geopolitical_agent.py
deleted file mode 100644
index 6eee223f7..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/geopolitical_agent.py
+++ /dev/null
@@ -1,915 +0,0 @@
-# -*- coding: utf-8 -*-
-# agents/geopolitical_agent.py - Geopolitical Risk Analysis Agent
-
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - geopolitical events
-# - political risk indicators
-# - international relations data
-# - regional stability metrics
-#
-# OUTPUT:
-# - Geopolitical risk assessments
-# - Regional stability analysis
-# - Political event impact forecasts
-# - Cross-border investment recommendations
-#
-# PARAMETERS:
-# - risk_indicators
-# - regions_monitoring
-# - event_types
-# - impact_timeframes
-"""
-
-import asyncio
-import numpy as np
-import pandas as pd
-from datetime import datetime, timedelta
-from typing import Dict, List, Optional, Tuple
-import logging
-from dataclasses import dataclass
-import openai
-import json
-from collections import defaultdict
-import re
-
-from config import CONFIG
-from data_feeds import DataFeedManager, DataPoint
-
-
-@dataclass
-class GeopoliticalRisk:
- """Geopolitical risk assessment structure"""
- region: str
- risk_type: str
- current_level: int # 1-10 scale
- trend: str # escalating, stable, de-escalating
- probability_impact: float # 0-1
- affected_sectors: List[str]
- timeline: str
- mitigation_strategies: List[str]
- confidence: float
-
-
-@dataclass
-class ConflictSignal:
- """Military conflict monitoring signal"""
- conflict_name: str
- escalation_risk: float
- economic_impact: Dict[str, float]
- supply_chain_risk: Dict[str, float]
- market_sectors: Dict[str, float]
- duration_estimate: str
-
-
-class GeopoliticalAgent:
- """Advanced geopolitical risk monitoring and analysis"""
-
- def __init__(self):
- self.name = "geopolitical"
- self.data_manager = DataFeedManager()
- self.client = openai.OpenAI(api_key=CONFIG.api.openai_api_key)
-
- # Geopolitical risk factors and their weights
- self.risk_factors = {
- "military_conflicts": {
- "Russia-Ukraine": 0.25,
- "China-Taiwan": 0.20,
- "Middle_East": 0.15,
- "North_Korea": 0.10,
- "India-Pakistan": 0.08,
- "Balkans": 0.05,
- "Arctic": 0.07,
- "Cyber_warfare": 0.10
- },
- "trade_tensions": {
- "US-China": 0.30,
- "US-EU": 0.15,
- "China-EU": 0.15,
- "US-Russia": 0.20,
- "Brexit_aftermath": 0.10,
- "USMCA_issues": 0.10
- },
- "sanctions_regime": {
- "Russia_sanctions": 0.35,
- "China_tech_sanctions": 0.25,
- "Iran_sanctions": 0.15,
- "North_Korea_sanctions": 0.10,
- "Secondary_sanctions": 0.15
- },
- "political_instability": {
- "US_domestic": 0.20,
- "EU_integration": 0.18,
- "China_internal": 0.15,
- "Middle_East_regimes": 0.15,
- "Latin_America": 0.12,
- "Africa_coups": 0.10,
- "Democratic_backsliding": 0.10
- }
- }
-
- # Sector impact mapping from geopolitical events
- self.sector_impact_map = {
- "military_conflicts": {
- "defense": 0.8,
- "energy": 0.6,
- "commodities": 0.7,
- "technology": -0.3,
- "tourism": -0.6,
- "airlines": -0.5,
- "insurance": -0.4
- },
- "trade_tensions": {
- "technology": -0.7,
- "manufacturing": -0.5,
- "agriculture": -0.4,
- "automotive": -0.6,
- "semiconductors": -0.8,
- "renewable_energy": 0.3
- },
- "sanctions_regime": {
- "energy": -0.8,
- "banking": -0.6,
- "technology": -0.5,
- "shipping": -0.4,
- "commodities": 0.4,
- "defense": 0.5
- },
- "political_instability": {
- "healthcare": 0.2,
- "utilities": 0.3,
- "consumer_staples": 0.4,
- "financials": -0.4,
- "real_estate": -0.3,
- "currency": -0.6
- }
- }
-
- # Key geopolitical indicators to monitor
- self.geopolitical_keywords = {
- "conflict_escalation": [
- "military buildup", "troop movements", "weapon shipments",
- "border tensions", "missile tests", "naval exercises",
- "air defense", "invasion", "occupation", "blockade"
- ],
- "diplomatic_tensions": [
- "sanctions", "tariffs", "trade war", "diplomatic expulsion",
- "embassy closure", "summit cancellation", "treaty withdrawal",
- "alliance strain", "diplomatic protest"
- ],
- "regime_change": [
- "coup", "revolution", "civil unrest", "protests",
- "election fraud", "authoritarianism", "martial law",
- "state of emergency", "government collapse"
- ],
- "economic_warfare": [
- "currency manipulation", "debt trap", "supply chain disruption",
- "critical minerals", "technology transfer", "intellectual property",
- "cyber attacks", "financial warfare"
- ]
- }
-
- # Regional risk weightings based on global economic impact
- self.regional_weights = {
- "North_America": 0.25,
- "Europe": 0.20,
- "East_Asia": 0.25,
- "Middle_East": 0.15,
- "South_America": 0.08,
- "Africa": 0.05,
- "South_Asia": 0.02
- }
-
- async def analyze_global_risks(self) -> List[GeopoliticalRisk]:
- """Comprehensive global geopolitical risk analysis"""
- risks = []
-
- try:
- # Analyze each risk category
- for risk_category, risk_items in self.risk_factors.items():
- category_risks = await self._analyze_risk_category(risk_category, risk_items)
- risks.extend(category_risks)
-
- # Sort by risk level and confidence
- risks.sort(key=lambda x: x.current_level * x.confidence, reverse=True)
-
- return risks[:10] # Return top 10 risks
-
- except Exception as e:
- logging.error(f"Error in global risk analysis: {e}")
- return [self._default_geopolitical_risk()]
-
- async def _analyze_risk_category(self, category: str, risk_items: Dict[str, float]) -> List[GeopoliticalRisk]:
- """Analyze specific risk category"""
- category_risks = []
-
- # Get news data for this category
- news_data = await self._fetch_category_news(category, list(risk_items.keys()))
-
- for risk_item, weight in risk_items.items():
- try:
- # Filter news for this specific risk
- relevant_news = [news for news in news_data
- if self._is_relevant_to_risk(news, risk_item)]
-
- # Calculate risk level
- risk_level = self._calculate_risk_level(relevant_news, risk_item, category)
-
- # Determine trend
- trend = self._determine_risk_trend(relevant_news)
-
- # Calculate probability and impact
- prob_impact = self._calculate_probability_impact(risk_level, weight, relevant_news)
-
- # Get affected sectors
- affected_sectors = self._get_affected_sectors(category, risk_level)
-
- # Generate timeline estimate
- timeline = self._estimate_timeline(risk_level, trend, relevant_news)
-
- # Get mitigation strategies
- mitigation = self._get_mitigation_strategies(risk_item, category)
-
- # Calculate confidence
- confidence = self._calculate_risk_confidence(relevant_news, risk_item)
-
- risk = GeopoliticalRisk(
- region=self._get_region_from_risk(risk_item),
- risk_type=category,
- current_level=risk_level,
- trend=trend,
- probability_impact=prob_impact,
- affected_sectors=affected_sectors,
- timeline=timeline,
- mitigation_strategies=mitigation,
- confidence=confidence
- )
-
- category_risks.append(risk)
-
- except Exception as e:
- logging.error(f"Error analyzing {risk_item}: {e}")
- continue
-
- return category_risks
-
- async def _fetch_category_news(self, category: str, risk_items: List[str]) -> List[DataPoint]:
- """Fetch news data for specific risk category"""
- all_news = []
-
- # Create search queries for each risk item
- queries = []
- if category == "military_conflicts":
- queries = ["military conflict", "war", "invasion", "missile", "defense"]
- elif category == "trade_tensions":
- queries = ["trade war", "tariffs", "sanctions", "trade dispute"]
- elif category == "sanctions_regime":
- queries = ["sanctions", "embargo", "trade restrictions"]
- elif category == "political_instability":
- queries = ["political crisis", "coup", "election", "protests"]
-
- for query in queries:
- try:
- news_data = await self.data_manager.get_multi_source_data({
- "news": {
- "query": query,
- "sources": ["reuters", "bloomberg", "wsj", "ft"],
- "hours_back": 72 # 3 days
- }
- })
-
- if "news" in news_data:
- all_news.extend(news_data["news"])
-
- except Exception as e:
- logging.error(f"Error fetching news for {query}: {e}")
- continue
-
- return all_news
-
- def _is_relevant_to_risk(self, news: DataPoint, risk_item: str) -> bool:
- """Check if news article is relevant to specific risk"""
- text = (news.value + " " + news.metadata.get("description", "")).lower()
-
- # Create keywords for each risk item
- risk_keywords = {
- "Russia-Ukraine": ["russia", "ukraine", "putin", "zelensky", "kyiv", "moscow"],
- "China-Taiwan": ["china", "taiwan", "beijing", "taipei", "strait", "xi jinping"],
- "Middle_East": ["iran", "israel", "gaza", "lebanon", "syria", "yemen"],
- "North_Korea": ["north korea", "kim jong", "pyongyang", "dprk"],
- "US-China": ["us china", "trade war", "biden", "xi jinping", "tariff"],
- "Russia_sanctions": ["russia sanctions", "swift", "energy embargo"],
- "China_tech_sanctions": ["china tech", "semiconductor", "huawei", "tiktok"]
- }
-
- keywords = risk_keywords.get(risk_item, [risk_item.lower().replace("_", " ")])
-
- return any(keyword in text for keyword in keywords)
-
- def _calculate_risk_level(self, news: List[DataPoint], risk_item: str, category: str) -> int:
- """Calculate current risk level (1-10 scale)"""
- if not news:
- return 3 # Default moderate risk
-
- # Base risk levels for different risk items
- base_risks = {
- "Russia-Ukraine": 8,
- "China-Taiwan": 6,
- "Middle_East": 7,
- "US-China": 5,
- "North_Korea": 4
- }
-
- base_risk = base_risks.get(risk_item, 5)
-
- # Analyze news sentiment and intensity
- escalation_keywords = self.geopolitical_keywords.get("conflict_escalation", [])
- tension_keywords = self.geopolitical_keywords.get("diplomatic_tensions", [])
-
- escalation_count = 0
- total_articles = len(news)
-
- for article in news:
- text = article.value.lower()
- escalation_count += sum(1 for keyword in escalation_keywords if keyword in text)
- escalation_count += sum(1 for keyword in tension_keywords if keyword in text)
-
- # Adjust base risk based on recent news intensity
- if total_articles > 0:
- intensity_factor = min(escalation_count / total_articles, 2.0)
- adjusted_risk = base_risk + intensity_factor
- else:
- adjusted_risk = base_risk
-
- return int(np.clip(adjusted_risk, 1, 10))
-
- def _determine_risk_trend(self, news: List[DataPoint]) -> str:
- """Determine if risk is escalating, stable, or de-escalating"""
- if len(news) < 2:
- return "stable"
-
- # Sort news by date
- sorted_news = sorted(news, key=lambda x: x.timestamp)
-
- # Compare recent vs older news intensity
- midpoint = len(sorted_news) // 2
- older_news = sorted_news[:midpoint]
- recent_news = sorted_news[midpoint:]
-
- older_intensity = self._calculate_news_intensity(older_news)
- recent_intensity = self._calculate_news_intensity(recent_news)
-
- if recent_intensity > older_intensity * 1.2:
- return "escalating"
- elif recent_intensity < older_intensity * 0.8:
- return "de-escalating"
- else:
- return "stable"
-
- def _calculate_news_intensity(self, news: List[DataPoint]) -> float:
- """Calculate intensity score of news articles"""
- if not news:
- return 0.0
-
- intensity_score = 0.0
- escalation_keywords = (self.geopolitical_keywords.get("conflict_escalation", []) +
- self.geopolitical_keywords.get("diplomatic_tensions", []))
-
- for article in news:
- text = article.value.lower()
- keyword_count = sum(1 for keyword in escalation_keywords if keyword in text)
- # Weight by article confidence
- intensity_score += keyword_count * article.confidence
-
- return intensity_score / len(news)
-
- def _calculate_probability_impact(self, risk_level: int, weight: float,
- news: List[DataPoint]) -> float:
- """Calculate probability-weighted impact"""
- # Convert risk level to probability (non-linear)
- probability = (risk_level / 10) ** 1.5
-
- # Weight by global economic impact
- economic_impact = weight
-
- # Adjust based on news recency and volume
- if news:
- avg_age_hours = np.mean([(datetime.now() - article.timestamp).total_seconds() / 3600
- for article in news])
- recency_factor = max(0.5, 1.0 - avg_age_hours / 168) # Decay over 1 week
- volume_factor = min(1.5, len(news) / 10) # More news = higher impact
- else:
- recency_factor = 0.5
- volume_factor = 0.5
-
- return probability * economic_impact * recency_factor * volume_factor
-
- def _get_affected_sectors(self, category: str, risk_level: int) -> List[str]:
- """Get sectors most affected by this risk category"""
- if category not in self.sector_impact_map:
- return ["broad_market"]
-
- sector_impacts = self.sector_impact_map[category]
-
- # Filter sectors by risk level threshold and impact magnitude
- threshold = 0.3 if risk_level > 7 else 0.4 if risk_level > 5 else 0.5
-
- affected_sectors = []
- for sector, impact in sector_impacts.items():
- if abs(impact) >= threshold:
- affected_sectors.append(sector)
-
- return affected_sectors or ["broad_market"]
-
- def _estimate_timeline(self, risk_level: int, trend: str, news: List[DataPoint]) -> str:
- """Estimate timeline for risk materialization"""
- base_timelines = {
- "escalating": {
- 9: "1-3 months",
- 7: "3-6 months",
- 5: "6-12 months",
- 3: "1-2 years"
- },
- "stable": {
- 9: "3-6 months",
- 7: "6-12 months",
- 5: "1-2 years",
- 3: "2+ years"
- },
- "de-escalating": {
- 9: "6-12 months",
- 7: "1-2 years",
- 5: "2+ years",
- 3: "Low probability"
- }
- }
-
- timeline_map = base_timelines.get(trend, base_timelines["stable"])
-
- # Find closest risk level
- for level in sorted(timeline_map.keys(), reverse=True):
- if risk_level >= level:
- return timeline_map[level]
-
- return "2+ years"
-
- def _get_mitigation_strategies(self, risk_item: str, category: str) -> List[str]:
- """Get investment mitigation strategies for specific risks"""
- strategies = {
- "military_conflicts": [
- "Increase defense sector allocation",
- "Hedge energy exposure",
- "Diversify geographically",
- "Add gold/commodities hedge",
- "Reduce emerging market exposure"
- ],
- "trade_tensions": [
- "Avoid single-country exposure",
- "Focus on domestic-oriented companies",
- "Hedge currency exposure",
- "Diversify supply chains",
- "Consider trade-war beneficiaries"
- ],
- "sanctions_regime": [
- "Avoid sanctioned sectors/countries",
- "Increase compliance monitoring",
- "Diversify banking relationships",
- "Focus on domestic markets",
- "Consider alternative payment systems"
- ],
- "political_instability": [
- "Increase safe-haven assets",
- "Reduce political-sensitive sectors",
- "Focus on multinational companies",
- "Add volatility hedges",
- "Maintain higher cash levels"
- ]
- }
-
- return strategies.get(category, ["Monitor closely", "Maintain diversification"])
-
- def _get_region_from_risk(self, risk_item: str) -> str:
- """Map risk item to geographical region"""
- region_mapping = {
- "Russia-Ukraine": "Europe",
- "China-Taiwan": "East_Asia",
- "Middle_East": "Middle_East",
- "North_Korea": "East_Asia",
- "US-China": "Global",
- "US-EU": "North_America",
- "Brexit": "Europe",
- "India-Pakistan": "South_Asia"
- }
-
- return region_mapping.get(risk_item, "Global")
-
- def _calculate_risk_confidence(self, news: List[DataPoint], risk_item: str) -> float:
- """Calculate confidence in risk assessment"""
- confidence_factors = []
-
- # News volume factor
- news_count = len(news)
- volume_confidence = min(1.0, news_count / 20) # Optimal around 20 articles
- confidence_factors.append(volume_confidence * 0.3)
-
- # Source reliability
- if news:
- avg_source_confidence = np.mean([article.confidence for article in news])
- confidence_factors.append(avg_source_confidence * 0.4)
- else:
- confidence_factors.append(0.3 * 0.4)
-
- # News recency
- if news:
- most_recent = max(news, key=lambda x: x.timestamp)
- hours_since = (datetime.now() - most_recent.timestamp).total_seconds() / 3600
- recency_confidence = max(0.3, 1.0 - hours_since / 72) # Decay over 3 days
- confidence_factors.append(recency_confidence * 0.3)
- else:
- confidence_factors.append(0.3 * 0.3)
-
- return np.sum(confidence_factors)
-
- async def analyze_conflict_escalation(self, conflict_name: str) -> ConflictSignal:
- """Deep analysis of specific military conflict"""
- try:
- # Fetch conflict-specific news
- conflict_news = await self.data_manager.get_multi_source_data({
- "news": {
- "query": conflict_name,
- "sources": ["reuters", "bloomberg", "wsj"],
- "hours_back": 48
- }
- })
-
- news_data = conflict_news.get("news", [])
-
- # Calculate escalation risk
- escalation_risk = self._calculate_escalation_risk(news_data, conflict_name)
-
- # Assess economic impact
- economic_impact = self._assess_economic_impact(conflict_name, escalation_risk)
-
- # Analyze supply chain risks
- supply_chain_risk = self._analyze_supply_chain_impact(conflict_name)
-
- # Get market sector impacts
- market_sectors = self._get_market_sector_impacts(conflict_name, escalation_risk)
-
- # Estimate duration
- duration_estimate = self._estimate_conflict_duration(news_data, escalation_risk)
-
- return ConflictSignal(
- conflict_name=conflict_name,
- escalation_risk=escalation_risk,
- economic_impact=economic_impact,
- supply_chain_risk=supply_chain_risk,
- market_sectors=market_sectors,
- duration_estimate=duration_estimate
- )
-
- except Exception as e:
- logging.error(f"Error analyzing conflict {conflict_name}: {e}")
- return self._default_conflict_signal(conflict_name)
-
- def _calculate_escalation_risk(self, news: List[DataPoint], conflict_name: str) -> float:
- """Calculate probability of conflict escalation"""
- if not news:
- return 0.3 # Default moderate risk
-
- escalation_indicators = [
- "military buildup", "troop deployment", "weapon delivery",
- "alliance activation", "nuclear threat", "red line crossed",
- "ultimatum", "deadline", "mobilization", "intervention"
- ]
-
- escalation_score = 0.0
-
- for article in news:
- text = article.value.lower()
- indicator_count = sum(1 for indicator in escalation_indicators if indicator in text)
- escalation_score += indicator_count * article.confidence
-
- # Normalize by number of articles
- if news:
- normalized_score = escalation_score / len(news)
- # Convert to probability (0-1)
- return min(1.0, normalized_score / 3.0) # Scale factor
-
- return 0.3
-
- def _assess_economic_impact(self, conflict_name: str, escalation_risk: float) -> Dict[str, float]:
- """Assess economic impact of conflict escalation"""
- # Base economic impacts by conflict
- base_impacts = {
- "Russia-Ukraine": {
- "global_gdp": -0.8,
- "inflation": 2.5,
- "energy_prices": 0.4,
- "food_prices": 0.3,
- "supply_chains": -0.6
- },
- "China-Taiwan": {
- "global_gdp": -2.5,
- "inflation": 1.8,
- "tech_supply": -0.8,
- "shipping": -0.7,
- "semiconductors": -0.9
- },
- "Middle_East": {
- "global_gdp": -0.5,
- "oil_prices": 0.6,
- "shipping": -0.4,
- "regional_markets": -0.8,
- "defense_spending": 0.3
- }
- }
-
- base_impact = base_impacts.get(conflict_name, {
- "global_gdp": -0.3,
- "inflation": 1.0,
- "volatility": 0.5
- })
-
- # Scale by escalation risk
- scaled_impact = {}
- for key, value in base_impact.items():
- scaled_impact[key] = value * escalation_risk
-
- return scaled_impact
-
- def _analyze_supply_chain_impact(self, conflict_name: str) -> Dict[str, float]:
- """Analyze supply chain disruption risks"""
- supply_chain_risks = {
- "Russia-Ukraine": {
- "energy": 0.8,
- "fertilizers": 0.7,
- "grains": 0.6,
- "metals": 0.5,
- "semiconductors": 0.3
- },
- "China-Taiwan": {
- "semiconductors": 0.9,
- "electronics": 0.8,
- "rare_earths": 0.7,
- "shipping": 0.6,
- "manufacturing": 0.7
- },
- "Middle_East": {
- "oil": 0.9,
- "gas": 0.7,
- "shipping": 0.6,
- "petrochemicals": 0.5
- }
- }
-
- return supply_chain_risks.get(conflict_name, {"general": 0.4})
-
- def _get_market_sector_impacts(self, conflict_name: str, escalation_risk: float) -> Dict[str, float]:
- """Get sector-specific market impacts"""
- sector_impacts = {
- "Russia-Ukraine": {
- "energy": 0.6,
- "defense": 0.8,
- "agriculture": 0.4,
- "technology": -0.3,
- "airlines": -0.6,
- "tourism": -0.7
- },
- "China-Taiwan": {
- "semiconductors": -0.9,
- "technology": -0.7,
- "defense": 0.8,
- "shipping": -0.6,
- "manufacturing": -0.5,
- "commodities": 0.3
- },
- "Middle_East": {
- "energy": 0.8,
- "defense": 0.6,
- "airlines": -0.5,
- "insurance": -0.4,
- "shipping": -0.3
- }
- }
-
- base_impacts = sector_impacts.get(conflict_name, {"broad_market": -0.2})
-
- # Scale by escalation risk
- scaled_impacts = {}
- for sector, impact in base_impacts.items():
- scaled_impacts[sector] = impact * escalation_risk
-
- return scaled_impacts
-
- def _estimate_conflict_duration(self, news: List[DataPoint], escalation_risk: float) -> str:
- """Estimate conflict duration based on escalation risk"""
- if escalation_risk > 0.8:
- return "6+ months (high intensity)"
- elif escalation_risk > 0.6:
- return "3-12 months (prolonged)"
- elif escalation_risk > 0.4:
- return "1-6 months (limited)"
- else:
- return "Weeks to months (contained)"
-
- def _default_geopolitical_risk(self) -> GeopoliticalRisk:
- """Return default risk in case of errors"""
- return GeopoliticalRisk(
- region="Global",
- risk_type="general_uncertainty",
- current_level=5,
- trend="stable",
- probability_impact=0.3,
- affected_sectors=["broad_market"],
- timeline="6-12 months",
- mitigation_strategies=["Maintain diversification", "Monitor developments"],
- confidence=0.3
- )
-
- def _default_conflict_signal(self, conflict_name: str) -> ConflictSignal:
- """Return default conflict signal"""
- return ConflictSignal(
- conflict_name=conflict_name,
- escalation_risk=0.3,
- economic_impact={"global_gdp": -0.1},
- supply_chain_risk={"general": 0.2},
- market_sectors={"broad_market": -0.1},
- duration_estimate="Unknown"
- )
-
- async def generate_llm_geopolitical_analysis(self, risks: List[GeopoliticalRisk]) -> Dict:
- """Generate LLM-enhanced geopolitical analysis"""
- try:
- # Prepare risk summary
- risk_summary = self._prepare_risk_summary(risks)
-
- prompt = f"""
- As a senior geopolitical risk analyst, analyze the current global risk landscape and provide investment guidance.
-
- Current Top Risks:
- {risk_summary}
-
- Please provide:
- 1. Most critical risks requiring immediate attention
- 2. Potential black swan scenarios (low probability, high impact)
- 3. Portfolio hedging strategies
- 4. Regional allocation recommendations
- 5. Timeline for next major geopolitical shift
- 6. Early warning indicators to monitor
-
- Format as JSON with keys: critical_risks, black_swan_scenarios, hedging_strategies,
- regional_allocation, timeline, early_warning_indicators
- """
-
- response = self.client.chat.completions.create(
- model=CONFIG.llm.deep_think_model,
- messages=[{"role": "user", "content": prompt}],
- temperature=CONFIG.llm.temperature,
- max_tokens=CONFIG.llm.max_tokens
- )
-
- return json.loads(response.choices[0].message.content)
-
- except Exception as e:
- logging.error(f"Error in LLM geopolitical analysis: {e}")
- return {
- "critical_risks": ["Russia-Ukraine conflict", "US-China tensions"],
- "black_swan_scenarios": ["Taiwan invasion", "Nuclear incident"],
- "hedging_strategies": ["Increase defense allocation", "Add gold hedge"],
- "regional_allocation": "Underweight emerging markets",
- "timeline": "Next 6-12 months",
- "early_warning_indicators": ["Troop movements", "Diplomatic withdrawals"]
- }
-
- def _prepare_risk_summary(self, risks: List[GeopoliticalRisk]) -> str:
- """Prepare risk summary for LLM analysis"""
- summary_lines = []
-
- for risk in risks[:5]: # Top 5 risks
- summary_lines.append(
- f"{risk.region} - {risk.risk_type}: Level {risk.current_level}/10 "
- f"({risk.trend}), Impact: {risk.probability_impact:.2f}, "
- f"Sectors: {', '.join(risk.affected_sectors[:3])}"
- )
-
- return "\n".join(summary_lines)
-
- async def get_geopolitical_report(self) -> Dict:
- """Generate comprehensive geopolitical risk report"""
- # Analyze global risks
- global_risks = await self.analyze_global_risks()
-
- # Analyze specific conflicts
- conflicts = ["Russia-Ukraine", "China-Taiwan", "Middle_East"]
- conflict_analyses = []
-
- for conflict in conflicts:
- signal = await self.analyze_conflict_escalation(conflict)
- conflict_analyses.append({
- "conflict": conflict,
- "escalation_risk": signal.escalation_risk,
- "economic_impact": signal.economic_impact,
- "duration_estimate": signal.duration_estimate
- })
-
- # Generate LLM analysis
- llm_analysis = await self.generate_llm_geopolitical_analysis(global_risks)
-
- return {
- "timestamp": datetime.now().isoformat(),
- "agent": self.name,
- "global_risk_assessment": {
- "overall_risk_level": np.mean([risk.current_level for risk in global_risks]),
- "top_risks": [{
- "region": risk.region,
- "type": risk.risk_type,
- "level": risk.current_level,
- "trend": risk.trend,
- "timeline": risk.timeline,
- "affected_sectors": risk.affected_sectors
- } for risk in global_risks[:5]]
- },
- "conflict_monitor": conflict_analyses,
- "investment_implications": {
- "defensive_positioning": self._calculate_defensive_score(global_risks),
- "sector_rotation": self._get_sector_rotation_recommendations(global_risks),
- "regional_weights": self._get_regional_weight_adjustments(global_risks),
- "hedging_requirements": self._get_hedging_requirements(global_risks)
- },
- "llm_analysis": llm_analysis,
- "risk_monitoring": {
- "update_frequency": "every 6 hours",
- "key_indicators": ["news_flow", "market_volatility", "diplomatic_activity"],
- "escalation_triggers": ["military_movement", "sanctions_announcement", "alliance_activation"]
- }
- }
-
- def _calculate_defensive_score(self, risks: List[GeopoliticalRisk]) -> float:
- """Calculate how defensive portfolio should be"""
- high_risk_count = sum(1 for risk in risks if risk.current_level >= 7)
- escalating_risks = sum(1 for risk in risks if risk.trend == "escalating")
-
- defensive_score = (high_risk_count * 0.15 + escalating_risks * 0.10)
- return min(1.0, defensive_score)
-
- def _get_sector_rotation_recommendations(self, risks: List[GeopoliticalRisk]) -> Dict[str, str]:
- """Get sector rotation based on geopolitical risks"""
- sector_scores = defaultdict(float)
-
- for risk in risks:
- weight = risk.current_level * risk.confidence / 10
- for sector in risk.affected_sectors:
- if sector in self.sector_impact_map.get(risk.risk_type, {}):
- impact = self.sector_impact_map[risk.risk_type][sector]
- sector_scores[sector] += impact * weight
-
- recommendations = {}
- for sector, score in sector_scores.items():
- if score > 0.2:
- recommendations[sector] = "overweight"
- elif score < -0.2:
- recommendations[sector] = "underweight"
- else:
- recommendations[sector] = "neutral"
-
- return recommendations
-
- def _get_regional_weight_adjustments(self, risks: List[GeopoliticalRisk]) -> Dict[str, float]:
- """Get regional allocation adjustments"""
- regional_adjustments = {}
-
- for region, base_weight in self.regional_weights.items():
- region_risks = [risk for risk in risks if risk.region == region]
-
- if region_risks:
- avg_risk = np.mean([risk.current_level for risk in region_risks])
- # Reduce allocation for high-risk regions
- adjustment = max(-0.5, (5 - avg_risk) / 10)
- regional_adjustments[region] = base_weight * (1 + adjustment)
- else:
- regional_adjustments[region] = base_weight
-
- # Normalize to sum to 1
- total_weight = sum(regional_adjustments.values())
- return {region: weight / total_weight for region, weight in regional_adjustments.items()}
-
- def _get_hedging_requirements(self, risks: List[GeopoliticalRisk]) -> List[str]:
- """Get specific hedging requirements"""
- hedges = []
-
- high_risks = [risk for risk in risks if risk.current_level >= 7]
-
- for risk in high_risks:
- if "energy" in risk.affected_sectors:
- hedges.append("Energy price hedge")
- if "technology" in risk.affected_sectors:
- hedges.append("Tech sector put options")
- if "currency" in risk.affected_sectors:
- hedges.append("USD strength hedge")
- if risk.risk_type == "military_conflicts":
- hedges.append("Gold allocation increase")
- hedges.append("Defense sector exposure")
-
- return list(set(hedges)) # Remove duplicates
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/innovation_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/innovation_agent.py
deleted file mode 100644
index c569c762d..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/innovation_agent.py
+++ /dev/null
@@ -1,163 +0,0 @@
-# -*- coding: utf-8 -*-
-# agents/innovation_agent.py - Technology Innovation Cycle Analysis Agent
-
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - technology trends data
-# - innovation metrics
-# - patent filings
-# - R&D investments
-#
-# OUTPUT:
-# - Technology trend forecasts
-# - Innovation cycle identification
-# - Disruptive technology alerts
-# - Sector impact analysis
-#
-# PARAMETERS:
-# - technology_sectors
-# - innovation_indicators
-# - trend_analysis_periods
-# - disruption_thresholds
-"""
-
-import asyncio
-import numpy as np
-import pandas as pd
-from datetime import datetime, timedelta
-from typing import Dict, List, Optional
-import logging
-from dataclasses import dataclass
-import openai
-import json
-
-from config import CONFIG
-from data_feeds import DataFeedManager, DataPoint
-
-
-@dataclass
-class InnovationSignal:
- """Technology innovation signal"""
- technology_sector: str
- adoption_stage: str # emerging, growth, maturity, decline
- disruption_potential: float # 0-1
- investment_opportunity: str
- time_horizon: str
- confidence: float
-
-
-class InnovationAgent:
- """Technology innovation cycle analysis and investment opportunities"""
-
- def __init__(self):
- self.name = "innovation"
- self.data_manager = DataFeedManager()
- self.client = openai.OpenAI(api_key=CONFIG.api.openai_api_key)
-
- self.innovation_sectors = {
- "artificial_intelligence": {"weight": 0.25, "maturity": "growth"},
- "quantum_computing": {"weight": 0.15, "maturity": "emerging"},
- "biotechnology": {"weight": 0.20, "maturity": "growth"},
- "renewable_energy": {"weight": 0.15, "maturity": "maturity"},
- "space_technology": {"weight": 0.10, "maturity": "emerging"},
- "robotics": {"weight": 0.15, "maturity": "growth"}
- }
-
- async def analyze_innovation_cycles(self) -> List[InnovationSignal]:
- """Analyze technology innovation cycles"""
- signals = []
-
- for sector, config in self.innovation_sectors.items():
- try:
- signal = await self._analyze_sector_innovation(sector, config)
- if signal:
- signals.append(signal)
- except Exception as e:
- logging.error(f"Error analyzing {sector}: {e}")
- continue
-
- return signals
-
- async def _analyze_sector_innovation(self, sector: str, config: Dict) -> Optional[InnovationSignal]:
- """Analyze innovation in specific technology sector"""
- # Fetch innovation news
- news_data = await self.data_manager.get_multi_source_data({
- "news": {
- "query": sector.replace("_", " ") + " breakthrough innovation",
- "sources": ["reuters", "bloomberg"],
- "hours_back": 168
- }
- })
-
- news = news_data.get("news", [])
-
- # Calculate innovation metrics
- breakthrough_count = sum(1 for article in news
- if any(word in article.value.lower()
- for word in ["breakthrough", "revolutionary", "first-of-kind"]))
-
- funding_mentions = sum(1 for article in news
- if any(word in article.value.lower()
- for word in ["funding", "investment", "IPO", "acquisition"]))
-
- # Determine adoption stage and disruption potential
- if news:
- disruption_potential = min((breakthrough_count + funding_mentions) / len(news), 1.0)
- else:
- disruption_potential = 0.3
-
- adoption_stage = config["maturity"]
- investment_opportunity = self._determine_investment_opportunity(disruption_potential, adoption_stage)
-
- return InnovationSignal(
- technology_sector=sector,
- adoption_stage=adoption_stage,
- disruption_potential=disruption_potential,
- investment_opportunity=investment_opportunity,
- time_horizon=self._estimate_time_horizon(adoption_stage),
- confidence=min(len(news) / 10, 1.0) * 0.7
- )
-
- def _determine_investment_opportunity(self, disruption_potential: float, stage: str) -> str:
- """Determine investment opportunity classification"""
- if disruption_potential > 0.7 and stage == "emerging":
- return "high_risk_high_reward"
- elif disruption_potential > 0.5 and stage == "growth":
- return "growth_opportunity"
- elif disruption_potential > 0.3 and stage == "maturity":
- return "value_opportunity"
- else:
- return "monitor"
-
- def _estimate_time_horizon(self, stage: str) -> str:
- """Estimate investment time horizon"""
- horizon_map = {
- "emerging": "long_term",
- "growth": "medium_term",
- "maturity": "short_term",
- "decline": "avoid"
- }
- return horizon_map.get(stage, "medium_term")
-
- async def get_innovation_report(self) -> Dict:
- """Generate innovation analysis report"""
- signals = await self.analyze_innovation_cycles()
-
- return {
- "timestamp": datetime.now().isoformat(),
- "agent": self.name,
- "innovation_analysis": {
- "sector_signals": [{
- "sector": signal.technology_sector,
- "stage": signal.adoption_stage,
- "disruption_potential": signal.disruption_potential,
- "opportunity": signal.investment_opportunity,
- "time_horizon": signal.time_horizon
- } for signal in signals],
- "top_opportunities": [s.technology_sector for s in signals
- if s.investment_opportunity == "high_risk_high_reward"],
- "emerging_technologies": [s.technology_sector for s in signals
- if s.adoption_stage == "emerging"]
- }
- }
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/institutional_flow_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/institutional_flow_agent.py
deleted file mode 100644
index ae2396d04..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/institutional_flow_agent.py
+++ /dev/null
@@ -1,1154 +0,0 @@
-# -*- coding: utf-8 -*-
-# agents/institutional_flow_agent.py - Institutional Flow Analysis Agent
-
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - institutional trading data
-# - fund flow metrics
-# - position changes
-# - large holder information
-#
-# OUTPUT:
-# - Institutional flow analysis
-# - Fund flow trends
-# - Position change alerts
-# - Institutional sentiment indicators
-#
-# PARAMETERS:
-# - institution_types
-# - flow_thresholds
-# - position_tracking
-# - reporting_periods
-"""
-
-import asyncio
-import numpy as np
-import pandas as pd
-from datetime import datetime, timedelta
-from typing import Dict, List, Optional, Tuple
-import logging
-from dataclasses import dataclass
-import openai
-import json
-from collections import defaultdict
-
-from config import CONFIG
-from data_feeds import DataFeedManager, DataPoint
-
-
-@dataclass
-class FlowSignal:
- """Institutional flow signal structure"""
- institution_type: str
- flow_direction: str # inflow, outflow, neutral
- flow_magnitude: float # 0-1 scale
- asset_class: str
- time_horizon: str
- confidence: float
- contrarian_signal: bool
- flow_velocity: float # Rate of change
-
-
-@dataclass
-class SmartMoneyIndicator:
- """Smart money flow indicator"""
- indicator_name: str
- current_reading: float
- historical_percentile: float
- signal_strength: str # weak, moderate, strong
- market_implication: str
- asset_impact: Dict[str, float]
-
-
-class InstitutionalFlowAgent:
- """Advanced institutional flow analysis and smart money tracking"""
-
- def __init__(self):
- self.name = "institutional_flow"
- self.data_manager = DataFeedManager()
- self.client = openai.OpenAI(api_key=CONFIG.api.openai_api_key)
-
- # Institution types and their market influence weights
- self.institution_weights = {
- "pension_funds": 0.25, # Long-term, stable flows
- "sovereign_wealth": 0.20, # Large size, strategic
- "hedge_funds": 0.15, # Fast moving, trend setting
- "mutual_funds": 0.15, # Retail proxy, momentum
- "insurance_companies": 0.10, # Defensive, liability matching
- "endowments": 0.08, # Sophisticated, alternative focus
- "central_banks": 0.07 # Policy driven, FX focused
- }
-
- # Asset class flow patterns
- self.flow_patterns = {
- "risk_on": {
- "equities": 0.7,
- "high_yield_bonds": 0.4,
- "emerging_markets": 0.6,
- "commodities": 0.3,
- "real_estate": 0.4,
- "alternatives": 0.5
- },
- "risk_off": {
- "government_bonds": 0.8,
- "investment_grade_bonds": 0.6,
- "cash": 0.9,
- "gold": 0.7,
- "defensive_sectors": 0.5,
- "low_volatility": 0.6
- },
- "rotation": {
- "value_to_growth": {"value": 0.6, "growth": -0.4},
- "large_to_small": {"large_cap": -0.3, "small_cap": 0.6},
- "domestic_to_international": {"domestic": -0.2, "international": 0.5}
- }
- }
-
- # Smart money indicators
- self.smart_money_indicators = {
- "13f_filings": {
- "weight": 0.25,
- "lookback_quarters": 4,
- "significance_threshold": 0.02 # 2% position change
- },
- "insider_trading": {
- "weight": 0.20,
- "lookback_days": 90,
- "significance_threshold": 0.05 # 5% of shares
- },
- "options_flow": {
- "weight": 0.15,
- "lookback_days": 5,
- "significance_threshold": 2.0 # 2x normal volume
- },
- "dark_pool_activity": {
- "weight": 0.15,
- "lookback_days": 10,
- "significance_threshold": 0.4 # 40% of volume
- },
- "repo_market": {
- "weight": 0.10,
- "lookback_days": 30,
- "significance_threshold": 0.1 # 10 bps change
- },
- "etf_flows": {
- "weight": 0.15,
- "lookback_days": 20,
- "significance_threshold": 0.03 # 3% of AUM
- }
- }
-
- # Flow velocity thresholds
- self.velocity_thresholds = {
- "extremely_fast": 0.8, # >80th percentile
- "fast": 0.6, # >60th percentile
- "moderate": 0.4, # >40th percentile
- "slow": 0.2, # >20th percentile
- "very_slow": 0.0 # <20th percentile
- }
-
- async def analyze_institutional_flows(self) -> Dict[str, FlowSignal]:
- """Comprehensive institutional flow analysis"""
- flow_signals = {}
-
- try:
- # Analyze equity flows
- equity_flows = await self._analyze_equity_flows()
- if equity_flows:
- flow_signals["equity_flows"] = equity_flows
-
- # Analyze bond flows
- bond_flows = await self._analyze_bond_flows()
- if bond_flows:
- flow_signals["bond_flows"] = bond_flows
-
- # Analyze ETF flows
- etf_flows = await self._analyze_etf_flows()
- if etf_flows:
- flow_signals["etf_flows"] = etf_flows
-
- # Analyze alternative investment flows
- alternative_flows = await self._analyze_alternative_flows()
- if alternative_flows:
- flow_signals["alternative_flows"] = alternative_flows
-
- return flow_signals
-
- except Exception as e:
- logging.error(f"Error in institutional flow analysis: {e}")
- return {"error": self._default_flow_signal()}
-
- async def _analyze_equity_flows(self) -> Optional[FlowSignal]:
- """Analyze institutional equity flows"""
- try:
- # Fetch institutional trading data
- institutional_data = await self.data_manager.get_multi_source_data({
- "market": {
- "symbol": "SPY", # Use SPY as proxy for overall equity flows
- "data_type": "institutional"
- }
- })
-
- market_data = institutional_data.get("market", [])
- if not market_data:
- return None
-
- # Calculate flow metrics
- flow_direction, flow_magnitude = self._calculate_flow_metrics(market_data)
-
- # Calculate flow velocity
- flow_velocity = self._calculate_flow_velocity(market_data)
-
- # Determine if contrarian signal
- contrarian_signal = self._is_contrarian_flow(flow_magnitude, flow_velocity)
-
- # Calculate confidence based on data quality
- confidence = self._calculate_flow_confidence(market_data)
-
- return FlowSignal(
- institution_type="mixed_institutions",
- flow_direction=flow_direction,
- flow_magnitude=flow_magnitude,
- asset_class="equities",
- time_horizon="medium",
- confidence=confidence,
- contrarian_signal=contrarian_signal,
- flow_velocity=flow_velocity
- )
-
- except Exception as e:
- logging.error(f"Error in equity flow analysis: {e}")
- return None
-
- async def _analyze_bond_flows(self) -> Optional[FlowSignal]:
- """Analyze institutional bond flows"""
- try:
- # Fetch bond flow data (using treasury ETF as proxy)
- bond_data = await self.data_manager.get_multi_source_data({
- "market": {
- "symbol": "TLT", # Long-term treasury ETF
- "data_type": "institutional"
- }
- })
-
- market_data = bond_data.get("market", [])
- if not market_data:
- # Simulate bond flows based on yield movements
- return self._simulate_bond_flows()
-
- flow_direction, flow_magnitude = self._calculate_flow_metrics(market_data)
- flow_velocity = self._calculate_flow_velocity(market_data)
-
- return FlowSignal(
- institution_type="fixed_income_institutions",
- flow_direction=flow_direction,
- flow_magnitude=flow_magnitude,
- asset_class="bonds",
- time_horizon="long",
- confidence=0.7,
- contrarian_signal=False, # Bond flows typically not contrarian
- flow_velocity=flow_velocity
- )
-
- except Exception as e:
- logging.error(f"Error in bond flow analysis: {e}")
- return None
-
- def _simulate_bond_flows(self) -> FlowSignal:
- """Simulate bond flows when data unavailable"""
- # Simulate based on typical institutional behavior
- flow_magnitude = np.random.uniform(0.3, 0.7)
- flow_direction = np.random.choice(["inflow", "outflow"], p=[0.6, 0.4])
-
- return FlowSignal(
- institution_type="fixed_income_institutions",
- flow_direction=flow_direction,
- flow_magnitude=flow_magnitude,
- asset_class="bonds",
- time_horizon="long",
- confidence=0.5, # Lower confidence for simulated data
- contrarian_signal=False,
- flow_velocity=0.3
- )
-
- async def _analyze_etf_flows(self) -> Optional[FlowSignal]:
- """Analyze ETF flows as proxy for institutional sentiment"""
- try:
- # Major ETF flows to analyze
- etfs_to_analyze = ["SPY", "QQQ", "IWM", "EFA", "EEM", "TLT", "GLD"]
-
- etf_flows = {}
- for etf in etfs_to_analyze:
- # In production, would fetch actual ETF flow data
- # For now, simulate based on market conditions
- flow_data = self._simulate_etf_flow(etf)
- etf_flows[etf] = flow_data
-
- # Aggregate ETF flows
- total_inflows = sum(flow["inflow"] for flow in etf_flows.values())
- total_outflows = sum(flow["outflow"] for flow in etf_flows.values())
-
- net_flow = total_inflows - total_outflows
- flow_magnitude = min(abs(net_flow) / (total_inflows + total_outflows), 1.0)
- flow_direction = "inflow" if net_flow > 0 else "outflow"
-
- # Calculate flow velocity from ETF data
- flow_velocity = np.mean([flow["velocity"] for flow in etf_flows.values()])
-
- return FlowSignal(
- institution_type="etf_participants",
- flow_direction=flow_direction,
- flow_magnitude=flow_magnitude,
- asset_class="broad_market",
- time_horizon="short",
- confidence=0.8, # ETF flows are reliable indicators
- contrarian_signal=flow_magnitude > 0.7, # Extreme flows can be contrarian
- flow_velocity=flow_velocity
- )
-
- except Exception as e:
- logging.error(f"Error in ETF flow analysis: {e}")
- return None
-
- def _simulate_etf_flow(self, etf_symbol: str) -> Dict[str, float]:
- """Simulate ETF flow data"""
- # Base flows by ETF type
- base_flows = {
- "SPY": {"inflow": 0.6, "outflow": 0.4}, # Large cap bias
- "QQQ": {"inflow": 0.7, "outflow": 0.3}, # Tech growth bias
- "IWM": {"inflow": 0.4, "outflow": 0.6}, # Small cap outflows
- "EFA": {"inflow": 0.3, "outflow": 0.7}, # International outflows
- "EEM": {"inflow": 0.2, "outflow": 0.8}, # EM outflows
- "TLT": {"inflow": 0.5, "outflow": 0.5}, # Neutral bonds
- "GLD": {"inflow": 0.4, "outflow": 0.6} # Gold outflows
- }
-
- base = base_flows.get(etf_symbol, {"inflow": 0.5, "outflow": 0.5})
-
- # Add random variation
- noise = np.random.normal(0, 0.1)
- inflow = np.clip(base["inflow"] + noise, 0, 1)
- outflow = np.clip(base["outflow"] - noise, 0, 1)
-
- # Normalize
- total = inflow + outflow
- inflow /= total
- outflow /= total
-
- velocity = np.random.uniform(0.2, 0.8)
-
- return {"inflow": inflow, "outflow": outflow, "velocity": velocity}
-
- async def _analyze_alternative_flows(self) -> Optional[FlowSignal]:
- """Analyze flows into alternative investments"""
- try:
- # Alternatives include private equity, hedge funds, real estate, commodities
- # Simulate based on market conditions and typical allocation patterns
-
- # Institutional allocation to alternatives typically 10-30%
- base_allocation = 0.2 # 20% baseline
-
- # Factors affecting alternative flows
- market_stress = np.random.uniform(0, 1) # Would be calculated from VIX, spreads
- yield_environment = np.random.uniform(0, 1) # Low yields favor alternatives
-
- # Calculate flow direction
- alternative_attractiveness = (market_stress * 0.3 + yield_environment * 0.7)
-
- if alternative_attractiveness > 0.6:
- flow_direction = "inflow"
- flow_magnitude = (alternative_attractiveness - 0.6) / 0.4
- elif alternative_attractiveness < 0.4:
- flow_direction = "outflow"
- flow_magnitude = (0.4 - alternative_attractiveness) / 0.4
- else:
- flow_direction = "neutral"
- flow_magnitude = 0.1
-
- return FlowSignal(
- institution_type="sophisticated_institutions",
- flow_direction=flow_direction,
- flow_magnitude=flow_magnitude,
- asset_class="alternatives",
- time_horizon="long",
- confidence=0.6,
- contrarian_signal=False, # Alternative flows are strategic, not contrarian
- flow_velocity=0.2 # Alternatives move slowly
- )
-
- except Exception as e:
- logging.error(f"Error in alternative flow analysis: {e}")
- return None
-
- def _calculate_flow_metrics(self, market_data: List[DataPoint]) -> Tuple[str, float]:
- """Calculate flow direction and magnitude from market data"""
- if not market_data:
- return "neutral", 0.1
-
- # Calculate net institutional flow from position changes
- position_changes = []
- for data_point in market_data:
- change = data_point.value
- position_changes.append(change)
-
- if position_changes:
- net_flow = np.sum(position_changes)
- total_flow = np.sum(np.abs(position_changes))
-
- if total_flow > 0:
- flow_magnitude = min(abs(net_flow) / total_flow, 1.0)
- flow_direction = "inflow" if net_flow > 0 else "outflow"
- else:
- flow_magnitude = 0.1
- flow_direction = "neutral"
- else:
- flow_magnitude = 0.1
- flow_direction = "neutral"
-
- return flow_direction, flow_magnitude
-
- def _calculate_flow_velocity(self, market_data: List[DataPoint]) -> float:
- """Calculate velocity of institutional flows"""
- if len(market_data) < 2:
- return 0.3
-
- # Sort by timestamp
- sorted_data = sorted(market_data, key=lambda x: x.timestamp)
-
- # Calculate rate of change
- velocities = []
- for i in range(1, len(sorted_data)):
- time_diff = (sorted_data[i].timestamp - sorted_data[i - 1].timestamp).days
- value_diff = abs(sorted_data[i].value - sorted_data[i - 1].value)
-
- if time_diff > 0:
- velocity = value_diff / time_diff
- velocities.append(velocity)
-
- if velocities:
- avg_velocity = np.mean(velocities)
- # Normalize to 0-1 scale
- normalized_velocity = min(avg_velocity / 0.1, 1.0) # 0.1 as normalization factor
- return normalized_velocity
-
- return 0.3
-
- def _is_contrarian_flow(self, flow_magnitude: float, flow_velocity: float) -> bool:
- """Determine if flow represents contrarian opportunity"""
- # High magnitude + high velocity often indicates emotional/momentum driven flows
- # which can be contrarian signals
-
- extreme_magnitude = flow_magnitude > 0.7
- high_velocity = flow_velocity > 0.6
-
- return extreme_magnitude and high_velocity
-
- def _calculate_flow_confidence(self, market_data: List[DataPoint]) -> float:
- """Calculate confidence in flow analysis"""
- if not market_data:
- return 0.3
-
- # Factors affecting confidence
- data_points = len(market_data)
- data_quality = np.mean([dp.confidence for dp in market_data])
- data_recency = self._calculate_data_recency(market_data)
-
- # Combine factors
- volume_confidence = min(data_points / 20, 1.0) * 0.4 # Optimal ~20 data points
- quality_confidence = data_quality * 0.4
- recency_confidence = data_recency * 0.2
-
- return volume_confidence + quality_confidence + recency_confidence
-
- def _calculate_data_recency(self, market_data: List[DataPoint]) -> float:
- """Calculate how recent the data is"""
- if not market_data:
- return 0.1
-
- most_recent = max(market_data, key=lambda x: x.timestamp)
- hours_since = (datetime.now() - most_recent.timestamp).total_seconds() / 3600
-
- # Decay over 48 hours
- recency_score = max(0.1, 1.0 - hours_since / 48)
- return recency_score
-
- def _default_flow_signal(self) -> FlowSignal:
- """Return default flow signal"""
- return FlowSignal(
- institution_type="unknown",
- flow_direction="neutral",
- flow_magnitude=0.3,
- asset_class="broad_market",
- time_horizon="medium",
- confidence=0.2,
- contrarian_signal=False,
- flow_velocity=0.3
- )
-
- async def analyze_smart_money_indicators(self) -> List[SmartMoneyIndicator]:
- """Analyze various smart money flow indicators"""
- indicators = []
-
- try:
- for indicator_name, config in self.smart_money_indicators.items():
- indicator = await self._analyze_specific_indicator(indicator_name, config)
- if indicator:
- indicators.append(indicator)
-
- return indicators
-
- except Exception as e:
- logging.error(f"Error in smart money analysis: {e}")
- return []
-
- async def _analyze_specific_indicator(self, indicator_name: str,
- config: Dict) -> Optional[SmartMoneyIndicator]:
- """Analyze specific smart money indicator"""
- try:
- if indicator_name == "13f_filings":
- return await self._analyze_13f_filings(config)
- elif indicator_name == "insider_trading":
- return await self._analyze_insider_trading(config)
- elif indicator_name == "options_flow":
- return await self._analyze_options_flow(config)
- elif indicator_name == "dark_pool_activity":
- return await self._analyze_dark_pool_activity(config)
- elif indicator_name == "repo_market":
- return await self._analyze_repo_market(config)
- elif indicator_name == "etf_flows":
- return await self._analyze_etf_smart_money(config)
- else:
- return None
-
- except Exception as e:
- logging.error(f"Error analyzing {indicator_name}: {e}")
- return None
-
- async def _analyze_13f_filings(self, config: Dict) -> Optional[SmartMoneyIndicator]:
- """Analyze 13F filings for institutional position changes"""
- try:
- # Fetch institutional holdings data
- institutional_data = await self.data_manager.get_multi_source_data({
- "market": {
- "symbol": "SPY", # Use broad market as proxy
- "data_type": "institutional"
- }
- })
-
- holdings_data = institutional_data.get("market", [])
- if not holdings_data:
- # Simulate 13F analysis
- return self._simulate_13f_indicator()
-
- # Calculate position changes
- position_changes = [dp.value for dp in holdings_data]
-
- if position_changes:
- current_reading = np.mean(position_changes)
- historical_percentile = self._calculate_percentile(current_reading, position_changes)
-
- # Determine signal strength
- if abs(current_reading) > config["significance_threshold"]:
- signal_strength = "strong"
- elif abs(current_reading) > config["significance_threshold"] / 2:
- signal_strength = "moderate"
- else:
- signal_strength = "weak"
-
- # Market implication
- if current_reading > 0.02:
- market_implication = "Institutional accumulation - bullish signal"
- elif current_reading < -0.02:
- market_implication = "Institutional distribution - bearish signal"
- else:
- market_implication = "Neutral institutional positioning"
-
- return SmartMoneyIndicator(
- indicator_name="13f_filings",
- current_reading=current_reading,
- historical_percentile=historical_percentile,
- signal_strength=signal_strength,
- market_implication=market_implication,
- asset_impact={"equities": current_reading * 2} # Amplify for asset impact
- )
-
- except Exception as e:
- logging.error(f"Error in 13F analysis: {e}")
-
- return None
-
- def _simulate_13f_indicator(self) -> SmartMoneyIndicator:
- """Simulate 13F indicator when data unavailable"""
- # Simulate typical institutional behavior
- current_reading = np.random.normal(0.01, 0.02) # Slight bullish bias
- historical_percentile = np.random.uniform(0.3, 0.7)
-
- signal_strength = "moderate" if abs(current_reading) > 0.015 else "weak"
-
- if current_reading > 0.02:
- market_implication = "Simulated institutional accumulation"
- elif current_reading < -0.02:
- market_implication = "Simulated institutional distribution"
- else:
- market_implication = "Neutral simulated positioning"
-
- return SmartMoneyIndicator(
- indicator_name="13f_filings",
- current_reading=current_reading,
- historical_percentile=historical_percentile,
- signal_strength=signal_strength,
- market_implication=market_implication,
- asset_impact={"equities": current_reading * 2}
- )
-
- async def _analyze_insider_trading(self, config: Dict) -> Optional[SmartMoneyIndicator]:
- """Analyze insider trading patterns"""
- try:
- # Fetch insider trading data
- insider_data = await self.data_manager.get_multi_source_data({
- "market": {
- "symbol": "SPY",
- "data_type": "insider",
- "days_back": config["lookback_days"]
- }
- })
-
- trades = insider_data.get("market", [])
- if not trades:
- return self._simulate_insider_indicator()
-
- # Calculate insider buying vs selling
- buy_volume = sum(dp.value for dp in trades if dp.value > 0)
- sell_volume = sum(abs(dp.value) for dp in trades if dp.value < 0)
-
- total_volume = buy_volume + sell_volume
- if total_volume > 0:
- buy_sell_ratio = (buy_volume - sell_volume) / total_volume
-
- historical_percentile = np.random.uniform(0.3, 0.8) # Simulate historical context
-
- if abs(buy_sell_ratio) > config["significance_threshold"]:
- signal_strength = "strong"
- elif abs(buy_sell_ratio) > config["significance_threshold"] / 2:
- signal_strength = "moderate"
- else:
- signal_strength = "weak"
-
- if buy_sell_ratio > 0.1:
- market_implication = "Strong insider buying - bullish signal"
- elif buy_sell_ratio < -0.1:
- market_implication = "Heavy insider selling - bearish signal"
- else:
- market_implication = "Balanced insider activity"
-
- return SmartMoneyIndicator(
- indicator_name="insider_trading",
- current_reading=buy_sell_ratio,
- historical_percentile=historical_percentile,
- signal_strength=signal_strength,
- market_implication=market_implication,
- asset_impact={"individual_stocks": buy_sell_ratio * 1.5}
- )
-
- except Exception as e:
- logging.error(f"Error in insider trading analysis: {e}")
-
- return None
-
- def _simulate_insider_indicator(self) -> SmartMoneyIndicator:
- """Simulate insider trading indicator"""
- buy_sell_ratio = np.random.normal(-0.02, 0.05) # Slight selling bias (normal)
- historical_percentile = np.random.uniform(0.2, 0.8)
-
- signal_strength = "moderate" if abs(buy_sell_ratio) > 0.03 else "weak"
-
- if buy_sell_ratio > 0.05:
- market_implication = "Simulated insider buying signal"
- elif buy_sell_ratio < -0.05:
- market_implication = "Simulated insider selling pressure"
- else:
- market_implication = "Normal insider activity pattern"
-
- return SmartMoneyIndicator(
- indicator_name="insider_trading",
- current_reading=buy_sell_ratio,
- historical_percentile=historical_percentile,
- signal_strength=signal_strength,
- market_implication=market_implication,
- asset_impact={"individual_stocks": buy_sell_ratio * 1.5}
- )
-
- async def _analyze_options_flow(self, config: Dict) -> Optional[SmartMoneyIndicator]:
- """Analyze unusual options activity"""
- # Simulate options flow analysis
- # In production, would analyze actual options flow data
-
- # Simulate call/put ratio and unusual activity
- call_put_ratio = np.random.uniform(0.6, 1.4) # Normal range 0.8-1.2
- unusual_activity_ratio = np.random.uniform(0.8, 3.0) # >2.0 is unusual
-
- current_reading = (call_put_ratio - 1.0) + (unusual_activity_ratio - 1.0) / 2
- historical_percentile = np.random.uniform(0.2, 0.9)
-
- if unusual_activity_ratio > config["significance_threshold"]:
- signal_strength = "strong"
- market_implication = f"Unusual options activity detected (ratio: {unusual_activity_ratio:.1f})"
- elif unusual_activity_ratio > 1.5:
- signal_strength = "moderate"
- market_implication = "Elevated options activity"
- else:
- signal_strength = "weak"
- market_implication = "Normal options flow"
-
- return SmartMoneyIndicator(
- indicator_name="options_flow",
- current_reading=current_reading,
- historical_percentile=historical_percentile,
- signal_strength=signal_strength,
- market_implication=market_implication,
- asset_impact={"volatility": current_reading * 0.3, "equities": current_reading * 0.2}
- )
-
- async def _analyze_dark_pool_activity(self, config: Dict) -> Optional[SmartMoneyIndicator]:
- """Analyze dark pool trading activity"""
- # Simulate dark pool analysis
- # Dark pools typically 35-45% of equity volume
-
- dark_pool_percentage = np.random.uniform(0.30, 0.50)
- average_dark_pool = 0.40
-
- current_reading = dark_pool_percentage - average_dark_pool
- historical_percentile = np.random.uniform(0.2, 0.8)
-
- if abs(current_reading) > config["significance_threshold"]:
- signal_strength = "strong"
- if current_reading > 0:
- market_implication = "High dark pool activity - large institutional trades"
- else:
- market_implication = "Low dark pool activity - retail dominated"
- elif abs(current_reading) > config["significance_threshold"] / 2:
- signal_strength = "moderate"
- market_implication = "Moderate dark pool activity variation"
- else:
- signal_strength = "weak"
- market_implication = "Normal dark pool activity levels"
-
- return SmartMoneyIndicator(
- indicator_name="dark_pool_activity",
- current_reading=current_reading,
- historical_percentile=historical_percentile,
- signal_strength=signal_strength,
- market_implication=market_implication,
- asset_impact={"equities": current_reading * 0.5}
- )
-
- async def _analyze_repo_market(self, config: Dict) -> Optional[SmartMoneyIndicator]:
- """Analyze repo market for institutional liquidity conditions"""
- # Simulate repo market analysis
- # Repo rates typically track fed funds rate
-
- repo_spread = np.random.normal(0.05, 0.15) # Spread to fed funds
- current_reading = repo_spread
- historical_percentile = np.random.uniform(0.1, 0.9)
-
- if abs(current_reading) > config["significance_threshold"]:
- signal_strength = "strong"
- if current_reading > 0.1:
- market_implication = "Repo market stress - liquidity tightening"
- else:
- market_implication = "Repo market ease - abundant liquidity"
- else:
- signal_strength = "weak"
- market_implication = "Normal repo market conditions"
-
- return SmartMoneyIndicator(
- indicator_name="repo_market",
- current_reading=current_reading,
- historical_percentile=historical_percentile,
- signal_strength=signal_strength,
- market_implication=market_implication,
- asset_impact={"bonds": -current_reading * 0.8, "equities": -current_reading * 0.3}
- )
-
- async def _analyze_etf_smart_money(self, config: Dict) -> Optional[SmartMoneyIndicator]:
- """Analyze ETF flows for smart money patterns"""
- # Simulate smart money ETF analysis
- # Look for flows into sophisticated vs retail ETFs
-
- smart_money_ratio = np.random.uniform(0.4, 1.6) # Smart money vs retail flows
- current_reading = smart_money_ratio - 1.0
- historical_percentile = np.random.uniform(0.2, 0.8)
-
- if abs(current_reading) > config["significance_threshold"]:
- signal_strength = "strong"
- if current_reading > 0:
- market_implication = "Smart money ETF inflows - sophisticated accumulation"
- else:
- market_implication = "Retail ETF inflows - momentum chasing"
- else:
- signal_strength = "moderate"
- market_implication = "Balanced ETF flow patterns"
-
- return SmartMoneyIndicator(
- indicator_name="etf_flows",
- current_reading=current_reading,
- historical_percentile=historical_percentile,
- signal_strength=signal_strength,
- market_implication=market_implication,
- asset_impact={"broad_market": current_reading * 0.4}
- )
-
- def _calculate_percentile(self, current_value: float, historical_values: List[float]) -> float:
- """Calculate percentile of current value in historical context"""
- if not historical_values:
- return 0.5
-
- sorted_values = sorted(historical_values)
-
- # Find position of current value
- position = 0
- for value in sorted_values:
- if current_value > value:
- position += 1
- else:
- break
-
- return position / len(sorted_values)
-
- async def get_flow_report(self) -> Dict:
- """Generate comprehensive institutional flow report"""
- # Analyze institutional flows
- flow_signals = await self.analyze_institutional_flows()
-
- # Analyze smart money indicators
- smart_money_indicators = await self.analyze_smart_money_indicators()
-
- # Calculate overall flow sentiment
- overall_flow_sentiment = self._calculate_overall_flow_sentiment(flow_signals)
-
- # Generate LLM analysis
- llm_analysis = await self._generate_flow_llm_analysis(flow_signals, smart_money_indicators)
-
- return {
- "timestamp": datetime.now().isoformat(),
- "agent": self.name,
- "flow_analysis": {
- "overall_flow_sentiment": overall_flow_sentiment,
- "flow_classification": self._classify_flow_regime(overall_flow_sentiment),
- "institutional_signals": {
- source: {
- "direction": signal.flow_direction,
- "magnitude": signal.flow_magnitude,
- "velocity": signal.flow_velocity,
- "asset_class": signal.asset_class,
- "contrarian_signal": signal.contrarian_signal,
- "confidence": signal.confidence
- } for source, signal in flow_signals.items() if hasattr(signal, 'flow_direction')
- }
- },
- "smart_money_indicators": [{
- "indicator": indicator.indicator_name,
- "reading": indicator.current_reading,
- "percentile": indicator.historical_percentile,
- "strength": indicator.signal_strength,
- "implication": indicator.market_implication,
- "asset_impact": indicator.asset_impact
- } for indicator in smart_money_indicators],
- "flow_regime_analysis": {
- "current_regime": self._determine_flow_regime(flow_signals),
- "regime_sustainability": self._assess_regime_sustainability(flow_signals),
- "rotation_signals": self._detect_rotation_signals(flow_signals),
- "contrarian_opportunities": self._identify_contrarian_opportunities(flow_signals)
- },
- "trading_implications": {
- "momentum_signals": self._get_momentum_signals(flow_signals),
- "reversal_signals": self._get_reversal_signals(flow_signals),
- "asset_allocation": self._get_flow_based_allocation(overall_flow_sentiment),
- "position_sizing": self._get_flow_position_sizing(flow_signals)
- },
- "llm_analysis": llm_analysis,
- "monitoring_priorities": {
- "high_velocity_flows": [s for s in flow_signals.keys()
- if hasattr(flow_signals[s], 'flow_velocity') and
- flow_signals[s].flow_velocity > 0.6],
- "contrarian_signals": [s for s in flow_signals.keys()
- if hasattr(flow_signals[s], 'contrarian_signal') and
- flow_signals[s].contrarian_signal],
- "strong_smart_money": [i.indicator_name for i in smart_money_indicators
- if i.signal_strength == "strong"]
- }
- }
-
- def _calculate_overall_flow_sentiment(self, flow_signals: Dict[str, FlowSignal]) -> float:
- """Calculate overall institutional flow sentiment"""
- if not flow_signals:
- return 0.0
-
- weighted_sentiments = []
- weights = []
-
- for source, signal in flow_signals.items():
- if hasattr(signal, 'flow_direction'):
- # Convert flow direction to sentiment score
- if signal.flow_direction == "inflow":
- sentiment = signal.flow_magnitude
- elif signal.flow_direction == "outflow":
- sentiment = -signal.flow_magnitude
- else:
- sentiment = 0.0
-
- # Weight by confidence and institution importance
- weight = signal.confidence * self.institution_weights.get(signal.institution_type, 0.1)
-
- weighted_sentiments.append(sentiment * weight)
- weights.append(weight)
-
- if weights:
- return np.sum(weighted_sentiments) / np.sum(weights)
- else:
- return 0.0
-
- def _classify_flow_regime(self, flow_sentiment: float) -> str:
- """Classify current flow regime"""
- if flow_sentiment > 0.4:
- return "strong_inflows"
- elif flow_sentiment > 0.1:
- return "moderate_inflows"
- elif flow_sentiment > -0.1:
- return "balanced_flows"
- elif flow_sentiment > -0.4:
- return "moderate_outflows"
- else:
- return "strong_outflows"
-
- def _determine_flow_regime(self, flow_signals: Dict[str, FlowSignal]) -> str:
- """Determine current institutional flow regime"""
- if not flow_signals:
- return "uncertain"
-
- # Count different flow directions
- inflow_count = sum(1 for s in flow_signals.values()
- if hasattr(s, 'flow_direction') and s.flow_direction == "inflow")
- outflow_count = sum(1 for s in flow_signals.values()
- if hasattr(s, 'flow_direction') and s.flow_direction == "outflow")
-
- total_signals = len([s for s in flow_signals.values() if hasattr(s, 'flow_direction')])
-
- if total_signals == 0:
- return "uncertain"
-
- inflow_ratio = inflow_count / total_signals
-
- if inflow_ratio > 0.7:
- return "risk_on"
- elif inflow_ratio < 0.3:
- return "risk_off"
- else:
- return "rotation"
-
- def _assess_regime_sustainability(self, flow_signals: Dict[str, FlowSignal]) -> str:
- """Assess sustainability of current flow regime"""
- if not flow_signals:
- return "uncertain"
-
- # Check flow velocities and magnitudes
- high_velocity_signals = sum(1 for s in flow_signals.values()
- if hasattr(s, 'flow_velocity') and s.flow_velocity > 0.6)
-
- extreme_magnitude_signals = sum(1 for s in flow_signals.values()
- if hasattr(s, 'flow_magnitude') and s.flow_magnitude > 0.7)
-
- total_signals = len(flow_signals)
-
- if high_velocity_signals > total_signals * 0.5:
- return "unsustainable" # High velocity suggests momentum exhaustion
- elif extreme_magnitude_signals > total_signals * 0.6:
- return "late_stage" # Extreme magnitudes suggest late stage
- else:
- return "sustainable"
-
- def _detect_rotation_signals(self, flow_signals: Dict[str, FlowSignal]) -> List[str]:
- """Detect sector/style rotation signals"""
- rotation_signals = []
-
- # Look for opposing flows in different asset classes
- equity_flows = [s for s in flow_signals.values()
- if hasattr(s, 'asset_class') and s.asset_class == "equities"]
- bond_flows = [s for s in flow_signals.values()
- if hasattr(s, 'asset_class') and s.asset_class == "bonds"]
-
- if equity_flows and bond_flows:
- avg_equity_flow = np.mean([1 if s.flow_direction == "inflow" else -1
- for s in equity_flows if hasattr(s, 'flow_direction')])
- avg_bond_flow = np.mean([1 if s.flow_direction == "inflow" else -1
- for s in bond_flows if hasattr(s, 'flow_direction')])
-
- if avg_equity_flow > 0.3 and avg_bond_flow < -0.3:
- rotation_signals.append("bond_to_equity_rotation")
- elif avg_equity_flow < -0.3 and avg_bond_flow > 0.3:
- rotation_signals.append("equity_to_bond_rotation")
-
- return rotation_signals
-
- def _identify_contrarian_opportunities(self, flow_signals: Dict[str, FlowSignal]) -> List[Dict]:
- """Identify contrarian opportunities from flow extremes"""
- opportunities = []
-
- for source, signal in flow_signals.items():
- if hasattr(signal, 'contrarian_signal') and signal.contrarian_signal:
- opportunity = {
- "source": source,
- "asset_class": signal.asset_class,
- "opportunity_type": "contrarian_" + signal.flow_direction,
- "conviction": signal.flow_magnitude * signal.confidence,
- "time_horizon": signal.time_horizon
- }
- opportunities.append(opportunity)
-
- return opportunities
-
- def _get_momentum_signals(self, flow_signals: Dict[str, FlowSignal]) -> List[str]:
- """Get momentum signals from institutional flows"""
- momentum_signals = []
-
- for source, signal in flow_signals.items():
- if (hasattr(signal, 'flow_velocity') and signal.flow_velocity > 0.5 and
- hasattr(signal, 'flow_magnitude') and signal.flow_magnitude > 0.4 and
- not signal.contrarian_signal):
- momentum_signals.append(f"{signal.asset_class}_{signal.flow_direction}_momentum")
-
- return momentum_signals
-
- def _get_reversal_signals(self, flow_signals: Dict[str, FlowSignal]) -> List[str]:
- """Get reversal signals from institutional flows"""
- reversal_signals = []
-
- for source, signal in flow_signals.items():
- if hasattr(signal, 'contrarian_signal') and signal.contrarian_signal:
- reversal_signals.append(f"{signal.asset_class}_reversal_signal")
-
- return reversal_signals
-
- def _get_flow_based_allocation(self, flow_sentiment: float) -> Dict[str, str]:
- """Get asset allocation based on institutional flows"""
- if flow_sentiment > 0.3:
- return {
- "equities": "overweight",
- "bonds": "underweight",
- "alternatives": "neutral",
- "cash": "underweight"
- }
- elif flow_sentiment < -0.3:
- return {
- "equities": "underweight",
- "bonds": "overweight",
- "alternatives": "neutral",
- "cash": "overweight"
- }
- else:
- return {
- "equities": "neutral",
- "bonds": "neutral",
- "alternatives": "neutral",
- "cash": "neutral"
- }
-
- def _get_flow_position_sizing(self, flow_signals: Dict[str, FlowSignal]) -> str:
- """Get position sizing recommendation based on flows"""
- if not flow_signals:
- return "normal"
-
- high_conviction_signals = sum(1 for s in flow_signals.values()
- if hasattr(s, 'confidence') and s.confidence > 0.7)
-
- contrarian_signals = sum(1 for s in flow_signals.values()
- if hasattr(s, 'contrarian_signal') and s.contrarian_signal)
-
- total_signals = len(flow_signals)
-
- if high_conviction_signals > total_signals * 0.6:
- return "increase_size"
- elif contrarian_signals > total_signals * 0.4:
- return "reduce_size"
- else:
- return "normal"
-
- async def _generate_flow_llm_analysis(self, flow_signals: Dict[str, FlowSignal],
- smart_money_indicators: List[SmartMoneyIndicator]) -> Dict:
- """Generate LLM-enhanced institutional flow analysis"""
- try:
- # Prepare flow summary
- flow_summary = self._prepare_flow_summary(flow_signals)
- smart_money_summary = self._prepare_smart_money_summary(smart_money_indicators)
-
- prompt = f"""
- As a senior institutional flow analyst, analyze current money flows and provide investment guidance.
-
- Institutional Flow Analysis:
- {flow_summary}
-
- Smart Money Indicators:
- {smart_money_summary}
-
- Please provide:
- 1. Current institutional positioning and sentiment analysis
- 2. Smart money flow patterns and their implications
- 3. Contrarian opportunities from flow extremes
- 4. Asset allocation recommendations based on institutional flows
- 5. Timeline for potential flow reversals
- 6. Risk factors from institutional positioning
-
- Format as JSON with keys: institutional_positioning, smart_money_patterns, contrarian_opportunities,
- asset_allocation, flow_timeline, risk_factors
- """
-
- response = self.client.chat.completions.create(
- model=CONFIG.llm.deep_think_model,
- messages=[{"role": "user", "content": prompt}],
- temperature=CONFIG.llm.temperature,
- max_tokens=CONFIG.llm.max_tokens
- )
-
- return json.loads(response.choices[0].message.content)
-
- except Exception as e:
- logging.error(f"Error in LLM flow analysis: {e}")
- return {
- "institutional_positioning": "Mixed institutional flows with slight equity bias",
- "smart_money_patterns": "Moderate institutional accumulation in large caps",
- "contrarian_opportunities": "Monitor for sentiment extremes in small caps",
- "asset_allocation": "Balanced approach with equity overweight",
- "flow_timeline": "Next 4-8 weeks for potential shifts",
- "risk_factors": ["Flow velocity", "Sentiment extremes", "Liquidity conditions"]
- }
-
- def _prepare_flow_summary(self, flow_signals: Dict[str, FlowSignal]) -> str:
- """Prepare flow summary for LLM"""
- summary_lines = []
-
- for source, signal in flow_signals.items():
- if hasattr(signal, 'flow_direction'):
- summary_lines.append(
- f"{source}: {signal.flow_direction} "
- f"(Magnitude: {signal.flow_magnitude:.2f}, "
- f"Velocity: {signal.flow_velocity:.2f}, "
- f"Asset: {signal.asset_class}, "
- f"Contrarian: {signal.contrarian_signal})"
- )
-
- return "\n".join(summary_lines) if summary_lines else "Limited flow data available"
-
- def _prepare_smart_money_summary(self, indicators: List[SmartMoneyIndicator]) -> str:
- """Prepare smart money summary for LLM"""
- summary_lines = []
-
- for indicator in indicators:
- summary_lines.append(
- f"{indicator.indicator_name}: {indicator.current_reading:.3f} "
- f"({indicator.signal_strength} signal, "
- f"{indicator.historical_percentile:.0%} percentile) - "
- f"{indicator.market_implication}"
- )
-
- return "\n".join(summary_lines) if summary_lines else "Smart money indicators not available"
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/macro_cycle_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/macro_cycle_agent.py
deleted file mode 100644
index 1bb986350..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/macro_cycle_agent.py
+++ /dev/null
@@ -1,546 +0,0 @@
-# -*- coding: utf-8 -*-
-# agents/macro_cycle_agent.py - Economic Cycles Analysis Agent
-
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - economic indicators
-# - business cycle data
-# - employment statistics
-# - inflation metrics
-#
-# OUTPUT:
-# - Economic cycle phase identification
-# - Business cycle forecasts
-# - Macro trend analysis
-# - Sector rotation recommendations
-#
-# PARAMETERS:
-# - economic_indicators
-# - cycle_detection_methods
-# - forecast_horizons
-# - sector_classification
-"""
-
-import asyncio
-import numpy as np
-import pandas as pd
-from datetime import datetime, timedelta
-from typing import Dict, List, Optional, Tuple
-import logging
-from dataclasses import dataclass
-import openai
-from scipy import signal
-from scipy.stats import pearsonr
-import json
-
-from config import CONFIG
-from data_feeds import DataFeedManager, DataPoint
-
-
-@dataclass
-class CycleSignal:
- """Economic cycle signal structure"""
- cycle_type: str
- phase: str
- strength: float
- confidence: float
- duration_months: int
- next_inflection: Optional[datetime]
- supporting_indicators: List[str]
- investment_implications: Dict[str, float]
-
-
-class MacroCycleAgent:
- """Advanced economic cycle analysis agent"""
-
- def __init__(self):
- self.name = "macro_cycle"
- self.data_manager = DataFeedManager()
- self.client = openai.OpenAI(api_key=CONFIG.api.openai_api_key)
-
- # Economic cycle indicators and their weights
- self.cycle_indicators = {
- "leading": {
- "DSPIC96": 0.15, # Real Disposable Personal Income
- "HOUST": 0.20, # Housing Starts
- "AWHMAN": 0.10, # Average Weekly Hours Manufacturing
- "PAYEMS": 0.15, # Nonfarm Payrolls
- "UMCSENT": 0.15, # Consumer Sentiment
- "DEXUSEU": 0.10, # USD/EUR Exchange Rate
- "GS10": 0.15 # 10-Year Treasury Rate
- },
- "coincident": {
- "GDPC1": 0.30, # Real GDP
- "INDPRO": 0.25, # Industrial Production
- "PAYEMS": 0.25, # Employment
- "RSAFS": 0.20 # Retail Sales
- },
- "lagging": {
- "UNRATE": 0.40, # Unemployment Rate
- "CPIAUCSL": 0.35, # Consumer Price Index
- "CPILFESL": 0.25 # Core CPI
- }
- }
-
- # Cycle phases and their characteristics
- self.cycle_phases = {
- "expansion": {
- "gdp_growth": (2.0, 4.0),
- "unemployment": (3.5, 6.0),
- "inflation": (1.5, 3.0),
- "duration_months": (18, 60)
- },
- "peak": {
- "gdp_growth": (1.0, 2.5),
- "unemployment": (3.0, 5.0),
- "inflation": (2.5, 4.0),
- "duration_months": (3, 9)
- },
- "contraction": {
- "gdp_growth": (-2.0, 1.0),
- "unemployment": (5.0, 10.0),
- "inflation": (0.0, 2.0),
- "duration_months": (6, 18)
- },
- "trough": {
- "gdp_growth": (-1.0, 1.5),
- "unemployment": (6.0, 10.0),
- "inflation": (-1.0, 1.5),
- "duration_months": (2, 6)
- }
- }
-
- # Sector rotation strategy by cycle phase
- self.sector_rotation = {
- "expansion": {
- "technology": 0.25,
- "consumer_discretionary": 0.20,
- "industrials": 0.20,
- "materials": 0.15,
- "financials": 0.20
- },
- "peak": {
- "energy": 0.30,
- "materials": 0.25,
- "financials": 0.20,
- "real_estate": 0.15,
- "utilities": 0.10
- },
- "contraction": {
- "healthcare": 0.25,
- "consumer_staples": 0.25,
- "utilities": 0.20,
- "telecommunications": 0.15,
- "government_bonds": 0.15
- },
- "trough": {
- "technology": 0.30,
- "financials": 0.25,
- "consumer_discretionary": 0.20,
- "industrials": 0.15,
- "small_caps": 0.10
- }
- }
-
- async def analyze_business_cycle(self) -> CycleSignal:
- """Comprehensive business cycle analysis"""
- try:
- # Fetch economic indicators
- economic_data = await self._fetch_cycle_indicators()
-
- # Calculate composite leading index
- leading_index = self._calculate_composite_index(economic_data, "leading")
- coincident_index = self._calculate_composite_index(economic_data, "coincident")
-
- # Determine cycle phase
- current_phase = self._determine_cycle_phase(leading_index, coincident_index)
-
- # Calculate cycle strength and confidence
- cycle_strength = self._calculate_cycle_strength(economic_data, current_phase)
- confidence = self._calculate_confidence(economic_data, current_phase)
-
- # Predict next inflection point
- next_inflection = self._predict_inflection_point(leading_index, current_phase)
-
- # Generate LLM-enhanced analysis
- llm_analysis = await self._generate_llm_analysis(economic_data, current_phase)
-
- # Get investment implications
- investment_implications = self.sector_rotation.get(current_phase, {})
-
- return CycleSignal(
- cycle_type="business_cycle",
- phase=current_phase,
- strength=cycle_strength,
- confidence=confidence,
- duration_months=self._estimate_phase_duration(current_phase, economic_data),
- next_inflection=next_inflection,
- supporting_indicators=list(economic_data.keys()),
- investment_implications=investment_implications
- )
-
- except Exception as e:
- logging.error(f"Error in business cycle analysis: {e}")
- return self._default_cycle_signal()
-
- async def _fetch_cycle_indicators(self) -> Dict[str, pd.Series]:
- """Fetch all economic indicators for cycle analysis"""
- data_requests = {}
-
- # Collect all unique indicators
- all_indicators = set()
- for category in self.cycle_indicators.values():
- all_indicators.update(category.keys())
-
- # Create data requests for each indicator
- for indicator in all_indicators:
- data_requests[f"economic_{indicator}"] = {
- "series_id": indicator,
- "limit": 240 # 20 years of monthly data
- }
-
- # Fetch data concurrently
- raw_data = await self.data_manager.get_multi_source_data({
- "economic": data_requests
- })
-
- # Process into time series
- processed_data = {}
- for key, data_points in raw_data.get("economic", {}).items():
- if data_points:
- df = pd.DataFrame([{
- 'date': dp.timestamp,
- 'value': dp.value
- } for dp in data_points])
- df['date'] = pd.to_datetime(df['date'])
- df = df.sort_values('date').set_index('date')
-
- # Calculate year-over-year growth rates
- indicator_name = key.replace("economic_", "")
- processed_data[indicator_name] = df['value'].pct_change(12) * 100
-
- return processed_data
-
- def _calculate_composite_index(self, data: Dict[str, pd.Series],
- indicator_type: str) -> pd.Series:
- """Calculate weighted composite index for indicator category"""
- if indicator_type not in self.cycle_indicators:
- return pd.Series()
-
- weights = self.cycle_indicators[indicator_type]
- composite_values = []
- dates = None
-
- for indicator, weight in weights.items():
- if indicator in data and not data[indicator].empty:
- series = data[indicator].dropna()
- if dates is None:
- dates = series.index
- else:
- dates = dates.intersection(series.index)
-
- if dates is None or len(dates) == 0:
- return pd.Series()
-
- composite_index = pd.Series(0.0, index=dates)
- total_weight = 0
-
- for indicator, weight in weights.items():
- if indicator in data and not data[indicator].empty:
- series = data[indicator].reindex(dates).fillna(method='ffill')
- composite_index += series * weight
- total_weight += weight
-
- if total_weight > 0:
- composite_index /= total_weight
-
- return composite_index
-
- def _determine_cycle_phase(self, leading_index: pd.Series,
- coincident_index: pd.Series) -> str:
- """Determine current business cycle phase"""
- if leading_index.empty or coincident_index.empty:
- return "expansion" # Default assumption
-
- # Get recent trends
- leading_trend = self._calculate_trend(leading_index, periods=6)
- coincident_trend = self._calculate_trend(coincident_index, periods=3)
-
- # Recent values
- leading_recent = leading_index.iloc[-3:].mean()
- coincident_recent = coincident_index.iloc[-3:].mean()
-
- # Phase determination logic
- if leading_trend > 0 and coincident_trend > 0 and coincident_recent > 0:
- return "expansion"
- elif leading_trend < 0 and coincident_trend > 0 and coincident_recent > 1:
- return "peak"
- elif leading_trend < 0 and coincident_trend < 0:
- return "contraction"
- elif leading_trend > 0 and coincident_trend < 0 and coincident_recent < -1:
- return "trough"
- else:
- return "expansion" # Default
-
- def _calculate_trend(self, series: pd.Series, periods: int = 6) -> float:
- """Calculate trend over specified periods"""
- if len(series) < periods:
- return 0.0
-
- recent_data = series.iloc[-periods:]
- x = np.arange(len(recent_data))
-
- try:
- slope, _ = np.polyfit(x, recent_data.values, 1)
- return slope
- except:
- return 0.0
-
- def _calculate_cycle_strength(self, data: Dict[str, pd.Series], phase: str) -> float:
- """Calculate strength of current cycle phase"""
- if phase not in self.cycle_phases:
- return 0.5
-
- phase_characteristics = self.cycle_phases[phase]
- strength_scores = []
-
- # Check GDP growth if available
- if "GDPC1" in data and not data["GDPC1"].empty:
- gdp_growth = data["GDPC1"].iloc[-1]
- gdp_range = phase_characteristics["gdp_growth"]
- gdp_score = self._score_in_range(gdp_growth, gdp_range)
- strength_scores.append(gdp_score * 0.4)
-
- # Check unemployment if available
- if "UNRATE" in data and not data["UNRATE"].empty:
- unemployment = data["UNRATE"].iloc[-1]
- unemp_range = phase_characteristics["unemployment"]
- unemp_score = self._score_in_range(unemployment, unemp_range)
- strength_scores.append(unemp_score * 0.3)
-
- # Check inflation if available
- if "CPIAUCSL" in data and not data["CPIAUCSL"].empty:
- inflation = data["CPIAUCSL"].iloc[-1]
- inf_range = phase_characteristics["inflation"]
- inf_score = self._score_in_range(inflation, inf_range)
- strength_scores.append(inf_score * 0.3)
-
- return np.mean(strength_scores) if strength_scores else 0.5
-
- def _score_in_range(self, value: float, range_tuple: Tuple[float, float]) -> float:
- """Score how well a value fits within expected range"""
- min_val, max_val = range_tuple
-
- if min_val <= value <= max_val:
- # Perfect fit
- return 1.0
- elif value < min_val:
- # Below range - score based on distance
- distance = min_val - value
- return max(0.0, 1.0 - distance / min_val)
- else:
- # Above range - score based on distance
- distance = value - max_val
- return max(0.0, 1.0 - distance / max_val)
-
- def _calculate_confidence(self, data: Dict[str, pd.Series], phase: str) -> float:
- """Calculate confidence in cycle phase determination"""
- confidence_factors = []
-
- # Data availability factor
- available_indicators = len([k for k, v in data.items() if not v.empty])
- total_indicators = sum(len(cat) for cat in self.cycle_indicators.values())
- data_coverage = available_indicators / total_indicators
- confidence_factors.append(data_coverage * 0.3)
-
- # Data recency factor
- recent_data_count = 0
- for series in data.values():
- if not series.empty and series.index[-1] >= datetime.now() - timedelta(days=90):
- recent_data_count += 1
-
- recency_factor = recent_data_count / len(data) if data else 0
- confidence_factors.append(recency_factor * 0.3)
-
- # Consistency factor - how well indicators agree
- phase_consistency = self._calculate_phase_consistency(data, phase)
- confidence_factors.append(phase_consistency * 0.4)
-
- return np.mean(confidence_factors)
-
- def _calculate_phase_consistency(self, data: Dict[str, pd.Series], phase: str) -> float:
- """Calculate how consistently indicators point to the same phase"""
- if phase not in self.cycle_phases:
- return 0.5
-
- consistent_indicators = 0
- total_indicators = 0
-
- phase_ranges = self.cycle_phases[phase]
-
- for indicator, series in data.items():
- if series.empty:
- continue
-
- recent_value = series.iloc[-1]
- total_indicators += 1
-
- # Check if indicator value is consistent with phase
- if indicator == "GDPC1" and "gdp_growth" in phase_ranges:
- if phase_ranges["gdp_growth"][0] <= recent_value <= phase_ranges["gdp_growth"][1]:
- consistent_indicators += 1
- elif indicator == "UNRATE" and "unemployment" in phase_ranges:
- if phase_ranges["unemployment"][0] <= recent_value <= phase_ranges["unemployment"][1]:
- consistent_indicators += 1
- elif indicator in ["CPIAUCSL", "CPILFESL"] and "inflation" in phase_ranges:
- if phase_ranges["inflation"][0] <= recent_value <= phase_ranges["inflation"][1]:
- consistent_indicators += 1
-
- return consistent_indicators / total_indicators if total_indicators > 0 else 0.5
-
- def _predict_inflection_point(self, leading_index: pd.Series, phase: str) -> Optional[datetime]:
- """Predict next cycle inflection point"""
- if leading_index.empty:
- return None
-
- try:
- # Calculate rate of change in leading indicators
- roc = leading_index.pct_change(3).dropna()
-
- if len(roc) < 6:
- return None
-
- # Find trend acceleration/deceleration
- recent_roc = roc.iloc[-6:]
- trend_change = np.diff(recent_roc.values)
-
- # Estimate time to inflection based on trend
- if phase in ["expansion", "contraction"]:
- # Look for trend reversals
- if len(trend_change) >= 3 and np.all(trend_change[-3:] < 0):
- # Decelerating trend suggests inflection in 3-9 months
- months_ahead = np.random.randint(3, 10)
- else:
- # Stable trend suggests inflection in 6-18 months
- months_ahead = np.random.randint(6, 19)
- else:
- # Peak or trough phases are typically shorter
- months_ahead = np.random.randint(2, 7)
-
- return datetime.now() + timedelta(days=months_ahead * 30)
-
- except Exception:
- return None
-
- def _estimate_phase_duration(self, phase: str, data: Dict[str, pd.Series]) -> int:
- """Estimate duration of current phase"""
- if phase not in self.cycle_phases:
- return 12
-
- duration_range = self.cycle_phases[phase]["duration_months"]
-
- # Base estimate from historical averages
- base_duration = np.mean(duration_range)
-
- # Adjust based on current strength
- current_strength = self._calculate_cycle_strength(data, phase)
-
- # Stronger phases tend to last longer
- duration_adjustment = (current_strength - 0.5) * 0.3
- adjusted_duration = base_duration * (1 + duration_adjustment)
-
- return int(np.clip(adjusted_duration, duration_range[0], duration_range[1]))
-
- async def _generate_llm_analysis(self, data: Dict[str, pd.Series], phase: str) -> Dict:
- """Generate LLM-enhanced cycle analysis"""
- try:
- # Prepare data summary for LLM
- data_summary = self._prepare_data_summary(data)
-
- prompt = f"""
- As a senior macroeconomic analyst, analyze the current business cycle phase and provide insights.
-
- Current Phase: {phase}
-
- Economic Indicators Summary:
- {data_summary}
-
- Please provide:
- 1. Confirmation or challenge of the current phase assessment
- 2. Key risks to monitor
- 3. Expected duration of current phase
- 4. Investment strategy recommendations
- 5. Probability of recession in next 12 months (0-100%)
-
- Format as JSON with keys: phase_assessment, key_risks, duration_estimate, investment_strategy, recession_probability
- """
-
- response = self.client.chat.completions.create(
- model=CONFIG.llm.deep_think_model,
- messages=[{"role": "user", "content": prompt}],
- temperature=CONFIG.llm.temperature,
- max_tokens=CONFIG.llm.max_tokens
- )
-
- return json.loads(response.choices[0].message.content)
-
- except Exception as e:
- logging.error(f"Error in LLM analysis: {e}")
- return {
- "phase_assessment": f"Current phase appears to be {phase}",
- "key_risks": ["Data quality", "Model uncertainty"],
- "duration_estimate": "6-12 months",
- "investment_strategy": "Diversified approach recommended",
- "recession_probability": 25
- }
-
- def _prepare_data_summary(self, data: Dict[str, pd.Series]) -> str:
- """Prepare human-readable data summary for LLM"""
- summary_lines = []
-
- for indicator, series in data.items():
- if not series.empty:
- latest_value = series.iloc[-1]
- trend = self._calculate_trend(series, 6)
-
- trend_desc = "rising" if trend > 0.1 else "falling" if trend < -0.1 else "stable"
- summary_lines.append(f"{indicator}: {latest_value:.2f}% ({trend_desc})")
-
- return "\n".join(summary_lines)
-
- def _default_cycle_signal(self) -> CycleSignal:
- """Return default cycle signal in case of errors"""
- return CycleSignal(
- cycle_type="business_cycle",
- phase="expansion",
- strength=0.5,
- confidence=0.3,
- duration_months=12,
- next_inflection=datetime.now() + timedelta(days=365),
- supporting_indicators=[],
- investment_implications=self.sector_rotation["expansion"]
- )
-
- async def get_cycle_report(self) -> Dict:
- """Generate comprehensive cycle analysis report"""
- cycle_signal = await self.analyze_business_cycle()
-
- return {
- "timestamp": datetime.now().isoformat(),
- "agent": self.name,
- "cycle_analysis": {
- "current_phase": cycle_signal.phase,
- "strength": cycle_signal.strength,
- "confidence": cycle_signal.confidence,
- "duration_estimate": cycle_signal.duration_months,
- "next_inflection": cycle_signal.next_inflection.isoformat() if cycle_signal.next_inflection else None
- },
- "investment_implications": cycle_signal.investment_implications,
- "supporting_indicators": cycle_signal.supporting_indicators,
- "risk_assessment": {
- "phase_transition_risk": 1 - cycle_signal.confidence,
- "data_quality_risk": 1 - len(cycle_signal.supporting_indicators) / 10,
- "model_uncertainty": 0.2
- }
- }
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/regulatory_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/regulatory_agent.py
deleted file mode 100644
index a68b3ccaf..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/regulatory_agent.py
+++ /dev/null
@@ -1,924 +0,0 @@
-# -*- coding: utf-8 -*-
-# agents/regulatory_agent.py - Regulatory Intelligence Agent
-
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - regulatory announcements
-# - compliance updates
-# - policy changes
-# - enforcement actions
-#
-# OUTPUT:
-# - Regulatory impact assessments
-# - Compliance requirement updates
-# - Policy change analysis
-# - Risk mitigation recommendations
-#
-# PARAMETERS:
-# - regulatory_sources
-# - compliance_frameworks
-# - risk_categories
-# - monitoring_frequency
-"""
-
-import asyncio
-import numpy as np
-import pandas as pd
-from datetime import datetime, timedelta
-from typing import Dict, List, Optional, Tuple
-import logging
-from dataclasses import dataclass
-import openai
-import json
-import re
-from collections import defaultdict
-
-from config import CONFIG
-from data_feeds import DataFeedManager, DataPoint
-
-
-@dataclass
-class RegulatorySignal:
- """Regulatory change signal structure"""
- regulation_type: str
- jurisdiction: str
- impact_level: int # 1-10 scale
- implementation_timeline: str
- affected_sectors: List[str]
- market_impact: Dict[str, float]
- compliance_cost: float
- competitive_advantage: Dict[str, float]
- confidence: float
-
-
-@dataclass
-class PolicyChange:
- """Policy change monitoring structure"""
- policy_area: str
- change_type: str # proposed, enacted, implemented
- probability_passage: float
- economic_impact: Dict[str, float]
- sector_winners: List[str]
- sector_losers: List[str]
- timeline: str
-
-
-class RegulatoryAgent:
- """Advanced regulatory intelligence and policy change analysis"""
-
- def __init__(self):
- self.name = "regulatory"
- self.data_manager = DataFeedManager()
- self.client = openai.OpenAI(api_key=CONFIG.api.openai_api_key)
-
- # Regulatory domains and their market impact weights
- self.regulatory_domains = {
- "financial_regulation": {
- "banking_rules": 0.25,
- "securities_regulation": 0.20,
- "derivatives_oversight": 0.15,
- "crypto_regulation": 0.15,
- "payment_systems": 0.10,
- "systemic_risk": 0.15
- },
- "environmental_regulation": {
- "carbon_pricing": 0.30,
- "renewable_mandates": 0.25,
- "emission_standards": 0.20,
- "plastic_bans": 0.10,
- "water_regulation": 0.08,
- "biodiversity_rules": 0.07
- },
- "technology_regulation": {
- "data_privacy": 0.25,
- "ai_governance": 0.20,
- "platform_regulation": 0.20,
- "cybersecurity_rules": 0.15,
- "semiconductor_controls": 0.20
- },
- "healthcare_regulation": {
- "drug_pricing": 0.30,
- "medical_device_approval": 0.25,
- "telehealth_rules": 0.15,
- "insurance_regulation": 0.15,
- "public_health_policy": 0.15
- },
- "tax_policy": {
- "corporate_tax_rates": 0.35,
- "international_tax_coordination": 0.25,
- "digital_services_tax": 0.20,
- "carbon_tax": 0.20
- }
- }
-
- # Sector impact mapping from regulatory changes
- self.sector_impact_map = {
- "financial_regulation": {
- "banks": -0.6,
- "insurance": -0.4,
- "asset_management": -0.3,
- "fintech": -0.5,
- "real_estate": -0.2,
- "consumer_finance": -0.4
- },
- "environmental_regulation": {
- "oil_gas": -0.8,
- "utilities": 0.3,
- "renewable_energy": 0.7,
- "automotive": -0.4,
- "chemicals": -0.5,
- "materials": -0.3,
- "industrials": -0.2
- },
- "technology_regulation": {
- "big_tech": -0.7,
- "social_media": -0.8,
- "semiconductors": -0.4,
- "cybersecurity": 0.5,
- "cloud_services": -0.3,
- "telecommunications": -0.2
- },
- "healthcare_regulation": {
- "pharmaceuticals": -0.5,
- "biotechnology": -0.3,
- "medical_devices": -0.4,
- "health_insurance": -0.6,
- "hospitals": -0.3,
- "telehealth": 0.4
- },
- "tax_policy": {
- "multinational_corps": -0.6,
- "domestic_focused": 0.2,
- "high_margin_tech": -0.5,
- "capital_intensive": 0.1,
- "dividend_stocks": -0.3
- }
- }
-
- # Regulatory keyword patterns
- self.regulatory_keywords = {
- "proposal_stage": [
- "proposed rule", "draft regulation", "consultation paper",
- "request for comment", "policy proposal", "legislative draft"
- ],
- "advancement_stage": [
- "committee approval", "senate passage", "house passage",
- "regulatory approval", "agency adoption", "cabinet approval"
- ],
- "implementation_stage": [
- "effective date", "compliance deadline", "enforcement begins",
- "mandatory compliance", "phased implementation", "grace period"
- ],
- "enforcement_action": [
- "regulatory fine", "enforcement action", "compliance violation",
- "penalty imposed", "consent order", "regulatory sanction"
- ]
- }
-
- # Jurisdictional weights based on global market impact
- self.jurisdiction_weights = {
- "United_States": 0.35,
- "European_Union": 0.25,
- "China": 0.20,
- "United_Kingdom": 0.10,
- "Japan": 0.05,
- "Other": 0.05
- }
-
- async def analyze_regulatory_landscape(self) -> List[RegulatorySignal]:
- """Comprehensive regulatory landscape analysis"""
- signals = []
-
- try:
- # Analyze each regulatory domain
- for domain, regulations in self.regulatory_domains.items():
- domain_signals = await self._analyze_regulatory_domain(domain, regulations)
- signals.extend(domain_signals)
-
- # Sort by impact level and confidence
- signals.sort(key=lambda x: x.impact_level * x.confidence, reverse=True)
-
- return signals[:15] # Return top 15 regulatory signals
-
- except Exception as e:
- logging.error(f"Error in regulatory landscape analysis: {e}")
- return [self._default_regulatory_signal()]
-
- async def _analyze_regulatory_domain(self, domain: str, regulations: Dict[str, float]) -> List[RegulatorySignal]:
- """Analyze specific regulatory domain"""
- domain_signals = []
-
- # Get news data for this domain
- news_data = await self._fetch_regulatory_news(domain, list(regulations.keys()))
-
- for regulation, weight in regulations.items():
- try:
- # Filter news for this specific regulation
- relevant_news = [news for news in news_data
- if self._is_relevant_to_regulation(news, regulation, domain)]
-
- if not relevant_news:
- continue
-
- # Analyze regulatory stage and probability
- stage_analysis = self._analyze_regulatory_stage(relevant_news)
-
- # Calculate impact level
- impact_level = self._calculate_regulatory_impact(relevant_news, regulation, domain, weight)
-
- # Determine affected sectors
- affected_sectors = self._get_affected_sectors(domain, impact_level)
-
- # Calculate market impact
- market_impact = self._calculate_market_impact(domain, regulation, impact_level)
-
- # Estimate compliance costs
- compliance_cost = self._estimate_compliance_cost(regulation, domain, impact_level)
-
- # Identify competitive advantages
- competitive_advantage = self._analyze_competitive_impact(domain, regulation, relevant_news)
-
- # Generate timeline
- timeline = self._estimate_implementation_timeline(stage_analysis, relevant_news)
-
- # Calculate confidence
- confidence = self._calculate_regulatory_confidence(relevant_news, stage_analysis)
-
- signal = RegulatorySignal(
- regulation_type=f"{domain}_{regulation}",
- jurisdiction=self._determine_jurisdiction(relevant_news),
- impact_level=impact_level,
- implementation_timeline=timeline,
- affected_sectors=affected_sectors,
- market_impact=market_impact,
- compliance_cost=compliance_cost,
- competitive_advantage=competitive_advantage,
- confidence=confidence
- )
-
- domain_signals.append(signal)
-
- except Exception as e:
- logging.error(f"Error analyzing regulation {regulation}: {e}")
- continue
-
- return domain_signals
-
- async def _fetch_regulatory_news(self, domain: str, regulations: List[str]) -> List[DataPoint]:
- """Fetch regulatory news for specific domain"""
- all_news = []
-
- # Create domain-specific search queries
- domain_queries = {
- "financial_regulation": ["banking regulation", "financial oversight", "securities rules",
- "fintech regulation"],
- "environmental_regulation": ["environmental regulation", "carbon policy", "emissions standards",
- "green legislation"],
- "technology_regulation": ["tech regulation", "data privacy", "ai governance", "platform oversight"],
- "healthcare_regulation": ["healthcare policy", "drug regulation", "medical device approval",
- "health insurance"],
- "tax_policy": ["tax reform", "corporate tax", "international taxation", "digital tax"]
- }
-
- queries = domain_queries.get(domain, [domain.replace("_", " ")])
-
- for query in queries:
- try:
- news_data = await self.data_manager.get_multi_source_data({
- "news": {
- "query": query,
- "sources": ["reuters", "bloomberg", "wsj", "ft"],
- "hours_back": 168 # 1 week
- }
- })
-
- if "news" in news_data:
- all_news.extend(news_data["news"])
-
- except Exception as e:
- logging.error(f"Error fetching regulatory news for {query}: {e}")
- continue
-
- return all_news
-
- def _is_relevant_to_regulation(self, news: DataPoint, regulation: str, domain: str) -> bool:
- """Check if news is relevant to specific regulation"""
- text = (news.value + " " + news.metadata.get("description", "")).lower()
-
- # Create regulation-specific keywords
- regulation_keywords = {
- "banking_rules": ["basel", "capital requirements", "stress test", "bank supervision"],
- "carbon_pricing": ["carbon tax", "cap and trade", "emissions trading", "carbon border"],
- "data_privacy": ["gdpr", "data protection", "privacy regulation", "data governance"],
- "drug_pricing": ["prescription drug", "medicare negotiation", "drug pricing", "pharmaceutical"],
- "ai_governance": ["artificial intelligence", "ai regulation", "algorithmic oversight", "ai safety"]
- }
-
- keywords = regulation_keywords.get(regulation, [regulation.replace("_", " ")])
-
- # Also check for regulatory action keywords
- regulatory_action_keywords = [
- "regulation", "policy", "rule", "legislation", "bill", "act",
- "oversight", "compliance", "enforcement", "approval", "mandate"
- ]
-
- has_regulation_keyword = any(keyword in text for keyword in keywords)
- has_action_keyword = any(keyword in text for keyword in regulatory_action_keywords)
-
- return has_regulation_keyword and has_action_keyword
-
- def _analyze_regulatory_stage(self, news: List[DataPoint]) -> Dict[str, float]:
- """Analyze what stage regulations are in"""
- stage_scores = {
- "proposal": 0.0,
- "advancement": 0.0,
- "implementation": 0.0,
- "enforcement": 0.0
- }
-
- total_articles = len(news)
- if total_articles == 0:
- return stage_scores
-
- for article in news:
- text = article.value.lower()
-
- # Count stage indicators
- for stage, keywords in self.regulatory_keywords.items():
- stage_name = stage.replace("_stage", "").replace("_action", "")
- for keyword in keywords:
- if keyword in text:
- stage_scores[stage_name] += article.confidence / total_articles
-
- return stage_scores
-
- def _calculate_regulatory_impact(self, news: List[DataPoint], regulation: str,
- domain: str, weight: float) -> int:
- """Calculate regulatory impact level (1-10)"""
- if not news:
- return 3
-
- # Base impact levels by regulation type
- base_impacts = {
- "banking_rules": 7,
- "carbon_pricing": 8,
- "data_privacy": 6,
- "drug_pricing": 8,
- "corporate_tax_rates": 9,
- "ai_governance": 5,
- "securities_regulation": 6
- }
-
- base_impact = base_impacts.get(regulation, 5)
-
- # Analyze news intensity and scope
- high_impact_keywords = [
- "sweeping changes", "major reform", "significant impact", "industry transformation",
- "mandatory compliance", "substantial penalties", "widespread adoption",
- "market disruption", "regulatory overhaul", "unprecedented"
- ]
-
- scope_indicators = [
- "global", "international", "nationwide", "industry-wide", "comprehensive",
- "all companies", "every business", "mandatory for all"
- ]
-
- intensity_score = 0
- scope_score = 0
-
- for article in news:
- text = article.value.lower()
- intensity_score += sum(1 for keyword in high_impact_keywords if keyword in text)
- scope_score += sum(1 for keyword in scope_indicators if keyword in text)
-
- # Adjust base impact
- if news:
- intensity_factor = min(intensity_score / len(news), 2.0)
- scope_factor = min(scope_score / len(news), 1.5)
- weight_factor = weight * 2 # Domain weight influence
-
- adjusted_impact = base_impact + intensity_factor + scope_factor + weight_factor
- else:
- adjusted_impact = base_impact
-
- return int(np.clip(adjusted_impact, 1, 10))
-
- def _get_affected_sectors(self, domain: str, impact_level: int) -> List[str]:
- """Get sectors affected by regulatory domain"""
- if domain not in self.sector_impact_map:
- return ["broad_market"]
-
- sector_impacts = self.sector_impact_map[domain]
-
- # Filter sectors by impact threshold
- threshold = 0.2 if impact_level > 7 else 0.3 if impact_level > 5 else 0.4
-
- affected_sectors = []
- for sector, impact in sector_impacts.items():
- if abs(impact) >= threshold:
- affected_sectors.append(sector)
-
- return affected_sectors or ["broad_market"]
-
- def _calculate_market_impact(self, domain: str, regulation: str, impact_level: int) -> Dict[str, float]:
- """Calculate expected market impact by asset class"""
- if domain not in self.sector_impact_map:
- return {"broad_market": 0.0}
-
- sector_impacts = self.sector_impact_map[domain]
-
- # Scale impacts by regulation impact level
- impact_multiplier = impact_level / 10.0
-
- market_impacts = {}
- for sector, base_impact in sector_impacts.items():
- scaled_impact = base_impact * impact_multiplier
- market_impacts[sector] = np.clip(scaled_impact, -1.0, 1.0)
-
- return market_impacts
-
- def _estimate_compliance_cost(self, regulation: str, domain: str, impact_level: int) -> float:
- """Estimate compliance cost as percentage of revenue"""
- # Base compliance costs by regulation type (% of revenue)
- base_costs = {
- "banking_rules": 0.015, # 1.5% of revenue
- "data_privacy": 0.008, # 0.8% of revenue
- "emissions_standards": 0.012, # 1.2% of revenue
- "drug_pricing": 0.005, # 0.5% of revenue
- "cybersecurity_rules": 0.010 # 1.0% of revenue
- }
-
- base_cost = base_costs.get(regulation, 0.005)
-
- # Scale by impact level
- impact_multiplier = impact_level / 5.0 # Normalize around level 5
-
- return base_cost * impact_multiplier
-
- def _analyze_competitive_impact(self, domain: str, regulation: str,
- news: List[DataPoint]) -> Dict[str, float]:
- """Analyze which companies/sectors gain competitive advantage"""
- competitive_advantages = {}
-
- # Analyze news for competitive implications
- advantage_keywords = {
- "large_companies": ["economies of scale", "large companies benefit", "big players advantage"],
- "incumbents": ["existing players", "incumbent advantage", "barriers to entry"],
- "tech_leaders": ["technology advantage", "innovation leaders", "digital transformation"],
- "compliance_specialists": ["compliance expertise", "regulatory experience", "specialized knowledge"]
- }
-
- for company_type, keywords in advantage_keywords.items():
- advantage_score = 0.0
-
- for article in news:
- text = article.value.lower()
- keyword_count = sum(1 for keyword in keywords if keyword in text)
- advantage_score += keyword_count * article.confidence
-
- if news and advantage_score > 0:
- competitive_advantages[company_type] = min(advantage_score / len(news), 1.0)
-
- return competitive_advantages
-
- def _estimate_implementation_timeline(self, stage_analysis: Dict[str, float],
- news: List[DataPoint]) -> str:
- """Estimate regulatory implementation timeline"""
- # Determine current stage
- current_stage = max(stage_analysis.items(), key=lambda x: x[1])[0]
-
- # Timeline estimates by stage
- timeline_estimates = {
- "proposal": "12-24 months",
- "advancement": "6-18 months",
- "implementation": "3-12 months",
- "enforcement": "Immediate"
- }
-
- base_timeline = timeline_estimates.get(current_stage, "12-24 months")
-
- # Look for specific timeline mentions in news
- timeline_patterns = [
- r"(\d+)\s*months?",
- r"(\d+)\s*years?",
- r"by\s+(\d{4})",
- r"effective\s+(\w+\s+\d{1,2},?\s+\d{4})"
- ]
-
- for article in news:
- text = article.value
- for pattern in timeline_patterns:
- matches = re.findall(pattern, text, re.IGNORECASE)
- if matches:
- # Found specific timeline mention
- return f"Specific timeline mentioned: {matches[0]}"
-
- return base_timeline
-
- def _determine_jurisdiction(self, news: List[DataPoint]) -> str:
- """Determine primary jurisdiction from news"""
- jurisdiction_keywords = {
- "United_States": ["usa", "united states", "sec", "fed", "congress", "senate", "house"],
- "European_Union": ["eu", "european union", "brussels", "european commission", "esma"],
- "China": ["china", "beijing", "pboc", "csrc", "chinese regulators"],
- "United_Kingdom": ["uk", "united kingdom", "fca", "pra", "bank of england"],
- "Japan": ["japan", "jfsa", "boj", "bank of japan"]
- }
-
- jurisdiction_scores = {j: 0 for j in jurisdiction_keywords.keys()}
-
- for article in news:
- text = article.value.lower()
- for jurisdiction, keywords in jurisdiction_keywords.items():
- score = sum(1 for keyword in keywords if keyword in text)
- jurisdiction_scores[jurisdiction] += score * article.confidence
-
- if any(jurisdiction_scores.values()):
- return max(jurisdiction_scores.items(), key=lambda x: x[1])[0]
-
- return "Multiple/Global"
-
- def _calculate_regulatory_confidence(self, news: List[DataPoint],
- stage_analysis: Dict[str, float]) -> float:
- """Calculate confidence in regulatory analysis"""
- confidence_factors = []
-
- # News volume and quality
- if news:
- news_confidence = min(len(news) / 10, 1.0) * 0.3 # Optimal around 10 articles
- source_quality = np.mean([article.confidence for article in news]) * 0.4
- confidence_factors.extend([news_confidence, source_quality])
- else:
- confidence_factors.extend([0.1, 0.2])
-
- # Stage clarity - clearer stage = higher confidence
- max_stage_score = max(stage_analysis.values()) if stage_analysis else 0
- stage_confidence = max_stage_score * 0.3
- confidence_factors.append(stage_confidence)
-
- return np.sum(confidence_factors)
-
- def _default_regulatory_signal(self) -> RegulatorySignal:
- """Return default regulatory signal"""
- return RegulatorySignal(
- regulation_type="general_regulatory_uncertainty",
- jurisdiction="Global",
- impact_level=5,
- implementation_timeline="12-24 months",
- affected_sectors=["broad_market"],
- market_impact={"broad_market": 0.0},
- compliance_cost=0.005,
- competitive_advantage={},
- confidence=0.3
- )
-
- async def analyze_policy_changes(self) -> List[PolicyChange]:
- """Analyze upcoming policy changes and their market implications"""
- policy_changes = []
-
- policy_areas = [
- "tax_reform", "healthcare_policy", "infrastructure_spending",
- "trade_policy", "energy_policy", "immigration_policy"
- ]
-
- for policy_area in policy_areas:
- try:
- change = await self._analyze_specific_policy(policy_area)
- if change:
- policy_changes.append(change)
- except Exception as e:
- logging.error(f"Error analyzing policy {policy_area}: {e}")
- continue
-
- return policy_changes
-
- async def _analyze_specific_policy(self, policy_area: str) -> Optional[PolicyChange]:
- """Analyze specific policy area for changes"""
- # Get policy-related news
- news_data = await self.data_manager.get_multi_source_data({
- "news": {
- "query": policy_area.replace("_", " "),
- "sources": ["reuters", "bloomberg", "wsj"],
- "hours_back": 72
- }
- })
-
- news = news_data.get("news", [])
- if not news:
- return None
-
- # Analyze policy change type and probability
- change_type = self._determine_policy_change_type(news)
- probability = self._calculate_passage_probability(news, policy_area)
-
- if probability < 0.2: # Skip low-probability changes
- return None
-
- # Calculate economic impact
- economic_impact = self._calculate_policy_economic_impact(policy_area, news)
-
- # Identify winners and losers
- winners, losers = self._identify_policy_winners_losers(policy_area)
-
- # Estimate timeline
- timeline = self._estimate_policy_timeline(news, change_type)
-
- return PolicyChange(
- policy_area=policy_area,
- change_type=change_type,
- probability_passage=probability,
- economic_impact=economic_impact,
- sector_winners=winners,
- sector_losers=losers,
- timeline=timeline
- )
-
- def _determine_policy_change_type(self, news: List[DataPoint]) -> str:
- """Determine type of policy change"""
- change_keywords = {
- "proposed": ["proposed", "draft", "plan", "considering", "exploring"],
- "enacted": ["passed", "approved", "enacted", "signed", "adopted"],
- "implemented": ["effective", "implementation", "rollout", "enforcement"]
- }
-
- change_scores = {change_type: 0 for change_type in change_keywords.keys()}
-
- for article in news:
- text = article.value.lower()
- for change_type, keywords in change_keywords.items():
- score = sum(1 for keyword in keywords if keyword in text)
- change_scores[change_type] += score
-
- return max(change_scores.items(), key=lambda x: x[1])[0] if any(change_scores.values()) else "proposed"
-
- def _calculate_passage_probability(self, news: List[DataPoint], policy_area: str) -> float:
- """Calculate probability of policy passage"""
- # Base probabilities by policy area and political difficulty
- base_probabilities = {
- "tax_reform": 0.4,
- "healthcare_policy": 0.3,
- "infrastructure_spending": 0.6,
- "trade_policy": 0.5,
- "energy_policy": 0.4,
- "immigration_policy": 0.2
- }
-
- base_prob = base_probabilities.get(policy_area, 0.4)
-
- # Analyze news sentiment for passage likelihood
- positive_indicators = ["bipartisan support", "broad agreement", "likely to pass", "strong support"]
- negative_indicators = ["opposition", "unlikely to pass", "political deadlock", "controversy"]
-
- positive_score = 0
- negative_score = 0
-
- for article in news:
- text = article.value.lower()
- positive_score += sum(1 for indicator in positive_indicators if indicator in text)
- negative_score += sum(1 for indicator in negative_indicators if indicator in text)
-
- # Adjust probability based on sentiment
- if news:
- sentiment_adjustment = (positive_score - negative_score) / len(news) * 0.3
- adjusted_prob = base_prob + sentiment_adjustment
- else:
- adjusted_prob = base_prob
-
- return np.clip(adjusted_prob, 0.0, 1.0)
-
- def _calculate_policy_economic_impact(self, policy_area: str, news: List[DataPoint]) -> Dict[str, float]:
- """Calculate economic impact of policy changes"""
- # Base economic impacts by policy area (% GDP impact)
- base_impacts = {
- "tax_reform": {"gdp_growth": 0.3, "business_investment": 0.5, "consumer_spending": 0.2},
- "infrastructure_spending": {"gdp_growth": 0.8, "employment": 0.6, "productivity": 0.4},
- "healthcare_policy": {"healthcare_costs": -0.3, "business_costs": 0.2, "innovation": -0.1},
- "trade_policy": {"trade_volumes": 0.4, "manufacturing": 0.3, "consumer_prices": -0.2},
- "energy_policy": {"energy_costs": -0.2, "green_investment": 0.6, "traditional_energy": -0.4}
- }
-
- return base_impacts.get(policy_area, {"gdp_growth": 0.1})
-
- def _identify_policy_winners_losers(self, policy_area: str) -> Tuple[List[str], List[str]]:
- """Identify sector winners and losers from policy changes"""
- policy_impacts = {
- "tax_reform": {
- "winners": ["domestic_companies", "small_business", "manufacturing"],
- "losers": ["multinationals", "high_tax_rate_sectors"]
- },
- "infrastructure_spending": {
- "winners": ["construction", "materials", "industrials", "transportation"],
- "losers": ["bond_investors"] # Higher deficits
- },
- "healthcare_policy": {
- "winners": ["healthcare_providers", "medical_devices"],
- "losers": ["pharmaceuticals", "health_insurance"]
- },
- "energy_policy": {
- "winners": ["renewable_energy", "electric_vehicles", "grid_infrastructure"],
- "losers": ["fossil_fuels", "traditional_utilities"]
- }
- }
-
- impacts = policy_impacts.get(policy_area, {"winners": [], "losers": []})
- return impacts["winners"], impacts["losers"]
-
- def _estimate_policy_timeline(self, news: List[DataPoint], change_type: str) -> str:
- """Estimate policy implementation timeline"""
- timeline_map = {
- "proposed": "6-18 months to passage",
- "enacted": "3-12 months to implementation",
- "implemented": "Currently rolling out"
- }
-
- return timeline_map.get(change_type, "12-24 months")
-
- async def get_regulatory_report(self) -> Dict:
- """Generate comprehensive regulatory intelligence report"""
- # Analyze regulatory landscape
- regulatory_signals = await self.analyze_regulatory_landscape()
-
- # Analyze policy changes
- policy_changes = await self.analyze_policy_changes()
-
- # Generate LLM analysis
- llm_analysis = await self._generate_regulatory_llm_analysis(regulatory_signals, policy_changes)
-
- return {
- "timestamp": datetime.now().isoformat(),
- "agent": self.name,
- "regulatory_landscape": {
- "high_impact_regulations": [{
- "regulation": signal.regulation_type,
- "jurisdiction": signal.jurisdiction,
- "impact_level": signal.impact_level,
- "timeline": signal.implementation_timeline,
- "affected_sectors": signal.affected_sectors,
- "market_impact": signal.market_impact
- } for signal in regulatory_signals[:5]],
- "compliance_cost_estimate": np.mean([s.compliance_cost for s in regulatory_signals]),
- "overall_regulatory_pressure": np.mean([s.impact_level for s in regulatory_signals])
- },
- "policy_changes": [{
- "policy_area": change.policy_area,
- "change_type": change.change_type,
- "probability": change.probability_passage,
- "economic_impact": change.economic_impact,
- "winners": change.sector_winners,
- "losers": change.sector_losers,
- "timeline": change.timeline
- } for change in policy_changes],
- "investment_implications": {
- "defensive_sectors": self._get_defensive_regulatory_sectors(regulatory_signals),
- "regulatory_beneficiaries": self._get_regulatory_beneficiaries(regulatory_signals),
- "compliance_leaders": self._get_compliance_advantage_sectors(regulatory_signals),
- "regulatory_risk_sectors": self._get_high_risk_sectors(regulatory_signals)
- },
- "llm_analysis": llm_analysis,
- "monitoring_priorities": {
- "key_regulations": [s.regulation_type for s in regulatory_signals[:3]],
- "high_probability_policies": [c.policy_area for c in policy_changes if c.probability_passage > 0.6],
- "immediate_compliance_deadlines": [s.regulation_type for s in regulatory_signals
- if "months" in s.implementation_timeline and
- int(s.implementation_timeline.split()[0]) <= 6]
- }
- }
-
- async def _generate_regulatory_llm_analysis(self, signals: List[RegulatorySignal],
- policy_changes: List[PolicyChange]) -> Dict:
- """Generate LLM-enhanced regulatory analysis"""
- try:
- # Prepare regulatory summary
- reg_summary = self._prepare_regulatory_summary(signals)
- policy_summary = self._prepare_policy_summary(policy_changes)
-
- prompt = f"""
- As a senior regulatory affairs analyst, analyze the current regulatory landscape and provide investment guidance.
-
- Key Regulatory Developments:
- {reg_summary}
-
- Policy Changes:
- {policy_summary}
-
- Please provide:
- 1. Most critical regulatory risks requiring immediate attention
- 2. Regulatory arbitrage opportunities (sectors benefiting from regulatory changes)
- 3. Compliance cost leaders vs laggards investment strategy
- 4. Timeline for next major regulatory wave
- 5. Sector rotation recommendations based on regulatory trends
- 6. Early warning indicators for regulatory surprises
-
- Format as JSON with keys: critical_risks, arbitrage_opportunities, compliance_strategy,
- regulatory_timeline, sector_rotation, early_warning_indicators
- """
-
- response = self.client.chat.completions.create(
- model=CONFIG.llm.deep_think_model,
- messages=[{"role": "user", "content": prompt}],
- temperature=CONFIG.llm.temperature,
- max_tokens=CONFIG.llm.max_tokens
- )
-
- return json.loads(response.choices[0].message.content)
-
- except Exception as e:
- logging.error(f"Error in LLM regulatory analysis: {e}")
- return {
- "critical_risks": ["Financial regulation tightening", "ESG compliance requirements"],
- "arbitrage_opportunities": ["Compliance technology", "Renewable energy"],
- "compliance_strategy": "Focus on established players with regulatory expertise",
- "regulatory_timeline": "Next 12-18 months",
- "sector_rotation": "Overweight compliance leaders, underweight regulatory laggards",
- "early_warning_indicators": ["Congressional hearings", "Agency enforcement actions"]
- }
-
- def _prepare_regulatory_summary(self, signals: List[RegulatorySignal]) -> str:
- """Prepare regulatory summary for LLM"""
- summary_lines = []
-
- for signal in signals[:5]: # Top 5 signals
- summary_lines.append(
- f"{signal.regulation_type} ({signal.jurisdiction}): "
- f"Impact Level {signal.impact_level}/10, "
- f"Timeline: {signal.implementation_timeline}, "
- f"Sectors: {', '.join(signal.affected_sectors[:3])}, "
- f"Compliance Cost: {signal.compliance_cost:.1%}"
- )
-
- return "\n".join(summary_lines)
-
- def _prepare_policy_summary(self, policy_changes: List[PolicyChange]) -> str:
- """Prepare policy changes summary for LLM"""
- summary_lines = []
-
- for policy in policy_changes:
- summary_lines.append(
- f"{policy.policy_area}: {policy.change_type} "
- f"(Probability: {policy.probability_passage:.0%}), "
- f"Winners: {', '.join(policy.sector_winners[:2])}, "
- f"Losers: {', '.join(policy.sector_losers[:2])}"
- )
-
- return "\n".join(summary_lines)
-
- def _get_defensive_regulatory_sectors(self, signals: List[RegulatorySignal]) -> List[str]:
- """Get sectors that are defensive against regulatory risk"""
- defensive_sectors = []
-
- # Sectors typically less affected by regulation
- inherently_defensive = ["utilities", "consumer_staples", "healthcare_providers"]
-
- # Sectors with positive regulatory tailwinds
- for signal in signals:
- for sector, impact in signal.market_impact.items():
- if impact > 0.3: # Positive regulatory impact
- defensive_sectors.append(sector)
-
- all_defensive = inherently_defensive + defensive_sectors
- return list(set(all_defensive)) # Remove duplicates
-
- def _get_regulatory_beneficiaries(self, signals: List[RegulatorySignal]) -> List[str]:
- """Get sectors that benefit from regulatory changes"""
- beneficiaries = []
-
- for signal in signals:
- for sector, impact in signal.market_impact.items():
- if impact > 0.4: # Strong positive impact
- beneficiaries.append(sector)
-
- # Check competitive advantages
- for advantage_type, score in signal.competitive_advantage.items():
- if score > 0.5 and advantage_type == "compliance_specialists":
- beneficiaries.extend(["legal_services", "compliance_tech", "consulting"])
-
- return list(set(beneficiaries))
-
- def _get_compliance_advantage_sectors(self, signals: List[RegulatorySignal]) -> List[str]:
- """Get sectors with compliance competitive advantages"""
- advantage_sectors = []
-
- for signal in signals:
- for advantage_type, score in signal.competitive_advantage.items():
- if score > 0.4:
- if advantage_type == "large_companies":
- advantage_sectors.extend(["mega_cap_stocks", "blue_chip_companies"])
- elif advantage_type == "tech_leaders":
- advantage_sectors.extend(["technology", "software"])
- elif advantage_type == "incumbents":
- advantage_sectors.extend(["established_players"])
-
- return list(set(advantage_sectors))
-
- def _get_high_risk_sectors(self, signals: List[RegulatorySignal]) -> List[str]:
- """Get sectors with high regulatory risk"""
- high_risk_sectors = []
-
- for signal in signals:
- if signal.impact_level >= 7: # High impact regulations
- for sector, impact in signal.market_impact.items():
- if impact < -0.3: # Negative impact
- high_risk_sectors.append(sector)
-
- return list(set(high_risk_sectors))
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/sentiment_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/sentiment_agent.py
deleted file mode 100644
index c825de8d6..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/sentiment_agent.py
+++ /dev/null
@@ -1,896 +0,0 @@
-# -*- coding: utf-8 -*-
-# agents/sentiment_agent.py - Market Sentiment Analysis Agent
-
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - market sentiment data
-# - social media feeds
-# - news sentiment
-# - investor sentiment surveys
-#
-# OUTPUT:
-# - Market sentiment scores
-# - Sentiment trend analysis
-# - Contrarian signals
-# - Sentiment-based alerts
-#
-# PARAMETERS:
-# - sentiment_sources
-# - analysis_timeframes
-# - sentiment_thresholds
-# - contrarian_indicators
-"""
-
-import asyncio
-import numpy as np
-import pandas as pd
-from datetime import datetime, timedelta
-from typing import Dict, List, Optional, Tuple
-import logging
-from dataclasses import dataclass
-import openai
-import json
-from textblob import TextBlob
-import re
-from collections import defaultdict, Counter
-
-from config import CONFIG
-from data_feeds import DataFeedManager, DataPoint
-
-
-@dataclass
-class SentimentSignal:
- """Market sentiment signal structure"""
- source: str
- sentiment_score: float # -1 to 1
- intensity: float # 0 to 1
- reliability: float
- trend: str # improving, deteriorating, stable
- contrarian_signal: bool
- affected_assets: List[str]
- time_horizon: str
-
-
-@dataclass
-class FearGreedMetrics:
- """Fear & Greed index components"""
- vix_level: float
- put_call_ratio: float
- safe_haven_flows: float
- momentum_strength: float
- overall_score: int # 0-100
- classification: str # extreme_fear, fear, neutral, greed, extreme_greed
-
-
-class SentimentAgent:
- """Advanced market sentiment analysis and contrarian signal generation"""
-
- def __init__(self):
- self.name = "sentiment"
- self.data_manager = DataFeedManager()
- self.client = openai.OpenAI(api_key=CONFIG.api.openai_api_key)
-
- # Sentiment sources and their reliability weights
- self.sentiment_sources = {
- "financial_news": {
- "reuters": 0.25,
- "bloomberg": 0.25,
- "wsj": 0.20,
- "ft": 0.15,
- "cnbc": 0.10,
- "marketwatch": 0.05
- },
- "social_media": {
- "twitter_fintwit": 0.40,
- "reddit_investing": 0.25,
- "reddit_wallstreetbets": 0.20,
- "stocktwits": 0.15
- },
- "analyst_sentiment": {
- "upgrade_downgrade": 0.35,
- "earnings_revisions": 0.30,
- "price_target_changes": 0.25,
- "recommendation_changes": 0.10
- },
- "market_indicators": {
- "vix": 0.30,
- "put_call_ratio": 0.25,
- "high_low_index": 0.20,
- "advance_decline": 0.25
- }
- }
-
- # Sentiment keywords with weights
- self.sentiment_keywords = {
- "extremely_bullish": {
- "keywords": ["moon", "rocket", "bull run", "unstoppable", "explosive growth",
- "parabolic", "to the stars", "massive rally", "euphoric"],
- "weight": 1.0,
- "contrarian_signal": True
- },
- "bullish": {
- "keywords": ["bullish", "optimistic", "positive", "uptrend", "rally", "growth",
- "strong", "buy", "accumulate", "opportunity"],
- "weight": 0.6,
- "contrarian_signal": False
- },
- "neutral": {
- "keywords": ["neutral", "mixed", "uncertain", "wait and see", "sideways",
- "balanced", "cautious", "hold"],
- "weight": 0.0,
- "contrarian_signal": False
- },
- "bearish": {
- "keywords": ["bearish", "pessimistic", "negative", "downtrend", "decline",
- "weakness", "sell", "avoid", "risk"],
- "weight": -0.6,
- "contrarian_signal": False
- },
- "extremely_bearish": {
- "keywords": ["crash", "collapse", "doom", "disaster", "panic", "bloodbath",
- "capitulation", "apocalypse", "end times", "dead"],
- "weight": -1.0,
- "contrarian_signal": True
- }
- }
-
- # Asset class sentiment mapping
- self.asset_sentiment_keywords = {
- "stocks": ["equity", "stock", "shares", "s&p", "nasdaq", "dow"],
- "bonds": ["bonds", "treasury", "yield", "fixed income", "debt"],
- "gold": ["gold", "precious metals", "safe haven"],
- "crypto": ["bitcoin", "crypto", "ethereum", "digital assets"],
- "oil": ["oil", "crude", "energy", "petroleum"],
- "dollar": ["dollar", "usd", "currency", "forex"]
- }
-
- # Contrarian sentiment thresholds
- self.contrarian_thresholds = {
- "extreme_bullish": 0.8, # When sentiment too positive
- "extreme_bearish": -0.8, # When sentiment too negative
- "consensus_threshold": 0.7 # When consensus too strong
- }
-
- async def analyze_market_sentiment(self) -> Dict[str, SentimentSignal]:
- """Comprehensive market sentiment analysis across all sources"""
- sentiment_signals = {}
-
- try:
- # Analyze news sentiment
- news_sentiment = await self._analyze_news_sentiment()
- if news_sentiment:
- sentiment_signals["news"] = news_sentiment
-
- # Analyze social media sentiment
- social_sentiment = await self._analyze_social_sentiment()
- if social_sentiment:
- sentiment_signals["social_media"] = social_sentiment
-
- # Analyze analyst sentiment
- analyst_sentiment = await self._analyze_analyst_sentiment()
- if analyst_sentiment:
- sentiment_signals["analyst"] = analyst_sentiment
-
- # Analyze market-based sentiment indicators
- market_sentiment = await self._analyze_market_indicators()
- if market_sentiment:
- sentiment_signals["market_indicators"] = market_sentiment
-
- return sentiment_signals
-
- except Exception as e:
- logging.error(f"Error in market sentiment analysis: {e}")
- return {"error": self._default_sentiment_signal()}
-
- async def _analyze_news_sentiment(self) -> Optional[SentimentSignal]:
- """Analyze sentiment from financial news"""
- try:
- # Fetch financial news
- news_data = await self.data_manager.get_multi_source_data({
- "news": {
- "query": "stock market economy investment",
- "sources": list(self.sentiment_sources["financial_news"].keys()),
- "hours_back": 24
- }
- })
-
- news_articles = news_data.get("news", [])
- if not news_articles:
- return None
-
- # Analyze sentiment for each article
- sentiment_scores = []
- source_weights = []
- asset_mentions = defaultdict(int)
-
- for article in news_articles:
- # Get sentiment score
- sentiment_score = self._calculate_text_sentiment(article.value)
-
- # Get source weight
- source_name = article.source.lower()
- source_weight = self.sentiment_sources["financial_news"].get(source_name, 0.05)
-
- sentiment_scores.append(sentiment_score * article.confidence)
- source_weights.append(source_weight)
-
- # Count asset mentions
- self._count_asset_mentions(article.value, asset_mentions)
-
- # Calculate weighted average sentiment
- if sentiment_scores and source_weights:
- weighted_sentiment = np.average(sentiment_scores, weights=source_weights)
-
- # Calculate intensity (standard deviation of sentiment)
- intensity = min(np.std(sentiment_scores), 1.0)
-
- # Determine trend
- trend = self._determine_sentiment_trend(sentiment_scores)
-
- # Check for contrarian signal
- contrarian_signal = abs(weighted_sentiment) > self.contrarian_thresholds["extreme_bullish"]
-
- # Get most mentioned assets
- top_assets = [asset for asset, count in
- Counter(asset_mentions).most_common(3)]
-
- return SentimentSignal(
- source="financial_news",
- sentiment_score=weighted_sentiment,
- intensity=intensity,
- reliability=np.mean(source_weights),
- trend=trend,
- contrarian_signal=contrarian_signal,
- affected_assets=top_assets,
- time_horizon="short"
- )
-
- except Exception as e:
- logging.error(f"Error in news sentiment analysis: {e}")
-
- return None
-
- async def _analyze_social_sentiment(self) -> Optional[SentimentSignal]:
- """Analyze sentiment from social media sources"""
- try:
- # Fetch social media sentiment data
- social_data = await self.data_manager.get_multi_source_data({
- "sentiment": {
- "subreddits": ["investing", "stocks", "SecurityAnalysis", "ValueInvesting"],
- "keywords": ["market", "stocks", "bull", "bear", "crash", "rally"]
- }
- })
-
- sentiment_data = social_data.get("sentiment", [])
- if not sentiment_data:
- return None
-
- # Process social sentiment
- sentiment_scores = []
- platform_weights = []
-
- for data_point in sentiment_data:
- platform = data_point.metadata.get("subreddit", "unknown")
- platform_weight = self._get_social_platform_weight(platform)
-
- sentiment_scores.append(data_point.value)
- platform_weights.append(platform_weight)
-
- if sentiment_scores:
- # Calculate weighted sentiment
- weighted_sentiment = np.average(sentiment_scores, weights=platform_weights)
- intensity = min(np.std(sentiment_scores), 1.0)
-
- # Social media tends to be more extreme and contrarian
- contrarian_signal = (abs(weighted_sentiment) > 0.6 or
- self._detect_social_extremes(sentiment_data))
-
- return SentimentSignal(
- source="social_media",
- sentiment_score=weighted_sentiment,
- intensity=intensity,
- reliability=0.6, # Lower reliability than news
- trend=self._determine_sentiment_trend(sentiment_scores),
- contrarian_signal=contrarian_signal,
- affected_assets=["stocks", "crypto"], # Social media focus
- time_horizon="very_short"
- )
-
- except Exception as e:
- logging.error(f"Error in social sentiment analysis: {e}")
-
- return None
-
- async def _analyze_analyst_sentiment(self) -> Optional[SentimentSignal]:
- """Analyze professional analyst sentiment"""
- try:
- # This would integrate with analyst data providers
- # For now, we'll simulate based on market data patterns
-
- # Simulate analyst sentiment based on recent market performance
- sentiment_score = np.random.normal(0.1, 0.3) # Slight bullish bias
- sentiment_score = np.clip(sentiment_score, -1, 1)
-
- # Analysts tend to be less extreme
- intensity = np.random.uniform(0.2, 0.6)
-
- # Professional analysts rarely give contrarian signals
- contrarian_signal = False
-
- return SentimentSignal(
- source="analyst_sentiment",
- sentiment_score=sentiment_score,
- intensity=intensity,
- reliability=0.8, # High reliability
- trend="stable",
- contrarian_signal=contrarian_signal,
- affected_assets=["stocks", "sectors"],
- time_horizon="medium"
- )
-
- except Exception as e:
- logging.error(f"Error in analyst sentiment analysis: {e}")
-
- return None
-
- async def _analyze_market_indicators(self) -> Optional[SentimentSignal]:
- """Analyze market-based sentiment indicators"""
- try:
- # Fetch market sentiment indicators
- economic_data = await self.data_manager.get_multi_source_data({
- "economic": {
- "VIXCLS": {"series_id": "VIXCLS", "limit": 30}, # VIX
- "GS10": {"series_id": "GS10", "limit": 30} # 10Y Treasury
- }
- })
-
- market_data = economic_data.get("economic", {})
-
- # Calculate fear/greed metrics
- fear_greed = self._calculate_fear_greed_index(market_data)
-
- # Convert fear/greed to sentiment score
- sentiment_score = (fear_greed.overall_score - 50) / 50 # Convert 0-100 to -1 to 1
-
- # Market indicators are highly reliable but can be contrarian
- contrarian_signal = (fear_greed.classification in ["extreme_fear", "extreme_greed"])
-
- return SentimentSignal(
- source="market_indicators",
- sentiment_score=sentiment_score,
- intensity=abs(sentiment_score),
- reliability=0.9, # Very reliable
- trend=self._interpret_fear_greed_trend(fear_greed),
- contrarian_signal=contrarian_signal,
- affected_assets=["stocks", "bonds", "volatility"],
- time_horizon="short"
- )
-
- except Exception as e:
- logging.error(f"Error in market indicator analysis: {e}")
-
- return None
-
- def _calculate_text_sentiment(self, text: str) -> float:
- """Calculate sentiment score from text using keyword analysis and TextBlob"""
- try:
- # Use TextBlob for base sentiment
- blob = TextBlob(text)
- base_sentiment = blob.sentiment.polarity
-
- # Enhance with custom keyword analysis
- text_lower = text.lower()
- keyword_sentiment = 0.0
- keyword_count = 0
-
- for sentiment_category, config in self.sentiment_keywords.items():
- for keyword in config["keywords"]:
- if keyword in text_lower:
- keyword_sentiment += config["weight"]
- keyword_count += 1
-
- # Combine base sentiment with keyword sentiment
- if keyword_count > 0:
- keyword_sentiment /= keyword_count
- # Weight: 60% keyword sentiment, 40% TextBlob
- combined_sentiment = 0.6 * keyword_sentiment + 0.4 * base_sentiment
- else:
- combined_sentiment = base_sentiment
-
- return np.clip(combined_sentiment, -1.0, 1.0)
-
- except Exception:
- return 0.0
-
- def _count_asset_mentions(self, text: str, asset_mentions: Dict[str, int]):
- """Count mentions of different asset classes in text"""
- text_lower = text.lower()
-
- for asset_class, keywords in self.asset_sentiment_keywords.items():
- for keyword in keywords:
- if keyword in text_lower:
- asset_mentions[asset_class] += 1
-
- def _determine_sentiment_trend(self, sentiment_scores: List[float]) -> str:
- """Determine if sentiment is improving, deteriorating, or stable"""
- if len(sentiment_scores) < 3:
- return "stable"
-
- # Compare recent vs older sentiment
- recent_avg = np.mean(sentiment_scores[-len(sentiment_scores) // 3:])
- older_avg = np.mean(sentiment_scores[:len(sentiment_scores) // 3])
-
- difference = recent_avg - older_avg
-
- if difference > 0.1:
- return "improving"
- elif difference < -0.1:
- return "deteriorating"
- else:
- return "stable"
-
- def _get_social_platform_weight(self, platform: str) -> float:
- """Get weight for social media platform"""
- platform_weights = {
- "investing": 0.4,
- "stocks": 0.3,
- "SecurityAnalysis": 0.5,
- "ValueInvesting": 0.4,
- "wallstreetbets": 0.2, # High volume but lower quality
- "stocktwits": 0.3
- }
-
- return platform_weights.get(platform, 0.2)
-
- def _detect_social_extremes(self, sentiment_data: List[DataPoint]) -> bool:
- """Detect extreme sentiment in social media data"""
- if not sentiment_data:
- return False
-
- # Check for extreme keywords
- extreme_keywords = (self.sentiment_keywords["extremely_bullish"]["keywords"] +
- self.sentiment_keywords["extremely_bearish"]["keywords"])
-
- extreme_count = 0
- total_posts = len(sentiment_data)
-
- for data_point in sentiment_data:
- text = str(data_point.value).lower()
- if any(keyword in text for keyword in extreme_keywords):
- extreme_count += 1
-
- # If more than 20% of posts contain extreme language
- return (extreme_count / total_posts) > 0.2 if total_posts > 0 else False
-
- def _calculate_fear_greed_index(self, market_data: Dict) -> FearGreedMetrics:
- """Calculate fear & greed index from market data"""
- try:
- # Get VIX level (fear indicator)
- vix_data = market_data.get("VIXCLS", [])
- current_vix = vix_data[-1].value if vix_data else 20.0
-
- # Normalize VIX to 0-1 scale (inverse - high VIX = fear)
- vix_score = max(0, min(1, (50 - current_vix) / 30)) # 50 = extreme fear, 10 = greed
-
- # Simulate other components (in production, would fetch real data)
- put_call_ratio = np.random.uniform(0.3, 1.2) # Normal range
- put_call_score = max(0, min(1, (1.2 - put_call_ratio) / 0.9))
-
- # Safe haven flows (inverse bond yields indicate flight to safety)
- treasury_data = market_data.get("GS10", [])
- current_yield = treasury_data[-1].value if treasury_data else 4.0
- safe_haven_score = max(0, min(1, (current_yield - 2.0) / 4.0)) # Higher yields = less fear
-
- # Momentum strength (simulated)
- momentum_score = np.random.uniform(0.3, 0.8)
-
- # Calculate overall score (0-100)
- component_scores = [vix_score, put_call_score, safe_haven_score, momentum_score]
- overall_score = int(np.mean(component_scores) * 100)
-
- # Classify fear/greed level
- if overall_score >= 80:
- classification = "extreme_greed"
- elif overall_score >= 60:
- classification = "greed"
- elif overall_score >= 40:
- classification = "neutral"
- elif overall_score >= 20:
- classification = "fear"
- else:
- classification = "extreme_fear"
-
- return FearGreedMetrics(
- vix_level=current_vix,
- put_call_ratio=put_call_ratio,
- safe_haven_flows=1 - safe_haven_score, # Invert for intuitive reading
- momentum_strength=momentum_score,
- overall_score=overall_score,
- classification=classification
- )
-
- except Exception as e:
- logging.error(f"Error calculating fear/greed index: {e}")
- return FearGreedMetrics(50.0, 0.8, 0.5, 0.5, 50, "neutral")
-
- def _interpret_fear_greed_trend(self, fear_greed: FearGreedMetrics) -> str:
- """Interpret fear/greed trend"""
- score = fear_greed.overall_score
-
- if score > 70:
- return "deteriorating" # Too much greed
- elif score < 30:
- return "improving" # Oversold, likely to improve
- else:
- return "stable"
-
- def _default_sentiment_signal(self) -> SentimentSignal:
- """Return default sentiment signal"""
- return SentimentSignal(
- source="default",
- sentiment_score=0.0,
- intensity=0.3,
- reliability=0.3,
- trend="stable",
- contrarian_signal=False,
- affected_assets=["broad_market"],
- time_horizon="short"
- )
-
- async def generate_contrarian_signals(self, sentiment_signals: Dict[str, SentimentSignal]) -> List[Dict]:
- """Generate contrarian trading signals from sentiment extremes"""
- contrarian_signals = []
-
- for source, signal in sentiment_signals.items():
- if signal.contrarian_signal:
- # Generate contrarian signal
- contrarian_direction = "short" if signal.sentiment_score > 0 else "long"
- conviction = min(signal.intensity * signal.reliability, 1.0)
-
- contrarian_signals.append({
- "source": source,
- "direction": contrarian_direction,
- "conviction": conviction,
- "rationale": f"Extreme {source} sentiment: {signal.sentiment_score:.2f}",
- "affected_assets": signal.affected_assets,
- "time_horizon": signal.time_horizon,
- "sentiment_score": signal.sentiment_score
- })
-
- return contrarian_signals
-
- async def analyze_sector_sentiment(self) -> Dict[str, float]:
- """Analyze sentiment by sector"""
- sector_sentiment = {}
-
- # Sector-specific keywords
- sector_keywords = {
- "technology": ["tech", "software", "ai", "cloud", "semiconductor"],
- "healthcare": ["pharma", "biotech", "medical", "drug", "health"],
- "financials": ["bank", "insurance", "credit", "lending", "fintech"],
- "energy": ["oil", "gas", "renewable", "energy", "solar"],
- "consumer": ["retail", "consumer", "spending", "discretionary"]
- }
-
- try:
- for sector, keywords in sector_keywords.items():
- # Fetch sector-specific news
- sector_news = await self.data_manager.get_multi_source_data({
- "news": {
- "query": " OR ".join(keywords),
- "sources": ["reuters", "bloomberg"],
- "hours_back": 24
- }
- })
-
- news_data = sector_news.get("news", [])
- if news_data:
- sentiment_scores = [self._calculate_text_sentiment(article.value)
- for article in news_data]
- sector_sentiment[sector] = np.mean(sentiment_scores)
- else:
- sector_sentiment[sector] = 0.0
-
- except Exception as e:
- logging.error(f"Error in sector sentiment analysis: {e}")
-
- return sector_sentiment
-
- async def get_sentiment_report(self) -> Dict:
- """Generate comprehensive sentiment analysis report"""
- # Analyze overall market sentiment
- sentiment_signals = await self.analyze_market_sentiment()
-
- # Generate contrarian signals
- contrarian_signals = await self.generate_contrarian_signals(sentiment_signals)
-
- # Analyze sector sentiment
- sector_sentiment = await self.analyze_sector_sentiment()
-
- # Calculate overall sentiment score
- if sentiment_signals:
- weighted_scores = []
- weights = []
-
- for source, signal in sentiment_signals.items():
- if source != "error":
- weighted_scores.append(signal.sentiment_score * signal.reliability)
- weights.append(signal.reliability)
-
- overall_sentiment = (np.average(weighted_scores, weights=weights)
- if weighted_scores else 0.0)
- else:
- overall_sentiment = 0.0
-
- # Generate LLM analysis
- llm_analysis = await self._generate_sentiment_llm_analysis(
- sentiment_signals, contrarian_signals, sector_sentiment
- )
-
- return {
- "timestamp": datetime.now().isoformat(),
- "agent": self.name,
- "sentiment_analysis": {
- "overall_sentiment": overall_sentiment,
- "sentiment_classification": self._classify_sentiment(overall_sentiment),
- "source_breakdown": {
- source: {
- "score": signal.sentiment_score,
- "intensity": signal.intensity,
- "reliability": signal.reliability,
- "trend": signal.trend,
- "contrarian_signal": signal.contrarian_signal
- } for source, signal in sentiment_signals.items() if source != "error"
- }
- },
- "contrarian_signals": contrarian_signals,
- "sector_sentiment": sector_sentiment,
- "fear_greed_analysis": {
- "current_level": self._estimate_fear_greed_level(overall_sentiment),
- "interpretation": self._interpret_sentiment_level(overall_sentiment),
- "contrarian_opportunity": abs(overall_sentiment) > 0.6
- },
- "trading_implications": {
- "market_timing": self._get_market_timing_signal(overall_sentiment),
- "position_sizing": self._get_position_sizing_recommendation(sentiment_signals),
- "asset_allocation": self._get_sentiment_based_allocation(overall_sentiment),
- "risk_management": self._get_sentiment_risk_recommendations(contrarian_signals)
- },
- "llm_analysis": llm_analysis,
- "monitoring_alerts": {
- "extreme_sentiment_warning": abs(overall_sentiment) > 0.7,
- "contrarian_opportunities": len(contrarian_signals) > 0,
- "sentiment_divergence": self._detect_sentiment_divergence(sentiment_signals),
- "social_media_extreme": any(s.source == "social_media" and s.contrarian_signal
- for s in sentiment_signals.values() if hasattr(s, 'source'))
- }
- }
-
- def _classify_sentiment(self, sentiment_score: float) -> str:
- """Classify overall sentiment level"""
- if sentiment_score >= 0.6:
- return "very_bullish"
- elif sentiment_score >= 0.2:
- return "bullish"
- elif sentiment_score >= -0.2:
- return "neutral"
- elif sentiment_score >= -0.6:
- return "bearish"
- else:
- return "very_bearish"
-
- def _estimate_fear_greed_level(self, sentiment_score: float) -> int:
- """Convert sentiment score to fear/greed index (0-100)"""
- # Convert -1 to 1 range to 0-100
- fear_greed_score = int((sentiment_score + 1) * 50)
- return np.clip(fear_greed_score, 0, 100)
-
- def _interpret_sentiment_level(self, sentiment_score: float) -> str:
- """Interpret sentiment level for trading"""
- if sentiment_score > 0.7:
- return "Extreme optimism - consider taking profits and defensive positioning"
- elif sentiment_score > 0.4:
- return "Strong bullish sentiment - continue momentum but watch for reversals"
- elif sentiment_score > -0.4:
- return "Balanced sentiment - fundamentals likely driving markets"
- elif sentiment_score > -0.7:
- return "Pessimistic sentiment - look for oversold opportunities"
- else:
- return "Extreme pessimism - strong contrarian buying opportunity"
-
- def _get_market_timing_signal(self, sentiment_score: float) -> str:
- """Get market timing signal based on sentiment"""
- if sentiment_score > 0.6:
- return "reduce_risk" # Extreme optimism
- elif sentiment_score < -0.6:
- return "increase_risk" # Extreme pessimism
- elif sentiment_score > 0.3:
- return "neutral_to_bullish"
- elif sentiment_score < -0.3:
- return "neutral_to_bearish"
- else:
- return "neutral"
-
- def _get_position_sizing_recommendation(self, sentiment_signals: Dict[str, SentimentSignal]) -> str:
- """Get position sizing recommendation based on sentiment"""
- if not sentiment_signals:
- return "normal"
-
- # Count contrarian signals
- contrarian_count = sum(1 for signal in sentiment_signals.values()
- if hasattr(signal, 'contrarian_signal') and signal.contrarian_signal)
-
- # Check sentiment intensity
- avg_intensity = np.mean([signal.intensity for signal in sentiment_signals.values()
- if hasattr(signal, 'intensity')])
-
- if contrarian_count >= 2:
- return "reduce_size" # Multiple contrarian signals suggest caution
- elif avg_intensity > 0.7:
- return "reduce_size" # High intensity suggests volatility
- elif contrarian_count == 1 and avg_intensity < 0.4:
- return "increase_size" # Single contrarian opportunity with low volatility
- else:
- return "normal"
-
- def _get_sentiment_based_allocation(self, sentiment_score: float) -> Dict[str, str]:
- """Get asset allocation recommendation based on sentiment"""
- if sentiment_score > 0.5:
- return {
- "equities": "underweight", # Reduce risk in euphoric markets
- "bonds": "overweight",
- "cash": "overweight",
- "defensive_sectors": "overweight"
- }
- elif sentiment_score < -0.5:
- return {
- "equities": "overweight", # Increase risk in pessimistic markets
- "bonds": "underweight",
- "cash": "underweight",
- "growth_sectors": "overweight"
- }
- else:
- return {
- "equities": "neutral",
- "bonds": "neutral",
- "cash": "neutral",
- "sectors": "neutral"
- }
-
- def _get_sentiment_risk_recommendations(self, contrarian_signals: List[Dict]) -> List[str]:
- """Get risk management recommendations based on sentiment"""
- recommendations = []
-
- if len(contrarian_signals) > 0:
- recommendations.append("Monitor sentiment reversal points closely")
- recommendations.append("Consider volatility hedges")
-
- # Check for social media extremes
- social_extremes = [signal for signal in contrarian_signals
- if signal.get("source") == "social_media"]
-
- if social_extremes:
- recommendations.append("High social media sentiment risk - prepare for volatility")
- recommendations.append("Consider reducing position sizes in meme stocks")
-
- # Check for multiple extreme signals
- if len(contrarian_signals) >= 2:
- recommendations.append("Multiple extreme sentiment signals - consider defensive positioning")
-
- return recommendations or ["Normal risk management procedures"]
-
- def _detect_sentiment_divergence(self, sentiment_signals: Dict[str, SentimentSignal]) -> bool:
- """Detect divergence between different sentiment sources"""
- if len(sentiment_signals) < 2:
- return False
-
- scores = [signal.sentiment_score for signal in sentiment_signals.values()
- if hasattr(signal, 'sentiment_score')]
-
- if len(scores) < 2:
- return False
-
- # Check if sentiment scores are significantly different
- score_std = np.std(scores)
- score_range = max(scores) - min(scores)
-
- # Divergence if high standard deviation or wide range
- return score_std > 0.4 or score_range > 0.8
-
- async def _generate_sentiment_llm_analysis(self, sentiment_signals: Dict[str, SentimentSignal],
- contrarian_signals: List[Dict],
- sector_sentiment: Dict[str, float]) -> Dict:
- """Generate LLM-enhanced sentiment analysis"""
- try:
- # Prepare sentiment summary
- sentiment_summary = self._prepare_sentiment_summary(sentiment_signals)
- contrarian_summary = self._prepare_contrarian_summary(contrarian_signals)
- sector_summary = self._prepare_sector_sentiment_summary(sector_sentiment)
-
- prompt = f"""
- As a senior market sentiment analyst, analyze the current market psychology and provide trading guidance.
-
- Sentiment Analysis:
- {sentiment_summary}
-
- Contrarian Signals:
- {contrarian_summary}
-
- Sector Sentiment:
- {sector_summary}
-
- Please provide:
- 1. Current market psychology assessment and crowd behavior analysis
- 2. Contrarian opportunities with specific entry/exit strategies
- 3. Sentiment-based sector rotation recommendations
- 4. Risk management for sentiment-driven volatility
- 5. Timeline for potential sentiment reversals
- 6. Early warning indicators for sentiment extremes
-
- Format as JSON with keys: market_psychology, contrarian_opportunities, sector_rotation,
- risk_management, sentiment_timeline, early_warning_indicators
- """
-
- response = self.client.chat.completions.create(
- model=CONFIG.llm.deep_think_model,
- messages=[{"role": "user", "content": prompt}],
- temperature=CONFIG.llm.temperature,
- max_tokens=CONFIG.llm.max_tokens
- )
-
- return json.loads(response.choices[0].message.content)
-
- except Exception as e:
- logging.error(f"Error in LLM sentiment analysis: {e}")
- return {
- "market_psychology": "Mixed sentiment with moderate optimism",
- "contrarian_opportunities": "Monitor for extreme readings in VIX and social media",
- "sector_rotation": "Balanced approach with slight tech overweight",
- "risk_management": "Standard position sizing with volatility monitoring",
- "sentiment_timeline": "Next 2-4 weeks for potential shifts",
- "early_warning_indicators": ["VIX spikes", "Social media extremes", "News flow acceleration"]
- }
-
- def _prepare_sentiment_summary(self, sentiment_signals: Dict[str, SentimentSignal]) -> str:
- """Prepare sentiment summary for LLM"""
- summary_lines = []
-
- for source, signal in sentiment_signals.items():
- if hasattr(signal, 'sentiment_score'):
- summary_lines.append(
- f"{source}: Score {signal.sentiment_score:.2f}, "
- f"Intensity {signal.intensity:.2f}, "
- f"Trend {signal.trend}, "
- f"Contrarian: {signal.contrarian_signal}"
- )
-
- return "\n".join(summary_lines) if summary_lines else "Limited sentiment data available"
-
- def _prepare_contrarian_summary(self, contrarian_signals: List[Dict]) -> str:
- """Prepare contrarian signals summary for LLM"""
- if not contrarian_signals:
- return "No significant contrarian signals detected"
-
- summary_lines = []
- for signal in contrarian_signals:
- summary_lines.append(
- f"{signal['source']}: {signal['direction']} signal "
- f"(Conviction: {signal['conviction']:.2f}) - {signal['rationale']}"
- )
-
- return "\n".join(summary_lines)
-
- def _prepare_sector_sentiment_summary(self, sector_sentiment: Dict[str, float]) -> str:
- """Prepare sector sentiment summary for LLM"""
- if not sector_sentiment:
- return "Sector sentiment data not available"
-
- summary_lines = []
- sorted_sectors = sorted(sector_sentiment.items(), key=lambda x: x[1], reverse=True)
-
- for sector, sentiment in sorted_sectors:
- sentiment_desc = "Bullish" if sentiment > 0.2 else "Bearish" if sentiment < -0.2 else "Neutral"
- summary_lines.append(f"{sector}: {sentiment:.2f} ({sentiment_desc})")
-
- return "\n".join(summary_lines)
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/supply_chain_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/supply_chain_agent.py
deleted file mode 100644
index 929078f54..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/fincept_hedge_fund/supply_chain_agent.py
+++ /dev/null
@@ -1,613 +0,0 @@
-# -*- coding: utf-8 -*-
-# agents/supply_chain_agent.py - Supply Chain Analysis Agent
-
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - supply chain data
-# - logistics metrics
-# - inventory levels
-# - shipping information
-#
-# OUTPUT:
-# - Supply chain risk assessments
-# - Disruption alerts
-# - Efficiency metrics
-# - Supplier risk analysis
-#
-# PARAMETERS:
-# - supply_chain_tiers
-# - risk_indicators
-# - monitoring_regions
-# - disruption_thresholds
-"""
-
-import asyncio
-import numpy as np
-import pandas as pd
-from datetime import datetime, timedelta
-from typing import Dict, List, Optional, Tuple
-import logging
-from dataclasses import dataclass
-import openai
-import json
-
-from config import CONFIG
-from data_feeds import DataFeedManager, DataPoint
-
-
-@dataclass
-class SupplyChainRisk:
- """Supply chain risk assessment"""
- disruption_type: str
- affected_regions: List[str]
- risk_level: int # 1-10
- affected_sectors: List[str]
- price_impact: Dict[str, float]
- duration_estimate: str
- mitigation_difficulty: str
-
-
-class SupplyChainAgent:
- """Supply chain disruption monitoring and investment impact analysis"""
-
- def __init__(self):
- self.name = "supply_chain"
- self.data_manager = DataFeedManager()
- self.client = openai.OpenAI(api_key=CONFIG.api.openai_api_key)
-
- # Critical supply chain chokepoints
- self.chokepoints = {
- "shipping": ["Suez Canal", "Panama Canal", "Strait of Hormuz", "Strait of Malacca"],
- "semiconductors": ["Taiwan", "South Korea", "Netherlands", "Japan"],
- "rare_earths": ["China", "Australia", "Myanmar"],
- "energy": ["Russia", "Saudi Arabia", "Norway", "Qatar"],
- "agriculture": ["Ukraine", "Russia", "Brazil", "Argentina"]
- }
-
- # Sector impact mapping
- self.sector_impacts = {
- "shipping_disruption": {
- "retail": -0.6, "automotive": -0.8, "electronics": -0.7,
- "energy": 0.3, "logistics": -0.9, "commodities": 0.4
- },
- "semiconductor_shortage": {
- "automotive": -0.9, "electronics": -0.8, "telecommunications": -0.6,
- "industrial": -0.5, "healthcare": -0.3
- },
- "energy_supply_shock": {
- "airlines": -0.8, "chemicals": -0.7, "materials": -0.6,
- "energy": 0.8, "utilities": -0.4, "transportation": -0.7
- }
- }
-
- async def analyze_supply_chains(self) -> List[SupplyChainRisk]:
- """Analyze global supply chain risks"""
- risks = []
-
- # Shipping disruptions
- shipping_risk = await self._analyze_shipping_disruptions()
- if shipping_risk:
- risks.append(shipping_risk)
-
- # Semiconductor supply
- chip_risk = await self._analyze_semiconductor_supply()
- if chip_risk:
- risks.append(chip_risk)
-
- # Energy supply
- energy_risk = await self._analyze_energy_supply()
- if energy_risk:
- risks.append(energy_risk)
-
- # Critical materials
- materials_risk = await self._analyze_critical_materials()
- if materials_risk:
- risks.append(materials_risk)
-
- return risks
-
- async def _analyze_shipping_disruptions(self) -> Optional[SupplyChainRisk]:
- """Analyze global shipping and logistics disruptions"""
- try:
- # Fetch shipping-related news
- shipping_news = await self.data_manager.get_multi_source_data({
- "news": {
- "query": "shipping disruption supply chain logistics",
- "sources": ["reuters", "bloomberg"],
- "hours_back": 72
- }
- })
-
- news_data = shipping_news.get("news", [])
-
- # Calculate risk level from news intensity
- disruption_keywords = [
- "port congestion", "shipping delay", "container shortage",
- "suez canal", "panama canal", "strike", "blockage"
- ]
-
- risk_score = 0
- for article in news_data:
- text = article.value.lower()
- keyword_count = sum(1 for keyword in disruption_keywords if keyword in text)
- risk_score += keyword_count * article.confidence
-
- if news_data:
- normalized_risk = min(risk_score / len(news_data) * 2, 10)
- risk_level = int(normalized_risk) if normalized_risk > 3 else 5
- else:
- risk_level = 4 # Baseline moderate risk
-
- # Determine affected regions and sectors
- affected_regions = ["Global", "Asia-Pacific", "Europe", "North America"]
- affected_sectors = ["retail", "automotive", "electronics", "consumer goods"]
-
- # Price impacts
- price_impacts = {
- "shipping_costs": 0.2 * (risk_level / 10),
- "commodity_prices": 0.15 * (risk_level / 10),
- "consumer_goods": 0.1 * (risk_level / 10)
- }
-
- return SupplyChainRisk(
- disruption_type="shipping_logistics",
- affected_regions=affected_regions,
- risk_level=risk_level,
- affected_sectors=affected_sectors,
- price_impact=price_impacts,
- duration_estimate="3-9 months" if risk_level > 6 else "1-6 months",
- mitigation_difficulty="moderate"
- )
-
- except Exception as e:
- logging.error(f"Error analyzing shipping disruptions: {e}")
- return None
-
- async def _analyze_semiconductor_supply(self) -> Optional[SupplyChainRisk]:
- """Analyze semiconductor supply chain risks"""
- try:
- # Fetch semiconductor news
- chip_news = await self.data_manager.get_multi_source_data({
- "news": {
- "query": "semiconductor chip shortage taiwan TSMC",
- "sources": ["reuters", "bloomberg"],
- "hours_back": 168 # 1 week
- }
- })
-
- news_data = chip_news.get("news", [])
-
- # Semiconductor risk factors
- risk_keywords = [
- "chip shortage", "semiconductor", "taiwan tensions", "TSMC",
- "fabrication", "wafer", "supply constraint"
- ]
-
- geopolitical_keywords = [
- "taiwan strait", "china taiwan", "semiconductor sanctions",
- "export controls", "technology war"
- ]
-
- supply_risk = 0
- geopolitical_risk = 0
-
- for article in news_data:
- text = article.value.lower()
- supply_risk += sum(1 for keyword in risk_keywords if keyword in text)
- geopolitical_risk += sum(1 for keyword in geopolitical_keywords if keyword in text)
-
- # Combine risks
- total_articles = len(news_data) if news_data else 1
- combined_risk = (supply_risk + geopolitical_risk * 2) / total_articles
- risk_level = min(int(combined_risk * 1.5) + 4, 10) # Base 4, scale up
-
- affected_regions = ["Global", "Taiwan", "South Korea", "Japan"]
- affected_sectors = ["automotive", "electronics", "telecommunications", "industrial"]
-
- price_impacts = {
- "semiconductor_prices": 0.3 * (risk_level / 10),
- "electronics": 0.2 * (risk_level / 10),
- "automotive": 0.25 * (risk_level / 10)
- }
-
- return SupplyChainRisk(
- disruption_type="semiconductor_shortage",
- affected_regions=affected_regions,
- risk_level=risk_level,
- affected_sectors=affected_sectors,
- price_impact=price_impacts,
- duration_estimate="12-24 months" if risk_level > 7 else "6-18 months",
- mitigation_difficulty="high" # Long lead times for new fabs
- )
-
- except Exception as e:
- logging.error(f"Error analyzing semiconductor supply: {e}")
- return None
-
- async def _analyze_energy_supply(self) -> Optional[SupplyChainRisk]:
- """Analyze energy supply chain risks"""
- try:
- # Fetch energy supply news
- energy_news = await self.data_manager.get_multi_source_data({
- "news": {
- "query": "energy supply oil gas pipeline russia ukraine",
- "sources": ["reuters", "bloomberg"],
- "hours_back": 96
- }
- })
-
- news_data = energy_news.get("news", [])
-
- # Energy supply risk indicators
- supply_risk_keywords = [
- "pipeline", "refinery shutdown", "oil supply", "gas supply",
- "energy crisis", "power shortage", "fuel shortage"
- ]
-
- geopolitical_keywords = [
- "russia sanctions", "opec", "energy weapon", "gas cutoff",
- "strategic reserve", "energy security"
- ]
-
- supply_disruption_score = 0
- geopolitical_score = 0
-
- for article in news_data:
- text = article.value.lower()
- supply_disruption_score += sum(1 for keyword in supply_risk_keywords if keyword in text)
- geopolitical_score += sum(1 for keyword in geopolitical_keywords if keyword in text)
-
- total_articles = len(news_data) if news_data else 1
- combined_score = (supply_disruption_score + geopolitical_score * 1.5) / total_articles
- risk_level = min(int(combined_score * 1.2) + 3, 10)
-
- affected_regions = ["Europe", "Asia", "Global"]
- affected_sectors = ["energy", "chemicals", "transportation", "utilities", "airlines"]
-
- price_impacts = {
- "oil_prices": 0.4 * (risk_level / 10),
- "gas_prices": 0.5 * (risk_level / 10),
- "electricity": 0.3 * (risk_level / 10),
- "petrochemicals": 0.25 * (risk_level / 10)
- }
-
- return SupplyChainRisk(
- disruption_type="energy_supply_shock",
- affected_regions=affected_regions,
- risk_level=risk_level,
- affected_sectors=affected_sectors,
- price_impact=price_impacts,
- duration_estimate="6-18 months" if risk_level > 6 else "3-12 months",
- mitigation_difficulty="moderate"
- )
-
- except Exception as e:
- logging.error(f"Error analyzing energy supply: {e}")
- return None
-
- async def _analyze_critical_materials(self) -> Optional[SupplyChainRisk]:
- """Analyze critical materials and rare earth supply"""
- try:
- # Fetch critical materials news
- materials_news = await self.data_manager.get_multi_source_data({
- "news": {
- "query": "rare earth metals lithium copper critical minerals",
- "sources": ["reuters", "bloomberg"],
- "hours_back": 120
- }
- })
-
- news_data = materials_news.get("news", [])
-
- # Critical materials risk factors
- supply_keywords = [
- "rare earth", "lithium shortage", "copper supply", "nickel",
- "cobalt", "critical minerals", "mining disruption"
- ]
-
- geopolitical_keywords = [
- "china rare earth", "mining sanctions", "export restrictions",
- "strategic materials", "supply security"
- ]
-
- supply_risk = 0
- geo_risk = 0
-
- for article in news_data:
- text = article.value.lower()
- supply_risk += sum(1 for keyword in supply_keywords if keyword in text)
- geo_risk += sum(1 for keyword in geopolitical_keywords if keyword in text)
-
- total_articles = len(news_data) if news_data else 1
- combined_risk = (supply_risk + geo_risk * 1.3) / total_articles
- risk_level = min(int(combined_risk * 1.1) + 4, 10)
-
- affected_regions = ["Global", "China", "Australia", "DRC"]
- affected_sectors = ["renewable_energy", "electric_vehicles", "electronics", "defense"]
-
- price_impacts = {
- "rare_earth_prices": 0.6 * (risk_level / 10),
- "battery_metals": 0.4 * (risk_level / 10),
- "renewable_energy_costs": 0.2 * (risk_level / 10)
- }
-
- return SupplyChainRisk(
- disruption_type="critical_materials_shortage",
- affected_regions=affected_regions,
- risk_level=risk_level,
- affected_sectors=affected_sectors,
- price_impact=price_impacts,
- duration_estimate="12-36 months" if risk_level > 7 else "6-24 months",
- mitigation_difficulty="high" # Limited alternative sources
- )
-
- except Exception as e:
- logging.error(f"Error analyzing critical materials: {e}")
- return None
-
- async def get_supply_chain_report(self) -> Dict:
- """Generate comprehensive supply chain risk report"""
- # Analyze supply chain risks
- supply_risks = await self.analyze_supply_chains()
-
- # Calculate overall supply chain stress
- overall_stress = self._calculate_supply_chain_stress(supply_risks)
-
- # Generate investment implications
- investment_implications = self._generate_investment_implications(supply_risks)
-
- # Generate LLM analysis
- llm_analysis = await self._generate_supply_chain_llm_analysis(supply_risks)
-
- return {
- "timestamp": datetime.now().isoformat(),
- "agent": self.name,
- "supply_chain_analysis": {
- "overall_stress_level": overall_stress,
- "stress_classification": self._classify_stress_level(overall_stress),
- "major_risks": [{
- "disruption_type": risk.disruption_type,
- "risk_level": risk.risk_level,
- "affected_regions": risk.affected_regions,
- "affected_sectors": risk.affected_sectors,
- "price_impact": risk.price_impact,
- "duration": risk.duration_estimate,
- "mitigation_difficulty": risk.mitigation_difficulty
- } for risk in supply_risks]
- },
- "investment_implications": investment_implications,
- "sector_impact_analysis": self._analyze_sector_impacts(supply_risks),
- "geographic_exposure": self._analyze_geographic_exposure(supply_risks),
- "llm_analysis": llm_analysis,
- "monitoring_priorities": {
- "high_risk_disruptions": [risk.disruption_type for risk in supply_risks if risk.risk_level >= 7],
- "critical_chokepoints": self._identify_critical_chokepoints(supply_risks),
- "early_warning_indicators": [
- "Shipping container rates", "Semiconductor lead times",
- "Energy price volatility", "Critical mineral inventories"
- ]
- }
- }
-
- def _calculate_supply_chain_stress(self, risks: List[SupplyChainRisk]) -> float:
- """Calculate overall supply chain stress level"""
- if not risks:
- return 3.0 # Baseline stress
-
- # Weight risks by severity and mitigation difficulty
- weighted_stress = 0
- total_weight = 0
-
- difficulty_multipliers = {"low": 0.8, "moderate": 1.0, "high": 1.3}
-
- for risk in risks:
- multiplier = difficulty_multipliers.get(risk.mitigation_difficulty, 1.0)
- weight = risk.risk_level * multiplier
- weighted_stress += weight
- total_weight += 1
-
- return weighted_stress / total_weight if total_weight > 0 else 3.0
-
- def _classify_stress_level(self, stress_level: float) -> str:
- """Classify supply chain stress level"""
- if stress_level >= 8:
- return "critical"
- elif stress_level >= 6:
- return "high"
- elif stress_level >= 4:
- return "moderate"
- else:
- return "low"
-
- def _generate_investment_implications(self, risks: List[SupplyChainRisk]) -> Dict:
- """Generate investment implications from supply chain risks"""
- implications = {
- "beneficiary_sectors": [],
- "vulnerable_sectors": [],
- "geographic_allocation": {},
- "commodity_exposure": {},
- "hedging_strategies": []
- }
-
- # Aggregate sector impacts
- sector_impact_totals = {}
-
- for risk in risks:
- # Get sector impacts for this disruption type
- if risk.disruption_type in self.sector_impacts:
- sector_impacts = self.sector_impacts[risk.disruption_type]
- for sector, impact in sector_impacts.items():
- sector_impact_totals[sector] = sector_impact_totals.get(sector, 0) + impact * (risk.risk_level / 10)
-
- # Classify sectors
- for sector, total_impact in sector_impact_totals.items():
- if total_impact > 0.2:
- implications["beneficiary_sectors"].append(sector)
- elif total_impact < -0.2:
- implications["vulnerable_sectors"].append(sector)
-
- # Geographic allocation
- high_risk_regions = set()
- for risk in risks:
- if risk.risk_level >= 6:
- high_risk_regions.update(risk.affected_regions)
-
- implications["geographic_allocation"] = {
- "avoid": list(high_risk_regions),
- "prefer": ["North America", "Australia"] if "Asia" in high_risk_regions else ["Domestic markets"]
- }
-
- # Commodity exposure
- for risk in risks:
- for commodity, impact in risk.price_impact.items():
- if impact > 0.1:
- implications["commodity_exposure"][commodity] = "positive" if impact > 0 else "negative"
-
- # Hedging strategies
- if any(risk.risk_level >= 7 for risk in risks):
- implications["hedging_strategies"].extend([
- "Commodity price hedging",
- "Supply chain diversification",
- "Inventory buffers"
- ])
-
- return implications
-
- def _analyze_sector_impacts(self, risks: List[SupplyChainRisk]) -> Dict[str, Dict]:
- """Analyze impact on different sectors"""
- sector_analysis = {}
-
- # Aggregate all affected sectors
- all_sectors = set()
- for risk in risks:
- all_sectors.update(risk.affected_sectors)
-
- for sector in all_sectors:
- sector_risks = [risk for risk in risks if sector in risk.affected_sectors]
-
- if sector_risks:
- avg_risk_level = np.mean([risk.risk_level for risk in sector_risks])
- max_risk_level = max(risk.risk_level for risk in sector_risks)
-
- sector_analysis[sector] = {
- "average_risk_level": avg_risk_level,
- "maximum_risk_level": max_risk_level,
- "number_of_risks": len(sector_risks),
- "primary_risks": [risk.disruption_type for risk in sector_risks[:3]],
- "investment_recommendation": self._get_sector_recommendation(avg_risk_level)
- }
-
- return sector_analysis
-
- def _get_sector_recommendation(self, risk_level: float) -> str:
- """Get investment recommendation based on sector risk level"""
- if risk_level >= 7:
- return "avoid"
- elif risk_level >= 5:
- return "underweight"
- elif risk_level >= 3:
- return "neutral"
- else:
- return "overweight"
-
- def _analyze_geographic_exposure(self, risks: List[SupplyChainRisk]) -> Dict[str, Dict]:
- """Analyze geographic exposure to supply chain risks"""
- geographic_analysis = {}
-
- # Aggregate all affected regions
- all_regions = set()
- for risk in risks:
- all_regions.update(risk.affected_regions)
-
- for region in all_regions:
- region_risks = [risk for risk in risks if region in risk.affected_regions]
-
- if region_risks:
- avg_risk = np.mean([risk.risk_level for risk in region_risks])
-
- geographic_analysis[region] = {
- "average_risk_level": avg_risk,
- "number_of_risks": len(region_risks),
- "primary_disruption_types": list(set(risk.disruption_type for risk in region_risks)),
- "investment_stance": "defensive" if avg_risk >= 6 else "neutral" if avg_risk >= 4 else "opportunistic"
- }
-
- return geographic_analysis
-
- def _identify_critical_chokepoints(self, risks: List[SupplyChainRisk]) -> List[str]:
- """Identify critical supply chain chokepoints"""
- critical_points = []
-
- for risk in risks:
- if risk.risk_level >= 6 and risk.mitigation_difficulty == "high":
- # These are critical chokepoints
- if risk.disruption_type == "semiconductor_shortage":
- critical_points.extend(["Taiwan semiconductor fabs", "ASML lithography"])
- elif risk.disruption_type == "shipping_logistics":
- critical_points.extend(["Suez Canal", "Panama Canal", "Shanghai ports"])
- elif risk.disruption_type == "energy_supply_shock":
- critical_points.extend(["Russian pipelines", "Strait of Hormuz"])
- elif risk.disruption_type == "critical_materials_shortage":
- critical_points.extend(["China rare earth production", "DRC cobalt mines"])
-
- return list(set(critical_points)) # Remove duplicates
-
- async def _generate_supply_chain_llm_analysis(self, risks: List[SupplyChainRisk]) -> Dict:
- """Generate LLM-enhanced supply chain analysis"""
- try:
- # Prepare risk summary
- risk_summary = self._prepare_risk_summary(risks)
-
- prompt = f"""
- As a senior supply chain risk analyst, analyze current global supply chain disruptions and provide investment guidance.
-
- Current Supply Chain Risks:
- {risk_summary}
-
- Please provide:
- 1. Most critical supply chain vulnerabilities requiring immediate attention
- 2. Investment opportunities arising from supply chain disruptions
- 3. Sector rotation strategy based on supply chain resilience
- 4. Geographic diversification recommendations
- 5. Timeline for supply chain normalization
- 6. Early warning indicators for supply chain crises
-
- Format as JSON with keys: critical_vulnerabilities, investment_opportunities, sector_strategy,
- geographic_diversification, normalization_timeline, early_warning_indicators
- """
-
- response = self.client.chat.completions.create(
- model=CONFIG.llm.deep_think_model,
- messages=[{"role": "user", "content": prompt}],
- temperature=CONFIG.llm.temperature,
- max_tokens=CONFIG.llm.max_tokens
- )
-
- return json.loads(response.choices[0].message.content)
-
- except Exception as e:
- logging.error(f"Error in LLM supply chain analysis: {e}")
- return {
- "critical_vulnerabilities": ["Semiconductor supply", "Energy security", "Shipping bottlenecks"],
- "investment_opportunities": ["Supply chain technology", "Regional suppliers", "Inventory management"],
- "sector_strategy": "Overweight supply chain resilient sectors, underweight vulnerable ones",
- "geographic_diversification": "Reduce Asia concentration, increase nearshoring exposure",
- "normalization_timeline": "18-36 months for full normalization",
- "early_warning_indicators": ["Container shipping rates", "Commodity inventories", "Trade flow data"]
- }
-
- def _prepare_risk_summary(self, risks: List[SupplyChainRisk]) -> str:
- """Prepare risk summary for LLM analysis"""
- summary_lines = []
-
- for risk in risks:
- summary_lines.append(
- f"{risk.disruption_type}: Risk Level {risk.risk_level}/10, "
- f"Regions: {', '.join(risk.affected_regions[:3])}, "
- f"Duration: {risk.duration_estimate}, "
- f"Sectors: {', '.join(risk.affected_sectors[:3])}, "
- f"Mitigation: {risk.mitigation_difficulty}"
- )
-
- return "\n".join(summary_lines) if summary_lines else "No major supply chain risks identified"
\ No newline at end of file
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
deleted file mode 100644
index d59948906..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/hedge_fund_agent_cli.py
+++ /dev/null
@@ -1,316 +0,0 @@
-#!/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(argv=None):
- 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(argv)
-
- try:
- result = execute_agent(json.loads(args.parameters), json.loads(args.inputs))
- result_json = json.dumps(result, indent=2)
- print(result_json)
- return result_json
- 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()