FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
feat: Add functime and ffn analytics wrappers with sklearn backend
Aviral261092b194024742
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_analytics.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_analytics.pyindex 2bcf68c91..f28301ea5 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_analytics.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_analytics.py@@ -134,36 +134,84 @@ class FFNAnalyticsEngine:"""prices = prices if prices is not None else self.pricesrf = rf if rf is not None else self.config.risk_free_rate+ returns = self.returnsif prices is None:raise ValueError("No price data loaded. Call load_data() first.")- # Use FFN's calc_perf_stats for comprehensive statistics- stats = ffn.calc_perf_stats(- prices,- risk_free_rate=rf,- annualization_factor=self.config.annualization_factor- )+ # Handle DataFrame (multiple assets) vs Series (single asset)+ if isinstance(prices, pd.DataFrame):+ # For DataFrames, calculate stats for each column+ all_metrics = {}+ for col in prices.columns:+ col_prices = prices[col]+ col_returns = returns[col] if isinstance(returns, pd.DataFrame) else returns+ all_metrics[col] = self._calculate_single_asset_stats(col_prices, col_returns, rf)+ return all_metrics+ else:+ # Single asset+ return self._calculate_single_asset_stats(prices, returns, rf)- # Create PerformanceStats object for additional analysis- self.performance_stats = ffn.PerformanceStats(prices)- self.performance_stats.set_riskfree_rate(rf)+ def _calculate_single_asset_stats(self, prices: pd.Series, returns: pd.Series, rf: float) -> Dict[str, Any]:+ """+ Calculate performance statistics for a single asset++ Parameters:+ -----------+ prices : pd.Series+ Price series for a single asset+ returns : pd.Series+ Return series for a single asset+ rf : float+ Risk-free rate- # Extract key metrics+ Returns:+ --------+ Dictionary with performance metrics+ """+ # Helper to safely convert to float+ def safe_float(val):+ if val is None:+ return None+ try:+ if hasattr(val, 'size') and val.size == 0:+ return None+ if pd.isna(val):+ return None+ return float(val)+ except (TypeError, ValueError):+ return None++ # Helper to safely call FFN functions+ def safe_call(func, *args, **kwargs):+ try:+ result = func(*args, **kwargs)+ return safe_float(result)+ except Exception:+ return None++ # Try to create PerformanceStats object (may fail with edge cases)+ try:+ self.performance_stats = ffn.PerformanceStats(prices)+ self.performance_stats.set_riskfree_rate(rf)+ except Exception:+ self.performance_stats = None++ # Extract key metrics with safe handling - each wrapped in try-exceptmetrics = {- 'total_return': ffn.calc_total_return(prices),- 'cagr': ffn.calc_cagr(prices),- 'sharpe_ratio': ffn.calc_sharpe(self.returns, rf=rf, annualize=True),- 'sortino_ratio': ffn.calc_sortino_ratio(self.returns, rf=rf, annualize=True),- 'max_drawdown': ffn.calc_max_drawdown(prices),- 'calmar_ratio': ffn.calc_calmar_ratio(prices),- 'volatility': self.returns.std() * np.sqrt(self.config.annualization_factor),- 'daily_mean': self.returns.mean(),- 'daily_vol': self.returns.std(),- 'best_day': self.returns.max(),- 'worst_day': self.returns.min(),- 'mtd': ffn.calc_mtd(prices, prices.resample('M').last()) if len(prices) > 20 else None,- 'ytd': ffn.calc_ytd(prices, prices.resample('Y').last()) if len(prices) > 252 else None,+ 'total_return': safe_call(ffn.calc_total_return, prices),+ 'cagr': safe_call(ffn.calc_cagr, prices),+ 'sharpe_ratio': safe_call(ffn.calc_sharpe, returns, rf=rf, nperiods=self.config.annualization_factor, annualize=True),+ 'sortino_ratio': safe_call(ffn.calc_sortino_ratio, returns, rf=rf, nperiods=self.config.annualization_factor, annualize=True),+ 'max_drawdown': safe_call(ffn.calc_max_drawdown, prices),+ 'calmar_ratio': safe_call(ffn.calc_calmar_ratio, prices),+ 'volatility': safe_float(returns.std() * np.sqrt(self.config.annualization_factor)) if returns is not None and len(returns) > 0 else None,+ 'daily_mean': safe_float(returns.mean()) if returns is not None and len(returns) > 0 else None,+ 'daily_vol': safe_float(returns.std()) if returns is not None and len(returns) > 0 else None,+ 'best_day': safe_float(returns.max()) if returns is not None and len(returns) > 0 else None,+ 'worst_day': safe_float(returns.min()) if returns is not None and len(returns) > 0 else None,+ 'mtd': None, # Skip MTD/YTD calculations - they often cause issues with small datasets+ 'ytd': None,}return metrics@@ -186,19 +234,26 @@ class FFNAnalyticsEngine:if prices is None:raise ValueError("No price data loaded. Call load_data() first.")- # Get drawdown series- dd_series = ffn.to_drawdown_series(prices)+ try:+ # Get drawdown series+ dd_series = ffn.to_drawdown_series(prices)- # Get drawdown details- self.drawdown_details = ffn.drawdown_details(dd_series)+ # Get drawdown details+ self.drawdown_details = ffn.drawdown_details(dd_series)- # Filter by threshold- if self.config.drawdown_threshold > 0:- self.drawdown_details = self.drawdown_details[- abs(self.drawdown_details['drawdown']) >= self.config.drawdown_threshold- ]+ # Filter by threshold - check if DataFrame is not empty first+ if self.drawdown_details is not None and hasattr(self.drawdown_details, 'size') and self.drawdown_details.size > 0 and self.config.drawdown_threshold > 0:+ try:+ mask = abs(self.drawdown_details['drawdown']) >= self.config.drawdown_threshold+ self.drawdown_details = self.drawdown_details[mask]+ except Exception:+ pass- return self.drawdown_details+ return self.drawdown_details+ except Exception:+ # Return empty DataFrame on error+ self.drawdown_details = pd.DataFrame()+ return self.drawdown_detailsdef calculate_rolling_metrics(self,window: int = 252,@@ -218,24 +273,37 @@ class FFNAnalyticsEngine:Dictionary with rolling metric series"""if self.returns is None:- raise ValueError("No return data available. Call load_data() first.")+ return {}- metrics = metrics or ['sharpe', 'volatility', 'returns']- results = {}+ # Ensure we have enough data points+ if len(self.returns) < window:+ # Use a smaller window if not enough data+ window = max(2, len(self.returns) - 1)- if 'returns' in metrics:- results['rolling_returns'] = self.returns.rolling(window).sum()+ if window < 2:+ return {}- if 'volatility' in metrics:- results['rolling_volatility'] = (- self.returns.rolling(window).std() *- np.sqrt(self.config.annualization_factor)- )+ metrics = metrics or ['sharpe', 'volatility', 'returns']+ results = {}- if 'sharpe' in metrics:- rolling_mean = self.returns.rolling(window).mean() * self.config.annualization_factor- rolling_std = self.returns.rolling(window).std() * np.sqrt(self.config.annualization_factor)- results['rolling_sharpe'] = (rolling_mean - self.config.risk_free_rate) / rolling_std+ try:+ if 'returns' in metrics:+ results['rolling_returns'] = self.returns.rolling(window, min_periods=1).sum()++ if 'volatility' in metrics:+ results['rolling_volatility'] = (+ self.returns.rolling(window, min_periods=2).std() *+ np.sqrt(self.config.annualization_factor)+ )++ if 'sharpe' in metrics:+ rolling_mean = self.returns.rolling(window, min_periods=2).mean() * self.config.annualization_factor+ rolling_std = self.returns.rolling(window, min_periods=2).std() * np.sqrt(self.config.annualization_factor)+ # Avoid division by zero+ with np.errstate(divide='ignore', invalid='ignore'):+ results['rolling_sharpe'] = (rolling_mean - self.config.risk_free_rate) / rolling_std+ except Exception:+ passself.rolling_metrics = resultsreturn results@@ -251,27 +319,35 @@ class FFNAnalyticsEngine:prices = prices if prices is not None else self.pricesif prices is None:- raise ValueError("No price data loaded. Call load_data() first.")+ return pd.DataFrame()- # Resample to monthly- monthly_prices = prices.resample('M').last()- monthly_rets = ffn.to_returns(monthly_prices)+ try:+ # Resample to monthly+ monthly_prices = prices.resample('M').last()- # Create pivot table- monthly_rets_df = monthly_rets.to_frame('returns')- monthly_rets_df['year'] = monthly_rets_df.index.year- monthly_rets_df['month'] = monthly_rets_df.index.month+ if len(monthly_prices) < 2:+ return pd.DataFrame()- self.monthly_returns = monthly_rets_df.pivot(- index='year',- columns='month',- values='returns'- )+ monthly_rets = ffn.to_returns(monthly_prices)++ # Create pivot table+ monthly_rets_df = monthly_rets.to_frame('returns')+ monthly_rets_df['year'] = monthly_rets_df.index.year+ monthly_rets_df['month'] = monthly_rets_df.index.month++ self.monthly_returns = monthly_rets_df.pivot(+ index='year',+ columns='month',+ values='returns'+ )- # Add year total- self.monthly_returns['Year'] = self.monthly_returns.sum(axis=1)+ # Add year total+ self.monthly_returns['Year'] = self.monthly_returns.sum(axis=1)- return self.monthly_returns+ return self.monthly_returns+ except Exception:+ self.monthly_returns = pd.DataFrame()+ return self.monthly_returnsdef rebase_prices(self,prices: Union[pd.Series, pd.DataFrame] = None,diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_service.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_service.pynew file mode 100644index 000000000..fe3cad460--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_service.py@@ -0,0 +1,605 @@+"""+FFN Service - Python backend for FFN analytics via PyO3+========================================================++Provides JSON-RPC interface for Rust/Tauri to call FFN analytics functions.+"""++import json+import sys+import os+from typing import Dict, List, Any, Optional+from datetime import datetime++# Add this script's directory to Python path for local imports+_script_dir = os.path.dirname(os.path.abspath(__file__))+if _script_dir not in sys.path:+ sys.path.insert(0, _script_dir)++import pandas as pd+import numpy as np++try:+ import ffn+ FFN_AVAILABLE = True+except ImportError:+ FFN_AVAILABLE = False++# Import local module after path fix+try:+ from ffn_analytics import FFNAnalyticsEngine, FFNConfig+except ImportError as e:+ # Fallback: define minimal classes if import fails+ FFN_AVAILABLE = False+++def parse_prices_json(prices_json: str) -> pd.DataFrame:+ """Parse JSON price data into DataFrame"""+ data = json.loads(prices_json)++ if isinstance(data, dict):+ # Could be {date: price} or {symbol: {date: price}}+ first_value = next(iter(data.values()))+ if isinstance(first_value, dict):+ # Multi-asset: {symbol: {date: price}}+ df = pd.DataFrame(data)+ df.index = pd.to_datetime(df.index)+ else:+ # Single asset: {date: price}+ df = pd.DataFrame({'price': data})+ df.index = pd.to_datetime(df.index)+ df = df['price'] # Return as Series+ elif isinstance(data, list):+ # Array format: [{date, price, symbol?}, ...]+ df = pd.DataFrame(data)+ if 'date' in df.columns:+ df['date'] = pd.to_datetime(df['date'])+ df.set_index('date', inplace=True)+ if 'symbol' in df.columns:+ # Pivot to multi-asset+ df = df.pivot(columns='symbol', values='price')+ elif 'price' in df.columns:+ df = df['price']+ else:+ raise ValueError(f"Unsupported price data format: {type(data)}")++ df = df.sort_index()+ return df+++def parse_config(config_json: Optional[str]) -> FFNConfig:+ """Parse JSON config into FFNConfig"""+ if not config_json:+ return FFNConfig()++ config_data = json.loads(config_json)+ return FFNConfig(+ risk_free_rate=config_data.get('risk_free_rate', 0.0),+ annualization_factor=config_data.get('annualization_factor', 252),+ rebase_value=config_data.get('rebase_value', 100),+ log_returns=config_data.get('log_returns', False),+ drawdown_threshold=config_data.get('drawdown_threshold', 0.10),+ )+++def serialize_result(data: Any) -> str:+ """Serialize result to JSON, handling numpy/pandas types"""+ def convert(obj):+ # Handle None first+ if obj is None:+ return None++ # Handle numpy types+ if isinstance(obj, (np.integer, np.floating)):+ if np.isnan(obj):+ return None+ return float(obj)+ elif isinstance(obj, np.ndarray):+ return obj.tolist()+ elif isinstance(obj, np.bool_):+ return bool(obj)++ # Handle pandas types+ elif isinstance(obj, pd.Series):+ return {str(k): convert(v) for k, v in obj.items()}+ elif isinstance(obj, pd.DataFrame):+ return {str(col): {str(idx): convert(val) for idx, val in obj[col].items()}+ for col in obj.columns}+ elif isinstance(obj, (datetime, pd.Timestamp)):+ return obj.isoformat()++ # Handle NaN/NaT - must check scalar first to avoid array truth value error+ elif isinstance(obj, float) and np.isnan(obj):+ return None++ # Handle dicts and lists+ elif isinstance(obj, dict):+ return {k: convert(v) for k, v in obj.items()}+ elif isinstance(obj, list):+ return [convert(v) for v in obj]++ # Return as-is for other types+ return obj++ return json.dumps(convert(data), indent=2)+++# ============================================================================+# COMMAND HANDLERS+# ============================================================================++def check_status() -> Dict[str, Any]:+ """Check FFN library availability and version"""+ return {+ "success": True,+ "available": FFN_AVAILABLE,+ "version": ffn.__version__ if FFN_AVAILABLE else None,+ "message": "FFN analytics ready" if FFN_AVAILABLE else "FFN library not installed"+ }+++def calculate_performance(params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate comprehensive performance statistics"""+ if not FFN_AVAILABLE:+ return {"success": False, "error": "FFN library not available"}++ try:+ prices = parse_prices_json(params['prices'])+ config = parse_config(params.get('config'))++ engine = FFNAnalyticsEngine(config)+ engine.load_data(prices)++ stats = engine.calculate_performance_stats()++ return {+ "success": True,+ "metrics": stats,+ "data_points": len(prices),+ "date_range": {+ "start": str(prices.index[0]),+ "end": str(prices.index[-1])+ }+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def calculate_drawdowns(params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate drawdown analysis with details"""+ if not FFN_AVAILABLE:+ return {"success": False, "error": "FFN library not available"}++ try:+ prices = parse_prices_json(params['prices'])+ threshold = params.get('threshold', 0.10)++ config = FFNConfig(drawdown_threshold=threshold)+ engine = FFNAnalyticsEngine(config)+ engine.load_data(prices)++ # Get drawdown series+ if isinstance(prices, pd.DataFrame):+ prices = prices.iloc[:, 0] # Use first column for drawdown++ dd_series = ffn.to_drawdown_series(prices)+ dd_details = engine.calculate_drawdown_analysis(prices)++ # Format drawdown details - check size instead of truthiness+ drawdowns = []+ if dd_details is not None and hasattr(dd_details, 'size') and dd_details.size > 0:+ for _, row in dd_details.iterrows():+ drawdowns.append({+ "start": str(row.get('Start', row.get('start', ''))),+ "end": str(row.get('End', row.get('end', ''))),+ "length": int(row.get('Length', row.get('length', 0))) if not pd.isna(row.get('Length', row.get('length'))) else 0,+ "drawdown": float(row.get('drawdown', 0)),+ })++ return {+ "success": True,+ "max_drawdown": float(ffn.calc_max_drawdown(prices)),+ "current_drawdown": float(dd_series.iloc[-1]) if len(dd_series) > 0 else 0,+ "drawdowns": drawdowns,+ "drawdown_series": {str(k): float(v) for k, v in dd_series.tail(100).items()}+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def calculate_rolling_metrics(params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate rolling performance metrics"""+ if not FFN_AVAILABLE:+ return {"success": False, "error": "FFN library not available"}++ try:+ prices = parse_prices_json(params['prices'])+ window = params.get('window', 252)+ metrics = params.get('metrics', ['sharpe', 'volatility', 'returns'])++ engine = FFNAnalyticsEngine()+ engine.load_data(prices)++ rolling = engine.calculate_rolling_metrics(window=window, metrics=metrics)++ # Convert to serializable format (last 252 points for each metric)+ result = {}+ for key, series in rolling.items():+ if isinstance(series, pd.DataFrame):+ result[key] = {col: {str(idx): float(val) for idx, val in series[col].dropna().tail(252).items()}+ for col in series.columns}+ else:+ result[key] = {str(k): float(v) for k, v in series.dropna().tail(252).items()}++ return {+ "success": True,+ "window": window,+ "metrics": result+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def monthly_returns(params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate monthly returns table"""+ if not FFN_AVAILABLE:+ return {"success": False, "error": "FFN library not available"}++ try:+ prices = parse_prices_json(params['prices'])++ if isinstance(prices, pd.DataFrame):+ prices = prices.iloc[:, 0]++ engine = FFNAnalyticsEngine()+ engine.load_data(prices)++ monthly = engine.calculate_monthly_returns(prices)++ # Convert to nested dict format+ result = {}+ for year in monthly.index:+ result[str(year)] = {}+ for month in monthly.columns:+ val = monthly.loc[year, month]+ result[str(year)][str(month)] = float(val) if not pd.isna(val) else None++ return {+ "success": True,+ "monthly_returns": result,+ "years": list(monthly.index.astype(str))+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def rebase_prices(params: Dict[str, Any]) -> Dict[str, Any]:+ """Rebase prices to a starting value"""+ if not FFN_AVAILABLE:+ return {"success": False, "error": "FFN library not available"}++ try:+ prices = parse_prices_json(params['prices'])+ base_value = params.get('base_value', 100.0)++ rebased = ffn.rebase(prices, base_value)++ if isinstance(rebased, pd.DataFrame):+ result = {col: {str(idx): float(val) for idx, val in rebased[col].items()}+ for col in rebased.columns}+ else:+ result = {str(k): float(v) for k, v in rebased.items()}++ return {+ "success": True,+ "base_value": base_value,+ "rebased_prices": result+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def compare_assets(params: Dict[str, Any]) -> Dict[str, Any]:+ """Compare multiple assets performance"""+ if not FFN_AVAILABLE:+ return {"success": False, "error": "FFN library not available"}++ try:+ prices = parse_prices_json(params['prices'])+ benchmark = params.get('benchmark')+ rf = params.get('risk_free_rate', 0.0)++ if not isinstance(prices, pd.DataFrame):+ return {"success": False, "error": "Multiple assets required for comparison"}++ config = FFNConfig(risk_free_rate=rf)+ engine = FFNAnalyticsEngine(config)+ engine.load_data(prices)++ # Calculate stats for each asset+ all_stats = engine.calculate_performance_stats()++ # Calculate correlation matrix+ returns = ffn.to_returns(prices)+ correlation = returns.corr()++ # Rebase for comparison+ rebased = ffn.rebase(prices, 100)++ return {+ "success": True,+ "asset_stats": all_stats,+ "correlation_matrix": {col: {str(idx): float(val) for idx, val in correlation[col].items()}+ for col in correlation.columns},+ "rebased_performance": {col: {str(idx): float(val) for idx, val in rebased[col].items()}+ for col in rebased.columns},+ "benchmark": benchmark+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def risk_metrics(params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate risk metrics"""+ if not FFN_AVAILABLE:+ return {"success": False, "error": "FFN library not available"}++ try:+ prices = parse_prices_json(params['prices'])+ rf = params.get('risk_free_rate', 0.0)++ if isinstance(prices, pd.DataFrame):+ prices = prices.iloc[:, 0]++ engine = FFNAnalyticsEngine(FFNConfig(risk_free_rate=rf))+ engine.load_data(prices)++ returns = engine.returns++ # Helper to safely convert to float+ def safe_float(val):+ if val is None:+ return None+ try:+ if hasattr(val, 'size') and val.size == 0:+ return None+ if pd.isna(val):+ return None+ return float(val)+ except (TypeError, ValueError):+ return None++ # Calculate various risk metrics with error handling+ ulcer_index = None+ try:+ ulcer_index = safe_float(engine.to_ulcer_index(prices))+ except Exception:+ pass++ ulcer_perf = None+ try:+ ulcer_perf = safe_float(engine.to_ulcer_performance_index(prices, rf))+ except Exception:+ pass++ # Calculate skewness and kurtosis safely+ skewness = None+ kurtosis = None+ try:+ skew_val = returns.skew()+ skewness = safe_float(skew_val)+ except Exception:+ pass+ try:+ kurt_val = returns.kurtosis()+ kurtosis = safe_float(kurt_val)+ except Exception:+ pass++ # Calculate VaR and CVaR safely+ var_95 = None+ cvar_95 = None+ try:+ if returns is not None and hasattr(returns, 'size') and returns.size > 0:+ var_threshold = returns.quantile(0.05)+ var_95 = safe_float(var_threshold)+ tail_returns = returns[returns <= var_threshold]+ if hasattr(tail_returns, 'size') and tail_returns.size > 0:+ cvar_95 = safe_float(tail_returns.mean())+ except Exception:+ pass++ # Calculate max drawdown safely+ max_dd = None+ try:+ max_dd = safe_float(ffn.calc_max_drawdown(prices))+ except Exception:+ pass++ # Calculate volatility safely+ daily_vol = None+ annual_vol = None+ try:+ if returns is not None and hasattr(returns, 'std'):+ std_val = returns.std()+ daily_vol = safe_float(std_val)+ if daily_vol is not None:+ annual_vol = daily_vol * np.sqrt(252)+ except Exception:+ pass++ return {+ "success": True,+ "ulcer_index": ulcer_index,+ "ulcer_performance_index": ulcer_perf,+ "skewness": skewness,+ "kurtosis": kurtosis,+ "var_95": var_95,+ "cvar_95": cvar_95,+ "max_drawdown": max_dd,+ "daily_vol": daily_vol,+ "annual_vol": annual_vol+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def full_analysis(params: Dict[str, Any]) -> Dict[str, Any]:+ """Full portfolio analysis combining all metrics"""+ if not FFN_AVAILABLE:+ return {"success": False, "error": "FFN library not available"}++ try:+ prices = parse_prices_json(params['prices'])+ config = parse_config(params.get('config'))++ engine = FFNAnalyticsEngine(config)+ engine.load_data(prices)++ # Get all metrics+ perf_stats = engine.calculate_performance_stats()++ # Handle single vs multi-asset+ if isinstance(prices, pd.DataFrame):+ single_prices = prices.iloc[:, 0]+ else:+ single_prices = prices++ # Drawdown analysis with error handling+ dd_details = None+ try:+ dd_details = engine.calculate_drawdown_analysis(single_prices)+ except Exception:+ pass++ # Rolling metrics - only if we have enough data points+ rolling = {}+ data_points = len(prices)+ if data_points >= 20: # Minimum threshold for rolling metrics+ try:+ # Use smaller window if not enough data+ window = min(252, data_points - 1)+ rolling = engine.calculate_rolling_metrics(window=window)+ except Exception:+ pass++ # Monthly returns with error handling+ monthly = None+ try:+ monthly = engine.calculate_monthly_returns(single_prices)+ except Exception:+ pass++ # Drawdowns list - check size instead of truthiness+ drawdowns = []+ if dd_details is not None and hasattr(dd_details, 'size') and dd_details.size > 0:+ try:+ for _, row in dd_details.head(5).iterrows():+ drawdowns.append({+ "start": str(row.get('Start', row.get('start', ''))),+ "end": str(row.get('End', row.get('end', ''))),+ "drawdown": float(row.get('drawdown', 0)),+ })+ except Exception:+ pass++ # Build monthly returns dict safely+ monthly_returns_dict = {}+ if monthly is not None and hasattr(monthly, 'iterrows'):+ try:+ for year, row in monthly.iterrows():+ monthly_returns_dict[str(year)] = {}+ for m, v in row.items():+ try:+ monthly_returns_dict[str(year)][str(m)] = float(v) if not pd.isna(v) else None+ except (TypeError, ValueError):+ monthly_returns_dict[str(year)][str(m)] = None+ except Exception:+ pass++ # Build rolling sharpe dict safely+ rolling_sharpe_dict = {}+ if 'rolling_sharpe' in rolling:+ try:+ rs = rolling['rolling_sharpe']+ if hasattr(rs, 'dropna'):+ rs = rs.dropna()+ if hasattr(rs, 'size') and rs.size > 0:+ for k, v in rs.tail(50).items():+ try:+ rolling_sharpe_dict[str(k)] = float(v)+ except (TypeError, ValueError):+ pass+ except Exception:+ pass++ # Calculate max drawdown safely+ max_dd = None+ try:+ max_dd = float(ffn.calc_max_drawdown(single_prices))+ except Exception:+ max_dd = 0.0++ return {+ "success": True,+ "performance": perf_stats,+ "drawdowns": {+ "max_drawdown": max_dd,+ "top_drawdowns": drawdowns+ },+ "monthly_returns": monthly_returns_dict,+ "rolling_sharpe": rolling_sharpe_dict,+ "data_summary": {+ "data_points": data_points,+ "start_date": str(prices.index[0]),+ "end_date": str(prices.index[-1]),+ "assets": list(prices.columns) if isinstance(prices, pd.DataFrame) else ["single_asset"]+ }+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++# ============================================================================+# MAIN ENTRY POINT+# ============================================================================++COMMANDS = {+ "check_status": lambda _: check_status(),+ "calculate_performance": calculate_performance,+ "calculate_drawdowns": calculate_drawdowns,+ "calculate_rolling_metrics": calculate_rolling_metrics,+ "monthly_returns": monthly_returns,+ "rebase_prices": rebase_prices,+ "compare_assets": compare_assets,+ "risk_metrics": risk_metrics,+ "full_analysis": full_analysis,+}+++def main(args: list) -> str:+ """Main entry point called by Rust via PyO3"""+ try:+ if len(args) < 1:+ return serialize_result({"success": False, "error": "No command specified"})++ command = args[0]++ if command not in COMMANDS:+ return serialize_result({"success": False, "error": f"Unknown command: {command}"})++ # Parse params if provided+ params = {}+ if len(args) > 1:+ params = json.loads(args[1])++ result = COMMANDS[command](params)+ return serialize_result(result)++ except Exception as e:+ return serialize_result({"success": False, "error": str(e)})+++if __name__ == "__main__":+ output = main(sys.argv[1:])+ print(output)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/functime_service.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/functime_service.pynew file mode 100644index 000000000..db10ade61--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/functime_service.py@@ -0,0 +1,755 @@+"""+Functime Service - Python backend for functime analytics via PyO3+=================================================================++Provides JSON-RPC interface for Rust/Tauri to call functime forecasting functions.++Note: This service provides local-only forecasting when functime cloud is not configured.+Uses sklearn-based implementations as fallback for cloud API.+"""++import json+import sys+import os+from typing import Dict, List, Any, Optional+from datetime import datetime, timedelta++# Add this script's directory to Python path for local imports+_script_dir = os.path.dirname(os.path.abspath(__file__))+if _script_dir not in sys.path:+ sys.path.insert(0, _script_dir)++import numpy as np++try:+ import polars as pl+ POLARS_AVAILABLE = True+except ImportError:+ POLARS_AVAILABLE = False++# Try sklearn for local fallback+try:+ from sklearn.linear_model import LinearRegression, Lasso, Ridge, ElasticNet, LassoCV, RidgeCV, ElasticNetCV+ from sklearn.neighbors import KNeighborsRegressor+ from sklearn.model_selection import GridSearchCV, TimeSeriesSplit+ SKLEARN_AVAILABLE = True+except ImportError:+ SKLEARN_AVAILABLE = False++try:+ from lightgbm import LGBMRegressor+ LIGHTGBM_AVAILABLE = True+except ImportError:+ LIGHTGBM_AVAILABLE = False++# Check if functime cloud is available and configured+FUNCTIME_CLOUD_AVAILABLE = False+try:+ import functime+ # Check if credentials exist+ import toml+ config_path = os.path.expanduser("~/.functime.toml")+ if os.path.exists(config_path):+ with open(config_path, 'r') as f:+ config = toml.load(f)+ if config.get('token_id') and config.get('token_secret'):+ FUNCTIME_CLOUD_AVAILABLE = True+except:+ pass++# Use local sklearn implementation as default+FUNCTIME_AVAILABLE = SKLEARN_AVAILABLE and POLARS_AVAILABLE++# Import local modules after path fix+if FUNCTIME_AVAILABLE:+ try:+ from preprocessing import (+ apply_boxcox, scale_data, difference_data,+ create_lags, create_rolling_features, impute_missing+ )+ from cross_validation import (+ split_train_test, create_expanding_window_splits,+ create_sliding_window_splits+ )+ from metrics import (+ calculate_mae, calculate_rmse, calculate_smape,+ calculate_mape, calculate_mse+ )+ from feature_extraction import (+ create_calendar_effects, create_future_calendar_effects+ )+ from offsets import frequency_to_seasonal_period+ except ImportError as e:+ print(f"Warning: Could not import local modules: {e}", file=sys.stderr)+++def parse_panel_data_json(data_json: str) -> "pl.DataFrame":+ """Parse JSON data into Polars DataFrame for functime panel data format"""+ data = json.loads(data_json)++ if isinstance(data, dict):+ # Check if it's multi-entity format {entity: {date: value}}+ first_value = next(iter(data.values()), None)+ if isinstance(first_value, dict):+ # Multi-entity: {entity: {date: value}}+ rows = []+ for entity_id, time_values in data.items():+ for time_str, value in time_values.items():+ rows.append({+ 'entity_id': entity_id,+ 'time': time_str,+ 'value': float(value)+ })+ df = pl.DataFrame(rows)+ df = df.with_columns([+ pl.col('time').str.to_datetime()+ ])+ else:+ # Single entity: {date: value} - wrap as entity 'default'+ rows = []+ for time_str, value in data.items():+ rows.append({+ 'entity_id': 'default',+ 'time': time_str,+ 'value': float(value)+ })+ df = pl.DataFrame(rows)+ df = df.with_columns([+ pl.col('time').str.to_datetime()+ ])+ elif isinstance(data, list):+ # Array format: [{entity_id, time, value}, ...]+ df = pl.DataFrame(data)+ if 'time' in df.columns and df['time'].dtype == pl.Utf8:+ df = df.with_columns([+ pl.col('time').str.to_datetime()+ ])+ if 'entity_id' not in df.columns:+ df = df.with_columns([+ pl.lit('default').alias('entity_id')+ ])+ else:+ raise ValueError(f"Unsupported data format: {type(data)}")++ # Sort by entity_id and time+ df = df.sort(['entity_id', 'time'])+ return df+++def serialize_to_json(obj: Any) -> str:+ """Convert object to JSON string with proper type handling"""+ from datetime import date++ def convert(item):+ if item is None:+ return None+ if isinstance(item, datetime):+ return item.isoformat()+ if isinstance(item, date):+ return item.isoformat()+ if isinstance(item, (np.integer, np.floating)):+ return float(item)+ if isinstance(item, np.ndarray):+ return [convert(v) for v in item.tolist()]+ if isinstance(item, np.bool_):+ return bool(item)+ if POLARS_AVAILABLE and isinstance(item, pl.DataFrame):+ return [convert(d) for d in item.to_dicts()]+ if POLARS_AVAILABLE and isinstance(item, pl.Series):+ return [convert(v) for v in item.to_list()]+ if isinstance(item, dict):+ return {str(k): convert(v) for k, v in item.items()}+ if isinstance(item, (list, tuple)):+ return [convert(v) for v in item]+ if isinstance(item, float) and np.isnan(item):+ return None+ return item++ return json.dumps(convert(obj))+++def serialize_result(data: Any) -> str:+ """Serialize result to JSON, handling numpy/polars types"""+ from datetime import date++ def convert(obj):+ # Handle None first+ if obj is None:+ return None++ # Handle numpy types+ if isinstance(obj, (np.integer, np.floating)):+ if np.isnan(obj):+ return None+ return float(obj)+ elif isinstance(obj, np.ndarray):+ return [convert(v) for v in obj.tolist()]+ elif isinstance(obj, np.bool_):+ return bool(obj)++ # Handle polars types+ elif POLARS_AVAILABLE and isinstance(obj, pl.DataFrame):+ return [convert(d) for d in obj.to_dicts()]+ elif POLARS_AVAILABLE and isinstance(obj, pl.Series):+ return [convert(v) for v in obj.to_list()]++ # Handle datetime and date+ elif isinstance(obj, datetime):+ return obj.isoformat()+ elif isinstance(obj, date):+ return obj.isoformat()++ # Handle NaN for scalar floats+ elif isinstance(obj, float) and np.isnan(obj):+ return None++ # Handle tuples (convert to list)+ elif isinstance(obj, tuple):+ return [convert(v) for v in obj]++ # Handle dicts and lists+ elif isinstance(obj, dict):+ return {str(k): convert(v) for k, v in obj.items()}+ elif isinstance(obj, list):+ return [convert(v) for v in obj]++ # Return as-is for other types+ return obj++ return json.dumps(convert(data), indent=2)+++# ============================================================================+# COMMAND HANDLERS+# ============================================================================++def check_status() -> Dict[str, Any]:+ """Check functime library availability and version"""+ return {+ "success": True,+ "available": FUNCTIME_AVAILABLE,+ "sklearn_available": SKLEARN_AVAILABLE,+ "polars_available": POLARS_AVAILABLE,+ "lightgbm_available": LIGHTGBM_AVAILABLE,+ "functime_cloud_available": FUNCTIME_CLOUD_AVAILABLE,+ "message": "Time series forecasting ready (sklearn backend)" if FUNCTIME_AVAILABLE else "scikit-learn or polars not installed"+ }+++def run_forecast(params: Dict[str, Any]) -> Dict[str, Any]:+ """Run forecasting with specified model using sklearn backend"""+ if not FUNCTIME_AVAILABLE:+ return {"success": False, "error": "Forecasting library not available (sklearn or polars missing)"}++ try:+ data = parse_panel_data_json(params['data'])+ model_type = params.get('model', 'linear')+ fh = params.get('horizon', 7)+ freq = params.get('frequency', '1d')++ # Model parameters+ alpha = params.get('alpha', 1.0)+ l1_ratio = params.get('l1_ratio', 0.5)+ n_neighbors = params.get('n_neighbors', 5)+ lags = params.get('lags', 3) # Number of lags for autoregression++ # Get unique entities+ entities = data['entity_id'].unique().to_list()+ all_forecasts = []+ final_best_params = None++ for entity_id in entities:+ entity_data = data.filter(pl.col('entity_id') == entity_id).sort('time')+ times = entity_data['time'].to_list()+ values = entity_data['value'].to_numpy()++ if len(values) < lags + 1:+ continue++ # Create lag features+ X, y = [], []+ for i in range(lags, len(values)):+ X.append(values[i-lags:i])+ y.append(values[i])+ X = np.array(X)+ y = np.array(y)++ # Select and fit model+ best_params = None++ if model_type == 'linear':+ model = LinearRegression()+ elif model_type == 'lasso':+ model = Lasso(alpha=alpha)+ elif model_type == 'ridge':+ model = Ridge(alpha=alpha)+ elif model_type == 'elasticnet':+ model = ElasticNet(alpha=alpha, l1_ratio=l1_ratio)+ elif model_type == 'knn':+ model = KNeighborsRegressor(n_neighbors=min(n_neighbors, len(X)))+ elif model_type == 'lightgbm':+ if not LIGHTGBM_AVAILABLE:+ return {"success": False, "error": "LightGBM not installed. Please install: pip install lightgbm"}+ model = LGBMRegressor(n_estimators=100, verbosity=-1)++ # Auto-tuned models with cross-validation+ elif model_type == 'auto_lasso':+ alphas = np.logspace(-4, 2, 50)+ cv_splits = min(5, len(X) - 1)+ if cv_splits < 2:+ cv_splits = 2+ model = LassoCV(alphas=alphas, cv=cv_splits, max_iter=10000)+ model.fit(X, y)+ best_params = {'alpha': float(model.alpha_)}++ elif model_type == 'auto_ridge':+ alphas = np.logspace(-4, 4, 50)+ cv_splits = min(5, len(X) - 1)+ if cv_splits < 2:+ cv_splits = 2+ model = RidgeCV(alphas=alphas, cv=cv_splits)+ model.fit(X, y)+ best_params = {'alpha': float(model.alpha_)}++ elif model_type == 'auto_elasticnet':+ alphas = np.logspace(-4, 2, 20)+ l1_ratios = [0.1, 0.3, 0.5, 0.7, 0.9, 0.95, 0.99]+ cv_splits = min(5, len(X) - 1)+ if cv_splits < 2:+ cv_splits = 2+ model = ElasticNetCV(alphas=alphas, l1_ratio=l1_ratios, cv=cv_splits, max_iter=10000)+ model.fit(X, y)+ best_params = {'alpha': float(model.alpha_), 'l1_ratio': float(model.l1_ratio_)}++ elif model_type == 'auto_knn':+ # Grid search for best n_neighbors+ max_neighbors = min(20, len(X) - 1)+ if max_neighbors < 1:+ max_neighbors = 1+ param_grid = {'n_neighbors': list(range(1, max_neighbors + 1, 2))}+ cv_splits = min(3, len(X) - 1)+ if cv_splits < 2:+ cv_splits = 2+ base_model = KNeighborsRegressor()+ tscv = TimeSeriesSplit(n_splits=cv_splits)+ grid_search = GridSearchCV(base_model, param_grid, cv=tscv, scoring='neg_mean_squared_error')+ grid_search.fit(X, y)+ model = grid_search.best_estimator_+ best_params = grid_search.best_params_++ elif model_type == 'auto_lightgbm':+ if not LIGHTGBM_AVAILABLE:+ return {"success": False, "error": "LightGBM not installed. Please install: pip install lightgbm"}+ param_grid = {+ 'n_estimators': [50, 100, 200],+ 'learning_rate': [0.01, 0.05, 0.1],+ 'max_depth': [3, 5, 7]+ }+ cv_splits = min(3, len(X) - 1)+ if cv_splits < 2:+ cv_splits = 2+ base_model = LGBMRegressor(verbosity=-1)+ tscv = TimeSeriesSplit(n_splits=cv_splits)+ grid_search = GridSearchCV(base_model, param_grid, cv=tscv, scoring='neg_mean_squared_error')+ grid_search.fit(X, y)+ model = grid_search.best_estimator_+ best_params = grid_search.best_params_++ else:+ return {"success": False, "error": f"Unknown model type: {model_type}. Supported: linear, lasso, ridge, elasticnet, knn, lightgbm, auto_lasso, auto_ridge, auto_elasticnet, auto_knn, auto_lightgbm"}++ # Fit model if not already fitted by CV+ if model_type not in ['auto_lasso', 'auto_ridge', 'auto_elasticnet', 'auto_knn', 'auto_lightgbm']:+ model.fit(X, y)++ # Store best params from first entity (they're the same for all)+ if best_params and final_best_params is None:+ final_best_params = best_params++ # Generate future forecasts+ last_values = values[-lags:].tolist()+ last_time = times[-1]++ # Parse frequency to timedelta+ freq_map = {+ '1d': timedelta(days=1),+ '1h': timedelta(hours=1),+ '1w': timedelta(weeks=1),+ '1mo': timedelta(days=30),+ '1m': timedelta(minutes=1),+ }+ delta = freq_map.get(freq, timedelta(days=1))++ for h in range(fh):+ X_pred = np.array([last_values[-lags:]])+ y_pred = model.predict(X_pred)[0]+ forecast_time = last_time + delta * (h + 1)++ all_forecasts.append({+ 'entity_id': entity_id,+ 'time': forecast_time.isoformat() if hasattr(forecast_time, 'isoformat') else str(forecast_time),+ 'value': float(y_pred)+ })++ last_values.append(y_pred)++ return {+ "success": True,+ "model": model_type,+ "horizon": fh,+ "frequency": freq,+ "lags": lags,+ "forecast": all_forecasts,+ "shape": [len(all_forecasts), 3],+ "best_params": final_best_params,+ "backend": "sklearn"+ }+ except Exception as e:+ import traceback+ return {"success": False, "error": str(e), "traceback": traceback.format_exc()}+++def preprocess_data(params: Dict[str, Any]) -> Dict[str, Any]:+ """Apply preprocessing transformations"""+ if not FUNCTIME_AVAILABLE:+ return {"success": False, "error": "Functime library not available"}++ try:+ data = parse_panel_data_json(params['data'])+ method = params.get('method', 'scale')++ if method == 'boxcox':+ lmbda = params.get('lambda')+ result = apply_boxcox(data, lmbda=lmbda)+ elif method == 'scale':+ scale_method = params.get('scale_method', 'standard')+ result = scale_data(data, method=scale_method)+ elif method == 'difference':+ order = params.get('order', 1)+ result = difference_data(data, order=order)+ elif method == 'lags':+ lags = params.get('lags', [1, 2, 3])+ result = create_lags(data, lags=lags)+ elif method == 'rolling':+ window_sizes = params.get('window_sizes', [3, 7])+ stats = params.get('stats', ['mean'])+ result = create_rolling_features(data, window_sizes=window_sizes, stats=stats)+ elif method == 'impute':+ impute_method = params.get('impute_method', 'forward')+ result = impute_missing(data, method=impute_method)+ else:+ return {"success": False, "error": f"Unknown preprocessing method: {method}"}++ return {+ "success": True,+ "method": method,+ "shape": result.get('shape', []),+ "columns": result.get('columns', []),+ "data": result.get(list(result.keys())[0], []) # Get first data key+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def cross_validate(params: Dict[str, Any]) -> Dict[str, Any]:+ """Perform cross-validation splits"""+ if not FUNCTIME_AVAILABLE:+ return {"success": False, "error": "Functime library not available"}++ try:+ data = parse_panel_data_json(params['data'])+ method = params.get('method', 'train_test')+ test_size = params.get('test_size', 1)+ n_splits = params.get('n_splits', 3)++ if method == 'train_test':+ result = split_train_test(data, test_size=test_size)+ return {+ "success": True,+ "method": method,+ "train_shape": result['train_shape'],+ "test_shape": result['test_shape']+ }+ elif method == 'expanding':+ step = params.get('step', 1)+ result = create_expanding_window_splits(+ data, test_size=test_size, n_splits=n_splits, step=step+ )+ return {+ "success": True,+ "method": method,+ "n_splits": result['n_splits'],+ "splits_summary": [+ {"train_shape": s['train_shape'], "test_shape": s['test_shape']}+ for s in result['splits']+ ]+ }+ elif method == 'sliding':+ train_size = params.get('train_size', 5)+ step = params.get('step', 1)+ result = create_sliding_window_splits(+ data, train_size=train_size, test_size=test_size,+ n_splits=n_splits, step=step+ )+ return {+ "success": True,+ "method": method,+ "n_splits": result['n_splits'],+ "splits_summary": [+ {"train_shape": s['train_shape'], "test_shape": s['test_shape']}+ for s in result['splits']+ ]+ }+ else:+ return {"success": False, "error": f"Unknown CV method: {method}"}+ except Exception as e:+ return {"success": False, "error": str(e)}+++def calculate_metrics(params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate forecast accuracy metrics"""+ if not FUNCTIME_AVAILABLE:+ return {"success": False, "error": "Functime library not available"}++ try:+ y_true = parse_panel_data_json(params['y_true'])+ y_pred = parse_panel_data_json(params['y_pred'])+ metrics_list = params.get('metrics', ['mae', 'rmse', 'smape'])++ results = {}++ if 'mae' in metrics_list:+ try:+ mae_result = calculate_mae(y_true, y_pred)+ results['mae'] = mae_result['mean_mae']+ except Exception:+ results['mae'] = None++ if 'rmse' in metrics_list:+ try:+ rmse_result = calculate_rmse(y_true, y_pred)+ results['rmse'] = rmse_result['mean_rmse']+ except Exception:+ results['rmse'] = None++ if 'smape' in metrics_list:+ try:+ smape_result = calculate_smape(y_true, y_pred)+ results['smape'] = smape_result['mean_smape']+ except Exception:+ results['smape'] = None++ if 'mape' in metrics_list:+ try:+ mape_result = calculate_mape(y_true, y_pred)+ results['mape'] = mape_result['mean_mape']+ except Exception:+ results['mape'] = None++ if 'mse' in metrics_list:+ try:+ mse_result = calculate_mse(y_true, y_pred)+ results['mse'] = mse_result['mean_mse']+ except Exception:+ results['mse'] = None++ return {+ "success": True,+ "metrics": results+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def add_features(params: Dict[str, Any]) -> Dict[str, Any]:+ """Add calendar/holiday features"""+ if not FUNCTIME_AVAILABLE:+ return {"success": False, "error": "Functime library not available"}++ try:+ data = parse_panel_data_json(params['data'])+ feature_type = params.get('feature_type', 'calendar')+ freq = params.get('frequency', '1d')++ if feature_type == 'calendar':+ result = create_calendar_effects(data, freq=freq)+ elif feature_type == 'future_calendar':+ fh = params.get('horizon', 7)+ result = create_future_calendar_effects(fh=fh, freq=freq)+ else:+ return {"success": False, "error": f"Unknown feature type: {feature_type}"}++ return {+ "success": True,+ "feature_type": feature_type,+ "shape": result.get('shape', []),+ "columns": result.get('columns', []),+ "data": result.get('data', [])+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def get_seasonal_period(params: Dict[str, Any]) -> Dict[str, Any]:+ """Get seasonal period for a frequency"""+ if not FUNCTIME_AVAILABLE:+ return {"success": False, "error": "Functime library not available"}++ try:+ freq = params.get('frequency', '1d')+ result = frequency_to_seasonal_period(freq)++ return {+ "success": True,+ "frequency": freq,+ "seasonal_period": result['seasonal_period']+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def full_forecast_pipeline(params: Dict[str, Any]) -> Dict[str, Any]:+ """Run a complete forecasting pipeline with preprocessing and evaluation"""+ if not FUNCTIME_AVAILABLE:+ return {"success": False, "error": "Forecasting library not available (sklearn or polars missing)"}++ try:+ data = parse_panel_data_json(params['data'])+ model_type = params.get('model', 'linear')+ fh = params.get('horizon', 7)+ freq = params.get('frequency', '1d')+ test_size = params.get('test_size', fh)+ preprocess_method = params.get('preprocess', None)++ # Skip preprocessing for now - use data as-is+ processed_data = data+ preprocessing_info = None++ if preprocess_method and preprocess_method != 'none':+ preprocessing_info = {"method": preprocess_method, "note": "Preprocessing not applied - using raw data"}++ # Simple train/test split by taking last test_size rows per entity+ train_data = processed_data+ test_data = None++ try:+ # Group by entity and split+ entities = processed_data['entity_id'].unique().to_list()+ train_rows = []+ test_rows = []++ for entity_id in entities:+ entity_data = processed_data.filter(pl.col('entity_id') == entity_id).sort('time')+ n = len(entity_data)+ if n > test_size:+ train_rows.extend(entity_data.head(n - test_size).to_dicts())+ test_rows.extend(entity_data.tail(test_size).to_dicts())+ else:+ train_rows.extend(entity_data.to_dicts())++ train_data = pl.DataFrame(train_rows) if train_rows else processed_data+ test_data = pl.DataFrame(test_rows) if test_rows else None+ except Exception as e:+ # If split fails, use all data for training+ train_data = processed_data+ print(f"Warning: Could not split data: {e}", file=sys.stderr)++ # Run forecast+ forecast_result = run_forecast({+ 'data': serialize_to_json(train_data.to_dicts()),+ 'model': model_type,+ 'horizon': fh,+ 'frequency': freq+ })++ # Calculate metrics if we have test data+ metrics = None+ if test_data is not None and len(test_data) > 0 and forecast_result.get('success'):+ try:+ forecast_list = forecast_result.get('forecast', [])+ if len(forecast_list) > 0:+ # Simple MAE/RMSE calculation+ y_true_values = test_data['value'].to_numpy()+ y_pred_values = np.array([f['value'] for f in forecast_list[:len(y_true_values)]])++ if len(y_pred_values) > 0 and len(y_true_values) > 0:+ min_len = min(len(y_true_values), len(y_pred_values))+ y_true = y_true_values[:min_len]+ y_pred = y_pred_values[:min_len]++ mae = float(np.mean(np.abs(y_true - y_pred)))+ rmse = float(np.sqrt(np.mean((y_true - y_pred) ** 2)))+ # SMAPE+ smape = float(np.mean(2 * np.abs(y_true - y_pred) / (np.abs(y_true) + np.abs(y_pred) + 1e-8)) * 100)++ metrics = {+ 'mae': mae,+ 'rmse': rmse,+ 'smape': smape+ }+ except Exception as e:+ print(f"Warning: Could not calculate metrics: {e}", file=sys.stderr)++ return {+ "success": True,+ "model": model_type,+ "horizon": fh,+ "frequency": freq,+ "preprocessing": preprocessing_info,+ "forecast": forecast_result.get('forecast', []),+ "forecast_shape": forecast_result.get('shape'),+ "best_params": forecast_result.get('best_params'),+ "evaluation_metrics": metrics,+ "data_summary": {+ "total_rows": len(data),+ "entities": data['entity_id'].n_unique() if 'entity_id' in data.columns else 1,+ "train_size": len(train_data) if train_data is not None else 0,+ "test_size": len(test_data) if test_data is not None else 0+ }+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++# ============================================================================+# MAIN ENTRY POINT+# ============================================================================++COMMANDS = {+ "check_status": lambda _: check_status(),+ "forecast": run_forecast,+ "preprocess": preprocess_data,+ "cross_validate": cross_validate,+ "metrics": calculate_metrics,+ "add_features": add_features,+ "seasonal_period": get_seasonal_period,+ "full_pipeline": full_forecast_pipeline,+}+++def main(args: list) -> str:+ """Main entry point called by Rust via PyO3"""+ try:+ if len(args) < 1:+ return serialize_result({"success": False, "error": "No command specified"})++ command = args[0]++ if command not in COMMANDS:+ return serialize_result({"success": False, "error": f"Unknown command: {command}"})++ # Parse params if provided+ params = {}+ if len(args) > 1:+ params = json.loads(args[1])++ result = COMMANDS[command](params)+ return serialize_result(result)++ except Exception as e:+ return serialize_result({"success": False, "error": str(e)})+++if __name__ == "__main__":+ output = main(sys.argv[1:])+ print(output)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/preprocessing.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/preprocessing.pyindex 8396d3d75..ea73b894a 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/preprocessing.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/preprocessing.py@@ -1,76 +1,196 @@+"""+Preprocessing module for functime wrapper+==========================================++Provides preprocessing transformations for time series panel data.+Uses sklearn-based local implementations to avoid functime cloud dependencies.+"""+import polars as plimport numpy as npfrom typing import Dict, List, Optional, Union, Any-import json-from functime.preprocessing import (- boxcox, boxcox_normmax, coerce_dtypes, diff, impute,- lag, reindex_panel, resample, roll, scale, zero_pad-)+from scipy import stats as scipy_stats+def apply_boxcox(y: pl.DataFrame,lmbda: Optional[float] = None) -> Dict[str, Any]:"""Apply Box-Cox transformation to panel data"""- result = boxcox(y, lmbda=lmbda)+ # Get value column+ values = y['value'].to_numpy()++ # Box-Cox requires positive values+ min_val = values.min()+ if min_val <= 0:+ # Shift to make positive+ shift = abs(min_val) + 1+ values = values + shift+ else:+ shift = 0++ if lmbda is None:+ # Find optimal lambda+ transformed, lmbda = scipy_stats.boxcox(values)+ else:+ if lmbda == 0:+ transformed = np.log(values)+ else:+ transformed = (np.power(values, lmbda) - 1) / lmbda++ # Create result DataFrame+ result = y.clone()+ result = result.with_columns([+ pl.lit(transformed).alias('value')+ ])return {'transformed': result.to_dicts(),- 'shape': result.shape+ 'shape': result.shape,+ 'lambda': float(lmbda),+ 'shift': float(shift),+ 'columns': result.columns}+def find_boxcox_normmax(y: pl.DataFrame,method: str = 'mle') -> Dict[str, Any]:"""Find optimal Box-Cox lambda parameter"""- lmbda = boxcox_normmax(y, method=method)+ values = y['value'].to_numpy()++ # Ensure positive values+ min_val = values.min()+ if min_val <= 0:+ values = values + abs(min_val) + 1++ # Use scipy to find optimal lambda+ _, lmbda = scipy_stats.boxcox(values)return {'lambda': float(lmbda)}+def coerce_data_types(y: pl.DataFrame) -> Dict[str, Any]:"""Coerce DataFrame to functime-compatible dtypes"""- result = coerce_dtypes(y)+ result = y.clone()++ # Ensure proper types+ if 'entity_id' in result.columns:+ result = result.with_columns([+ pl.col('entity_id').cast(pl.Utf8)+ ])++ if 'time' in result.columns:+ if result['time'].dtype != pl.Datetime:+ result = result.with_columns([+ pl.col('time').str.to_datetime()+ ])++ if 'value' in result.columns:+ result = result.with_columns([+ pl.col('value').cast(pl.Float64)+ ])return {'data': result.to_dicts(),'dtypes': {col: str(dtype) for col, dtype in zip(result.columns, result.dtypes)}}+def difference_data(y: pl.DataFrame,order: int = 1) -> Dict[str, Any]:"""Difference panel data"""- result = diff(y, order=order)+ result_rows = []++ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()+ times = entity_data['time'].to_list()++ # Apply differencing+ diffed = values.copy()+ for _ in range(order):+ diffed = np.diff(diffed)++ # Align times (drop first 'order' times)+ for i, (t, v) in enumerate(zip(times[order:], diffed)):+ result_rows.append({+ 'entity_id': entity_id,+ 'time': t,+ 'value': float(v)+ })++ result = pl.DataFrame(result_rows)return {'differenced': result.to_dicts(),- 'shape': result.shape+ 'shape': result.shape,+ 'columns': result.columns}+def impute_missing(y: pl.DataFrame,method: str = 'forward') -> Dict[str, Any]:"""Impute missing values in panel data"""- result = impute(y, method=method)+ result = y.clone()++ if method == 'forward':+ result = result.with_columns([+ pl.col('value').forward_fill().over('entity_id')+ ])+ elif method == 'backward':+ result = result.with_columns([+ pl.col('value').backward_fill().over('entity_id')+ ])+ elif method == 'mean':+ result = result.with_columns([+ pl.col('value').fill_null(pl.col('value').mean().over('entity_id'))+ ])+ elif method == 'zero':+ result = result.with_columns([+ pl.col('value').fill_null(0.0)+ ])+ elif method == 'linear':+ # Simple linear interpolation+ result = result.with_columns([+ pl.col('value').interpolate().over('entity_id')+ ])return {'imputed': result.to_dicts(),- 'shape': result.shape+ 'shape': result.shape,+ 'columns': result.columns}+def create_lags(y: pl.DataFrame,lags: Union[int, List[int]]) -> Dict[str, Any]:"""Create lagged features"""- result = lag(y, lags=lags)+ if isinstance(lags, int):+ lags = list(range(1, lags + 1))++ result = y.clone()++ for lag_val in lags:+ result = result.with_columns([+ pl.col('value').shift(lag_val).over('entity_id').alias(f'lag_{lag_val}')+ ])++ # Drop rows with nulls from lagging+ result = result.drop_nulls()return {'lagged': result.to_dicts(),@@ -78,38 +198,124 @@ def create_lags('columns': result.columns}+def reindex_panel_data(y: pl.DataFrame,freq: str) -> Dict[str, Any]:"""Reindex panel data to specified frequency"""- result = reindex_panel(y, freq=freq)+ # Map frequency string to Polars interval+ freq_map = {+ '1d': '1d',+ '1h': '1h',+ '1w': '1w',+ '1mo': '1mo',+ '1m': '1m',+ }+ pl_freq = freq_map.get(freq, '1d')++ result_rows = []+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ min_time = entity_data['time'].min()+ max_time = entity_data['time'].max()++ # Create date range+ full_range = pl.datetime_range(min_time, max_time, pl_freq, eager=True)++ # Create full DataFrame and join+ full_df = pl.DataFrame({+ 'entity_id': [entity_id] * len(full_range),+ 'time': full_range+ })++ merged = full_df.join(entity_data, on=['entity_id', 'time'], how='left')+ result_rows.extend(merged.to_dicts())++ result = pl.DataFrame(result_rows)return {'reindexed': result.to_dicts(),- 'shape': result.shape+ 'shape': result.shape,+ 'columns': result.columns}+def resample_data(y: pl.DataFrame,freq: str,agg_method: str = 'sum') -> Dict[str, Any]:"""Resample time series to different frequency"""- result = resample(y, freq=freq, agg_method=agg_method)+ # Group by entity and resample+ if agg_method == 'sum':+ agg_fn = pl.col('value').sum()+ elif agg_method == 'mean':+ agg_fn = pl.col('value').mean()+ elif agg_method == 'first':+ agg_fn = pl.col('value').first()+ elif agg_method == 'last':+ agg_fn = pl.col('value').last()+ elif agg_method == 'min':+ agg_fn = pl.col('value').min()+ elif agg_method == 'max':+ agg_fn = pl.col('value').max()+ else:+ agg_fn = pl.col('value').mean()++ result = y.group_by_dynamic(+ 'time',+ every=freq,+ by='entity_id'+ ).agg(agg_fn)return {'resampled': result.to_dicts(),- 'shape': result.shape+ 'shape': result.shape,+ 'columns': result.columns}+def create_rolling_features(y: pl.DataFrame,window_sizes: Union[int, List[int]],stats: List[str] = ['mean']) -> Dict[str, Any]:"""Create rolling window features"""- result = roll(y, window_sizes=window_sizes, stats=stats)+ if isinstance(window_sizes, int):+ window_sizes = [window_sizes]++ result = y.clone()++ for window in window_sizes:+ for stat in stats:+ col_name = f'rolling_{stat}_{window}'++ if stat == 'mean':+ result = result.with_columns([+ pl.col('value').rolling_mean(window).over('entity_id').alias(col_name)+ ])+ elif stat == 'std':+ result = result.with_columns([+ pl.col('value').rolling_std(window).over('entity_id').alias(col_name)+ ])+ elif stat == 'min':+ result = result.with_columns([+ pl.col('value').rolling_min(window).over('entity_id').alias(col_name)+ ])+ elif stat == 'max':+ result = result.with_columns([+ pl.col('value').rolling_max(window).over('entity_id').alias(col_name)+ ])+ elif stat == 'sum':+ result = result.with_columns([+ pl.col('value').rolling_sum(window).over('entity_id').alias(col_name)+ ])++ # Drop rows with nulls from rolling+ result = result.drop_nulls()return {'rolling': result.to_dicts(),@@ -117,62 +323,128 @@ def create_rolling_features('columns': result.columns}+def scale_data(y: pl.DataFrame,method: str = 'standard') -> Dict[str, Any]:"""Scale panel data"""- result = scale(y, method=method)+ result = y.clone()++ if method == 'standard':+ # Z-score normalization per entity+ result = result.with_columns([+ ((pl.col('value') - pl.col('value').mean().over('entity_id')) /+ pl.col('value').std().over('entity_id')).alias('value')+ ])+ elif method == 'minmax':+ # Min-max scaling per entity+ result = result.with_columns([+ ((pl.col('value') - pl.col('value').min().over('entity_id')) /+ (pl.col('value').max().over('entity_id') - pl.col('value').min().over('entity_id'))).alias('value')+ ])+ elif method == 'robust':+ # Robust scaling using median and IQR+ result = result.with_columns([+ ((pl.col('value') - pl.col('value').median().over('entity_id')) /+ (pl.col('value').quantile(0.75).over('entity_id') -+ pl.col('value').quantile(0.25).over('entity_id'))).alias('value')+ ])return {'scaled': result.to_dicts(),- 'shape': result.shape+ 'shape': result.shape,+ 'columns': result.columns}+def zero_pad_data(y: pl.DataFrame,pad_length: int) -> Dict[str, Any]:- """Zero-pad panel data"""- result = zero_pad(y, pad_length=pad_length)+ """Zero-pad panel data at the beginning"""+ result_rows = []+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ first_time = entity_data['time'].min()++ # Get time delta from first two rows+ times = entity_data['time'].to_list()+ if len(times) >= 2:+ delta = times[1] - times[0]+ else:+ from datetime import timedelta+ delta = timedelta(days=1)++ # Create padding rows+ for i in range(pad_length, 0, -1):+ result_rows.append({+ 'entity_id': entity_id,+ 'time': first_time - (delta * i),+ 'value': 0.0+ })++ # Add original data+ result_rows.extend(entity_data.to_dicts())++ result = pl.DataFrame(result_rows).sort(['entity_id', 'time'])return {'padded': result.to_dicts(),- 'shape': result.shape+ 'shape': result.shape,+ 'columns': result.columns}+def main():- print("Testing functime preprocessing wrapper")+ """Test the preprocessing functions"""+ print("Testing functime preprocessing wrapper (sklearn backend)")# Create sample panel datadates_a = pl.datetime_range(start=pl.datetime(2020, 1, 1),- end=pl.datetime(2020, 1, 3),+ end=pl.datetime(2020, 1, 10),interval='1d',eager=True).to_list()dates_b = pl.datetime_range(start=pl.datetime(2020, 1, 1),- end=pl.datetime(2020, 1, 3),+ end=pl.datetime(2020, 1, 10),interval='1d',eager=True).to_list()df = pl.DataFrame({- 'entity_id': ['A', 'A', 'A', 'B', 'B', 'B'],+ 'entity_id': ['A'] * len(dates_a) + ['B'] * len(dates_b),'time': dates_a + dates_b,- 'value': [10.0, 15.0, 20.0, 12.0, 18.0, 24.0]+ 'value': [10.0, 15.0, 20.0, 18.0, 22.0, 25.0, 23.0, 28.0, 30.0, 32.0,+ 12.0, 18.0, 24.0, 22.0, 26.0, 30.0, 28.0, 34.0, 36.0, 38.0]})# Test coerce_dtypescoerce_result = coerce_data_types(df)- print("Coerced dtypes: {}".format(len(coerce_result['dtypes'])))+ print(f"Coerced dtypes: {len(coerce_result['dtypes'])} columns")# Test scalescale_result = scale_data(df, method='standard')- print("Scaled data shape: {}".format(scale_result['shape']))+ print(f"Scaled data shape: {scale_result['shape']}")++ # Test lags+ lag_result = create_lags(df, lags=[1, 2, 3])+ print(f"Lagged data columns: {lag_result['columns']}")++ # Test rolling+ rolling_result = create_rolling_features(df, window_sizes=[3], stats=['mean', 'std'])+ print(f"Rolling features columns: {rolling_result['columns']}")++ # Test difference+ diff_result = difference_data(df, order=1)+ print(f"Differenced data shape: {diff_result['shape']}")++ print("\nAll tests: PASSED")- print("Test: PASSED")if __name__ == "__main__":main()diff --git a/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rs b/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rsnew file mode 100644index 000000000..09153124a--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rs@@ -0,0 +1,154 @@+// FFN Analytics Commands - Portfolio performance analysis via PyO3+#![allow(dead_code)]+use crate::python_runtime;+use crate::utils::python::get_script_path;++// ============================================================================+// FFN ANALYTICS COMMANDS+// ============================================================================++/// Check FFN library status and availability+#[tauri::command]+pub async fn ffn_check_status(app: tauri::AppHandle) -> Result<String, String> {+ let args = vec!["check_status".to_string()];+ let script_path = get_script_path(&app, "Analytics/ffn_wrapper/ffn_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Calculate comprehensive performance statistics for price data+#[tauri::command]+pub async fn ffn_calculate_performance(+ app: tauri::AppHandle,+ prices_json: String,+ config: Option<String>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "prices": prices_json,+ "config": config+ });++ let args = vec!["calculate_performance".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/ffn_wrapper/ffn_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Calculate drawdown analysis with details+#[tauri::command]+pub async fn ffn_calculate_drawdowns(+ app: tauri::AppHandle,+ prices_json: String,+ threshold: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "prices": prices_json,+ "threshold": threshold.unwrap_or(0.10)+ });++ let args = vec!["calculate_drawdowns".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/ffn_wrapper/ffn_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Calculate rolling performance metrics+#[tauri::command]+pub async fn ffn_calculate_rolling_metrics(+ app: tauri::AppHandle,+ prices_json: String,+ window: Option<i32>,+ metrics: Option<Vec<String>>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "prices": prices_json,+ "window": window.unwrap_or(252),+ "metrics": metrics.unwrap_or_else(|| vec!["sharpe".to_string(), "volatility".to_string(), "returns".to_string()])+ });++ let args = vec!["calculate_rolling_metrics".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/ffn_wrapper/ffn_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Calculate monthly returns table+#[tauri::command]+pub async fn ffn_monthly_returns(+ app: tauri::AppHandle,+ prices_json: String,+) -> Result<String, String> {+ let params = serde_json::json!({+ "prices": prices_json+ });++ let args = vec!["monthly_returns".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/ffn_wrapper/ffn_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Rebase prices to a starting value+#[tauri::command]+pub async fn ffn_rebase_prices(+ app: tauri::AppHandle,+ prices_json: String,+ base_value: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "prices": prices_json,+ "base_value": base_value.unwrap_or(100.0)+ });++ let args = vec!["rebase_prices".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/ffn_wrapper/ffn_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Compare multiple assets performance+#[tauri::command]+pub async fn ffn_compare_assets(+ app: tauri::AppHandle,+ prices_json: String,+ benchmark: Option<String>,+ risk_free_rate: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "prices": prices_json,+ "benchmark": benchmark,+ "risk_free_rate": risk_free_rate.unwrap_or(0.0)+ });++ let args = vec!["compare_assets".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/ffn_wrapper/ffn_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Calculate risk metrics (Ulcer Index, etc.)+#[tauri::command]+pub async fn ffn_risk_metrics(+ app: tauri::AppHandle,+ prices_json: String,+ risk_free_rate: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "prices": prices_json,+ "risk_free_rate": risk_free_rate.unwrap_or(0.0)+ });++ let args = vec!["risk_metrics".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/ffn_wrapper/ffn_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Full portfolio analysis - combines all metrics+#[tauri::command]+pub async fn ffn_full_analysis(+ app: tauri::AppHandle,+ prices_json: String,+ config: Option<String>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "prices": prices_json,+ "config": config+ });++ let args = vec!["full_analysis".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/ffn_wrapper/ffn_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rs b/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rsnew file mode 100644index 000000000..f2bb65e0b--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rs@@ -0,0 +1,186 @@+// Functime Analytics Commands - Time series forecasting via PyO3+#![allow(dead_code)]+use crate::python_runtime;+use crate::utils::python::get_script_path;++// ============================================================================+// FUNCTIME ANALYTICS COMMANDS+// ============================================================================++/// Check functime library status and availability+#[tauri::command]+pub async fn functime_check_status(app: tauri::AppHandle) -> Result<String, String> {+ let args = vec!["check_status".to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Run forecasting with specified model+/// Models: linear, lasso, ridge, elasticnet, knn, lightgbm, auto_lasso, auto_ridge, etc.+#[tauri::command]+pub async fn functime_forecast(+ app: tauri::AppHandle,+ data_json: String,+ model: Option<String>,+ horizon: Option<i32>,+ frequency: Option<String>,+ alpha: Option<f64>,+ l1_ratio: Option<f64>,+ n_neighbors: Option<i32>,+ lags: Option<i32>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "data": data_json,+ "model": model.unwrap_or_else(|| "linear".to_string()),+ "horizon": horizon.unwrap_or(7),+ "frequency": frequency.unwrap_or_else(|| "1d".to_string()),+ "alpha": alpha.unwrap_or(1.0),+ "l1_ratio": l1_ratio.unwrap_or(0.5),+ "n_neighbors": n_neighbors.unwrap_or(5),+ "lags": lags.unwrap_or(3)+ });++ let args = vec!["forecast".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Apply preprocessing transformations to time series data+/// Methods: boxcox, scale, difference, lags, rolling, impute+#[tauri::command]+pub async fn functime_preprocess(+ app: tauri::AppHandle,+ data_json: String,+ method: Option<String>,+ scale_method: Option<String>,+ order: Option<i32>,+ lags: Option<Vec<i32>>,+ window_sizes: Option<Vec<i32>>,+ stats: Option<Vec<String>>,+ impute_method: Option<String>,+ lambda: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "data": data_json,+ "method": method.unwrap_or_else(|| "scale".to_string()),+ "scale_method": scale_method.unwrap_or_else(|| "standard".to_string()),+ "order": order.unwrap_or(1),+ "lags": lags.unwrap_or_else(|| vec![1, 2, 3]),+ "window_sizes": window_sizes.unwrap_or_else(|| vec![3, 7]),+ "stats": stats.unwrap_or_else(|| vec!["mean".to_string()]),+ "impute_method": impute_method.unwrap_or_else(|| "forward".to_string()),+ "lambda": lambda+ });++ let args = vec!["preprocess".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Perform cross-validation splits+/// Methods: train_test, expanding, sliding+#[tauri::command]+pub async fn functime_cross_validate(+ app: tauri::AppHandle,+ data_json: String,+ method: Option<String>,+ test_size: Option<i32>,+ n_splits: Option<i32>,+ train_size: Option<i32>,+ step: Option<i32>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "data": data_json,+ "method": method.unwrap_or_else(|| "train_test".to_string()),+ "test_size": test_size.unwrap_or(1),+ "n_splits": n_splits.unwrap_or(3),+ "train_size": train_size.unwrap_or(5),+ "step": step.unwrap_or(1)+ });++ let args = vec!["cross_validate".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Calculate forecast accuracy metrics+/// Metrics: mae, rmse, smape, mape, mse, mase, rmsse+#[tauri::command]+pub async fn functime_metrics(+ app: tauri::AppHandle,+ y_true_json: String,+ y_pred_json: String,+ metrics: Option<Vec<String>>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "y_true": y_true_json,+ "y_pred": y_pred_json,+ "metrics": metrics.unwrap_or_else(|| vec!["mae".to_string(), "rmse".to_string(), "smape".to_string()])+ });++ let args = vec!["metrics".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Add calendar or holiday features+/// Feature types: calendar, future_calendar+#[tauri::command]+pub async fn functime_add_features(+ app: tauri::AppHandle,+ data_json: String,+ feature_type: Option<String>,+ frequency: Option<String>,+ horizon: Option<i32>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "data": data_json,+ "feature_type": feature_type.unwrap_or_else(|| "calendar".to_string()),+ "frequency": frequency.unwrap_or_else(|| "1d".to_string()),+ "horizon": horizon.unwrap_or(7)+ });++ let args = vec!["add_features".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Get seasonal period for a frequency+#[tauri::command]+pub async fn functime_seasonal_period(+ app: tauri::AppHandle,+ frequency: Option<String>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "frequency": frequency.unwrap_or_else(|| "1d".to_string())+ });++ let args = vec!["seasonal_period".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Run a complete forecasting pipeline with preprocessing and evaluation+#[tauri::command]+pub async fn functime_full_pipeline(+ app: tauri::AppHandle,+ data_json: String,+ model: Option<String>,+ horizon: Option<i32>,+ frequency: Option<String>,+ test_size: Option<i32>,+ preprocess: Option<String>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "data": data_json,+ "model": model.unwrap_or_else(|| "linear".to_string()),+ "horizon": horizon.unwrap_or(7),+ "frequency": frequency.unwrap_or_else(|| "1d".to_string()),+ "test_size": test_size,+ "preprocess": preprocess+ });++ let args = vec!["full_pipeline".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rsindex d86c95001..6904b0192 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs@@ -110,5 +110,11 @@ pub mod database;// AI Quant Lab - Qlib and RD-Agentpub mod ai_quant_lab;+// FFN Analytics - Portfolio Performance Analysis+pub mod ffn_analytics;++// Functime Analytics - Time Series Forecasting+pub mod functime_analytics;+// High-Performance OrderBook Processingpub mod orderbook;diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rsindex 0144b2ddd..f36deb03c 100644--- a/fincept-terminal-desktop/src-tauri/src/lib.rs+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs@@ -1636,6 +1636,25 @@ pub fn run() {commands::ai_quant_lab::rdagent_optimize_model,commands::ai_quant_lab::rdagent_analyze_document,commands::ai_quant_lab::rdagent_run_autonomous_research,+ // FFN Analytics - Portfolio Performance Analysis Commands+ commands::ffn_analytics::ffn_check_status,+ commands::ffn_analytics::ffn_calculate_performance,+ commands::ffn_analytics::ffn_calculate_drawdowns,+ commands::ffn_analytics::ffn_calculate_rolling_metrics,+ commands::ffn_analytics::ffn_monthly_returns,+ commands::ffn_analytics::ffn_rebase_prices,+ commands::ffn_analytics::ffn_compare_assets,+ commands::ffn_analytics::ffn_risk_metrics,+ commands::ffn_analytics::ffn_full_analysis,+ // Functime Analytics - Time Series Forecasting Commands+ commands::functime_analytics::functime_check_status,+ commands::functime_analytics::functime_forecast,+ commands::functime_analytics::functime_preprocess,+ commands::functime_analytics::functime_cross_validate,+ commands::functime_analytics::functime_metrics,+ commands::functime_analytics::functime_add_features,+ commands::functime_analytics::functime_seasonal_period,+ commands::functime_analytics::functime_full_pipeline,// High-Performance OrderBook Processing Commandscommands::orderbook::merge_orderbook,commands::orderbook::update_orderbook_snapshot,diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AIQuantLabTab.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AIQuantLabTab.tsxindex 44e91ecea..fa83c0ac0 100644--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AIQuantLabTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AIQuantLabTab.tsx@@ -32,6 +32,8 @@ import { FactorDiscoveryPanel } from './FactorDiscoveryPanel';import { ModelLibraryPanel } from './ModelLibraryPanel';import { BacktestingPanel } from './BacktestingPanel';import { LiveSignalsPanel } from './LiveSignalsPanel';+import { FFNAnalyticsPanel } from './FFNAnalyticsPanel';+import { FunctimePanel } from './FunctimePanel';import { StatusBar } from './StatusBar';// Bloomberg Professional Color Palette - Consistent across all tabs@@ -53,7 +55,7 @@ const BLOOMBERG = {MUTED: '#4A4A4A'};-type ViewMode = 'factor_discovery' | 'model_library' | 'backtesting' | 'live_signals';+type ViewMode = 'factor_discovery' | 'model_library' | 'backtesting' | 'live_signals' | 'ffn_analytics' | 'functime';export default function AIQuantLabTab() {// State@@ -194,7 +196,9 @@ export default function AIQuantLabTab() {{ id: 'factor_discovery', label: 'FACTOR DISCOVERY', icon: Sparkles, description: 'AI-powered factor mining with RD-Agent' },{ id: 'model_library', label: 'MODEL LIBRARY', icon: Brain, description: '15+ pre-trained Qlib models' },{ id: 'backtesting', label: 'BACKTESTING', icon: BarChart3, description: 'Strategy validation & analysis' },- { id: 'live_signals', label: 'LIVE SIGNALS', icon: Activity, description: 'Real-time predictions' }+ { id: 'live_signals', label: 'LIVE SIGNALS', icon: Activity, description: 'Real-time predictions' },+ { id: 'ffn_analytics', label: 'FFN ANALYTICS', icon: TrendingUp, description: 'Portfolio performance & risk metrics' },+ { id: 'functime', label: 'FUNCTIME', icon: Zap, description: 'ML time series forecasting' }];const bothInitialized = qlibStatus.initialized && rdAgentStatus.initialized;@@ -316,7 +320,12 @@ export default function AIQuantLabTab() {{/* Main Content Area */}<div className="flex-1 overflow-hidden relative">- {!bothAvailable ? (+ {/* FFN Analytics and Functime are always available - independent of Qlib/RDAgent */}+ {activeView === 'ffn_analytics' ? (+ <FFNAnalyticsPanel />+ ) : activeView === 'functime' ? (+ <FunctimePanel />+ ) : !bothAvailable ? (<InstallationGuide />) : !bothInitialized ? (isLoading ? (diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FFNAnalyticsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FFNAnalyticsPanel.tsxnew file mode 100644index 000000000..8e133d8b9--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FFNAnalyticsPanel.tsx@@ -0,0 +1,589 @@+/**+ * FFN Analytics Panel - Portfolio Performance Analysis+ * Bloomberg Professional Design+ * Integrated with FFN library via PyO3+ */++import React, { useState, useEffect } from 'react';+import {+ TrendingUp,+ TrendingDown,+ Activity,+ BarChart2,+ Calendar,+ RefreshCw,+ AlertCircle,+ CheckCircle2,+ ChevronDown,+ ChevronUp,+ LineChart,+ PieChart,+ Percent,+ DollarSign,+ Clock,+ Target+} from 'lucide-react';+import { ffnService, type PerformanceMetrics, type DrawdownInfo, type FFNConfig } from '@/services/aiQuantLab/ffnService';++// Bloomberg Professional Color Palette+const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A'+};++// Sample data for demonstration+const SAMPLE_PRICES = {+ '2023-01-03': 100.0,+ '2023-01-04': 101.2,+ '2023-01-05': 99.8,+ '2023-01-06': 102.5,+ '2023-01-09': 103.1,+ '2023-01-10': 104.0,+ '2023-01-11': 102.3,+ '2023-01-12': 105.2,+ '2023-01-13': 106.8,+ '2023-01-17': 105.5,+ '2023-01-18': 107.2,+ '2023-01-19': 106.0,+ '2023-01-20': 108.5,+ '2023-01-23': 109.3,+ '2023-01-24': 110.0,+ '2023-01-25': 108.7,+ '2023-01-26': 111.2,+ '2023-01-27': 112.5,+ '2023-01-30': 111.0,+ '2023-01-31': 113.8+};++interface AnalysisResult {+ performance?: PerformanceMetrics;+ drawdowns?: {+ max_drawdown: number;+ top_drawdowns: DrawdownInfo[];+ };+ riskMetrics?: {+ ulcer_index?: number;+ skewness?: number;+ kurtosis?: number;+ var_95?: number;+ cvar_95?: number;+ };+}++export function FFNAnalyticsPanel() {+ const [isFFNAvailable, setIsFFNAvailable] = useState<boolean | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [analysisResult, setAnalysisResult] = useState<AnalysisResult | null>(null);+ const [priceInput, setPriceInput] = useState(JSON.stringify(SAMPLE_PRICES, null, 2));+ const [config, setConfig] = useState<FFNConfig>({+ risk_free_rate: 0.02,+ annualization_factor: 252,+ drawdown_threshold: 0.05+ });+ const [expandedSections, setExpandedSections] = useState({+ performance: true,+ drawdowns: true,+ risk: true+ });++ // Check FFN availability on mount+ useEffect(() => {+ checkFFNStatus();+ }, []);++ const checkFFNStatus = async () => {+ try {+ const status = await ffnService.checkStatus();+ setIsFFNAvailable(status.available);+ if (!status.available) {+ setError('FFN library not installed. Run: pip install ffn');+ }+ } catch (err) {+ setIsFFNAvailable(false);+ setError('Failed to check FFN status');+ }+ };++ const runAnalysis = async () => {+ setIsLoading(true);+ setError(null);++ try {+ const prices = JSON.parse(priceInput);++ // Run full analysis+ const result = await ffnService.fullAnalysis(prices, config);++ if (!result.success) {+ setError(result.error || 'Analysis failed');+ return;+ }++ // Get additional risk metrics+ const riskResult = await ffnService.riskMetrics(prices, config.risk_free_rate);++ setAnalysisResult({+ performance: result.performance as PerformanceMetrics,+ drawdowns: result.drawdowns,+ riskMetrics: riskResult.success ? {+ ulcer_index: riskResult.ulcer_index,+ skewness: riskResult.skewness,+ kurtosis: riskResult.kurtosis,+ var_95: riskResult.var_95,+ cvar_95: riskResult.cvar_95+ } : undefined+ });+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Analysis failed');+ } finally {+ setIsLoading(false);+ }+ };++ const toggleSection = (section: keyof typeof expandedSections) => {+ setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));+ };++ const formatPercent = (value: number | null | undefined, decimals = 2): string => {+ if (value === null || value === undefined || isNaN(value)) return 'N/A';+ return `${(value * 100).toFixed(decimals)}%`;+ };++ const formatRatio = (value: number | null | undefined, decimals = 2): string => {+ if (value === null || value === undefined || isNaN(value)) return 'N/A';+ return value.toFixed(decimals);+ };++ const getValueColor = (value: number | null | undefined, inverse = false): string => {+ if (value === null || value === undefined) return BLOOMBERG.GRAY;+ if (inverse) return value < 0 ? BLOOMBERG.GREEN : value > 0 ? BLOOMBERG.RED : BLOOMBERG.WHITE;+ return value > 0 ? BLOOMBERG.GREEN : value < 0 ? BLOOMBERG.RED : BLOOMBERG.WHITE;+ };++ // Loading/Error states+ if (isFFNAvailable === null) {+ return (+ <div className="flex items-center justify-center h-full" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <RefreshCw size={32} color={BLOOMBERG.ORANGE} className="animate-spin" />+ </div>+ );+ }++ if (!isFFNAvailable) {+ return (+ <div className="flex items-center justify-center h-full p-8" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <div className="text-center max-w-md">+ <AlertCircle size={48} color={BLOOMBERG.RED} className="mx-auto mb-4" />+ <h3 className="text-lg font-bold uppercase mb-2" style={{ color: BLOOMBERG.WHITE }}>+ FFN Library Not Installed+ </h3>+ <code+ className="block p-4 rounded text-sm font-mono mt-4"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, color: BLOOMBERG.ORANGE }}+ >+ pip install ffn+ </code>+ <button+ onClick={checkFFNStatus}+ className="mt-6 px-6 py-2 rounded font-bold text-sm uppercase flex items-center gap-2 mx-auto"+ style={{ backgroundColor: BLOOMBERG.ORANGE, color: BLOOMBERG.DARK_BG }}+ >+ <RefreshCw size={14} />+ Check Again+ </button>+ </div>+ </div>+ );+ }++ return (+ <div className="flex h-full" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ {/* Left Panel - Input */}+ <div+ className="w-80 flex flex-col border-r"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, borderColor: BLOOMBERG.BORDER }}+ >+ {/* Input Header */}+ <div+ className="px-4 py-3 border-b flex items-center gap-2"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG, borderColor: BLOOMBERG.BORDER }}+ >+ <LineChart size={16} color={BLOOMBERG.ORANGE} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Price Data Input+ </span>+ </div>++ {/* Price Input */}+ <div className="flex-1 p-4 overflow-auto">+ <label className="block text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>+ PRICE DATA (JSON)+ </label>+ <textarea+ value={priceInput}+ onChange={(e) => setPriceInput(e.target.value)}+ className="w-full h-48 p-3 rounded text-xs font-mono resize-none"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ placeholder='{"2023-01-01": 100, "2023-01-02": 101, ...}'+ />++ {/* Config Options */}+ <div className="mt-4 space-y-3">+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ RISK-FREE RATE+ </label>+ <input+ type="number"+ step="0.01"+ value={config.risk_free_rate}+ onChange={(e) => setConfig({ ...config, risk_free_rate: parseFloat(e.target.value) || 0 })}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ />+ </div>++ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ DRAWDOWN THRESHOLD+ </label>+ <input+ type="number"+ step="0.01"+ value={config.drawdown_threshold}+ onChange={(e) => setConfig({ ...config, drawdown_threshold: parseFloat(e.target.value) || 0.05 })}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ />+ </div>+ </div>+ </div>++ {/* Run Button */}+ <div className="p-4 border-t" style={{ borderColor: BLOOMBERG.BORDER }}>+ <button+ onClick={runAnalysis}+ disabled={isLoading}+ className="w-full py-3 rounded font-bold text-sm uppercase flex items-center justify-center gap-2 disabled:opacity-50"+ style={{ backgroundColor: BLOOMBERG.ORANGE, color: BLOOMBERG.DARK_BG }}+ >+ {isLoading ? (+ <>+ <RefreshCw size={16} className="animate-spin" />+ ANALYZING...+ </>+ ) : (+ <>+ <Activity size={16} />+ RUN ANALYSIS+ </>+ )}+ </button>+ </div>+ </div>++ {/* Right Panel - Results */}+ <div className="flex-1 overflow-auto p-4">+ {error && (+ <div+ className="mb-4 p-4 rounded flex items-center gap-3"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, borderLeft: `3px solid ${BLOOMBERG.RED}` }}+ >+ <AlertCircle size={20} color={BLOOMBERG.RED} />+ <span className="text-sm font-mono" style={{ color: BLOOMBERG.RED }}>{error}</span>+ </div>+ )}++ {!analysisResult && !error && (+ <div className="flex items-center justify-center h-full">+ <div className="text-center">+ <BarChart2 size={64} color={BLOOMBERG.MUTED} className="mx-auto mb-4" />+ <p className="text-sm font-mono" style={{ color: BLOOMBERG.GRAY }}>+ Enter price data and click "Run Analysis" to see results+ </p>+ </div>+ </div>+ )}++ {analysisResult && (+ <div className="space-y-4">+ {/* Performance Metrics Section */}+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <button+ onClick={() => toggleSection('performance')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <TrendingUp size={16} color={BLOOMBERG.GREEN} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Performance Metrics+ </span>+ </div>+ {expandedSections.performance ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.performance && analysisResult.performance && (+ <div className="p-4 grid grid-cols-3 gap-4">+ <MetricCard+ label="Total Return"+ value={formatPercent(analysisResult.performance.total_return)}+ color={getValueColor(analysisResult.performance.total_return)}+ icon={<Percent size={14} />}+ />+ <MetricCard+ label="CAGR"+ value={formatPercent(analysisResult.performance.cagr)}+ color={getValueColor(analysisResult.performance.cagr)}+ icon={<TrendingUp size={14} />}+ />+ <MetricCard+ label="Sharpe Ratio"+ value={formatRatio(analysisResult.performance.sharpe_ratio)}+ color={getValueColor(analysisResult.performance.sharpe_ratio)}+ icon={<Target size={14} />}+ />+ <MetricCard+ label="Sortino Ratio"+ value={formatRatio(analysisResult.performance.sortino_ratio)}+ color={getValueColor(analysisResult.performance.sortino_ratio)}+ icon={<Target size={14} />}+ />+ <MetricCard+ label="Volatility"+ value={formatPercent(analysisResult.performance.volatility)}+ color={BLOOMBERG.YELLOW}+ icon={<Activity size={14} />}+ />+ <MetricCard+ label="Calmar Ratio"+ value={formatRatio(analysisResult.performance.calmar_ratio)}+ color={getValueColor(analysisResult.performance.calmar_ratio)}+ icon={<BarChart2 size={14} />}+ />+ <MetricCard+ label="Best Day"+ value={formatPercent(analysisResult.performance.best_day)}+ color={BLOOMBERG.GREEN}+ icon={<TrendingUp size={14} />}+ />+ <MetricCard+ label="Worst Day"+ value={formatPercent(analysisResult.performance.worst_day)}+ color={BLOOMBERG.RED}+ icon={<TrendingDown size={14} />}+ />+ <MetricCard+ label="Daily Mean"+ value={formatPercent(analysisResult.performance.daily_mean, 4)}+ color={getValueColor(analysisResult.performance.daily_mean)}+ icon={<LineChart size={14} />}+ />+ </div>+ )}+ </div>++ {/* Drawdowns Section */}+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <button+ onClick={() => toggleSection('drawdowns')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <TrendingDown size={16} color={BLOOMBERG.RED} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Drawdown Analysis+ </span>+ </div>+ {expandedSections.drawdowns ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.drawdowns && analysisResult.drawdowns && (+ <div className="p-4">+ <div className="mb-4">+ <MetricCard+ label="Max Drawdown"+ value={formatPercent(analysisResult.drawdowns.max_drawdown)}+ color={BLOOMBERG.RED}+ icon={<TrendingDown size={14} />}+ large+ />+ </div>++ {analysisResult.drawdowns.top_drawdowns && analysisResult.drawdowns.top_drawdowns.length > 0 && (+ <div>+ <h4 className="text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>+ TOP DRAWDOWN PERIODS+ </h4>+ <div className="space-y-2">+ {analysisResult.drawdowns.top_drawdowns.map((dd, idx) => (+ <div+ key={idx}+ className="p-3 rounded flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.DARK_BG }}+ >+ <div className="flex items-center gap-3">+ <span+ className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold"+ style={{ backgroundColor: BLOOMBERG.RED, color: BLOOMBERG.WHITE }}+ >+ {idx + 1}+ </span>+ <div>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.WHITE }}>+ {dd.start} → {dd.end}+ </span>+ </div>+ </div>+ <span className="text-sm font-bold" style={{ color: BLOOMBERG.RED }}>+ {formatPercent(dd.drawdown)}+ </span>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ )}+ </div>++ {/* Risk Metrics Section */}+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <button+ onClick={() => toggleSection('risk')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <AlertCircle size={16} color={BLOOMBERG.YELLOW} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Risk Metrics+ </span>+ </div>+ {expandedSections.risk ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.risk && analysisResult.riskMetrics && (+ <div className="p-4 grid grid-cols-3 gap-4">+ <MetricCard+ label="Ulcer Index"+ value={formatRatio(analysisResult.riskMetrics.ulcer_index, 4)}+ color={BLOOMBERG.YELLOW}+ icon={<Activity size={14} />}+ />+ <MetricCard+ label="Skewness"+ value={formatRatio(analysisResult.riskMetrics.skewness)}+ color={BLOOMBERG.CYAN}+ icon={<BarChart2 size={14} />}+ />+ <MetricCard+ label="Kurtosis"+ value={formatRatio(analysisResult.riskMetrics.kurtosis)}+ color={BLOOMBERG.CYAN}+ icon={<BarChart2 size={14} />}+ />+ <MetricCard+ label="VaR (95%)"+ value={formatPercent(analysisResult.riskMetrics.var_95)}+ color={BLOOMBERG.RED}+ icon={<TrendingDown size={14} />}+ />+ <MetricCard+ label="CVaR (95%)"+ value={formatPercent(analysisResult.riskMetrics.cvar_95)}+ color={BLOOMBERG.RED}+ icon={<TrendingDown size={14} />}+ />+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ </div>+ );+}++// Metric Card Component+function MetricCard({+ label,+ value,+ color,+ icon,+ large = false+}: {+ label: string;+ value: string;+ color: string;+ icon: React.ReactNode;+ large?: boolean;+}) {+ return (+ <div+ className={`p-3 rounded ${large ? 'col-span-3' : ''}`}+ style={{ backgroundColor: BLOOMBERG.DARK_BG }}+ >+ <div className="flex items-center gap-2 mb-1">+ <span style={{ color: BLOOMBERG.GRAY }}>{icon}</span>+ <span className="text-xs font-mono uppercase" style={{ color: BLOOMBERG.GRAY }}>+ {label}+ </span>+ </div>+ <span+ className={`font-bold font-mono ${large ? 'text-2xl' : 'text-lg'}`}+ style={{ color }}+ >+ {value}+ </span>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FunctimePanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FunctimePanel.tsxnew file mode 100644index 000000000..38a3ebb05--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FunctimePanel.tsx@@ -0,0 +1,1034 @@+/**+ * Functime Analytics Panel - Time Series Forecasting+ * Bloomberg Professional Design+ * Integrated with functime library via PyO3+ */++import React, { useState, useEffect, useMemo } from 'react';+import {+ TrendingUp,+ TrendingDown,+ Activity,+ BarChart2,+ Calendar,+ RefreshCw,+ AlertCircle,+ CheckCircle2,+ ChevronDown,+ ChevronUp,+ LineChart,+ Play,+ Settings,+ Zap,+ Target,+ Clock,+ Layers,+ GitBranch,+ Database+} from 'lucide-react';+import {+ functimeService,+ type ForecastResult,+ type ForecastConfig,+ type PreprocessConfig,+ type FullPipelineResponse+} from '@/services/aiQuantLab/functimeService';++// Bloomberg Professional Color Palette+const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A'+};++// Sample panel data for demonstration+const SAMPLE_DATA = [+ { entity_id: 'AAPL', time: '2024-01-02', value: 185.64 },+ { entity_id: 'AAPL', time: '2024-01-03', value: 184.25 },+ { entity_id: 'AAPL', time: '2024-01-04', value: 181.91 },+ { entity_id: 'AAPL', time: '2024-01-05', value: 181.18 },+ { entity_id: 'AAPL', time: '2024-01-08', value: 185.56 },+ { entity_id: 'AAPL', time: '2024-01-09', value: 185.14 },+ { entity_id: 'AAPL', time: '2024-01-10', value: 186.19 },+ { entity_id: 'AAPL', time: '2024-01-11', value: 185.59 },+ { entity_id: 'AAPL', time: '2024-01-12', value: 185.92 },+ { entity_id: 'AAPL', time: '2024-01-16', value: 183.63 },+ { entity_id: 'AAPL', time: '2024-01-17', value: 182.68 },+ { entity_id: 'AAPL', time: '2024-01-18', value: 188.63 },+ { entity_id: 'AAPL', time: '2024-01-19', value: 191.56 },+ { entity_id: 'AAPL', time: '2024-01-22', value: 193.89 },+ { entity_id: 'AAPL', time: '2024-01-23', value: 195.18 },+ { entity_id: 'AAPL', time: '2024-01-24', value: 194.50 },+ { entity_id: 'AAPL', time: '2024-01-25', value: 194.17 },+ { entity_id: 'AAPL', time: '2024-01-26', value: 192.42 },+ { entity_id: 'AAPL', time: '2024-01-29', value: 191.73 },+ { entity_id: 'AAPL', time: '2024-01-30', value: 188.04 }+];++interface ForecastAnalysisResult {+ forecast?: ForecastResult[];+ model?: string;+ horizon?: number;+ frequency?: string;+ best_params?: Record<string, unknown>;+ evaluation_metrics?: {+ mae?: number;+ rmse?: number;+ smape?: number;+ };+ data_summary?: {+ total_rows: number;+ entities: number;+ train_size: number;+ test_size: number;+ };+}++export function FunctimePanel() {+ const [isFunctimeAvailable, setIsFunctimeAvailable] = useState<boolean | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [analysisResult, setAnalysisResult] = useState<ForecastAnalysisResult | null>(null);+ const [dataInput, setDataInput] = useState(JSON.stringify(SAMPLE_DATA, null, 2));++ // Forecast configuration+ const [selectedModel, setSelectedModel] = useState('linear');+ const [horizon, setHorizon] = useState(7);+ const [frequency, setFrequency] = useState('1d');+ const [alpha, setAlpha] = useState(1.0);+ const [testSize, setTestSize] = useState(5);+ const [preprocess, setPreprocess] = useState<'none' | 'scale' | 'difference'>('none');++ const [expandedSections, setExpandedSections] = useState({+ config: true,+ forecast: true,+ metrics: true,+ summary: true,+ chart: true+ });++ const models = functimeService.getAvailableModels();+ const frequencies = functimeService.getAvailableFrequencies();++ // Check functime availability on mount+ useEffect(() => {+ checkFunctimeStatus();+ }, []);++ const checkFunctimeStatus = async () => {+ try {+ const status = await functimeService.checkStatus();+ setIsFunctimeAvailable(status.available);+ if (!status.available) {+ setError('Functime library not installed. Run: pip install functime polars');+ }+ } catch (err) {+ setIsFunctimeAvailable(false);+ setError('Failed to check functime status');+ }+ };++ const runForecast = async () => {+ setIsLoading(true);+ setError(null);++ try {+ const data = JSON.parse(dataInput);++ // Run full pipeline+ const result = await functimeService.fullPipeline(+ data,+ selectedModel,+ horizon,+ frequency,+ testSize,+ preprocess === 'none' ? undefined : preprocess+ );++ if (!result.success) {+ setError(result.error || 'Forecast failed');+ return;+ }++ setAnalysisResult({+ forecast: result.forecast,+ model: result.model,+ horizon: result.horizon,+ frequency: result.frequency,+ best_params: result.best_params,+ evaluation_metrics: result.evaluation_metrics,+ data_summary: result.data_summary+ });+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Forecast failed');+ } finally {+ setIsLoading(false);+ }+ };++ const toggleSection = (section: keyof typeof expandedSections) => {+ setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));+ };++ const formatMetric = (value: number | null | undefined, decimals = 4): string => {+ if (value === null || value === undefined || isNaN(value)) return 'N/A';+ return value.toFixed(decimals);+ };++ // Parse historical data from input for chart visualization+ const historicalData = useMemo(() => {+ try {+ const data = JSON.parse(dataInput);+ if (Array.isArray(data)) {+ return data.map(d => ({+ time: d.time,+ value: d.value+ }));+ }+ return [];+ } catch {+ return [];+ }+ }, [dataInput]);++ // Loading state+ if (isFunctimeAvailable === null) {+ return (+ <div className="flex items-center justify-center h-full" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <RefreshCw size={32} color={BLOOMBERG.ORANGE} className="animate-spin" />+ </div>+ );+ }++ // Not available state+ if (!isFunctimeAvailable) {+ return (+ <div className="flex items-center justify-center h-full p-8" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <div className="text-center max-w-md">+ <AlertCircle size={48} color={BLOOMBERG.RED} className="mx-auto mb-4" />+ <h3 className="text-lg font-bold uppercase mb-2" style={{ color: BLOOMBERG.WHITE }}>+ Functime Library Not Installed+ </h3>+ <p className="text-sm mb-4" style={{ color: BLOOMBERG.GRAY }}>+ Install functime and polars for ML time series forecasting+ </p>+ <code+ className="block p-4 rounded text-sm font-mono mt-4"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, color: BLOOMBERG.ORANGE }}+ >+ pip install functime polars+ </code>+ <button+ onClick={checkFunctimeStatus}+ className="mt-6 px-6 py-2 rounded font-bold text-sm uppercase flex items-center gap-2 mx-auto"+ style={{ backgroundColor: BLOOMBERG.ORANGE, color: BLOOMBERG.DARK_BG }}+ >+ <RefreshCw size={14} />+ Check Again+ </button>+ </div>+ </div>+ );+ }++ return (+ <div className="flex h-full" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ {/* Left Panel - Configuration */}+ <div+ className="w-96 flex flex-col border-r"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, borderColor: BLOOMBERG.BORDER }}+ >+ {/* Input Header */}+ <div+ className="px-4 py-3 border-b flex items-center gap-2"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG, borderColor: BLOOMBERG.BORDER }}+ >+ <Zap size={16} color={BLOOMBERG.ORANGE} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Time Series Forecasting+ </span>+ </div>++ {/* Scrollable Content */}+ <div className="flex-1 overflow-auto p-4 space-y-4">+ {/* Data Input */}+ <div>+ <label className="block text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>+ PANEL DATA (JSON)+ </label>+ <textarea+ value={dataInput}+ onChange={(e) => setDataInput(e.target.value)}+ className="w-full h-32 p-3 rounded text-xs font-mono resize-none"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ placeholder='[{"entity_id": "A", "time": "2024-01-01", "value": 100}, ...]'+ />+ </div>++ {/* Model Configuration */}+ <div+ className="rounded overflow-hidden"+ style={{ border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <button+ onClick={() => toggleSection('config')}+ className="w-full px-3 py-2 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <Settings size={14} color={BLOOMBERG.CYAN} />+ <span className="text-xs font-bold uppercase" style={{ color: BLOOMBERG.WHITE }}>+ Model Configuration+ </span>+ </div>+ {expandedSections.config ? (+ <ChevronUp size={14} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={14} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.config && (+ <div className="p-3 space-y-3">+ {/* Model Selection */}+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ FORECAST MODEL+ </label>+ <select+ value={selectedModel}+ onChange={(e) => setSelectedModel(e.target.value)}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ {models.map((m) => (+ <option key={m.id} value={m.id}>+ {m.name}+ </option>+ ))}+ </select>+ </div>++ {/* Horizon */}+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ FORECAST HORIZON+ </label>+ <input+ type="number"+ min={1}+ max={365}+ value={horizon}+ onChange={(e) => setHorizon(parseInt(e.target.value) || 7)}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ />+ </div>++ {/* Frequency */}+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ DATA FREQUENCY+ </label>+ <select+ value={frequency}+ onChange={(e) => setFrequency(e.target.value)}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ {frequencies.map((f) => (+ <option key={f.id} value={f.id}>+ {f.name}+ </option>+ ))}+ </select>+ </div>++ {/* Alpha (for regularized models) */}+ {['lasso', 'ridge', 'elasticnet', 'auto_lasso', 'auto_ridge', 'auto_elasticnet'].includes(selectedModel) && (+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ ALPHA (REGULARIZATION)+ </label>+ <input+ type="number"+ step="0.1"+ min={0}+ value={alpha}+ onChange={(e) => setAlpha(parseFloat(e.target.value) || 1.0)}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ />+ </div>+ )}++ {/* Test Size */}+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ TEST SIZE (FOR EVALUATION)+ </label>+ <input+ type="number"+ min={1}+ value={testSize}+ onChange={(e) => setTestSize(parseInt(e.target.value) || 5)}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ />+ </div>++ {/* Preprocessing */}+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ PREPROCESSING+ </label>+ <select+ value={preprocess}+ onChange={(e) => setPreprocess(e.target.value as 'none' | 'scale' | 'difference')}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ <option value="none">None</option>+ <option value="scale">Standard Scaling</option>+ <option value="difference">Differencing</option>+ </select>+ </div>+ </div>+ )}+ </div>+ </div>++ {/* Run Button */}+ <div className="p-4 border-t" style={{ borderColor: BLOOMBERG.BORDER }}>+ <button+ onClick={runForecast}+ disabled={isLoading}+ className="w-full py-3 rounded font-bold text-sm uppercase flex items-center justify-center gap-2 disabled:opacity-50"+ style={{ backgroundColor: BLOOMBERG.ORANGE, color: BLOOMBERG.DARK_BG }}+ >+ {isLoading ? (+ <>+ <RefreshCw size={16} className="animate-spin" />+ FORECASTING...+ </>+ ) : (+ <>+ <Play size={16} />+ RUN FORECAST+ </>+ )}+ </button>+ </div>+ </div>++ {/* Right Panel - Results */}+ <div className="flex-1 overflow-auto p-4">+ {error && (+ <div+ className="mb-4 p-4 rounded flex items-center gap-3"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, borderLeft: `3px solid ${BLOOMBERG.RED}` }}+ >+ <AlertCircle size={20} color={BLOOMBERG.RED} />+ <span className="text-sm font-mono" style={{ color: BLOOMBERG.RED }}>{error}</span>+ </div>+ )}++ {!analysisResult && !error && (+ <div className="flex items-center justify-center h-full">+ <div className="text-center">+ <LineChart size={64} color={BLOOMBERG.MUTED} className="mx-auto mb-4" />+ <p className="text-sm font-mono" style={{ color: BLOOMBERG.GRAY }}>+ Configure model and click "Run Forecast" to see predictions+ </p>+ </div>+ </div>+ )}++ {analysisResult && (+ <div className="space-y-4">+ {/* Data Summary Section */}+ {analysisResult.data_summary && (+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <button+ onClick={() => toggleSection('summary')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <Database size={16} color={BLOOMBERG.CYAN} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Data Summary+ </span>+ </div>+ {expandedSections.summary ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.summary && (+ <div className="p-4 grid grid-cols-4 gap-4">+ <MetricCard+ label="Total Rows"+ value={String(analysisResult.data_summary.total_rows)}+ color={BLOOMBERG.WHITE}+ icon={<Database size={14} />}+ />+ <MetricCard+ label="Entities"+ value={String(analysisResult.data_summary.entities)}+ color={BLOOMBERG.CYAN}+ icon={<Layers size={14} />}+ />+ <MetricCard+ label="Train Size"+ value={String(analysisResult.data_summary.train_size)}+ color={BLOOMBERG.GREEN}+ icon={<GitBranch size={14} />}+ />+ <MetricCard+ label="Test Size"+ value={String(analysisResult.data_summary.test_size)}+ color={BLOOMBERG.YELLOW}+ icon={<Target size={14} />}+ />+ </div>+ )}+ </div>+ )}++ {/* Evaluation Metrics Section */}+ {analysisResult.evaluation_metrics && (+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <button+ onClick={() => toggleSection('metrics')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <Target size={16} color={BLOOMBERG.GREEN} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Evaluation Metrics+ </span>+ </div>+ {expandedSections.metrics ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.metrics && (+ <div className="p-4 grid grid-cols-3 gap-4">+ <MetricCard+ label="MAE"+ value={formatMetric(analysisResult.evaluation_metrics.mae)}+ color={BLOOMBERG.CYAN}+ icon={<BarChart2 size={14} />}+ />+ <MetricCard+ label="RMSE"+ value={formatMetric(analysisResult.evaluation_metrics.rmse)}+ color={BLOOMBERG.YELLOW}+ icon={<Activity size={14} />}+ />+ <MetricCard+ label="SMAPE"+ value={formatMetric(analysisResult.evaluation_metrics.smape)}+ color={BLOOMBERG.PURPLE}+ icon={<TrendingUp size={14} />}+ />+ </div>+ )}+ </div>+ )}++ {/* Forecast Chart Visualization */}+ {analysisResult.forecast && analysisResult.forecast.length > 0 && (+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <button+ onClick={() => toggleSection('chart')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <LineChart size={16} color={BLOOMBERG.CYAN} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Forecast Chart+ </span>+ </div>+ {expandedSections.chart ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.chart && (+ <div className="p-4">+ <ForecastChart+ historicalData={historicalData}+ forecastData={analysisResult.forecast}+ height={350}+ />+ </div>+ )}+ </div>+ )}++ {/* Forecast Results Section */}+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <button+ onClick={() => toggleSection('forecast')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <TrendingUp size={16} color={BLOOMBERG.ORANGE} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Forecast Results+ </span>+ {analysisResult.model && (+ <span+ className="ml-2 px-2 py-0.5 rounded text-xs font-mono"+ style={{ backgroundColor: BLOOMBERG.ORANGE, color: BLOOMBERG.DARK_BG }}+ >+ {analysisResult.model.toUpperCase()}+ </span>+ )}+ </div>+ {expandedSections.forecast ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.forecast && analysisResult.forecast && (+ <div className="p-4">+ {/* Forecast info */}+ <div className="mb-4 flex gap-4 text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ <span>Horizon: <span style={{ color: BLOOMBERG.WHITE }}>{analysisResult.horizon}</span></span>+ <span>Frequency: <span style={{ color: BLOOMBERG.WHITE }}>{analysisResult.frequency}</span></span>+ {analysisResult.best_params && (+ <span>Auto-tuned: <CheckCircle2 size={12} color={BLOOMBERG.GREEN} className="inline ml-1" /></span>+ )}+ </div>++ {/* Forecast table */}+ <div+ className="rounded overflow-hidden"+ style={{ border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <table className="w-full text-xs font-mono">+ <thead>+ <tr style={{ backgroundColor: BLOOMBERG.HEADER_BG }}>+ <th className="px-3 py-2 text-left" style={{ color: BLOOMBERG.GRAY }}>ENTITY</th>+ <th className="px-3 py-2 text-left" style={{ color: BLOOMBERG.GRAY }}>TIME</th>+ <th className="px-3 py-2 text-right" style={{ color: BLOOMBERG.GRAY }}>FORECAST</th>+ </tr>+ </thead>+ <tbody>+ {analysisResult.forecast.slice(0, 20).map((row, idx) => (+ <tr+ key={idx}+ style={{+ backgroundColor: idx % 2 === 0 ? BLOOMBERG.DARK_BG : BLOOMBERG.PANEL_BG+ }}+ >+ <td className="px-3 py-2" style={{ color: BLOOMBERG.CYAN }}>+ {row.entity_id}+ </td>+ <td className="px-3 py-2" style={{ color: BLOOMBERG.WHITE }}>+ {row.time}+ </td>+ <td className="px-3 py-2 text-right" style={{ color: BLOOMBERG.GREEN }}>+ {typeof row.value === 'number' ? row.value.toFixed(2) : row.value}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ {analysisResult.forecast.length > 20 && (+ <div+ className="px-3 py-2 text-xs font-mono text-center"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG, color: BLOOMBERG.GRAY }}+ >+ + {analysisResult.forecast.length - 20} more rows+ </div>+ )}+ </div>+ </div>+ )}+ </div>++ {/* Best Params (if auto-tuned) */}+ {analysisResult.best_params && Object.keys(analysisResult.best_params).length > 0 && (+ <div+ className="rounded p-4"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <div className="flex items-center gap-2 mb-3">+ <Zap size={16} color={BLOOMBERG.YELLOW} />+ <span className="text-xs font-bold uppercase" style={{ color: BLOOMBERG.WHITE }}>+ Best Parameters (Auto-tuned)+ </span>+ </div>+ <div className="grid grid-cols-3 gap-2">+ {Object.entries(analysisResult.best_params).map(([key, value]) => (+ <div key={key} className="flex justify-between p-2 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>{key}</span>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.CYAN }}>+ {typeof value === 'number' ? value.toFixed(4) : String(value)}+ </span>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ </div>+ );+}++// Metric Card Component+function MetricCard({+ label,+ value,+ color,+ icon,+ large = false+}: {+ label: string;+ value: string;+ color: string;+ icon: React.ReactNode;+ large?: boolean;+}) {+ return (+ <div+ className={`p-3 rounded ${large ? 'col-span-3' : ''}`}+ style={{ backgroundColor: BLOOMBERG.DARK_BG }}+ >+ <div className="flex items-center gap-2 mb-1">+ <span style={{ color: BLOOMBERG.GRAY }}>{icon}</span>+ <span className="text-xs font-mono uppercase" style={{ color: BLOOMBERG.GRAY }}>+ {label}+ </span>+ </div>+ <span+ className={`font-bold font-mono ${large ? 'text-2xl' : 'text-lg'}`}+ style={{ color }}+ >+ {value}+ </span>+ </div>+ );+}++// Forecast Chart Component - SVG-based line chart+interface ChartDataPoint {+ time: string;+ value: number;+ type: 'historical' | 'forecast';+}++function ForecastChart({+ historicalData,+ forecastData,+ height = 300+}: {+ historicalData: { time: string; value: number }[];+ forecastData: ForecastResult[];+ height?: number;+}) {+ const chartData = useMemo(() => {+ const historical: ChartDataPoint[] = historicalData.map(d => ({+ time: d.time,+ value: d.value,+ type: 'historical' as const+ }));++ const forecast: ChartDataPoint[] = forecastData.map(d => ({+ time: d.time,+ value: d.value,+ type: 'forecast' as const+ }));++ return [...historical, ...forecast];+ }, [historicalData, forecastData]);++ if (chartData.length === 0) {+ return (+ <div+ className="flex items-center justify-center"+ style={{ height, backgroundColor: BLOOMBERG.DARK_BG }}+ >+ <span className="text-sm font-mono" style={{ color: BLOOMBERG.GRAY }}>+ No data to display+ </span>+ </div>+ );+ }++ const width = 800;+ const padding = { top: 20, right: 60, bottom: 40, left: 60 };+ const chartWidth = width - padding.left - padding.right;+ const chartHeight = height - padding.top - padding.bottom;++ // Calculate scales+ const values = chartData.map(d => d.value);+ const minValue = Math.min(...values);+ const maxValue = Math.max(...values);+ const valueRange = maxValue - minValue || 1;+ const yMin = minValue - valueRange * 0.1;+ const yMax = maxValue + valueRange * 0.1;++ const xScale = (index: number) => padding.left + (index / (chartData.length - 1 || 1)) * chartWidth;+ const yScale = (value: number) => padding.top + chartHeight - ((value - yMin) / (yMax - yMin)) * chartHeight;++ // Find split point between historical and forecast+ const historicalEndIndex = historicalData.length - 1;++ // Generate path for historical data+ const historicalPath = historicalData+ .map((d, i) => {+ const x = xScale(i);+ const y = yScale(d.value);+ return `${i === 0 ? 'M' : 'L'} ${x} ${y}`;+ })+ .join(' ');++ // Generate path for forecast data (starts from last historical point)+ const forecastPath = forecastData.length > 0+ ? [+ historicalData.length > 0+ ? `M ${xScale(historicalEndIndex)} ${yScale(historicalData[historicalEndIndex]?.value ?? forecastData[0].value)}`+ : `M ${xScale(0)} ${yScale(forecastData[0].value)}`,+ ...forecastData.map((d, i) => {+ const x = xScale(historicalData.length + i);+ const y = yScale(d.value);+ return `L ${x} ${y}`;+ })+ ].join(' ')+ : '';++ // Y-axis ticks+ const yTicks = Array.from({ length: 5 }, (_, i) => {+ const value = yMin + (yMax - yMin) * (i / 4);+ return { value, y: yScale(value) };+ });++ // X-axis labels (show first, middle, last, and split point)+ const xLabels = [+ { index: 0, label: chartData[0]?.time.split('T')[0] || '' },+ { index: historicalEndIndex, label: chartData[historicalEndIndex]?.time.split('T')[0] || '' },+ { index: chartData.length - 1, label: chartData[chartData.length - 1]?.time.split('T')[0] || '' }+ ].filter((item, index, arr) =>+ arr.findIndex(t => t.index === item.index) === index && item.label+ );++ return (+ <div className="w-full overflow-x-auto">+ <svg+ width="100%"+ height={height}+ viewBox={`0 0 ${width} ${height}`}+ preserveAspectRatio="xMidYMid meet"+ style={{ backgroundColor: BLOOMBERG.DARK_BG }}+ >+ {/* Grid lines */}+ {yTicks.map((tick, i) => (+ <line+ key={i}+ x1={padding.left}+ y1={tick.y}+ x2={width - padding.right}+ y2={tick.y}+ stroke={BLOOMBERG.BORDER}+ strokeWidth={1}+ strokeDasharray="4,4"+ />+ ))}++ {/* Forecast region background */}+ {forecastData.length > 0 && (+ <rect+ x={xScale(historicalEndIndex)}+ y={padding.top}+ width={chartWidth - xScale(historicalEndIndex) + padding.left}+ height={chartHeight}+ fill={BLOOMBERG.ORANGE}+ opacity={0.05}+ />+ )}++ {/* Vertical line at forecast start */}+ {forecastData.length > 0 && historicalData.length > 0 && (+ <line+ x1={xScale(historicalEndIndex)}+ y1={padding.top}+ x2={xScale(historicalEndIndex)}+ y2={height - padding.bottom}+ stroke={BLOOMBERG.ORANGE}+ strokeWidth={1}+ strokeDasharray="6,4"+ opacity={0.6}+ />+ )}++ {/* Historical line */}+ {historicalPath && (+ <path+ d={historicalPath}+ fill="none"+ stroke={BLOOMBERG.CYAN}+ strokeWidth={2}+ />+ )}++ {/* Forecast line */}+ {forecastPath && (+ <path+ d={forecastPath}+ fill="none"+ stroke={BLOOMBERG.ORANGE}+ strokeWidth={2}+ strokeDasharray="6,3"+ />+ )}++ {/* Historical data points */}+ {historicalData.map((d, i) => (+ <circle+ key={`hist-${i}`}+ cx={xScale(i)}+ cy={yScale(d.value)}+ r={3}+ fill={BLOOMBERG.CYAN}+ />+ ))}++ {/* Forecast data points */}+ {forecastData.map((d, i) => (+ <circle+ key={`forecast-${i}`}+ cx={xScale(historicalData.length + i)}+ cy={yScale(d.value)}+ r={4}+ fill={BLOOMBERG.ORANGE}+ stroke={BLOOMBERG.DARK_BG}+ strokeWidth={1}+ />+ ))}++ {/* Y-axis labels */}+ {yTicks.map((tick, i) => (+ <text+ key={i}+ x={padding.left - 10}+ y={tick.y + 4}+ textAnchor="end"+ fontSize={10}+ fontFamily="monospace"+ fill={BLOOMBERG.GRAY}+ >+ {tick.value.toFixed(2)}+ </text>+ ))}++ {/* X-axis labels */}+ {xLabels.map((item, i) => (+ <text+ key={i}+ x={xScale(item.index)}+ y={height - padding.bottom + 20}+ textAnchor="middle"+ fontSize={10}+ fontFamily="monospace"+ fill={BLOOMBERG.GRAY}+ >+ {item.label}+ </text>+ ))}++ {/* Legend */}+ <g transform={`translate(${width - padding.right - 120}, ${padding.top})`}>+ <rect x={0} y={0} width={120} height={50} fill={BLOOMBERG.PANEL_BG} rx={4} />+ <line x1={10} y1={15} x2={35} y2={15} stroke={BLOOMBERG.CYAN} strokeWidth={2} />+ <text x={42} y={18} fontSize={10} fontFamily="monospace" fill={BLOOMBERG.WHITE}>Historical</text>+ <line x1={10} y1={35} x2={35} y2={35} stroke={BLOOMBERG.ORANGE} strokeWidth={2} strokeDasharray="6,3" />+ <text x={42} y={38} fontSize={10} fontFamily="monospace" fill={BLOOMBERG.WHITE}>Forecast</text>+ </g>++ {/* Forecast label */}+ {forecastData.length > 0 && historicalData.length > 0 && (+ <text+ x={xScale(historicalEndIndex) + 5}+ y={padding.top + 15}+ fontSize={10}+ fontFamily="monospace"+ fill={BLOOMBERG.ORANGE}+ >+ ▼ Forecast+ </text>+ )}+ </svg>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/services/aiQuantLab/ffnService.ts b/fincept-terminal-desktop/src/services/aiQuantLab/ffnService.tsnew file mode 100644index 000000000..4f2124abf--- /dev/null+++ b/fincept-terminal-desktop/src/services/aiQuantLab/ffnService.ts@@ -0,0 +1,389 @@+/**+ * FFN Analytics Service - Frontend API for FFN portfolio performance analysis+ * Provides comprehensive performance statistics, risk metrics, and drawdown analysis+ */++import { invoke } from '@tauri-apps/api/core';++// ============================================================================+// TYPE DEFINITIONS+// ============================================================================++export interface FFNConfig {+ risk_free_rate?: number;+ annualization_factor?: number;+ rebase_value?: number;+ log_returns?: boolean;+ drawdown_threshold?: number;+}++export interface FFNStatusResponse {+ success: boolean;+ available: boolean;+ version?: string;+ message?: string;+ error?: string;+}++export interface PerformanceMetrics {+ total_return: number;+ cagr: number;+ sharpe_ratio: number;+ sortino_ratio: number;+ max_drawdown: number;+ calmar_ratio: number;+ volatility: number;+ daily_mean: number;+ daily_vol: number;+ best_day: number;+ worst_day: number;+ mtd?: number;+ ytd?: number;+}++export interface PerformanceResponse {+ success: boolean;+ metrics?: PerformanceMetrics | Record<string, PerformanceMetrics>;+ data_points?: number;+ date_range?: {+ start: string;+ end: string;+ };+ error?: string;+}++export interface DrawdownInfo {+ start: string;+ end: string;+ length?: number;+ drawdown: number;+}++export interface DrawdownResponse {+ success: boolean;+ max_drawdown?: number;+ current_drawdown?: number;+ drawdowns?: DrawdownInfo[];+ drawdown_series?: Record<string, number>;+ error?: string;+}++export interface RollingMetricsResponse {+ success: boolean;+ window?: number;+ metrics?: {+ rolling_sharpe?: Record<string, number>;+ rolling_volatility?: Record<string, number>;+ rolling_returns?: Record<string, number>;+ };+ error?: string;+}++export interface MonthlyReturnsResponse {+ success: boolean;+ monthly_returns?: Record<string, Record<string, number | null>>;+ years?: string[];+ error?: string;+}++export interface RiskMetricsResponse {+ success: boolean;+ ulcer_index?: number;+ ulcer_performance_index?: number;+ skewness?: number;+ kurtosis?: number;+ var_95?: number;+ cvar_95?: number;+ max_drawdown?: number;+ daily_vol?: number;+ annual_vol?: number;+ error?: string;+}++export interface AssetComparisonResponse {+ success: boolean;+ asset_stats?: Record<string, PerformanceMetrics>;+ correlation_matrix?: Record<string, Record<string, number>>;+ rebased_performance?: Record<string, Record<string, number>>;+ benchmark?: string;+ error?: string;+}++export interface FullAnalysisResponse {+ success: boolean;+ performance?: PerformanceMetrics | Record<string, PerformanceMetrics>;+ drawdowns?: {+ max_drawdown: number;+ top_drawdowns: DrawdownInfo[];+ };+ monthly_returns?: Record<string, Record<string, number | null>>;+ rolling_sharpe?: Record<string, number>;+ data_summary?: {+ data_points: number;+ start_date: string;+ end_date: string;+ assets: string[];+ };+ error?: string;+}++// Price data can be provided in multiple formats+export type PriceData =+ | Record<string, number> // {date: price}+ | Record<string, Record<string, number>> // {symbol: {date: price}}+ | Array<{ date: string; price: number; symbol?: string }>; // Array format++// ============================================================================+// FFN SERVICE CLASS+// ============================================================================++class FFNService {+ /**+ * Check FFN library status and availability+ */+ async checkStatus(): Promise<FFNStatusResponse> {+ try {+ const result = await invoke<string>('ffn_check_status');+ return JSON.parse(result);+ } catch (error) {+ console.error('[FFNService] checkStatus error:', error);+ return {+ success: false,+ available: false,+ error: String(error)+ };+ }+ }++ /**+ * Calculate comprehensive performance statistics+ * @param prices - Price data (object with dates as keys, or array)+ * @param config - Optional FFN configuration+ */+ async calculatePerformance(+ prices: PriceData,+ config?: FFNConfig+ ): Promise<PerformanceResponse> {+ try {+ const result = await invoke<string>('ffn_calculate_performance', {+ pricesJson: JSON.stringify(prices),+ config: config ? JSON.stringify(config) : null+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FFNService] calculatePerformance error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Calculate drawdown analysis with detailed breakdown+ * @param prices - Price data+ * @param threshold - Minimum drawdown to report (default: 0.10 = 10%)+ */+ async calculateDrawdowns(+ prices: PriceData,+ threshold?: number+ ): Promise<DrawdownResponse> {+ try {+ const result = await invoke<string>('ffn_calculate_drawdowns', {+ pricesJson: JSON.stringify(prices),+ threshold+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FFNService] calculateDrawdowns error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Calculate rolling performance metrics+ * @param prices - Price data+ * @param window - Rolling window in days (default: 252 = 1 year)+ * @param metrics - Which metrics to calculate ['sharpe', 'volatility', 'returns']+ */+ async calculateRollingMetrics(+ prices: PriceData,+ window?: number,+ metrics?: string[]+ ): Promise<RollingMetricsResponse> {+ try {+ const result = await invoke<string>('ffn_calculate_rolling_metrics', {+ pricesJson: JSON.stringify(prices),+ window,+ metrics+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FFNService] calculateRollingMetrics error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Calculate monthly returns table+ * @param prices - Price data+ */+ async monthlyReturns(prices: PriceData): Promise<MonthlyReturnsResponse> {+ try {+ const result = await invoke<string>('ffn_monthly_returns', {+ pricesJson: JSON.stringify(prices)+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FFNService] monthlyReturns error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Rebase prices to a starting value+ * @param prices - Price data+ * @param baseValue - Starting value (default: 100)+ */+ async rebasePrices(+ prices: PriceData,+ baseValue?: number+ ): Promise<{ success: boolean; base_value?: number; rebased_prices?: Record<string, number>; error?: string }> {+ try {+ const result = await invoke<string>('ffn_rebase_prices', {+ pricesJson: JSON.stringify(prices),+ baseValue+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FFNService] rebasePrices error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Compare multiple assets performance+ * @param prices - Price data with multiple assets+ * @param benchmark - Optional benchmark symbol+ * @param riskFreeRate - Risk-free rate for calculations+ */+ async compareAssets(+ prices: PriceData,+ benchmark?: string,+ riskFreeRate?: number+ ): Promise<AssetComparisonResponse> {+ try {+ const result = await invoke<string>('ffn_compare_assets', {+ pricesJson: JSON.stringify(prices),+ benchmark,+ riskFreeRate+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FFNService] compareAssets error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Calculate comprehensive risk metrics+ * @param prices - Price data+ * @param riskFreeRate - Risk-free rate+ */+ async riskMetrics(+ prices: PriceData,+ riskFreeRate?: number+ ): Promise<RiskMetricsResponse> {+ try {+ const result = await invoke<string>('ffn_risk_metrics', {+ pricesJson: JSON.stringify(prices),+ riskFreeRate+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FFNService] riskMetrics error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Full portfolio analysis - combines all metrics+ * @param prices - Price data+ * @param config - Optional FFN configuration+ */+ async fullAnalysis(+ prices: PriceData,+ config?: FFNConfig+ ): Promise<FullAnalysisResponse> {+ try {+ const result = await invoke<string>('ffn_full_analysis', {+ pricesJson: JSON.stringify(prices),+ config: config ? JSON.stringify(config) : null+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FFNService] fullAnalysis error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ // ============================================================================+ // UTILITY METHODS+ // ============================================================================++ /**+ * Convert array of OHLCV data to price format+ */+ ohlcvToPrices(+ data: Array<{ date: string; close: number }>,+ symbol?: string+ ): PriceData {+ if (symbol) {+ return data.map(d => ({ date: d.date, price: d.close, symbol }));+ }+ return data.reduce((acc, d) => {+ acc[d.date] = d.close;+ return acc;+ }, {} as Record<string, number>);+ }++ /**+ * Format percentage for display+ */+ formatPercent(value: number | null | undefined, decimals = 2): string {+ if (value === null || value === undefined || isNaN(value)) return 'N/A';+ return `${(value * 100).toFixed(decimals)}%`;+ }++ /**+ * Format ratio for display+ */+ formatRatio(value: number | null | undefined, decimals = 2): string {+ if (value === null || value === undefined || isNaN(value)) return 'N/A';+ return value.toFixed(decimals);+ }+}++// Export singleton instance+export const ffnService = new FFNService();diff --git a/fincept-terminal-desktop/src/services/aiQuantLab/functimeService.ts b/fincept-terminal-desktop/src/services/aiQuantLab/functimeService.tsnew file mode 100644index 000000000..37f16fb73--- /dev/null+++ b/fincept-terminal-desktop/src/services/aiQuantLab/functimeService.ts@@ -0,0 +1,473 @@+/**+ * Functime Analytics Service - Frontend API for time series forecasting+ * Provides ML-based forecasting, preprocessing, cross-validation, and metrics+ */++import { invoke } from '@tauri-apps/api/core';++// ============================================================================+// TYPE DEFINITIONS+// ============================================================================++export interface FunctimeStatusResponse {+ success: boolean;+ available: boolean;+ sklearn_available?: boolean;+ polars_available?: boolean;+ lightgbm_available?: boolean;+ functime_cloud_available?: boolean;+ message?: string;+ error?: string;+}++export interface ForecastConfig {+ model?: 'linear' | 'lasso' | 'ridge' | 'elasticnet' | 'knn' | 'lightgbm' |+ 'auto_lasso' | 'auto_ridge' | 'auto_elasticnet' | 'auto_knn' | 'auto_lightgbm';+ horizon?: number;+ frequency?: '1d' | '1w' | '1mo' | '1q' | '1y' | '1h' | '30m' | string;+ alpha?: number; // Regularization for lasso/ridge/elasticnet+ l1_ratio?: number; // L1 ratio for elasticnet+ n_neighbors?: number; // K for KNN+ lags?: number; // Number of lag features for autoregression+}++export interface ForecastResult {+ entity_id: string;+ time: string;+ value: number;+}++export interface ForecastResponse {+ success: boolean;+ model?: string;+ horizon?: number;+ frequency?: string;+ lags?: number;+ forecast?: ForecastResult[];+ shape?: [number, number];+ best_params?: Record<string, unknown>;+ backend?: string;+ error?: string;+}++export interface PreprocessConfig {+ method?: 'boxcox' | 'scale' | 'difference' | 'lags' | 'rolling' | 'impute';+ scale_method?: 'standard' | 'minmax' | 'robust';+ order?: number; // For differencing+ lags?: number[]; // For lag features+ window_sizes?: number[]; // For rolling features+ stats?: string[]; // For rolling features: 'mean', 'std', 'min', 'max'+ impute_method?: 'forward' | 'backward' | 'mean' | 'median';+ lambda?: number; // For Box-Cox+}++export interface PreprocessResponse {+ success: boolean;+ method?: string;+ shape?: [number, number];+ columns?: string[];+ data?: unknown[];+ error?: string;+}++export interface CrossValidateConfig {+ method?: 'train_test' | 'expanding' | 'sliding';+ test_size?: number;+ n_splits?: number;+ train_size?: number; // For sliding window+ step?: number;+}++export interface SplitSummary {+ train_shape: [number, number];+ test_shape: [number, number];+}++export interface CrossValidateResponse {+ success: boolean;+ method?: string;+ train_shape?: [number, number];+ test_shape?: [number, number];+ n_splits?: number;+ splits_summary?: SplitSummary[];+ error?: string;+}++export interface MetricsResponse {+ success: boolean;+ metrics?: {+ mae?: number;+ rmse?: number;+ smape?: number;+ mape?: number;+ mse?: number;+ mase?: number;+ rmsse?: number;+ };+ error?: string;+}++export interface FeatureResponse {+ success: boolean;+ feature_type?: string;+ shape?: [number, number];+ columns?: string[];+ data?: unknown[];+ error?: string;+}++export interface SeasonalPeriodResponse {+ success: boolean;+ frequency?: string;+ seasonal_period?: number;+ error?: string;+}++export interface FullPipelineResponse {+ success: boolean;+ model?: string;+ horizon?: number;+ frequency?: string;+ preprocessing?: {+ method: string;+ type?: string;+ order?: number;+ };+ forecast?: ForecastResult[];+ forecast_shape?: [number, number];+ best_params?: Record<string, unknown>;+ evaluation_metrics?: {+ mae?: number;+ rmse?: number;+ smape?: number;+ };+ data_summary?: {+ total_rows: number;+ entities: number;+ train_size: number;+ test_size: number;+ };+ error?: string;+}++// Panel data format for functime (requires entity_id, time, value)+export type PanelData =+ | Record<string, Record<string, number>> // {entity: {date: value}}+ | Record<string, number> // {date: value} (single entity)+ | Array<{ entity_id: string; time: string; value: number }>; // Array format++// ============================================================================+// FUNCTIME SERVICE CLASS+// ============================================================================++class FunctimeService {+ /**+ * Check functime library status and availability+ */+ async checkStatus(): Promise<FunctimeStatusResponse> {+ try {+ const result = await invoke<string>('functime_check_status');+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] checkStatus error:', error);+ return {+ success: false,+ available: false,+ error: String(error)+ };+ }+ }++ /**+ * Run forecasting with specified model+ * @param data - Panel data with entity_id, time, value+ * @param config - Forecast configuration+ */+ async forecast(+ data: PanelData,+ config?: ForecastConfig+ ): Promise<ForecastResponse> {+ try {+ const result = await invoke<string>('functime_forecast', {+ dataJson: JSON.stringify(data),+ model: config?.model,+ horizon: config?.horizon,+ frequency: config?.frequency,+ alpha: config?.alpha,+ l1Ratio: config?.l1_ratio,+ nNeighbors: config?.n_neighbors,+ lags: config?.lags+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] forecast error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Apply preprocessing transformations+ * @param data - Panel data+ * @param config - Preprocessing configuration+ */+ async preprocess(+ data: PanelData,+ config?: PreprocessConfig+ ): Promise<PreprocessResponse> {+ try {+ const result = await invoke<string>('functime_preprocess', {+ dataJson: JSON.stringify(data),+ method: config?.method,+ scaleMethod: config?.scale_method,+ order: config?.order,+ lags: config?.lags,+ windowSizes: config?.window_sizes,+ stats: config?.stats,+ imputeMethod: config?.impute_method,+ lambda: config?.lambda+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] preprocess error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Perform cross-validation splits+ * @param data - Panel data+ * @param config - CV configuration+ */+ async crossValidate(+ data: PanelData,+ config?: CrossValidateConfig+ ): Promise<CrossValidateResponse> {+ try {+ const result = await invoke<string>('functime_cross_validate', {+ dataJson: JSON.stringify(data),+ method: config?.method,+ testSize: config?.test_size,+ nSplits: config?.n_splits,+ trainSize: config?.train_size,+ step: config?.step+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] crossValidate error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Calculate forecast accuracy metrics+ * @param yTrue - Actual values (panel data format)+ * @param yPred - Predicted values (panel data format)+ * @param metrics - Which metrics to calculate+ */+ async calculateMetrics(+ yTrue: PanelData,+ yPred: PanelData,+ metrics?: string[]+ ): Promise<MetricsResponse> {+ try {+ const result = await invoke<string>('functime_metrics', {+ yTrueJson: JSON.stringify(yTrue),+ yPredJson: JSON.stringify(yPred),+ metrics+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] calculateMetrics error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Add calendar or holiday features+ * @param data - Panel data+ * @param featureType - 'calendar' or 'future_calendar'+ * @param frequency - Data frequency+ * @param horizon - For future features+ */+ async addFeatures(+ data: PanelData,+ featureType?: 'calendar' | 'future_calendar',+ frequency?: string,+ horizon?: number+ ): Promise<FeatureResponse> {+ try {+ const result = await invoke<string>('functime_add_features', {+ dataJson: JSON.stringify(data),+ featureType,+ frequency,+ horizon+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] addFeatures error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Get seasonal period for a frequency+ * @param frequency - Frequency string (e.g., '1d', '1w', '1mo')+ */+ async getSeasonalPeriod(frequency: string): Promise<SeasonalPeriodResponse> {+ try {+ const result = await invoke<string>('functime_seasonal_period', {+ frequency+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] getSeasonalPeriod error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Run complete forecasting pipeline with preprocessing and evaluation+ * @param data - Panel data+ * @param model - Model type+ * @param horizon - Forecast horizon+ * @param frequency - Data frequency+ * @param testSize - Test set size for evaluation+ * @param preprocess - Preprocessing method (optional)+ */+ async fullPipeline(+ data: PanelData,+ model?: string,+ horizon?: number,+ frequency?: string,+ testSize?: number,+ preprocess?: 'scale' | 'difference'+ ): Promise<FullPipelineResponse> {+ try {+ const result = await invoke<string>('functime_full_pipeline', {+ dataJson: JSON.stringify(data),+ model,+ horizon,+ frequency,+ testSize,+ preprocess+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] fullPipeline error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ // ============================================================================+ // UTILITY METHODS+ // ============================================================================++ /**+ * Convert OHLCV data to panel data format+ */+ ohlcvToPanelData(+ data: Array<{ date: string; close: number }>,+ entityId: string = 'default'+ ): Array<{ entity_id: string; time: string; value: number }> {+ return data.map(d => ({+ entity_id: entityId,+ time: d.date,+ value: d.close+ }));+ }++ /**+ * Convert simple time series to panel data format+ */+ timeSeriesToPanelData(+ data: Record<string, number>,+ entityId: string = 'default'+ ): Array<{ entity_id: string; time: string; value: number }> {+ return Object.entries(data).map(([time, value]) => ({+ entity_id: entityId,+ time,+ value+ }));+ }++ /**+ * Combine multiple time series into panel data+ */+ combineTimeSeries(+ series: Record<string, Record<string, number>>+ ): Array<{ entity_id: string; time: string; value: number }> {+ const result: Array<{ entity_id: string; time: string; value: number }> = [];+ for (const [entityId, data] of Object.entries(series)) {+ for (const [time, value] of Object.entries(data)) {+ result.push({ entity_id: entityId, time, value });+ }+ }+ return result;+ }++ /**+ * Format metric value for display+ */+ formatMetric(value: number | null | undefined, decimals = 4): string {+ if (value === null || value === undefined || isNaN(value)) return 'N/A';+ return value.toFixed(decimals);+ }++ /**+ * Get available forecast models+ */+ getAvailableModels(): Array<{ id: string; name: string; description: string }> {+ return [+ { id: 'linear', name: 'Linear Regression', description: 'Simple linear model' },+ { id: 'lasso', name: 'Lasso', description: 'L1 regularized linear model' },+ { id: 'ridge', name: 'Ridge', description: 'L2 regularized linear model' },+ { id: 'elasticnet', name: 'ElasticNet', description: 'Combined L1/L2 regularization' },+ { id: 'knn', name: 'KNN', description: 'K-Nearest Neighbors' },+ { id: 'lightgbm', name: 'LightGBM', description: 'Gradient boosting' },+ { id: 'auto_lasso', name: 'Auto Lasso', description: 'Auto-tuned Lasso' },+ { id: 'auto_ridge', name: 'Auto Ridge', description: 'Auto-tuned Ridge' },+ { id: 'auto_elasticnet', name: 'Auto ElasticNet', description: 'Auto-tuned ElasticNet' },+ { id: 'auto_knn', name: 'Auto KNN', description: 'Auto-tuned KNN' },+ { id: 'auto_lightgbm', name: 'Auto LightGBM', description: 'Auto-tuned LightGBM' }+ ];+ }++ /**+ * Get available frequencies+ */+ getAvailableFrequencies(): Array<{ id: string; name: string }> {+ return [+ { id: '1d', name: 'Daily' },+ { id: '1w', name: 'Weekly' },+ { id: '1mo', name: 'Monthly' },+ { id: '1q', name: 'Quarterly' },+ { id: '1y', name: 'Yearly' },+ { id: '1h', name: 'Hourly' },+ { id: '30m', name: '30 Minutes' }+ ];+ }+}++// Export singleton instance+export const functimeService = new FunctimeService();