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.

feat: Add comprehensive Economic Agents system with multiple economic models

rudrasheth301a2443ab57
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/base_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/base_agent.py
new file mode 100644
index 000000000..c71677037
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/base_agent.py
@@ -0,0 +1,74 @@
+"""
+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/Economic agents/capitalism_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/capitalism_agent.py
new file mode 100644
index 000000000..f6f030bfa
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/capitalism_agent.py
@@ -0,0 +1,282 @@
+"""
+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/Economic agents/cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/cli.py
new file mode 100644
index 000000000..062b3a051
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/cli.py
@@ -0,0 +1,588 @@
+"""
+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()
+ 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():
+ """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/Economic agents/comparison.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/comparison.py
new file mode 100644
index 000000000..44e408413
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/comparison.py
@@ -0,0 +1,604 @@
+"""
+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/Economic agents/config.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/config.py
new file mode 100644
index 000000000..a67b3d970
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/config.py
@@ -0,0 +1,431 @@
+"""
+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/Economic agents/data_processor.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/data_processor.py
new file mode 100644
index 000000000..333a147f7
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/data_processor.py
@@ -0,0 +1,488 @@
+"""
+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/Economic agents/example_usage.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/example_usage.py
new file mode 100644
index 000000000..36409166f
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/example_usage.py
@@ -0,0 +1,179 @@
+"""
+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/Economic agents/keynesian_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/keynesian_agent.py
new file mode 100644
index 000000000..dfe4e266f
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/keynesian_agent.py
@@ -0,0 +1,449 @@
+"""
+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/Economic agents/mercantilist_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/mercantilist_agent.py
new file mode 100644
index 000000000..8e5aa5736
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/mercantilist_agent.py
@@ -0,0 +1,374 @@
+"""
+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/Economic agents/mixed_economy_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/mixed_economy_agent.py
new file mode 100644
index 000000000..9f4f1cebf
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/mixed_economy_agent.py
@@ -0,0 +1,376 @@
+"""
+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/Economic agents/neoliberal_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/neoliberal_agent.py
new file mode 100644
index 000000000..2bbcbd145
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/neoliberal_agent.py
@@ -0,0 +1,367 @@
+"""
+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/Economic agents/socialism_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/socialism_agent.py
new file mode 100644
index 000000000..6a16ffcaa
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/socialism_agent.py
@@ -0,0 +1,325 @@
+"""
+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/Economic agents/utils.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/utils.py
new file mode 100644
index 000000000..540fac264
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/Economic agents/utils.py
@@ -0,0 +1,366 @@
+"""
+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