Skip to content

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

🔧 Fix Python wrapper execution and JSON serialization

Aviral2610365006c81ff1
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.py
index f28301ea5..c877567fb 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
@@ -111,10 +111,6 @@ class FFNAnalyticsEngine:
else:
self.returns = ffn.to_returns(prices)
- print(f"Data loaded: {len(self.prices)} periods")
- if isinstance(prices, pd.DataFrame):
- print(f"Assets: {len(self.prices.columns)}")
-
def calculate_performance_stats(self,
prices: pd.Series = None,
rf: float = None) -> Dict[str, Any]:
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_performance.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_performance.py
index 06035f9d0..a81a1032d 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_performance.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_performance.py
@@ -68,7 +68,6 @@ class FFNPerformanceAnalyzer:
prices = prices[prices.index <= end_date]
self.prices = prices
- print(f"Multi-asset data loaded: {len(self.prices)} periods, {len(self.prices.columns)} assets")
def calculate_group_stats(self, prices: pd.DataFrame = None) -> ffn.GroupStats:
"""
@@ -377,7 +376,6 @@ class FFNPerformanceAnalyzer:
# Limit to first 4 assets for readability
if len(returns.columns) > 4:
returns = returns.iloc[:, :4]
- print("Limited to first 4 assets for scatter matrix visualization")
import plotly.express as px
fig = px.scatter_matrix(
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_portfolio.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_portfolio.py
index eea1b11cd..4f705c4fd 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_portfolio.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_portfolio.py
@@ -97,8 +97,6 @@ class FFNPortfolioOptimizer:
self.prices = prices
self.returns = ffn.to_returns(prices).dropna() # Remove NaN from first row
- print(f"Portfolio data loaded: {len(self.prices)} periods, {len(self.prices.columns)} assets")
-
def calculate_erc_weights(self,
returns: pd.DataFrame = None,
initial_weights: np.ndarray = 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.py
index 67065e2d2..55d4751df 100644
--- 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.py
@@ -99,12 +99,20 @@ def serialize_result(data: Any) -> str:
elif isinstance(obj, np.bool_):
return bool(obj)
- # Handle pandas types
+ # Handle pandas types - with tuple key support
elif isinstance(obj, pd.Series):
- return {str(k): convert(v) for k, v in obj.items()}
+ # Handle Series with tuple index
+ return {str(k) if isinstance(k, tuple) else 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}
+ # Handle DataFrames with tuple column names (MultiIndex)
+ result = {}
+ for col in obj.columns:
+ col_key = str(col) if isinstance(col, tuple) else str(col)
+ result[col_key] = {}
+ for idx in obj.index:
+ idx_key = str(idx) if isinstance(idx, tuple) else str(idx)
+ result[col_key][idx_key] = convert(obj.loc[idx, col])
+ return result
elif isinstance(obj, (datetime, pd.Timestamp)):
return obj.isoformat()
@@ -112,9 +120,9 @@ def serialize_result(data: Any) -> str:
elif isinstance(obj, float) and np.isnan(obj):
return None
- # Handle dicts and lists
+ # Handle dicts and lists - convert tuple keys to strings
elif isinstance(obj, dict):
- return {k: convert(v) for k, v in obj.items()}
+ return {str(k) if isinstance(k, tuple) else k: convert(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [convert(v) for v in obj]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.py
index 5df99b777..31d975fde 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.py
@@ -86,15 +86,25 @@ def serialize_result(data: Any) -> str:
elif isinstance(obj, np.bool_):
return bool(obj)
elif isinstance(obj, pd.DataFrame):
- return obj.to_dict()
+ # Handle DataFrames with tuple column names (MultiIndex)
+ result = {}
+ for col in obj.columns:
+ col_key = str(col) if isinstance(col, tuple) else col
+ result[col_key] = {}
+ for idx in obj.index:
+ idx_key = str(idx) if isinstance(idx, tuple) else str(idx)
+ result[col_key][idx_key] = convert(obj.loc[idx, col])
+ return result
elif isinstance(obj, pd.Series):
- return obj.to_dict()
+ # Handle Series with tuple index
+ return {str(k) if isinstance(k, tuple) else str(k): convert(v) for k, v in obj.items()}
elif isinstance(obj, pd.Timestamp):
return str(obj)
elif isinstance(obj, datetime):
return obj.isoformat()
elif isinstance(obj, dict):
- return {k: convert(v) for k, v in obj.items()}
+ # Convert tuple keys to strings for JSON compatibility
+ return {str(k) if isinstance(k, tuple) else k: convert(v) for k, v in obj.items()}
elif isinstance(obj, (list, tuple)):
return [convert(i) for i in obj]
return obj
@@ -548,13 +558,21 @@ def main(args: list) -> str:
command = args[0]
- # Parse params if provided
+ # Parse params - either from args or stdin
params = {}
if len(args) > 1:
- try:
- params = json.loads(args[1])
- except json.JSONDecodeError as e:
- return serialize_result({"success": False, "error": f"Invalid JSON params: {e}"})
+ if args[1] == "--stdin":
+ # Read params from stdin (for large payloads)
+ try:
+ stdin_data = sys.stdin.read()
+ params = json.loads(stdin_data)
+ except json.JSONDecodeError as e:
+ return serialize_result({"success": False, "error": f"Invalid JSON from stdin: {e}"})
+ else:
+ try:
+ params = json.loads(args[1])
+ except json.JSONDecodeError as e:
+ return serialize_result({"success": False, "error": f"Invalid JSON params: {e}"})
# Route commands
handlers = {
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.py
index 6e9afbe7f..07f99185c 100644
--- 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.py
@@ -291,9 +291,9 @@ def serialize_result(data: Any) -> str:
elif isinstance(obj, tuple):
return [convert(v) for v in obj]
- # Handle dicts and lists
+ # Handle dicts and lists - convert tuple keys to strings
elif isinstance(obj, dict):
- return {str(k): convert(v) for k, v in obj.items()}
+ return {str(k) if isinstance(k, tuple) else str(k): convert(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [convert(v) for v in obj]
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rs b/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rs
index 53170631e..40bf03bad 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rs
@@ -1,7 +1,6 @@
-// FFN Analytics Commands - Portfolio performance analysis via PyO3
+// FFN Analytics Commands - Portfolio performance analysis via subprocess
#![allow(dead_code)]
-use crate::python_runtime;
-use crate::utils::python::get_script_path;
+use crate::utils::python::execute_python_subprocess;
// ============================================================================
// FFN ANALYTICS COMMANDS
@@ -11,8 +10,12 @@ use crate::utils::python::get_script_path;
#[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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/ffn_wrapper/ffn_service.py",
+ &args,
+ Some("ffn"),
+ )
}
/// Calculate comprehensive performance statistics for price data
@@ -28,8 +31,12 @@ pub async fn ffn_calculate_performance(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/ffn_wrapper/ffn_service.py",
+ &args,
+ Some("ffn"),
+ )
}
/// Calculate drawdown analysis with details
@@ -45,8 +52,12 @@ pub async fn ffn_calculate_drawdowns(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/ffn_wrapper/ffn_service.py",
+ &args,
+ Some("ffn"),
+ )
}
/// Calculate rolling performance metrics
@@ -64,8 +75,12 @@ pub async fn ffn_calculate_rolling_metrics(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/ffn_wrapper/ffn_service.py",
+ &args,
+ Some("ffn"),
+ )
}
/// Calculate monthly returns table
@@ -79,8 +94,12 @@ pub async fn ffn_monthly_returns(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/ffn_wrapper/ffn_service.py",
+ &args,
+ Some("ffn"),
+ )
}
/// Rebase prices to a starting value
@@ -96,8 +115,12 @@ pub async fn ffn_rebase_prices(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/ffn_wrapper/ffn_service.py",
+ &args,
+ Some("ffn"),
+ )
}
/// Compare multiple assets performance
@@ -115,8 +138,12 @@ pub async fn ffn_compare_assets(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/ffn_wrapper/ffn_service.py",
+ &args,
+ Some("ffn"),
+ )
}
/// Calculate risk metrics (Ulcer Index, etc.)
@@ -132,8 +159,12 @@ pub async fn ffn_risk_metrics(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/ffn_wrapper/ffn_service.py",
+ &args,
+ Some("ffn"),
+ )
}
/// Full portfolio analysis - combines all metrics
@@ -149,8 +180,12 @@ pub async fn ffn_full_analysis(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/ffn_wrapper/ffn_service.py",
+ &args,
+ Some("ffn"),
+ )
}
/// Portfolio optimization - calculate optimal weights using various methods
@@ -171,8 +206,12 @@ pub async fn ffn_portfolio_optimization(
});
let args = vec!["portfolio_optimization".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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/ffn_wrapper/ffn_service.py",
+ &args,
+ Some("ffn"),
+ )
}
/// Benchmark comparison - compare portfolio against a benchmark
@@ -192,6 +231,10 @@ pub async fn ffn_benchmark_comparison(
});
let args = vec!["benchmark_comparison".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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/ffn_wrapper/ffn_service.py",
+ &args,
+ Some("ffn"),
+ )
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/fortitudo_analytics.rs b/fincept-terminal-desktop/src-tauri/src/commands/fortitudo_analytics.rs
index 998aa46fa..622467706 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/fortitudo_analytics.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/fortitudo_analytics.rs
@@ -1,7 +1,6 @@
-// Fortitudo.tech Analytics Commands - Portfolio risk analytics via PyO3
+// Fortitudo.tech Analytics Commands - Portfolio risk analytics via subprocess
#![allow(dead_code)]
-use crate::python_runtime;
-use crate::utils::python::get_script_path;
+use crate::utils::python::{execute_python_subprocess, execute_python_subprocess_with_stdin};
// ============================================================================
// FORTITUDO ANALYTICS COMMANDS
@@ -11,8 +10,12 @@ use crate::utils::python::get_script_path;
#[tauri::command]
pub async fn fortitudo_check_status(app: tauri::AppHandle) -> Result<String, String> {
let args = vec!["check_status".to_string()];
- let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ execute_python_subprocess(
+ &app,
+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
+ &args,
+ Some("fortitudo"),
+ )
}
/// Calculate comprehensive portfolio risk metrics (VaR, CVaR, volatility, Sharpe)
@@ -31,9 +34,13 @@ pub async fn fortitudo_portfolio_metrics(
"probabilities": probabilities
});
- let args = vec!["portfolio_metrics".to_string(), params.to_string()];
- let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ execute_python_subprocess_with_stdin(
+ &app,
+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
+ "portfolio_metrics",
+ &params.to_string(),
+ Some("fortitudo"),
+ )
}
/// Calculate covariance and correlation matrices with statistical moments
@@ -48,9 +55,13 @@ pub async fn fortitudo_covariance_analysis(
"probabilities": probabilities
});
- let args = vec!["covariance_analysis".to_string(), params.to_string()];
- let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ execute_python_subprocess_with_stdin(
+ &app,
+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
+ "covariance_analysis",
+ &params.to_string(),
+ Some("fortitudo"),
+ )
}
/// Calculate exponentially decaying probabilities for scenario weighting
@@ -65,9 +76,13 @@ pub async fn fortitudo_exp_decay_weighting(
"half_life": half_life.unwrap_or(252)
});
- let args = vec!["exp_decay_weighting".to_string(), params.to_string()];
- let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ execute_python_subprocess_with_stdin(
+ &app,
+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
+ "exp_decay_weighting",
+ &params.to_string(),
+ Some("fortitudo"),
+ )
}
/// Price options using Black-Scholes model
@@ -91,8 +106,12 @@ pub async fn fortitudo_option_pricing(
});
let args = vec!["option_pricing".to_string(), params.to_string()];
- let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ execute_python_subprocess(
+ &app,
+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
+ &args,
+ Some("fortitudo"),
+ )
}
/// Generate option chain for multiple strikes
@@ -116,8 +135,12 @@ pub async fn fortitudo_option_chain(
});
let args = vec!["option_chain".to_string(), params.to_string()];
- let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ execute_python_subprocess(
+ &app,
+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
+ &args,
+ Some("fortitudo"),
+ )
}
/// Apply entropy pooling for scenario probability adjustment
@@ -133,8 +156,12 @@ pub async fn fortitudo_entropy_pooling(
});
let args = vec!["entropy_pooling".to_string(), params.to_string()];
- let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ execute_python_subprocess(
+ &app,
+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
+ &args,
+ Some("fortitudo"),
+ )
}
/// Calculate exposure stacking portfolio from sample portfolios
@@ -149,9 +176,13 @@ pub async fn fortitudo_exposure_stacking(
"n_partitions": n_partitions.unwrap_or(4)
});
- let args = vec!["exposure_stacking".to_string(), params.to_string()];
- let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ execute_python_subprocess_with_stdin(
+ &app,
+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
+ "exposure_stacking",
+ &params.to_string(),
+ Some("fortitudo"),
+ )
}
/// Full portfolio risk analysis combining all metrics
@@ -170,9 +201,13 @@ pub async fn fortitudo_full_analysis(
"half_life": half_life.unwrap_or(252)
});
- let args = vec!["full_analysis".to_string(), params.to_string()];
- let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ execute_python_subprocess_with_stdin(
+ &app,
+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
+ "full_analysis",
+ &params.to_string(),
+ Some("fortitudo"),
+ )
}
/// Calculate option Greeks (Delta, Gamma, Vega, Theta, Rho)
@@ -196,8 +231,12 @@ pub async fn fortitudo_option_greeks(
});
let args = vec!["option_greeks".to_string(), params.to_string()];
- let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ execute_python_subprocess(
+ &app,
+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
+ &args,
+ Some("fortitudo"),
+ )
}
/// Mean-Variance portfolio optimization
@@ -222,9 +261,13 @@ pub async fn fortitudo_optimize_mean_variance(
"target_return": target_return
});
- let args = vec!["optimize_mean_variance".to_string(), params.to_string()];
- let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ execute_python_subprocess_with_stdin(
+ &app,
+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
+ "optimize_mean_variance",
+ &params.to_string(),
+ Some("fortitudo"),
+ )
}
/// Mean-CVaR portfolio optimization
@@ -251,9 +294,13 @@ pub async fn fortitudo_optimize_mean_cvar(
"target_return": target_return
});
- let args = vec!["optimize_mean_cvar".to_string(), params.to_string()];
- let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ execute_python_subprocess_with_stdin(
+ &app,
+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
+ "optimize_mean_cvar",
+ &params.to_string(),
+ Some("fortitudo"),
+ )
}
/// Generate Mean-Variance efficient frontier
@@ -274,9 +321,13 @@ pub async fn fortitudo_efficient_frontier_mv(
"risk_free_rate": risk_free_rate.unwrap_or(0.0)
});
- let args = vec!["efficient_frontier_mv".to_string(), params.to_string()];
- let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ execute_python_subprocess_with_stdin(
+ &app,
+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
+ "efficient_frontier_mv",
+ &params.to_string(),
+ Some("fortitudo"),
+ )
}
/// Generate Mean-CVaR efficient frontier
@@ -297,7 +348,11 @@ pub async fn fortitudo_efficient_frontier_cvar(
"max_weight": max_weight
});
- let args = vec!["efficient_frontier_cvar".to_string(), params.to_string()];
- let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;
- python_runtime::execute_python_script(&script_path, args)
+ execute_python_subprocess_with_stdin(
+ &app,
+ "Analytics/fortitudo_tech_wrapper/fortitudo_service.py",
+ "efficient_frontier_cvar",
+ &params.to_string(),
+ Some("fortitudo"),
+ )
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rs b/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rs
index 637995b57..671f99ec8 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rs
@@ -1,7 +1,6 @@
-// Functime Analytics Commands - Time series forecasting via PyO3
+// Functime Analytics Commands - Time series forecasting via subprocess
#![allow(dead_code)]
-use crate::python_runtime;
-use crate::utils::python::get_script_path;
+use crate::utils::python::execute_python_subprocess;
// ============================================================================
// FUNCTIME ANALYTICS COMMANDS
@@ -11,8 +10,12 @@ use crate::utils::python::get_script_path;
#[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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Run forecasting with specified model
@@ -41,8 +44,12 @@ pub async fn functime_forecast(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Apply preprocessing transformations to time series data
@@ -73,8 +80,12 @@ pub async fn functime_preprocess(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Perform cross-validation splits
@@ -99,8 +110,12 @@ pub async fn functime_cross_validate(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Calculate forecast accuracy metrics
@@ -119,8 +134,12 @@ pub async fn functime_metrics(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Add calendar or holiday features
@@ -141,8 +160,12 @@ pub async fn functime_add_features(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Get seasonal period for a frequency
@@ -156,8 +179,12 @@ pub async fn functime_seasonal_period(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Run a complete forecasting pipeline with preprocessing and evaluation
@@ -181,8 +208,12 @@ pub async fn functime_full_pipeline(
});
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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
// ============================================================================
@@ -216,8 +247,12 @@ pub async fn functime_advanced_forecast(
});
let args = vec!["advanced_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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Ensemble forecasting combining multiple models
@@ -239,8 +274,12 @@ pub async fn functime_ensemble(
});
let args = vec!["ensemble".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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Automatic ensemble with weight optimization
@@ -258,8 +297,12 @@ pub async fn functime_auto_ensemble(
});
let args = vec!["auto_ensemble".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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Anomaly detection in time series
@@ -281,8 +324,12 @@ pub async fn functime_anomaly_detection(
});
let args = vec!["anomaly_detection".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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Seasonality analysis (decomposition, strength, detection)
@@ -321,8 +368,12 @@ pub async fn functime_seasonality(
});
let args = vec!["seasonality".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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Calculate confidence intervals for forecasts
@@ -344,8 +395,12 @@ pub async fn functime_confidence_intervals(
});
let args = vec!["confidence_intervals".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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Feature importance analysis for ML models
@@ -365,8 +420,12 @@ pub async fn functime_feature_importance(
});
let args = vec!["feature_importance".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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Advanced cross-validation with model evaluation
@@ -390,8 +449,12 @@ pub async fn functime_advanced_cv(
});
let args = vec!["advanced_cv".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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
/// Strategy backtesting for forecasting models
@@ -415,6 +478,10 @@ pub async fn functime_backtest(
});
let args = vec!["backtest".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)
+ execute_python_subprocess(
+ &app,
+ "Analytics/functime_wrapper/functime_service.py",
+ &args,
+ Some("functime"),
+ )
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/yfinance.rs b/fincept-terminal-desktop/src-tauri/src/commands/yfinance.rs
index c2c2b1f2f..ab1821339 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/yfinance.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/yfinance.rs
@@ -1,8 +1,8 @@
// Yahoo Finance data commands
-use crate::utils::python::get_script_path;
-use crate::python_runtime;
+use crate::utils::python::execute_python_subprocess;
-/// Execute Yahoo Finance Python script command with PyO3
+/// Execute Yahoo Finance Python script command via subprocess
+/// Uses direct subprocess instead of worker pool to avoid deadlocks on Windows
#[tauri::command]
pub async fn execute_yfinance_command(
app: tauri::AppHandle,
@@ -13,7 +13,11 @@ pub async fn execute_yfinance_command(
let mut cmd_args = vec![command];
cmd_args.extend(args);
- // Execute Python script with PyO3
- let script_path = get_script_path(&app, "yfinance_data.py")?;
- python_runtime::execute_python_script(&script_path, cmd_args)
+ // Execute Python script via subprocess (avoids worker pool deadlocks)
+ execute_python_subprocess(
+ &app,
+ "yfinance_data.py",
+ &cmd_args,
+ None, // Uses default venv (venv-numpy2)
+ )
}
diff --git a/fincept-terminal-desktop/src-tauri/src/utils/python.rs b/fincept-terminal-desktop/src-tauri/src/utils/python.rs
index 2ba38efd9..d8015b0d6 100644
--- a/fincept-terminal-desktop/src-tauri/src/utils/python.rs
+++ b/fincept-terminal-desktop/src-tauri/src/utils/python.rs
@@ -297,3 +297,53 @@ pub fn execute_python_subprocess(
Err(format!("Python script failed:\nstderr: {}\nstdout: {}", stderr, stdout))
}
}
+
+/// Execute Python script with data passed via stdin (for large payloads)
+/// This avoids Windows command line length limits
+pub fn execute_python_subprocess_with_stdin(
+ app: &tauri::AppHandle,
+ script_relative_path: &str,
+ command: &str,
+ stdin_data: &str,
+ library_hint: Option<&str>,
+) -> Result<String, String> {
+ use std::process::{Command, Stdio};
+ use std::io::Write;
+ #[cfg(target_os = "windows")]
+ use std::os::windows::process::CommandExt;
+
+ let script_path = get_script_path(app, script_relative_path)?;
+ let python_path = get_python_path_for_library(app, library_hint)?;
+
+ let mut cmd = Command::new(&python_path);
+ cmd.arg(&script_path)
+ .arg(command)
+ .arg("--stdin") // Signal to read from stdin
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+
+ let mut child = cmd.spawn()
+ .map_err(|e| format!("Failed to spawn Python: {}", e))?;
+
+ // Write data to stdin
+ if let Some(mut stdin) = child.stdin.take() {
+ stdin.write_all(stdin_data.as_bytes())
+ .map_err(|e| format!("Failed to write to stdin: {}", e))?;
+ }
+
+ let output = child.wait_with_output()
+ .map_err(|e| format!("Failed to wait for Python: {}", e))?;
+
+ if output.status.success() {
+ String::from_utf8(output.stdout)
+ .map_err(|e| format!("Failed to parse output: {}", e))
+ } else {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ Err(format!("Python script failed:\nstderr: {}\nstdout: {}", stderr, stdout))
+ }
+}