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.

voice agent update

tilakpatel223337208c4a58
diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.json
index 0a44c4636..623e59fb7 100644
--- a/fincept-terminal-desktop/package.json
+++ b/fincept-terminal-desktop/package.json
@@ -1,7 +1,7 @@
{
"name": "fincept-terminal-desktop",
"private": true,
- "version": "3.2.1",
+ "version": "3.3.0",
"type": "module",
"license": "AGPL-3.0-or-later",
"scripts": {
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.lock b/fincept-terminal-desktop/src-tauri/Cargo.lock
index c91a7f10c..2b1279c30 100644
--- a/fincept-terminal-desktop/src-tauri/Cargo.lock
+++ b/fincept-terminal-desktop/src-tauri/Cargo.lock
@@ -1247,7 +1247,7 @@ dependencies = [
[[package]]
name = "fincept-terminal-desktop"
-version = "3.2.1"
+version = "3.3.0"
dependencies = [
"aes-gcm",
"ahash",
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.toml b/fincept-terminal-desktop/src-tauri/Cargo.toml
index 10058f675..40fa513d8 100644
--- a/fincept-terminal-desktop/src-tauri/Cargo.toml
+++ b/fincept-terminal-desktop/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "fincept-terminal-desktop"
-version = "3.2.1"
+version = "3.3.0"
description = "Professional-grade financial analysis platform with AI-powered insights and real-time market data"
authors = ["Fincept Corporation <[email protected]>"]
edition = "2021"
diff --git a/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txt b/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txt
index 4aeb7305d..54e0dae5e 100644
--- a/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txt
+++ b/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txt
@@ -62,6 +62,13 @@ langchain-community>=0.0.1
tiktoken>=0.5.0
# Note: litellm removed - model data extracted to llm_models_data.json (240KB static file)
+# Agno AI Framework
+agno>=1.0.0
+
+# Agno Tool Dependencies (free tools - no API keys required)
+ddgs>=6.0.0
+wikipedia>=1.4.0
+
# ML/DL (NumPy 2.x compatible)
# PyTorch 2.3.1+ doesn't support macOS Intel, use 2.2.2 for compatibility
torch==2.2.2; platform_machine == "x86_64" and sys_platform == "darwin"
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_indicators.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_indicators.py
index 0fc7a1ca4..be42d7730 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_indicators.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vbt_indicators.py
@@ -670,6 +670,7 @@ class IndicatorFactory:
raise ValueError("No function defined. Use from_custom_func or from_apply_func.")
param_vals = [params.get(p, None) for p in self._param_names]
+ print(f"[IndicatorFactory.run] param_names={self._param_names}, params={params}, param_vals={param_vals}")
result = func(*inputs, *param_vals)
if isinstance(result, tuple):
@@ -708,7 +709,10 @@ class IndicatorFactory:
try:
output = self.run(*inputs, **params)
results.append({'params': params, 'output': output})
- except Exception:
+ except Exception as e:
+ print(f"[IndicatorFactory.run_combs] Exception for params {params}: {e}")
+ import traceback
+ traceback.print_exc()
continue
return results
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py
index caf29a961..84b32e618 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py
@@ -832,6 +832,55 @@ class VectorBTProvider(BacktestingProviderBase):
except Exception as e:
return {'success': False, 'error': str(e), 'traceback': __import__('traceback').format_exc()}
+ def _calculate_signal_metrics(self, entries, exits, close_series):
+ """Calculate performance metrics for generated signals."""
+ import numpy as np
+
+ metrics = {
+ 'totalSignals': int(entries.sum()),
+ 'signalDensity': float(entries.sum() / len(close_series) * 100), # % of bars with signals
+ }
+
+ # Simple forward-looking performance (next bar return after entry)
+ if entries.sum() > 0:
+ entry_indices = np.where(entries)[0]
+ forward_returns = []
+ holding_periods = []
+
+ for entry_idx in entry_indices:
+ if entry_idx < len(close_series) - 1:
+ entry_price = close_series.iloc[entry_idx]
+
+ # Find next exit or end of data
+ exit_idx = None
+ for idx in range(entry_idx + 1, len(exits)):
+ if exits.iloc[idx]:
+ exit_idx = idx
+ break
+
+ if exit_idx is None:
+ exit_idx = len(close_series) - 1
+
+ exit_price = close_series.iloc[exit_idx]
+ ret = (exit_price - entry_price) / entry_price * 100
+ forward_returns.append(ret)
+ holding_periods.append(exit_idx - entry_idx)
+
+ if forward_returns:
+ returns_array = np.array(forward_returns)
+ metrics['avgReturn'] = float(np.mean(returns_array))
+ metrics['medianReturn'] = float(np.median(returns_array))
+ metrics['winRate'] = float(np.sum(returns_array > 0) / len(returns_array) * 100)
+ metrics['bestTrade'] = float(np.max(returns_array))
+ metrics['worstTrade'] = float(np.min(returns_array))
+ metrics['avgHoldingPeriod'] = float(np.mean(holding_periods))
+ metrics['profitFactor'] = float(
+ np.sum(returns_array[returns_array > 0]) /
+ abs(np.sum(returns_array[returns_array < 0]))
+ ) if np.sum(returns_array < 0) != 0 else float('inf')
+
+ return metrics
+
def indicator_signals(self, request: Dict[str, Any]) -> Dict[str, Any]:
"""Generate indicator-based signals (crossover, threshold, breakout, mean_reversion, filter)."""
try:
@@ -850,7 +899,16 @@ class VectorBTProvider(BacktestingProviderBase):
self._normalize_symbols(symbols), start_date, end_date
)
- result_data = {'mode': mode, 'totalBars': len(close_series), 'usingSyntheticData': using_synthetic}
+ result_data = {
+ 'mode': mode,
+ 'totalBars': len(close_series),
+ 'usingSyntheticData': using_synthetic,
+ 'symbol': symbols[0] if symbols else 'Unknown',
+ 'dateRange': {
+ 'start': str(close_series.index[0]),
+ 'end': str(close_series.index[-1])
+ }
+ }
if mode == 'crossover_signals':
fast_ind = params.get('fast_indicator', 'ma')
@@ -858,46 +916,117 @@ class VectorBTProvider(BacktestingProviderBase):
slow_ind = params.get('slow_indicator', 'ma')
slow_period = params.get('slow_period', 20)
- calc_map = {'ma': ind.calculate_ma, 'ema': lambda s, p: ind.calculate_ma(s, p, ma_type='ema')}
- fast_line = calc_map.get(fast_ind, ind.calculate_ma)(close_series, fast_period)
- slow_line = calc_map.get(slow_ind, ind.calculate_ma)(close_series, slow_period)
+ calc_map = {
+ 'ma': lambda s, p: ind.calculate_ma(None, s, p, ewm=False),
+ 'ema': lambda s, p: ind.calculate_ma(None, s, p, ewm=True)
+ }
+ fast_line = calc_map.get(fast_ind, calc_map['ma'])(close_series, fast_period)
+ slow_line = calc_map.get(slow_ind, calc_map['ma'])(close_series, slow_period)
entries, exits = ind.generate_crossover_signals(fast_line, slow_line, close_series.index)
+
+ # Add performance metrics
+ metrics = self._calculate_signal_metrics(entries, exits, close_series)
+ result_data.update(metrics)
+
+ # Add signal details with context
result_data['entryCount'] = int(entries.sum())
result_data['exitCount'] = int(exits.sum())
- result_data['entries'] = [str(d) for d in entries[entries].index[:50]]
- result_data['exits'] = [str(d) for d in exits[exits].index[:50]]
+ result_data['entrySignals'] = [
+ {
+ 'date': str(d),
+ 'price': float(close_series.loc[d]),
+ 'fastMA': float(fast_line[close_series.index.get_loc(d)]),
+ 'slowMA': float(slow_line[close_series.index.get_loc(d)]),
+ }
+ for d in entries[entries].index[:50]
+ ]
+ result_data['exitSignals'] = [
+ {
+ 'date': str(d),
+ 'price': float(close_series.loc[d]),
+ 'fastMA': float(fast_line[close_series.index.get_loc(d)]),
+ 'slowMA': float(slow_line[close_series.index.get_loc(d)]),
+ }
+ for d in exits[exits].index[:50]
+ ]
elif mode == 'threshold_signals':
period = params.get('period', 14)
lower = params.get('lower', 30)
upper = params.get('upper', 70)
- ind_calc = {'rsi': ind.calculate_rsi, 'cci': ind.calculate_cci, 'williams_r': ind.calculate_williams_r,
- 'stoch': lambda s, p: ind.calculate_stoch(s, s, s, p)[0]}
- calc_fn = ind_calc.get(indicator, ind.calculate_rsi)
+ # Need to get full OHLCV for some indicators
+ import yfinance as yf
+ normalized_symbols = self._normalize_symbols(symbols)
+ raw_data = yf.download(
+ normalized_symbols if len(normalized_symbols) > 1 else normalized_symbols[0],
+ start=start_date, end=end_date, progress=False
+ )
+ high_series = raw_data['High'].values.flatten() if 'High' in raw_data.columns else close_series
+ low_series = raw_data['Low'].values.flatten() if 'Low' in raw_data.columns else close_series
+
+ ind_calc = {
+ 'rsi': lambda s, p: ind.calculate_rsi(None, s, p),
+ 'cci': lambda s, p: ind.calculate_cci(high_series, low_series, s, p),
+ 'williams_r': lambda s, p: ind.calculate_williams_r(high_series, low_series, s, p),
+ 'stoch': lambda s, p: ind.calculate_stoch(None, high_series, low_series, s, p)['k']
+ }
+ calc_fn = ind_calc.get(indicator, ind_calc['rsi'])
values = calc_fn(close_series, period)
entries, exits = ind.generate_threshold_signals(values, lower, upper, close_series.index)
+
+ # Add performance metrics
+ metrics = self._calculate_signal_metrics(entries, exits, close_series)
+ result_data.update(metrics)
+
+ # Add signal details with context
result_data['entryCount'] = int(entries.sum())
result_data['exitCount'] = int(exits.sum())
- result_data['entries'] = [str(d) for d in entries[entries].index[:50]]
- result_data['exits'] = [str(d) for d in exits[exits].index[:50]]
+ result_data['entrySignals'] = [
+ {
+ 'date': str(d),
+ 'price': float(close_series.loc[d]),
+ 'indicatorValue': float(values[close_series.index.get_loc(d)]),
+ 'threshold': lower,
+ }
+ for d in entries[entries].index[:50]
+ ]
+ result_data['exitSignals'] = [
+ {
+ 'date': str(d),
+ 'price': float(close_series.loc[d]),
+ 'indicatorValue': float(values[close_series.index.get_loc(d)]),
+ 'threshold': upper,
+ }
+ for d in exits[exits].index[:50]
+ ]
elif mode == 'breakout_signals':
channel = params.get('channel', 'donchian')
period = params.get('period', 20)
+ # Get full OHLCV for Keltner
+ import yfinance as yf
+ normalized_symbols = self._normalize_symbols(symbols)
+ raw_data = yf.download(
+ normalized_symbols if len(normalized_symbols) > 1 else normalized_symbols[0],
+ start=start_date, end=end_date, progress=False
+ )
+ high_series = raw_data['High'].values.flatten() if 'High' in raw_data.columns else close_series
+ low_series = raw_data['Low'].values.flatten() if 'Low' in raw_data.columns else close_series
+
if channel == 'donchian':
ch = ind.calculate_donchian(close_series, period)
upper_ch = ch['upper'] if isinstance(ch, dict) else ch[0]
lower_ch = ch['lower'] if isinstance(ch, dict) else ch[1]
elif channel == 'bbands':
- bb = ind.calculate_bbands(close_series, period)
+ bb = ind.calculate_bbands(None, close_series, period)
upper_ch = bb['upper'] if isinstance(bb, dict) else bb[0]
lower_ch = bb['lower'] if isinstance(bb, dict) else bb[2]
else:
- ch = ind.calculate_keltner(close_series, close_series, close_series, period)
+ ch = ind.calculate_keltner(high_series, low_series, close_series, ema_period=period, atr_period=10, multiplier=2.0)
upper_ch = ch['upper'] if isinstance(ch, dict) else ch[0]
lower_ch = ch['lower'] if isinstance(ch, dict) else ch[2]
@@ -927,18 +1056,38 @@ class VectorBTProvider(BacktestingProviderBase):
filter_threshold = params.get('filter_threshold', 25)
filter_type = params.get('filter_type', 'above')
+ # Get full OHLCV for indicators that need it
+ import yfinance as yf
+ normalized_symbols = self._normalize_symbols(symbols)
+ raw_data = yf.download(
+ normalized_symbols if len(normalized_symbols) > 1 else normalized_symbols[0],
+ start=start_date, end=end_date, progress=False
+ )
+ high_series = raw_data['High'].values.flatten() if 'High' in raw_data.columns else close_series
+ low_series = raw_data['Low'].values.flatten() if 'Low' in raw_data.columns else close_series
+
# Compute base indicator and generate threshold signals
- base_calc = {'rsi': ind.calculate_rsi, 'cci': ind.calculate_cci, 'williams_r': ind.calculate_williams_r,
- 'momentum': ind.calculate_momentum, 'stoch': lambda s, p: ind.calculate_stoch(s, s, s, p)[0],
- 'macd': lambda s, p: ind.calculate_macd(s, p, p * 2, 9)[0]}
- base_fn = base_calc.get(base_indicator, ind.calculate_rsi)
+ base_calc = {
+ 'rsi': lambda s, p: ind.calculate_rsi(None, s, p),
+ 'cci': lambda s, p: ind.calculate_cci(high_series, low_series, s, p),
+ 'williams_r': lambda s, p: ind.calculate_williams_r(high_series, low_series, s, p),
+ 'momentum': lambda s, p: ind.calculate_momentum(s, p),
+ 'stoch': lambda s, p: ind.calculate_stoch(None, high_series, low_series, s, p)['k'],
+ 'macd': lambda s, p: ind.calculate_macd(None, s, p, p * 2, 9)['macd']
+ }
+ base_fn = base_calc.get(base_indicator, base_calc['rsi'])
base_values = base_fn(close_series, base_period)
entries, exits = ind.generate_threshold_signals(base_values, 30, 70, close_series.index)
# Compute filter indicator
- filter_calc = {'adx': ind.calculate_adx, 'atr': ind.calculate_atr, 'mstd': ind.calculate_mstd,
- 'zscore': ind.calculate_zscore, 'rsi': ind.calculate_rsi}
- filter_fn = filter_calc.get(filter_indicator, ind.calculate_adx)
+ filter_calc = {
+ 'adx': lambda s, p: ind.calculate_adx(s, high=high_series, low=low_series, period=p),
+ 'atr': lambda s, p: ind.calculate_atr(None, high_series, low_series, s, p),
+ 'mstd': lambda s, p: ind.calculate_mstd(None, s, p),
+ 'zscore': lambda s, p: ind.calculate_zscore(s, p),
+ 'rsi': lambda s, p: ind.calculate_rsi(None, s, p)
+ }
+ filter_fn = filter_calc.get(filter_indicator, filter_calc['adx'])
filter_values = filter_fn(close_series, filter_period)
filtered_entries, filtered_exits = ind.apply_signal_filter(
@@ -959,6 +1108,13 @@ class VectorBTProvider(BacktestingProviderBase):
def indicator_param_sweep(self, request: Dict[str, Any]) -> Dict[str, Any]:
"""Run indicator parameter sweep using IndicatorFactory.run_combs()."""
+ import sys
+ print("[INDICATOR_SWEEP] === STARTING ===", flush=True)
+ sys.stdout.flush()
+
+ # TEST: Return immediately to see if function is being called
+ # return {'success': True, 'data': {'indicator': 'TEST', 'totalCombinations': 999, 'usingSyntheticData': False, 'results': []}}
+
try:
import numpy as np
import pandas as pd
@@ -970,9 +1126,46 @@ class VectorBTProvider(BacktestingProviderBase):
end_date = request.get('endDate')
param_ranges = request.get('paramRanges', {})
- close_series, using_synthetic = self._load_market_data(
- self._normalize_symbols(symbols), start_date, end_date
- )
+ print(f"[INDICATOR_SWEEP] Got request: indicator={indicator}, symbols={symbols}", flush=True)
+ print(f"[INDICATOR_SWEEP] param_ranges={param_ranges}", flush=True)
+ sys.stdout.flush()
+
+ # Load full OHLCV data instead of just close
+ normalized_symbols = self._normalize_symbols(symbols)
+ using_synthetic = False
+
+ try:
+ import yfinance as yf
+ raw_data = yf.download(
+ normalized_symbols if len(normalized_symbols) > 1 else normalized_symbols[0],
+ start=start_date, end=end_date, progress=False
+ )
+
+ if raw_data is None or raw_data.empty:
+ raise ValueError(f'No data returned for {normalized_symbols}')
+
+ # Extract OHLCV columns
+ if len(normalized_symbols) == 1:
+ # Single symbol - yfinance returns multi-index columns, need to flatten
+ close_series = (raw_data['Close'].values if 'Close' in raw_data else raw_data['close'].values).flatten()
+ high_series = (raw_data['High'].values if 'High' in raw_data else raw_data['high'].values).flatten()
+ low_series = (raw_data['Low'].values if 'Low' in raw_data else raw_data['low'].values).flatten()
+ volume_series = (raw_data['Volume'].values if 'Volume' in raw_data else raw_data['volume'].values).flatten()
+ else:
+ # Multi-symbol: take first symbol
+ close_series = raw_data['Close'].iloc[:, 0].values
+ high_series = raw_data['High'].iloc[:, 0].values
+ low_series = raw_data['Low'].iloc[:, 0].values
+ volume_series = raw_data['Volume'].iloc[:, 0].values
+
+ except Exception as e:
+ print(f"[INDICATOR_SWEEP] Data load failed: {e}, using synthetic")
+ using_synthetic = True
+ # Generate synthetic OHLCV
+ close_series = self._generate_synthetic_data(symbols, start_date, end_date).values
+ high_series = close_series * 1.02 # High = close * 1.02
+ low_series = close_series * 0.98 # Low = close * 0.98
+ volume_series = np.random.randint(1000000, 10000000, len(close_series))
# Build parameter lists from ranges
param_lists = {}
@@ -980,31 +1173,82 @@ class VectorBTProvider(BacktestingProviderBase):
mn, mx, st = rng.get('min', 5), rng.get('max', 50), rng.get('step', 5)
param_lists[name] = list(range(int(mn), int(mx) + 1, int(st))) if st >= 1 else list(np.arange(mn, mx + st, st))
+ print(f"[INDICATOR_SWEEP] indicator={indicator}")
+ print(f"[INDICATOR_SWEEP] param_ranges={param_ranges}")
+ print(f"[INDICATOR_SWEEP] param_lists={param_lists}")
+ print(f"[INDICATOR_SWEEP] close_series length={len(close_series)}")
+
# Map indicator to factory-compatible function
+ # Signatures from python -c inspection:
+ # Single-price indicators (work with close only):
+ # calculate_ma(vbt, close, period, ewm=False)
+ # calculate_rsi(vbt, close, period=14)
+ # calculate_mstd(vbt, close, period, ewm=False)
+ # calculate_zscore(close, period=20)
+ # calculate_momentum(close, lookback=20)
+ # calculate_donchian(close, period=20) -> dict
+ # calculate_bbands(vbt, close, period=20, alpha=2.0) -> dict
+ # calculate_obv(vbt, close, volume) - needs volume
+ # Multi-price indicators (need high/low/close):
+ # calculate_atr(vbt, high, low, close, period=14)
+ # calculate_cci(high, low, close, period=20)
+ # calculate_williams_r(high, low, close, period=14)
+ # calculate_keltner(high, low, close, ema_period=20, atr_period=10, multiplier=2.0) -> dict
+ # calculate_stoch(vbt, high, low, close, k_period=14, d_period=3) -> dict
+ # calculate_macd(vbt, close, fast_period=12, slow_period=26, signal_period=9) -> dict
+ # calculate_adx(close, high=None, low=None, period=14) -> dict
+
+ # Now we have full OHLCV data, support ALL indicators
calc_map = {
- 'rsi': lambda s, period=14: ind.calculate_rsi(s, period),
- 'ma': lambda s, period=20: ind.calculate_ma(s, period),
- 'ema': lambda s, period=20: ind.calculate_ma(s, period, ma_type='ema'),
- 'atr': lambda s, period=14: ind.calculate_atr(s, period),
- 'mstd': lambda s, period=20: ind.calculate_mstd(s, period),
- 'zscore': lambda s, period=20: ind.calculate_zscore(s, period),
- 'adx': lambda s, period=14: ind.calculate_adx(s, period),
- 'momentum': lambda s, lookback=20: ind.calculate_momentum(s, lookback),
- 'cci': lambda s, period=20: ind.calculate_cci(s, period),
- 'williams_r': lambda s, period=14: ind.calculate_williams_r(s, period),
+ # Moving averages (close only)
+ 'ma': lambda period: ind.calculate_ma(None, close_series, period, ewm=False),
+ 'ema': lambda period: ind.calculate_ma(None, close_series, period, ewm=True),
+ 'mstd': lambda period: ind.calculate_mstd(None, close_series, period, ewm=False),
+
+ # Oscillators (close only)
+ 'rsi': lambda period: ind.calculate_rsi(None, close_series, period),
+ 'momentum': lambda lookback: ind.calculate_momentum(close_series, lookback),
+
+ # Statistical (close only)
+ 'zscore': lambda period: ind.calculate_zscore(close_series, period),
+
+ # Channels/Bands (close only)
+ 'donchian': lambda period: ind.calculate_donchian(close_series, period),
+ 'bbands': lambda period: ind.calculate_bbands(None, close_series, period, alpha=2.0),
+ 'macd': lambda fast, slow, signal: ind.calculate_macd(None, close_series, fast, slow, signal),
+ 'adx': lambda period: ind.calculate_adx(close_series, high=high_series, low=low_series, period=period),
+
+ # Multi-price indicators (need high/low/close)
+ 'atr': lambda period: ind.calculate_atr(None, high_series, low_series, close_series, period),
+ 'cci': lambda period: ind.calculate_cci(high_series, low_series, close_series, period),
+ 'williams_r': lambda period: ind.calculate_williams_r(high_series, low_series, close_series, period),
+ 'keltner': lambda period: ind.calculate_keltner(high_series, low_series, close_series, ema_period=period, atr_period=10, multiplier=2.0),
+ 'stoch': lambda k_period, d_period: ind.calculate_stoch(None, high_series, low_series, close_series, k_period, d_period),
+
+ # Volume indicators
+ 'obv': lambda: ind.calculate_obv(None, close_series, volume_series),
+ 'vwap': lambda: ind.calculate_vwap(high_series, low_series, close_series, volume_series),
}
if indicator not in calc_map:
return {'success': False, 'error': f'Indicator {indicator} not supported for param sweep'}
- factory = ind.IndicatorFactory(
- input_names=['close'],
+ print(f"[INDICATOR_SWEEP] Creating factory with param_names={list(param_lists.keys())}")
+
+ # Create factory - the lambdas now capture OHLCV data internally
+ # So we don't pass inputs to run_combs, only params
+ factory_fn = ind.IndicatorFactory.from_custom_func(
+ calc_map[indicator],
+ input_names=[], # No inputs needed, captured in lambda
param_names=list(param_lists.keys()),
output_names=['output'],
short_name=indicator,
)
- factory_fn = factory.from_custom_func(lambda close, **kw: calc_map[indicator](close, **kw))
- results = factory_fn.run_combs(close_series, param_ranges=param_lists)
+ print(f"[INDICATOR_SWEEP] Calling run_combs with param_ranges={param_lists}")
+
+ # Call run_combs without inputs since lambdas capture OHLCV
+ results = factory_fn.run_combs(param_ranges=param_lists)
+ print(f"[INDICATOR_SWEEP] run_combs returned {len(results)} results")
# Summarize results
summaries = []
@@ -1012,24 +1256,54 @@ class VectorBTProvider(BacktestingProviderBase):
params_dict = r.get('params', {})
output = r.get('output')
summary = {'params': params_dict}
- if output is not None and hasattr(output, '__len__') and len(output) > 0:
- vals = np.array(output, dtype=float)
- vals = vals[~np.isnan(vals)]
- if len(vals) > 0:
- summary['mean'] = float(np.mean(vals))
- summary['std'] = float(np.std(vals))
- summary['min'] = float(np.min(vals))
- summary['max'] = float(np.max(vals))
- summary['last'] = float(vals[-1])
+
+ # Output can be a dict (from IndicatorFactory) or array
+ if output is not None:
+ # IndicatorFactory wraps output in dict with 'output' key
+ if isinstance(output, dict) and 'output' in output:
+ output = output['output']
+
+ # Now output is the actual indicator result (array or dict)
+ if isinstance(output, dict):
+ # Multi-output indicator (MACD, BBands, Stoch)
+ # Calculate stats for each component
+ summary['outputs'] = {}
+ for component_name, component_array in output.items():
+ if component_array is not None and hasattr(component_array, '__len__') and len(component_array) > 0:
+ vals = np.array(component_array, dtype=float)
+ vals = vals[~np.isnan(vals)]
+ if len(vals) > 0:
+ summary['outputs'][component_name] = {
+ 'mean': float(np.mean(vals)),
+ 'std': float(np.std(vals)),
+ 'min': float(np.min(vals)),
+ 'max': float(np.max(vals)),
+ 'last': float(vals[-1])
+ }
+ elif hasattr(output, '__len__') and len(output) > 0:
+ # Single-output indicator (MA, RSI, ATR, etc.)
+ vals = np.array(output, dtype=float)
+ vals = vals[~np.isnan(vals)]
+ if len(vals) > 0:
+ summary['mean'] = float(np.mean(vals))
+ summary['std'] = float(np.std(vals))
+ summary['min'] = float(np.min(vals))
+ summary['max'] = float(np.max(vals))
+ summary['last'] = float(vals[-1])
summaries.append(summary)
- return {'success': True, 'data': {
+ result_data = {
'indicator': indicator,
'totalCombinations': len(results),
'usingSyntheticData': using_synthetic,
'results': summaries,
- }}
+ }
+ print(f"[INDICATOR_SWEEP] Returning: {result_data}")
+ return {'success': True, 'data': result_data}
except Exception as e:
+ print(f"[INDICATOR_SWEEP] ERROR: {e}")
+ import traceback
+ traceback.print_exc()
return {'success': False, 'error': str(e), 'traceback': __import__('traceback').format_exc()}
def labels_to_signals(self, request: Dict[str, Any]) -> Dict[str, Any]:
@@ -1564,7 +1838,11 @@ def main():
result = provider.indicator_signals(args)
result_str = json_response(result)
elif command == 'indicator_param_sweep':
+ print("[MAIN] About to call indicator_param_sweep")
+ sys.stdout.flush()
result = provider.indicator_param_sweep(args)
+ print(f"[MAIN] indicator_param_sweep returned: {result}")
+ sys.stdout.flush()
result_str = json_response(result)
elif command == 'labels_to_signals':
result = provider.labels_to_signals(args)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/behavioral_finance_analyst_agent.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/behavioral_finance_analyst_agent.json
new file mode 100644
index 000000000..4fd771c50
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/behavioral_finance_analyst_agent.json
@@ -0,0 +1,23 @@
+{
+ "id": "behavioral_finance_analyst",
+ "name": "Behavioral Finance Analyst",
+ "description": "Analyzes investor psychology, sentiment indicators, and behavioral patterns to identify overbought/oversold conditions and contrarian trade setups.",
+ "category": "hedgeFundAgents",
+ "version": "1.0.0",
+ "provider": "local",
+ "capabilities": ["sentiment_analysis", "behavioral_psychology", "contrarian_opportunities"],
+ "config": {
+ "role": "Market psychology and sentiment analysis expert",
+ "goal": "Identify market sentiment extremes and behavioral biases for contrarian opportunities",
+ "instructions": "You are a behavioral finance expert for a hedge fund. Analyze investor psychology using: 1) Sentiment indicators (VIX, put/call ratios, investor surveys), 2) Positioning data (CFTC commitments, fund flows), 3) Behavioral biases (herding, recency bias, anchoring), 4) Market narratives and their evolution, 5) Contrarian signals from extreme sentiment. Identify when markets are pricing in too much optimism or pessimism.",
+ "llm_config": {
+ "provider": "anthropic",
+ "model_id": "claude-3-sonnet-20240229",
+ "temperature": 0.7,
+ "max_tokens": 3000
+ },
+ "tools": ["market_data", "sentiment_analysis", "web_search"],
+ "enable_memory": true,
+ "enable_agentic_memory": true
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/central_bank_analyst_agent.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/central_bank_analyst_agent.json
new file mode 100644
index 000000000..772fa3c2f
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/central_bank_analyst_agent.json
@@ -0,0 +1,23 @@
+{
+ "id": "central_bank_analyst",
+ "name": "Central Bank Policy Analyst",
+ "description": "Monitors central bank communications, policy tools, and macroeconomic conditions to predict interest rate paths and quantitative easing/tightening cycles.",
+ "category": "hedgeFundAgents",
+ "version": "1.0.0",
+ "provider": "local",
+ "capabilities": ["monetary_policy", "interest_rate_forecasting", "central_bank_analysis"],
+ "config": {
+ "role": "Monetary policy and interest rate forecasting expert",
+ "goal": "Forecast central bank policy decisions and analyze their market impact",
+ "instructions": "You are a central bank policy analyst for a hedge fund. Monitor Fed, ECB, BOJ, and other central banks. Analyze: 1) Forward guidance and dot plots, 2) Inflation vs employment trade-offs, 3) Balance sheet policy (QE/QT), 4) Currency intervention signals, 5) Cross-border policy coordination. Predict policy pivots and recommend positioning in rates, currencies, and duration-sensitive assets.",
+ "llm_config": {
+ "provider": "openai",
+ "model_id": "gpt-4-turbo",
+ "temperature": 0.7,
+ "max_tokens": 3000
+ },
+ "tools": ["economic_data", "web_search", "news_analysis"],
+ "enable_memory": true,
+ "enable_agentic_memory": true
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/currency_strategist_agent.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/currency_strategist_agent.json
new file mode 100644
index 000000000..bc7cdbc67
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/currency_strategist_agent.json
@@ -0,0 +1,23 @@
+{
+ "id": "currency_strategist",
+ "name": "Currency & FX Strategist",
+ "description": "Analyzes interest rate differentials, capital flows, trade balances, and central bank policies to forecast currency trends and volatility.",
+ "category": "hedgeFundAgents",
+ "version": "1.0.0",
+ "provider": "local",
+ "capabilities": ["fx_analysis", "currency_forecasting", "carry_trade_opportunities"],
+ "config": {
+ "role": "Foreign exchange markets and currency dynamics expert",
+ "goal": "Forecast currency movements and identify FX trading opportunities",
+ "instructions": "You are a currency strategist for a hedge fund. Analyze FX markets using: 1) Interest rate differentials and carry trade opportunities, 2) Current account and capital flow balances, 3) Central bank intervention signals, 4) Political risk and safe-haven flows, 5) Currency valuation metrics (PPP, REER). Recommend directional trades, volatility plays, and hedging strategies. Consider both G10 and emerging market currencies.",
+ "llm_config": {
+ "provider": "openai",
+ "model_id": "gpt-4-turbo",
+ "temperature": 0.7,
+ "max_tokens": 3000
+ },
+ "tools": ["economic_data", "market_data", "web_search"],
+ "enable_memory": true,
+ "enable_agentic_memory": true
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/geopolitical_risk_analyst_agent.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/geopolitical_risk_analyst_agent.json
new file mode 100644
index 000000000..f7c79a75d
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/geopolitical_risk_analyst_agent.json
@@ -0,0 +1,23 @@
+{
+ "id": "geopolitical_risk_analyst",
+ "name": "Geopolitical Risk Analyst",
+ "description": "Analyzes geopolitical events, conflicts, trade tensions, and regulatory changes for investment implications across equities, commodities, and currencies.",
+ "category": "hedgeFundAgents",
+ "version": "1.0.0",
+ "provider": "local",
+ "capabilities": ["geopolitical_analysis", "risk_assessment", "event_driven_trading"],
+ "config": {
+ "role": "Geopolitical risk assessment and opportunity identification expert",
+ "goal": "Assess geopolitical risks and identify opportunities arising from global events",
+ "instructions": "You are a geopolitical analyst for a hedge fund. Assess risks and opportunities from: 1) International conflicts and military actions, 2) Trade tensions and tariff policies, 3) Sanctions and regulatory changes, 4) Energy security and commodity supply chains, 5) Political transitions and policy shifts. Identify both direct impacts (defense stocks, commodity prices) and second-order effects (supply chain disruptions, currency volatility).",
+ "llm_config": {
+ "provider": "openai",
+ "model_id": "gpt-4-turbo",
+ "temperature": 0.7,
+ "max_tokens": 3000
+ },
+ "tools": ["news_analysis", "web_search", "economic_data"],
+ "enable_memory": true,
+ "enable_agentic_memory": true
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/innovation_disruption_analyst_agent.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/innovation_disruption_analyst_agent.json
new file mode 100644
index 000000000..b17a0606a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/innovation_disruption_analyst_agent.json
@@ -0,0 +1,23 @@
+{
+ "id": "innovation_disruption_analyst",
+ "name": "Innovation & Disruption Analyst",
+ "description": "Analyzes technological trends, disruptive business models, and innovation cycles to identify long-term growth opportunities and disruption threats.",
+ "category": "hedgeFundAgents",
+ "version": "1.0.0",
+ "provider": "local",
+ "capabilities": ["technology_analysis", "innovation_tracking", "disruption_detection"],
+ "config": {
+ "role": "Disruptive technology and innovation investment expert",
+ "goal": "Identify emerging technologies and business model innovations creating investment opportunities",
+ "instructions": "You are an innovation analyst for a hedge fund. Identify disruptive trends: 1) Emerging technologies (AI, quantum, biotech, clean energy), 2) Business model innovations (platform economics, subscription models), 3) Regulatory changes enabling new markets, 4) Patent filings indicating R&D direction, 5) Adoption curves and tipping points. Distinguish between genuine innovation and hype cycles. Identify both long opportunities (innovators) and short opportunities (disrupted incumbents).",
+ "llm_config": {
+ "provider": "anthropic",
+ "model_id": "claude-3-sonnet-20240229",
+ "temperature": 0.8,
+ "max_tokens": 3000
+ },
+ "tools": ["web_search", "patent_analysis", "market_data"],
+ "enable_memory": true,
+ "enable_agentic_memory": true
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/institutional_flow_tracker_agent.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/institutional_flow_tracker_agent.json
new file mode 100644
index 000000000..7dc77b70f
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/institutional_flow_tracker_agent.json
@@ -0,0 +1,23 @@
+{
+ "id": "institutional_flow_tracker",
+ "name": "Institutional Flow Tracker",
+ "description": "Monitors hedge fund holdings (13F filings), mutual fund flows, pension allocations, and other institutional activity to identify smart money positioning.",
+ "category": "hedgeFundAgents",
+ "version": "1.0.0",
+ "provider": "local",
+ "capabilities": ["institutional_analysis", "flow_tracking", "positioning_analysis"],
+ "config": {
+ "role": "Smart money positioning and flow analysis expert",
+ "goal": "Track institutional investor positioning and capital flows",
+ "instructions": "You are an institutional flow analyst for a hedge fund. Track smart money by: 1) Analyzing 13F filings for hedge fund positioning changes, 2) Monitoring mutual fund and ETF flows, 3) Tracking pension fund allocations, 4) Identifying unusual options activity by institutions, 5) Analyzing block trades and dark pool activity. Determine if institutions are accumulating or distributing, and identify crowded trades vs under-owned opportunities.",
+ "llm_config": {
+ "provider": "openai",
+ "model_id": "gpt-4-turbo",
+ "temperature": 0.6,
+ "max_tokens": 3000
+ },
+ "tools": ["sec_filings", "fund_flows", "web_search"],
+ "enable_memory": true,
+ "enable_agentic_memory": true
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/macro_cycle_agent_agent.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/macro_cycle_agent_agent.json
new file mode 100644
index 000000000..63e5888ab
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/macro_cycle_agent_agent.json
@@ -0,0 +1,23 @@
+{
+ "id": "macro_cycle_agent",
+ "name": "Macro Cycle Analyst",
+ "description": "Analyzes macroeconomic data to determine business cycle positioning - expansion, peak, contraction, or trough. Provides insights on cyclical sector rotation.",
+ "category": "hedgeFundAgents",
+ "version": "1.0.0",
+ "provider": "local",
+ "capabilities": ["economic_analysis", "cycle_identification", "sector_rotation"],
+ "config": {
+ "role": "Business cycle and economic phase identification expert",
+ "goal": "Identify current economic cycle phase and predict transitions",
+ "instructions": "You are a macro cycle analyst for a hedge fund. Analyze economic indicators (GDP growth, unemployment, inflation, yield curve, PMI, consumer confidence) to determine: 1) Current cycle phase, 2) Expected duration before transition, 3) Sector rotation recommendations, 4) Leading vs lagging indicators divergence. Provide actionable insights for portfolio positioning based on cycle dynamics.",
+ "llm_config": {
+ "provider": "openai",
+ "model_id": "gpt-4-turbo",
+ "temperature": 0.7,
+ "max_tokens": 3000
+ },
+ "tools": ["economic_data", "web_search", "market_data"],
+ "enable_memory": true,
+ "enable_agentic_memory": true
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/regulatory_policy_analyst_agent.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/regulatory_policy_analyst_agent.json
new file mode 100644
index 000000000..f27276b2d
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/regulatory_policy_analyst_agent.json
@@ -0,0 +1,23 @@
+{
+ "id": "regulatory_policy_analyst",
+ "name": "Regulatory & Policy Analyst",
+ "description": "Tracks regulatory proposals, compliance requirements, and policy changes across sectors to identify winners and losers from regulatory shifts.",
+ "category": "hedgeFundAgents",
+ "version": "1.0.0",
+ "provider": "local",
+ "capabilities": ["regulatory_analysis", "policy_tracking", "compliance_monitoring"],
+ "config": {
+ "role": "Regulatory changes and compliance impact expert",
+ "goal": "Analyze regulatory developments and their investment implications",
+ "instructions": "You are a regulatory analyst for a hedge fund. Monitor policy developments: 1) Proposed legislation and regulatory rule changes, 2) Antitrust and competition policy, 3) Environmental and climate regulations, 4) Financial services oversight changes, 5) Healthcare and pharma policy shifts. Identify sectors facing regulatory headwinds (short candidates) and those benefiting from deregulation or favorable policy (long candidates). Track regulatory calendar and comment period deadlines.",
+ "llm_config": {
+ "provider": "openai",
+ "model_id": "gpt-4-turbo",
+ "temperature": 0.6,
+ "max_tokens": 3000
+ },
+ "tools": ["web_search", "news_analysis", "regulatory_filings"],
+ "enable_memory": true,
+ "enable_agentic_memory": true
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/renaissance_technologies_agent.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/renaissance_technologies_agent.json
new file mode 100644
index 000000000..c7f8f4fcb
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/renaissance_technologies_agent.json
@@ -0,0 +1,114 @@
+{
+ "id": "renaissance_technologies",
+ "name": "Renaissance Technologies Medallion Fund",
+ "description": "Multi-agent quantitative hedge fund system inspired by RenTech's systematic approach. Features 10 specialized agents, 4 teams, signal discovery, risk assessment, IC deliberation, and execution workflows.",
+ "category": "hedgeFundAgents",
+ "version": "1.0.0",
+ "provider": "local",
+ "capabilities": [
+ "signal_discovery",
+ "statistical_analysis",
+ "risk_assessment",
+ "portfolio_optimization",
+ "ic_deliberation",
+ "trade_execution",
+ "post_trade_analysis",
+ "multi_agent_collaboration",
+ "systematic_trading",
+ "quantitative_research"
+ ],
+ "config": {
+ "model": {
+ "provider": "openai",
+ "model_id": "gpt-4o",
+ "temperature": 0.7,
+ "max_tokens": 4096
+ },
+ "instructions": "Renaissance Technologies Multi-Agent System with 10 specialized agents:\n\n**Research Team:**\n- Signal Scientist: Discovers statistical signals (p<0.01)\n- Data Scientist: Data quality and feature engineering\n- Quant Researcher: Strategy development and backtesting\n- Research Lead: Validates research and coordinates team\n\n**Trading Team:**\n- Execution Trader: Optimal order execution (TWAP/VWAP)\n- Market Maker: Liquidity provision and spread capture\n\n**Risk Team:**\n- Risk Quant: VaR, drawdown, stress testing\n- Compliance Officer: Regulatory compliance\n\n**Investment Committee:**\n- Portfolio Manager: Position sizing and portfolio construction\n- Investment Committee Chair: Final approval with 0.5075 win rate threshold\n\n**Key Features:**\n- Statistical rigor (p-values, IC, t-stats)\n- Multi-step reasoning engine\n- Agent memory system\n- Knowledge base with LanceDB\n- Guardrails (position limits, VaR limits)\n- Evaluation and learning\n- Full observability/tracing\n\n**Workflows:**\n1. Signal Discovery → Validation → Risk Assessment → IC Deliberation → Execution → Post-Trade Analysis\n\n**Commands:**\n- analyze_signal: Full signal analysis pipeline\n- run_ic_deliberation: Investment Committee decision\n- run_agent: Execute specific agent\n- run_team: Execute team workflow",
+ "tools": [
+ "signal_discovery",
+ "statistical_testing",
+ "backtesting",
+ "risk_modeling",
+ "portfolio_optimization",
+ "market_data_fetch",
+ "execution_algorithms"
+ ],
+ "output_format": "json",
+ "script_path": "agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/rentech_cli.py",
+ "agents": [
+ {
+ "id": "signal_scientist",
+ "name": "Signal Scientist",
+ "role": "Statistical signal discovery"
+ },
+ {
+ "id": "data_scientist",
+ "name": "Data Scientist",
+ "role": "Data quality and feature engineering"
+ },
+ {
+ "id": "quant_researcher",
+ "name": "Quant Researcher",
+ "role": "Strategy development and backtesting"
+ },
+ {
+ "id": "research_lead",
+ "name": "Research Lead",
+ "role": "Research validation and coordination"
+ },
+ {
+ "id": "execution_trader",
+ "name": "Execution Trader",
+ "role": "Optimal trade execution"
+ },
+ {
+ "id": "market_maker",
+ "name": "Market Maker",
+ "role": "Liquidity and spread capture"
+ },
+ {
+ "id": "risk_quant",
+ "name": "Risk Quant",
+ "role": "Risk modeling and assessment"
+ },
+ {
+ "id": "compliance_officer",
+ "name": "Compliance Officer",
+ "role": "Regulatory compliance"
+ },
+ {
+ "id": "portfolio_manager",
+ "name": "Portfolio Manager",
+ "role": "Position sizing and portfolio construction"
+ },
+ {
+ "id": "investment_committee_chair",
+ "name": "Investment Committee Chair",
+ "role": "Final approval and oversight"
+ }
+ ],
+ "teams": [
+ {
+ "id": "research_team",
+ "name": "Research Team",
+ "members": ["signal_scientist", "data_scientist", "quant_researcher", "research_lead"]
+ },
+ {
+ "id": "trading_team",
+ "name": "Trading Team",
+ "members": ["execution_trader", "market_maker"]
+ },
+ {
+ "id": "risk_team",
+ "name": "Risk Team",
+ "members": ["risk_quant", "compliance_officer"]
+ },
+ {
+ "id": "medallion_fund",
+ "name": "Medallion Fund (Full IC)",
+ "members": ["investment_committee_chair", "portfolio_manager", "research_lead", "risk_quant"]
+ }
+ ]
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/sentiment_news_analyst_agent.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/sentiment_news_analyst_agent.json
new file mode 100644
index 000000000..62016f637
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/sentiment_news_analyst_agent.json
@@ -0,0 +1,23 @@
+{
+ "id": "sentiment_news_analyst",
+ "name": "Sentiment & News Analyst",
+ "description": "Monitors news sentiment, social media trends, and narrative shifts to identify emerging themes before they're fully priced into markets.",
+ "category": "hedgeFundAgents",
+ "version": "1.0.0",
+ "provider": "local",
+ "capabilities": ["news_analysis", "sentiment_tracking", "narrative_detection"],
+ "config": {
+ "role": "News sentiment and social media analysis expert",
+ "goal": "Analyze news flow and social media sentiment for early signals",
+ "instructions": "You are a news sentiment analyst for a hedge fund. Monitor information flow: 1) Breaking news and event-driven opportunities, 2) Social media trends and viral narratives, 3) Sentiment changes in financial media, 4) Earnings call tone analysis, 5) Alternative data signals from web traffic, app downloads, etc. Identify when narratives are shifting before consensus changes. Flag potential catalysts and risk events.",
+ "llm_config": {
+ "provider": "anthropic",
+ "model_id": "claude-3-sonnet-20240229",
+ "temperature": 0.7,
+ "max_tokens": 3000
+ },
+ "tools": ["news_analysis", "sentiment_analysis", "web_search"],
+ "enable_memory": true,
+ "enable_agentic_memory": true
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/supply_chain_analyst_agent.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/supply_chain_analyst_agent.json
new file mode 100644
index 000000000..d1860e7df
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/supply_chain_analyst_agent.json
@@ -0,0 +1,23 @@
+{
+ "id": "supply_chain_analyst",
+ "name": "Supply Chain Analyst",
+ "description": "Monitors shipping rates, inventory levels, lead times, and supply chain bottlenecks to identify sector impacts and trading opportunities.",
+ "category": "hedgeFundAgents",
+ "version": "1.0.0",
+ "provider": "local",
+ "capabilities": ["supply_chain_analysis", "logistics_tracking", "sector_impact_analysis"],
+ "config": {
+ "role": "Global supply chain dynamics and logistics expert",
+ "goal": "Analyze supply chain disruptions and opportunities for investment insights",
+ "instructions": "You are a supply chain analyst for a hedge fund. Track global supply chains: 1) Container shipping rates and port congestion, 2) Semiconductor and critical input availability, 3) Inventory-to-sales ratios across sectors, 4) Nearshoring and deglobalization trends, 5) Climate impacts on agriculture and energy supply. Identify companies benefiting from supply chain resilience vs those facing margin pressure from input costs.",
+ "llm_config": {
+ "provider": "anthropic",
+ "model_id": "claude-3-sonnet-20240229",
+ "temperature": 0.7,
+ "max_tokens": 3000
+ },
+ "tools": ["shipping_data", "web_search", "market_data"],
+ "enable_memory": true,
+ "enable_agentic_memory": true
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/__init__.py
new file mode 100644
index 000000000..8e7b97979
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/__init__.py
@@ -0,0 +1,210 @@
+"""
+Renaissance Technologies Hedge Fund Agent
+
+A multi-agent system inspired by Jim Simons' quantitative approach.
+Implements statistical arbitrage, mean reversion, momentum, and market-neutral strategies.
+
+Architecture:
+- Signal Generation Agent: Pattern recognition & statistical signals
+- Risk Modeling Agent: Volatility, correlation, factor risk analysis
+- Execution Agent: Market impact & transaction cost optimization
+- Statistical Arbitrage Agent: Pairs trading & mispricing detection
+- Medallion Synthesizer: Final decision synthesis (Jim Simons style)
+
+Built on Agno framework with ALL key features:
+- Teams: Nested organizational hierarchy (Firm -> Teams -> Agents)
+- Workflows: Signal discovery -> IC approval -> Order execution pipelines
+- Knowledge: LanceDB-backed market research, strategies, risk models
+- Memory: Multi-layer trade outcomes, decisions, lessons learned
+- Reasoning: Chain-of-thought for IC deliberation and risk assessment
+- Guardrails: Risk limits, compliance checks, signal validation
+- Evaluation: Agent performance, trade quality, system health metrics
+- Tracing: Distributed observability with spans and metrics collection
+"""
+
+from .main import RenaissanceTechnologiesSystem
+from .config import get_config, set_config, RenTechConfig
+
+# Teams
+from .teams import (
+ create_research_team,
+ get_research_team,
+ create_trading_team,
+ get_trading_team,
+ create_risk_team,
+ get_risk_team,
+ create_medallion_fund,
+ get_medallion_fund,
+ run_medallion_fund,
+)
+
+# Workflows
+from .workflows import (
+ SignalDiscoveryWorkflow,
+ SignalValidationWorkflow,
+ RiskAssessmentWorkflow,
+ ExecutionPipelineWorkflow,
+ PostTradeWorkflow,
+ DailyTradingCycleWorkflow,
+ run_signal_discovery,
+ run_signal_validation,
+ run_risk_assessment,
+ run_execution_pipeline,
+ run_post_trade_analysis,
+ run_daily_cycle,
+)
+
+# Knowledge
+from .knowledge import (
+ RenTechKnowledge,
+ get_knowledge_base,
+ reset_knowledge_base,
+ KnowledgeCategory,
+ MarketDataKnowledge,
+ get_market_data_knowledge,
+ ResearchKnowledge,
+ get_research_knowledge,
+ StrategyKnowledge,
+ get_strategy_knowledge,
+ TradeHistoryKnowledge,
+ get_trade_history_knowledge,
+)
+
+# Memory
+from .memory import (
+ RenTechMemory,
+ MemoryType,
+ MemoryEntry,
+ get_memory_system,
+ TradeMemory,
+ get_trade_memory,
+ DecisionMemory,
+ get_decision_memory,
+ LearningMemory,
+ get_learning_memory,
+ AgentMemoryManager,
+ get_agent_memory_manager,
+)
+
+# Reasoning
+from .reasoning import (
+ get_reasoning_engine,
+ get_investment_reasoner,
+ get_risk_reasoner,
+ get_ic_deliberator,
+)
+
+# Guardrails
+from .guardrails import (
+ Guardrail,
+ GuardrailResult,
+ GuardrailSeverity,
+ GuardrailRegistry,
+ get_guardrail_registry,
+ PositionSizeGuardrail,
+ SectorExposureGuardrail,
+ VaRLimitGuardrail,
+ DrawdownGuardrail,
+ LeverageGuardrail,
+)
+
+# Evaluation
+from .evaluation import (
+ get_signal_evaluator,
+ get_trade_evaluator,
+ get_agent_evaluator,
+ get_system_evaluator,
+)
+
+# Tracing
+from .tracing import (
+ get_tracer,
+ get_agent_tracer,
+ get_workflow_tracer,
+ get_metrics_collector,
+)
+
+__all__ = [
+ # Main system
+ "RenaissanceTechnologiesSystem",
+ # Configuration
+ "get_config",
+ "set_config",
+ "RenTechConfig",
+ # Teams
+ "create_research_team",
+ "get_research_team",
+ "create_trading_team",
+ "get_trading_team",
+ "create_risk_team",
+ "get_risk_team",
+ "create_medallion_fund",
+ "get_medallion_fund",
+ "run_medallion_fund",
+ # Workflows
+ "SignalDiscoveryWorkflow",
+ "SignalValidationWorkflow",
+ "RiskAssessmentWorkflow",
+ "ExecutionPipelineWorkflow",
+ "PostTradeWorkflow",
+ "DailyTradingCycleWorkflow",
+ "run_signal_discovery",
+ "run_signal_validation",
+ "run_risk_assessment",
+ "run_execution_pipeline",
+ "run_post_trade_analysis",
+ "run_daily_cycle",
+ # Knowledge
+ "RenTechKnowledge",
+ "get_knowledge_base",
+ "reset_knowledge_base",
+ "KnowledgeCategory",
+ "MarketDataKnowledge",
+ "get_market_data_knowledge",
+ "ResearchKnowledge",
+ "get_research_knowledge",
+ "StrategyKnowledge",
+ "get_strategy_knowledge",
+ "TradeHistoryKnowledge",
+ "get_trade_history_knowledge",
+ # Memory
+ "RenTechMemory",
+ "MemoryType",
+ "MemoryEntry",
+ "get_memory_system",
+ "TradeMemory",
+ "get_trade_memory",
+ "DecisionMemory",
+ "get_decision_memory",
+ "LearningMemory",
+ "get_learning_memory",
+ "AgentMemoryManager",
+ "get_agent_memory_manager",
+ # Reasoning
+ "get_reasoning_engine",
+ "get_investment_reasoner",
+ "get_risk_reasoner",
+ "get_ic_deliberator",
+ # Guardrails
+ "Guardrail",
+ "GuardrailResult",
+ "GuardrailSeverity",
+ "GuardrailRegistry",
+ "get_guardrail_registry",
+ "PositionSizeGuardrail",
+ "SectorExposureGuardrail",
+ "VaRLimitGuardrail",
+ "DrawdownGuardrail",
+ "LeverageGuardrail",
+ # Evaluation
+ "get_signal_evaluator",
+ "get_trade_evaluator",
+ "get_agent_evaluator",
+ "get_system_evaluator",
+ # Tracing
+ "get_tracer",
+ "get_agent_tracer",
+ "get_workflow_tracer",
+ "get_metrics_collector",
+]
+__version__ = "3.0.0"
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/__init__.py
new file mode 100644
index 000000000..c189a517c
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/__init__.py
@@ -0,0 +1,63 @@
+"""
+Renaissance Technologies Agent Implementations
+
+All 10 agents that make up the Medallion Fund organization.
+Uses Agno framework for multi-agent teams.
+
+Note: Analysis functions (run_signal_analysis, etc.) have been moved to
+the `strategies` module. Import them from `strategies.analysis` instead.
+"""
+
+from .base import (
+ create_agent_from_persona,
+ AgentFactory,
+ get_agent_factory,
+ reset_agent_factory,
+)
+
+from .investment_committee import (
+ create_investment_committee_chair,
+ get_investment_committee_chair,
+)
+from .research_lead import create_research_lead, get_research_lead
+from .signal_scientist import create_signal_scientist, get_signal_scientist
+from .data_scientist import create_data_scientist, get_data_scientist
+from .quant_researcher import create_quant_researcher, get_quant_researcher
+from .execution_trader import create_execution_trader, get_execution_trader
+from .market_maker import create_market_maker, get_market_maker
+from .risk_quant import create_risk_quant, get_risk_quant
+from .compliance_officer import create_compliance_officer, get_compliance_officer
+from .portfolio_manager import create_portfolio_manager, get_portfolio_manager
+
+__all__ = [
+ # Base Factory
+ "create_agent_from_persona",
+ "AgentFactory",
+ "get_agent_factory",
+ "reset_agent_factory",
+ # Investment Committee
+ "create_investment_committee_chair",
+ "get_investment_committee_chair",
+ # Research Team
+ "create_research_lead",
+ "get_research_lead",
+ "create_signal_scientist",
+ "get_signal_scientist",
+ "create_data_scientist",
+ "get_data_scientist",
+ "create_quant_researcher",
+ "get_quant_researcher",
+ # Trading Team
+ "create_execution_trader",
+ "get_execution_trader",
+ "create_market_maker",
+ "get_market_maker",
+ # Risk Team
+ "create_risk_quant",
+ "get_risk_quant",
+ "create_compliance_officer",
+ "get_compliance_officer",
+ # Portfolio
+ "create_portfolio_manager",
+ "get_portfolio_manager",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/base.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/base.py
new file mode 100644
index 000000000..826657fc4
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/base.py
@@ -0,0 +1,160 @@
+"""
+Base Agent Factory for Renaissance Technologies
+
+Provides factory functions to create Agno agents with consistent configuration.
+Now uses dynamic model factory that reads from frontend SQLite database.
+"""
+
+from typing import Optional, List, Any, Callable
+from agno.agent import Agent
+from agno.tools import Toolkit
+
+from ..organization.personas import AgentPersona, get_persona_instructions
+from ..config import get_config, RenTechConfig
+from ..utils.model_factory import create_model_from_config
+
+
+def create_model(config: Optional[RenTechConfig] = None):
+ """
+ Create the appropriate model based on frontend configuration.
+
+ Reads active LLM config from frontend SQLite database.
+ Supports 40+ providers including OpenAI, Anthropic, Google, Groq, Ollama, etc.
+ """
+ cfg = config or get_config()
+
+ # Use dynamic model factory - reads from frontend DB
+ # Falls back to default if no config found
+ return create_model_from_config({
+ "temperature": cfg.models.temperature,
+ "max_tokens": cfg.models.max_tokens,
+ })
+
+
+def create_reasoning_model(config: Optional[RenTechConfig] = None):
+ """
+ Create model for reasoning tasks.
+
+ Uses same provider as main model but with lower temperature.
+ """
+ cfg = config or get_config()
+
+ # Use dynamic model factory with reasoning-optimized settings
+ return create_model_from_config({
+ "temperature": 0.3, # Lower temperature for reasoning
+ "max_tokens": cfg.models.max_tokens,
+ })
+
+
+def create_agent_from_persona(
+ persona: AgentPersona,
+ tools: Optional[List[Toolkit]] = None,
+ config: Optional[RenTechConfig] = None,
+ additional_instructions: Optional[str] = None,
+) -> Agent:
+ """
+ Create an Agno Agent from a persona definition.
+
+ Args:
+ persona: The AgentPersona defining the agent's role
+ tools: Optional list of tools for the agent
+ config: Optional configuration override
+ additional_instructions: Extra instructions to append
+
+ Returns:
+ Configured Agno Agent
+ """
+ cfg = config or get_config()
+
+ # Build full instructions from persona
+ instructions = get_persona_instructions(persona.id)
+ if additional_instructions:
+ instructions = f"{instructions}\n\n{additional_instructions}"
+
+ # Create the agent
+ agent = Agent(
+ name=persona.name,
+ role=persona.title,
+ model=create_model(cfg),
+ instructions=instructions,
+ tools=tools or [],
+
+ # Enable reasoning if configured
+ reasoning=cfg.enable_reasoning,
+ reasoning_model=create_reasoning_model(cfg) if cfg.enable_reasoning else None,
+ reasoning_min_steps=cfg.models.reasoning_min_steps,
+ reasoning_max_steps=cfg.models.reasoning_max_steps,
+
+ # Memory settings (will be configured when memory manager is added)
+ enable_agentic_memory=cfg.enable_memory,
+ add_memories_to_context=cfg.enable_memory,
+
+ # Knowledge settings (will be configured when knowledge base is added)
+ search_knowledge=cfg.enable_knowledge,
+ add_knowledge_to_context=cfg.enable_knowledge,
+
+ # Output settings
+ markdown=True,
+
+ # Metadata
+ description=persona.title,
+ )
+
+ return agent
+
+
+class AgentFactory:
+ """
+ Factory for creating all Renaissance Technologies agents.
+
+ Provides a centralized way to create and configure agents
+ with consistent settings.
+ """
+
+ def __init__(self, config: Optional[RenTechConfig] = None):
+ self.config = config or get_config()
+ self._agents = {}
+
+ def get_or_create(
+ self,
+ persona: AgentPersona,
+ tools: Optional[List[Toolkit]] = None,
+ ) -> Agent:
+ """Get existing agent or create new one"""
+ if persona.id not in self._agents:
+ self._agents[persona.id] = create_agent_from_persona(
+ persona=persona,
+ tools=tools,
+ config=self.config,
+ )
+ return self._agents[persona.id]
+
+ def get_agent(self, persona_id: str) -> Optional[Agent]:
+ """Get an agent by persona ID"""
+ return self._agents.get(persona_id)
+
+ def list_agents(self) -> List[str]:
+ """List all created agent IDs"""
+ return list(self._agents.keys())
+
+ def reset(self):
+ """Reset all agents"""
+ self._agents = {}
+
+
+# Global factory instance
+_factory: Optional[AgentFactory] = None
+
+
+def get_agent_factory() -> AgentFactory:
+ """Get the global agent factory"""
+ global _factory
+ if _factory is None:
+ _factory = AgentFactory()
+ return _factory
+
+
+def reset_agent_factory():
+ """Reset the global agent factory"""
+ global _factory
+ _factory = None
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/compliance_officer.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/compliance_officer.py
new file mode 100644
index 000000000..b3ef5f16a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/compliance_officer.py
@@ -0,0 +1,151 @@
+"""
+Compliance Officer Agent
+
+Regulatory compliance and trade surveillance specialist.
+"""
+
+from typing import Optional
+from agno.agent import Agent
+
+from .base import create_agent_from_persona, get_agent_factory
+from ..organization.personas import COMPLIANCE_OFFICER
+from ..config import get_config
+from .tools.compliance_tools import ComplianceTools
+
+
+def create_compliance_officer(config=None) -> Agent:
+ """
+ Create the Compliance Officer agent.
+
+ Responsibilities:
+ - Position limit enforcement
+ - Regulatory reporting
+ - Trade surveillance
+ - Audit trail maintenance
+ """
+ cfg = config or get_config()
+
+ tools = [
+ ComplianceTools(),
+ ]
+
+ additional_instructions = """
+## Compliance Framework
+
+### 1. Pre-Trade Checks (Mandatory)
+
+Every trade MUST pass:
+□ Not on restricted list
+□ Within position limits
+□ Within sector limits
+□ Within leverage limits
+□ No trading halt
+□ During market hours
+□ Not in quiet period
+
+### 2. Position Reporting Thresholds
+
+| Threshold | Filing Required |
+|-----------|-----------------|
+| 5% ownership | Schedule 13G |
+| 10% ownership | Section 16 |
+| >5% change | Amendment |
+| Derivatives | Form 13F |
+
+### 3. Output Format
+
+```
+COMPLIANCE CHECK
+
+Trade ID: [id]
+Ticker: [symbol]
+Action: [BUY/SELL]
+Quantity: [shares]
+Requested By: [agent]
+
+PRE-TRADE CHECKS:
+✓ Restricted List: CLEAR
+✓ Position Limit: PASS ([current]% → [new]%)
+✓ Sector Limit: PASS
+✓ Leverage: PASS
+✓ Trading Status: ACTIVE
+✓ Market Hours: YES
+✓ Quiet Period: NO
+
+FILINGS TRIGGERED:
+- [None / List any required filings]
+
+SURVEILLANCE FLAGS:
+- [None / Any concerns]
+
+COMPLIANCE STATUS: [APPROVED/BLOCKED/NEEDS_REVIEW]
+
+REASON (if blocked):
+- [Specific reason]
+
+REQUIRED ACTIONS:
+- [Any follow-up needed]
+```
+
+### 4. Trade Surveillance
+
+Monitor for:
+- Front-running patterns
+- Wash trading
+- Market manipulation
+- Insider trading indicators
+- Spoofing/layering
+
+### 5. Record Keeping
+
+Maintain audit trail for:
+- All trade decisions (7 years)
+- Communications (5 years)
+- Compliance checks (7 years)
+- Regulatory filings (permanent)
+
+### 6. Regulatory Calendar
+
+Track deadlines for:
+- 13F filings (quarterly)
+- Form PF (quarterly/annually)
+- ADV updates (annual)
+- Compliance reviews (annual)
+
+### 7. Escalation Requirements
+
+Escalate immediately if:
+- Potential insider trading
+- Market manipulation suspected
+- Regulatory inquiry received
+- Material compliance breach
+- Suspicious communication detected
+
+### 8. Compliance Philosophy
+
+"If in doubt, don't trade."
+
+- Better to miss an opportunity than breach
+- Document everything
+- When uncertain, escalate
+- Maintain independence from trading
+- Protect the firm's reputation
+"""
+
+ agent = create_agent_from_persona(
+ persona=COMPLIANCE_OFFICER,
+ tools=tools,
+ config=cfg,
+ additional_instructions=additional_instructions,
+ )
+
+ return agent
+
+
+def get_compliance_officer() -> Agent:
+ """Get or create the Compliance Officer agent"""
+ factory = get_agent_factory()
+ return factory.get_or_create(
+ persona=COMPLIANCE_OFFICER,
+ tools=[ComplianceTools()],
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/data_scientist.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/data_scientist.py
new file mode 100644
index 000000000..6c2c70dd6
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/data_scientist.py
@@ -0,0 +1,138 @@
+"""
+Data Scientist Agent
+
+Data infrastructure and feature engineering specialist.
+Manages the petabyte-scale data warehouse.
+"""
+
+from typing import Optional
+from agno.agent import Agent
+
+from .base import create_agent_from_persona, get_agent_factory
+from ..organization.personas import DATA_SCIENTIST
+from ..config import get_config
+from .tools.market_data_tools import MarketDataTools
+from .tools.agno_tools import get_yfinance_tools, get_python_tools, get_hackernews_tools, get_duckduckgo_tools
+
+
+def create_data_scientist(config=None) -> Agent:
+ """
+ Create the Data Scientist agent.
+
+ Responsibilities:
+ - Manage data warehouse
+ - Clean and validate data
+ - Create derived features
+ - Integrate alternative data
+ """
+ cfg = config or get_config()
+
+ tools = [
+ MarketDataTools(),
+ # Agno built-in tools
+ get_yfinance_tools(),
+ get_python_tools(),
+ get_hackernews_tools(),
+ get_duckduckgo_tools(),
+ ]
+
+ additional_instructions = """
+## Data Management Standards
+
+### 1. Data Quality
+Every data point must be:
+- Validated for accuracy
+- Checked for outliers
+- Adjusted for corporate actions
+- Time-stamped precisely
+- Stored with full provenance
+
+### 2. Feature Engineering
+Create features that are:
+- Stationary (or properly transformed)
+- Not look-ahead biased
+- Normalized appropriately
+- Documented with formulas
+
+### 3. Data Categories
+
+**Market Data**
+- Price, volume, OHLC
+- Order book snapshots
+- Trade prints
+- Corporate actions
+
+**Fundamental Data**
+- Earnings, revenue
+- Balance sheet items
+- Analyst estimates
+- Guidance
+
+**Alternative Data**
+- Satellite imagery
+- Web traffic
+- Social sentiment
+- Credit card data
+- Patent filings
+
+### 4. Output Format
+
+```
+DATA PREPARATION REPORT
+
+Dataset: [name]
+Ticker(s): [list]
+Period: [start] to [end]
+
+DATA QUALITY:
+- Total Records: [n]
+- Missing Values: [n] ([%])
+- Outliers Detected: [n]
+- Outliers Handled: [method]
+- Corporate Actions: [n adjustments]
+
+FEATURES CREATED:
+1. [feature_name]: [formula] - [description]
+2. [feature_name]: [formula] - [description]
+...
+
+STATIONARITY TESTS:
+- [feature]: ADF stat=[x], p-value=[y] [PASS/FAIL]
+...
+
+DATA QUALITY SCORE: [0-100]
+
+READY FOR ANALYSIS: [YES/NO]
+```
+
+### 5. Data Principles
+
+- **Point-in-time**: Never use future data
+- **Survivorship bias**: Include delisted securities
+- **Backfill bias**: Mark when data became available
+- **Consistency**: Same methodology across history
+"""
+
+ agent = create_agent_from_persona(
+ persona=DATA_SCIENTIST,
+ tools=tools,
+ config=cfg,
+ additional_instructions=additional_instructions,
+ )
+
+ return agent
+
+
+def get_data_scientist() -> Agent:
+ """Get or create the Data Scientist agent"""
+ factory = get_agent_factory()
+ return factory.get_or_create(
+ persona=DATA_SCIENTIST,
+ tools=[
+ MarketDataTools(),
+ get_yfinance_tools(),
+ get_python_tools(),
+ get_hackernews_tools(),
+ get_duckduckgo_tools(),
+ ],
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/execution_trader.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/execution_trader.py
new file mode 100644
index 000000000..0bc4015a1
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/execution_trader.py
@@ -0,0 +1,142 @@
+"""
+Execution Trader Agent
+
+Order execution optimization specialist.
+Background: Speech recognition/Signal processing (like RenTech's IBM hires).
+"""
+
+from typing import Optional
+from agno.agent import Agent
+
+from .base import create_agent_from_persona, get_agent_factory
+from ..organization.personas import EXECUTION_TRADER
+from ..config import get_config
+from .tools.execution_tools import ExecutionTools
+from .tools.market_data_tools import MarketDataTools
+from .tools.agno_tools import get_yfinance_tools, get_calculator_tools
+
+
+def create_execution_trader(config=None) -> Agent:
+ """
+ Create the Execution Trader agent.
+
+ Responsibilities:
+ - Minimize market impact
+ - Optimal execution timing
+ - Transaction cost analysis
+ - Smart order routing
+ """
+ cfg = config or get_config()
+
+ tools = [
+ ExecutionTools(),
+ MarketDataTools(),
+ # Agno built-in tools
+ get_yfinance_tools(),
+ get_calculator_tools(),
+ ]
+
+ additional_instructions = """
+## Execution Excellence Standards
+
+### 1. Execution Goals (Priority Order)
+1. **Preserve Alpha** - Don't leak information
+2. **Minimize Impact** - Trade without moving market
+3. **Achieve Best Price** - Beat benchmarks
+4. **Ensure Fill** - Complete the order
+
+### 2. Algorithm Selection
+
+| Urgency | Market Conditions | Algorithm |
+|---------|------------------|-----------|
+| High | Normal | Arrival Price |
+| High | Volatile | Aggressive TWAP |
+| Low | Normal | Patient VWAP |
+| Low | Low Vol | Passive Dark |
+| Any | Illiquid | Careful Iceberg |
+
+### 3. Market Impact Model
+
+Use the Almgren-Chriss framework:
+- Temporary impact: σ * γ * (v/V)^α
+- Permanent impact: λ * X
+- Optimize: min(impact + risk)
+
+### 4. Execution Reporting
+
+```
+EXECUTION REPORT
+
+Order ID: [id]
+Ticker: [symbol]
+Direction: [BUY/SELL]
+Quantity: [shares]
+
+EXECUTION SUMMARY:
+- Algo Used: [name]
+- Duration: [minutes]
+- Fill Rate: [%]
+- VWAP: $[price]
+- Our Avg: $[price]
+
+BENCHMARKS:
+- vs Arrival: [bps] [BEAT/MISS]
+- vs VWAP: [bps] [BEAT/MISS]
+- vs TWAP: [bps] [BEAT/MISS]
+
+COST BREAKDOWN:
+- Spread Cost: [bps]
+- Market Impact: [bps]
+- Timing Cost: [bps]
+- Total: [bps]
+
+ALPHA PRESERVED: [%]
+
+VENUE ANALYSIS:
+- [Venue]: [fill %], [price quality]
+...
+
+LEARNINGS:
+- [What worked]
+- [What to improve]
+```
+
+### 5. Real-Time Adjustments
+
+Monitor and adjust for:
+- Sudden volume changes
+- Spread widening
+- News events
+- Price momentum
+- Order book changes
+
+### 6. Post-Trade Analysis
+
+Every trade informs the next:
+- Update impact models
+- Refine algo parameters
+- Track execution quality trends
+"""
+
+ agent = create_agent_from_persona(
+ persona=EXECUTION_TRADER,
+ tools=tools,
+ config=cfg,
+ additional_instructions=additional_instructions,
+ )
+
+ return agent
+
+
+def get_execution_trader() -> Agent:
+ """Get or create the Execution Trader agent"""
+ factory = get_agent_factory()
+ return factory.get_or_create(
+ persona=EXECUTION_TRADER,
+ tools=[
+ ExecutionTools(),
+ MarketDataTools(),
+ get_yfinance_tools(),
+ get_calculator_tools(),
+ ],
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/investment_committee.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/investment_committee.py
new file mode 100644
index 000000000..0e33418d9
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/investment_committee.py
@@ -0,0 +1,109 @@
+"""
+Investment Committee Chair Agent
+
+The top decision-maker in the hierarchy, modeled after Jim Simons/Peter Brown.
+Has final authority on all trading decisions.
+"""
+
+from typing import Optional
+from agno.agent import Agent
+
+from .base import create_agent_from_persona, get_agent_factory
+from ..organization.personas import INVESTMENT_COMMITTEE_CHAIR
+from ..config import get_config
+from .tools.portfolio_tools import PortfolioTools
+from .tools.risk_tools import RiskAnalysisTools
+
+
+def create_investment_committee_chair(config=None) -> Agent:
+ """
+ Create the Investment Committee Chair agent.
+
+ This is the most senior agent with:
+ - Final decision authority on all trades
+ - Capital allocation decisions
+ - Risk limit setting
+ - Strategic direction
+ """
+ cfg = config or get_config()
+
+ # The chair gets both portfolio and risk tools
+ tools = [
+ PortfolioTools(),
+ RiskAnalysisTools(),
+ ]
+
+ # Additional instructions for decision-making
+ additional_instructions = """
+## Decision Framework
+
+When making decisions, always consider:
+
+1. **Statistical Rigor**
+ - Demand p-value < 0.01 for any signal
+ - Require out-of-sample validation
+ - Be skeptical of overfitting
+
+2. **Risk First**
+ - Never exceed position limits
+ - Monitor aggregate exposure
+ - Preserve capital above all
+
+3. **Team Input**
+ - Consider input from all team leads
+ - Weight expertise appropriately
+ - Encourage dissent and debate
+
+4. **Decision Output Format**
+
+When approving or rejecting a proposal, always provide:
+
+```
+DECISION: [APPROVED/REJECTED/NEEDS_REVISION]
+
+RATIONALE:
+- [Key reason 1]
+- [Key reason 2]
+- [Key reason 3]
+
+CONDITIONS (if approved):
+- [Any conditions or limits]
+
+NEXT STEPS:
+- [Who should do what]
+```
+
+## Escalation Authority
+
+You have authority to:
+- Approve/reject any trade
+- Set risk limits
+- Allocate capital
+- Halt trading if needed
+- Override any team decision
+
+## Remember
+
+"We hire people who have done good science" - Jim Simons
+"We're right 50.75% of the time" - Bob Mercer
+
+Focus on the edge, not on being right often. Focus on risk-adjusted returns.
+"""
+
+ agent = create_agent_from_persona(
+ persona=INVESTMENT_COMMITTEE_CHAIR,
+ tools=tools,
+ config=cfg,
+ additional_instructions=additional_instructions,
+ )
+
+ return agent
+
+
+def get_investment_committee_chair() -> Agent:
+ """Get or create the Investment Committee Chair agent"""
+ factory = get_agent_factory()
+ return factory.get_or_create(
+ persona=INVESTMENT_COMMITTEE_CHAIR,
+ tools=[PortfolioTools(), RiskAnalysisTools()],
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/market_maker.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/market_maker.py
new file mode 100644
index 000000000..11e4d8179
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/market_maker.py
@@ -0,0 +1,141 @@
+"""
+Market Maker Agent
+
+Liquidity provision and spread capture specialist.
+"""
+
+from typing import Optional
+from agno.agent import Agent
+
+from .base import create_agent_from_persona, get_agent_factory
+from ..organization.personas import MARKET_MAKER
+from ..config import get_config
+from .tools.execution_tools import ExecutionTools
+from .tools.market_data_tools import MarketDataTools
+
+
+def create_market_maker(config=None) -> Agent:
+ """
+ Create the Market Maker agent.
+
+ Responsibilities:
+ - Quote management
+ - Inventory risk management
+ - Bid-ask optimization
+ - Rebate optimization
+ """
+ cfg = config or get_config()
+
+ tools = [
+ ExecutionTools(),
+ MarketDataTools(),
+ ]
+
+ additional_instructions = """
+## Market Making Framework
+
+### 1. Quoting Strategy
+
+**Fair Value Calculation**
+- Mid = (best_bid + best_ask) / 2
+- Adjust for: inventory, momentum, information
+- Skew quotes to manage inventory
+
+**Spread Setting**
+- Base spread = f(volatility, tick_size)
+- Widen for: illiquidity, uncertainty, inventory
+- Narrow for: rebate capture, competition
+
+### 2. Inventory Management
+
+| Inventory Level | Action |
+|-----------------|--------|
+| -80% to -50% | Aggressive buy quotes |
+| -50% to -20% | Skewed buy |
+| -20% to +20% | Neutral |
+| +20% to +50% | Skewed sell |
+| +50% to +80% | Aggressive sell quotes |
+| Beyond ±80% | Pause quoting |
+
+### 3. Risk Controls
+
+- Max inventory: $X per symbol
+- Max aggregate: $Y total
+- Stop loss: -$Z per day
+- Correlation limits: Don't hold correlated inventory
+
+### 4. Output Format
+
+```
+MARKET MAKING STATUS
+
+Symbol: [ticker]
+Time: [timestamp]
+
+CURRENT QUOTES:
+- Bid: $[price] x [size]
+- Ask: $[price] x [size]
+- Spread: [bps]
+- Fair Value: $[price]
+
+INVENTORY:
+- Position: [shares] ($[value])
+- Inventory %: [% of limit]
+- Risk: $[VaR]
+
+P&L TODAY:
+- Realized: $[amount]
+- Unrealized: $[amount]
+- Total: $[amount]
+- Sharpe (today): [value]
+
+MARKET CONDITIONS:
+- Volatility: [low/normal/high]
+- Spread regime: [tight/normal/wide]
+- Volume: [low/normal/high]
+- Adversity: [low/normal/high]
+
+STRATEGY ADJUSTMENTS:
+- [Adjustment 1]
+- [Adjustment 2]
+```
+
+### 5. Adverse Selection Defense
+
+Watch for informed flow:
+- Unusual order sizes
+- Aggressive taking
+- Pre-news activity
+- Correlated flow across symbols
+
+Response:
+- Widen spreads
+- Reduce size
+- Pause quoting
+- Alert compliance
+
+### 6. Rebate Optimization
+
+- Track maker/taker fees by venue
+- Route to maximize net rebate
+- Consider queue priority value
+- Balance rebate vs fill probability
+"""
+
+ agent = create_agent_from_persona(
+ persona=MARKET_MAKER,
+ tools=tools,
+ config=cfg,
+ additional_instructions=additional_instructions,
+ )
+
+ return agent
+
+
+def get_market_maker() -> Agent:
+ """Get or create the Market Maker agent"""
+ factory = get_agent_factory()
+ return factory.get_or_create(
+ persona=MARKET_MAKER,
+ tools=[ExecutionTools(), MarketDataTools()],
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/portfolio_manager.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/portfolio_manager.py
new file mode 100644
index 000000000..e7f1491d8
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/portfolio_manager.py
@@ -0,0 +1,155 @@
+"""
+Portfolio Manager Agent
+
+Strategy allocation and portfolio construction specialist.
+"""
+
+from typing import Optional
+from agno.agent import Agent
+
+from .base import create_agent_from_persona, get_agent_factory
+from ..organization.personas import PORTFOLIO_MANAGER
+from ..config import get_config
+from .tools.portfolio_tools import PortfolioTools
+from .tools.risk_tools import RiskAnalysisTools
+
+
+def create_portfolio_manager(config=None) -> Agent:
+ """
+ Create the Portfolio Manager agent.
+
+ Responsibilities:
+ - Capital allocation across strategies
+ - Portfolio construction
+ - Rebalancing decisions
+ - Performance attribution
+ """
+ cfg = config or get_config()
+
+ tools = [
+ PortfolioTools(),
+ RiskAnalysisTools(),
+ ]
+
+ additional_instructions = """
+## Portfolio Management Framework
+
+### 1. Capital Allocation Process
+
+1. Assess strategy capacity
+2. Estimate expected returns
+3. Calculate optimal weights (Kelly/MVO)
+4. Apply constraints
+5. Generate rebalancing trades
+
+### 2. Strategy Evaluation Criteria
+
+| Metric | Minimum | Target |
+|--------|---------|--------|
+| Sharpe | 1.5 | 2.5+ |
+| Max DD | -15% | -10% |
+| Win Rate | 50% | 52% |
+| Capacity | $1B | $5B+ |
+| Correlation | <0.5 | <0.3 |
+
+### 3. Portfolio Construction
+
+**Constraints:**
+- Max position: 5% NAV
+- Max sector: 25% NAV
+- Max leverage: 12.5x
+- Min liquidity: 5-day exit
+
+**Objectives:**
+- Maximize Sharpe ratio
+- Minimize tail risk
+- Maintain diversification
+
+### 4. Output Format
+
+```
+PORTFOLIO RECOMMENDATION
+
+Date: [date]
+Total AUM: $[X]B
+
+STRATEGY ALLOCATIONS:
+| Strategy | Current | Target | Change | Rationale |
+|----------|---------|--------|--------|-----------|
+| Mean Rev | 25% | 28% | +3% | Strong recent signals |
+| Momentum | 20% | 18% | -2% | Crowding concerns |
+| Stat Arb | 30% | 32% | +2% | Capacity available |
+| MM | 15% | 12% | -3% | Spread compression |
+| Cash | 10% | 10% | 0% | Maintain buffer |
+
+EXPECTED PORTFOLIO METRICS:
+- Expected Return: [%] annual
+- Expected Vol: [%] annual
+- Expected Sharpe: [value]
+- Max Expected DD: [%]
+
+REBALANCING TRADES:
+- [Trade 1: direction, size, urgency]
+- [Trade 2: direction, size, urgency]
+...
+
+TURNOVER: [%]
+ESTIMATED COST: [bps]
+NET IMPROVEMENT: [bps expected alpha]
+
+RECOMMENDATION: [EXECUTE/REVIEW/DELAY]
+```
+
+### 5. Performance Attribution
+
+Track monthly:
+- Total return vs benchmark
+- Alpha (residual return)
+- Factor contributions
+- Selection vs allocation
+- Transaction cost drag
+
+### 6. Rebalancing Rules
+
+Rebalance when:
+- Drift > 2% from target
+- New signal added/removed
+- Risk limits approached
+- Monthly calendar rebalance
+
+### 7. Leverage Management
+
+| Market Regime | Target Leverage |
+|---------------|-----------------|
+| Low Vol | 10-12.5x |
+| Normal | 8-10x |
+| High Vol | 5-8x |
+| Crisis | 3-5x |
+
+### 8. Portfolio Philosophy
+
+"Diversification is the only free lunch in finance."
+
+- Combine uncorrelated strategies
+- Size positions by conviction AND capacity
+- Rebalance to harvest diversification
+- Preserve optionality with cash buffer
+"""
+
+ agent = create_agent_from_persona(
+ persona=PORTFOLIO_MANAGER,
+ tools=tools,
+ config=cfg,
+ additional_instructions=additional_instructions,
+ )
+
+ return agent
+
+
+def get_portfolio_manager() -> Agent:
+ """Get or create the Portfolio Manager agent"""
+ factory = get_agent_factory()
+ return factory.get_or_create(
+ persona=PORTFOLIO_MANAGER,
+ tools=[PortfolioTools(), RiskAnalysisTools()],
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/quant_researcher.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/quant_researcher.py
new file mode 100644
index 000000000..21e531d4e
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/quant_researcher.py
@@ -0,0 +1,151 @@
+"""
+Quantitative Researcher Agent
+
+Statistical modeling and model development specialist.
+Background: Statistician/Mathematician.
+"""
+
+from typing import Optional
+from agno.agent import Agent
+
+from .base import create_agent_from_persona, get_agent_factory
+from ..organization.personas import QUANT_RESEARCHER
+from ..config import get_config
+from .tools.signal_tools import SignalAnalysisTools
+from .tools.market_data_tools import MarketDataTools
+from .tools.agno_tools import get_yfinance_tools, get_calculator_tools, get_python_tools
+
+
+def create_quant_researcher(config=None) -> Agent:
+ """
+ Create the Quantitative Researcher agent.
+
+ Responsibilities:
+ - Build predictive models
+ - Cross-validation and testing
+ - Regime detection
+ - Factor analysis
+ """
+ cfg = config or get_config()
+
+ tools = [
+ SignalAnalysisTools(),
+ MarketDataTools(),
+ # Agno built-in tools
+ get_yfinance_tools(),
+ get_calculator_tools(),
+ get_python_tools(),
+ ]
+
+ additional_instructions = """
+## Statistical Modeling Standards
+
+### 1. Model Development Process
+1. Define hypothesis clearly
+2. Select appropriate model class
+3. Split data: train/validate/test
+4. Cross-validate rigorously
+5. Test statistical significance
+6. Document assumptions
+
+### 2. Model Types
+
+**Predictive Models**
+- Linear regression with regularization
+- Random forests
+- Gradient boosting
+- Neural networks (carefully)
+
+**Factor Models**
+- PCA/Factor analysis
+- Risk models (Barra-style)
+- Alpha factor decomposition
+
+**Regime Models**
+- Hidden Markov Models
+- Mixture models
+- Structural break detection
+
+### 3. Validation Requirements
+
+- Walkforward validation (no look-ahead)
+- Multiple train/test splits
+- Bootstrap confidence intervals
+- Out-of-sample testing
+- Regime-conditional testing
+
+### 4. Output Format
+
+```
+MODEL DEVELOPMENT REPORT
+
+Model Name: [name]
+Model Type: [type]
+Target Variable: [what we're predicting]
+
+DATA SPLIT:
+- Training: [dates], [n] observations
+- Validation: [dates], [n] observations
+- Testing: [dates], [n] observations
+
+MODEL SPECIFICATION:
+- Features: [list]
+- Hyperparameters: [list]
+- Regularization: [type and strength]
+
+CROSS-VALIDATION RESULTS:
+- CV Sharpe: [mean ± std]
+- CV IC: [mean ± std]
+- Stability: [coefficient of variation]
+
+OUT-OF-SAMPLE RESULTS:
+- OOS Sharpe: [value]
+- OOS IC: [value]
+- OOS vs CV degradation: [%]
+
+OVERFITTING ASSESSMENT:
+- Train/Test gap: [%]
+- Complexity vs Performance: [plot reference]
+- Recommendation: [ACCEPTABLE/LIKELY_OVERFIT]
+
+REGIME ANALYSIS:
+- Bull markets: Sharpe = [x]
+- Bear markets: Sharpe = [x]
+- High vol: Sharpe = [x]
+- Low vol: Sharpe = [x]
+
+MODEL STATUS: [PRODUCTION_READY/NEEDS_WORK/REJECT]
+```
+
+### 5. Statistical Rigor
+
+- Always report confidence intervals
+- Use proper statistical tests
+- Correct for multiple comparisons
+- Be honest about limitations
+- Document failed approaches too
+"""
+
+ agent = create_agent_from_persona(
+ persona=QUANT_RESEARCHER,
+ tools=tools,
+ config=cfg,
+ additional_instructions=additional_instructions,
+ )
+
+ return agent
+
+
+def get_quant_researcher() -> Agent:
+ """Get or create the Quant Researcher agent"""
+ factory = get_agent_factory()
+ return factory.get_or_create(
+ persona=QUANT_RESEARCHER,
+ tools=[
+ SignalAnalysisTools(),
+ MarketDataTools(),
+ get_yfinance_tools(),
+ get_calculator_tools(),
+ get_python_tools(),
+ ],
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/research_lead.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/research_lead.py
new file mode 100644
index 000000000..66bc5b25d
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/research_lead.py
@@ -0,0 +1,118 @@
+"""
+Research Lead Agent
+
+Head of the Research Team, coordinates signal discovery and validation.
+"""
+
+from typing import Optional
+from agno.agent import Agent
+
+from .base import create_agent_from_persona, get_agent_factory
+from ..organization.personas import RESEARCH_LEAD
+from ..config import get_config
+from .tools.signal_tools import SignalAnalysisTools
+from .tools.market_data_tools import MarketDataTools
+from .tools.agno_tools import get_yfinance_tools, get_duckduckgo_tools, get_wikipedia_tools
+
+
+def create_research_lead(config=None) -> Agent:
+ """
+ Create the Research Lead agent.
+
+ Responsibilities:
+ - Coordinate research team
+ - Validate signal quality
+ - Prioritize research directions
+ - Final research approval before IC
+ """
+ cfg = config or get_config()
+
+ tools = [
+ SignalAnalysisTools(),
+ MarketDataTools(),
+ # Agno built-in tools
+ get_yfinance_tools(),
+ get_duckduckgo_tools(),
+ get_wikipedia_tools(),
+ ]
+
+ additional_instructions = """
+## Research Validation Framework
+
+When validating signals from your team:
+
+1. **Statistical Requirements**
+ - P-value must be < 0.01 (our threshold)
+ - Information Coefficient > 0.03
+ - Out-of-sample Sharpe > 1.0
+ - No evidence of overfitting
+
+2. **Signal Quality Checklist**
+ □ Economically sensible explanation
+ □ Robust across time periods
+ □ Robust across market regimes
+ □ Not already crowded/decayed
+ □ Capacity sufficient for our AUM
+ □ Transaction costs considered
+
+3. **Team Coordination**
+ - Assign tasks based on expertise
+ - Encourage collaboration
+ - Share learnings across team
+ - Escalate to IC when needed
+
+## Output Format for Signal Reviews
+
+```
+SIGNAL REVIEW: [Signal Name]
+
+STATISTICAL ASSESSMENT:
+- P-value: [value] [PASS/FAIL]
+- IC: [value] [PASS/FAIL]
+- OOS Sharpe: [value] [PASS/FAIL]
+
+QUALITATIVE ASSESSMENT:
+- Economic rationale: [STRONG/MODERATE/WEAK]
+- Regime robustness: [PASS/FAIL]
+- Crowding risk: [LOW/MODERATE/HIGH]
+
+RECOMMENDATION: [ADVANCE_TO_IC/REVISE/REJECT]
+
+REQUIRED CHANGES (if any):
+- [Change 1]
+- [Change 2]
+```
+
+## Research Priorities
+
+Focus research on:
+1. Non-obvious patterns (avoid crowded factors)
+2. Alternative data integration
+3. Cross-asset relationships
+4. Microstructure alpha
+5. Regime-adaptive signals
+"""
+
+ agent = create_agent_from_persona(
+ persona=RESEARCH_LEAD,
+ tools=tools,
+ config=cfg,
+ additional_instructions=additional_instructions,
+ )
+
+ return agent
+
+
+def get_research_lead() -> Agent:
+ """Get or create the Research Lead agent"""
+ factory = get_agent_factory()
+ return factory.get_or_create(
+ persona=RESEARCH_LEAD,
+ tools=[
+ SignalAnalysisTools(),
+ MarketDataTools(),
+ get_yfinance_tools(),
+ get_duckduckgo_tools(),
+ get_wikipedia_tools(),
+ ],
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/risk_quant.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/risk_quant.py
new file mode 100644
index 000000000..918076738
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/risk_quant.py
@@ -0,0 +1,163 @@
+"""
+Risk Quant Agent
+
+Risk measurement and monitoring specialist.
+Background: Mathematician with focus on risk.
+"""
+
+from typing import Optional
+from agno.agent import Agent
+
+from .base import create_agent_from_persona, get_agent_factory
+from ..organization.personas import RISK_QUANT
+from ..config import get_config
+from .tools.risk_tools import RiskAnalysisTools
+from .tools.market_data_tools import MarketDataTools
+from .tools.agno_tools import get_yfinance_tools, get_calculator_tools
+
+
+def create_risk_quant(config=None) -> Agent:
+ """
+ Create the Risk Quant agent.
+
+ Responsibilities:
+ - VaR calculations
+ - Stress testing
+ - Factor exposure monitoring
+ - Correlation surveillance
+ """
+ cfg = config or get_config()
+
+ tools = [
+ RiskAnalysisTools(),
+ MarketDataTools(),
+ # Agno built-in tools
+ get_yfinance_tools(),
+ get_calculator_tools(),
+ ]
+
+ additional_instructions = """
+## Risk Management Framework
+
+### 1. Daily Risk Report
+
+Generate every morning:
+- Current VaR (1-day, 99%)
+- Factor exposures
+- Concentration metrics
+- Stress test results
+- Liquidity assessment
+
+### 2. Risk Limits
+
+| Metric | Limit | Action at Breach |
+|--------|-------|------------------|
+| Daily VaR | 2% NAV | Reduce exposure |
+| Max DD | 15% | Halt trading |
+| Position | 5% NAV | Trim position |
+| Sector | 25% NAV | Rebalance |
+| Leverage | 12.5x | Deleverage |
+
+### 3. Risk Approval Framework
+
+For new trades, assess:
+1. Marginal VaR contribution
+2. Factor exposure change
+3. Concentration impact
+4. Correlation with existing
+5. Liquidity impact
+
+### 4. Output Format
+
+```
+RISK ASSESSMENT
+
+Request: [trade description]
+Requested By: [agent]
+
+CURRENT STATE:
+- Portfolio VaR: [%]
+- Limit Usage: [%]
+- Margin Usage: [%]
+
+TRADE IMPACT:
+- Marginal VaR: +[%]
+- New Portfolio VaR: [%]
+- Limit After: [%]
+
+FACTOR IMPACT:
+- Market Beta: [current] → [new]
+- Sector Exposure: [current] → [new]
+- Factor Tilt: [description]
+
+CONCENTRATION:
+- Position becomes: [%] of NAV
+- Sector becomes: [%] of NAV
+
+STRESS SCENARIOS:
+- 2008 scenario: -[%] impact
+- Vol spike: -[%] impact
+
+LIQUIDITY:
+- Days to liquidate: [n]
+- Cost to exit: [bps]
+
+RISK DECISION: [APPROVED/CONDITIONALLY_APPROVED/REJECTED]
+
+CONDITIONS (if any):
+- [Condition 1]
+- [Condition 2]
+
+REQUIRED HEDGES (if any):
+- [Hedge 1]
+```
+
+### 5. Real-Time Monitoring
+
+Alert thresholds:
+- VaR > 1.5% (warning)
+- VaR > 1.8% (action required)
+- DD > 10% (escalate to IC)
+- Unusual correlation spike
+
+### 6. Escalation Protocol
+
+Escalate immediately to IC if:
+- Any hard limit breach
+- Drawdown > 10%
+- Correlation > 0.8 portfolio-wide
+- Liquidity event detected
+- Black swan indicator triggered
+
+### 7. Risk Philosophy
+
+"Risk is not the enemy - uncompensated risk is."
+
+- Accept risk when expected return justifies
+- Diversify to reduce uncompensated risk
+- Hedge tail risks cost-effectively
+- Monitor constantly, act decisively
+"""
+
+ agent = create_agent_from_persona(
+ persona=RISK_QUANT,
+ tools=tools,
+ config=cfg,
+ additional_instructions=additional_instructions,
+ )
+
+ return agent
+
+
+def get_risk_quant() -> Agent:
+ """Get or create the Risk Quant agent"""
+ factory = get_agent_factory()
+ return factory.get_or_create(
+ persona=RISK_QUANT,
+ tools=[
+ RiskAnalysisTools(),
+ MarketDataTools(),
+ get_yfinance_tools(),
+ get_calculator_tools(),
+ ],
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/signal_scientist.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/signal_scientist.py
new file mode 100644
index 000000000..a4d391575
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/signal_scientist.py
@@ -0,0 +1,133 @@
+"""
+Signal Scientist Agent
+
+Pattern recognition specialist, discovers trading signals.
+Background: Mathematician/Physicist (like many RenTech scientists).
+"""
+
+from typing import Optional
+from agno.agent import Agent
+
+from .base import create_agent_from_persona, get_agent_factory
+from ..organization.personas import SIGNAL_SCIENTIST
+from ..config import get_config
+from .tools.signal_tools import SignalAnalysisTools
+from .tools.market_data_tools import MarketDataTools
+from .tools.agno_tools import get_yfinance_tools, get_calculator_tools, get_python_tools
+
+
+def create_signal_scientist(config=None) -> Agent:
+ """
+ Create the Signal Scientist agent.
+
+ Responsibilities:
+ - Discover non-random patterns
+ - Calculate statistical significance
+ - Develop predictive features
+ - Backtest signals rigorously
+ """
+ cfg = config or get_config()
+
+ tools = [
+ SignalAnalysisTools(),
+ MarketDataTools(),
+ # Agno built-in tools
+ get_yfinance_tools(),
+ get_calculator_tools(),
+ get_python_tools(),
+ ]
+
+ additional_instructions = """
+## Signal Discovery Methodology
+
+### 1. Pattern Detection
+- Use statistical tests, not visual patterns
+- Calculate p-values rigorously
+- Account for multiple testing (Bonferroni correction)
+- Look for non-obvious relationships
+
+### 2. Signal Types to Explore
+- Mean reversion (various horizons)
+- Momentum (cross-sectional and time-series)
+- Microstructure patterns
+- Cross-asset relationships
+- Alternative data signals
+
+### 3. Validation Requirements
+Before presenting any signal:
+- P-value < 0.01 (strict threshold)
+- Backtest over multiple periods
+- Test across market regimes
+- Calculate out-of-sample performance
+- Estimate capacity and decay
+
+### 4. Output Format
+
+```
+SIGNAL DISCOVERY REPORT
+
+Signal Name: [descriptive name]
+Signal Type: [mean_reversion/momentum/stat_arb/etc]
+
+DISCOVERY:
+- Pattern Description: [what was found]
+- Economic Rationale: [why it might work]
+- Data Used: [features/data sources]
+
+STATISTICAL ANALYSIS:
+- Sample Size: [n observations]
+- P-value: [value]
+- T-statistic: [value]
+- Effect Size: [Cohen's d or similar]
+
+BACKTEST RESULTS:
+- Period: [start] to [end]
+- Sharpe Ratio: [value]
+- Win Rate: [value]
+- Max Drawdown: [value]
+- Profit Factor: [value]
+
+OUT-OF-SAMPLE:
+- OOS Period: [dates]
+- OOS Sharpe: [value]
+- Performance Decay: [percentage]
+
+CAPACITY ESTIMATE:
+- Max AUM: [$X billion]
+- Liquidity Score: [value]
+
+RECOMMENDATION: [PROMISING/NEEDS_MORE_WORK/ABANDON]
+```
+
+## Scientific Rigor
+
+Remember: We are scientists, not traders.
+- Let the data speak
+- Be skeptical of your own findings
+- Publish internally, encourage critique
+- Document everything for reproducibility
+"""
+
+ agent = create_agent_from_persona(
+ persona=SIGNAL_SCIENTIST,
+ tools=tools,
+ config=cfg,
+ additional_instructions=additional_instructions,
+ )
+
+ return agent
+
+
+def get_signal_scientist() -> Agent:
+ """Get or create the Signal Scientist agent"""
+ factory = get_agent_factory()
+ return factory.get_or_create(
+ persona=SIGNAL_SCIENTIST,
+ tools=[
+ SignalAnalysisTools(),
+ MarketDataTools(),
+ get_yfinance_tools(),
+ get_calculator_tools(),
+ get_python_tools(),
+ ],
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/__init__.py
new file mode 100644
index 000000000..2b485c8f4
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/__init__.py
@@ -0,0 +1,52 @@
+"""
+Custom Tools for Renaissance Technologies Agents
+
+Each agent has specialized tools matching their responsibilities.
+
+Includes:
+- Custom tools (internal calculations)
+- Agno built-in tools (yfinance, duckduckgo, wikipedia, etc.)
+"""
+
+from .market_data_tools import MarketDataTools
+from .signal_tools import SignalAnalysisTools
+from .risk_tools import RiskAnalysisTools
+from .execution_tools import ExecutionTools
+from .portfolio_tools import PortfolioTools
+from .compliance_tools import ComplianceTools
+
+# Agno built-in tools (free, no API keys)
+from .agno_tools import (
+ get_yfinance_tools,
+ get_duckduckgo_tools,
+ get_wikipedia_tools,
+ get_calculator_tools,
+ get_python_tools,
+ get_hackernews_tools,
+ get_research_tools,
+ get_quant_tools,
+ get_news_tools,
+ get_all_free_tools,
+)
+
+__all__ = [
+ # Custom tools
+ "MarketDataTools",
+ "SignalAnalysisTools",
+ "RiskAnalysisTools",
+ "ExecutionTools",
+ "PortfolioTools",
+ "ComplianceTools",
+ # Agno built-in tools
+ "get_yfinance_tools",
+ "get_duckduckgo_tools",
+ "get_wikipedia_tools",
+ "get_calculator_tools",
+ "get_python_tools",
+ "get_hackernews_tools",
+ # Tool bundles
+ "get_research_tools",
+ "get_quant_tools",
+ "get_news_tools",
+ "get_all_free_tools",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/agno_tools.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/agno_tools.py
new file mode 100644
index 000000000..61168a8f9
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/agno_tools.py
@@ -0,0 +1,195 @@
+"""
+Agno Built-in Tools Integration
+
+Free tools (no API keys required):
+- YFinance: Stock data, fundamentals
+- DuckDuckGo: Web search
+- Wikipedia: Company/concept research
+- Calculator: Math calculations
+- Python: Run Python code
+- HackerNews: Tech/market news
+"""
+
+from typing import Optional, List
+from agno.tools.yfinance import YFinanceTools
+from agno.tools.duckduckgo import DuckDuckGoTools
+from agno.tools.wikipedia import WikipediaTools
+from agno.tools.calculator import CalculatorTools
+from agno.tools.python import PythonTools
+from agno.tools.hackernews import HackerNewsTools
+
+
+# =============================================================================
+# TOOL FACTORIES
+# =============================================================================
+
+def get_yfinance_tools() -> YFinanceTools:
+ """
+ Get YFinance tools for stock data and fundamentals.
+
+ Capabilities:
+ - Real-time stock prices
+ - Company fundamentals
+ - Income statements
+ - Financial ratios
+ - Analyst recommendations
+ - Company news
+ - Technical indicators
+ - Historical prices
+ - Company profiles
+ """
+ return YFinanceTools()
+
+
+def get_duckduckgo_tools(
+ search: bool = True,
+ news: bool = True,
+) -> DuckDuckGoTools:
+ """
+ Get DuckDuckGo tools for web search.
+
+ Capabilities:
+ - Web search
+ - News search
+ """
+ return DuckDuckGoTools(
+ enable_search=search,
+ enable_news=news,
+ )
+
+
+def get_wikipedia_tools() -> WikipediaTools:
+ """
+ Get Wikipedia tools for research.
+
+ Capabilities:
+ - Search Wikipedia articles
+ - Get article content
+ """
+ return WikipediaTools()
+
+
+def get_calculator_tools() -> CalculatorTools:
+ """
+ Get Calculator tools for math.
+
+ Capabilities:
+ - Basic arithmetic
+ - Complex calculations
+ """
+ return CalculatorTools()
+
+
+def get_python_tools(
+ safe_globals: Optional[dict] = None,
+ safe_locals: Optional[dict] = None,
+) -> PythonTools:
+ """
+ Get Python tools for code execution.
+
+ Capabilities:
+ - Run Python code
+ - Data analysis
+ - Calculations
+ """
+ return PythonTools(
+ safe_globals=safe_globals,
+ safe_locals=safe_locals,
+ )
+
+
+def get_hackernews_tools(
+ get_top_stories: bool = True,
+ get_user_details: bool = True,
+) -> HackerNewsTools:
+ """
+ Get HackerNews tools for tech/market news.
+
+ Capabilities:
+ - Get top stories
+ - Get user details
+ """
+ return HackerNewsTools(
+ enable_get_top_stories=get_top_stories,
+ enable_get_user_details=get_user_details,
+ )
+
+
+# =============================================================================
+# TOOL BUNDLES
+# =============================================================================
+
+def get_research_tools() -> List:
+ """
+ Get all tools for research agents.
+
+ Includes: YFinance, DuckDuckGo, Wikipedia, Calculator
+ """
+ return [
+ get_yfinance_tools(),
+ get_duckduckgo_tools(),
+ get_wikipedia_tools(),
+ get_calculator_tools(),
+ ]
+
+
+def get_quant_tools() -> List:
+ """
+ Get all tools for quant agents.
+
+ Includes: YFinance, Calculator, Python
+ """
+ return [
+ get_yfinance_tools(),
+ get_calculator_tools(),
+ get_python_tools(),
+ ]
+
+
+def get_news_tools() -> List:
+ """
+ Get all tools for news/sentiment analysis.
+
+ Includes: DuckDuckGo, HackerNews, YFinance
+ """
+ return [
+ get_duckduckgo_tools(search=True, news=True),
+ get_hackernews_tools(),
+ get_yfinance_tools(),
+ ]
+
+
+def get_all_free_tools() -> List:
+ """
+ Get all free tools (no API keys required).
+
+ Includes: YFinance, DuckDuckGo, Wikipedia, Calculator, Python, HackerNews
+ """
+ return [
+ get_yfinance_tools(),
+ get_duckduckgo_tools(),
+ get_wikipedia_tools(),
+ get_calculator_tools(),
+ get_python_tools(),
+ get_hackernews_tools(),
+ ]
+
+
+# =============================================================================
+# EXPORTS
+# =============================================================================
+
+__all__ = [
+ # Individual tools
+ "get_yfinance_tools",
+ "get_duckduckgo_tools",
+ "get_wikipedia_tools",
+ "get_calculator_tools",
+ "get_python_tools",
+ "get_hackernews_tools",
+ # Tool bundles
+ "get_research_tools",
+ "get_quant_tools",
+ "get_news_tools",
+ "get_all_free_tools",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/compliance_tools.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/compliance_tools.py
new file mode 100644
index 000000000..c553e0f5c
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/compliance_tools.py
@@ -0,0 +1,294 @@
+"""
+Compliance Tools for Compliance Officers
+
+Tools for regulatory compliance, position monitoring, and audit.
+"""
+
+from typing import Dict, Any, List, Optional
+from agno.tools import Toolkit
+
+
+class ComplianceTools(Toolkit):
+ """Tools for compliance monitoring"""
+
+ def __init__(self):
+ super().__init__(name="compliance_tools")
+ self.register(self.check_position_limits)
+ self.register(self.verify_trade_compliance)
+ self.register(self.generate_regulatory_report)
+ self.register(self.monitor_restricted_list)
+ self.register(self.check_insider_trading_risk)
+ self.register(self.audit_trade_trail)
+ self.register(self.verify_best_execution)
+
+ def check_position_limits(
+ self,
+ portfolio: Dict[str, float]
+ ) -> Dict[str, Any]:
+ """
+ Check portfolio against regulatory position limits.
+
+ Args:
+ portfolio: Current portfolio positions
+
+ Returns:
+ Position limit compliance check
+ """
+ return {
+ "overall_compliance": True,
+ "checks_performed": 12,
+ "issues_found": 1,
+ "position_checks": {
+ "single_name_5pct": {
+ "limit": 0.05,
+ "max_current": 0.035,
+ "compliant": True,
+ },
+ "sector_25pct": {
+ "limit": 0.25,
+ "max_current": 0.28,
+ "compliant": False,
+ "breach_ticker": "technology_sector",
+ },
+ "short_interest_limit": {
+ "limit": 0.30,
+ "current": 0.22,
+ "compliant": True,
+ },
+ "derivative_notional": {
+ "limit": 2.0, # 200% of NAV
+ "current": 1.5,
+ "compliant": True,
+ },
+ },
+ "13f_filing_required": True,
+ "13d_filing_required": False,
+ "schedule_13g_positions": ["MSFT", "AAPL"],
+ "recommended_actions": [
+ "Reduce technology sector exposure by 3%"
+ ],
+ }
+
+ def verify_trade_compliance(
+ self,
+ trade: Dict[str, Any]
+ ) -> Dict[str, Any]:
+ """
+ Pre-trade compliance verification.
+
+ Args:
+ trade: Proposed trade details
+
+ Returns:
+ Compliance verification result
+ """
+ return {
+ "trade_id": trade.get("id", "pending"),
+ "compliance_status": "APPROVED",
+ "checks_performed": [
+ {"check": "restricted_list", "result": "PASS"},
+ {"check": "position_limit", "result": "PASS"},
+ {"check": "sector_limit", "result": "PASS"},
+ {"check": "leverage_limit", "result": "PASS"},
+ {"check": "concentration_limit", "result": "PASS"},
+ {"check": "trading_halt", "result": "PASS"},
+ {"check": "market_hours", "result": "PASS"},
+ ],
+ "warnings": [],
+ "required_approvals": [],
+ "execution_permitted": True,
+ "compliance_timestamp": "2024-01-15T10:30:00Z",
+ }
+
+ def generate_regulatory_report(
+ self,
+ report_type: str,
+ period: str
+ ) -> Dict[str, Any]:
+ """
+ Generate regulatory compliance reports.
+
+ Args:
+ report_type: Type of report (13f, form_pf, etc.)
+ period: Reporting period
+
+ Returns:
+ Report data
+ """
+ return {
+ "report_type": report_type,
+ "period": period,
+ "status": "generated",
+ "report_contents": {
+ "total_aum": 15000000000, # $15B
+ "positions_reported": 1250,
+ "beneficial_ownership_filings": 3,
+ "material_changes": False,
+ },
+ "filing_deadline": "2024-02-14",
+ "days_until_deadline": 30,
+ "validation_status": "valid",
+ "signature_required": True,
+ "electronic_filing_ready": True,
+ }
+
+ def monitor_restricted_list(
+ self,
+ tickers: List[str]
+ ) -> Dict[str, Any]:
+ """
+ Check tickers against restricted trading list.
+
+ Args:
+ tickers: List of tickers to check
+
+ Returns:
+ Restricted list check results
+ """
+ return {
+ "tickers_checked": len(tickers),
+ "restricted_found": 1,
+ "watch_list_found": 2,
+ "results": {
+ "AAPL": {"status": "clear", "reason": None},
+ "XYZ": {"status": "restricted", "reason": "pending_acquisition"},
+ "ABC": {"status": "watch_list", "reason": "earnings_quiet_period"},
+ "DEF": {"status": "watch_list", "reason": "analyst_meeting"},
+ },
+ "restricted_list_updated": "2024-01-14",
+ "next_review_date": "2024-01-21",
+ }
+
+ def check_insider_trading_risk(
+ self,
+ trade: Dict[str, Any],
+ trader_id: str
+ ) -> Dict[str, Any]:
+ """
+ Check for potential insider trading indicators.
+
+ Args:
+ trade: Proposed trade
+ trader_id: ID of trader proposing
+
+ Returns:
+ Insider trading risk assessment
+ """
+ return {
+ "risk_level": "LOW",
+ "risk_score": 0.15,
+ "checks": {
+ "material_event_proximity": {
+ "upcoming_events": ["earnings_02_15"],
+ "days_to_event": 31,
+ "risk": "low",
+ },
+ "trading_pattern_anomaly": {
+ "vs_historical": "normal",
+ "risk": "low",
+ },
+ "information_access": {
+ "trader_clearance": "standard",
+ "ticker_sensitive": False,
+ "risk": "low",
+ },
+ "communication_flags": {
+ "flagged_communications": 0,
+ "risk": "low",
+ },
+ },
+ "approval_required": False,
+ "escalation_required": False,
+ }
+
+ def audit_trade_trail(
+ self,
+ trade_id: str
+ ) -> Dict[str, Any]:
+ """
+ Generate audit trail for a trade.
+
+ Args:
+ trade_id: Trade identifier
+
+ Returns:
+ Complete audit trail
+ """
+ return {
+ "trade_id": trade_id,
+ "audit_complete": True,
+ "trail": [
+ {
+ "timestamp": "2024-01-15T10:00:00Z",
+ "event": "signal_generated",
+ "agent": "signal_scientist",
+ "details": {"signal_strength": 0.72},
+ },
+ {
+ "timestamp": "2024-01-15T10:05:00Z",
+ "event": "signal_validated",
+ "agent": "research_lead",
+ "details": {"validation": "approved"},
+ },
+ {
+ "timestamp": "2024-01-15T10:10:00Z",
+ "event": "risk_checked",
+ "agent": "risk_quant",
+ "details": {"risk_ok": True, "var_impact": 0.02},
+ },
+ {
+ "timestamp": "2024-01-15T10:12:00Z",
+ "event": "compliance_approved",
+ "agent": "compliance_officer",
+ "details": {"all_checks_passed": True},
+ },
+ {
+ "timestamp": "2024-01-15T10:15:00Z",
+ "event": "execution_started",
+ "agent": "execution_trader",
+ "details": {"algo": "adaptive_arrival"},
+ },
+ {
+ "timestamp": "2024-01-15T12:30:00Z",
+ "event": "execution_completed",
+ "agent": "execution_trader",
+ "details": {"fill_rate": 0.98, "slippage_bps": 3.2},
+ },
+ ],
+ "chain_of_custody": "verified",
+ "data_integrity": "verified",
+ "retention_compliant": True,
+ }
+
+ def verify_best_execution(
+ self,
+ executions: List[Dict[str, Any]]
+ ) -> Dict[str, Any]:
+ """
+ Verify best execution compliance.
+
+ Args:
+ executions: List of executed trades
+
+ Returns:
+ Best execution analysis
+ """
+ return {
+ "period": "2024-Q1",
+ "executions_analyzed": len(executions),
+ "best_execution_achieved": True,
+ "metrics": {
+ "average_vs_nbbo_bps": 0.5, # Half basis point inside
+ "price_improvement_rate": 0.65, # 65% got price improvement
+ "average_improvement_bps": 1.2,
+ "fill_rate": 0.97,
+ "execution_speed_ms": 45,
+ },
+ "venue_analysis": {
+ "NYSE": {"fill_rate": 0.98, "price_quality": "excellent"},
+ "NASDAQ": {"fill_rate": 0.96, "price_quality": "good"},
+ "dark_pools": {"fill_rate": 0.85, "price_quality": "good"},
+ },
+ "compliance_statement": "Best execution obligations met",
+ "documentation_complete": True,
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/execution_tools.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/execution_tools.py
new file mode 100644
index 000000000..f863b193e
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/execution_tools.py
@@ -0,0 +1,330 @@
+"""
+Execution Tools for Execution Traders and Market Makers
+
+Tools for trade execution, order management, and market making.
+"""
+
+from typing import Dict, Any, List, Optional
+from agno.tools import Toolkit
+
+
+class ExecutionTools(Toolkit):
+ """Tools for trade execution"""
+
+ def __init__(self):
+ super().__init__(name="execution_tools")
+ self.register(self.analyze_market_microstructure)
+ self.register(self.calculate_optimal_execution)
+ self.register(self.estimate_market_impact)
+ self.register(self.generate_order_schedule)
+ self.register(self.route_order)
+ self.register(self.calculate_transaction_costs)
+ self.register(self.analyze_post_trade)
+ self.register(self.quote_market)
+
+ def analyze_market_microstructure(
+ self,
+ ticker: str
+ ) -> Dict[str, Any]:
+ """
+ Analyze market microstructure for a ticker.
+
+ Args:
+ ticker: Stock ticker
+
+ Returns:
+ Microstructure analysis
+ """
+ return {
+ "ticker": ticker,
+ "bid_ask_spread_bps": 2.5,
+ "effective_spread_bps": 3.2,
+ "realized_spread_bps": 1.8,
+ "price_impact_bps_per_100k": 0.8,
+ "order_book_depth": {
+ "bid_1pct": 2500000,
+ "ask_1pct": 2300000,
+ "bid_5pct": 8500000,
+ "ask_5pct": 8200000,
+ },
+ "volatility_intraday_bps": 45,
+ "average_trade_size": 250,
+ "trades_per_minute": 85,
+ "kyle_lambda": 0.0012, # Price impact coefficient
+ "informed_trading_probability": 0.15,
+ "optimal_participation_rate": 0.03, # 3% of volume
+ }
+
+ def calculate_optimal_execution(
+ self,
+ ticker: str,
+ quantity: int,
+ side: str,
+ urgency: float,
+ risk_aversion: float = 0.5
+ ) -> Dict[str, Any]:
+ """
+ Calculate optimal execution strategy (Almgren-Chriss style).
+
+ Args:
+ ticker: Stock ticker
+ quantity: Number of shares
+ side: 'buy' or 'sell'
+ urgency: How urgent (0-1, higher = faster)
+ risk_aversion: Risk aversion parameter
+
+ Returns:
+ Optimal execution plan
+ """
+ return {
+ "ticker": ticker,
+ "quantity": quantity,
+ "side": side,
+ "recommended_algo": "adaptive_arrival_price",
+ "expected_duration_minutes": 120,
+ "participation_rate": 0.05,
+ "expected_cost_bps": 8.5,
+ "cost_breakdown": {
+ "spread_cost": 2.5,
+ "market_impact_temporary": 3.0,
+ "market_impact_permanent": 2.0,
+ "timing_risk": 1.0,
+ },
+ "schedule": [
+ {"minute": 0, "pct_complete": 0.10},
+ {"minute": 30, "pct_complete": 0.35},
+ {"minute": 60, "pct_complete": 0.60},
+ {"minute": 90, "pct_complete": 0.85},
+ {"minute": 120, "pct_complete": 1.00},
+ ],
+ "variance_cost": 2.5,
+ "efficient_frontier_position": "balanced",
+ }
+
+ def estimate_market_impact(
+ self,
+ ticker: str,
+ quantity: int,
+ execution_time_minutes: int
+ ) -> Dict[str, Any]:
+ """
+ Estimate market impact of a trade.
+
+ Args:
+ ticker: Stock ticker
+ quantity: Number of shares
+ execution_time_minutes: Planned execution time
+
+ Returns:
+ Market impact estimates
+ """
+ return {
+ "ticker": ticker,
+ "quantity": quantity,
+ "pct_of_adv": 0.8, # 0.8% of average daily volume
+ "temporary_impact_bps": 5.2,
+ "permanent_impact_bps": 2.1,
+ "total_impact_bps": 7.3,
+ "impact_uncertainty_bps": 2.5,
+ "impact_percentile_95": 12.0,
+ "alpha_decay_cost": 3.5, # Cost of slow execution
+ "optimal_execution_time": 90, # minutes
+ "impact_models_used": ["almgren_chriss", "obizhaeva_wang", "kyle"],
+ }
+
+ def generate_order_schedule(
+ self,
+ ticker: str,
+ quantity: int,
+ algo_type: str,
+ start_time: str,
+ end_time: str
+ ) -> Dict[str, Any]:
+ """
+ Generate detailed order execution schedule.
+
+ Args:
+ ticker: Stock ticker
+ quantity: Total quantity
+ algo_type: Algorithm type (twap, vwap, arrival_price)
+ start_time: Execution start time
+ end_time: Execution end time
+
+ Returns:
+ Order schedule
+ """
+ return {
+ "ticker": ticker,
+ "total_quantity": quantity,
+ "algo_type": algo_type,
+ "schedule": [
+ {"time": "09:30", "quantity": 5000, "urgency": "high"},
+ {"time": "10:00", "quantity": 8000, "urgency": "normal"},
+ {"time": "10:30", "quantity": 10000, "urgency": "normal"},
+ {"time": "11:00", "quantity": 12000, "urgency": "normal"},
+ {"time": "11:30", "quantity": 10000, "urgency": "normal"},
+ {"time": "12:00", "quantity": 8000, "urgency": "low"},
+ {"time": "14:00", "quantity": 15000, "urgency": "normal"},
+ {"time": "15:00", "quantity": 18000, "urgency": "normal"},
+ {"time": "15:30", "quantity": 14000, "urgency": "high"},
+ ],
+ "volume_curve_target": "historical_intraday",
+ "passive_aggressive_ratio": 0.7, # 70% passive
+ "dark_pool_participation": 0.3, # 30% to dark pools
+ "venue_preferences": ["NYSE", "NASDAQ", "ARCA", "BATS"],
+ }
+
+ def route_order(
+ self,
+ ticker: str,
+ quantity: int,
+ side: str,
+ order_type: str,
+ limit_price: Optional[float] = None
+ ) -> Dict[str, Any]:
+ """
+ Smart order routing decision.
+
+ Args:
+ ticker: Stock ticker
+ quantity: Order quantity
+ side: 'buy' or 'sell'
+ order_type: 'market', 'limit', 'midpoint'
+ limit_price: Limit price if applicable
+
+ Returns:
+ Routing decision
+ """
+ return {
+ "ticker": ticker,
+ "quantity": quantity,
+ "side": side,
+ "routing_decision": {
+ "primary_venue": "NYSE",
+ "primary_allocation": 0.40,
+ "secondary_venues": [
+ {"venue": "NASDAQ", "allocation": 0.25},
+ {"venue": "ARCA", "allocation": 0.15},
+ {"venue": "IEX", "allocation": 0.10},
+ {"venue": "dark_pool", "allocation": 0.10},
+ ],
+ },
+ "order_types": {
+ "NYSE": "limit",
+ "NASDAQ": "hidden_limit",
+ "dark_pool": "midpoint_peg",
+ },
+ "expected_fill_rate": 0.85,
+ "expected_rebate_bps": 0.2,
+ "routing_rationale": "Maximize rebate while minimizing information leakage",
+ }
+
+ def calculate_transaction_costs(
+ self,
+ trades: List[Dict[str, Any]]
+ ) -> Dict[str, Any]:
+ """
+ Calculate transaction cost analysis (TCA).
+
+ Args:
+ trades: List of executed trades
+
+ Returns:
+ TCA results
+ """
+ return {
+ "num_trades": len(trades),
+ "total_volume": 1500000,
+ "total_notional": 75000000,
+ "implementation_shortfall_bps": 8.2,
+ "cost_breakdown": {
+ "commission": 0.5,
+ "spread": 2.5,
+ "market_impact": 4.0,
+ "timing": 1.2,
+ },
+ "benchmark_comparison": {
+ "vs_arrival": 8.2,
+ "vs_vwap": 3.5,
+ "vs_twap": 4.1,
+ "vs_close": -2.0, # Beat close price
+ },
+ "execution_quality_score": 0.78,
+ "alpha_preservation": 0.85, # 85% of alpha preserved
+ "cost_vs_estimate": -1.5, # 1.5 bps better than estimated
+ }
+
+ def analyze_post_trade(
+ self,
+ trade_id: str
+ ) -> Dict[str, Any]:
+ """
+ Post-trade analysis for learning and improvement.
+
+ Args:
+ trade_id: Trade identifier
+
+ Returns:
+ Post-trade analysis
+ """
+ return {
+ "trade_id": trade_id,
+ "execution_quality": "above_average",
+ "vs_arrival_price_bps": -5.2, # 5.2 bps better
+ "vs_vwap_bps": 2.1, # 2.1 bps worse
+ "fill_rate": 0.98,
+ "venues_used": ["NYSE", "NASDAQ", "ARCA"],
+ "algo_performance": {
+ "algo_used": "adaptive_arrival",
+ "alpha_capture": 0.88,
+ "urgency_appropriate": True,
+ "size_appropriate": True,
+ },
+ "market_conditions": {
+ "volatility": "normal",
+ "volume": "above_average",
+ "spread": "tight",
+ },
+ "learnings": [
+ "Dark pool fill rate lower than expected",
+ "Opening auction participation beneficial",
+ "Reduce participation in last 5 minutes",
+ ],
+ "model_update_recommended": True,
+ }
+
+ def quote_market(
+ self,
+ ticker: str,
+ inventory: int,
+ risk_limit: float
+ ) -> Dict[str, Any]:
+ """
+ Generate market making quotes.
+
+ Args:
+ ticker: Stock ticker
+ inventory: Current inventory position
+ risk_limit: Maximum inventory risk
+
+ Returns:
+ Bid/ask quotes
+ """
+ return {
+ "ticker": ticker,
+ "current_inventory": inventory,
+ "inventory_risk_pct": abs(inventory) / risk_limit,
+ "quotes": {
+ "bid_price": 150.25,
+ "bid_size": 500,
+ "ask_price": 150.30,
+ "ask_size": 500,
+ "spread_bps": 3.3,
+ },
+ "quote_skew": -0.02 if inventory > 0 else 0.02, # Skew to reduce inventory
+ "fair_value": 150.275,
+ "edge_per_round_trip_bps": 2.5,
+ "expected_pnl_per_share": 0.03,
+ "quote_life_ms": 50, # 50ms until refresh
+ "cancel_threshold_bps": 2.0,
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/market_data_tools.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/market_data_tools.py
new file mode 100644
index 000000000..27c9d2bb9
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/market_data_tools.py
@@ -0,0 +1,261 @@
+"""
+Market Data Tools for Data Scientists and Researchers
+
+Tools for fetching, processing, and analyzing market data.
+"""
+
+from typing import Dict, Any, List, Optional
+from datetime import datetime, timedelta
+from agno.tools import Toolkit
+import json
+
+
+class MarketDataTools(Toolkit):
+ """Tools for market data operations"""
+
+ def __init__(self):
+ super().__init__(name="market_data_tools")
+ self.register(self.fetch_price_data)
+ self.register(self.fetch_volume_data)
+ self.register(self.calculate_returns)
+ self.register(self.calculate_volatility)
+ self.register(self.get_correlation_matrix)
+ self.register(self.fetch_alternative_data)
+ self.register(self.clean_data)
+ self.register(self.create_features)
+
+ def fetch_price_data(
+ self,
+ ticker: str,
+ start_date: str,
+ end_date: str,
+ interval: str = "1d"
+ ) -> Dict[str, Any]:
+ """
+ Fetch historical price data for a ticker.
+
+ Args:
+ ticker: Stock/asset ticker symbol
+ start_date: Start date (YYYY-MM-DD)
+ end_date: End date (YYYY-MM-DD)
+ interval: Data interval (1m, 5m, 1h, 1d)
+
+ Returns:
+ Dictionary with OHLCV data
+ """
+ # Placeholder - would integrate with actual data provider
+ return {
+ "ticker": ticker,
+ "start_date": start_date,
+ "end_date": end_date,
+ "interval": interval,
+ "data_points": 252, # Trading days
+ "columns": ["open", "high", "low", "close", "volume"],
+ "status": "fetched",
+ "source": "internal_data_warehouse",
+ }
+
+ def fetch_volume_data(
+ self,
+ ticker: str,
+ lookback_days: int = 30
+ ) -> Dict[str, Any]:
+ """
+ Fetch volume profile data.
+
+ Args:
+ ticker: Stock ticker
+ lookback_days: Number of days to analyze
+
+ Returns:
+ Volume statistics
+ """
+ return {
+ "ticker": ticker,
+ "average_daily_volume": 5000000,
+ "volume_std": 1200000,
+ "volume_percentiles": {
+ "25th": 3500000,
+ "50th": 4800000,
+ "75th": 6200000,
+ "95th": 8500000,
+ },
+ "typical_spread_bps": 2.5,
+ "market_depth_score": 0.85,
+ }
+
+ def calculate_returns(
+ self,
+ ticker: str,
+ period: str = "1d",
+ lookback_days: int = 252
+ ) -> Dict[str, Any]:
+ """
+ Calculate return statistics.
+
+ Args:
+ ticker: Stock ticker
+ period: Return period (1d, 5d, 21d)
+ lookback_days: Historical window
+
+ Returns:
+ Return statistics
+ """
+ return {
+ "ticker": ticker,
+ "period": period,
+ "mean_return": 0.0008, # 0.08% daily
+ "std_return": 0.018, # 1.8% daily std
+ "skewness": -0.15,
+ "kurtosis": 4.2,
+ "sharpe_ratio": 1.8,
+ "sortino_ratio": 2.4,
+ "max_drawdown": -0.12,
+ "win_rate": 0.52,
+ }
+
+ def calculate_volatility(
+ self,
+ ticker: str,
+ window: int = 21
+ ) -> Dict[str, Any]:
+ """
+ Calculate volatility metrics.
+
+ Args:
+ ticker: Stock ticker
+ window: Rolling window (days)
+
+ Returns:
+ Volatility metrics
+ """
+ return {
+ "ticker": ticker,
+ "realized_vol_21d": 0.25, # 25% annualized
+ "realized_vol_63d": 0.22,
+ "implied_vol": 0.28,
+ "vol_of_vol": 0.15,
+ "vol_regime": "normal", # low, normal, high, extreme
+ "vol_percentile": 0.55,
+ }
+
+ def get_correlation_matrix(
+ self,
+ tickers: List[str],
+ lookback_days: int = 63
+ ) -> Dict[str, Any]:
+ """
+ Calculate correlation matrix for multiple tickers.
+
+ Args:
+ tickers: List of ticker symbols
+ lookback_days: Historical window
+
+ Returns:
+ Correlation matrix and statistics
+ """
+ return {
+ "tickers": tickers,
+ "lookback_days": lookback_days,
+ "average_correlation": 0.35,
+ "max_correlation": 0.75,
+ "min_correlation": -0.15,
+ "correlation_regime": "moderate",
+ "matrix": "[[1.0, 0.35, ...], ...]", # Simplified
+ }
+
+ def fetch_alternative_data(
+ self,
+ ticker: str,
+ data_type: str
+ ) -> Dict[str, Any]:
+ """
+ Fetch alternative data sources.
+
+ Args:
+ ticker: Stock ticker
+ data_type: Type of alt data (sentiment, satellite, web_traffic, etc.)
+
+ Returns:
+ Alternative data metrics
+ """
+ data_types = {
+ "sentiment": {
+ "social_sentiment_score": 0.65,
+ "news_sentiment_score": 0.58,
+ "analyst_sentiment": 0.72,
+ "retail_vs_institutional": 0.4,
+ },
+ "satellite": {
+ "parking_lot_fullness": 0.78,
+ "shipping_activity": 0.82,
+ "construction_activity": 0.65,
+ },
+ "web_traffic": {
+ "website_visits_change": 0.15,
+ "app_downloads_change": 0.22,
+ "search_trend_score": 0.68,
+ },
+ }
+ return {
+ "ticker": ticker,
+ "data_type": data_type,
+ "data": data_types.get(data_type, {}),
+ "data_freshness": "T-1",
+ "confidence": 0.75,
+ }
+
+ def clean_data(
+ self,
+ ticker: str,
+ data_issues: List[str]
+ ) -> Dict[str, Any]:
+ """
+ Clean and validate market data.
+
+ Args:
+ ticker: Stock ticker
+ data_issues: List of issues to check/fix
+
+ Returns:
+ Data quality report
+ """
+ return {
+ "ticker": ticker,
+ "issues_found": 3,
+ "issues_fixed": 3,
+ "missing_values_filled": 2,
+ "outliers_removed": 1,
+ "corporate_actions_adjusted": True,
+ "data_quality_score": 0.98,
+ }
+
+ def create_features(
+ self,
+ ticker: str,
+ feature_types: List[str]
+ ) -> Dict[str, Any]:
+ """
+ Create derived features for modeling.
+
+ Args:
+ ticker: Stock ticker
+ feature_types: Types of features to create
+
+ Returns:
+ Feature engineering results
+ """
+ return {
+ "ticker": ticker,
+ "features_created": len(feature_types) * 5,
+ "feature_types": feature_types,
+ "feature_list": [
+ "return_1d", "return_5d", "return_21d",
+ "vol_21d", "vol_ratio",
+ "momentum_12_1", "momentum_6_1",
+ "rsi_14", "macd_signal",
+ "volume_ratio", "price_to_vwap",
+ ],
+ "nan_ratio": 0.001,
+ "feature_importance_estimated": True,
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/portfolio_tools.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/portfolio_tools.py
new file mode 100644
index 000000000..aaa41acd0
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/portfolio_tools.py
@@ -0,0 +1,296 @@
+"""
+Portfolio Management Tools
+
+Tools for portfolio construction, optimization, and attribution.
+"""
+
+from typing import Dict, Any, List, Optional
+from agno.tools import Toolkit
+
+
+class PortfolioTools(Toolkit):
+ """Tools for portfolio management"""
+
+ def __init__(self):
+ super().__init__(name="portfolio_tools")
+ self.register(self.optimize_portfolio)
+ self.register(self.calculate_kelly_sizing)
+ self.register(self.rebalance_portfolio)
+ self.register(self.calculate_performance_attribution)
+ self.register(self.analyze_strategy_capacity)
+ self.register(self.allocate_capital)
+ self.register(self.calculate_leverage)
+
+ def optimize_portfolio(
+ self,
+ signals: Dict[str, float],
+ constraints: Dict[str, Any],
+ objective: str = "maximize_sharpe"
+ ) -> Dict[str, Any]:
+ """
+ Optimize portfolio weights given signals and constraints.
+
+ Args:
+ signals: Dictionary of ticker -> signal strength
+ constraints: Portfolio constraints
+ objective: Optimization objective
+
+ Returns:
+ Optimal portfolio weights
+ """
+ return {
+ "objective": objective,
+ "optimal_weights": {
+ "AAPL": 0.035,
+ "MSFT": 0.032,
+ "GOOGL": 0.028,
+ "AMZN": 0.025,
+ "META": 0.022,
+ # ... many more positions
+ },
+ "expected_return": 0.15, # 15% annual
+ "expected_volatility": 0.08, # 8% annual
+ "expected_sharpe": 1.88,
+ "turnover_from_current": 0.12, # 12% turnover
+ "transaction_cost_drag": 0.005, # 50 bps
+ "net_expected_return": 0.145,
+ "optimization_status": "optimal",
+ "binding_constraints": ["max_position_size", "sector_tech"],
+ "num_positions": 150,
+ }
+
+ def calculate_kelly_sizing(
+ self,
+ signals: List[Dict[str, Any]]
+ ) -> Dict[str, Any]:
+ """
+ Calculate Kelly criterion position sizes.
+
+ Args:
+ signals: List of signals with win rates and payoffs
+
+ Returns:
+ Kelly-optimal position sizes
+ """
+ return {
+ "kelly_fractions": {
+ "signal_1": 0.08, # 8% Kelly
+ "signal_2": 0.06,
+ "signal_3": 0.12,
+ },
+ "fractional_kelly": 0.25, # Use 25% of full Kelly
+ "adjusted_sizes": {
+ "signal_1": 0.02, # 2% position
+ "signal_2": 0.015,
+ "signal_3": 0.03,
+ },
+ "aggregate_kelly": 0.35, # Total Kelly fraction
+ "leverage_implied": 8.5, # Implied leverage
+ "risk_of_ruin_1yr": 0.001, # 0.1% risk of ruin
+ "expected_geometric_growth": 0.18,
+ "recommendation": "Sizes within acceptable range",
+ }
+
+ def rebalance_portfolio(
+ self,
+ current_weights: Dict[str, float],
+ target_weights: Dict[str, float],
+ constraints: Dict[str, Any]
+ ) -> Dict[str, Any]:
+ """
+ Generate rebalancing trades.
+
+ Args:
+ current_weights: Current portfolio weights
+ target_weights: Target portfolio weights
+ constraints: Rebalancing constraints
+
+ Returns:
+ Rebalancing plan
+ """
+ return {
+ "trades_required": [
+ {"ticker": "AAPL", "action": "sell", "quantity": 5000, "urgency": "low"},
+ {"ticker": "NVDA", "action": "buy", "quantity": 3000, "urgency": "medium"},
+ {"ticker": "TSLA", "action": "sell", "quantity": 8000, "urgency": "high"},
+ ],
+ "total_turnover_pct": 8.5,
+ "estimated_cost_bps": 12,
+ "tracking_error_reduction": 0.5, # 50 bps improvement
+ "rebalancing_frequency": "weekly",
+ "threshold_triggered": "drift_exceeded_2pct",
+ "tax_lots_to_use": "minimize_gain",
+ "net_tax_impact": -5000, # Harvested losses
+ }
+
+ def calculate_performance_attribution(
+ self,
+ portfolio_returns: List[float],
+ benchmark_returns: List[float],
+ holdings_history: List[Dict[str, float]]
+ ) -> Dict[str, Any]:
+ """
+ Calculate performance attribution.
+
+ Args:
+ portfolio_returns: Portfolio return series
+ benchmark_returns: Benchmark return series
+ holdings_history: Historical holdings
+
+ Returns:
+ Performance attribution
+ """
+ return {
+ "total_return": 0.182, # 18.2%
+ "benchmark_return": 0.125, # 12.5%
+ "excess_return": 0.057, # 5.7% alpha
+ "attribution": {
+ "allocation_effect": 0.015, # 1.5%
+ "selection_effect": 0.035, # 3.5%
+ "interaction_effect": 0.007, # 0.7%
+ },
+ "factor_attribution": {
+ "market": 0.10,
+ "size": -0.005,
+ "value": 0.008,
+ "momentum": 0.025,
+ "residual_alpha": 0.054, # True alpha
+ },
+ "sector_attribution": {
+ "technology": 0.032,
+ "healthcare": 0.012,
+ "financials": -0.005,
+ "consumer": 0.008,
+ },
+ "information_ratio": 2.1,
+ "tracking_error": 0.027, # 2.7%
+ }
+
+ def analyze_strategy_capacity(
+ self,
+ strategy_name: str,
+ current_aum: float
+ ) -> Dict[str, Any]:
+ """
+ Analyze strategy capacity constraints.
+
+ Args:
+ strategy_name: Name of the strategy
+ current_aum: Current assets under management
+
+ Returns:
+ Capacity analysis
+ """
+ return {
+ "strategy_name": strategy_name,
+ "current_aum_billions": current_aum,
+ "estimated_capacity_billions": 15.0,
+ "capacity_utilization": current_aum / 15.0,
+ "marginal_impact_at_capacity": {
+ "execution_cost_increase_bps": 5,
+ "alpha_decay_pct": 15,
+ "sharpe_degradation": 0.3,
+ },
+ "optimal_aum": 10.0, # $10B optimal
+ "capacity_by_component": {
+ "market_impact": 12.0, # Limited by impact at $12B
+ "liquidity": 18.0, # Limited by liquidity at $18B
+ "alpha_decay": 15.0, # Alpha decays above $15B
+ },
+ "scaling_recommendation": "SOFT_CLOSE_AT_12B",
+ "capacity_trend": "declining", # Competition increasing
+ }
+
+ def allocate_capital(
+ self,
+ strategies: List[Dict[str, Any]],
+ total_capital: float,
+ risk_budget: float
+ ) -> Dict[str, Any]:
+ """
+ Allocate capital across strategies.
+
+ Args:
+ strategies: List of strategy profiles
+ total_capital: Total capital to allocate
+ risk_budget: Total risk budget
+
+ Returns:
+ Capital allocation
+ """
+ return {
+ "total_capital": total_capital,
+ "allocations": {
+ "mean_reversion_equities": {
+ "capital_pct": 0.25,
+ "capital_usd": total_capital * 0.25,
+ "risk_contribution": 0.20,
+ "expected_return": 0.18,
+ "sharpe": 2.2,
+ },
+ "momentum_equities": {
+ "capital_pct": 0.20,
+ "capital_usd": total_capital * 0.20,
+ "risk_contribution": 0.25,
+ "expected_return": 0.15,
+ "sharpe": 1.8,
+ },
+ "statistical_arbitrage": {
+ "capital_pct": 0.30,
+ "capital_usd": total_capital * 0.30,
+ "risk_contribution": 0.30,
+ "expected_return": 0.22,
+ "sharpe": 2.5,
+ },
+ "market_making": {
+ "capital_pct": 0.15,
+ "capital_usd": total_capital * 0.15,
+ "risk_contribution": 0.15,
+ "expected_return": 0.12,
+ "sharpe": 3.0,
+ },
+ "cash_reserve": {
+ "capital_pct": 0.10,
+ "capital_usd": total_capital * 0.10,
+ "risk_contribution": 0.00,
+ },
+ },
+ "portfolio_expected_return": 0.172,
+ "portfolio_expected_sharpe": 2.3,
+ "diversification_ratio": 1.4,
+ "rebalancing_frequency": "monthly",
+ }
+
+ def calculate_leverage(
+ self,
+ gross_exposure: float,
+ net_exposure: float,
+ capital: float
+ ) -> Dict[str, Any]:
+ """
+ Calculate and monitor leverage metrics.
+
+ Args:
+ gross_exposure: Total long + short exposure
+ net_exposure: Long - short exposure
+ capital: Total capital
+
+ Returns:
+ Leverage analysis
+ """
+ return {
+ "gross_leverage": gross_exposure / capital,
+ "net_leverage": net_exposure / capital,
+ "long_exposure": (gross_exposure + net_exposure) / 2,
+ "short_exposure": (gross_exposure - net_exposure) / 2,
+ "leverage_limit": 12.5, # RenTech uses high leverage
+ "limit_utilization": (gross_exposure / capital) / 12.5,
+ "margin_usage": 0.75, # 75% of available margin
+ "margin_buffer": 0.25,
+ "leverage_at_risk": {
+ "if_vol_doubles": 8.0, # Reduce to 8x if vol doubles
+ "if_drawdown_10pct": 6.0, # Reduce to 6x at 10% DD
+ },
+ "financing_cost_bps": 50, # 50 bps annual
+ "recommended_leverage": 10.0,
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/risk_tools.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/risk_tools.py
new file mode 100644
index 000000000..e7cbe718f
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/risk_tools.py
@@ -0,0 +1,307 @@
+"""
+Risk Analysis Tools for Risk Quants
+
+Tools for measuring, monitoring, and managing portfolio risk.
+"""
+
+from typing import Dict, Any, List, Optional
+from agno.tools import Toolkit
+
+
+class RiskAnalysisTools(Toolkit):
+ """Tools for risk analysis and monitoring"""
+
+ def __init__(self):
+ super().__init__(name="risk_analysis_tools")
+ self.register(self.calculate_var)
+ self.register(self.run_stress_test)
+ self.register(self.analyze_factor_exposure)
+ self.register(self.calculate_correlation_risk)
+ self.register(self.check_concentration)
+ self.register(self.monitor_drawdown)
+ self.register(self.calculate_tail_risk)
+ self.register(self.assess_liquidity_risk)
+
+ def calculate_var(
+ self,
+ portfolio: Dict[str, float],
+ confidence_level: float = 0.99,
+ horizon_days: int = 1,
+ method: str = "historical"
+ ) -> Dict[str, Any]:
+ """
+ Calculate Value at Risk for portfolio.
+
+ Args:
+ portfolio: Dictionary of ticker -> position size
+ confidence_level: VaR confidence level (0.95, 0.99)
+ horizon_days: Time horizon
+ method: VaR method (historical, parametric, monte_carlo)
+
+ Returns:
+ VaR metrics
+ """
+ return {
+ "var_pct": 2.1, # 2.1% daily VaR at 99%
+ "var_dollars": 21000000,
+ "confidence_level": confidence_level,
+ "horizon_days": horizon_days,
+ "method": method,
+ "expected_shortfall": 3.2, # CVaR/ES
+ "component_var": {
+ "equity": 1.5,
+ "rates": 0.3,
+ "fx": 0.2,
+ "commodity": 0.1,
+ },
+ "marginal_var_top_5": [
+ {"ticker": "AAPL", "marginal_var": 0.15},
+ {"ticker": "MSFT", "marginal_var": 0.12},
+ {"ticker": "GOOGL", "marginal_var": 0.10},
+ ],
+ "var_limit": 2.0,
+ "limit_utilization": 1.05, # Slightly over limit
+ "breach": True,
+ }
+
+ def run_stress_test(
+ self,
+ portfolio: Dict[str, float],
+ scenarios: List[str]
+ ) -> Dict[str, Any]:
+ """
+ Run stress tests on portfolio.
+
+ Args:
+ portfolio: Portfolio positions
+ scenarios: Stress scenarios to run
+
+ Returns:
+ Stress test results
+ """
+ return {
+ "scenarios_tested": len(scenarios),
+ "results": {
+ "2008_crisis": {
+ "loss_pct": -35.0,
+ "recovery_days": 180,
+ "max_drawdown": -42.0,
+ },
+ "2020_covid": {
+ "loss_pct": -28.0,
+ "recovery_days": 45,
+ "max_drawdown": -33.0,
+ },
+ "2022_rate_hike": {
+ "loss_pct": -18.0,
+ "recovery_days": 120,
+ "max_drawdown": -22.0,
+ },
+ "flash_crash": {
+ "loss_pct": -8.0,
+ "recovery_days": 3,
+ "max_drawdown": -12.0,
+ },
+ "vol_spike_50pct": {
+ "loss_pct": -15.0,
+ "recovery_days": 30,
+ "max_drawdown": -18.0,
+ },
+ },
+ "worst_case_loss": -42.0,
+ "expected_loss_severe": -25.0,
+ "stress_capital_required": 50000000,
+ "recommendation": "REDUCE_EXPOSURE",
+ }
+
+ def analyze_factor_exposure(
+ self,
+ portfolio: Dict[str, float]
+ ) -> Dict[str, Any]:
+ """
+ Analyze portfolio factor exposures.
+
+ Args:
+ portfolio: Portfolio positions
+
+ Returns:
+ Factor exposure analysis
+ """
+ return {
+ "factor_exposures": {
+ "market_beta": 0.85,
+ "size_smb": -0.15, # Slight large cap bias
+ "value_hml": 0.10,
+ "momentum_umd": 0.25,
+ "quality_qmj": 0.30,
+ "low_vol": -0.20,
+ "liquidity": 0.05,
+ },
+ "factor_contributions_to_risk": {
+ "market": 0.65, # 65% of risk from market
+ "size": 0.05,
+ "value": 0.08,
+ "momentum": 0.12,
+ "residual": 0.10,
+ },
+ "factor_tilts_vs_benchmark": {
+ "overweight": ["momentum", "quality"],
+ "underweight": ["value", "size"],
+ "neutral": ["market"],
+ },
+ "tracking_error_pct": 3.5,
+ "active_share": 0.72,
+ "factor_crowding_risk": "moderate",
+ }
+
+ def calculate_correlation_risk(
+ self,
+ portfolio: Dict[str, float]
+ ) -> Dict[str, Any]:
+ """
+ Analyze correlation-based risks.
+
+ Args:
+ portfolio: Portfolio positions
+
+ Returns:
+ Correlation risk metrics
+ """
+ return {
+ "average_correlation": 0.42,
+ "correlation_percentile": 0.75, # Higher than 75% of history
+ "correlation_regime": "elevated",
+ "diversification_ratio": 1.8,
+ "effective_n_assets": 25, # Out of 100 positions
+ "correlation_stress": {
+ "if_corr_goes_to_0.8": {
+ "var_increase_pct": 45,
+ "expected_loss_increase": 30,
+ },
+ },
+ "tail_correlation": 0.65, # Correlation spikes in tails
+ "recommendation": "ADD_DIVERSIFIERS",
+ }
+
+ def check_concentration(
+ self,
+ portfolio: Dict[str, float]
+ ) -> Dict[str, Any]:
+ """
+ Check portfolio concentration limits.
+
+ Args:
+ portfolio: Portfolio positions
+
+ Returns:
+ Concentration analysis
+ """
+ return {
+ "top_5_concentration": 0.25, # 25% in top 5
+ "top_10_concentration": 0.40,
+ "sector_concentration": {
+ "technology": 0.28, # 28% in tech
+ "healthcare": 0.15,
+ "financials": 0.12,
+ },
+ "single_name_max": 0.035, # 3.5% max single name
+ "limit_breaches": [
+ {
+ "type": "sector",
+ "sector": "technology",
+ "exposure": 0.28,
+ "limit": 0.25,
+ "breach_pct": 12,
+ }
+ ],
+ "herfindahl_index": 0.015,
+ "gini_coefficient": 0.55,
+ "recommendation": "REDUCE_TECH_EXPOSURE",
+ }
+
+ def monitor_drawdown(
+ self,
+ portfolio_value_history: List[float]
+ ) -> Dict[str, Any]:
+ """
+ Monitor portfolio drawdown.
+
+ Args:
+ portfolio_value_history: Historical portfolio values
+
+ Returns:
+ Drawdown metrics
+ """
+ return {
+ "current_drawdown_pct": -5.2,
+ "max_drawdown_pct": -12.5,
+ "drawdown_duration_days": 15,
+ "days_since_high_water_mark": 18,
+ "drawdown_limit": -15.0,
+ "limit_utilization": 0.35,
+ "average_recovery_time": 25,
+ "drawdown_velocity": -0.3, # Losing 0.3% per day
+ "drawdown_percentile": 0.72, # Worse than 72% of history
+ "alert_level": "WARNING",
+ "recommendation": "REDUCE_RISK_GRADUALLY",
+ }
+
+ def calculate_tail_risk(
+ self,
+ portfolio: Dict[str, float]
+ ) -> Dict[str, Any]:
+ """
+ Calculate tail risk metrics.
+
+ Args:
+ portfolio: Portfolio positions
+
+ Returns:
+ Tail risk analysis
+ """
+ return {
+ "expected_shortfall_99": 4.5, # 4.5% CVaR
+ "expected_shortfall_99_9": 7.2,
+ "tail_index": 3.5, # Fat tails
+ "skewness": -0.8, # Negative skew
+ "kurtosis": 5.2, # Fat tails
+ "worst_day_historical": -8.5,
+ "worst_week_historical": -15.2,
+ "black_swan_probability": 0.02, # 2% chance of extreme event
+ "tail_hedging_cost_monthly": 0.15, # 15 bps
+ "recommendation": "CONSIDER_TAIL_HEDGE",
+ }
+
+ def assess_liquidity_risk(
+ self,
+ portfolio: Dict[str, float]
+ ) -> Dict[str, Any]:
+ """
+ Assess portfolio liquidity risk.
+
+ Args:
+ portfolio: Portfolio positions
+
+ Returns:
+ Liquidity risk assessment
+ """
+ return {
+ "days_to_liquidate_100pct": 5.2,
+ "days_to_liquidate_50pct": 1.8,
+ "liquidation_cost_bps": 25,
+ "illiquid_positions_pct": 0.08, # 8% illiquid
+ "liquidity_score": 0.82, # 0-1 scale
+ "bid_ask_cost": 12, # bps
+ "market_impact_estimate": 35, # bps for full liquidation
+ "liquidity_bucketing": {
+ "highly_liquid": 0.65,
+ "liquid": 0.25,
+ "semi_liquid": 0.08,
+ "illiquid": 0.02,
+ },
+ "liquidity_stress_scenario": {
+ "cost_in_stress": 75, # bps
+ "time_to_liquidate_stress": 12, # days
+ },
+ "recommendation": "MAINTAIN_LIQUIDITY_BUFFER",
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/signal_tools.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/signal_tools.py
new file mode 100644
index 000000000..4f674e182
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/agents/tools/signal_tools.py
@@ -0,0 +1,291 @@
+"""
+Signal Analysis Tools for Signal Scientists and Quant Researchers
+
+Tools for discovering, analyzing, and validating trading signals.
+"""
+
+from typing import Dict, Any, List, Optional
+from agno.tools import Toolkit
+import json
+
+
+class SignalAnalysisTools(Toolkit):
+ """Tools for signal analysis and generation"""
+
+ def __init__(self):
+ super().__init__(name="signal_analysis_tools")
+ self.register(self.detect_patterns)
+ self.register(self.calculate_signal_strength)
+ self.register(self.backtest_signal)
+ self.register(self.calculate_p_value)
+ self.register(self.check_signal_decay)
+ self.register(self.combine_signals)
+ self.register(self.calculate_information_coefficient)
+ self.register(self.analyze_regime_dependency)
+
+ def detect_patterns(
+ self,
+ ticker: str,
+ pattern_types: List[str],
+ lookback_days: int = 252
+ ) -> Dict[str, Any]:
+ """
+ Detect statistical patterns in price data.
+
+ Args:
+ ticker: Stock ticker
+ pattern_types: Types of patterns to look for
+ lookback_days: Historical window
+
+ Returns:
+ Detected patterns with significance
+ """
+ return {
+ "ticker": ticker,
+ "patterns_detected": [
+ {
+ "type": "mean_reversion",
+ "strength": 0.65,
+ "half_life_days": 3.5,
+ "p_value": 0.008,
+ "significant": True,
+ },
+ {
+ "type": "momentum",
+ "strength": 0.42,
+ "lookback_optimal": 21,
+ "p_value": 0.045,
+ "significant": False, # Above 0.01 threshold
+ },
+ {
+ "type": "seasonality",
+ "strength": 0.55,
+ "pattern": "month_end_effect",
+ "p_value": 0.012,
+ "significant": False,
+ },
+ ],
+ "analysis_period": lookback_days,
+ "statistical_tests_run": 15,
+ }
+
+ def calculate_signal_strength(
+ self,
+ ticker: str,
+ signal_type: str,
+ parameters: Dict[str, Any]
+ ) -> Dict[str, Any]:
+ """
+ Calculate the strength of a trading signal.
+
+ Args:
+ ticker: Stock ticker
+ signal_type: Type of signal (momentum, mean_reversion, etc.)
+ parameters: Signal parameters
+
+ Returns:
+ Signal strength metrics
+ """
+ return {
+ "ticker": ticker,
+ "signal_type": signal_type,
+ "raw_signal": 0.72,
+ "normalized_signal": 1.85, # Z-score
+ "signal_percentile": 0.92,
+ "direction": "long",
+ "confidence": 0.68,
+ "expected_return_bps": 45,
+ "holding_period_days": 5,
+ "stop_loss_bps": -150,
+ "take_profit_bps": 120,
+ }
+
+ def backtest_signal(
+ self,
+ ticker: str,
+ signal_type: str,
+ start_date: str,
+ end_date: str,
+ parameters: Dict[str, Any]
+ ) -> Dict[str, Any]:
+ """
+ Backtest a trading signal.
+
+ Args:
+ ticker: Stock ticker
+ signal_type: Type of signal
+ start_date: Backtest start date
+ end_date: Backtest end date
+ parameters: Signal parameters
+
+ Returns:
+ Backtest results
+ """
+ return {
+ "ticker": ticker,
+ "signal_type": signal_type,
+ "period": f"{start_date} to {end_date}",
+ "total_trades": 847,
+ "win_rate": 0.5075, # RenTech's famous 50.75%
+ "average_win_bps": 52,
+ "average_loss_bps": -48,
+ "profit_factor": 1.12,
+ "sharpe_ratio": 2.1,
+ "sortino_ratio": 2.8,
+ "max_drawdown_pct": -8.5,
+ "calmar_ratio": 3.2,
+ "turnover_annual": 85.0, # High frequency
+ "transaction_costs_bps": 5,
+ "net_sharpe": 1.85,
+ "out_of_sample_degradation": 0.15, # 15% performance drop OOS
+ }
+
+ def calculate_p_value(
+ self,
+ test_statistic: float,
+ test_type: str,
+ sample_size: int
+ ) -> Dict[str, Any]:
+ """
+ Calculate statistical significance of a signal.
+
+ Args:
+ test_statistic: The test statistic value
+ test_type: Type of test (t_test, f_test, bootstrap)
+ sample_size: Number of observations
+
+ Returns:
+ P-value and significance assessment
+ """
+ # Simplified p-value calculation
+ import math
+ p_value = 2 * (1 - 0.5 * (1 + math.erf(abs(test_statistic) / math.sqrt(2))))
+
+ return {
+ "test_statistic": test_statistic,
+ "test_type": test_type,
+ "sample_size": sample_size,
+ "p_value": p_value,
+ "significant_at_01": p_value < 0.01, # RenTech threshold
+ "significant_at_05": p_value < 0.05,
+ "effect_size": abs(test_statistic) / math.sqrt(sample_size),
+ "power_estimate": 0.85,
+ "recommendation": "APPROVED" if p_value < 0.01 else "NEEDS_MORE_DATA",
+ }
+
+ def check_signal_decay(
+ self,
+ ticker: str,
+ signal_type: str,
+ historical_performance: List[float]
+ ) -> Dict[str, Any]:
+ """
+ Check if a signal is decaying over time.
+
+ Args:
+ ticker: Stock ticker
+ signal_type: Type of signal
+ historical_performance: List of period returns
+
+ Returns:
+ Signal decay analysis
+ """
+ return {
+ "ticker": ticker,
+ "signal_type": signal_type,
+ "decay_detected": False,
+ "decay_rate_monthly": -0.02, # 2% decay per month
+ "half_life_months": 18,
+ "current_strength_vs_peak": 0.85,
+ "regime_sensitivity": 0.3,
+ "crowding_risk": "moderate",
+ "recommendation": "MONITOR",
+ }
+
+ def combine_signals(
+ self,
+ signals: List[Dict[str, Any]],
+ combination_method: str = "weighted_average"
+ ) -> Dict[str, Any]:
+ """
+ Combine multiple signals into a composite signal.
+
+ Args:
+ signals: List of individual signals
+ combination_method: How to combine (weighted_average, voting, ml_ensemble)
+
+ Returns:
+ Combined signal
+ """
+ return {
+ "method": combination_method,
+ "num_signals": len(signals),
+ "composite_signal": 0.65,
+ "composite_direction": "long",
+ "signal_agreement": 0.8, # 80% agree on direction
+ "diversification_benefit": 0.25,
+ "correlation_among_signals": 0.35,
+ "weights_used": {
+ "momentum": 0.3,
+ "mean_reversion": 0.35,
+ "statistical_arbitrage": 0.35,
+ },
+ "confidence": 0.72,
+ }
+
+ def calculate_information_coefficient(
+ self,
+ predictions: List[float],
+ actual_returns: List[float]
+ ) -> Dict[str, Any]:
+ """
+ Calculate Information Coefficient (IC) for signal quality.
+
+ Args:
+ predictions: Signal predictions
+ actual_returns: Realized returns
+
+ Returns:
+ IC metrics
+ """
+ return {
+ "ic": 0.05, # 5% IC is very good
+ "ic_t_stat": 3.2,
+ "ic_p_value": 0.001,
+ "ic_ir": 0.8, # IC / std(IC)
+ "hit_rate": 0.52,
+ "quintile_spread": 0.08, # 8% spread top to bottom quintile
+ "ic_stability": 0.75, # How consistent is IC over time
+ }
+
+ def analyze_regime_dependency(
+ self,
+ ticker: str,
+ signal_type: str,
+ regimes: List[str]
+ ) -> Dict[str, Any]:
+ """
+ Analyze how signal performs across market regimes.
+
+ Args:
+ ticker: Stock ticker
+ signal_type: Type of signal
+ regimes: Regimes to analyze
+
+ Returns:
+ Regime-dependent performance
+ """
+ return {
+ "ticker": ticker,
+ "signal_type": signal_type,
+ "regime_performance": {
+ "bull_market": {"sharpe": 2.5, "win_rate": 0.55},
+ "bear_market": {"sharpe": 0.8, "win_rate": 0.48},
+ "high_volatility": {"sharpe": 1.2, "win_rate": 0.51},
+ "low_volatility": {"sharpe": 2.8, "win_rate": 0.54},
+ "crisis": {"sharpe": -0.5, "win_rate": 0.42},
+ },
+ "regime_sensitivity_score": 0.6, # Higher = more regime dependent
+ "current_regime": "bull_market",
+ "regime_adjusted_expectation": 0.025, # 2.5% expected return
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/config.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/config.py
new file mode 100644
index 000000000..fe513c540
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/config.py
@@ -0,0 +1,294 @@
+"""
+Renaissance Technologies Multi-Agent System Configuration
+
+Central configuration for all agents, teams, and system settings.
+"""
+
+from dataclasses import dataclass, field
+from typing import Dict, Any, Optional, List
+from enum import Enum
+
+
+class ModelProvider(str, Enum):
+ """Supported model providers"""
+ OPENAI = "openai"
+ ANTHROPIC = "anthropic"
+ OLLAMA = "ollama"
+ GROQ = "groq"
+ ZHIPUAI = "zhipuai"
+
+
+@dataclass
+class ModelConfig:
+ """
+ Configuration for AI models.
+
+ These are fallback/template values only.
+ Actual model settings are loaded dynamically from frontend config via model_factory.
+ """
+ provider: ModelProvider = ModelProvider.OPENAI
+ model_id: str = "gpt-4o" # Fallback only, loaded from frontend
+ temperature: float = 0.7
+ max_tokens: int = 4096
+
+ # Reasoning model (for complex decisions)
+ reasoning_model_id: str = "gpt-4o" # Fallback only
+ reasoning_min_steps: int = 3
+ reasoning_max_steps: int = 10
+
+ # Memory model (for memory operations)
+ memory_model_id: str = "gpt-4o-mini" # Fallback only
+
+ # API credentials (loaded from frontend config or environment)
+ anthropic_api_key: str = ""
+ anthropic_base_url: str = ""
+
+ zhipuai_api_key: str = ""
+ zhipuai_base_url: str = ""
+
+
+@dataclass
+class DatabaseConfig:
+ """
+ Database configuration.
+
+ All paths use proper application data directories:
+ - Windows: %APPDATA%\\fincept-terminal\\rentech\\
+ - macOS: ~/Library/Application Support/fincept-terminal/rentech/
+ - Linux: ~/.local/share/fincept-terminal/rentech/
+ """
+ # SQLite for local development (uses AppData)
+ sqlite_path: Optional[str] = None # Auto-set to AppData location
+
+ # Frontend SQLite database (for LLM configs)
+ frontend_db_path: Optional[str] = None # Auto-detected from AppData
+
+ # PostgreSQL for production (optional)
+ postgres_url: Optional[str] = None
+
+ # Vector database for knowledge
+ vector_db_type: str = "lancedb" # or "pgvector", "chromadb"
+ vector_db_path: Optional[str] = None # Auto-set to AppData location
+
+
+@dataclass
+class RiskLimits:
+ """Risk management limits (RenTech style)"""
+ # Position limits
+ max_position_size_pct: float = 5.0 # Max 5% per position
+ max_sector_exposure_pct: float = 25.0 # Max 25% per sector
+ max_single_name_pct: float = 2.0 # Max 2% in single name
+
+ # Portfolio limits
+ max_leverage: float = 12.5 # RenTech uses high leverage
+ max_drawdown_pct: float = 15.0 # Max 15% drawdown
+ max_daily_var_pct: float = 2.0 # Max 2% daily VaR
+
+ # Trade limits
+ max_daily_trades: int = 150000 # RenTech does 150k+ trades/day
+ max_order_size_adv_pct: float = 1.0 # Max 1% of ADV
+
+ # Signal thresholds
+ min_signal_confidence: float = 0.5075 # "Right 50.75% of the time"
+ min_p_value: float = 0.01 # Statistical significance threshold
+
+
+@dataclass
+class ExecutionConfig:
+ """Trade execution configuration"""
+ # Execution algorithms
+ default_algo: str = "twap" # TWAP, VWAP, Arrival Price
+ max_participation_rate: float = 0.05 # Max 5% of volume
+
+ # Timing
+ execution_window_hours: float = 4.0 # Spread orders over 4 hours
+ urgency_threshold: float = 0.8 # When to use aggressive execution
+
+ # Cost thresholds
+ max_slippage_bps: float = 5.0 # Max 5 bps slippage
+ max_market_impact_bps: float = 10.0 # Max 10 bps impact
+
+
+@dataclass
+class WorkflowConfig:
+ """Workflow execution configuration"""
+ # Timeouts (seconds)
+ step_timeout: int = 60
+ workflow_timeout: int = 300
+
+ # Retries
+ max_retries: int = 3
+ retry_delay: float = 1.0
+
+ # Parallel execution
+ max_parallel_tasks: int = 5
+
+
+@dataclass
+class MemoryConfig:
+ """Memory system configuration"""
+ # Memory retention
+ short_term_memory_hours: int = 24
+ long_term_memory_days: int = 365
+
+ # Memory limits
+ max_memories_per_agent: int = 1000
+ max_context_memories: int = 20
+
+ # Learning rate
+ memory_importance_threshold: float = 0.5
+
+
+@dataclass
+class TracingConfig:
+ """Observability and tracing configuration"""
+ enabled: bool = True
+ service_name: str = "rentech_agents"
+
+ # Export destinations
+ export_to_db: bool = True
+ export_to_console: bool = False
+ export_to_jaeger: bool = False
+ jaeger_endpoint: Optional[str] = None
+
+ # Sampling
+ sample_rate: float = 1.0 # 100% sampling
+
+
+@dataclass
+class RenTechConfig:
+ """
+ Master configuration for Renaissance Technologies Multi-Agent System.
+
+ This mirrors the actual configuration parameters that a real
+ quantitative trading firm would use.
+ """
+ # Core settings
+ name: str = "Renaissance Technologies Medallion Fund"
+ environment: str = "development" # development, staging, production
+
+ # Sub-configurations
+ models: ModelConfig = field(default_factory=ModelConfig)
+ database: DatabaseConfig = field(default_factory=DatabaseConfig)
+ risk_limits: RiskLimits = field(default_factory=RiskLimits)
+ execution: ExecutionConfig = field(default_factory=ExecutionConfig)
+ workflow: WorkflowConfig = field(default_factory=WorkflowConfig)
+ memory: MemoryConfig = field(default_factory=MemoryConfig)
+ tracing: TracingConfig = field(default_factory=TracingConfig)
+
+ # Feature flags
+ enable_reasoning: bool = True
+ enable_memory: bool = True
+ enable_knowledge: bool = True
+ enable_guardrails: bool = True
+ enable_evaluation: bool = True
+ enable_tracing: bool = True
+
+ # Team settings
+ share_interactions: bool = True
+ enable_delegation: bool = True
+ delegation_mode: str = "intelligent" # intelligent, round_robin, broadcast
+
+ @classmethod
+ def development(cls) -> "RenTechConfig":
+ """
+ Configuration for development environment.
+
+ Model settings loaded dynamically from frontend config.
+ """
+ return cls(
+ environment="development",
+ models=ModelConfig(), # Use defaults (loaded from frontend)
+ tracing=TracingConfig(
+ export_to_console=True,
+ ),
+ )
+
+ @classmethod
+ def production(cls) -> "RenTechConfig":
+ """
+ Configuration for production environment.
+
+ Model settings loaded dynamically from frontend config.
+ """
+ return cls(
+ environment="production",
+ models=ModelConfig(
+ temperature=0.3, # More deterministic in production
+ ),
+ tracing=TracingConfig(
+ export_to_jaeger=True,
+ sample_rate=0.1, # 10% sampling in prod
+ ),
+ )
+
+ @classmethod
+ def with_openai(cls) -> "RenTechConfig":
+ """Configuration using OpenAI models"""
+ return cls(
+ environment="development",
+ models=ModelConfig(
+ provider=ModelProvider.OPENAI,
+ model_id="gpt-4o",
+ reasoning_model_id="gpt-4o",
+ memory_model_id="gpt-4o-mini",
+ ),
+ )
+
+
+# Global configuration instance
+_config: Optional[RenTechConfig] = None
+
+
+def get_config() -> RenTechConfig:
+ """
+ Get the global configuration.
+
+ Automatically sets paths to proper application data directories.
+ """
+ global _config
+ if _config is None:
+ _config = RenTechConfig.development()
+
+ # Auto-configure paths using cross-platform utilities
+ try:
+ from .utils.paths import (
+ get_memory_path,
+ get_knowledge_path,
+ get_frontend_db_path,
+ )
+
+ # Set database paths if not already configured
+ if _config.database.sqlite_path is None:
+ _config.database.sqlite_path = get_memory_path()
+
+ if _config.database.vector_db_path is None:
+ _config.database.vector_db_path = get_knowledge_path()
+
+ if _config.database.frontend_db_path is None:
+ frontend_db = get_frontend_db_path()
+ if frontend_db:
+ _config.database.frontend_db_path = str(frontend_db)
+
+ except ImportError as e:
+ # Fallback to relative paths if utils not available (shouldn't happen)
+ import logging
+ logging.warning(f"Could not import path utilities: {e}")
+ if _config.database.sqlite_path is None:
+ _config.database.sqlite_path = "rentech_memory.db"
+ if _config.database.vector_db_path is None:
+ _config.database.vector_db_path = "./rentech_knowledge"
+
+ return _config
+
+
+def set_config(config: RenTechConfig):
+ """Set the global configuration"""
+ global _config
+ _config = config
+
+
+def reset_config():
+ """Reset configuration to default"""
+ global _config
+ _config = None
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/__init__.py
new file mode 100644
index 000000000..b34172df1
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/__init__.py
@@ -0,0 +1,40 @@
+"""
+Renaissance Technologies Evaluation System
+
+Evaluation framework for agent performance:
+- Signal quality evaluation
+- Trade outcome evaluation
+- Agent performance metrics
+- Team effectiveness analysis
+- System health monitoring
+"""
+
+from .base import (
+ Evaluator,
+ EvaluationResult,
+ EvaluationMetric,
+ EvaluationRegistry,
+ get_evaluation_registry,
+)
+from .signal_evaluation import SignalEvaluator, get_signal_evaluator
+from .trade_evaluation import TradeEvaluator, get_trade_evaluator
+from .agent_evaluation import AgentEvaluator, get_agent_evaluator
+from .system_evaluation import SystemEvaluator, get_system_evaluator
+
+__all__ = [
+ # Base
+ "Evaluator",
+ "EvaluationResult",
+ "EvaluationMetric",
+ "EvaluationRegistry",
+ "get_evaluation_registry",
+ # Specialized evaluators
+ "SignalEvaluator",
+ "get_signal_evaluator",
+ "TradeEvaluator",
+ "get_trade_evaluator",
+ "AgentEvaluator",
+ "get_agent_evaluator",
+ "SystemEvaluator",
+ "get_system_evaluator",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/agent_evaluation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/agent_evaluation.py
new file mode 100644
index 000000000..a1b38cf06
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/agent_evaluation.py
@@ -0,0 +1,356 @@
+"""
+Agent Evaluation
+
+Evaluates individual agent performance:
+- Decision accuracy
+- Response quality
+- Task completion
+- Learning effectiveness
+"""
+
+from typing import Optional, List, Dict, Any
+from datetime import datetime
+import statistics
+import uuid
+
+from .base import (
+ Evaluator,
+ EvaluationResult,
+ EvaluationMetric,
+ EvaluationLevel,
+ MetricType,
+)
+from ..config import get_config
+
+
+class AgentEvaluator(Evaluator):
+ """
+ Evaluates individual agent performance.
+
+ Key metrics:
+ - Decision accuracy
+ - Response quality
+ - Task completion rate
+ - Learning from feedback
+ - Consistency
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="agent_evaluator",
+ description="Evaluates individual agent performance",
+ level=EvaluationLevel.AGENT,
+ )
+
+ def evaluate(self, context: Dict[str, Any]) -> EvaluationResult:
+ """
+ Evaluate agent performance.
+
+ Context should contain:
+ - agent_id: ID of the agent to evaluate
+ - decisions: List of decisions made by the agent
+ - tasks: List of tasks completed
+ - feedback: Feedback received
+ """
+ agent_id = context.get("agent_id", "unknown")
+ decisions = context.get("decisions", [])
+ tasks = context.get("tasks", [])
+ feedback = context.get("feedback", [])
+
+ result = EvaluationResult(
+ evaluation_id=f"agent_eval_{uuid.uuid4().hex[:8]}",
+ level=self.level,
+ subject=f"Agent: {agent_id}",
+ )
+
+ # Evaluate different aspects
+ self._evaluate_decision_accuracy(result, decisions)
+ self._evaluate_task_completion(result, tasks)
+ self._evaluate_response_quality(result, decisions, tasks)
+ self._evaluate_learning(result, decisions, feedback)
+ self._evaluate_consistency(result, decisions)
+
+ # Calculate overall score
+ result.calculate_overall_score()
+
+ # Generate summary
+ result.summary = self._generate_summary(result, agent_id)
+ result.findings = self._generate_findings(result)
+ result.recommendations = self._generate_recommendations(result)
+
+ self._history.append(result)
+ return result
+
+ def _evaluate_decision_accuracy(
+ self,
+ result: EvaluationResult,
+ decisions: List[Dict[str, Any]],
+ ):
+ """Evaluate decision accuracy"""
+ if not decisions:
+ return
+
+ # Overall accuracy
+ correct = len([d for d in decisions if d.get("outcome") == "correct"])
+ incorrect = len([d for d in decisions if d.get("outcome") == "incorrect"])
+ total = correct + incorrect
+
+ if total > 0:
+ accuracy = correct / total
+ result.add_metric(EvaluationMetric(
+ name="decision_accuracy",
+ value=accuracy,
+ metric_type=MetricType.ACCURACY,
+ unit="%",
+ target=0.70,
+ warning_threshold=0.60,
+ critical_threshold=0.50,
+ ))
+
+ # Accuracy by decision type
+ by_type = {}
+ for d in decisions:
+ d_type = d.get("decision_type", "unknown")
+ if d_type not in by_type:
+ by_type[d_type] = {"correct": 0, "total": 0}
+ by_type[d_type]["total"] += 1
+ if d.get("outcome") == "correct":
+ by_type[d_type]["correct"] += 1
+
+ for d_type, counts in by_type.items():
+ if counts["total"] > 0:
+ accuracy = counts["correct"] / counts["total"]
+ result.add_metric(EvaluationMetric(
+ name=f"{d_type}_accuracy",
+ value=accuracy,
+ metric_type=MetricType.ACCURACY,
+ unit="%",
+ ))
+
+ # P&L impact of decisions
+ pnl_impacts = [
+ d.get("pnl_impact_bps", 0)
+ for d in decisions
+ if d.get("pnl_impact_bps") is not None
+ ]
+
+ if pnl_impacts:
+ total_pnl = sum(pnl_impacts)
+ result.add_metric(EvaluationMetric(
+ name="total_pnl_impact_bps",
+ value=total_pnl,
+ metric_type=MetricType.PROFIT,
+ unit="bps",
+ ))
+
+ def _evaluate_task_completion(
+ self,
+ result: EvaluationResult,
+ tasks: List[Dict[str, Any]],
+ ):
+ """Evaluate task completion"""
+ if not tasks:
+ return
+
+ completed = len([t for t in tasks if t.get("status") == "completed"])
+ failed = len([t for t in tasks if t.get("status") == "failed"])
+ total = len(tasks)
+
+ # Completion rate
+ completion_rate = completed / total if total > 0 else 0
+ result.add_metric(EvaluationMetric(
+ name="task_completion_rate",
+ value=completion_rate,
+ metric_type=MetricType.ACCURACY,
+ unit="%",
+ target=0.95,
+ warning_threshold=0.90,
+ critical_threshold=0.80,
+ ))
+
+ # Average completion time
+ completion_times = [
+ t.get("completion_time_seconds", 0)
+ for t in tasks
+ if t.get("status") == "completed" and t.get("completion_time_seconds")
+ ]
+
+ if completion_times:
+ avg_time = statistics.mean(completion_times)
+ result.add_metric(EvaluationMetric(
+ name="avg_task_completion_time_seconds",
+ value=avg_time,
+ metric_type=MetricType.LATENCY,
+ unit="seconds",
+ ))
+
+ def _evaluate_response_quality(
+ self,
+ result: EvaluationResult,
+ decisions: List[Dict[str, Any]],
+ tasks: List[Dict[str, Any]],
+ ):
+ """Evaluate response quality"""
+ quality_scores = []
+
+ # Get quality ratings from decisions
+ for d in decisions:
+ if d.get("quality_score"):
+ quality_scores.append(d["quality_score"])
+
+ # Get quality ratings from tasks
+ for t in tasks:
+ if t.get("quality_score"):
+ quality_scores.append(t["quality_score"])
+
+ if quality_scores:
+ avg_quality = statistics.mean(quality_scores)
+ result.add_metric(EvaluationMetric(
+ name="avg_response_quality",
+ value=avg_quality,
+ metric_type=MetricType.QUALITY,
+ target=0.8,
+ warning_threshold=0.7,
+ ))
+
+ def _evaluate_learning(
+ self,
+ result: EvaluationResult,
+ decisions: List[Dict[str, Any]],
+ feedback: List[Dict[str, Any]],
+ ):
+ """Evaluate learning from feedback"""
+ if len(decisions) < 10:
+ return # Need enough data
+
+ # Split into first half and second half
+ mid = len(decisions) // 2
+ first_half = decisions[:mid]
+ second_half = decisions[mid:]
+
+ # Calculate accuracy improvement
+ first_accuracy = len([d for d in first_half if d.get("outcome") == "correct"]) / len(first_half)
+ second_accuracy = len([d for d in second_half if d.get("outcome") == "correct"]) / len(second_half)
+
+ improvement = second_accuracy - first_accuracy
+
+ result.add_metric(EvaluationMetric(
+ name="learning_improvement",
+ value=improvement,
+ metric_type=MetricType.QUALITY,
+ target=0.05, # 5% improvement target
+ ))
+
+ # Feedback incorporation rate
+ if feedback:
+ applied = len([f for f in feedback if f.get("applied", False)])
+ incorporation_rate = applied / len(feedback)
+ result.add_metric(EvaluationMetric(
+ name="feedback_incorporation_rate",
+ value=incorporation_rate,
+ metric_type=MetricType.ACCURACY,
+ unit="%",
+ target=0.8,
+ ))
+
+ def _evaluate_consistency(
+ self,
+ result: EvaluationResult,
+ decisions: List[Dict[str, Any]],
+ ):
+ """Evaluate decision consistency"""
+ if len(decisions) < 5:
+ return
+
+ # Check for contradictory decisions
+ # (Same situation but different decision)
+ contradictions = 0
+ # This would need more sophisticated logic in production
+
+ # Evaluate confidence calibration
+ confidences = [d.get("confidence", 0.5) for d in decisions]
+ outcomes = [1 if d.get("outcome") == "correct" else 0 for d in decisions]
+
+ if confidences and outcomes:
+ # Simple calibration: high confidence should correlate with correct
+ high_conf = [(c, o) for c, o in zip(confidences, outcomes) if c > 0.7]
+ low_conf = [(c, o) for c, o in zip(confidences, outcomes) if c < 0.5]
+
+ if high_conf:
+ high_conf_accuracy = sum(o for _, o in high_conf) / len(high_conf)
+ result.add_metric(EvaluationMetric(
+ name="high_confidence_accuracy",
+ value=high_conf_accuracy,
+ metric_type=MetricType.ACCURACY,
+ unit="%",
+ target=0.75,
+ ))
+
+ def _generate_summary(
+ self,
+ result: EvaluationResult,
+ agent_id: str,
+ ) -> str:
+ """Generate evaluation summary"""
+ summary = f"""
+Agent Performance Evaluation: {agent_id}
+=========================================
+Overall Score: {result.overall_score:.0f}/100 (Grade: {result.grade})
+Status: {result.status.upper()}
+
+""".strip()
+
+ # Add key metrics
+ key_metrics = ["decision_accuracy", "task_completion_rate", "avg_response_quality"]
+ for m in result.metrics:
+ if m.name in key_metrics:
+ status = "PASS" if m.meets_target else "NEEDS IMPROVEMENT"
+ summary += f"\n{m.name}: {m.value:.1%} ({status})"
+
+ return summary
+
+ def _generate_findings(self, result: EvaluationResult) -> List[str]:
+ """Generate key findings"""
+ findings = []
+
+ for m in result.metrics:
+ if m.status == "critical":
+ findings.append(f"CRITICAL: {m.name} below threshold")
+ elif m.status == "warning":
+ findings.append(f"WARNING: {m.name} needs improvement")
+
+ # Add positive findings
+ for m in result.metrics:
+ if m.meets_target and m.name in ["decision_accuracy", "task_completion_rate"]:
+ findings.append(f"GOOD: {m.name} meets target")
+
+ return findings
+
+ def _generate_recommendations(self, result: EvaluationResult) -> List[str]:
+ """Generate recommendations"""
+ recommendations = []
+
+ for m in result.metrics:
+ if not m.meets_target:
+ if "accuracy" in m.name:
+ recommendations.append(f"Review decision criteria for {m.name}")
+ elif "completion" in m.name:
+ recommendations.append("Investigate task failures and bottlenecks")
+ elif "quality" in m.name:
+ recommendations.append("Improve response generation with more context")
+ elif "learning" in m.name:
+ recommendations.append("Enhance feedback loop and memory utilization")
+
+ return list(set(recommendations))
+
+
+# Global instance
+_agent_evaluator: Optional[AgentEvaluator] = None
+
+
+def get_agent_evaluator() -> AgentEvaluator:
+ """Get the global agent evaluator"""
+ global _agent_evaluator
+ if _agent_evaluator is None:
+ _agent_evaluator = AgentEvaluator()
+ return _agent_evaluator
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/base.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/base.py
new file mode 100644
index 000000000..7aa78690b
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/base.py
@@ -0,0 +1,353 @@
+"""
+Base Evaluation Infrastructure
+
+Core evaluation framework for Renaissance Technologies multi-agent system.
+Implements metrics tracking, performance assessment, and continuous improvement.
+"""
+
+from typing import Optional, List, Dict, Any, Callable
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta
+from enum import Enum
+from abc import ABC, abstractmethod
+import statistics
+
+from ..config import get_config
+
+
+class EvaluationLevel(str, Enum):
+ """Levels at which evaluation is performed"""
+ SIGNAL = "signal" # Individual signal quality
+ TRADE = "trade" # Trade outcome
+ AGENT = "agent" # Agent performance
+ TEAM = "team" # Team effectiveness
+ SYSTEM = "system" # Overall system health
+ WORKFLOW = "workflow" # Workflow performance
+
+
+class MetricType(str, Enum):
+ """Types of evaluation metrics"""
+ ACCURACY = "accuracy" # Correctness rate
+ PRECISION = "precision" # True positive rate
+ RECALL = "recall" # Coverage rate
+ F1_SCORE = "f1_score" # Harmonic mean of precision/recall
+ LATENCY = "latency" # Response time
+ THROUGHPUT = "throughput" # Volume processed
+ QUALITY = "quality" # Output quality score
+ PROFIT = "profit" # Financial performance
+ RISK = "risk" # Risk metrics
+
+
+@dataclass
+class EvaluationMetric:
+ """A single evaluation metric"""
+ name: str
+ value: float
+ metric_type: MetricType
+ unit: str = ""
+ timestamp: str = field(default_factory=lambda: datetime.utcnow().isoformat())
+
+ # Comparison thresholds
+ target: Optional[float] = None
+ warning_threshold: Optional[float] = None
+ critical_threshold: Optional[float] = None
+
+ # Historical context
+ previous_value: Optional[float] = None
+ historical_avg: Optional[float] = None
+ percentile: Optional[float] = None
+
+ @property
+ def meets_target(self) -> bool:
+ """Check if metric meets target"""
+ if self.target is None:
+ return True
+ return self.value >= self.target
+
+ @property
+ def status(self) -> str:
+ """Get metric status"""
+ if self.critical_threshold and self.value <= self.critical_threshold:
+ return "critical"
+ if self.warning_threshold and self.value <= self.warning_threshold:
+ return "warning"
+ if self.meets_target:
+ return "good"
+ return "below_target"
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "name": self.name,
+ "value": self.value,
+ "metric_type": self.metric_type.value,
+ "unit": self.unit,
+ "timestamp": self.timestamp,
+ "target": self.target,
+ "meets_target": self.meets_target,
+ "status": self.status,
+ }
+
+
+@dataclass
+class EvaluationResult:
+ """Result of an evaluation"""
+ evaluation_id: str
+ level: EvaluationLevel
+ subject: str # What was evaluated
+
+ # Metrics
+ metrics: List[EvaluationMetric] = field(default_factory=list)
+
+ # Overall assessment
+ overall_score: float = 0.0
+ grade: str = "N/A" # A, B, C, D, F
+ status: str = "unknown" # excellent, good, acceptable, poor, critical
+
+ # Details
+ summary: str = ""
+ findings: List[str] = field(default_factory=list)
+ recommendations: List[str] = field(default_factory=list)
+
+ # Metadata
+ evaluated_at: str = field(default_factory=lambda: datetime.utcnow().isoformat())
+ evaluated_by: str = "system"
+
+ def add_metric(self, metric: EvaluationMetric):
+ """Add a metric to the result"""
+ self.metrics.append(metric)
+
+ def calculate_overall_score(self):
+ """Calculate overall score from metrics"""
+ if not self.metrics:
+ self.overall_score = 0
+ return
+
+ scores = []
+ for metric in self.metrics:
+ if metric.target and metric.target > 0:
+ score = min(100, (metric.value / metric.target) * 100)
+ scores.append(score)
+ elif metric.value > 0:
+ scores.append(min(100, metric.value * 100))
+
+ self.overall_score = statistics.mean(scores) if scores else 0
+ self._assign_grade()
+
+ def _assign_grade(self):
+ """Assign letter grade based on score"""
+ if self.overall_score >= 90:
+ self.grade = "A"
+ self.status = "excellent"
+ elif self.overall_score >= 80:
+ self.grade = "B"
+ self.status = "good"
+ elif self.overall_score >= 70:
+ self.grade = "C"
+ self.status = "acceptable"
+ elif self.overall_score >= 60:
+ self.grade = "D"
+ self.status = "poor"
+ else:
+ self.grade = "F"
+ self.status = "critical"
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "evaluation_id": self.evaluation_id,
+ "level": self.level.value,
+ "subject": self.subject,
+ "metrics": [m.to_dict() for m in self.metrics],
+ "overall_score": self.overall_score,
+ "grade": self.grade,
+ "status": self.status,
+ "summary": self.summary,
+ "findings": self.findings,
+ "recommendations": self.recommendations,
+ "evaluated_at": self.evaluated_at,
+ }
+
+
+class Evaluator(ABC):
+ """
+ Base class for all evaluators.
+
+ Evaluators assess performance at different levels
+ of the system.
+ """
+
+ def __init__(
+ self,
+ name: str,
+ description: str,
+ level: EvaluationLevel,
+ ):
+ self.name = name
+ self.description = description
+ self.level = level
+ self.config = get_config()
+
+ # Historical results
+ self._history: List[EvaluationResult] = []
+
+ @abstractmethod
+ def evaluate(self, context: Dict[str, Any]) -> EvaluationResult:
+ """
+ Perform evaluation.
+
+ Args:
+ context: Data needed for evaluation
+
+ Returns:
+ EvaluationResult with metrics and assessment
+ """
+ pass
+
+ def get_history(
+ self,
+ limit: int = 100,
+ since: Optional[datetime] = None,
+ ) -> List[EvaluationResult]:
+ """Get historical evaluation results"""
+ results = self._history
+
+ if since:
+ results = [
+ r for r in results
+ if datetime.fromisoformat(r.evaluated_at) >= since
+ ]
+
+ return results[-limit:]
+
+ def get_trend(
+ self,
+ metric_name: str,
+ periods: int = 10,
+ ) -> Dict[str, Any]:
+ """Get trend for a specific metric"""
+ history = self.get_history(limit=periods)
+
+ values = []
+ for result in history:
+ for metric in result.metrics:
+ if metric.name == metric_name:
+ values.append(metric.value)
+ break
+
+ if len(values) < 2:
+ return {"trend": "insufficient_data", "values": values}
+
+ # Calculate trend
+ avg_first_half = statistics.mean(values[:len(values)//2])
+ avg_second_half = statistics.mean(values[len(values)//2:])
+
+ if avg_second_half > avg_first_half * 1.05:
+ trend = "improving"
+ elif avg_second_half < avg_first_half * 0.95:
+ trend = "declining"
+ else:
+ trend = "stable"
+
+ return {
+ "trend": trend,
+ "values": values,
+ "avg_first_half": avg_first_half,
+ "avg_second_half": avg_second_half,
+ "change_pct": (avg_second_half - avg_first_half) / avg_first_half * 100 if avg_first_half else 0,
+ }
+
+
+class EvaluationRegistry:
+ """
+ Registry for all evaluators in the system.
+ """
+
+ def __init__(self):
+ self._evaluators: Dict[str, Evaluator] = {}
+
+ def register(self, evaluator: Evaluator):
+ """Register an evaluator"""
+ self._evaluators[evaluator.name] = evaluator
+
+ def get(self, name: str) -> Optional[Evaluator]:
+ """Get an evaluator by name"""
+ return self._evaluators.get(name)
+
+ def get_by_level(self, level: EvaluationLevel) -> List[Evaluator]:
+ """Get all evaluators for a level"""
+ return [e for e in self._evaluators.values() if e.level == level]
+
+ def evaluate_all(
+ self,
+ level: Optional[EvaluationLevel] = None,
+ context: Optional[Dict[str, Any]] = None,
+ ) -> List[EvaluationResult]:
+ """Run all evaluators (or for specific level)"""
+ results = []
+ context = context or {}
+
+ evaluators = (
+ self.get_by_level(level) if level
+ else list(self._evaluators.values())
+ )
+
+ for evaluator in evaluators:
+ try:
+ result = evaluator.evaluate(context)
+ results.append(result)
+ except Exception as e:
+ # Create error result
+ results.append(EvaluationResult(
+ evaluation_id=f"error_{evaluator.name}",
+ level=evaluator.level,
+ subject=evaluator.name,
+ overall_score=0,
+ status="error",
+ summary=f"Evaluation failed: {str(e)}",
+ ))
+
+ return results
+
+ def get_system_health(self) -> Dict[str, Any]:
+ """Get overall system health from all evaluators"""
+ results = self.evaluate_all()
+
+ scores = [r.overall_score for r in results if r.overall_score > 0]
+ statuses = [r.status for r in results]
+
+ return {
+ "overall_health": statistics.mean(scores) if scores else 0,
+ "evaluations_run": len(results),
+ "status_distribution": {
+ status: statuses.count(status)
+ for status in set(statuses)
+ },
+ "critical_issues": [
+ r.subject for r in results if r.status == "critical"
+ ],
+ }
+
+
+# Global registry instance
+_evaluation_registry: Optional[EvaluationRegistry] = None
+
+
+def get_evaluation_registry() -> EvaluationRegistry:
+ """Get the global evaluation registry"""
+ global _evaluation_registry
+ if _evaluation_registry is None:
+ _evaluation_registry = EvaluationRegistry()
+ _register_default_evaluators(_evaluation_registry)
+ return _evaluation_registry
+
+
+def _register_default_evaluators(registry: EvaluationRegistry):
+ """Register default evaluators"""
+ from .signal_evaluation import SignalEvaluator
+ from .trade_evaluation import TradeEvaluator
+ from .agent_evaluation import AgentEvaluator
+ from .system_evaluation import SystemEvaluator
+
+ registry.register(SignalEvaluator())
+ registry.register(TradeEvaluator())
+ registry.register(AgentEvaluator())
+ registry.register(SystemEvaluator())
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/signal_evaluation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/signal_evaluation.py
new file mode 100644
index 000000000..1c6f09362
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/signal_evaluation.py
@@ -0,0 +1,406 @@
+"""
+Signal Evaluation
+
+Evaluates the quality and performance of trading signals:
+- Statistical validity
+- Predictive accuracy
+- Risk-adjusted returns
+- Signal decay analysis
+"""
+
+from typing import Optional, List, Dict, Any
+from datetime import datetime, timedelta
+import statistics
+import uuid
+
+from .base import (
+ Evaluator,
+ EvaluationResult,
+ EvaluationMetric,
+ EvaluationLevel,
+ MetricType,
+)
+from ..config import get_config
+
+
+class SignalEvaluator(Evaluator):
+ """
+ Evaluates trading signal quality and performance.
+
+ Key metrics:
+ - Win rate (signals that were profitable)
+ - Average return per signal
+ - Information coefficient (IC)
+ - Hit rate (signals > threshold)
+ - False positive rate
+ - Signal-to-noise ratio
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="signal_evaluator",
+ description="Evaluates trading signal quality and performance",
+ level=EvaluationLevel.SIGNAL,
+ )
+
+ # Targets based on RenTech standards
+ self.target_win_rate = 0.5075 # "Right 50.75% of the time"
+ self.target_ic = 0.05 # Information coefficient
+ self.target_sharpe = 2.0 # High Sharpe target
+ self.min_p_value = 0.01
+
+ def evaluate(self, context: Dict[str, Any]) -> EvaluationResult:
+ """
+ Evaluate signal quality.
+
+ Context should contain:
+ - signals: List of signal objects with outcomes
+ - period: Evaluation period
+ """
+ signals = context.get("signals", [])
+ period = context.get("period", "unknown")
+
+ result = EvaluationResult(
+ evaluation_id=f"signal_eval_{uuid.uuid4().hex[:8]}",
+ level=self.level,
+ subject=f"Signal Quality ({period})",
+ )
+
+ if not signals:
+ result.summary = "No signals to evaluate"
+ result.overall_score = 0
+ return result
+
+ # Calculate metrics
+ self._evaluate_win_rate(result, signals)
+ self._evaluate_returns(result, signals)
+ self._evaluate_statistical_quality(result, signals)
+ self._evaluate_signal_timing(result, signals)
+ self._evaluate_by_type(result, signals)
+
+ # Calculate overall score
+ result.calculate_overall_score()
+
+ # Generate summary
+ result.summary = self._generate_summary(result)
+ result.findings = self._generate_findings(result, signals)
+ result.recommendations = self._generate_recommendations(result, signals)
+
+ # Store in history
+ self._history.append(result)
+
+ return result
+
+ def _evaluate_win_rate(
+ self,
+ result: EvaluationResult,
+ signals: List[Dict[str, Any]],
+ ):
+ """Evaluate signal win rate"""
+ winning = [s for s in signals if s.get("pnl_bps", 0) > 0]
+ losing = [s for s in signals if s.get("pnl_bps", 0) < 0]
+ breakeven = [s for s in signals if s.get("pnl_bps", 0) == 0]
+
+ total = len(signals)
+ win_rate = len(winning) / total if total > 0 else 0
+
+ result.add_metric(EvaluationMetric(
+ name="win_rate",
+ value=win_rate,
+ metric_type=MetricType.ACCURACY,
+ unit="%",
+ target=self.target_win_rate,
+ warning_threshold=0.50,
+ critical_threshold=0.48,
+ ))
+
+ # Profit factor
+ gross_profit = sum(s.get("pnl_bps", 0) for s in winning)
+ gross_loss = abs(sum(s.get("pnl_bps", 0) for s in losing))
+ profit_factor = gross_profit / gross_loss if gross_loss > 0 else float('inf')
+
+ result.add_metric(EvaluationMetric(
+ name="profit_factor",
+ value=min(profit_factor, 10), # Cap for display
+ metric_type=MetricType.PROFIT,
+ target=1.5,
+ warning_threshold=1.0,
+ ))
+
+ def _evaluate_returns(
+ self,
+ result: EvaluationResult,
+ signals: List[Dict[str, Any]],
+ ):
+ """Evaluate return metrics"""
+ returns = [s.get("pnl_bps", 0) for s in signals]
+
+ if not returns:
+ return
+
+ # Average return
+ avg_return = statistics.mean(returns)
+ result.add_metric(EvaluationMetric(
+ name="avg_return_bps",
+ value=avg_return,
+ metric_type=MetricType.PROFIT,
+ unit="bps",
+ target=10,
+ warning_threshold=0,
+ ))
+
+ # Return volatility
+ if len(returns) > 1:
+ return_vol = statistics.stdev(returns)
+ result.add_metric(EvaluationMetric(
+ name="return_volatility_bps",
+ value=return_vol,
+ metric_type=MetricType.RISK,
+ unit="bps",
+ ))
+
+ # Sharpe-like ratio
+ sharpe = avg_return / return_vol if return_vol > 0 else 0
+ result.add_metric(EvaluationMetric(
+ name="signal_sharpe",
+ value=sharpe,
+ metric_type=MetricType.QUALITY,
+ target=self.target_sharpe,
+ warning_threshold=1.0,
+ ))
+
+ # Max return and max loss
+ result.add_metric(EvaluationMetric(
+ name="max_return_bps",
+ value=max(returns),
+ metric_type=MetricType.PROFIT,
+ unit="bps",
+ ))
+
+ result.add_metric(EvaluationMetric(
+ name="max_loss_bps",
+ value=min(returns),
+ metric_type=MetricType.RISK,
+ unit="bps",
+ ))
+
+ def _evaluate_statistical_quality(
+ self,
+ result: EvaluationResult,
+ signals: List[Dict[str, Any]],
+ ):
+ """Evaluate statistical quality of signals"""
+ p_values = [s.get("p_value") for s in signals if s.get("p_value") is not None]
+
+ if not p_values:
+ return
+
+ # Average p-value
+ avg_p_value = statistics.mean(p_values)
+ result.add_metric(EvaluationMetric(
+ name="avg_p_value",
+ value=avg_p_value,
+ metric_type=MetricType.QUALITY,
+ target=self.min_p_value,
+ ))
+
+ # Percentage meeting p-value threshold
+ passing = len([p for p in p_values if p < self.min_p_value])
+ pass_rate = passing / len(p_values)
+ result.add_metric(EvaluationMetric(
+ name="p_value_pass_rate",
+ value=pass_rate,
+ metric_type=MetricType.ACCURACY,
+ unit="%",
+ target=0.95,
+ warning_threshold=0.80,
+ ))
+
+ # Information coefficient (correlation between signal and outcome)
+ confidences = [s.get("confidence", 0.5) for s in signals]
+ returns = [s.get("pnl_bps", 0) for s in signals]
+
+ if len(confidences) > 2:
+ try:
+ # Simplified IC calculation
+ ic = self._calculate_ic(confidences, returns)
+ result.add_metric(EvaluationMetric(
+ name="information_coefficient",
+ value=ic,
+ metric_type=MetricType.QUALITY,
+ target=self.target_ic,
+ warning_threshold=0.02,
+ ))
+ except:
+ pass
+
+ def _calculate_ic(self, predictions: List[float], outcomes: List[float]) -> float:
+ """Calculate Information Coefficient (Spearman correlation)"""
+ n = len(predictions)
+ if n < 3:
+ return 0
+
+ # Rank both series
+ pred_ranks = self._rank(predictions)
+ outcome_ranks = self._rank(outcomes)
+
+ # Spearman correlation
+ d_squared = sum((p - o) ** 2 for p, o in zip(pred_ranks, outcome_ranks))
+ ic = 1 - (6 * d_squared) / (n * (n**2 - 1))
+
+ return ic
+
+ def _rank(self, values: List[float]) -> List[float]:
+ """Calculate ranks for a list of values"""
+ sorted_idx = sorted(range(len(values)), key=lambda i: values[i])
+ ranks = [0] * len(values)
+ for rank, idx in enumerate(sorted_idx):
+ ranks[idx] = rank + 1
+ return ranks
+
+ def _evaluate_signal_timing(
+ self,
+ result: EvaluationResult,
+ signals: List[Dict[str, Any]],
+ ):
+ """Evaluate signal timing and decay"""
+ # Average holding period
+ holding_periods = [
+ s.get("holding_period_days", 0)
+ for s in signals
+ if s.get("holding_period_days") is not None
+ ]
+
+ if holding_periods:
+ avg_holding = statistics.mean(holding_periods)
+ result.add_metric(EvaluationMetric(
+ name="avg_holding_period_days",
+ value=avg_holding,
+ metric_type=MetricType.LATENCY,
+ unit="days",
+ ))
+
+ # Signal age at execution
+ ages = [
+ s.get("execution_delay_minutes", 0)
+ for s in signals
+ if s.get("execution_delay_minutes") is not None
+ ]
+
+ if ages:
+ avg_age = statistics.mean(ages)
+ result.add_metric(EvaluationMetric(
+ name="avg_execution_delay_minutes",
+ value=avg_age,
+ metric_type=MetricType.LATENCY,
+ unit="minutes",
+ target=30, # Execute within 30 minutes
+ warning_threshold=60,
+ ))
+
+ def _evaluate_by_type(
+ self,
+ result: EvaluationResult,
+ signals: List[Dict[str, Any]],
+ ):
+ """Evaluate by signal type"""
+ by_type = {}
+ for s in signals:
+ signal_type = s.get("signal_type", "unknown")
+ if signal_type not in by_type:
+ by_type[signal_type] = []
+ by_type[signal_type].append(s)
+
+ for signal_type, type_signals in by_type.items():
+ returns = [s.get("pnl_bps", 0) for s in type_signals]
+ winning = len([r for r in returns if r > 0])
+
+ result.add_metric(EvaluationMetric(
+ name=f"{signal_type}_win_rate",
+ value=winning / len(returns) if returns else 0,
+ metric_type=MetricType.ACCURACY,
+ unit="%",
+ ))
+
+ result.add_metric(EvaluationMetric(
+ name=f"{signal_type}_avg_return",
+ value=statistics.mean(returns) if returns else 0,
+ metric_type=MetricType.PROFIT,
+ unit="bps",
+ ))
+
+ def _generate_summary(self, result: EvaluationResult) -> str:
+ """Generate evaluation summary"""
+ win_rate = None
+ sharpe = None
+ ic = None
+
+ for m in result.metrics:
+ if m.name == "win_rate":
+ win_rate = m.value
+ elif m.name == "signal_sharpe":
+ sharpe = m.value
+ elif m.name == "information_coefficient":
+ ic = m.value
+
+ summary = f"Signal Quality Score: {result.overall_score:.0f}/100 (Grade: {result.grade})\n"
+
+ if win_rate:
+ summary += f"Win Rate: {win_rate:.1%} "
+ summary += "(PASS)" if win_rate >= self.target_win_rate else "(BELOW TARGET)"
+ summary += "\n"
+
+ if sharpe:
+ summary += f"Signal Sharpe: {sharpe:.2f}\n"
+
+ if ic:
+ summary += f"Information Coefficient: {ic:.3f}\n"
+
+ return summary
+
+ def _generate_findings(
+ self,
+ result: EvaluationResult,
+ signals: List[Dict[str, Any]],
+ ) -> List[str]:
+ """Generate key findings"""
+ findings = []
+
+ for metric in result.metrics:
+ if metric.status == "critical":
+ findings.append(f"CRITICAL: {metric.name} at {metric.value:.4f} (threshold: {metric.critical_threshold})")
+ elif metric.status == "warning":
+ findings.append(f"WARNING: {metric.name} at {metric.value:.4f} (threshold: {metric.warning_threshold})")
+
+ return findings
+
+ def _generate_recommendations(
+ self,
+ result: EvaluationResult,
+ signals: List[Dict[str, Any]],
+ ) -> List[str]:
+ """Generate recommendations"""
+ recommendations = []
+
+ for metric in result.metrics:
+ if not metric.meets_target and metric.target:
+ if "win_rate" in metric.name:
+ recommendations.append("Review signal generation parameters to improve win rate")
+ elif "p_value" in metric.name:
+ recommendations.append("Increase statistical significance threshold for signal acceptance")
+ elif "sharpe" in metric.name:
+ recommendations.append("Consider reducing position sizes or improving signal quality")
+
+ return recommendations
+
+
+# Global instance
+_signal_evaluator: Optional[SignalEvaluator] = None
+
+
+def get_signal_evaluator() -> SignalEvaluator:
+ """Get the global signal evaluator"""
+ global _signal_evaluator
+ if _signal_evaluator is None:
+ _signal_evaluator = SignalEvaluator()
+ return _signal_evaluator
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/system_evaluation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/system_evaluation.py
new file mode 100644
index 000000000..640194e4c
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/system_evaluation.py
@@ -0,0 +1,377 @@
+"""
+System Evaluation
+
+Evaluates overall system health and performance:
+- System uptime and reliability
+- Resource utilization
+- Component health
+- End-to-end latency
+"""
+
+from typing import Optional, List, Dict, Any
+from datetime import datetime, timedelta
+import statistics
+import uuid
+
+from .base import (
+ Evaluator,
+ EvaluationResult,
+ EvaluationMetric,
+ EvaluationLevel,
+ MetricType,
+)
+from ..config import get_config
+
+
+class SystemEvaluator(Evaluator):
+ """
+ Evaluates overall system health and performance.
+
+ Key metrics:
+ - System availability
+ - End-to-end latency
+ - Throughput
+ - Error rates
+ - Resource utilization
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="system_evaluator",
+ description="Evaluates overall system health and performance",
+ level=EvaluationLevel.SYSTEM,
+ )
+
+ def evaluate(self, context: Dict[str, Any]) -> EvaluationResult:
+ """
+ Evaluate system health.
+
+ Context should contain:
+ - uptime_pct: System uptime percentage
+ - requests: List of request/response data
+ - errors: List of errors
+ - resources: Resource utilization data
+ - components: Component health data
+ """
+ result = EvaluationResult(
+ evaluation_id=f"system_eval_{uuid.uuid4().hex[:8]}",
+ level=self.level,
+ subject="System Health",
+ )
+
+ # Evaluate different aspects
+ self._evaluate_availability(result, context)
+ self._evaluate_latency(result, context)
+ self._evaluate_throughput(result, context)
+ self._evaluate_errors(result, context)
+ self._evaluate_resources(result, context)
+ self._evaluate_components(result, context)
+
+ # Calculate overall score
+ result.calculate_overall_score()
+
+ # Generate summary
+ result.summary = self._generate_summary(result)
+ result.findings = self._generate_findings(result)
+ result.recommendations = self._generate_recommendations(result)
+
+ self._history.append(result)
+ return result
+
+ def _evaluate_availability(
+ self,
+ result: EvaluationResult,
+ context: Dict[str, Any],
+ ):
+ """Evaluate system availability"""
+ uptime_pct = context.get("uptime_pct", 100)
+
+ result.add_metric(EvaluationMetric(
+ name="system_uptime",
+ value=uptime_pct,
+ metric_type=MetricType.ACCURACY,
+ unit="%",
+ target=99.9, # 3 nines
+ warning_threshold=99.5,
+ critical_threshold=99.0,
+ ))
+
+ # Calculate downtime
+ downtime_minutes = (100 - uptime_pct) / 100 * 24 * 60 # Per day
+ result.add_metric(EvaluationMetric(
+ name="estimated_daily_downtime_minutes",
+ value=downtime_minutes,
+ metric_type=MetricType.LATENCY,
+ unit="minutes",
+ ))
+
+ def _evaluate_latency(
+ self,
+ result: EvaluationResult,
+ context: Dict[str, Any],
+ ):
+ """Evaluate system latency"""
+ requests = context.get("requests", [])
+
+ latencies = [
+ r.get("latency_ms", 0)
+ for r in requests
+ if r.get("latency_ms") is not None
+ ]
+
+ if not latencies:
+ return
+
+ # Average latency
+ avg_latency = statistics.mean(latencies)
+ result.add_metric(EvaluationMetric(
+ name="avg_latency_ms",
+ value=avg_latency,
+ metric_type=MetricType.LATENCY,
+ unit="ms",
+ target=100, # 100ms target
+ warning_threshold=500,
+ critical_threshold=1000,
+ ))
+
+ # P95 latency
+ sorted_latencies = sorted(latencies)
+ p95_idx = int(len(sorted_latencies) * 0.95)
+ p95_latency = sorted_latencies[p95_idx] if sorted_latencies else 0
+
+ result.add_metric(EvaluationMetric(
+ name="p95_latency_ms",
+ value=p95_latency,
+ metric_type=MetricType.LATENCY,
+ unit="ms",
+ target=500,
+ warning_threshold=1000,
+ ))
+
+ # P99 latency
+ p99_idx = int(len(sorted_latencies) * 0.99)
+ p99_latency = sorted_latencies[p99_idx] if sorted_latencies else 0
+
+ result.add_metric(EvaluationMetric(
+ name="p99_latency_ms",
+ value=p99_latency,
+ metric_type=MetricType.LATENCY,
+ unit="ms",
+ ))
+
+ def _evaluate_throughput(
+ self,
+ result: EvaluationResult,
+ context: Dict[str, Any],
+ ):
+ """Evaluate system throughput"""
+ requests = context.get("requests", [])
+ time_window_seconds = context.get("time_window_seconds", 3600) # Default 1 hour
+
+ if requests and time_window_seconds > 0:
+ throughput = len(requests) / time_window_seconds * 60 # Per minute
+ result.add_metric(EvaluationMetric(
+ name="requests_per_minute",
+ value=throughput,
+ metric_type=MetricType.THROUGHPUT,
+ unit="req/min",
+ ))
+
+ # Signals processed
+ signals_processed = context.get("signals_processed", 0)
+ if signals_processed:
+ result.add_metric(EvaluationMetric(
+ name="signals_processed",
+ value=signals_processed,
+ metric_type=MetricType.THROUGHPUT,
+ ))
+
+ # Trades executed
+ trades_executed = context.get("trades_executed", 0)
+ if trades_executed:
+ result.add_metric(EvaluationMetric(
+ name="trades_executed",
+ value=trades_executed,
+ metric_type=MetricType.THROUGHPUT,
+ ))
+
+ def _evaluate_errors(
+ self,
+ result: EvaluationResult,
+ context: Dict[str, Any],
+ ):
+ """Evaluate error rates"""
+ errors = context.get("errors", [])
+ requests = context.get("requests", [])
+
+ total_requests = len(requests)
+ total_errors = len(errors)
+
+ if total_requests > 0:
+ error_rate = total_errors / total_requests
+ result.add_metric(EvaluationMetric(
+ name="error_rate",
+ value=error_rate,
+ metric_type=MetricType.ACCURACY,
+ unit="%",
+ target=0.001, # 0.1% target
+ warning_threshold=0.01,
+ critical_threshold=0.05,
+ ))
+
+ # Error breakdown by type
+ if errors:
+ error_types = {}
+ for e in errors:
+ e_type = e.get("type", "unknown")
+ error_types[e_type] = error_types.get(e_type, 0) + 1
+
+ for e_type, count in error_types.items():
+ result.add_metric(EvaluationMetric(
+ name=f"errors_{e_type}",
+ value=count,
+ metric_type=MetricType.QUALITY,
+ ))
+
+ def _evaluate_resources(
+ self,
+ result: EvaluationResult,
+ context: Dict[str, Any],
+ ):
+ """Evaluate resource utilization"""
+ resources = context.get("resources", {})
+
+ # CPU utilization
+ cpu_pct = resources.get("cpu_percent", 0)
+ if cpu_pct:
+ result.add_metric(EvaluationMetric(
+ name="cpu_utilization",
+ value=cpu_pct,
+ metric_type=MetricType.QUALITY,
+ unit="%",
+ target=70, # Want to stay under 70%
+ warning_threshold=80,
+ critical_threshold=90,
+ ))
+
+ # Memory utilization
+ memory_pct = resources.get("memory_percent", 0)
+ if memory_pct:
+ result.add_metric(EvaluationMetric(
+ name="memory_utilization",
+ value=memory_pct,
+ metric_type=MetricType.QUALITY,
+ unit="%",
+ target=70,
+ warning_threshold=80,
+ critical_threshold=90,
+ ))
+
+ # Disk utilization
+ disk_pct = resources.get("disk_percent", 0)
+ if disk_pct:
+ result.add_metric(EvaluationMetric(
+ name="disk_utilization",
+ value=disk_pct,
+ metric_type=MetricType.QUALITY,
+ unit="%",
+ target=70,
+ warning_threshold=80,
+ critical_threshold=90,
+ ))
+
+ def _evaluate_components(
+ self,
+ result: EvaluationResult,
+ context: Dict[str, Any],
+ ):
+ """Evaluate component health"""
+ components = context.get("components", {})
+
+ healthy = 0
+ unhealthy = 0
+
+ for name, status in components.items():
+ is_healthy = status.get("healthy", True)
+ if is_healthy:
+ healthy += 1
+ else:
+ unhealthy += 1
+ result.add_metric(EvaluationMetric(
+ name=f"component_{name}_status",
+ value=0,
+ metric_type=MetricType.QUALITY,
+ ))
+
+ total = healthy + unhealthy
+ if total > 0:
+ health_rate = healthy / total
+ result.add_metric(EvaluationMetric(
+ name="component_health_rate",
+ value=health_rate,
+ metric_type=MetricType.ACCURACY,
+ unit="%",
+ target=1.0,
+ warning_threshold=0.9,
+ critical_threshold=0.8,
+ ))
+
+ def _generate_summary(self, result: EvaluationResult) -> str:
+ """Generate system health summary"""
+ summary = f"""
+System Health Evaluation
+========================
+Overall Score: {result.overall_score:.0f}/100 (Grade: {result.grade})
+Status: {result.status.upper()}
+
+""".strip()
+
+ # Key metrics
+ key_metrics = ["system_uptime", "avg_latency_ms", "error_rate", "component_health_rate"]
+ for m in result.metrics:
+ if m.name in key_metrics:
+ status = "OK" if m.meets_target else "ISSUE"
+ summary += f"\n{m.name}: {m.value:.2f}{m.unit} ({status})"
+
+ return summary
+
+ def _generate_findings(self, result: EvaluationResult) -> List[str]:
+ """Generate key findings"""
+ findings = []
+
+ for m in result.metrics:
+ if m.status == "critical":
+ findings.append(f"CRITICAL: {m.name} = {m.value:.2f}{m.unit}")
+ elif m.status == "warning":
+ findings.append(f"WARNING: {m.name} = {m.value:.2f}{m.unit}")
+
+ return findings
+
+ def _generate_recommendations(self, result: EvaluationResult) -> List[str]:
+ """Generate recommendations"""
+ recommendations = []
+
+ for m in result.metrics:
+ if not m.meets_target:
+ if "uptime" in m.name:
+ recommendations.append("Investigate availability issues and add redundancy")
+ elif "latency" in m.name:
+ recommendations.append("Optimize slow endpoints and add caching")
+ elif "error" in m.name:
+ recommendations.append("Review error logs and fix recurring issues")
+ elif "cpu" in m.name or "memory" in m.name:
+ recommendations.append("Scale resources or optimize resource usage")
+
+ return list(set(recommendations))
+
+
+# Global instance
+_system_evaluator: Optional[SystemEvaluator] = None
+
+
+def get_system_evaluator() -> SystemEvaluator:
+ """Get the global system evaluator"""
+ global _system_evaluator
+ if _system_evaluator is None:
+ _system_evaluator = SystemEvaluator()
+ return _system_evaluator
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/trade_evaluation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/trade_evaluation.py
new file mode 100644
index 000000000..3b192f048
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/evaluation/trade_evaluation.py
@@ -0,0 +1,390 @@
+"""
+Trade Evaluation
+
+Evaluates trade execution and outcomes:
+- Execution quality
+- Slippage analysis
+- Market impact assessment
+- P&L attribution
+"""
+
+from typing import Optional, List, Dict, Any
+from datetime import datetime
+import statistics
+import uuid
+
+from .base import (
+ Evaluator,
+ EvaluationResult,
+ EvaluationMetric,
+ EvaluationLevel,
+ MetricType,
+)
+from ..config import get_config
+
+
+class TradeEvaluator(Evaluator):
+ """
+ Evaluates trade execution quality and outcomes.
+
+ Key metrics:
+ - Execution quality (vs arrival, vs VWAP)
+ - Slippage
+ - Market impact
+ - Fill rate
+ - P&L analysis
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="trade_evaluator",
+ description="Evaluates trade execution and outcomes",
+ level=EvaluationLevel.TRADE,
+ )
+
+ def evaluate(self, context: Dict[str, Any]) -> EvaluationResult:
+ """
+ Evaluate trade execution.
+
+ Context should contain:
+ - trades: List of trade objects with execution details
+ - period: Evaluation period
+ """
+ trades = context.get("trades", [])
+ period = context.get("period", "unknown")
+
+ result = EvaluationResult(
+ evaluation_id=f"trade_eval_{uuid.uuid4().hex[:8]}",
+ level=self.level,
+ subject=f"Trade Execution ({period})",
+ )
+
+ if not trades:
+ result.summary = "No trades to evaluate"
+ result.overall_score = 0
+ return result
+
+ # Evaluate different aspects
+ self._evaluate_execution_quality(result, trades)
+ self._evaluate_slippage(result, trades)
+ self._evaluate_market_impact(result, trades)
+ self._evaluate_fill_quality(result, trades)
+ self._evaluate_pnl(result, trades)
+ self._evaluate_by_algorithm(result, trades)
+
+ # Calculate overall score
+ result.calculate_overall_score()
+
+ # Generate summary
+ result.summary = self._generate_summary(result, trades)
+ result.findings = self._generate_findings(result)
+ result.recommendations = self._generate_recommendations(result)
+
+ self._history.append(result)
+ return result
+
+ def _evaluate_execution_quality(
+ self,
+ result: EvaluationResult,
+ trades: List[Dict[str, Any]],
+ ):
+ """Evaluate execution quality benchmarks"""
+ # vs Arrival Price
+ vs_arrival = [
+ t.get("vs_arrival_bps", 0)
+ for t in trades
+ if t.get("vs_arrival_bps") is not None
+ ]
+
+ if vs_arrival:
+ avg_vs_arrival = statistics.mean(vs_arrival)
+ result.add_metric(EvaluationMetric(
+ name="avg_vs_arrival_bps",
+ value=avg_vs_arrival,
+ metric_type=MetricType.QUALITY,
+ unit="bps",
+ target=-1, # Want to beat arrival by 1 bps
+ warning_threshold=2, # Warning if 2 bps worse
+ critical_threshold=5, # Critical if 5 bps worse
+ ))
+
+ # vs VWAP
+ vs_vwap = [
+ t.get("vs_vwap_bps", 0)
+ for t in trades
+ if t.get("vs_vwap_bps") is not None
+ ]
+
+ if vs_vwap:
+ avg_vs_vwap = statistics.mean(vs_vwap)
+ result.add_metric(EvaluationMetric(
+ name="avg_vs_vwap_bps",
+ value=avg_vs_vwap,
+ metric_type=MetricType.QUALITY,
+ unit="bps",
+ target=0, # Match VWAP
+ warning_threshold=3,
+ ))
+
+ # Implementation shortfall
+ shortfall = [
+ t.get("implementation_shortfall_bps", 0)
+ for t in trades
+ if t.get("implementation_shortfall_bps") is not None
+ ]
+
+ if shortfall:
+ avg_shortfall = statistics.mean(shortfall)
+ result.add_metric(EvaluationMetric(
+ name="avg_implementation_shortfall_bps",
+ value=avg_shortfall,
+ metric_type=MetricType.QUALITY,
+ unit="bps",
+ target=5,
+ warning_threshold=10,
+ critical_threshold=20,
+ ))
+
+ def _evaluate_slippage(
+ self,
+ result: EvaluationResult,
+ trades: List[Dict[str, Any]],
+ ):
+ """Evaluate slippage"""
+ slippage = [
+ t.get("slippage_bps", 0)
+ for t in trades
+ if t.get("slippage_bps") is not None
+ ]
+
+ if slippage:
+ avg_slippage = statistics.mean(slippage)
+ result.add_metric(EvaluationMetric(
+ name="avg_slippage_bps",
+ value=avg_slippage,
+ metric_type=MetricType.QUALITY,
+ unit="bps",
+ target=2,
+ warning_threshold=5,
+ critical_threshold=10,
+ ))
+
+ # Slippage volatility
+ if len(slippage) > 1:
+ slippage_vol = statistics.stdev(slippage)
+ result.add_metric(EvaluationMetric(
+ name="slippage_volatility_bps",
+ value=slippage_vol,
+ metric_type=MetricType.RISK,
+ unit="bps",
+ ))
+
+ def _evaluate_market_impact(
+ self,
+ result: EvaluationResult,
+ trades: List[Dict[str, Any]],
+ ):
+ """Evaluate market impact"""
+ impact = [
+ t.get("market_impact_bps", 0)
+ for t in trades
+ if t.get("market_impact_bps") is not None
+ ]
+
+ if impact:
+ avg_impact = statistics.mean(impact)
+ result.add_metric(EvaluationMetric(
+ name="avg_market_impact_bps",
+ value=avg_impact,
+ metric_type=MetricType.RISK,
+ unit="bps",
+ target=5,
+ warning_threshold=10,
+ critical_threshold=20,
+ ))
+
+ # Max impact
+ max_impact = max(impact)
+ result.add_metric(EvaluationMetric(
+ name="max_market_impact_bps",
+ value=max_impact,
+ metric_type=MetricType.RISK,
+ unit="bps",
+ ))
+
+ def _evaluate_fill_quality(
+ self,
+ result: EvaluationResult,
+ trades: List[Dict[str, Any]],
+ ):
+ """Evaluate fill quality"""
+ fill_rates = [
+ t.get("fill_rate", 1.0)
+ for t in trades
+ if t.get("fill_rate") is not None
+ ]
+
+ if fill_rates:
+ avg_fill_rate = statistics.mean(fill_rates)
+ result.add_metric(EvaluationMetric(
+ name="avg_fill_rate",
+ value=avg_fill_rate,
+ metric_type=MetricType.ACCURACY,
+ unit="%",
+ target=0.98,
+ warning_threshold=0.95,
+ critical_threshold=0.90,
+ ))
+
+ # Execution time
+ exec_times = [
+ t.get("execution_time_minutes", 0)
+ for t in trades
+ if t.get("execution_time_minutes") is not None
+ ]
+
+ if exec_times:
+ avg_exec_time = statistics.mean(exec_times)
+ result.add_metric(EvaluationMetric(
+ name="avg_execution_time_minutes",
+ value=avg_exec_time,
+ metric_type=MetricType.LATENCY,
+ unit="minutes",
+ ))
+
+ def _evaluate_pnl(
+ self,
+ result: EvaluationResult,
+ trades: List[Dict[str, Any]],
+ ):
+ """Evaluate P&L"""
+ pnl_bps = [
+ t.get("pnl_bps", 0)
+ for t in trades
+ if t.get("pnl_bps") is not None
+ ]
+
+ if pnl_bps:
+ # Total P&L
+ total_pnl = sum(pnl_bps)
+ result.add_metric(EvaluationMetric(
+ name="total_pnl_bps",
+ value=total_pnl,
+ metric_type=MetricType.PROFIT,
+ unit="bps",
+ ))
+
+ # Average P&L per trade
+ avg_pnl = statistics.mean(pnl_bps)
+ result.add_metric(EvaluationMetric(
+ name="avg_pnl_per_trade_bps",
+ value=avg_pnl,
+ metric_type=MetricType.PROFIT,
+ unit="bps",
+ target=5,
+ warning_threshold=0,
+ ))
+
+ # Win rate
+ winners = len([p for p in pnl_bps if p > 0])
+ win_rate = winners / len(pnl_bps)
+ result.add_metric(EvaluationMetric(
+ name="trade_win_rate",
+ value=win_rate,
+ metric_type=MetricType.ACCURACY,
+ unit="%",
+ target=0.5075,
+ ))
+
+ def _evaluate_by_algorithm(
+ self,
+ result: EvaluationResult,
+ trades: List[Dict[str, Any]],
+ ):
+ """Evaluate by execution algorithm"""
+ by_algo = {}
+ for t in trades:
+ algo = t.get("algorithm", "unknown")
+ if algo not in by_algo:
+ by_algo[algo] = []
+ by_algo[algo].append(t)
+
+ for algo, algo_trades in by_algo.items():
+ vs_arrival = [
+ t.get("vs_arrival_bps", 0)
+ for t in algo_trades
+ if t.get("vs_arrival_bps") is not None
+ ]
+
+ if vs_arrival:
+ result.add_metric(EvaluationMetric(
+ name=f"{algo}_avg_vs_arrival_bps",
+ value=statistics.mean(vs_arrival),
+ metric_type=MetricType.QUALITY,
+ unit="bps",
+ ))
+
+ def _generate_summary(
+ self,
+ result: EvaluationResult,
+ trades: List[Dict[str, Any]],
+ ) -> str:
+ """Generate evaluation summary"""
+ total_trades = len(trades)
+ total_notional = sum(t.get("notional", 0) for t in trades)
+
+ summary = f"""
+Trade Execution Evaluation
+==========================
+Total Trades: {total_trades:,}
+Total Notional: ${total_notional:,.0f}
+Overall Score: {result.overall_score:.0f}/100 (Grade: {result.grade})
+
+""".strip()
+
+ # Add key metrics
+ for m in result.metrics:
+ if m.name in ["avg_vs_arrival_bps", "avg_slippage_bps", "avg_market_impact_bps"]:
+ status = "PASS" if m.meets_target else "FAIL"
+ summary += f"\n{m.name}: {m.value:.2f} bps ({status})"
+
+ return summary
+
+ def _generate_findings(self, result: EvaluationResult) -> List[str]:
+ """Generate key findings"""
+ findings = []
+
+ for m in result.metrics:
+ if m.status == "critical":
+ findings.append(f"CRITICAL: {m.name} = {m.value:.2f} {m.unit}")
+ elif m.status == "warning":
+ findings.append(f"WARNING: {m.name} = {m.value:.2f} {m.unit}")
+
+ return findings
+
+ def _generate_recommendations(self, result: EvaluationResult) -> List[str]:
+ """Generate recommendations"""
+ recommendations = []
+
+ for m in result.metrics:
+ if not m.meets_target:
+ if "slippage" in m.name:
+ recommendations.append("Consider more passive execution algorithms")
+ elif "impact" in m.name:
+ recommendations.append("Reduce participation rate or extend execution window")
+ elif "fill_rate" in m.name:
+ recommendations.append("Review order pricing and urgency settings")
+
+ return list(set(recommendations))
+
+
+# Global instance
+_trade_evaluator: Optional[TradeEvaluator] = None
+
+
+def get_trade_evaluator() -> TradeEvaluator:
+ """Get the global trade evaluator"""
+ global _trade_evaluator
+ if _trade_evaluator is None:
+ _trade_evaluator = TradeEvaluator()
+ return _trade_evaluator
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/__init__.py
new file mode 100644
index 000000000..212473d5a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/__init__.py
@@ -0,0 +1,73 @@
+"""
+Renaissance Technologies Guardrails System
+
+Safety and compliance guardrails for the multi-agent system:
+- Risk limit enforcement
+- Compliance checks
+- Position limit validation
+- Trade validation
+- Input/output validation
+"""
+
+from .base import (
+ Guardrail,
+ GuardrailResult,
+ GuardrailSeverity,
+ GuardrailRegistry,
+ get_guardrail_registry,
+)
+from .risk_guardrails import (
+ PositionSizeGuardrail,
+ SectorExposureGuardrail,
+ VaRLimitGuardrail,
+ DrawdownGuardrail,
+ LeverageGuardrail,
+)
+from .compliance_guardrails import (
+ RestrictedListGuardrail,
+ InsiderTradingGuardrail,
+ TradeTimeGuardrail,
+ ComplianceApprovalGuardrail,
+)
+from .signal_guardrails import (
+ PValueGuardrail,
+ SampleSizeGuardrail,
+ SignalConfidenceGuardrail,
+ DataQualityGuardrail,
+)
+from .execution_guardrails import (
+ LiquidityGuardrail,
+ MarketImpactGuardrail,
+ ExecutionTimeGuardrail,
+ PriceDeviationGuardrail,
+)
+
+__all__ = [
+ # Base
+ "Guardrail",
+ "GuardrailResult",
+ "GuardrailSeverity",
+ "GuardrailRegistry",
+ "get_guardrail_registry",
+ # Risk guardrails
+ "PositionSizeGuardrail",
+ "SectorExposureGuardrail",
+ "VaRLimitGuardrail",
+ "DrawdownGuardrail",
+ "LeverageGuardrail",
+ # Compliance guardrails
+ "RestrictedListGuardrail",
+ "InsiderTradingGuardrail",
+ "TradeTimeGuardrail",
+ "ComplianceApprovalGuardrail",
+ # Signal guardrails
+ "PValueGuardrail",
+ "SampleSizeGuardrail",
+ "SignalConfidenceGuardrail",
+ "DataQualityGuardrail",
+ # Execution guardrails
+ "LiquidityGuardrail",
+ "MarketImpactGuardrail",
+ "ExecutionTimeGuardrail",
+ "PriceDeviationGuardrail",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/base.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/base.py
new file mode 100644
index 000000000..3de62715c
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/base.py
@@ -0,0 +1,372 @@
+"""
+Base Guardrail Infrastructure
+
+Core guardrail system for Renaissance Technologies multi-agent architecture.
+Implements validation, enforcement, and monitoring of trading constraints.
+"""
+
+from typing import Optional, List, Dict, Any, Callable, Type
+from dataclasses import dataclass, field
+from datetime import datetime
+from enum import Enum
+from abc import ABC, abstractmethod
+import uuid
+
+from ..config import get_config
+
+
+class GuardrailSeverity(str, Enum):
+ """Severity levels for guardrail violations"""
+ INFO = "info" # Informational only
+ WARNING = "warning" # Caution, but allowed to proceed
+ ERROR = "error" # Must be addressed before proceeding
+ CRITICAL = "critical" # Hard block, cannot proceed
+
+
+class GuardrailAction(str, Enum):
+ """Actions to take on guardrail trigger"""
+ ALLOW = "allow" # Allow to proceed
+ WARN = "warn" # Warn but allow
+ MODIFY = "modify" # Modify the request to comply
+ BLOCK = "block" # Block the action
+ ESCALATE = "escalate" # Escalate to human
+
+
+@dataclass
+class GuardrailResult:
+ """Result of a guardrail check"""
+ guardrail_name: str
+ passed: bool
+ severity: GuardrailSeverity
+ action: GuardrailAction
+
+ # Details
+ message: str
+ details: Dict[str, Any] = field(default_factory=dict)
+
+ # Modification (if action is MODIFY)
+ modified_value: Optional[Any] = None
+ original_value: Optional[Any] = None
+
+ # Metadata
+ timestamp: str = field(default_factory=lambda: datetime.utcnow().isoformat())
+ guardrail_id: str = field(default_factory=lambda: uuid.uuid4().hex[:8])
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary"""
+ return {
+ "guardrail_name": self.guardrail_name,
+ "passed": self.passed,
+ "severity": self.severity.value,
+ "action": self.action.value,
+ "message": self.message,
+ "details": self.details,
+ "modified_value": self.modified_value,
+ "original_value": self.original_value,
+ "timestamp": self.timestamp,
+ "guardrail_id": self.guardrail_id,
+ }
+
+
+class Guardrail(ABC):
+ """
+ Base class for all guardrails.
+
+ Guardrails are safety checks that run before, during, or after
+ agent actions to ensure compliance with rules and limits.
+ """
+
+ def __init__(
+ self,
+ name: str,
+ description: str,
+ severity: GuardrailSeverity = GuardrailSeverity.ERROR,
+ enabled: bool = True,
+ ):
+ self.name = name
+ self.description = description
+ self.severity = severity
+ self.enabled = enabled
+ self.config = get_config()
+
+ # Statistics
+ self.total_checks = 0
+ self.violations = 0
+
+ @abstractmethod
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """
+ Check if the guardrail condition is met.
+
+ Args:
+ context: Dictionary containing all relevant data for the check
+
+ Returns:
+ GuardrailResult indicating pass/fail and any actions
+ """
+ pass
+
+ def execute(self, context: Dict[str, Any]) -> GuardrailResult:
+ """
+ Execute the guardrail check with tracking.
+ """
+ if not self.enabled:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message="Guardrail disabled",
+ )
+
+ self.total_checks += 1
+
+ try:
+ result = self.check(context)
+
+ if not result.passed:
+ self.violations += 1
+
+ return result
+
+ except Exception as e:
+ self.violations += 1
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.CRITICAL,
+ action=GuardrailAction.BLOCK,
+ message=f"Guardrail error: {str(e)}",
+ details={"error": str(e)},
+ )
+
+ def get_stats(self) -> Dict[str, Any]:
+ """Get guardrail statistics"""
+ return {
+ "name": self.name,
+ "enabled": self.enabled,
+ "total_checks": self.total_checks,
+ "violations": self.violations,
+ "violation_rate": self.violations / self.total_checks if self.total_checks > 0 else 0,
+ }
+
+
+class CompositeGuardrail(Guardrail):
+ """
+ Composite guardrail that combines multiple guardrails.
+ """
+
+ def __init__(
+ self,
+ name: str,
+ description: str,
+ guardrails: List[Guardrail],
+ require_all: bool = True, # If True, all must pass. If False, any can pass
+ ):
+ super().__init__(name, description)
+ self.guardrails = guardrails
+ self.require_all = require_all
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check all sub-guardrails"""
+ results = []
+ all_passed = True
+ any_passed = False
+ highest_severity = GuardrailSeverity.INFO
+ messages = []
+
+ for guardrail in self.guardrails:
+ result = guardrail.execute(context)
+ results.append(result)
+
+ if result.passed:
+ any_passed = True
+ else:
+ all_passed = False
+ messages.append(f"{guardrail.name}: {result.message}")
+
+ # Track highest severity
+ severity_order = [
+ GuardrailSeverity.INFO,
+ GuardrailSeverity.WARNING,
+ GuardrailSeverity.ERROR,
+ GuardrailSeverity.CRITICAL,
+ ]
+ if severity_order.index(result.severity) > severity_order.index(highest_severity):
+ highest_severity = result.severity
+
+ # Determine overall pass/fail
+ passed = all_passed if self.require_all else any_passed
+
+ # Determine action
+ if passed:
+ action = GuardrailAction.ALLOW
+ elif highest_severity == GuardrailSeverity.CRITICAL:
+ action = GuardrailAction.BLOCK
+ elif highest_severity == GuardrailSeverity.ERROR:
+ action = GuardrailAction.BLOCK
+ else:
+ action = GuardrailAction.WARN
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=passed,
+ severity=highest_severity,
+ action=action,
+ message="; ".join(messages) if messages else "All checks passed",
+ details={"sub_results": [r.to_dict() for r in results]},
+ )
+
+
+class GuardrailRegistry:
+ """
+ Registry for all guardrails in the system.
+
+ Manages guardrail registration, lookup, and batch execution.
+ """
+
+ def __init__(self):
+ self._guardrails: Dict[str, Guardrail] = {}
+ self._categories: Dict[str, List[str]] = {}
+
+ def register(
+ self,
+ guardrail: Guardrail,
+ category: str = "default",
+ ):
+ """Register a guardrail"""
+ self._guardrails[guardrail.name] = guardrail
+
+ if category not in self._categories:
+ self._categories[category] = []
+ self._categories[category].append(guardrail.name)
+
+ def get(self, name: str) -> Optional[Guardrail]:
+ """Get a guardrail by name"""
+ return self._guardrails.get(name)
+
+ def get_by_category(self, category: str) -> List[Guardrail]:
+ """Get all guardrails in a category"""
+ names = self._categories.get(category, [])
+ return [self._guardrails[name] for name in names if name in self._guardrails]
+
+ def check_all(
+ self,
+ context: Dict[str, Any],
+ categories: Optional[List[str]] = None,
+ ) -> List[GuardrailResult]:
+ """
+ Run all guardrails (or specific categories) against context.
+ """
+ results = []
+
+ if categories:
+ guardrails = []
+ for cat in categories:
+ guardrails.extend(self.get_by_category(cat))
+ else:
+ guardrails = list(self._guardrails.values())
+
+ for guardrail in guardrails:
+ result = guardrail.execute(context)
+ results.append(result)
+
+ return results
+
+ def check_and_block(
+ self,
+ context: Dict[str, Any],
+ categories: Optional[List[str]] = None,
+ ) -> tuple:
+ """
+ Run all guardrails and return (can_proceed, results).
+ """
+ results = self.check_all(context, categories)
+
+ # Check for blocking violations
+ for result in results:
+ if result.action == GuardrailAction.BLOCK:
+ return False, results
+
+ return True, results
+
+ def get_all_stats(self) -> Dict[str, Any]:
+ """Get statistics for all guardrails"""
+ return {
+ name: guardrail.get_stats()
+ for name, guardrail in self._guardrails.items()
+ }
+
+ def list_guardrails(self) -> List[Dict[str, Any]]:
+ """List all registered guardrails"""
+ return [
+ {
+ "name": g.name,
+ "description": g.description,
+ "severity": g.severity.value,
+ "enabled": g.enabled,
+ }
+ for g in self._guardrails.values()
+ ]
+
+
+# Global registry instance
+_guardrail_registry: Optional[GuardrailRegistry] = None
+
+
+def get_guardrail_registry() -> GuardrailRegistry:
+ """Get the global guardrail registry"""
+ global _guardrail_registry
+ if _guardrail_registry is None:
+ _guardrail_registry = GuardrailRegistry()
+ _register_default_guardrails(_guardrail_registry)
+ return _guardrail_registry
+
+
+def _register_default_guardrails(registry: GuardrailRegistry):
+ """Register default guardrails"""
+ # Import here to avoid circular imports
+ from .risk_guardrails import (
+ PositionSizeGuardrail,
+ SectorExposureGuardrail,
+ VaRLimitGuardrail,
+ DrawdownGuardrail,
+ LeverageGuardrail,
+ )
+ from .compliance_guardrails import (
+ RestrictedListGuardrail,
+ InsiderTradingGuardrail,
+ TradeTimeGuardrail,
+ )
+ from .signal_guardrails import (
+ PValueGuardrail,
+ SampleSizeGuardrail,
+ SignalConfidenceGuardrail,
+ DataQualityGuardrail,
+ )
+ from .execution_guardrails import (
+ LiquidityGuardrail,
+ MarketImpactGuardrail,
+ )
+
+ # Risk guardrails
+ registry.register(PositionSizeGuardrail(), "risk")
+ registry.register(SectorExposureGuardrail(), "risk")
+ registry.register(VaRLimitGuardrail(), "risk")
+ registry.register(DrawdownGuardrail(), "risk")
+ registry.register(LeverageGuardrail(), "risk")
+
+ # Compliance guardrails
+ registry.register(RestrictedListGuardrail(), "compliance")
+ registry.register(InsiderTradingGuardrail(), "compliance")
+ registry.register(TradeTimeGuardrail(), "compliance")
+
+ # Signal guardrails
+ registry.register(PValueGuardrail(), "signal")
+ registry.register(SampleSizeGuardrail(), "signal")
+ registry.register(SignalConfidenceGuardrail(), "signal")
+ registry.register(DataQualityGuardrail(), "signal")
+
+ # Execution guardrails
+ registry.register(LiquidityGuardrail(), "execution")
+ registry.register(MarketImpactGuardrail(), "execution")
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/compliance_guardrails.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/compliance_guardrails.py
new file mode 100644
index 000000000..65359a51a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/compliance_guardrails.py
@@ -0,0 +1,430 @@
+"""
+Compliance Guardrails
+
+Regulatory and compliance guardrails:
+- Restricted securities lists
+- Insider trading prevention
+- Trading time windows
+- Approval requirements
+"""
+
+from typing import Dict, Any, List, Optional
+from datetime import datetime, time
+import pytz
+
+from .base import (
+ Guardrail,
+ GuardrailResult,
+ GuardrailSeverity,
+ GuardrailAction,
+)
+from ..config import get_config
+
+
+class RestrictedListGuardrail(Guardrail):
+ """
+ Checks against restricted securities list.
+
+ Prevents trading in securities that are restricted due to:
+ - Material non-public information
+ - Client relationships
+ - Regulatory restrictions
+ - Corporate actions
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="restricted_list",
+ description="Checks if security is on restricted list",
+ severity=GuardrailSeverity.CRITICAL,
+ )
+
+ # Simulated restricted list
+ # In production, this would be fetched from compliance database
+ self._restricted_securities: Dict[str, str] = {
+ # "TICKER": "reason"
+ }
+
+ # Temporarily restricted (e.g., during earnings)
+ self._temporarily_restricted: Dict[str, dict] = {
+ # "TICKER": {"reason": "...", "until": datetime}
+ }
+
+ def add_to_restricted_list(self, ticker: str, reason: str):
+ """Add a security to the restricted list"""
+ self._restricted_securities[ticker.upper()] = reason
+
+ def add_temporary_restriction(
+ self,
+ ticker: str,
+ reason: str,
+ until: datetime,
+ ):
+ """Add a temporary restriction"""
+ self._temporarily_restricted[ticker.upper()] = {
+ "reason": reason,
+ "until": until,
+ }
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check if security is restricted"""
+ ticker = context.get("ticker", "").upper()
+
+ # Check permanent restricted list
+ if ticker in self._restricted_securities:
+ reason = self._restricted_securities[ticker]
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.CRITICAL,
+ action=GuardrailAction.BLOCK,
+ message=f"{ticker} is on restricted list: {reason}",
+ details={
+ "ticker": ticker,
+ "reason": reason,
+ "restriction_type": "permanent",
+ },
+ )
+
+ # Check temporary restrictions
+ if ticker in self._temporarily_restricted:
+ restriction = self._temporarily_restricted[ticker]
+ until = restriction["until"]
+
+ if datetime.utcnow() < until:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.CRITICAL,
+ action=GuardrailAction.BLOCK,
+ message=f"{ticker} temporarily restricted: {restriction['reason']}",
+ details={
+ "ticker": ticker,
+ "reason": restriction["reason"],
+ "restriction_type": "temporary",
+ "restricted_until": until.isoformat(),
+ },
+ )
+ else:
+ # Restriction expired, remove it
+ del self._temporarily_restricted[ticker]
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"{ticker} not on restricted list",
+ )
+
+
+class InsiderTradingGuardrail(Guardrail):
+ """
+ Prevents potential insider trading.
+
+ Checks for:
+ - Recent corporate communications
+ - Upcoming earnings
+ - Pending M&A
+ - Material events
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="insider_trading_prevention",
+ description="Prevents trading on potential MNPI",
+ severity=GuardrailSeverity.CRITICAL,
+ )
+
+ # Blackout periods
+ self._blackout_periods: Dict[str, dict] = {}
+
+ def add_blackout_period(
+ self,
+ ticker: str,
+ reason: str,
+ start: datetime,
+ end: datetime,
+ ):
+ """Add a blackout period for a security"""
+ self._blackout_periods[ticker.upper()] = {
+ "reason": reason,
+ "start": start,
+ "end": end,
+ }
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check for insider trading concerns"""
+ ticker = context.get("ticker", "").upper()
+ has_corporate_contact = context.get("has_corporate_contact", False)
+ days_to_earnings = context.get("days_to_earnings")
+ pending_ma = context.get("pending_ma", False)
+
+ # Check blackout periods
+ if ticker in self._blackout_periods:
+ period = self._blackout_periods[ticker]
+ now = datetime.utcnow()
+
+ if period["start"] <= now <= period["end"]:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.CRITICAL,
+ action=GuardrailAction.BLOCK,
+ message=f"{ticker} in blackout period: {period['reason']}",
+ details={
+ "ticker": ticker,
+ "reason": period["reason"],
+ "blackout_end": period["end"].isoformat(),
+ },
+ )
+
+ # Check for recent corporate contact (potential MNPI)
+ if has_corporate_contact:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.CRITICAL,
+ action=GuardrailAction.ESCALATE,
+ message=f"Recent corporate contact for {ticker}. Compliance review required.",
+ details={
+ "ticker": ticker,
+ "concern": "potential_mnpi",
+ "action": "compliance_review",
+ },
+ )
+
+ # Check earnings proximity
+ if days_to_earnings is not None and 0 <= days_to_earnings <= 3:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.WARNING,
+ action=GuardrailAction.WARN,
+ message=f"{ticker} earnings in {days_to_earnings} days. Extra caution required.",
+ details={
+ "ticker": ticker,
+ "days_to_earnings": days_to_earnings,
+ },
+ )
+
+ # Check pending M&A
+ if pending_ma:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.CRITICAL,
+ action=GuardrailAction.BLOCK,
+ message=f"{ticker} has pending M&A. Trading blocked.",
+ details={
+ "ticker": ticker,
+ "concern": "pending_ma",
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"No insider trading concerns for {ticker}",
+ )
+
+
+class TradeTimeGuardrail(Guardrail):
+ """
+ Enforces trading time windows.
+
+ Controls:
+ - Market hours trading
+ - Pre/post market restrictions
+ - Holiday schedules
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="trading_time_window",
+ description="Ensures trading during appropriate times",
+ severity=GuardrailSeverity.ERROR,
+ )
+
+ self.market_open = time(9, 30) # 9:30 AM ET
+ self.market_close = time(16, 0) # 4:00 PM ET
+ self.timezone = pytz.timezone("America/New_York")
+
+ # Allow extended hours trading?
+ self.allow_premarket = True
+ self.allow_afterhours = True
+ self.premarket_start = time(4, 0)
+ self.afterhours_end = time(20, 0)
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check if current time is within trading window"""
+ # Get current time in ET
+ now_utc = datetime.utcnow()
+ try:
+ now_et = pytz.utc.localize(now_utc).astimezone(self.timezone)
+ except:
+ now_et = now_utc # Fallback if pytz not available
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message="Time check skipped (timezone unavailable)",
+ )
+
+ current_time = now_et.time()
+ is_weekend = now_et.weekday() >= 5
+
+ # Check weekend
+ if is_weekend:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.BLOCK,
+ message="Markets closed (weekend)",
+ details={
+ "current_day": now_et.strftime("%A"),
+ "reason": "weekend",
+ },
+ )
+
+ # Check regular market hours
+ if self.market_open <= current_time <= self.market_close:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message="Within regular market hours",
+ details={
+ "current_time": current_time.strftime("%H:%M"),
+ "session": "regular",
+ },
+ )
+
+ # Check premarket
+ if self.allow_premarket and self.premarket_start <= current_time < self.market_open:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.WARNING,
+ action=GuardrailAction.WARN,
+ message="Pre-market session (limited liquidity)",
+ details={
+ "current_time": current_time.strftime("%H:%M"),
+ "session": "premarket",
+ "warning": "reduced_liquidity",
+ },
+ )
+
+ # Check after-hours
+ if self.allow_afterhours and self.market_close < current_time <= self.afterhours_end:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.WARNING,
+ action=GuardrailAction.WARN,
+ message="After-hours session (limited liquidity)",
+ details={
+ "current_time": current_time.strftime("%H:%M"),
+ "session": "afterhours",
+ "warning": "reduced_liquidity",
+ },
+ )
+
+ # Outside all trading hours
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.BLOCK,
+ message="Outside trading hours",
+ details={
+ "current_time": current_time.strftime("%H:%M"),
+ "market_open": self.market_open.strftime("%H:%M"),
+ "market_close": self.market_close.strftime("%H:%M"),
+ },
+ )
+
+
+class ComplianceApprovalGuardrail(Guardrail):
+ """
+ Checks for required compliance approvals.
+
+ Certain trades require pre-approval:
+ - Large block trades
+ - Concentrated positions
+ - Related-party transactions
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="compliance_approval",
+ description="Checks for required compliance approvals",
+ severity=GuardrailSeverity.ERROR,
+ )
+
+ # Thresholds requiring approval
+ self.approval_threshold_pct = 3.0 # Positions > 3% need approval
+ self.large_trade_threshold = 10000000 # $10M+ trades need approval
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check if compliance approval is required and obtained"""
+ position_size_pct = context.get("position_size_pct", 0)
+ trade_notional = context.get("trade_notional", 0)
+ has_approval = context.get("compliance_approval", False)
+ ticker = context.get("ticker", "UNKNOWN")
+
+ needs_approval = False
+ reasons = []
+
+ # Check position size threshold
+ if position_size_pct > self.approval_threshold_pct:
+ needs_approval = True
+ reasons.append(f"Position size {position_size_pct:.1f}% > {self.approval_threshold_pct}%")
+
+ # Check trade size threshold
+ if trade_notional > self.large_trade_threshold:
+ needs_approval = True
+ reasons.append(f"Trade notional ${trade_notional:,.0f} > ${self.large_trade_threshold:,.0f}")
+
+ if needs_approval and not has_approval:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.ESCALATE,
+ message=f"Compliance approval required for {ticker}: {'; '.join(reasons)}",
+ details={
+ "ticker": ticker,
+ "reasons": reasons,
+ "position_size_pct": position_size_pct,
+ "trade_notional": trade_notional,
+ "approval_required": True,
+ },
+ )
+
+ if needs_approval and has_approval:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"Compliance approval obtained for {ticker}",
+ details={
+ "ticker": ticker,
+ "approval_required": True,
+ "approval_obtained": True,
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"No additional approval required for {ticker}",
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/execution_guardrails.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/execution_guardrails.py
new file mode 100644
index 000000000..d17ca537a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/execution_guardrails.py
@@ -0,0 +1,407 @@
+"""
+Execution Guardrails
+
+Trade execution guardrails:
+- Liquidity checks
+- Market impact limits
+- Execution timing
+- Price deviation limits
+"""
+
+from typing import Dict, Any, Optional
+from datetime import datetime
+
+from .base import (
+ Guardrail,
+ GuardrailResult,
+ GuardrailSeverity,
+ GuardrailAction,
+)
+from ..config import get_config
+
+
+class LiquidityGuardrail(Guardrail):
+ """
+ Enforces liquidity requirements for trades.
+
+ Ensures order sizes don't exceed a percentage of
+ average daily volume to minimize market impact.
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="liquidity_check",
+ description="Ensures trade size respects liquidity constraints",
+ severity=GuardrailSeverity.ERROR,
+ )
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check trade size against liquidity"""
+ limits = self.config.risk_limits
+ max_adv_pct = limits.max_order_size_adv_pct
+
+ ticker = context.get("ticker", "UNKNOWN")
+ order_shares = context.get("order_shares", 0)
+ adv = context.get("average_daily_volume", 1) # Avoid division by zero
+
+ if adv == 0:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.BLOCK,
+ message=f"No ADV data for {ticker}",
+ details={"ticker": ticker, "adv": 0},
+ )
+
+ adv_pct = (order_shares / adv) * 100
+
+ if adv_pct > max_adv_pct * 100: # Convert to percentage
+ # Calculate maximum allowed shares
+ max_shares = int(adv * max_adv_pct)
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.MODIFY,
+ message=f"{ticker} order ({order_shares:,} shares) is {adv_pct:.1f}% of ADV, exceeds {max_adv_pct*100}% limit",
+ details={
+ "ticker": ticker,
+ "order_shares": order_shares,
+ "adv": adv,
+ "adv_pct": adv_pct,
+ "limit_pct": max_adv_pct * 100,
+ "max_allowed_shares": max_shares,
+ },
+ modified_value=max_shares,
+ original_value=order_shares,
+ )
+
+ # Warning if approaching limit
+ if adv_pct > max_adv_pct * 50: # 50% of limit
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.WARNING,
+ action=GuardrailAction.WARN,
+ message=f"{ticker} order is {adv_pct:.1f}% of ADV, approaching liquidity limit",
+ details={
+ "ticker": ticker,
+ "order_shares": order_shares,
+ "adv_pct": adv_pct,
+ "warning": "high_adv_utilization",
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"{ticker} order size ({adv_pct:.2f}% of ADV) within liquidity limits",
+ details={
+ "ticker": ticker,
+ "order_shares": order_shares,
+ "adv_pct": adv_pct,
+ },
+ )
+
+
+class MarketImpactGuardrail(Guardrail):
+ """
+ Enforces market impact limits.
+
+ Ensures estimated market impact doesn't exceed thresholds.
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="market_impact_limit",
+ description="Ensures estimated market impact is acceptable",
+ severity=GuardrailSeverity.ERROR,
+ )
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check estimated market impact"""
+ limits = self.config.execution
+ max_impact = limits.max_market_impact_bps
+
+ ticker = context.get("ticker", "UNKNOWN")
+ estimated_impact_bps = context.get("estimated_impact_bps", 0)
+
+ if estimated_impact_bps > max_impact:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.MODIFY,
+ message=f"{ticker} estimated impact {estimated_impact_bps:.1f} bps exceeds limit {max_impact} bps",
+ details={
+ "ticker": ticker,
+ "estimated_impact_bps": estimated_impact_bps,
+ "limit_bps": max_impact,
+ "recommendation": "reduce_size_or_extend_duration",
+ },
+ )
+
+ # Warning if high impact
+ if estimated_impact_bps > max_impact * 0.7:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.WARNING,
+ action=GuardrailAction.WARN,
+ message=f"{ticker} estimated impact {estimated_impact_bps:.1f} bps approaching limit",
+ details={
+ "ticker": ticker,
+ "estimated_impact_bps": estimated_impact_bps,
+ "limit_bps": max_impact,
+ "recommendation": "consider_passive_execution",
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"{ticker} estimated impact {estimated_impact_bps:.1f} bps within limits",
+ )
+
+
+class ExecutionTimeGuardrail(Guardrail):
+ """
+ Enforces execution timing constraints.
+
+ Controls when orders can be executed based on:
+ - Time of day
+ - Volatility
+ - News events
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="execution_timing",
+ description="Validates execution timing is appropriate",
+ severity=GuardrailSeverity.WARNING,
+ )
+
+ # Times to avoid (in minutes from market open)
+ self.avoid_first_minutes = 15
+ self.avoid_last_minutes = 15
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check execution timing"""
+ ticker = context.get("ticker", "UNKNOWN")
+ minutes_from_open = context.get("minutes_from_open", 60)
+ minutes_to_close = context.get("minutes_to_close", 60)
+ has_news = context.get("has_recent_news", False)
+ volatility_spike = context.get("volatility_spike", False)
+
+ warnings = []
+
+ # Check market open period
+ if minutes_from_open < self.avoid_first_minutes:
+ warnings.append(f"First {self.avoid_first_minutes} minutes - higher spreads and volatility")
+
+ # Check market close period
+ if minutes_to_close < self.avoid_last_minutes:
+ warnings.append(f"Last {self.avoid_last_minutes} minutes - higher volatility")
+
+ # Check for news
+ if has_news:
+ warnings.append("Recent news detected - elevated volatility risk")
+
+ # Check for volatility spike
+ if volatility_spike:
+ warnings.append("Volatility spike detected - consider delaying")
+
+ if warnings:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True, # Warning only, not blocking
+ severity=GuardrailSeverity.WARNING,
+ action=GuardrailAction.WARN,
+ message=f"{ticker} execution timing warnings: {'; '.join(warnings)}",
+ details={
+ "ticker": ticker,
+ "warnings": warnings,
+ "minutes_from_open": minutes_from_open,
+ "minutes_to_close": minutes_to_close,
+ "has_news": has_news,
+ "volatility_spike": volatility_spike,
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"{ticker} execution timing is optimal",
+ )
+
+
+class PriceDeviationGuardrail(Guardrail):
+ """
+ Monitors price deviation during execution.
+
+ Alerts or blocks if price moves significantly during
+ order execution.
+ """
+
+ def __init__(self, max_deviation_bps: float = 50):
+ super().__init__(
+ name="price_deviation",
+ description="Monitors price deviation during execution",
+ severity=GuardrailSeverity.ERROR,
+ )
+ self.max_deviation_bps = max_deviation_bps
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check price deviation"""
+ ticker = context.get("ticker", "UNKNOWN")
+ reference_price = context.get("reference_price", 0)
+ current_price = context.get("current_price", 0)
+ direction = context.get("direction", "long")
+
+ if reference_price == 0:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message="No reference price, skipping deviation check",
+ )
+
+ deviation_bps = ((current_price - reference_price) / reference_price) * 10000
+
+ # For long orders, price increase is adverse
+ # For short orders, price decrease is adverse
+ if direction == "long":
+ adverse_deviation = deviation_bps # Higher price is bad
+ else:
+ adverse_deviation = -deviation_bps # Lower price is bad
+
+ if adverse_deviation > self.max_deviation_bps:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.BLOCK,
+ message=f"{ticker} price moved adversely by {adverse_deviation:.0f} bps, exceeds {self.max_deviation_bps} bps limit",
+ details={
+ "ticker": ticker,
+ "reference_price": reference_price,
+ "current_price": current_price,
+ "deviation_bps": deviation_bps,
+ "adverse_deviation_bps": adverse_deviation,
+ "limit_bps": self.max_deviation_bps,
+ "direction": direction,
+ "recommendation": "reconsider_or_reprice",
+ },
+ )
+
+ # Warning if significant deviation
+ if abs(deviation_bps) > self.max_deviation_bps * 0.5:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.WARNING,
+ action=GuardrailAction.WARN,
+ message=f"{ticker} price moved {deviation_bps:+.0f} bps from reference",
+ details={
+ "ticker": ticker,
+ "deviation_bps": deviation_bps,
+ "warning": "significant_price_movement",
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"{ticker} price deviation {deviation_bps:+.0f} bps within acceptable range",
+ )
+
+
+class SlippageGuardrail(Guardrail):
+ """
+ Monitors execution slippage.
+
+ Alerts if slippage exceeds expected levels.
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="slippage_monitor",
+ description="Monitors and limits execution slippage",
+ severity=GuardrailSeverity.WARNING,
+ )
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check slippage"""
+ limits = self.config.execution
+ max_slippage = limits.max_slippage_bps
+
+ ticker = context.get("ticker", "UNKNOWN")
+ expected_price = context.get("expected_price", 0)
+ fill_price = context.get("fill_price", 0)
+ direction = context.get("direction", "long")
+
+ if expected_price == 0 or fill_price == 0:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message="Price data incomplete, skipping slippage check",
+ )
+
+ # Calculate slippage (negative = good, positive = bad for longs)
+ if direction == "long":
+ slippage_bps = ((fill_price - expected_price) / expected_price) * 10000
+ else:
+ slippage_bps = ((expected_price - fill_price) / expected_price) * 10000
+
+ if slippage_bps > max_slippage:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.WARNING,
+ action=GuardrailAction.WARN,
+ message=f"{ticker} slippage {slippage_bps:.1f} bps exceeds target {max_slippage} bps",
+ details={
+ "ticker": ticker,
+ "expected_price": expected_price,
+ "fill_price": fill_price,
+ "slippage_bps": slippage_bps,
+ "limit_bps": max_slippage,
+ "direction": direction,
+ },
+ )
+
+ # Good execution
+ if slippage_bps < 0:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"{ticker} achieved price improvement of {-slippage_bps:.1f} bps",
+ details={
+ "ticker": ticker,
+ "slippage_bps": slippage_bps,
+ "quality": "excellent",
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"{ticker} slippage {slippage_bps:.1f} bps within acceptable range",
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/risk_guardrails.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/risk_guardrails.py
new file mode 100644
index 000000000..357eedc74
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/risk_guardrails.py
@@ -0,0 +1,401 @@
+"""
+Risk Guardrails
+
+Risk management guardrails for position and portfolio limits:
+- Position size limits
+- Sector exposure limits
+- VaR limits
+- Drawdown limits
+- Leverage limits
+"""
+
+from typing import Dict, Any, Optional
+from datetime import datetime
+
+from .base import (
+ Guardrail,
+ GuardrailResult,
+ GuardrailSeverity,
+ GuardrailAction,
+)
+from ..config import get_config
+
+
+class PositionSizeGuardrail(Guardrail):
+ """
+ Enforces maximum position size limits.
+
+ RenTech typically limits individual positions to prevent
+ concentration risk and ensure diversification.
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="position_size_limit",
+ description="Ensures position sizes don't exceed maximum limits",
+ severity=GuardrailSeverity.ERROR,
+ )
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check position size against limits"""
+ limits = self.config.risk_limits
+
+ position_size_pct = context.get("position_size_pct", 0)
+ ticker = context.get("ticker", "UNKNOWN")
+ max_single_name = limits.max_single_name_pct
+ max_position = limits.max_position_size_pct
+
+ # Check single name limit
+ if position_size_pct > max_single_name:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.MODIFY,
+ message=f"{ticker} position {position_size_pct:.2f}% exceeds single name limit {max_single_name}%",
+ details={
+ "ticker": ticker,
+ "requested_size": position_size_pct,
+ "limit": max_single_name,
+ "limit_type": "single_name",
+ },
+ modified_value=max_single_name,
+ original_value=position_size_pct,
+ )
+
+ # Check overall position limit
+ if position_size_pct > max_position:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.MODIFY,
+ message=f"{ticker} position {position_size_pct:.2f}% exceeds max position limit {max_position}%",
+ details={
+ "ticker": ticker,
+ "requested_size": position_size_pct,
+ "limit": max_position,
+ "limit_type": "max_position",
+ },
+ modified_value=max_position,
+ original_value=position_size_pct,
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"{ticker} position {position_size_pct:.2f}% within limits",
+ details={
+ "ticker": ticker,
+ "size": position_size_pct,
+ "max_single_name": max_single_name,
+ "max_position": max_position,
+ },
+ )
+
+
+class SectorExposureGuardrail(Guardrail):
+ """
+ Enforces sector concentration limits.
+
+ Prevents excessive exposure to any single sector.
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="sector_exposure_limit",
+ description="Ensures sector exposure doesn't exceed limits",
+ severity=GuardrailSeverity.ERROR,
+ )
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check sector exposure against limits"""
+ limits = self.config.risk_limits
+ max_sector = limits.max_sector_exposure_pct
+
+ sector = context.get("sector", "Unknown")
+ current_sector_exposure = context.get("current_sector_exposure_pct", 0)
+ proposed_addition = context.get("proposed_addition_pct", 0)
+ new_exposure = current_sector_exposure + proposed_addition
+
+ if new_exposure > max_sector:
+ # Calculate how much can be added
+ allowable_addition = max(0, max_sector - current_sector_exposure)
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.MODIFY,
+ message=f"Sector {sector} exposure would be {new_exposure:.1f}%, exceeds limit {max_sector}%",
+ details={
+ "sector": sector,
+ "current_exposure": current_sector_exposure,
+ "proposed_addition": proposed_addition,
+ "new_exposure": new_exposure,
+ "limit": max_sector,
+ "allowable_addition": allowable_addition,
+ },
+ modified_value=allowable_addition,
+ original_value=proposed_addition,
+ )
+
+ # Warning if approaching limit
+ if new_exposure > max_sector * 0.8:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.WARNING,
+ action=GuardrailAction.WARN,
+ message=f"Sector {sector} exposure at {new_exposure:.1f}%, approaching limit {max_sector}%",
+ details={
+ "sector": sector,
+ "new_exposure": new_exposure,
+ "limit": max_sector,
+ "utilization": new_exposure / max_sector * 100,
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"Sector {sector} exposure {new_exposure:.1f}% within limits",
+ )
+
+
+class VaRLimitGuardrail(Guardrail):
+ """
+ Enforces Value at Risk limits.
+
+ Ensures portfolio VaR stays within acceptable bounds.
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="var_limit",
+ description="Ensures VaR doesn't exceed daily limit",
+ severity=GuardrailSeverity.CRITICAL,
+ )
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check VaR against limits"""
+ limits = self.config.risk_limits
+ max_var = limits.max_daily_var_pct
+
+ current_var = context.get("current_var_pct", 0)
+ incremental_var = context.get("incremental_var_pct", 0)
+ post_trade_var = context.get("post_trade_var_pct", current_var + incremental_var)
+
+ if post_trade_var > max_var:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.CRITICAL,
+ action=GuardrailAction.BLOCK,
+ message=f"Post-trade VaR {post_trade_var:.2f}% would exceed limit {max_var}%",
+ details={
+ "current_var": current_var,
+ "incremental_var": incremental_var,
+ "post_trade_var": post_trade_var,
+ "limit": max_var,
+ "excess": post_trade_var - max_var,
+ },
+ )
+
+ # Warning if high utilization
+ utilization = post_trade_var / max_var * 100
+ if utilization > 80:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.WARNING,
+ action=GuardrailAction.WARN,
+ message=f"VaR utilization at {utilization:.0f}%, approaching limit",
+ details={
+ "post_trade_var": post_trade_var,
+ "limit": max_var,
+ "utilization": utilization,
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"VaR {post_trade_var:.2f}% within limit {max_var}%",
+ )
+
+
+class DrawdownGuardrail(Guardrail):
+ """
+ Enforces maximum drawdown limits.
+
+ Triggers risk reduction when drawdown exceeds thresholds.
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="drawdown_limit",
+ description="Monitors drawdown and triggers risk reduction",
+ severity=GuardrailSeverity.ERROR,
+ )
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check current drawdown against limits"""
+ limits = self.config.risk_limits
+ max_drawdown = limits.max_drawdown_pct
+
+ current_drawdown = context.get("current_drawdown_pct", 0)
+ peak_nav = context.get("peak_nav", 0)
+ current_nav = context.get("current_nav", 0)
+
+ # Hard limit breach
+ if current_drawdown > max_drawdown:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.CRITICAL,
+ action=GuardrailAction.BLOCK,
+ message=f"Drawdown {current_drawdown:.1f}% exceeds limit {max_drawdown}%. Risk reduction required.",
+ details={
+ "current_drawdown": current_drawdown,
+ "limit": max_drawdown,
+ "peak_nav": peak_nav,
+ "current_nav": current_nav,
+ "action_required": "reduce_risk",
+ },
+ )
+
+ # Warning level (50% of limit)
+ if current_drawdown > max_drawdown * 0.5:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.WARNING,
+ action=GuardrailAction.WARN,
+ message=f"Drawdown {current_drawdown:.1f}% at {current_drawdown/max_drawdown*100:.0f}% of limit. Increased caution.",
+ details={
+ "current_drawdown": current_drawdown,
+ "limit": max_drawdown,
+ "recommendation": "reduce_position_sizes",
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"Drawdown {current_drawdown:.1f}% within acceptable range",
+ )
+
+
+class LeverageGuardrail(Guardrail):
+ """
+ Enforces leverage limits.
+
+ RenTech uses leverage but within controlled bounds.
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="leverage_limit",
+ description="Ensures leverage stays within limits",
+ severity=GuardrailSeverity.ERROR,
+ )
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check leverage against limits"""
+ limits = self.config.risk_limits
+ max_leverage = limits.max_leverage
+
+ gross_exposure = context.get("gross_exposure_pct", 100)
+ current_leverage = gross_exposure / 100 # Convert to multiplier
+
+ if current_leverage > max_leverage:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.BLOCK,
+ message=f"Leverage {current_leverage:.1f}x exceeds limit {max_leverage}x",
+ details={
+ "current_leverage": current_leverage,
+ "gross_exposure_pct": gross_exposure,
+ "limit": max_leverage,
+ "excess": current_leverage - max_leverage,
+ },
+ )
+
+ # Warning if high utilization
+ utilization = current_leverage / max_leverage * 100
+ if utilization > 80:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.WARNING,
+ action=GuardrailAction.WARN,
+ message=f"Leverage {current_leverage:.1f}x at {utilization:.0f}% of limit",
+ details={
+ "current_leverage": current_leverage,
+ "limit": max_leverage,
+ "utilization": utilization,
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"Leverage {current_leverage:.1f}x within limit {max_leverage}x",
+ )
+
+
+class DailyTradeCountGuardrail(Guardrail):
+ """
+ Monitors daily trade count.
+
+ RenTech does high-frequency trading, but monitors for anomalies.
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="daily_trade_count",
+ description="Monitors daily trade volume",
+ severity=GuardrailSeverity.WARNING,
+ )
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check daily trade count"""
+ limits = self.config.risk_limits
+ max_trades = limits.max_daily_trades
+
+ current_trades = context.get("daily_trade_count", 0)
+
+ if current_trades > max_trades:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.WARNING,
+ action=GuardrailAction.WARN,
+ message=f"Daily trades {current_trades:,} exceeds typical volume {max_trades:,}",
+ details={
+ "current_trades": current_trades,
+ "typical_max": max_trades,
+ "excess_pct": (current_trades - max_trades) / max_trades * 100,
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"Daily trade count {current_trades:,} within normal range",
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/signal_guardrails.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/signal_guardrails.py
new file mode 100644
index 000000000..8ea53c519
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/guardrails/signal_guardrails.py
@@ -0,0 +1,382 @@
+"""
+Signal Guardrails
+
+Quality guardrails for trading signals:
+- Statistical significance
+- Sample size requirements
+- Confidence thresholds
+- Data quality checks
+"""
+
+from typing import Dict, Any, Optional
+from datetime import datetime
+
+from .base import (
+ Guardrail,
+ GuardrailResult,
+ GuardrailSeverity,
+ GuardrailAction,
+)
+from ..config import get_config
+
+
+class PValueGuardrail(Guardrail):
+ """
+ Enforces statistical significance requirements.
+
+ RenTech famously requires p-values below 0.01 for signals.
+ "We only trade when we're right 50.75% of the time, but
+ we know we're right to a high degree of certainty."
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="p_value_threshold",
+ description="Ensures signals meet statistical significance requirements",
+ severity=GuardrailSeverity.ERROR,
+ )
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check p-value against threshold"""
+ limits = self.config.risk_limits
+ required_p_value = limits.min_p_value
+
+ signal_p_value = context.get("p_value", 1.0)
+ signal_id = context.get("signal_id", "unknown")
+ ticker = context.get("ticker", "UNKNOWN")
+
+ if signal_p_value is None:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.BLOCK,
+ message=f"Signal {signal_id} missing p-value",
+ details={
+ "signal_id": signal_id,
+ "ticker": ticker,
+ "p_value": None,
+ },
+ )
+
+ if signal_p_value > required_p_value:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.BLOCK,
+ message=f"Signal {signal_id} p-value {signal_p_value:.4f} > threshold {required_p_value}",
+ details={
+ "signal_id": signal_id,
+ "ticker": ticker,
+ "p_value": signal_p_value,
+ "threshold": required_p_value,
+ "excess": signal_p_value - required_p_value,
+ },
+ )
+
+ # Excellent p-value
+ if signal_p_value < 0.005:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"Signal {signal_id} has excellent statistical significance (p={signal_p_value:.4f})",
+ details={
+ "signal_id": signal_id,
+ "ticker": ticker,
+ "p_value": signal_p_value,
+ "quality": "excellent",
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"Signal {signal_id} meets p-value threshold (p={signal_p_value:.4f})",
+ details={
+ "signal_id": signal_id,
+ "ticker": ticker,
+ "p_value": signal_p_value,
+ },
+ )
+
+
+class SampleSizeGuardrail(Guardrail):
+ """
+ Enforces minimum sample size requirements.
+
+ Ensures signals have sufficient historical data
+ to be statistically meaningful.
+ """
+
+ def __init__(self, min_sample_size: int = 100):
+ super().__init__(
+ name="sample_size_minimum",
+ description="Ensures signals have sufficient sample size",
+ severity=GuardrailSeverity.ERROR,
+ )
+ self.min_sample_size = min_sample_size
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check sample size"""
+ sample_size = context.get("sample_size", 0)
+ signal_id = context.get("signal_id", "unknown")
+ ticker = context.get("ticker", "UNKNOWN")
+
+ if sample_size < self.min_sample_size:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.BLOCK,
+ message=f"Signal {signal_id} sample size {sample_size} < minimum {self.min_sample_size}",
+ details={
+ "signal_id": signal_id,
+ "ticker": ticker,
+ "sample_size": sample_size,
+ "minimum": self.min_sample_size,
+ "shortfall": self.min_sample_size - sample_size,
+ },
+ )
+
+ # Large sample size is better
+ if sample_size >= self.min_sample_size * 5:
+ quality = "excellent"
+ elif sample_size >= self.min_sample_size * 2:
+ quality = "good"
+ else:
+ quality = "adequate"
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"Signal {signal_id} has {quality} sample size ({sample_size})",
+ details={
+ "signal_id": signal_id,
+ "ticker": ticker,
+ "sample_size": sample_size,
+ "quality": quality,
+ },
+ )
+
+
+class SignalConfidenceGuardrail(Guardrail):
+ """
+ Enforces minimum signal confidence.
+
+ The famous RenTech 50.75% threshold.
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="signal_confidence",
+ description="Ensures signals meet minimum confidence threshold",
+ severity=GuardrailSeverity.ERROR,
+ )
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check signal confidence"""
+ limits = self.config.risk_limits
+ min_confidence = limits.min_signal_confidence
+
+ confidence = context.get("confidence", 0)
+ signal_id = context.get("signal_id", "unknown")
+ ticker = context.get("ticker", "UNKNOWN")
+
+ if confidence < min_confidence:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.ERROR,
+ action=GuardrailAction.BLOCK,
+ message=f"Signal {signal_id} confidence {confidence:.2%} < threshold {min_confidence:.2%}",
+ details={
+ "signal_id": signal_id,
+ "ticker": ticker,
+ "confidence": confidence,
+ "threshold": min_confidence,
+ "shortfall": min_confidence - confidence,
+ },
+ )
+
+ # High confidence signals
+ if confidence >= 0.55:
+ quality = "high"
+ severity = GuardrailSeverity.INFO
+ elif confidence >= 0.52:
+ quality = "moderate"
+ severity = GuardrailSeverity.INFO
+ else:
+ quality = "marginal"
+ severity = GuardrailSeverity.WARNING
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=severity,
+ action=GuardrailAction.ALLOW if quality != "marginal" else GuardrailAction.WARN,
+ message=f"Signal {signal_id} has {quality} confidence ({confidence:.2%})",
+ details={
+ "signal_id": signal_id,
+ "ticker": ticker,
+ "confidence": confidence,
+ "quality": quality,
+ },
+ )
+
+
+class DataQualityGuardrail(Guardrail):
+ """
+ Checks for data quality issues.
+
+ Validates that the data underlying signals is clean:
+ - No missing values
+ - No extreme outliers
+ - Corporate action adjustments
+ - Data freshness
+ """
+
+ def __init__(self):
+ super().__init__(
+ name="data_quality",
+ description="Validates data quality for signals",
+ severity=GuardrailSeverity.ERROR,
+ )
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check data quality"""
+ signal_id = context.get("signal_id", "unknown")
+ ticker = context.get("ticker", "UNKNOWN")
+
+ issues = []
+
+ # Check for missing data
+ missing_pct = context.get("missing_data_pct", 0)
+ if missing_pct > 5:
+ issues.append(f"High missing data: {missing_pct:.1f}%")
+
+ # Check for outliers
+ outlier_count = context.get("outlier_count", 0)
+ if outlier_count > 10:
+ issues.append(f"High outlier count: {outlier_count}")
+
+ # Check for corporate actions
+ has_corp_actions = context.get("has_corporate_actions", False)
+ corp_actions_adjusted = context.get("corporate_actions_adjusted", True)
+ if has_corp_actions and not corp_actions_adjusted:
+ issues.append("Corporate actions not adjusted")
+
+ # Check data freshness
+ data_age_hours = context.get("data_age_hours", 0)
+ if data_age_hours > 24:
+ issues.append(f"Stale data: {data_age_hours:.0f} hours old")
+
+ # Check for data gaps
+ has_gaps = context.get("has_data_gaps", False)
+ if has_gaps:
+ issues.append("Data has gaps")
+
+ if issues:
+ severity = GuardrailSeverity.CRITICAL if "Corporate actions" in str(issues) else GuardrailSeverity.ERROR
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=severity,
+ action=GuardrailAction.BLOCK,
+ message=f"Data quality issues for {ticker}: {'; '.join(issues)}",
+ details={
+ "signal_id": signal_id,
+ "ticker": ticker,
+ "issues": issues,
+ "missing_pct": missing_pct,
+ "outlier_count": outlier_count,
+ "data_age_hours": data_age_hours,
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"Data quality check passed for {ticker}",
+ details={
+ "signal_id": signal_id,
+ "ticker": ticker,
+ "quality": "good",
+ },
+ )
+
+
+class SignalStalenessGuardrail(Guardrail):
+ """
+ Checks if signal is still fresh.
+
+ Alpha decays quickly - signals must be acted on promptly.
+ """
+
+ def __init__(self, max_age_minutes: int = 60):
+ super().__init__(
+ name="signal_staleness",
+ description="Ensures signals are acted on before alpha decays",
+ severity=GuardrailSeverity.WARNING,
+ )
+ self.max_age_minutes = max_age_minutes
+
+ def check(self, context: Dict[str, Any]) -> GuardrailResult:
+ """Check signal age"""
+ signal_id = context.get("signal_id", "unknown")
+ signal_time = context.get("signal_timestamp")
+
+ if signal_time is None:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message="Signal timestamp not provided, skipping staleness check",
+ )
+
+ # Calculate age
+ if isinstance(signal_time, str):
+ signal_time = datetime.fromisoformat(signal_time.replace("Z", "+00:00"))
+
+ now = datetime.utcnow()
+ if signal_time.tzinfo:
+ now = now.replace(tzinfo=signal_time.tzinfo)
+
+ age_minutes = (now - signal_time).total_seconds() / 60
+
+ if age_minutes > self.max_age_minutes:
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=False,
+ severity=GuardrailSeverity.WARNING,
+ action=GuardrailAction.WARN,
+ message=f"Signal {signal_id} is {age_minutes:.0f} minutes old (max {self.max_age_minutes})",
+ details={
+ "signal_id": signal_id,
+ "age_minutes": age_minutes,
+ "max_age_minutes": self.max_age_minutes,
+ "alpha_decay_warning": True,
+ },
+ )
+
+ return GuardrailResult(
+ guardrail_name=self.name,
+ passed=True,
+ severity=GuardrailSeverity.INFO,
+ action=GuardrailAction.ALLOW,
+ message=f"Signal {signal_id} is fresh ({age_minutes:.0f} minutes old)",
+ details={
+ "signal_id": signal_id,
+ "age_minutes": age_minutes,
+ },
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/__init__.py
new file mode 100644
index 000000000..b6ad436a9
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/__init__.py
@@ -0,0 +1,55 @@
+"""
+Renaissance Technologies Knowledge Base
+
+Provides shared knowledge across all agents using Agno's Knowledge system.
+Includes market data, research papers, strategy documentation, and trade history.
+
+Knowledge Categories:
+1. Market Data - Historical prices, fundamentals, alternative data
+2. Research Papers - Academic research and internal findings
+3. Strategy Documentation - Trading strategy specs and parameters
+4. Trade History - Historical trades and outcomes
+"""
+
+from .base import (
+ RenTechKnowledge,
+ get_knowledge_base,
+ reset_knowledge_base,
+ KnowledgeCategory,
+)
+from .market_data import (
+ MarketDataKnowledge,
+ get_market_data_knowledge,
+)
+from .research_papers import (
+ ResearchKnowledge,
+ get_research_knowledge,
+)
+from .strategy_docs import (
+ StrategyKnowledge,
+ get_strategy_knowledge,
+)
+from .trade_history import (
+ TradeHistoryKnowledge,
+ get_trade_history_knowledge,
+)
+
+__all__ = [
+ # Base
+ "RenTechKnowledge",
+ "get_knowledge_base",
+ "reset_knowledge_base",
+ "KnowledgeCategory",
+ # Market Data
+ "MarketDataKnowledge",
+ "get_market_data_knowledge",
+ # Research
+ "ResearchKnowledge",
+ "get_research_knowledge",
+ # Strategy
+ "StrategyKnowledge",
+ "get_strategy_knowledge",
+ # Trade History
+ "TradeHistoryKnowledge",
+ "get_trade_history_knowledge",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/base.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/base.py
new file mode 100644
index 000000000..2407d8a9c
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/base.py
@@ -0,0 +1,396 @@
+"""
+Knowledge Base Infrastructure
+
+Provides the core knowledge management system for Renaissance Technologies agents.
+Uses Agno's Knowledge and VectorDB capabilities for semantic search.
+"""
+
+from typing import Optional, List, Dict, Any, Union
+from dataclasses import dataclass, field
+from enum import Enum
+from datetime import datetime
+import json
+import os
+
+# Agno imports - conditional
+try:
+ from agno.knowledge.base import Knowledge
+ from agno.vectordb.lancedb import LanceDb
+ from agno.document import Document
+ AGNO_KNOWLEDGE_AVAILABLE = True
+except ImportError:
+ AGNO_KNOWLEDGE_AVAILABLE = False
+ Knowledge = object # type: ignore
+ LanceDb = None # type: ignore
+ Document = None # type: ignore
+
+from ..config import get_config, RenTechConfig
+from ..utils.embedder_factory import create_embedder_from_config
+
+
+class KnowledgeCategory(str, Enum):
+ """Categories of knowledge in the system"""
+ MARKET_DATA = "market_data"
+ RESEARCH = "research"
+ STRATEGY = "strategy"
+ TRADE_HISTORY = "trade_history"
+ RISK_MODELS = "risk_models"
+ EXECUTION = "execution"
+ COMPLIANCE = "compliance"
+
+
+@dataclass
+class KnowledgeDocument:
+ """
+ A document in the knowledge base.
+
+ Wraps content with metadata for proper indexing and retrieval.
+ """
+ id: str
+ category: KnowledgeCategory
+ title: str
+ content: str
+ metadata: Dict[str, Any] = field(default_factory=dict)
+ created_at: str = field(default_factory=lambda: datetime.utcnow().isoformat())
+ updated_at: str = field(default_factory=lambda: datetime.utcnow().isoformat())
+ tags: List[str] = field(default_factory=list)
+
+ # Relevance scoring
+ importance: float = 0.5 # 0-1, higher = more important
+ freshness_weight: float = 0.5 # How much freshness matters for this doc
+
+ def to_agno_document(self) -> Document:
+ """Convert to Agno Document format"""
+ return Document(
+ id=self.id,
+ name=self.title,
+ content=self.content,
+ meta_data={
+ "category": self.category.value,
+ "created_at": self.created_at,
+ "updated_at": self.updated_at,
+ "tags": self.tags,
+ "importance": self.importance,
+ **self.metadata,
+ },
+ )
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary"""
+ return {
+ "id": self.id,
+ "category": self.category.value,
+ "title": self.title,
+ "content": self.content,
+ "metadata": self.metadata,
+ "created_at": self.created_at,
+ "updated_at": self.updated_at,
+ "tags": self.tags,
+ "importance": self.importance,
+ "freshness_weight": self.freshness_weight,
+ }
+
+
+class RenTechKnowledge:
+ """
+ Renaissance Technologies Knowledge Base.
+
+ Unified knowledge management system that provides:
+ - Semantic search across all knowledge categories
+ - Category-specific filtering
+ - Importance and freshness weighting
+ - Easy integration with Agno agents
+
+ Uses LanceDB for vector storage (local, no external dependencies).
+ """
+
+ def __init__(
+ self,
+ config: Optional[RenTechConfig] = None,
+ db_path: Optional[str] = None,
+ embedder_config: Optional[Dict[str, Any]] = None,
+ ):
+ """
+ Initialize Renaissance Technologies Knowledge Base.
+
+ Args:
+ config: Optional RenTech configuration
+ db_path: Optional path to vector database
+ embedder_config: Optional embedder configuration override
+ If None, uses frontend config or falls back to Ollama
+ """
+ self.config = config or get_config()
+ self.db_path = db_path or self.config.database.vector_db_path
+
+ # Initialize embedder dynamically from frontend config
+ # Falls back to Ollama (local, free) if no config found
+ self.embedder = create_embedder_from_config(embedder_config)
+
+ # Initialize vector databases for each category
+ self._vector_dbs: Dict[KnowledgeCategory, LanceDb] = {}
+ self._knowledge_stores: Dict[KnowledgeCategory, Knowledge] = {}
+
+ # Document cache
+ self._documents: Dict[str, KnowledgeDocument] = {}
+
+ def _get_vector_db(self, category: KnowledgeCategory) -> LanceDb:
+ """Get or create vector DB for a category"""
+ if category not in self._vector_dbs:
+ table_name = f"rentech_{category.value}"
+ self._vector_dbs[category] = LanceDb(
+ table_name=table_name,
+ uri=self.db_path,
+ embedder=self.embedder,
+ )
+ return self._vector_dbs[category]
+
+ def _get_knowledge(self, category: KnowledgeCategory) -> Knowledge:
+ """Get or create Knowledge instance for a category"""
+ if category not in self._knowledge_stores:
+ self._knowledge_stores[category] = Knowledge(
+ vector_db=self._get_vector_db(category),
+ )
+ return self._knowledge_stores[category]
+
+ def add_document(self, doc: KnowledgeDocument) -> str:
+ """
+ Add a document to the knowledge base.
+
+ Args:
+ doc: The document to add
+
+ Returns:
+ Document ID
+ """
+ # Store in cache
+ self._documents[doc.id] = doc
+
+ # Add to vector DB
+ knowledge = self._get_knowledge(doc.category)
+ agno_doc = doc.to_agno_document()
+
+ # Load document into knowledge base
+ knowledge.load_documents([agno_doc])
+
+ return doc.id
+
+ def add_documents(self, docs: List[KnowledgeDocument]) -> List[str]:
+ """Add multiple documents"""
+ ids = []
+ for doc in docs:
+ doc_id = self.add_document(doc)
+ ids.append(doc_id)
+ return ids
+
+ def search(
+ self,
+ query: str,
+ category: Optional[KnowledgeCategory] = None,
+ limit: int = 10,
+ min_relevance: float = 0.0,
+ ) -> List[Dict[str, Any]]:
+ """
+ Search the knowledge base.
+
+ Args:
+ query: Search query
+ category: Optional category filter
+ limit: Maximum results to return
+ min_relevance: Minimum relevance score (0-1)
+
+ Returns:
+ List of matching documents with scores
+ """
+ results = []
+
+ # Search specific category or all
+ categories = [category] if category else list(KnowledgeCategory)
+
+ for cat in categories:
+ if cat in self._knowledge_stores:
+ knowledge = self._knowledge_stores[cat]
+ try:
+ search_results = knowledge.search(query, num_documents=limit)
+ for result in search_results:
+ results.append({
+ "id": result.id if hasattr(result, 'id') else None,
+ "content": result.content if hasattr(result, 'content') else str(result),
+ "category": cat.value,
+ "metadata": result.meta_data if hasattr(result, 'meta_data') else {},
+ })
+ except Exception as e:
+ # Knowledge base might be empty
+ pass
+
+ return results[:limit]
+
+ def get_document(self, doc_id: str) -> Optional[KnowledgeDocument]:
+ """Get a document by ID"""
+ return self._documents.get(doc_id)
+
+ def get_documents_by_category(
+ self,
+ category: KnowledgeCategory,
+ ) -> List[KnowledgeDocument]:
+ """Get all documents in a category"""
+ return [
+ doc for doc in self._documents.values()
+ if doc.category == category
+ ]
+
+ def get_documents_by_tag(self, tag: str) -> List[KnowledgeDocument]:
+ """Get all documents with a specific tag"""
+ return [
+ doc for doc in self._documents.values()
+ if tag in doc.tags
+ ]
+
+ def update_document(
+ self,
+ doc_id: str,
+ content: Optional[str] = None,
+ metadata: Optional[Dict[str, Any]] = None,
+ tags: Optional[List[str]] = None,
+ ) -> bool:
+ """Update an existing document"""
+ if doc_id not in self._documents:
+ return False
+
+ doc = self._documents[doc_id]
+ doc.updated_at = datetime.utcnow().isoformat()
+
+ if content:
+ doc.content = content
+ if metadata:
+ doc.metadata.update(metadata)
+ if tags:
+ doc.tags = tags
+
+ # Re-index
+ knowledge = self._get_knowledge(doc.category)
+ knowledge.load_documents([doc.to_agno_document()])
+
+ return True
+
+ def delete_document(self, doc_id: str) -> bool:
+ """Delete a document"""
+ if doc_id not in self._documents:
+ return False
+
+ del self._documents[doc_id]
+ return True
+
+ def get_context_for_agent(
+ self,
+ query: str,
+ agent_role: str,
+ max_tokens: int = 2000,
+ ) -> str:
+ """
+ Get relevant knowledge context for an agent.
+
+ Args:
+ query: The query/task the agent is working on
+ agent_role: The agent's role (for filtering)
+ max_tokens: Maximum context tokens
+
+ Returns:
+ Formatted context string
+ """
+ # Determine relevant categories based on agent role
+ role_categories = {
+ "signal_scientist": [KnowledgeCategory.MARKET_DATA, KnowledgeCategory.RESEARCH],
+ "data_scientist": [KnowledgeCategory.MARKET_DATA],
+ "quant_researcher": [KnowledgeCategory.RESEARCH, KnowledgeCategory.STRATEGY],
+ "research_lead": [KnowledgeCategory.RESEARCH, KnowledgeCategory.STRATEGY],
+ "execution_trader": [KnowledgeCategory.EXECUTION, KnowledgeCategory.MARKET_DATA],
+ "market_maker": [KnowledgeCategory.EXECUTION, KnowledgeCategory.MARKET_DATA],
+ "risk_quant": [KnowledgeCategory.RISK_MODELS, KnowledgeCategory.MARKET_DATA],
+ "compliance_officer": [KnowledgeCategory.COMPLIANCE, KnowledgeCategory.TRADE_HISTORY],
+ "portfolio_manager": [KnowledgeCategory.STRATEGY, KnowledgeCategory.TRADE_HISTORY],
+ "investment_committee_chair": list(KnowledgeCategory), # Access to all
+ }
+
+ categories = role_categories.get(agent_role, list(KnowledgeCategory))
+
+ # Search across relevant categories
+ all_results = []
+ for cat in categories:
+ results = self.search(query, category=cat, limit=5)
+ all_results.extend(results)
+
+ if not all_results:
+ return ""
+
+ # Format context
+ context_parts = ["## Relevant Knowledge\n"]
+ for result in all_results[:10]: # Limit total results
+ context_parts.append(f"### {result.get('category', 'Unknown')}")
+ context_parts.append(result.get('content', '')[:500]) # Truncate long content
+ context_parts.append("")
+
+ return "\n".join(context_parts)
+
+ def get_statistics(self) -> Dict[str, Any]:
+ """Get knowledge base statistics"""
+ stats = {
+ "total_documents": len(self._documents),
+ "by_category": {},
+ }
+
+ for cat in KnowledgeCategory:
+ count = len([d for d in self._documents.values() if d.category == cat])
+ stats["by_category"][cat.value] = count
+
+ return stats
+
+
+# =============================================================================
+# GLOBAL KNOWLEDGE BASE INSTANCE
+# =============================================================================
+
+_knowledge_base: Optional[RenTechKnowledge] = None
+
+
+def get_knowledge_base() -> RenTechKnowledge:
+ """Get the global knowledge base instance"""
+ global _knowledge_base
+ if _knowledge_base is None:
+ _knowledge_base = RenTechKnowledge()
+ return _knowledge_base
+
+
+def reset_knowledge_base():
+ """Reset the global knowledge base"""
+ global _knowledge_base
+ _knowledge_base = None
+
+
+# =============================================================================
+# KNOWLEDGE LOADER UTILITIES
+# =============================================================================
+
+def load_knowledge_from_dict(data: Dict[str, Any]) -> KnowledgeDocument:
+ """Load a knowledge document from a dictionary"""
+ return KnowledgeDocument(
+ id=data["id"],
+ category=KnowledgeCategory(data["category"]),
+ title=data["title"],
+ content=data["content"],
+ metadata=data.get("metadata", {}),
+ tags=data.get("tags", []),
+ importance=data.get("importance", 0.5),
+ )
+
+
+def load_knowledge_from_json(json_path: str) -> List[KnowledgeDocument]:
+ """Load knowledge documents from a JSON file"""
+ with open(json_path, 'r') as f:
+ data = json.load(f)
+
+ docs = []
+ for item in data:
+ doc = load_knowledge_from_dict(item)
+ docs.append(doc)
+
+ return docs
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/market_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/market_data.py
new file mode 100644
index 000000000..410a583fc
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/market_data.py
@@ -0,0 +1,323 @@
+"""
+Market Data Knowledge
+
+Knowledge base for market data including:
+- Historical price patterns
+- Volume profiles
+- Sector correlations
+- Market microstructure insights
+- Alternative data patterns
+"""
+
+from typing import Optional, List, Dict, Any
+from datetime import datetime
+import uuid
+
+from .base import (
+ RenTechKnowledge,
+ KnowledgeDocument,
+ KnowledgeCategory,
+ get_knowledge_base,
+)
+
+
+class MarketDataKnowledge:
+ """
+ Market Data Knowledge Manager.
+
+ Provides structured access to market data knowledge including
+ price patterns, volume analysis, and microstructure insights.
+ """
+
+ def __init__(self, knowledge_base: Optional[RenTechKnowledge] = None):
+ self.kb = knowledge_base or get_knowledge_base()
+ self.category = KnowledgeCategory.MARKET_DATA
+
+ def add_price_pattern(
+ self,
+ ticker: str,
+ pattern_name: str,
+ description: str,
+ statistics: Dict[str, Any],
+ tags: Optional[List[str]] = None,
+ ) -> str:
+ """
+ Add a discovered price pattern to knowledge base.
+
+ Args:
+ ticker: Stock ticker
+ pattern_name: Name of the pattern
+ description: Description of the pattern
+ statistics: Statistical metrics for the pattern
+ tags: Optional tags
+
+ Returns:
+ Document ID
+ """
+ content = f"""
+# Price Pattern: {pattern_name}
+
+## Ticker: {ticker}
+
+## Description
+{description}
+
+## Statistics
+- Mean Return: {statistics.get('mean_return', 'N/A')}
+- Std Return: {statistics.get('std_return', 'N/A')}
+- Sharpe Ratio: {statistics.get('sharpe_ratio', 'N/A')}
+- Win Rate: {statistics.get('win_rate', 'N/A')}
+- P-value: {statistics.get('p_value', 'N/A')}
+- Sample Size: {statistics.get('sample_size', 'N/A')}
+
+## Optimal Parameters
+- Lookback: {statistics.get('lookback', 'N/A')} days
+- Holding Period: {statistics.get('holding_period', 'N/A')} days
+- Entry Threshold: {statistics.get('entry_threshold', 'N/A')}
+- Exit Threshold: {statistics.get('exit_threshold', 'N/A')}
+
+## Regime Performance
+- Bull Market Sharpe: {statistics.get('bull_sharpe', 'N/A')}
+- Bear Market Sharpe: {statistics.get('bear_sharpe', 'N/A')}
+- High Vol Sharpe: {statistics.get('high_vol_sharpe', 'N/A')}
+"""
+
+ doc = KnowledgeDocument(
+ id=f"pattern_{ticker}_{pattern_name}_{uuid.uuid4().hex[:8]}",
+ category=self.category,
+ title=f"{ticker} - {pattern_name}",
+ content=content,
+ metadata={
+ "ticker": ticker,
+ "pattern_name": pattern_name,
+ "statistics": statistics,
+ "doc_type": "price_pattern",
+ },
+ tags=tags or [ticker, pattern_name, "price_pattern"],
+ importance=0.7,
+ )
+
+ return self.kb.add_document(doc)
+
+ def add_volume_profile(
+ self,
+ ticker: str,
+ profile_data: Dict[str, Any],
+ ) -> str:
+ """Add volume profile knowledge for a ticker"""
+ content = f"""
+# Volume Profile: {ticker}
+
+## Average Daily Volume
+- ADV (20-day): {profile_data.get('adv_20', 'N/A'):,} shares
+- ADV (60-day): {profile_data.get('adv_60', 'N/A'):,} shares
+
+## Intraday Pattern
+- Open Auction: {profile_data.get('open_pct', 'N/A')}% of volume
+- Morning (9:30-12:00): {profile_data.get('morning_pct', 'N/A')}%
+- Midday (12:00-14:00): {profile_data.get('midday_pct', 'N/A')}%
+- Afternoon (14:00-15:30): {profile_data.get('afternoon_pct', 'N/A')}%
+- Close Auction: {profile_data.get('close_pct', 'N/A')}%
+
+## Liquidity Metrics
+- Typical Spread: {profile_data.get('spread_bps', 'N/A')} bps
+- Market Depth (1%): ${profile_data.get('depth_1pct', 'N/A'):,}
+- Kyle's Lambda: {profile_data.get('kyle_lambda', 'N/A')}
+
+## Execution Recommendations
+- Optimal Participation: {profile_data.get('opt_participation', 'N/A')}%
+- Best Time to Trade: {profile_data.get('best_time', 'N/A')}
+- Avoid: {profile_data.get('avoid_time', 'N/A')}
+"""
+
+ doc = KnowledgeDocument(
+ id=f"volume_{ticker}_{datetime.utcnow().strftime('%Y%m%d')}",
+ category=self.category,
+ title=f"{ticker} - Volume Profile",
+ content=content,
+ metadata={
+ "ticker": ticker,
+ "profile_data": profile_data,
+ "doc_type": "volume_profile",
+ },
+ tags=[ticker, "volume", "liquidity", "execution"],
+ importance=0.6,
+ freshness_weight=0.8, # Volume profiles need to be fresh
+ )
+
+ return self.kb.add_document(doc)
+
+ def add_correlation_insight(
+ self,
+ tickers: List[str],
+ correlation: float,
+ insight: str,
+ period: str,
+ ) -> str:
+ """Add correlation insight between assets"""
+ ticker_str = " / ".join(tickers)
+
+ content = f"""
+# Correlation Insight: {ticker_str}
+
+## Period: {period}
+
+## Correlation: {correlation:.3f}
+
+## Insight
+{insight}
+
+## Trading Implications
+- Diversification benefit: {'Low' if abs(correlation) > 0.7 else 'Medium' if abs(correlation) > 0.4 else 'High'}
+- Pair trading opportunity: {'Yes' if abs(correlation) > 0.8 else 'Maybe' if abs(correlation) > 0.6 else 'No'}
+- Risk consideration: {'High co-movement' if correlation > 0.7 else 'Moderate co-movement' if correlation > 0.4 else 'Good diversification'}
+
+## Historical Context
+This correlation has been {'stable' if 'stable' in insight.lower() else 'variable'} over time.
+"""
+
+ doc = KnowledgeDocument(
+ id=f"corr_{'_'.join(tickers)}_{uuid.uuid4().hex[:8]}",
+ category=self.category,
+ title=f"Correlation: {ticker_str}",
+ content=content,
+ metadata={
+ "tickers": tickers,
+ "correlation": correlation,
+ "period": period,
+ "doc_type": "correlation",
+ },
+ tags=tickers + ["correlation", "risk"],
+ importance=0.5,
+ )
+
+ return self.kb.add_document(doc)
+
+ def add_sector_analysis(
+ self,
+ sector: str,
+ analysis: Dict[str, Any],
+ ) -> str:
+ """Add sector-level market analysis"""
+ content = f"""
+# Sector Analysis: {sector}
+
+## Current Characteristics
+- Average Beta: {analysis.get('avg_beta', 'N/A')}
+- Average Volatility: {analysis.get('avg_vol', 'N/A')}%
+- YTD Performance: {analysis.get('ytd_return', 'N/A')}%
+
+## Correlation with Market
+- SPY Correlation: {analysis.get('spy_corr', 'N/A')}
+- Sector Beta: {analysis.get('sector_beta', 'N/A')}
+
+## Top Holdings Impact
+{chr(10).join([f"- {h['ticker']}: {h['weight']}%" for h in analysis.get('top_holdings', [])])}
+
+## Regime Behavior
+- In Risk-Off: {analysis.get('risk_off_behavior', 'N/A')}
+- In Risk-On: {analysis.get('risk_on_behavior', 'N/A')}
+
+## Current Assessment
+{analysis.get('assessment', 'No assessment available.')}
+
+## Signal Implications
+- Mean reversion effectiveness: {analysis.get('mean_rev_score', 'N/A')}/10
+- Momentum effectiveness: {analysis.get('momentum_score', 'N/A')}/10
+"""
+
+ doc = KnowledgeDocument(
+ id=f"sector_{sector}_{datetime.utcnow().strftime('%Y%m%d')}",
+ category=self.category,
+ title=f"Sector Analysis: {sector}",
+ content=content,
+ metadata={
+ "sector": sector,
+ "analysis": analysis,
+ "doc_type": "sector_analysis",
+ },
+ tags=[sector, "sector", "market_analysis"],
+ importance=0.6,
+ freshness_weight=0.7,
+ )
+
+ return self.kb.add_document(doc)
+
+ def add_microstructure_insight(
+ self,
+ topic: str,
+ insight: str,
+ evidence: Dict[str, Any],
+ ) -> str:
+ """Add market microstructure insight"""
+ content = f"""
+# Microstructure Insight: {topic}
+
+## Insight
+{insight}
+
+## Evidence
+- Sample Period: {evidence.get('period', 'N/A')}
+- Sample Size: {evidence.get('sample_size', 'N/A')}
+- Statistical Significance: {evidence.get('significance', 'N/A')}
+
+## Key Findings
+{chr(10).join([f"- {f}" for f in evidence.get('findings', [])])}
+
+## Trading Implications
+{evidence.get('implications', 'No specific implications noted.')}
+
+## Recommended Actions
+{chr(10).join([f"- {a}" for a in evidence.get('actions', [])])}
+"""
+
+ doc = KnowledgeDocument(
+ id=f"micro_{topic.replace(' ', '_')}_{uuid.uuid4().hex[:8]}",
+ category=self.category,
+ title=f"Microstructure: {topic}",
+ content=content,
+ metadata={
+ "topic": topic,
+ "evidence": evidence,
+ "doc_type": "microstructure",
+ },
+ tags=["microstructure", "execution", topic.lower()],
+ importance=0.7,
+ )
+
+ return self.kb.add_document(doc)
+
+ def search_patterns(
+ self,
+ query: str,
+ ticker: Optional[str] = None,
+ limit: int = 10,
+ ) -> List[Dict[str, Any]]:
+ """Search for price patterns"""
+ results = self.kb.search(
+ query=query,
+ category=self.category,
+ limit=limit,
+ )
+
+ if ticker:
+ results = [r for r in results if r.get("metadata", {}).get("ticker") == ticker]
+
+ return results
+
+ def get_ticker_knowledge(self, ticker: str) -> List[KnowledgeDocument]:
+ """Get all knowledge for a specific ticker"""
+ docs = self.kb.get_documents_by_category(self.category)
+ return [d for d in docs if d.metadata.get("ticker") == ticker or ticker in d.tags]
+
+
+# Global instance
+_market_data_knowledge: Optional[MarketDataKnowledge] = None
+
+
+def get_market_data_knowledge() -> MarketDataKnowledge:
+ """Get the global market data knowledge instance"""
+ global _market_data_knowledge
+ if _market_data_knowledge is None:
+ _market_data_knowledge = MarketDataKnowledge()
+ return _market_data_knowledge
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/research_papers.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/research_papers.py
new file mode 100644
index 000000000..a6df64665
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/research_papers.py
@@ -0,0 +1,324 @@
+"""
+Research Papers Knowledge
+
+Knowledge base for academic and internal research including:
+- Academic papers on quantitative finance
+- Internal research findings
+- Factor research
+- Strategy development notes
+"""
+
+from typing import Optional, List, Dict, Any
+from datetime import datetime
+import uuid
+
+from .base import (
+ RenTechKnowledge,
+ KnowledgeDocument,
+ KnowledgeCategory,
+ get_knowledge_base,
+)
+
+
+class ResearchKnowledge:
+ """
+ Research Knowledge Manager.
+
+ Provides structured access to research papers, academic findings,
+ and internal research documentation.
+ """
+
+ def __init__(self, knowledge_base: Optional[RenTechKnowledge] = None):
+ self.kb = knowledge_base or get_knowledge_base()
+ self.category = KnowledgeCategory.RESEARCH
+
+ def add_academic_paper(
+ self,
+ title: str,
+ authors: List[str],
+ abstract: str,
+ key_findings: List[str],
+ methodology: str,
+ relevance_to_trading: str,
+ publication_year: int,
+ tags: Optional[List[str]] = None,
+ ) -> str:
+ """
+ Add an academic paper to the knowledge base.
+
+ Args:
+ title: Paper title
+ authors: List of authors
+ abstract: Paper abstract
+ key_findings: Key findings from the paper
+ methodology: Research methodology used
+ relevance_to_trading: How this applies to our trading
+ publication_year: Year of publication
+ tags: Optional tags
+
+ Returns:
+ Document ID
+ """
+ content = f"""
+# Research Paper: {title}
+
+## Authors
+{', '.join(authors)}
+
+## Publication Year: {publication_year}
+
+## Abstract
+{abstract}
+
+## Key Findings
+{chr(10).join([f"- {f}" for f in key_findings])}
+
+## Methodology
+{methodology}
+
+## Relevance to Trading
+{relevance_to_trading}
+
+## Implementation Notes
+Consider the following when implementing:
+- Data requirements
+- Parameter sensitivity
+- Transaction cost implications
+- Capacity constraints
+"""
+
+ doc = KnowledgeDocument(
+ id=f"paper_{title.replace(' ', '_')[:30]}_{uuid.uuid4().hex[:8]}",
+ category=self.category,
+ title=title,
+ content=content,
+ metadata={
+ "authors": authors,
+ "publication_year": publication_year,
+ "doc_type": "academic_paper",
+ },
+ tags=tags or ["academic", "research"] + [a.split()[-1].lower() for a in authors[:3]],
+ importance=0.8,
+ )
+
+ return self.kb.add_document(doc)
+
+ def add_internal_research(
+ self,
+ title: str,
+ researcher: str,
+ summary: str,
+ findings: List[str],
+ data_used: List[str],
+ statistical_results: Dict[str, Any],
+ recommendations: List[str],
+ status: str = "completed",
+ ) -> str:
+ """Add internal research finding"""
+ content = f"""
+# Internal Research: {title}
+
+## Researcher: {researcher}
+## Status: {status}
+## Date: {datetime.utcnow().strftime('%Y-%m-%d')}
+
+## Summary
+{summary}
+
+## Data Sources Used
+{chr(10).join([f"- {d}" for d in data_used])}
+
+## Key Findings
+{chr(10).join([f"- {f}" for f in findings])}
+
+## Statistical Results
+- Sample Size: {statistical_results.get('sample_size', 'N/A')}
+- P-value: {statistical_results.get('p_value', 'N/A')}
+- T-statistic: {statistical_results.get('t_stat', 'N/A')}
+- Sharpe Ratio: {statistical_results.get('sharpe', 'N/A')}
+- Information Coefficient: {statistical_results.get('ic', 'N/A')}
+
+## Recommendations
+{chr(10).join([f"- {r}" for r in recommendations])}
+
+## Next Steps
+- Further validation needed: {statistical_results.get('needs_validation', False)}
+- Ready for production: {statistical_results.get('production_ready', False)}
+"""
+
+ doc = KnowledgeDocument(
+ id=f"internal_{title.replace(' ', '_')[:30]}_{uuid.uuid4().hex[:8]}",
+ category=self.category,
+ title=f"Internal: {title}",
+ content=content,
+ metadata={
+ "researcher": researcher,
+ "status": status,
+ "statistical_results": statistical_results,
+ "doc_type": "internal_research",
+ },
+ tags=["internal", "research", researcher.lower().replace(" ", "_")],
+ importance=0.9, # Internal research is highly important
+ )
+
+ return self.kb.add_document(doc)
+
+ def add_factor_research(
+ self,
+ factor_name: str,
+ description: str,
+ construction: str,
+ historical_performance: Dict[str, Any],
+ correlation_with_other_factors: Dict[str, float],
+ implementation_notes: str,
+ ) -> str:
+ """Add factor research documentation"""
+ content = f"""
+# Factor Research: {factor_name}
+
+## Description
+{description}
+
+## Factor Construction
+{construction}
+
+## Historical Performance
+- Annualized Return: {historical_performance.get('annual_return', 'N/A')}%
+- Annualized Volatility: {historical_performance.get('annual_vol', 'N/A')}%
+- Sharpe Ratio: {historical_performance.get('sharpe', 'N/A')}
+- Max Drawdown: {historical_performance.get('max_dd', 'N/A')}%
+- Sample Period: {historical_performance.get('period', 'N/A')}
+
+## Factor Correlations
+{chr(10).join([f"- {f}: {c:.2f}" for f, c in correlation_with_other_factors.items()])}
+
+## Implementation Notes
+{implementation_notes}
+
+## Risk Considerations
+- Factor crowding risk
+- Regime dependency
+- Capacity constraints
+- Transaction cost sensitivity
+"""
+
+ doc = KnowledgeDocument(
+ id=f"factor_{factor_name.replace(' ', '_')}_{uuid.uuid4().hex[:8]}",
+ category=self.category,
+ title=f"Factor: {factor_name}",
+ content=content,
+ metadata={
+ "factor_name": factor_name,
+ "historical_performance": historical_performance,
+ "correlations": correlation_with_other_factors,
+ "doc_type": "factor_research",
+ },
+ tags=["factor", factor_name.lower(), "research"],
+ importance=0.85,
+ )
+
+ return self.kb.add_document(doc)
+
+ def add_signal_documentation(
+ self,
+ signal_name: str,
+ signal_type: str,
+ description: str,
+ parameters: Dict[str, Any],
+ backtest_results: Dict[str, Any],
+ live_results: Optional[Dict[str, Any]] = None,
+ lessons_learned: Optional[List[str]] = None,
+ ) -> str:
+ """Add signal documentation"""
+ content = f"""
+# Signal Documentation: {signal_name}
+
+## Signal Type: {signal_type}
+
+## Description
+{description}
+
+## Parameters
+{chr(10).join([f"- {k}: {v}" for k, v in parameters.items()])}
+
+## Backtest Results
+- Period: {backtest_results.get('period', 'N/A')}
+- Sharpe Ratio: {backtest_results.get('sharpe', 'N/A')}
+- Annual Return: {backtest_results.get('annual_return', 'N/A')}%
+- Win Rate: {backtest_results.get('win_rate', 'N/A')}%
+- Profit Factor: {backtest_results.get('profit_factor', 'N/A')}
+- Max Drawdown: {backtest_results.get('max_dd', 'N/A')}%
+
+## Live Results
+{f'''
+- Period: {live_results.get('period', 'N/A')}
+- Sharpe Ratio: {live_results.get('sharpe', 'N/A')}
+- Backtest vs Live Degradation: {live_results.get('degradation', 'N/A')}%
+''' if live_results else 'Not yet traded live.'}
+
+## Lessons Learned
+{chr(10).join([f"- {l}" for l in (lessons_learned or ['No lessons documented yet.'])])}
+
+## Current Status
+- Active: {backtest_results.get('active', False)}
+- Allocation: {backtest_results.get('allocation_pct', 0)}% of portfolio
+"""
+
+ doc = KnowledgeDocument(
+ id=f"signal_{signal_name.replace(' ', '_')}_{uuid.uuid4().hex[:8]}",
+ category=self.category,
+ title=f"Signal: {signal_name}",
+ content=content,
+ metadata={
+ "signal_name": signal_name,
+ "signal_type": signal_type,
+ "parameters": parameters,
+ "backtest_results": backtest_results,
+ "live_results": live_results,
+ "doc_type": "signal_documentation",
+ },
+ tags=["signal", signal_type.lower(), signal_name.lower()],
+ importance=0.9,
+ )
+
+ return self.kb.add_document(doc)
+
+ def search_research(
+ self,
+ query: str,
+ doc_type: Optional[str] = None,
+ limit: int = 10,
+ ) -> List[Dict[str, Any]]:
+ """Search research documents"""
+ results = self.kb.search(
+ query=query,
+ category=self.category,
+ limit=limit,
+ )
+
+ if doc_type:
+ results = [r for r in results if r.get("metadata", {}).get("doc_type") == doc_type]
+
+ return results
+
+ def get_factor_library(self) -> List[KnowledgeDocument]:
+ """Get all documented factors"""
+ docs = self.kb.get_documents_by_category(self.category)
+ return [d for d in docs if d.metadata.get("doc_type") == "factor_research"]
+
+ def get_signal_library(self) -> List[KnowledgeDocument]:
+ """Get all documented signals"""
+ docs = self.kb.get_documents_by_category(self.category)
+ return [d for d in docs if d.metadata.get("doc_type") == "signal_documentation"]
+
+
+# Global instance
+_research_knowledge: Optional[ResearchKnowledge] = None
+
+
+def get_research_knowledge() -> ResearchKnowledge:
+ """Get the global research knowledge instance"""
+ global _research_knowledge
+ if _research_knowledge is None:
+ _research_knowledge = ResearchKnowledge()
+ return _research_knowledge
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/seed_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/seed_data.py
new file mode 100644
index 000000000..0a23c8072
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/seed_data.py
@@ -0,0 +1,558 @@
+"""
+Seed Data for Knowledge Base
+
+Populates the knowledge base with initial data including:
+- Common trading strategies
+- Risk policies
+- Academic research summaries
+- Market patterns
+"""
+
+from typing import Optional
+from .base import get_knowledge_base, RenTechKnowledge
+from .market_data import get_market_data_knowledge
+from .research_papers import get_research_knowledge
+from .strategy_docs import get_strategy_knowledge
+from .trade_history import get_trade_history_knowledge
+
+
+def seed_research_knowledge(research_kb=None):
+ """Seed academic and internal research"""
+ kb = research_kb or get_research_knowledge()
+
+ # Academic papers
+ kb.add_academic_paper(
+ title="Returns to Buying Winners and Selling Losers",
+ authors=["Jegadeesh", "Titman"],
+ abstract="This paper documents that strategies which buy stocks that have performed well in the past and sell stocks that have performed poorly in the past generate significant positive returns over 3 to 12 month holding periods.",
+ key_findings=[
+ "Momentum strategies generate significant abnormal returns",
+ "6-month formation and 6-month holding period is optimal",
+ "Returns are not explained by systematic risk",
+ "Profits are partially due to delayed reaction to firm-specific information",
+ ],
+ methodology="Cross-sectional momentum portfolios with various formation and holding periods",
+ relevance_to_trading="Basis for our momentum signals. Use 12-1 month momentum with 1-month reversal adjustment.",
+ publication_year=1993,
+ tags=["momentum", "cross-sectional", "classic"],
+ )
+
+ kb.add_academic_paper(
+ title="Mean Reversion in Stock Prices: Evidence and Implications",
+ authors=["Poterba", "Summers"],
+ abstract="This paper investigates whether stock prices exhibit mean reversion using variance ratio tests.",
+ key_findings=[
+ "Stock returns exhibit positive autocorrelation at short horizons",
+ "Negative autocorrelation at longer horizons suggests mean reversion",
+ "Mean reversion is stronger for smaller stocks",
+ "Transaction costs may prevent full exploitation",
+ ],
+ methodology="Variance ratio tests on long-term stock returns",
+ relevance_to_trading="Supports our mean reversion strategies. Focus on 3-5 day holding periods.",
+ publication_year=1988,
+ tags=["mean_reversion", "autocorrelation", "classic"],
+ )
+
+ kb.add_academic_paper(
+ title="Statistical Arbitrage in the U.S. Equities Market",
+ authors=["Avellaneda", "Lee"],
+ abstract="We study the implementation of statistical arbitrage strategies using principal component analysis and mean-reverting residuals.",
+ key_findings=[
+ "PCA effectively identifies common factors in stock returns",
+ "Residuals after factor adjustment exhibit mean reversion",
+ "Optimal entry at 2 standard deviation moves",
+ "Half-life of mean reversion is typically 10-20 days",
+ ],
+ methodology="PCA factor model with Ornstein-Uhlenbeck mean reversion",
+ relevance_to_trading="Direct implementation guide for our stat arb strategies.",
+ publication_year=2010,
+ tags=["statistical_arbitrage", "pca", "mean_reversion"],
+ )
+
+ # Factor research
+ kb.add_factor_research(
+ factor_name="Momentum 12-1",
+ description="Cross-sectional momentum based on past 12-month returns excluding the most recent month",
+ construction="""
+1. Calculate 12-month cumulative return for each stock
+2. Exclude the most recent month (to avoid reversal)
+3. Rank stocks by this return
+4. Go long top decile, short bottom decile
+5. Rebalance monthly
+""",
+ historical_performance={
+ "annual_return": 8.5,
+ "annual_vol": 18.0,
+ "sharpe": 0.47,
+ "max_dd": -52.0,
+ "period": "1963-2023",
+ },
+ correlation_with_other_factors={
+ "market": 0.05,
+ "size": -0.15,
+ "value": -0.25,
+ "quality": 0.10,
+ },
+ implementation_notes="Use sector-neutral construction to reduce crash risk. Consider 50% Kelly fraction.",
+ )
+
+ kb.add_factor_research(
+ factor_name="Quality (Profitability)",
+ description="Long high-quality stocks (high ROE, low debt, stable earnings), short low-quality",
+ construction="""
+1. Calculate gross profitability (GP/Assets)
+2. Calculate ROE
+3. Calculate earnings stability (5-year std of earnings growth)
+4. Combine into composite score
+5. Long top quintile, short bottom quintile
+""",
+ historical_performance={
+ "annual_return": 5.2,
+ "annual_vol": 10.0,
+ "sharpe": 0.52,
+ "max_dd": -25.0,
+ "period": "1963-2023",
+ },
+ correlation_with_other_factors={
+ "market": -0.10,
+ "size": -0.20,
+ "value": -0.30,
+ "momentum": 0.15,
+ },
+ implementation_notes="Quality provides defensive characteristics. Increase weight in volatile markets.",
+ )
+
+ # Internal research
+ kb.add_internal_research(
+ title="Intraday Mean Reversion in Liquid Stocks",
+ researcher="Signal Scientist",
+ summary="Analysis of intraday mean reversion patterns in S&P 500 stocks shows significant opportunities in the first and last hours of trading.",
+ findings=[
+ "Opening 30 minutes show strongest mean reversion (half-life ~15 min)",
+ "Midday (11am-2pm) shows weakest patterns",
+ "Last hour mean reversion tied to index rebalancing",
+ "Pattern stronger on high-volume days",
+ ],
+ data_used=["1-minute bars for S&P 500", "2 years of data", "Order book snapshots"],
+ statistical_results={
+ "sample_size": 50000,
+ "p_value": 0.003,
+ "t_stat": 2.97,
+ "sharpe": 1.8,
+ "ic": 0.04,
+ "needs_validation": False,
+ "production_ready": True,
+ },
+ recommendations=[
+ "Focus mean reversion signals on first/last hour",
+ "Reduce activity during midday",
+ "Increase size on high-volume days",
+ ],
+ )
+
+ print("Research knowledge seeded successfully")
+
+
+def seed_strategy_knowledge(strategy_kb=None):
+ """Seed strategy documentation"""
+ kb = strategy_kb or get_strategy_knowledge()
+
+ # Mean reversion strategy
+ kb.add_strategy_spec(
+ strategy_name="Equity Mean Reversion",
+ strategy_type="mean_reversion",
+ description="Short-term mean reversion in liquid US equities. Exploits temporary price dislocations using statistical signals.",
+ universe=["S&P 500 constituents", "Liquid ETFs", "Min ADV $10M"],
+ signals_used=["Z-score of returns", "RSI divergence", "Bollinger band deviation"],
+ entry_rules=[
+ "Z-score > 2.0 for short, < -2.0 for long",
+ "RSI confirms (>70 for short, <30 for long)",
+ "No earnings in next 5 days",
+ "Not on restricted list",
+ ],
+ exit_rules=[
+ "Z-score returns to ±0.5",
+ "Max holding period 5 days",
+ "Stop loss at 3% adverse move",
+ "Profit target at 2% favorable move",
+ ],
+ risk_parameters={
+ "max_position_pct": 2.0,
+ "max_sector_pct": 15.0,
+ "stop_loss_pct": 3.0,
+ "take_profit_pct": 2.0,
+ "max_drawdown_pct": 10.0,
+ "max_leverage": 4.0,
+ "turnover_target": 50.0,
+ "execution_urgency": "normal",
+ "participation_rate": 5.0,
+ "default_algo": "TWAP",
+ "target_sharpe": 2.0,
+ "target_return": 15.0,
+ },
+ allocation=25.0,
+ status="active",
+ )
+
+ # Momentum strategy
+ kb.add_strategy_spec(
+ strategy_name="Cross-Sectional Momentum",
+ strategy_type="momentum",
+ description="Medium-term momentum strategy buying recent winners and shorting losers. Sector-neutral construction.",
+ universe=["Russell 1000", "Min market cap $1B", "Min ADV $5M"],
+ signals_used=["12-1 month return", "Earnings momentum", "Analyst revision momentum"],
+ entry_rules=[
+ "Top decile by 12-1 month return (long)",
+ "Bottom decile by 12-1 month return (short)",
+ "Sector neutral (equal weight per sector)",
+ "No recent earnings surprise > 3 std",
+ ],
+ exit_rules=[
+ "Monthly rebalance",
+ "Remove if drops out of top/bottom decile",
+ "Remove if major news event",
+ "Stop loss at 15% drawdown per position",
+ ],
+ risk_parameters={
+ "max_position_pct": 1.5,
+ "max_sector_pct": 20.0,
+ "stop_loss_pct": 15.0,
+ "max_drawdown_pct": 25.0,
+ "max_leverage": 2.0,
+ "turnover_target": 12.0,
+ "execution_urgency": "patient",
+ "participation_rate": 3.0,
+ "default_algo": "VWAP",
+ "target_sharpe": 0.8,
+ "target_return": 12.0,
+ },
+ allocation=20.0,
+ status="active",
+ )
+
+ # Risk policy
+ kb.add_risk_policy(
+ policy_name="Position Limits Policy",
+ policy_type="position_limits",
+ description="Defines maximum position sizes to ensure diversification and limit single-name risk.",
+ rules=[
+ "No single position may exceed 5% of NAV",
+ "No sector may exceed 25% of NAV",
+ "Aggregate short exposure may not exceed 100% of NAV",
+ "Aggregate long exposure may not exceed 150% of NAV",
+ ],
+ limits={
+ "single_position": {"soft": 3.0, "hard": 5.0},
+ "sector_exposure": {"soft": 20.0, "hard": 25.0},
+ "short_exposure": {"soft": 80.0, "hard": 100.0},
+ "long_exposure": {"soft": 120.0, "hard": 150.0},
+ },
+ escalation_procedure=[
+ "Soft limit breach: Alert risk team, monitor for 24h",
+ "Hard limit breach: Immediately reduce to soft limit",
+ "Repeated breaches: Escalate to Investment Committee",
+ ],
+ effective_date="2024-01-01",
+ )
+
+ kb.add_risk_policy(
+ policy_name="Drawdown Management Policy",
+ policy_type="drawdown",
+ description="Procedures for managing portfolio drawdowns to protect capital.",
+ rules=[
+ "At 10% drawdown: Review all positions, reduce risk by 25%",
+ "At 15% drawdown: Emergency IC meeting, reduce risk by 50%",
+ "At 20% drawdown: Halt new trades, orderly liquidation",
+ ],
+ limits={
+ "drawdown_warning": {"soft": 7.0, "hard": 10.0},
+ "drawdown_action": {"soft": 10.0, "hard": 15.0},
+ "drawdown_halt": {"soft": 15.0, "hard": 20.0},
+ },
+ escalation_procedure=[
+ "Warning level: Daily report to IC Chair",
+ "Action level: Emergency IC call within 2 hours",
+ "Halt level: Full trading halt, board notification",
+ ],
+ effective_date="2024-01-01",
+ )
+
+ # Position sizing guide
+ kb.add_position_sizing_guide(
+ guide_name="Signal-Based Kelly Sizing",
+ methodology="Fractional Kelly Criterion",
+ description="Position sizing based on signal strength and confidence using Kelly criterion with safety margin.",
+ formula="""
+Kelly Fraction = (p * b - q) / b
+
+Where:
+- p = win probability (from signal confidence)
+- q = 1 - p
+- b = win/loss ratio (from expected return / stop loss)
+
+Final Size = Kelly Fraction * 0.25 * Base Size
+
+The 0.25 multiplier (quarter Kelly) accounts for:
+- Estimation error in parameters
+- Fat tails in return distribution
+- Correlation with existing positions
+""",
+ parameters={
+ "kelly_fraction": 0.25,
+ "base_size_pct": 2.0,
+ "min_confidence": 0.55,
+ "max_position_pct": 5.0,
+ },
+ examples=[
+ {"signal_strength": 0.8, "confidence": 0.6, "volatility": 25, "size_pct": 1.5},
+ {"signal_strength": 0.5, "confidence": 0.55, "volatility": 20, "size_pct": 0.8},
+ {"signal_strength": 0.9, "confidence": 0.7, "volatility": 30, "size_pct": 2.0},
+ ],
+ )
+
+ # Execution playbook
+ kb.add_execution_playbook(
+ playbook_name="Large Order Execution",
+ scenario="Orders > 5% of ADV",
+ description="Execution approach for large orders that require careful handling to minimize market impact.",
+ steps=[
+ "Assess current market conditions (spread, depth, volatility)",
+ "Choose appropriate algorithm (typically Arrival Price or VWAP)",
+ "Set participation rate at 3-5% of volume",
+ "Spread execution over 2-4 hours",
+ "Use dark pools for 20-30% of order",
+ "Monitor real-time and adjust if conditions change",
+ "Complete post-trade analysis",
+ ],
+ algorithms=["Arrival Price", "Adaptive VWAP", "Implementation Shortfall"],
+ parameters={
+ "participation_rate": 5.0,
+ "duration_minutes": 180,
+ "urgency": "patient",
+ "max_spread_bps": 10,
+ "limit_offset_bps": 5,
+ "primary_venue": "Auto-route",
+ "dark_pool_pct": 25,
+ "cancel_condition": "Price moves 1% adverse",
+ "pause_condition": "Unusual volume spike",
+ },
+ examples=[
+ "100k shares of AAPL (0.1% of ADV) - use VWAP over 2 hours",
+ "500k shares of MSFT (0.5% of ADV) - use Arrival Price over 3 hours",
+ "1M shares of small cap (5% of ADV) - use Adaptive over full day",
+ ],
+ )
+
+ print("Strategy knowledge seeded successfully")
+
+
+def seed_market_knowledge(market_kb=None):
+ """Seed market data knowledge"""
+ kb = market_kb or get_market_data_knowledge()
+
+ # Price patterns
+ kb.add_price_pattern(
+ ticker="AAPL",
+ pattern_name="Post-Earnings Mean Reversion",
+ description="AAPL shows consistent mean reversion 3-5 days after earnings announcements when the initial move exceeds 5%.",
+ statistics={
+ "mean_return": 1.5,
+ "std_return": 3.2,
+ "sharpe_ratio": 1.2,
+ "win_rate": 0.58,
+ "p_value": 0.008,
+ "sample_size": 45,
+ "lookback": 5,
+ "holding_period": 3,
+ "entry_threshold": 5.0,
+ "exit_threshold": 0.5,
+ "bull_sharpe": 1.5,
+ "bear_sharpe": 0.8,
+ "high_vol_sharpe": 1.8,
+ },
+ tags=["AAPL", "earnings", "mean_reversion", "tech"],
+ )
+
+ # Volume profile
+ kb.add_volume_profile(
+ ticker="AAPL",
+ profile_data={
+ "adv_20": 75000000,
+ "adv_60": 72000000,
+ "open_pct": 8,
+ "morning_pct": 35,
+ "midday_pct": 20,
+ "afternoon_pct": 27,
+ "close_pct": 10,
+ "spread_bps": 1.5,
+ "depth_1pct": 50000000,
+ "kyle_lambda": 0.0008,
+ "opt_participation": 3,
+ "best_time": "10:00-11:30",
+ "avoid_time": "12:00-13:30",
+ },
+ )
+
+ # Sector analysis
+ kb.add_sector_analysis(
+ sector="Technology",
+ analysis={
+ "avg_beta": 1.15,
+ "avg_vol": 28,
+ "ytd_return": 25,
+ "spy_corr": 0.85,
+ "sector_beta": 1.2,
+ "top_holdings": [
+ {"ticker": "AAPL", "weight": 20},
+ {"ticker": "MSFT", "weight": 18},
+ {"ticker": "NVDA", "weight": 12},
+ ],
+ "risk_off_behavior": "Underperforms, high correlation increase",
+ "risk_on_behavior": "Outperforms, leads market rallies",
+ "assessment": "Currently extended, momentum strong but watch for reversal signals",
+ "mean_rev_score": 6,
+ "momentum_score": 8,
+ },
+ )
+
+ # Microstructure insight
+ kb.add_microstructure_insight(
+ topic="Opening Auction Dynamics",
+ insight="The opening auction contains significant price discovery. Stocks that gap up more than 2% tend to continue in the same direction for the first 30 minutes but then mean-revert.",
+ evidence={
+ "period": "2020-2024",
+ "sample_size": 15000,
+ "significance": "p < 0.01",
+ "findings": [
+ "Gap-up > 2%: 65% continue for 30min, then 55% mean revert",
+ "Gap-down > 2%: 60% continue for 30min, then 50% mean revert",
+ "Opening volume predicts intraday volume with R² = 0.7",
+ ],
+ "implications": "Trade with momentum in first 30min, then fade",
+ "actions": [
+ "Set momentum signals for 9:30-10:00 window",
+ "Set mean reversion signals for 10:00-11:00 window",
+ "Size based on opening volume",
+ ],
+ },
+ )
+
+ print("Market knowledge seeded successfully")
+
+
+def seed_trade_history(history_kb=None):
+ """Seed example trade history"""
+ kb = history_kb or get_trade_history_knowledge()
+
+ # Example profitable trade
+ kb.add_trade_record(
+ trade_id="TRD_20240115_001",
+ ticker="AAPL",
+ direction="long",
+ signal_type="mean_reversion",
+ entry_date="2024-01-15",
+ exit_date="2024-01-18",
+ entry_price=185.50,
+ exit_price=189.25,
+ quantity=10000,
+ pnl_bps=202,
+ execution_metrics={
+ "vs_arrival_bps": -2.5,
+ "vs_vwap_bps": 1.2,
+ "impact_bps": 3.0,
+ "fill_rate": 0.98,
+ "algorithm": "TWAP",
+ },
+ signal_metrics={
+ "strength": 0.75,
+ "confidence": 0.68,
+ "p_value": 0.007,
+ "expected_return_bps": 150,
+ },
+ lessons=[
+ "Signal worked well in low-vol environment",
+ "Entry timing was good (near daily low)",
+ "Could have held longer for additional gain",
+ ],
+ )
+
+ # Example loss trade
+ kb.add_trade_record(
+ trade_id="TRD_20240120_002",
+ ticker="NVDA",
+ direction="short",
+ signal_type="mean_reversion",
+ entry_date="2024-01-20",
+ exit_date="2024-01-22",
+ entry_price=615.00,
+ exit_price=642.50,
+ quantity=2000,
+ pnl_bps=-447,
+ execution_metrics={
+ "vs_arrival_bps": 1.5,
+ "vs_vwap_bps": -0.8,
+ "impact_bps": 5.0,
+ "fill_rate": 0.95,
+ "algorithm": "Arrival Price",
+ },
+ signal_metrics={
+ "strength": 0.65,
+ "confidence": 0.58,
+ "p_value": 0.015,
+ "expected_return_bps": 100,
+ },
+ lessons=[
+ "Mean reversion failed during strong momentum",
+ "Should have checked sector momentum before entry",
+ "P-value was borderline (0.015 > 0.01 threshold)",
+ "Stop loss saved from larger loss",
+ ],
+ )
+
+ # Trade lesson
+ kb.add_trade_lesson(
+ lesson_title="Avoid Mean Reversion Shorts in Strong Momentum",
+ context="Several mean reversion short signals failed during Q1 2024 tech rally",
+ what_happened="Mean reversion signals correctly identified overbought conditions but momentum was too strong. Multiple trades hit stop losses.",
+ what_we_learned=[
+ "Check sector momentum before mean reversion shorts",
+ "Avoid shorting stocks with 20+ day momentum > 10%",
+ "Mean reversion works better in range-bound markets",
+ "Consider reducing short exposure in trending markets",
+ ],
+ action_items=[
+ "Add momentum filter to mean reversion signal",
+ "Create market regime indicator",
+ "Reduce mean reversion allocation in trending regimes",
+ ],
+ related_trades=["TRD_20240120_002", "TRD_20240122_003", "TRD_20240125_004"],
+ severity="high",
+ )
+
+ print("Trade history seeded successfully")
+
+
+def seed_all_knowledge():
+ """Seed all knowledge bases with initial data"""
+ print("Seeding Renaissance Technologies Knowledge Base...")
+ print("-" * 50)
+
+ seed_research_knowledge()
+ seed_strategy_knowledge()
+ seed_market_knowledge()
+ seed_trade_history()
+
+ print("-" * 50)
+ print("Knowledge base seeding complete!")
+
+ # Print statistics
+ kb = get_knowledge_base()
+ stats = kb.get_statistics()
+ print(f"\nTotal documents: {stats['total_documents']}")
+ for cat, count in stats['by_category'].items():
+ if count > 0:
+ print(f" - {cat}: {count}")
+
+
+if __name__ == "__main__":
+ seed_all_knowledge()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/strategy_docs.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/strategy_docs.py
new file mode 100644
index 000000000..b5b8ca6cd
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/strategy_docs.py
@@ -0,0 +1,358 @@
+"""
+Strategy Documentation Knowledge
+
+Knowledge base for trading strategy documentation including:
+- Strategy specifications
+- Risk parameters
+- Execution guidelines
+- Position sizing rules
+"""
+
+from typing import Optional, List, Dict, Any
+from datetime import datetime
+import uuid
+
+from .base import (
+ RenTechKnowledge,
+ KnowledgeDocument,
+ KnowledgeCategory,
+ get_knowledge_base,
+)
+
+
+class StrategyKnowledge:
+ """
+ Strategy Documentation Manager.
+
+ Provides structured access to trading strategy specifications,
+ risk parameters, and operational guidelines.
+ """
+
+ def __init__(self, knowledge_base: Optional[RenTechKnowledge] = None):
+ self.kb = knowledge_base or get_knowledge_base()
+ self.category = KnowledgeCategory.STRATEGY
+
+ def add_strategy_spec(
+ self,
+ strategy_name: str,
+ strategy_type: str,
+ description: str,
+ universe: List[str],
+ signals_used: List[str],
+ entry_rules: List[str],
+ exit_rules: List[str],
+ risk_parameters: Dict[str, Any],
+ allocation: float,
+ status: str = "active",
+ ) -> str:
+ """
+ Add a strategy specification document.
+
+ Args:
+ strategy_name: Name of the strategy
+ strategy_type: Type (mean_reversion, momentum, stat_arb, etc.)
+ description: Strategy description
+ universe: Trading universe
+ signals_used: Signals incorporated
+ entry_rules: Entry criteria
+ exit_rules: Exit criteria
+ risk_parameters: Risk limits and parameters
+ allocation: Target allocation (% of portfolio)
+ status: Strategy status (active, paused, retired)
+
+ Returns:
+ Document ID
+ """
+ content = f"""
+# Strategy Specification: {strategy_name}
+
+## Overview
+- **Type**: {strategy_type}
+- **Status**: {status}
+- **Target Allocation**: {allocation}%
+
+## Description
+{description}
+
+## Trading Universe
+{chr(10).join([f"- {u}" for u in universe])}
+
+## Signals Used
+{chr(10).join([f"- {s}" for s in signals_used])}
+
+## Entry Rules
+{chr(10).join([f"{i+1}. {r}" for i, r in enumerate(entry_rules)])}
+
+## Exit Rules
+{chr(10).join([f"{i+1}. {r}" for i, r in enumerate(exit_rules)])}
+
+## Risk Parameters
+- Max Position Size: {risk_parameters.get('max_position_pct', 'N/A')}%
+- Max Sector Exposure: {risk_parameters.get('max_sector_pct', 'N/A')}%
+- Stop Loss: {risk_parameters.get('stop_loss_pct', 'N/A')}%
+- Take Profit: {risk_parameters.get('take_profit_pct', 'N/A')}%
+- Max Drawdown: {risk_parameters.get('max_drawdown_pct', 'N/A')}%
+- Max Leverage: {risk_parameters.get('max_leverage', 'N/A')}x
+- Turnover Target: {risk_parameters.get('turnover_target', 'N/A')}x annual
+
+## Execution Guidelines
+- Urgency: {risk_parameters.get('execution_urgency', 'normal')}
+- Participation Rate: {risk_parameters.get('participation_rate', 'N/A')}%
+- Algorithm: {risk_parameters.get('default_algo', 'TWAP')}
+
+## Performance Targets
+- Target Sharpe: {risk_parameters.get('target_sharpe', 'N/A')}
+- Target Annual Return: {risk_parameters.get('target_return', 'N/A')}%
+"""
+
+ doc = KnowledgeDocument(
+ id=f"strategy_{strategy_name.replace(' ', '_')}_{uuid.uuid4().hex[:8]}",
+ category=self.category,
+ title=f"Strategy: {strategy_name}",
+ content=content,
+ metadata={
+ "strategy_name": strategy_name,
+ "strategy_type": strategy_type,
+ "status": status,
+ "allocation": allocation,
+ "risk_parameters": risk_parameters,
+ "doc_type": "strategy_spec",
+ },
+ tags=["strategy", strategy_type.lower(), strategy_name.lower()],
+ importance=0.95, # Strategy specs are critical
+ )
+
+ return self.kb.add_document(doc)
+
+ def add_risk_policy(
+ self,
+ policy_name: str,
+ policy_type: str,
+ description: str,
+ rules: List[str],
+ limits: Dict[str, Any],
+ escalation_procedure: List[str],
+ effective_date: str,
+ ) -> str:
+ """Add a risk policy document"""
+ content = f"""
+# Risk Policy: {policy_name}
+
+## Policy Type: {policy_type}
+## Effective Date: {effective_date}
+
+## Description
+{description}
+
+## Rules
+{chr(10).join([f"{i+1}. {r}" for i, r in enumerate(rules)])}
+
+## Limits
+| Metric | Soft Limit | Hard Limit |
+|--------|------------|------------|
+{chr(10).join([f"| {k} | {v.get('soft', 'N/A')} | {v.get('hard', 'N/A')} |" for k, v in limits.items()])}
+
+## Breach Response
+1. Soft limit breach: Warning, monitor closely
+2. Hard limit breach: Immediate action required
+3. Escalation to IC if breach persists
+
+## Escalation Procedure
+{chr(10).join([f"{i+1}. {e}" for i, e in enumerate(escalation_procedure)])}
+
+## Monitoring
+- Frequency: Real-time
+- Reports: Daily risk report
+- Reviews: Weekly risk committee
+"""
+
+ doc = KnowledgeDocument(
+ id=f"policy_{policy_name.replace(' ', '_')}_{uuid.uuid4().hex[:8]}",
+ category=self.category,
+ title=f"Policy: {policy_name}",
+ content=content,
+ metadata={
+ "policy_name": policy_name,
+ "policy_type": policy_type,
+ "limits": limits,
+ "effective_date": effective_date,
+ "doc_type": "risk_policy",
+ },
+ tags=["policy", "risk", policy_type.lower()],
+ importance=0.95,
+ )
+
+ return self.kb.add_document(doc)
+
+ def add_execution_playbook(
+ self,
+ playbook_name: str,
+ scenario: str,
+ description: str,
+ steps: List[str],
+ algorithms: List[str],
+ parameters: Dict[str, Any],
+ examples: List[str],
+ ) -> str:
+ """Add an execution playbook"""
+ content = f"""
+# Execution Playbook: {playbook_name}
+
+## Scenario: {scenario}
+
+## Description
+{description}
+
+## When to Use
+This playbook applies when:
+{chr(10).join([f"- {e}" for e in examples])}
+
+## Execution Steps
+{chr(10).join([f"{i+1}. {s}" for i, s in enumerate(steps)])}
+
+## Recommended Algorithms
+{chr(10).join([f"- {a}" for a in algorithms])}
+
+## Parameters
+- Participation Rate: {parameters.get('participation_rate', 'N/A')}%
+- Duration: {parameters.get('duration_minutes', 'N/A')} minutes
+- Urgency Level: {parameters.get('urgency', 'normal')}
+- Max Spread to Pay: {parameters.get('max_spread_bps', 'N/A')} bps
+- Price Limit Offset: {parameters.get('limit_offset_bps', 'N/A')} bps
+
+## Venue Preferences
+- Primary: {parameters.get('primary_venue', 'Best available')}
+- Dark Pool: {parameters.get('dark_pool_pct', 'N/A')}%
+
+## Risk Controls
+- Cancel if: {parameters.get('cancel_condition', 'N/A')}
+- Pause if: {parameters.get('pause_condition', 'N/A')}
+"""
+
+ doc = KnowledgeDocument(
+ id=f"playbook_{playbook_name.replace(' ', '_')}_{uuid.uuid4().hex[:8]}",
+ category=self.category,
+ title=f"Playbook: {playbook_name}",
+ content=content,
+ metadata={
+ "playbook_name": playbook_name,
+ "scenario": scenario,
+ "algorithms": algorithms,
+ "parameters": parameters,
+ "doc_type": "execution_playbook",
+ },
+ tags=["execution", "playbook", scenario.lower().replace(" ", "_")],
+ importance=0.8,
+ )
+
+ return self.kb.add_document(doc)
+
+ def add_position_sizing_guide(
+ self,
+ guide_name: str,
+ methodology: str,
+ description: str,
+ formula: str,
+ parameters: Dict[str, Any],
+ examples: List[Dict[str, Any]],
+ ) -> str:
+ """Add position sizing methodology"""
+ content = f"""
+# Position Sizing Guide: {guide_name}
+
+## Methodology: {methodology}
+
+## Description
+{description}
+
+## Formula
+{formula}
+
+## Parameters
+{chr(10).join([f"- {k}: {v}" for k, v in parameters.items()])}
+
+## Examples
+
+{chr(10).join([f'''
+### Example {i+1}
+- Signal Strength: {ex.get('signal_strength', 'N/A')}
+- Confidence: {ex.get('confidence', 'N/A')}
+- Volatility: {ex.get('volatility', 'N/A')}%
+- **Calculated Size**: {ex.get('size_pct', 'N/A')}%
+''' for i, ex in enumerate(examples)])}
+
+## Constraints Applied
+- Max position: 5% of NAV (hard limit)
+- Min position: 0.1% of NAV (to be meaningful)
+- Liquidity adjustment: Size ≤ 1% of ADV
+- Correlation penalty: Reduce if >0.7 corr with existing
+
+## Kelly Fraction
+We use {parameters.get('kelly_fraction', 0.25)} of full Kelly criterion
+to account for estimation error and fat tails.
+"""
+
+ doc = KnowledgeDocument(
+ id=f"sizing_{guide_name.replace(' ', '_')}_{uuid.uuid4().hex[:8]}",
+ category=self.category,
+ title=f"Sizing: {guide_name}",
+ content=content,
+ metadata={
+ "guide_name": guide_name,
+ "methodology": methodology,
+ "parameters": parameters,
+ "doc_type": "position_sizing",
+ },
+ tags=["sizing", "position", methodology.lower()],
+ importance=0.85,
+ )
+
+ return self.kb.add_document(doc)
+
+ def search_strategies(
+ self,
+ query: str,
+ strategy_type: Optional[str] = None,
+ status: Optional[str] = None,
+ limit: int = 10,
+ ) -> List[Dict[str, Any]]:
+ """Search strategy documents"""
+ results = self.kb.search(
+ query=query,
+ category=self.category,
+ limit=limit,
+ )
+
+ if strategy_type:
+ results = [r for r in results if r.get("metadata", {}).get("strategy_type") == strategy_type]
+
+ if status:
+ results = [r for r in results if r.get("metadata", {}).get("status") == status]
+
+ return results
+
+ def get_active_strategies(self) -> List[KnowledgeDocument]:
+ """Get all active strategies"""
+ docs = self.kb.get_documents_by_category(self.category)
+ return [
+ d for d in docs
+ if d.metadata.get("doc_type") == "strategy_spec"
+ and d.metadata.get("status") == "active"
+ ]
+
+ def get_risk_policies(self) -> List[KnowledgeDocument]:
+ """Get all risk policies"""
+ docs = self.kb.get_documents_by_category(self.category)
+ return [d for d in docs if d.metadata.get("doc_type") == "risk_policy"]
+
+
+# Global instance
+_strategy_knowledge: Optional[StrategyKnowledge] = None
+
+
+def get_strategy_knowledge() -> StrategyKnowledge:
+ """Get the global strategy knowledge instance"""
+ global _strategy_knowledge
+ if _strategy_knowledge is None:
+ _strategy_knowledge = StrategyKnowledge()
+ return _strategy_knowledge
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/trade_history.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/trade_history.py
new file mode 100644
index 000000000..34f750683
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/knowledge/trade_history.py
@@ -0,0 +1,409 @@
+"""
+Trade History Knowledge
+
+Knowledge base for historical trade data including:
+- Trade outcomes
+- Execution quality
+- Lessons learned
+- Pattern recognition from past trades
+"""
+
+from typing import Optional, List, Dict, Any
+from datetime import datetime
+import uuid
+
+from .base import (
+ RenTechKnowledge,
+ KnowledgeDocument,
+ KnowledgeCategory,
+ get_knowledge_base,
+)
+
+
+class TradeHistoryKnowledge:
+ """
+ Trade History Knowledge Manager.
+
+ Provides structured access to historical trade information,
+ outcomes, and lessons learned.
+ """
+
+ def __init__(self, knowledge_base: Optional[RenTechKnowledge] = None):
+ self.kb = knowledge_base or get_knowledge_base()
+ self.category = KnowledgeCategory.TRADE_HISTORY
+
+ def add_trade_record(
+ self,
+ trade_id: str,
+ ticker: str,
+ direction: str,
+ signal_type: str,
+ entry_date: str,
+ exit_date: Optional[str],
+ entry_price: float,
+ exit_price: Optional[float],
+ quantity: int,
+ pnl_bps: Optional[float],
+ execution_metrics: Dict[str, Any],
+ signal_metrics: Dict[str, Any],
+ lessons: Optional[List[str]] = None,
+ ) -> str:
+ """
+ Add a completed trade record to knowledge base.
+
+ Args:
+ trade_id: Unique trade identifier
+ ticker: Stock ticker
+ direction: long/short
+ signal_type: Type of signal that generated trade
+ entry_date: Entry date
+ exit_date: Exit date (None if still open)
+ entry_price: Entry price
+ exit_price: Exit price (None if still open)
+ quantity: Number of shares
+ pnl_bps: P&L in basis points
+ execution_metrics: Execution quality metrics
+ signal_metrics: Signal performance metrics
+ lessons: Lessons learned
+
+ Returns:
+ Document ID
+ """
+ status = "closed" if exit_date else "open"
+ pnl_str = f"{pnl_bps:+.1f} bps" if pnl_bps else "N/A"
+ outcome = "profitable" if (pnl_bps or 0) > 0 else "loss" if (pnl_bps or 0) < 0 else "break_even"
+
+ content = f"""
+# Trade Record: {trade_id}
+
+## Summary
+- **Ticker**: {ticker}
+- **Direction**: {direction.upper()}
+- **Signal Type**: {signal_type}
+- **Status**: {status.upper()}
+- **Outcome**: {outcome.upper()}
+
+## Timing
+- Entry Date: {entry_date}
+- Exit Date: {exit_date or 'Still Open'}
+- Holding Period: {self._calc_holding_period(entry_date, exit_date)}
+
+## Prices
+- Entry Price: ${entry_price:.2f}
+- Exit Price: ${exit_price:.2f if exit_price else 'N/A'}
+- Quantity: {quantity:,} shares
+- Notional: ${quantity * entry_price:,.0f}
+
+## Performance
+- P&L: {pnl_str}
+- Return: {(pnl_bps or 0) / 100:.2f}%
+
+## Signal Metrics
+- Signal Strength: {signal_metrics.get('strength', 'N/A')}
+- Confidence: {signal_metrics.get('confidence', 'N/A')}
+- P-value: {signal_metrics.get('p_value', 'N/A')}
+- Expected Return: {signal_metrics.get('expected_return_bps', 'N/A')} bps
+- Actual vs Expected: {((pnl_bps or 0) - signal_metrics.get('expected_return_bps', 0)):+.1f} bps
+
+## Execution Metrics
+- vs Arrival: {execution_metrics.get('vs_arrival_bps', 'N/A')} bps
+- vs VWAP: {execution_metrics.get('vs_vwap_bps', 'N/A')} bps
+- Market Impact: {execution_metrics.get('impact_bps', 'N/A')} bps
+- Fill Rate: {execution_metrics.get('fill_rate', 'N/A')}
+- Algorithm Used: {execution_metrics.get('algorithm', 'N/A')}
+
+## Lessons Learned
+{chr(10).join([f"- {l}" for l in (lessons or ['No lessons documented.'])])}
+
+## Tags
+- Outcome: {outcome}
+- Direction: {direction}
+- Signal: {signal_type}
+"""
+
+ doc = KnowledgeDocument(
+ id=f"trade_{trade_id}",
+ category=self.category,
+ title=f"Trade: {ticker} {direction} ({outcome})",
+ content=content,
+ metadata={
+ "trade_id": trade_id,
+ "ticker": ticker,
+ "direction": direction,
+ "signal_type": signal_type,
+ "outcome": outcome,
+ "pnl_bps": pnl_bps,
+ "entry_date": entry_date,
+ "exit_date": exit_date,
+ "execution_metrics": execution_metrics,
+ "signal_metrics": signal_metrics,
+ "doc_type": "trade_record",
+ },
+ tags=[ticker, direction, signal_type, outcome, "trade"],
+ importance=0.6 if outcome == "loss" else 0.5, # Losses are more important to remember
+ )
+
+ return self.kb.add_document(doc)
+
+ def _calc_holding_period(self, entry: str, exit: Optional[str]) -> str:
+ """Calculate holding period string"""
+ if not exit:
+ return "Ongoing"
+ try:
+ entry_dt = datetime.fromisoformat(entry)
+ exit_dt = datetime.fromisoformat(exit)
+ days = (exit_dt - entry_dt).days
+ return f"{days} days"
+ except:
+ return "Unknown"
+
+ def add_trade_lesson(
+ self,
+ lesson_title: str,
+ context: str,
+ what_happened: str,
+ what_we_learned: List[str],
+ action_items: List[str],
+ related_trades: List[str],
+ severity: str = "medium",
+ ) -> str:
+ """
+ Add a trade lesson learned document.
+
+ Args:
+ lesson_title: Title of the lesson
+ context: Context/situation
+ what_happened: What occurred
+ what_we_learned: Key learnings
+ action_items: Actions to take
+ related_trades: Related trade IDs
+ severity: Impact severity (low, medium, high, critical)
+
+ Returns:
+ Document ID
+ """
+ content = f"""
+# Trade Lesson: {lesson_title}
+
+## Severity: {severity.upper()}
+## Date: {datetime.utcnow().strftime('%Y-%m-%d')}
+
+## Context
+{context}
+
+## What Happened
+{what_happened}
+
+## What We Learned
+{chr(10).join([f"- {l}" for l in what_we_learned])}
+
+## Action Items
+{chr(10).join([f"- [ ] {a}" for a in action_items])}
+
+## Related Trades
+{chr(10).join([f"- {t}" for t in related_trades])}
+
+## Prevention
+How to prevent this in the future:
+{chr(10).join([f"- {l}" for l in what_we_learned[:3]])}
+
+## Review
+- Reviewed by: Pending
+- Review date: Pending
+- Status: Active lesson
+"""
+
+ doc = KnowledgeDocument(
+ id=f"lesson_{lesson_title.replace(' ', '_')[:30]}_{uuid.uuid4().hex[:8]}",
+ category=self.category,
+ title=f"Lesson: {lesson_title}",
+ content=content,
+ metadata={
+ "lesson_title": lesson_title,
+ "severity": severity,
+ "related_trades": related_trades,
+ "action_items": action_items,
+ "doc_type": "trade_lesson",
+ },
+ tags=["lesson", severity, "learning"],
+ importance=0.95 if severity == "critical" else 0.8 if severity == "high" else 0.6,
+ )
+
+ return self.kb.add_document(doc)
+
+ def add_pattern_observation(
+ self,
+ pattern_name: str,
+ observation: str,
+ supporting_trades: List[str],
+ statistics: Dict[str, Any],
+ recommendation: str,
+ ) -> str:
+ """Add a pattern observed across trades"""
+ content = f"""
+# Trade Pattern: {pattern_name}
+
+## Observation
+{observation}
+
+## Supporting Evidence
+- Number of trades: {len(supporting_trades)}
+- Trade IDs: {', '.join(supporting_trades[:5])}{'...' if len(supporting_trades) > 5 else ''}
+
+## Statistics
+- Win Rate: {statistics.get('win_rate', 'N/A')}%
+- Average P&L: {statistics.get('avg_pnl_bps', 'N/A')} bps
+- Sample Size: {statistics.get('sample_size', 'N/A')}
+- Confidence: {statistics.get('confidence', 'N/A')}%
+
+## Recommendation
+{recommendation}
+
+## Action
+- If pattern is positive: Consider increasing allocation
+- If pattern is negative: Investigate root cause
+- Document any model changes
+"""
+
+ doc = KnowledgeDocument(
+ id=f"pattern_{pattern_name.replace(' ', '_')}_{uuid.uuid4().hex[:8]}",
+ category=self.category,
+ title=f"Pattern: {pattern_name}",
+ content=content,
+ metadata={
+ "pattern_name": pattern_name,
+ "supporting_trades": supporting_trades,
+ "statistics": statistics,
+ "doc_type": "pattern_observation",
+ },
+ tags=["pattern", "analysis"],
+ importance=0.75,
+ )
+
+ return self.kb.add_document(doc)
+
+ def add_execution_analysis(
+ self,
+ period: str,
+ summary: str,
+ statistics: Dict[str, Any],
+ best_practices: List[str],
+ areas_for_improvement: List[str],
+ ) -> str:
+ """Add execution quality analysis"""
+ content = f"""
+# Execution Analysis: {period}
+
+## Summary
+{summary}
+
+## Statistics
+- Total Trades: {statistics.get('total_trades', 'N/A')}
+- Total Notional: ${statistics.get('total_notional', 0):,.0f}
+- Average Cost: {statistics.get('avg_cost_bps', 'N/A')} bps
+- vs Arrival (avg): {statistics.get('avg_vs_arrival', 'N/A')} bps
+- vs VWAP (avg): {statistics.get('avg_vs_vwap', 'N/A')} bps
+- Fill Rate (avg): {statistics.get('avg_fill_rate', 'N/A')}%
+
+## Best Performing
+- Best Algorithm: {statistics.get('best_algo', 'N/A')}
+- Best Time of Day: {statistics.get('best_time', 'N/A')}
+- Best Venue: {statistics.get('best_venue', 'N/A')}
+
+## Worst Performing
+- Worst Algorithm: {statistics.get('worst_algo', 'N/A')}
+- Worst Time of Day: {statistics.get('worst_time', 'N/A')}
+
+## Best Practices Confirmed
+{chr(10).join([f"- {b}" for b in best_practices])}
+
+## Areas for Improvement
+{chr(10).join([f"- {a}" for a in areas_for_improvement])}
+
+## Recommendations
+Based on this analysis, consider:
+1. Increase usage of {statistics.get('best_algo', 'best performing algo')}
+2. Prefer trading during {statistics.get('best_time', 'optimal hours')}
+3. Reduce usage of {statistics.get('worst_algo', 'underperforming algo')}
+"""
+
+ doc = KnowledgeDocument(
+ id=f"exec_analysis_{period.replace(' ', '_')}_{uuid.uuid4().hex[:8]}",
+ category=self.category,
+ title=f"Execution Analysis: {period}",
+ content=content,
+ metadata={
+ "period": period,
+ "statistics": statistics,
+ "doc_type": "execution_analysis",
+ },
+ tags=["execution", "analysis", period],
+ importance=0.7,
+ )
+
+ return self.kb.add_document(doc)
+
+ def search_trades(
+ self,
+ query: str,
+ ticker: Optional[str] = None,
+ outcome: Optional[str] = None,
+ signal_type: Optional[str] = None,
+ limit: int = 10,
+ ) -> List[Dict[str, Any]]:
+ """Search trade history"""
+ results = self.kb.search(
+ query=query,
+ category=self.category,
+ limit=limit * 2, # Get more, then filter
+ )
+
+ if ticker:
+ results = [r for r in results if r.get("metadata", {}).get("ticker") == ticker]
+ if outcome:
+ results = [r for r in results if r.get("metadata", {}).get("outcome") == outcome]
+ if signal_type:
+ results = [r for r in results if r.get("metadata", {}).get("signal_type") == signal_type]
+
+ return results[:limit]
+
+ def get_similar_trades(
+ self,
+ ticker: str,
+ signal_type: str,
+ direction: str,
+ limit: int = 5,
+ ) -> List[KnowledgeDocument]:
+ """Get similar historical trades for reference"""
+ query = f"{ticker} {signal_type} {direction} trade"
+ results = self.search_trades(
+ query=query,
+ ticker=ticker,
+ signal_type=signal_type,
+ limit=limit,
+ )
+ return [self.kb.get_document(r["id"]) for r in results if r.get("id")]
+
+ def get_lessons_for_situation(
+ self,
+ situation: str,
+ limit: int = 5,
+ ) -> List[Dict[str, Any]]:
+ """Get relevant lessons for a given situation"""
+ return self.kb.search(
+ query=f"lesson {situation}",
+ category=self.category,
+ limit=limit,
+ )
+
+
+# Global instance
+_trade_history_knowledge: Optional[TradeHistoryKnowledge] = None
+
+
+def get_trade_history_knowledge() -> TradeHistoryKnowledge:
+ """Get the global trade history knowledge instance"""
+ global _trade_history_knowledge
+ if _trade_history_knowledge is None:
+ _trade_history_knowledge = TradeHistoryKnowledge()
+ return _trade_history_knowledge
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/main.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/main.py
new file mode 100644
index 000000000..49cb0d351
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/main.py
@@ -0,0 +1,479 @@
+"""
+Renaissance Technologies Hedge Fund System
+
+Main orchestrator for the multi-agent Renaissance Technologies system.
+Implements Jim Simons' systematic quantitative approach.
+
+Architecture:
+ ┌─────────────────────────────────────────────────────────────┐
+ │ RenaissanceTechnologiesSystem │
+ │ │
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
+ │ │ Signal │ │ Risk │ │ Execution │ │
+ │ │ Generation │ │ Modeling │ │ Optimization │ │
+ │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
+ │ │ │ │ │
+ │ │ ┌──────────────┴──────────────┐ │ │
+ │ │ │ Statistical Arbitrage │ │ │
+ │ │ └──────────────┬──────────────┘ │ │
+ │ │ │ │ │
+ │ └────────────────┬┴─────────────────┘ │
+ │ │ │
+ │ ┌────────▼────────┐ │
+ │ │ Medallion │ │
+ │ │ Synthesizer │ │
+ │ └────────┬────────┘ │
+ │ │ │
+ │ ┌────────▼────────┐ │
+ │ │ Final Decision │ │
+ │ └─────────────────┘ │
+ └─────────────────────────────────────────────────────────────┘
+
+Usage:
+ from renaissance_technologies_hedge_fund_agent import RenaissanceTechnologiesSystem
+
+ # Pure quantitative analysis (no LLM)
+ system = RenaissanceTechnologiesSystem()
+ result = system.analyze("AAPL")
+
+ # With LLM enhancement
+ system = RenaissanceTechnologiesSystem(
+ model_provider="openai",
+ api_key="sk-..."
+ )
+ result = system.analyze_with_llm("AAPL")
+"""
+
+from typing import Dict, Any, Optional, List
+from dataclasses import dataclass
+import json
+import logging
+
+# Analysis functions (pure Python, no LLM)
+from .strategies import (
+ run_signal_analysis,
+ run_risk_analysis,
+ run_execution_analysis,
+ run_stat_arb_analysis,
+ synthesize_decision,
+)
+# Agno agents (LLM-enhanced)
+from .agents import (
+ create_signal_scientist,
+ create_risk_quant,
+ create_execution_trader,
+ create_quant_researcher,
+ create_investment_committee_chair,
+)
+from .models.schemas import MedallionDecision, RenaissancePortfolioAnalysis, SignalType
+from .utils import (
+ fetch_stock_data_yfinance,
+ fetch_market_benchmark,
+ validate_data,
+ prepare_analysis_inputs,
+)
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class AnalysisConfig:
+ """Configuration for Renaissance analysis"""
+ trade_value: float = 1_000_000 # Default $1M trade
+ period: str = "1y" # Historical data period
+ include_peers: bool = False
+ peer_ticker: Optional[str] = None
+ expected_edge_bps: float = 20.0
+ signal_decay_hours: float = 24.0
+
+
+class RenaissanceTechnologiesSystem:
+ """
+ Renaissance Technologies Multi-Agent System.
+
+ Implements Jim Simons' quantitative approach with:
+ - Signal Generation (mean reversion, momentum, patterns)
+ - Risk Modeling (volatility, VaR, factor decomposition)
+ - Execution Optimization (market impact, TCA)
+ - Statistical Arbitrage (mispricing, regime detection)
+ - Medallion Synthesis (final systematic decision)
+ """
+
+ def __init__(
+ self,
+ model_provider: Optional[str] = None,
+ model_id: str = "gpt-4o",
+ api_key: Optional[str] = None
+ ):
+ """
+ Initialize Renaissance Technologies System.
+
+ Args:
+ model_provider: LLM provider (openai, anthropic, groq) - None for pure quant
+ model_id: Model identifier
+ api_key: API key for LLM provider
+ """
+ self.model_provider = model_provider
+ self.model_id = model_id
+ self.api_key = api_key
+
+ # Create Agno agents if LLM enabled
+ self._agents = None
+ if model_provider:
+ self._agents = self._create_agents()
+
+ def _create_agents(self) -> Dict[str, Any]:
+ """
+ Create Agno agents for LLM-enhanced analysis.
+
+ Now uses dynamic model factory that reads from frontend SQLite config.
+ """
+ from .config import get_config
+ cfg = get_config()
+
+ # Agents will use model factory internally
+ # No need to pass model provider info - it's loaded from frontend DB
+ return {
+ "signal": create_signal_scientist(cfg),
+ "risk": create_risk_quant(cfg),
+ "execution": create_execution_trader(cfg),
+ "stat_arb": create_quant_researcher(cfg),
+ "medallion": create_investment_committee_chair(cfg),
+ }
+
+ def analyze(
+ self,
+ ticker: str,
+ config: Optional[AnalysisConfig] = None
+ ) -> MedallionDecision:
+ """
+ Run pure quantitative analysis (no LLM).
+
+ This is the core Renaissance approach: mathematical models only.
+
+ Args:
+ ticker: Stock ticker to analyze
+ config: Analysis configuration
+
+ Returns:
+ MedallionDecision with signal and recommendations
+ """
+ config = config or AnalysisConfig()
+
+ # Fetch data
+ logger.info(f"Fetching data for {ticker}...")
+ data = fetch_stock_data_yfinance(ticker, config.period)
+
+ # Validate data
+ is_valid, warnings = validate_data(data)
+ if not is_valid:
+ logger.warning(f"Data validation failed: {warnings}")
+ return self._create_error_decision(ticker, warnings)
+
+ for warning in warnings:
+ logger.warning(warning)
+
+ # Prepare inputs
+ inputs = prepare_analysis_inputs(data, config.trade_value)
+
+ # Fetch market benchmark for risk analysis
+ market_prices = fetch_market_benchmark(config.period)
+
+ # Run all analyses in parallel (conceptually)
+ logger.info("Running signal generation analysis...")
+ signal_analysis = run_signal_analysis(
+ ticker=ticker,
+ prices=inputs["prices"],
+ revenues=inputs["revenues"],
+ earnings=inputs["earnings"],
+ metrics=inputs["metrics"]
+ )
+
+ logger.info("Running risk modeling analysis...")
+ risk_analysis = run_risk_analysis(
+ ticker=ticker,
+ prices=inputs["prices"],
+ market_prices=market_prices,
+ market_cap=inputs["market_cap"],
+ signal_strength=signal_analysis["aggregate_signal"],
+ signal_confidence=signal_analysis["statistical_significance"] * 100
+ )
+
+ logger.info("Running execution analysis...")
+ execution_analysis = run_execution_analysis(
+ ticker=ticker,
+ trade_value=config.trade_value,
+ market_cap=inputs["market_cap"],
+ avg_daily_volume=inputs["avg_daily_volume"],
+ volatility=inputs["volatility"],
+ expected_edge_bps=config.expected_edge_bps,
+ signal_decay_hours=config.signal_decay_hours
+ )
+
+ logger.info("Running statistical arbitrage analysis...")
+ stat_arb_analysis = run_stat_arb_analysis(
+ ticker=ticker,
+ prices=inputs["prices"],
+ intrinsic_estimates=None, # Would need analyst estimates
+ peer_prices=None, # Would need peer selection
+ metrics=inputs["metrics"]
+ )
+
+ # Synthesize final decision
+ logger.info("Synthesizing Medallion decision...")
+ decision = synthesize_decision(
+ ticker=ticker,
+ signal_analysis=signal_analysis,
+ risk_analysis=risk_analysis,
+ execution_analysis=execution_analysis,
+ stat_arb_analysis=stat_arb_analysis
+ )
+
+ return decision
+
+ def analyze_portfolio(
+ self,
+ tickers: List[str],
+ config: Optional[AnalysisConfig] = None
+ ) -> RenaissancePortfolioAnalysis:
+ """
+ Analyze multiple tickers as a portfolio.
+
+ Args:
+ tickers: List of stock tickers
+ config: Analysis configuration
+
+ Returns:
+ Portfolio analysis with all individual decisions
+ """
+ config = config or AnalysisConfig()
+
+ decisions = {}
+ for ticker in tickers:
+ try:
+ decision = self.analyze(ticker, config)
+ decisions[ticker] = decision
+ except Exception as e:
+ logger.error(f"Error analyzing {ticker}: {e}")
+ decisions[ticker] = self._create_error_decision(ticker, [str(e)])
+
+ # Calculate portfolio-level metrics
+ signals = [d.signal for d in decisions.values()]
+ confidences = [d.confidence for d in decisions.values()]
+
+ bullish_count = sum(1 for s in signals if s == SignalType.BULLISH)
+ bearish_count = sum(1 for s in signals if s == SignalType.BEARISH)
+
+ if bullish_count > bearish_count * 1.5:
+ portfolio_signal = SignalType.BULLISH
+ elif bearish_count > bullish_count * 1.5:
+ portfolio_signal = SignalType.BEARISH
+ else:
+ portfolio_signal = SignalType.NEUTRAL
+
+ portfolio_confidence = sum(confidences) / len(confidences) if confidences else 0
+
+ summary = self._generate_portfolio_summary(decisions, portfolio_signal)
+
+ return RenaissancePortfolioAnalysis(
+ decisions=decisions,
+ portfolio_signal=portfolio_signal,
+ portfolio_confidence=portfolio_confidence,
+ correlation_matrix=None, # Would need to calculate
+ portfolio_var_95=None, # Would need to calculate
+ summary=summary
+ )
+
+ def analyze_with_llm(
+ self,
+ ticker: str,
+ query: Optional[str] = None,
+ config: Optional[AnalysisConfig] = None
+ ) -> Dict[str, Any]:
+ """
+ Run analysis with LLM enhancement.
+
+ Combines pure quant analysis with LLM reasoning.
+
+ Args:
+ ticker: Stock ticker
+ query: Optional specific question
+ config: Analysis configuration
+
+ Returns:
+ Enhanced analysis with LLM insights
+ """
+ if not self._agents:
+ raise ValueError("LLM not configured. Provide model_provider in constructor.")
+
+ # First run pure quant analysis
+ decision = self.analyze(ticker, config)
+
+ # Enhance with LLM
+ query = query or f"Provide Renaissance Technologies-style analysis for {ticker}"
+
+ # Run LLM agents
+ llm_response = self._agents["medallion"].run(
+ f"""Based on the following quantitative analysis, provide your assessment:
+
+Ticker: {ticker}
+Signal: {decision.signal.value}
+Confidence: {decision.confidence}%
+Statistical Edge: {decision.statistical_edge}
+
+Key Factors: {', '.join(decision.key_factors)}
+Risks: {', '.join(decision.risks)}
+
+Reasoning: {decision.reasoning}
+
+Question: {query}
+"""
+ )
+
+ return {
+ "quant_decision": decision,
+ "llm_enhancement": llm_response.content if hasattr(llm_response, 'content') else str(llm_response)
+ }
+
+ def _create_error_decision(
+ self,
+ ticker: str,
+ errors: List[str]
+ ) -> MedallionDecision:
+ """Create a neutral decision when analysis fails."""
+ from .models.schemas import PositionSizing
+
+ return MedallionDecision(
+ ticker=ticker,
+ signal=SignalType.NEUTRAL,
+ confidence=0.0,
+ statistical_edge=0.0,
+ signal_score=5.0,
+ risk_score=5.0,
+ execution_score=5.0,
+ arbitrage_score=5.0,
+ position_sizing=PositionSizing(
+ recommended_size_pct=0.0,
+ kelly_fraction=0.0,
+ max_position_size_pct=0.0,
+ leverage_recommendation=1.0
+ ),
+ signal_strength={
+ "mean_reversion": 0.0,
+ "momentum": 0.0,
+ "statistical_arbitrage": 0.0,
+ "risk_adjusted_return": 0.0
+ },
+ reasoning=f"Analysis failed: {'; '.join(errors)}",
+ key_factors=["Insufficient data for analysis"],
+ risks=errors
+ )
+
+ def _generate_portfolio_summary(
+ self,
+ decisions: Dict[str, MedallionDecision],
+ portfolio_signal: SignalType
+ ) -> str:
+ """Generate portfolio summary text."""
+ total = len(decisions)
+ bullish = sum(1 for d in decisions.values() if d.signal == SignalType.BULLISH)
+ bearish = sum(1 for d in decisions.values() if d.signal == SignalType.BEARISH)
+ neutral = total - bullish - bearish
+
+ avg_confidence = sum(d.confidence for d in decisions.values()) / total if total else 0
+
+ return (
+ f"Portfolio Analysis: {total} securities analyzed. "
+ f"Signal distribution: {bullish} bullish, {bearish} bearish, {neutral} neutral. "
+ f"Overall signal: {portfolio_signal.value.upper()}. "
+ f"Average confidence: {avg_confidence:.1f}%."
+ )
+
+
+def main():
+ """CLI entry point for Renaissance Technologies analysis."""
+ import sys
+ import argparse
+
+ parser = argparse.ArgumentParser(
+ description="Renaissance Technologies Quantitative Analysis System"
+ )
+ parser.add_argument("ticker", help="Stock ticker to analyze")
+ parser.add_argument(
+ "--trade-value",
+ type=float,
+ default=1_000_000,
+ help="Trade value in dollars (default: 1000000)"
+ )
+ parser.add_argument(
+ "--period",
+ default="1y",
+ choices=["1mo", "3mo", "6mo", "1y", "2y", "5y"],
+ help="Historical data period (default: 1y)"
+ )
+ parser.add_argument(
+ "--json",
+ action="store_true",
+ help="Output as JSON"
+ )
+ parser.add_argument(
+ "--verbose",
+ "-v",
+ action="store_true",
+ help="Verbose output"
+ )
+
+ args = parser.parse_args()
+
+ # Configure logging
+ logging.basicConfig(
+ level=logging.INFO if args.verbose else logging.WARNING,
+ format="%(asctime)s - %(levelname)s - %(message)s"
+ )
+
+ # Run analysis
+ system = RenaissanceTechnologiesSystem()
+ config = AnalysisConfig(
+ trade_value=args.trade_value,
+ period=args.period
+ )
+
+ try:
+ decision = system.analyze(args.ticker, config)
+
+ if args.json:
+ # Output as JSON
+ print(json.dumps(decision.model_dump(), indent=2, default=str))
+ else:
+ # Human-readable output
+ print("\n" + "=" * 60)
+ print(f"RENAISSANCE TECHNOLOGIES ANALYSIS: {args.ticker}")
+ print("=" * 60)
+ print(f"\nSignal: {decision.signal.value.upper()}")
+ print(f"Confidence: {decision.confidence:.1f}%")
+ print(f"Statistical Edge: {decision.statistical_edge:.4f}")
+ print(f"\nPosition Sizing:")
+ print(f" Recommended: {decision.position_sizing.recommended_size_pct:.2f}% of portfolio")
+ print(f" Kelly Fraction: {decision.position_sizing.kelly_fraction:.2f}")
+ print(f" Leverage: {decision.position_sizing.leverage_recommendation:.1f}x")
+ print(f"\nComponent Scores:")
+ print(f" Signal: {decision.signal_score:.1f}/10")
+ print(f" Risk: {decision.risk_score:.1f}/10")
+ print(f" Execution: {decision.execution_score:.1f}/10")
+ print(f" Arbitrage: {decision.arbitrage_score:.1f}/10")
+ print(f"\nKey Factors:")
+ for factor in decision.key_factors:
+ print(f" - {factor}")
+ print(f"\nRisks:")
+ for risk in decision.risks:
+ print(f" - {risk}")
+ print(f"\nReasoning:\n{decision.reasoning}")
+ print("\n" + "=" * 60)
+
+ except Exception as e:
+ print(f"Error: {e}", file=sys.stderr)
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/__init__.py
new file mode 100644
index 000000000..119e9f876
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/__init__.py
@@ -0,0 +1,39 @@
+"""
+Renaissance Technologies Memory System
+
+Multi-layer memory architecture for agent learning and recall:
+- Short-term: Recent interactions and decisions (24 hours)
+- Long-term: Persistent knowledge and patterns (years)
+- Episodic: Specific trade events and outcomes
+- Semantic: General trading knowledge and rules
+- Working: Active context during decision making
+"""
+
+from .base import (
+ RenTechMemory,
+ MemoryType,
+ MemoryEntry,
+ get_memory_system,
+)
+from .trade_memory import TradeMemory, get_trade_memory
+from .decision_memory import DecisionMemory, get_decision_memory
+from .learning_memory import LearningMemory, get_learning_memory
+from .agent_memory import AgentMemoryManager, get_agent_memory_manager
+
+__all__ = [
+ # Base memory
+ "RenTechMemory",
+ "MemoryType",
+ "MemoryEntry",
+ "get_memory_system",
+ # Specialized memories
+ "TradeMemory",
+ "get_trade_memory",
+ "DecisionMemory",
+ "get_decision_memory",
+ "LearningMemory",
+ "get_learning_memory",
+ # Agent memory manager
+ "AgentMemoryManager",
+ "get_agent_memory_manager",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/agent_memory.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/agent_memory.py
new file mode 100644
index 000000000..f4e2c9993
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/agent_memory.py
@@ -0,0 +1,473 @@
+"""
+Agent Memory Manager
+
+Unified memory management for individual agents:
+- Per-agent memory isolation
+- Memory sharing between agents
+- Context building for agent decisions
+- Memory lifecycle management
+"""
+
+from typing import Optional, List, Dict, Any
+from datetime import datetime
+from dataclasses import dataclass
+import uuid
+
+try:
+ from agno.memory import AgentMemory
+ from agno.memory.db.sqlite import SqliteMemoryDb
+except ImportError:
+ AgentMemory = object
+ SqliteMemoryDb = object
+
+from .base import (
+ RenTechMemory,
+ MemoryType,
+ MemoryEntry,
+ MemoryPriority,
+ get_memory_system,
+)
+from .trade_memory import TradeMemory, get_trade_memory
+from .decision_memory import DecisionMemory, get_decision_memory
+from .learning_memory import LearningMemory, get_learning_memory
+from ..config import get_config
+
+
+@dataclass
+class AgentContext:
+ """
+ Context object provided to an agent for decision making.
+
+ Contains relevant memories, learnings, and current state.
+ """
+ agent_id: str
+ timestamp: str
+
+ # Current working context
+ current_task: Optional[str] = None
+ current_ticker: Optional[str] = None
+ current_signal: Optional[Dict[str, Any]] = None
+
+ # Relevant memories
+ recent_trades: List[Dict[str, Any]] = None
+ similar_past_decisions: List[Dict[str, Any]] = None
+ relevant_lessons: List[Dict[str, Any]] = None
+ anti_patterns_to_avoid: List[Dict[str, Any]] = None
+
+ # Performance context
+ recent_performance: Optional[Dict[str, Any]] = None
+ decision_accuracy: Optional[Dict[str, Any]] = None
+
+ # Market context
+ market_insights: List[Dict[str, Any]] = None
+
+ def __post_init__(self):
+ self.recent_trades = self.recent_trades or []
+ self.similar_past_decisions = self.similar_past_decisions or []
+ self.relevant_lessons = self.relevant_lessons or []
+ self.anti_patterns_to_avoid = self.anti_patterns_to_avoid or []
+ self.market_insights = self.market_insights or []
+
+ def to_prompt_context(self) -> str:
+ """Convert to a string context for LLM prompts"""
+ sections = []
+
+ if self.current_task:
+ sections.append(f"CURRENT TASK: {self.current_task}")
+
+ if self.current_ticker:
+ sections.append(f"ANALYZING: {self.current_ticker}")
+
+ if self.recent_trades:
+ trades_str = "\n".join([
+ f"- {t.get('ticker', 'N/A')}: {t.get('outcome', 'N/A')} ({t.get('pnl_bps', 0):+.1f} bps)"
+ for t in self.recent_trades[:5]
+ ])
+ sections.append(f"RECENT TRADES:\n{trades_str}")
+
+ if self.relevant_lessons:
+ lessons_str = "\n".join([
+ f"- {l.get('title', 'N/A')}"
+ for l in self.relevant_lessons[:3]
+ ])
+ sections.append(f"RELEVANT LESSONS:\n{lessons_str}")
+
+ if self.anti_patterns_to_avoid:
+ patterns_str = "\n".join([
+ f"- AVOID: {p.get('title', 'N/A')}"
+ for p in self.anti_patterns_to_avoid[:3]
+ ])
+ sections.append(f"ANTI-PATTERNS TO AVOID:\n{patterns_str}")
+
+ if self.decision_accuracy:
+ sections.append(
+ f"YOUR RECENT ACCURACY: {self.decision_accuracy.get('accuracy', 0):.1%}"
+ )
+
+ return "\n\n".join(sections)
+
+
+class AgentMemoryManager:
+ """
+ Unified memory manager for all agents.
+
+ Provides:
+ 1. Per-agent memory isolation
+ 2. Cross-agent memory sharing (when appropriate)
+ 3. Context building for decisions
+ 4. Memory lifecycle management
+ 5. Integration with Agno's AgentMemory
+ """
+
+ def __init__(
+ self,
+ memory_system: Optional[RenTechMemory] = None,
+ trade_memory: Optional[TradeMemory] = None,
+ decision_memory: Optional[DecisionMemory] = None,
+ learning_memory: Optional[LearningMemory] = None,
+ ):
+ self.memory = memory_system or get_memory_system()
+ self.trades = trade_memory or get_trade_memory()
+ self.decisions = decision_memory or get_decision_memory()
+ self.learning = learning_memory or get_learning_memory()
+
+ self.config = get_config()
+
+ # Cache of agent contexts
+ self._agent_contexts: Dict[str, AgentContext] = {}
+
+ # Shared memory pool (for team-wide knowledge)
+ self._shared_memories: List[MemoryEntry] = []
+
+ def create_agent_memory(self, agent_id: str) -> AgentMemory:
+ """
+ Create an Agno AgentMemory instance for an agent.
+
+ This integrates with Agno's memory system while using
+ our custom storage backend.
+ """
+ try:
+ db = SqliteMemoryDb(
+ table_name=f"agent_{agent_id}_memory",
+ db_file=self.config.database.sqlite_path,
+ )
+
+ return AgentMemory(
+ db=db,
+ create_user_memories=True,
+ create_session_summary=True,
+ )
+ except Exception as e:
+ print(f"Warning: Could not create Agno memory for {agent_id}: {e}")
+ return None
+
+ def build_context(
+ self,
+ agent_id: str,
+ task: Optional[str] = None,
+ ticker: Optional[str] = None,
+ signal: Optional[Dict[str, Any]] = None,
+ market_condition: Optional[str] = None,
+ ) -> AgentContext:
+ """
+ Build a context object for an agent's decision making.
+
+ Gathers relevant memories from all memory systems to
+ provide comprehensive context.
+ """
+ context = AgentContext(
+ agent_id=agent_id,
+ timestamp=datetime.utcnow().isoformat(),
+ current_task=task,
+ current_ticker=ticker,
+ current_signal=signal,
+ )
+
+ # Get recent trades
+ if ticker:
+ similar_trades = self.trades.recall_similar_trades(
+ ticker=ticker,
+ signal_type=signal.get("type", "") if signal else "",
+ direction=signal.get("direction", "") if signal else "",
+ market_regime=market_condition,
+ limit=5,
+ )
+ context.recent_trades = [
+ m.context.get("trade_outcome", {})
+ for m in similar_trades
+ ]
+
+ # Get recent losses for this ticker
+ losses = self.trades.recall_losses(ticker=ticker, limit=3)
+ for loss in losses:
+ trade_ctx = loss.context.get("trade_outcome", {})
+ if trade_ctx and trade_ctx not in context.recent_trades:
+ context.recent_trades.append(trade_ctx)
+
+ # Get similar past decisions
+ if task:
+ from .decision_memory import DecisionType
+ decision_type = self._infer_decision_type(task)
+ if decision_type:
+ similar_decisions = self.decisions.recall_similar_decisions(
+ decision_type=decision_type,
+ subject=ticker or task,
+ limit=5,
+ )
+ context.similar_past_decisions = [
+ m.context.get("decision", {})
+ for m in similar_decisions
+ ]
+
+ # Get relevant lessons
+ situation = f"{task} {ticker}" if ticker else task
+ if situation:
+ lessons = self.learning.recall_lessons_for_situation(
+ situation=situation,
+ limit=3,
+ )
+ context.relevant_lessons = [
+ m.context.get("lesson", {})
+ for m in lessons
+ ]
+
+ # Get anti-patterns to avoid
+ anti_patterns = self.learning.recall_anti_patterns(
+ situation=situation,
+ limit=3,
+ )
+ context.anti_patterns_to_avoid = [
+ m.context.get("anti_pattern", {})
+ for m in anti_patterns
+ ]
+
+ # Get market insights
+ if market_condition:
+ insights = self.learning.recall_insights_for_market_condition(
+ market_condition=market_condition,
+ limit=3,
+ )
+ context.market_insights = [
+ m.context.get("insight", {})
+ for m in insights
+ ]
+
+ # Get agent's decision accuracy
+ context.decision_accuracy = self.decisions.get_agent_decision_accuracy(
+ agent_id=agent_id
+ )
+
+ # Cache the context
+ self._agent_contexts[agent_id] = context
+
+ return context
+
+ def _infer_decision_type(self, task: str) -> Optional[Any]:
+ """Infer decision type from task description"""
+ from .decision_memory import DecisionType
+
+ task_lower = task.lower()
+
+ if "approv" in task_lower or "reject" in task_lower or "ic " in task_lower:
+ return DecisionType.IC_APPROVAL
+ elif "risk" in task_lower:
+ return DecisionType.RISK_OVERRIDE
+ elif "size" in task_lower or "position" in task_lower:
+ return DecisionType.POSITION_SIZING
+ elif "execut" in task_lower:
+ return DecisionType.EXECUTION_CHOICE
+ elif "signal" in task_lower:
+ return DecisionType.SIGNAL_GENERATION
+
+ return None
+
+ def share_memory(
+ self,
+ memory_id: str,
+ from_agent: str,
+ to_agents: List[str],
+ ):
+ """
+ Share a memory between agents.
+
+ Used when one agent discovers something relevant to others.
+ """
+ # Find the memory
+ memory = None
+ for mt in MemoryType:
+ if memory_id in self.memory._memories[mt]:
+ memory = self.memory._memories[mt][memory_id]
+ break
+
+ if not memory:
+ return
+
+ # Add to shared pool
+ if memory not in self._shared_memories:
+ self._shared_memories.append(memory)
+
+ # Create references in target agents' memories
+ for agent_id in to_agents:
+ self.memory.add_memory(
+ content=f"[SHARED from {from_agent}] {memory.content[:200]}...",
+ memory_type=MemoryType.SHORT_TERM,
+ agent_id=agent_id,
+ context={
+ "shared_from": from_agent,
+ "original_memory_id": memory_id,
+ },
+ priority=memory.priority,
+ tags=memory.tags + ["shared"],
+ related_to=[memory_id],
+ )
+
+ def broadcast_to_team(
+ self,
+ content: str,
+ from_agent: str,
+ team: str,
+ priority: MemoryPriority = MemoryPriority.MEDIUM,
+ tags: Optional[List[str]] = None,
+ ) -> str:
+ """
+ Broadcast information to all agents in a team.
+
+ Used for important announcements that everyone should know.
+ """
+ memory_id = self.memory.add_memory(
+ content=f"[TEAM BROADCAST - {team}]\n{content}",
+ memory_type=MemoryType.SHORT_TERM,
+ agent_id=from_agent,
+ context={
+ "broadcast": True,
+ "team": team,
+ "from_agent": from_agent,
+ },
+ priority=priority,
+ tags=(tags or []) + ["broadcast", team],
+ )
+
+ return memory_id
+
+ def remember_interaction(
+ self,
+ agent_id: str,
+ user_message: str,
+ agent_response: str,
+ outcome: Optional[str] = None,
+ ) -> str:
+ """
+ Remember an agent interaction for learning.
+ """
+ content = f"""
+INTERACTION:
+User: {user_message[:500]}...
+
+Agent Response: {agent_response[:500]}...
+
+Outcome: {outcome or 'Not evaluated'}
+""".strip()
+
+ return self.memory.add_memory(
+ content=content,
+ memory_type=MemoryType.EPISODIC,
+ agent_id=agent_id,
+ context={
+ "interaction": {
+ "user_message": user_message,
+ "agent_response": agent_response,
+ "outcome": outcome,
+ }
+ },
+ priority=MemoryPriority.LOW,
+ tags=["interaction"],
+ )
+
+ def get_working_memory(self, agent_id: str) -> Dict[str, Any]:
+ """
+ Get the current working memory for an agent.
+ """
+ agent_working = {}
+
+ for memory_id, entry in self.memory._memories[MemoryType.WORKING].items():
+ if entry.agent_id == agent_id:
+ agent_working[memory_id] = entry.content
+
+ return agent_working
+
+ def set_working_memory(
+ self,
+ agent_id: str,
+ key: str,
+ value: Any,
+ ):
+ """
+ Set a value in an agent's working memory.
+ """
+ self.memory.add_memory(
+ content=f"{key}: {value}",
+ memory_type=MemoryType.WORKING,
+ agent_id=agent_id,
+ context={"key": key, "value": value},
+ priority=MemoryPriority.LOW,
+ tags=["working_memory", key],
+ )
+
+ def end_decision_cycle(self, agent_id: str):
+ """
+ End a decision cycle for an agent.
+
+ Clears working memory and consolidates important memories.
+ """
+ # Clear working memory for this agent
+ to_remove = []
+ for memory_id, entry in self.memory._memories[MemoryType.WORKING].items():
+ if entry.agent_id == agent_id:
+ to_remove.append(memory_id)
+
+ for memory_id in to_remove:
+ del self.memory._memories[MemoryType.WORKING][memory_id]
+
+ # Clear cached context
+ if agent_id in self._agent_contexts:
+ del self._agent_contexts[agent_id]
+
+ def consolidate_all(self):
+ """
+ Run memory consolidation for the entire system.
+
+ Should be called periodically (e.g., end of trading day).
+ """
+ self.memory.consolidate_memories()
+
+ def get_system_stats(self) -> Dict[str, Any]:
+ """
+ Get overall memory system statistics.
+ """
+ memory_summary = self.memory.get_memory_summary()
+ learning_summary = self.learning.get_learning_summary()
+
+ return {
+ "memory": memory_summary,
+ "learning": learning_summary,
+ "shared_memories": len(self._shared_memories),
+ "cached_contexts": len(self._agent_contexts),
+ }
+
+
+# Global agent memory manager instance
+_agent_memory_manager: Optional[AgentMemoryManager] = None
+
+
+def get_agent_memory_manager() -> AgentMemoryManager:
+ """Get the global agent memory manager instance"""
+ global _agent_memory_manager
+ if _agent_memory_manager is None:
+ _agent_memory_manager = AgentMemoryManager()
+ return _agent_memory_manager
+
+
+def reset_agent_memory_manager():
+ """Reset the agent memory manager (for testing)"""
+ global _agent_memory_manager
+ _agent_memory_manager = None
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/base.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/base.py
new file mode 100644
index 000000000..1d01d90f7
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/base.py
@@ -0,0 +1,466 @@
+"""
+Base Memory Infrastructure
+
+Core memory system for Renaissance Technologies multi-agent architecture.
+Implements multi-layer memory with vector storage for semantic search.
+"""
+
+from typing import Optional, List, Dict, Any
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta
+from enum import Enum
+import json
+import uuid
+
+try:
+ from agno.memory import AgentMemory
+ from agno.memory.db.sqlite import SqliteMemoryDb
+ from agno.memory.db.postgres import PostgresMemoryDb
+except ImportError:
+ # Fallback for type hints
+ AgentMemory = object
+ SqliteMemoryDb = object
+ PostgresMemoryDb = object
+
+from ..config import get_config, MemoryConfig
+
+
+class MemoryType(str, Enum):
+ """Types of memory in the system"""
+ SHORT_TERM = "short_term" # Recent interactions (24h)
+ LONG_TERM = "long_term" # Persistent memories (years)
+ EPISODIC = "episodic" # Specific events/trades
+ SEMANTIC = "semantic" # General knowledge/rules
+ WORKING = "working" # Active decision context
+
+
+class MemoryPriority(str, Enum):
+ """Priority levels for memory entries"""
+ CRITICAL = "critical" # Always remember (risk events, major losses)
+ HIGH = "high" # Important learnings
+ MEDIUM = "medium" # Regular operations
+ LOW = "low" # Routine information
+
+
+@dataclass
+class MemoryEntry:
+ """
+ A single memory entry in the system.
+
+ Models how a trader or analyst would remember
+ important information about trades and decisions.
+ """
+ id: str
+ type: MemoryType
+ priority: MemoryPriority
+ content: str
+ context: Dict[str, Any]
+
+ # Metadata
+ agent_id: str
+ created_at: datetime
+ expires_at: Optional[datetime] = None
+
+ # Memory strength (decays over time unless reinforced)
+ strength: float = 1.0
+ access_count: int = 0
+ last_accessed: Optional[datetime] = None
+
+ # Relationships
+ related_memories: List[str] = field(default_factory=list)
+ tags: List[str] = field(default_factory=list)
+
+ # Emotional/importance markers (affects retention)
+ emotional_valence: float = 0.0 # -1 (negative) to 1 (positive)
+ surprise_factor: float = 0.0 # How unexpected was this?
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary for storage"""
+ return {
+ "id": self.id,
+ "type": self.type.value,
+ "priority": self.priority.value,
+ "content": self.content,
+ "context": self.context,
+ "agent_id": self.agent_id,
+ "created_at": self.created_at.isoformat(),
+ "expires_at": self.expires_at.isoformat() if self.expires_at else None,
+ "strength": self.strength,
+ "access_count": self.access_count,
+ "last_accessed": self.last_accessed.isoformat() if self.last_accessed else None,
+ "related_memories": self.related_memories,
+ "tags": self.tags,
+ "emotional_valence": self.emotional_valence,
+ "surprise_factor": self.surprise_factor,
+ }
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "MemoryEntry":
+ """Create from dictionary"""
+ return cls(
+ id=data["id"],
+ type=MemoryType(data["type"]),
+ priority=MemoryPriority(data["priority"]),
+ content=data["content"],
+ context=data["context"],
+ agent_id=data["agent_id"],
+ created_at=datetime.fromisoformat(data["created_at"]),
+ expires_at=datetime.fromisoformat(data["expires_at"]) if data.get("expires_at") else None,
+ strength=data.get("strength", 1.0),
+ access_count=data.get("access_count", 0),
+ last_accessed=datetime.fromisoformat(data["last_accessed"]) if data.get("last_accessed") else None,
+ related_memories=data.get("related_memories", []),
+ tags=data.get("tags", []),
+ emotional_valence=data.get("emotional_valence", 0.0),
+ surprise_factor=data.get("surprise_factor", 0.0),
+ )
+
+ def is_expired(self) -> bool:
+ """Check if memory has expired"""
+ if self.expires_at is None:
+ return False
+ return datetime.utcnow() > self.expires_at
+
+ def decay_strength(self, decay_rate: float = 0.01):
+ """
+ Apply memory decay (forgetting curve).
+ Memories accessed more frequently decay slower.
+ """
+ # Reduce decay based on access frequency
+ effective_decay = decay_rate / (1 + self.access_count * 0.1)
+
+ # High priority memories decay slower
+ if self.priority == MemoryPriority.CRITICAL:
+ effective_decay *= 0.1
+ elif self.priority == MemoryPriority.HIGH:
+ effective_decay *= 0.5
+
+ self.strength = max(0.0, self.strength - effective_decay)
+
+ def reinforce(self, amount: float = 0.2):
+ """Reinforce memory (accessed or validated)"""
+ self.strength = min(1.0, self.strength + amount)
+ self.access_count += 1
+ self.last_accessed = datetime.utcnow()
+
+
+class RenTechMemory:
+ """
+ Core memory system for Renaissance Technologies agents.
+
+ Implements a multi-layer memory architecture inspired by
+ human memory systems:
+
+ 1. Working Memory: Active context for current decisions
+ 2. Short-term Memory: Recent interactions (24 hours)
+ 3. Long-term Memory: Persistent knowledge (years)
+ 4. Episodic Memory: Specific trade events and outcomes
+ 5. Semantic Memory: General trading rules and knowledge
+
+ Uses Agno's memory system with custom extensions for
+ trading-specific features.
+ """
+
+ def __init__(
+ self,
+ config: Optional[MemoryConfig] = None,
+ db_path: Optional[str] = None,
+ ):
+ self.config = config or get_config().memory
+ self.db_path = db_path or get_config().database.sqlite_path
+
+ # Memory stores by type
+ self._memories: Dict[MemoryType, Dict[str, MemoryEntry]] = {
+ mt: {} for mt in MemoryType
+ }
+
+ # Working memory (in-memory only, clears each session)
+ self._working_context: Dict[str, Any] = {}
+
+ # Initialize Agno memory backend
+ self._init_backend()
+
+ def _init_backend(self):
+ """Initialize the memory storage backend"""
+ try:
+ self.db = SqliteMemoryDb(
+ table_name="rentech_memories",
+ db_file=self.db_path,
+ )
+ self._backend_available = True
+ except Exception as e:
+ print(f"Warning: Could not initialize memory backend: {e}")
+ self._backend_available = False
+
+ def add_memory(
+ self,
+ content: str,
+ memory_type: MemoryType,
+ agent_id: str,
+ context: Optional[Dict[str, Any]] = None,
+ priority: MemoryPriority = MemoryPriority.MEDIUM,
+ tags: Optional[List[str]] = None,
+ related_to: Optional[List[str]] = None,
+ emotional_valence: float = 0.0,
+ surprise_factor: float = 0.0,
+ ) -> str:
+ """
+ Add a new memory to the system.
+
+ Args:
+ content: The memory content
+ memory_type: Type of memory (short_term, long_term, etc.)
+ agent_id: ID of the agent creating the memory
+ context: Additional context data
+ priority: Memory priority level
+ tags: Tags for categorization
+ related_to: IDs of related memories
+ emotional_valence: Emotional charge (-1 to 1)
+ surprise_factor: How unexpected (0 to 1)
+
+ Returns:
+ Memory ID
+ """
+ # Calculate expiration based on type
+ expires_at = None
+ if memory_type == MemoryType.SHORT_TERM:
+ expires_at = datetime.utcnow() + timedelta(hours=self.config.short_term_memory_hours)
+ elif memory_type == MemoryType.WORKING:
+ expires_at = datetime.utcnow() + timedelta(hours=1) # Working memory expires fast
+
+ # Create memory entry
+ memory_id = f"{memory_type.value}_{uuid.uuid4().hex[:12]}"
+
+ entry = MemoryEntry(
+ id=memory_id,
+ type=memory_type,
+ priority=priority,
+ content=content,
+ context=context or {},
+ agent_id=agent_id,
+ created_at=datetime.utcnow(),
+ expires_at=expires_at,
+ tags=tags or [],
+ related_memories=related_to or [],
+ emotional_valence=emotional_valence,
+ surprise_factor=surprise_factor,
+ )
+
+ # Store in appropriate memory store
+ self._memories[memory_type][memory_id] = entry
+
+ # Persist to backend if available
+ if self._backend_available:
+ self._persist_memory(entry)
+
+ return memory_id
+
+ def _persist_memory(self, entry: MemoryEntry):
+ """Persist memory to database"""
+ try:
+ # Store as JSON in the database
+ pass # Agno backend handles this
+ except Exception as e:
+ print(f"Warning: Could not persist memory: {e}")
+
+ def recall(
+ self,
+ query: str,
+ memory_types: Optional[List[MemoryType]] = None,
+ agent_id: Optional[str] = None,
+ limit: int = 10,
+ min_strength: float = 0.1,
+ ) -> List[MemoryEntry]:
+ """
+ Recall memories matching a query.
+
+ Uses semantic search to find relevant memories
+ across specified memory types.
+
+ Args:
+ query: Search query
+ memory_types: Types to search (all if None)
+ agent_id: Filter by agent
+ limit: Maximum results
+ min_strength: Minimum memory strength
+
+ Returns:
+ List of matching memories, ranked by relevance
+ """
+ types_to_search = memory_types or list(MemoryType)
+ results = []
+
+ for mt in types_to_search:
+ for entry in self._memories[mt].values():
+ # Filter by agent if specified
+ if agent_id and entry.agent_id != agent_id:
+ continue
+
+ # Filter by strength
+ if entry.strength < min_strength:
+ continue
+
+ # Filter expired
+ if entry.is_expired():
+ continue
+
+ # Simple keyword matching (would be vector search in production)
+ query_lower = query.lower()
+ content_lower = entry.content.lower()
+
+ if query_lower in content_lower or any(tag in query_lower for tag in entry.tags):
+ results.append(entry)
+ # Reinforce accessed memories
+ entry.reinforce(0.05)
+
+ # Sort by relevance (strength * priority_weight)
+ priority_weights = {
+ MemoryPriority.CRITICAL: 4,
+ MemoryPriority.HIGH: 3,
+ MemoryPriority.MEDIUM: 2,
+ MemoryPriority.LOW: 1,
+ }
+
+ results.sort(
+ key=lambda x: x.strength * priority_weights[x.priority],
+ reverse=True
+ )
+
+ return results[:limit]
+
+ def get_working_context(self) -> Dict[str, Any]:
+ """Get current working memory context"""
+ return self._working_context.copy()
+
+ def set_working_context(self, key: str, value: Any):
+ """Set a value in working memory"""
+ self._working_context[key] = value
+
+ def clear_working_memory(self):
+ """Clear working memory (end of decision cycle)"""
+ self._working_context = {}
+ self._memories[MemoryType.WORKING] = {}
+
+ def consolidate_memories(self):
+ """
+ Consolidate short-term memories to long-term.
+
+ Important memories (high strength, high priority, accessed often)
+ are promoted to long-term storage. Others are allowed to decay.
+ """
+ short_term = self._memories[MemoryType.SHORT_TERM]
+ to_promote = []
+ to_remove = []
+
+ for memory_id, entry in short_term.items():
+ # Apply decay
+ entry.decay_strength()
+
+ # Check for promotion to long-term
+ should_promote = (
+ entry.strength > 0.7 or
+ entry.priority in [MemoryPriority.CRITICAL, MemoryPriority.HIGH] or
+ entry.access_count >= 5 or
+ abs(entry.emotional_valence) > 0.5 or
+ entry.surprise_factor > 0.5
+ )
+
+ if should_promote:
+ to_promote.append(entry)
+ elif entry.strength < 0.1:
+ to_remove.append(memory_id)
+
+ # Promote memories
+ for entry in to_promote:
+ entry.type = MemoryType.LONG_TERM
+ entry.expires_at = None # Long-term doesn't expire
+ self._memories[MemoryType.LONG_TERM][entry.id] = entry
+ del self._memories[MemoryType.SHORT_TERM][entry.id]
+
+ # Remove weak memories
+ for memory_id in to_remove:
+ del self._memories[MemoryType.SHORT_TERM][memory_id]
+
+ def get_memories_by_tags(
+ self,
+ tags: List[str],
+ memory_types: Optional[List[MemoryType]] = None,
+ ) -> List[MemoryEntry]:
+ """Get all memories with specific tags"""
+ types_to_search = memory_types or list(MemoryType)
+ results = []
+
+ for mt in types_to_search:
+ for entry in self._memories[mt].values():
+ if not entry.is_expired() and any(tag in entry.tags for tag in tags):
+ results.append(entry)
+
+ return results
+
+ def get_agent_memories(
+ self,
+ agent_id: str,
+ memory_types: Optional[List[MemoryType]] = None,
+ limit: int = 50,
+ ) -> List[MemoryEntry]:
+ """Get all memories for a specific agent"""
+ types_to_search = memory_types or list(MemoryType)
+ results = []
+
+ for mt in types_to_search:
+ for entry in self._memories[mt].values():
+ if entry.agent_id == agent_id and not entry.is_expired():
+ results.append(entry)
+
+ # Sort by recency
+ results.sort(key=lambda x: x.created_at, reverse=True)
+ return results[:limit]
+
+ def forget(self, memory_id: str) -> bool:
+ """Explicitly forget a memory"""
+ for mt in MemoryType:
+ if memory_id in self._memories[mt]:
+ del self._memories[mt][memory_id]
+ return True
+ return False
+
+ def get_memory_summary(self) -> Dict[str, Any]:
+ """Get summary statistics of the memory system"""
+ summary = {
+ "total_memories": 0,
+ "by_type": {},
+ "by_priority": {p.value: 0 for p in MemoryPriority},
+ "average_strength": 0.0,
+ }
+
+ all_memories = []
+ for mt in MemoryType:
+ count = len(self._memories[mt])
+ summary["by_type"][mt.value] = count
+ summary["total_memories"] += count
+ all_memories.extend(self._memories[mt].values())
+
+ if all_memories:
+ for entry in all_memories:
+ summary["by_priority"][entry.priority.value] += 1
+ summary["average_strength"] = sum(m.strength for m in all_memories) / len(all_memories)
+
+ return summary
+
+
+# Global memory instance
+_memory_system: Optional[RenTechMemory] = None
+
+
+def get_memory_system() -> RenTechMemory:
+ """Get the global memory system instance"""
+ global _memory_system
+ if _memory_system is None:
+ _memory_system = RenTechMemory()
+ return _memory_system
+
+
+def reset_memory_system():
+ """Reset the memory system (for testing)"""
+ global _memory_system
+ _memory_system = None
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/decision_memory.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/decision_memory.py
new file mode 100644
index 000000000..24e595592
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/decision_memory.py
@@ -0,0 +1,394 @@
+"""
+Decision Memory
+
+Memory system for tracking investment decisions:
+- IC decisions and rationale
+- Signal approvals/rejections
+- Risk override decisions
+- Position sizing decisions
+"""
+
+from typing import Optional, List, Dict, Any
+from datetime import datetime
+from dataclasses import dataclass
+from enum import Enum
+import uuid
+
+from .base import (
+ RenTechMemory,
+ MemoryType,
+ MemoryEntry,
+ MemoryPriority,
+ get_memory_system,
+)
+
+
+class DecisionType(str, Enum):
+ """Types of investment decisions"""
+ IC_APPROVAL = "ic_approval"
+ IC_REJECTION = "ic_rejection"
+ SIGNAL_GENERATION = "signal_generation"
+ RISK_OVERRIDE = "risk_override"
+ POSITION_SIZING = "position_sizing"
+ EXECUTION_CHOICE = "execution_choice"
+ STOP_LOSS = "stop_loss"
+ TAKE_PROFIT = "take_profit"
+ REBALANCE = "rebalance"
+
+
+class DecisionOutcome(str, Enum):
+ """Outcomes of decisions"""
+ CORRECT = "correct"
+ INCORRECT = "incorrect"
+ PARTIAL = "partial"
+ PENDING = "pending"
+ UNKNOWN = "unknown"
+
+
+@dataclass
+class Decision:
+ """Structured decision record"""
+ decision_id: str
+ decision_type: DecisionType
+ decision_maker: str # Agent ID
+ timestamp: str
+
+ # What was decided
+ subject: str # What was the decision about (e.g., "AAPL long")
+ action: str # What action was taken
+ rationale: List[str] # Why this decision was made
+
+ # Context
+ signal_strength: Optional[float] = None
+ confidence: Optional[float] = None
+ risk_score: Optional[float] = None
+ market_conditions: Optional[Dict[str, Any]] = None
+
+ # Outcome (updated later)
+ outcome: DecisionOutcome = DecisionOutcome.PENDING
+ outcome_notes: Optional[str] = None
+ outcome_pnl_bps: Optional[float] = None
+
+
+class DecisionMemory:
+ """
+ Decision-specific memory manager.
+
+ Tracks and learns from all investment decisions made by
+ the fund's agents and teams. Used for:
+
+ 1. Understanding why decisions were made
+ 2. Learning from correct/incorrect decisions
+ 3. Improving decision-making over time
+ 4. Accountability and audit trails
+ """
+
+ def __init__(self, memory_system: Optional[RenTechMemory] = None):
+ self.memory = memory_system or get_memory_system()
+
+ def remember_decision(
+ self,
+ decision: Decision,
+ supporting_data: Optional[Dict[str, Any]] = None,
+ ) -> str:
+ """
+ Remember an investment decision.
+
+ Args:
+ decision: The decision to remember
+ supporting_data: Additional data that supported the decision
+
+ Returns:
+ Memory ID
+ """
+ # Determine priority based on decision type and impact
+ priority = self._determine_priority(decision)
+
+ # Build content
+ content = f"""
+Decision: {decision.decision_type.value.upper()}
+Subject: {decision.subject}
+Maker: {decision.decision_maker}
+Time: {decision.timestamp}
+
+Action: {decision.action}
+
+Rationale:
+{chr(10).join([f"- {r}" for r in decision.rationale])}
+
+Context:
+- Signal Strength: {decision.signal_strength or 'N/A'}
+- Confidence: {decision.confidence or 'N/A'}
+- Risk Score: {decision.risk_score or 'N/A'}
+- Market Conditions: {decision.market_conditions or 'N/A'}
+
+Outcome: {decision.outcome.value.upper()}
+{f"Notes: {decision.outcome_notes}" if decision.outcome_notes else ""}
+{f"P&L: {decision.outcome_pnl_bps:+.1f} bps" if decision.outcome_pnl_bps is not None else ""}
+""".strip()
+
+ # Context for structured retrieval
+ context = {
+ "decision": {
+ "id": decision.decision_id,
+ "type": decision.decision_type.value,
+ "maker": decision.decision_maker,
+ "subject": decision.subject,
+ "action": decision.action,
+ "rationale": decision.rationale,
+ "signal_strength": decision.signal_strength,
+ "confidence": decision.confidence,
+ "risk_score": decision.risk_score,
+ "outcome": decision.outcome.value,
+ },
+ "supporting_data": supporting_data or {},
+ }
+
+ # Tags
+ tags = [
+ decision.decision_type.value,
+ decision.decision_maker,
+ decision.outcome.value,
+ ]
+
+ # Extract ticker if present in subject
+ subject_parts = decision.subject.split()
+ if subject_parts:
+ tags.append(subject_parts[0]) # First word often ticker
+
+ # Emotional valence based on outcome
+ emotional_valence = 0.0
+ if decision.outcome == DecisionOutcome.CORRECT:
+ emotional_valence = 0.5
+ elif decision.outcome == DecisionOutcome.INCORRECT:
+ emotional_valence = -0.5
+
+ # IC decisions are critical memories
+ if decision.decision_type in [DecisionType.IC_APPROVAL, DecisionType.IC_REJECTION]:
+ memory_type = MemoryType.LONG_TERM
+ else:
+ memory_type = MemoryType.SHORT_TERM
+
+ return self.memory.add_memory(
+ content=content,
+ memory_type=memory_type,
+ agent_id=decision.decision_maker,
+ context=context,
+ priority=priority,
+ tags=tags,
+ emotional_valence=emotional_valence,
+ )
+
+ def _determine_priority(self, decision: Decision) -> MemoryPriority:
+ """Determine memory priority for a decision"""
+ # IC decisions are always high priority
+ if decision.decision_type in [DecisionType.IC_APPROVAL, DecisionType.IC_REJECTION]:
+ return MemoryPriority.HIGH
+
+ # Risk overrides are critical
+ if decision.decision_type == DecisionType.RISK_OVERRIDE:
+ return MemoryPriority.CRITICAL
+
+ # Incorrect decisions are important to remember
+ if decision.outcome == DecisionOutcome.INCORRECT:
+ return MemoryPriority.HIGH
+
+ return MemoryPriority.MEDIUM
+
+ def update_decision_outcome(
+ self,
+ decision_id: str,
+ outcome: DecisionOutcome,
+ outcome_notes: Optional[str] = None,
+ pnl_bps: Optional[float] = None,
+ ):
+ """
+ Update the outcome of a previously recorded decision.
+
+ Called when we know how a decision played out.
+ """
+ # Search for the decision
+ memories = self.memory.recall(
+ query=decision_id,
+ limit=5,
+ )
+
+ for m in memories:
+ ctx = m.context.get("decision", {})
+ if ctx.get("id") == decision_id:
+ # Update context
+ ctx["outcome"] = outcome.value
+ ctx["outcome_notes"] = outcome_notes
+ ctx["outcome_pnl_bps"] = pnl_bps
+ m.context["decision"] = ctx
+
+ # Adjust emotional valence
+ if outcome == DecisionOutcome.CORRECT:
+ m.emotional_valence = 0.5
+ m.reinforce(0.3) # Reinforce good decisions
+ elif outcome == DecisionOutcome.INCORRECT:
+ m.emotional_valence = -0.5
+ m.reinforce(0.5) # Strongly reinforce failures (to remember)
+
+ # Promote to long-term if significant
+ if outcome == DecisionOutcome.INCORRECT or abs(pnl_bps or 0) > 100:
+ if m.type == MemoryType.SHORT_TERM:
+ m.type = MemoryType.LONG_TERM
+ m.expires_at = None
+
+ break
+
+ def recall_similar_decisions(
+ self,
+ decision_type: DecisionType,
+ subject: str,
+ limit: int = 5,
+ ) -> List[MemoryEntry]:
+ """
+ Recall similar past decisions.
+
+ Used to inform current decision-making based on
+ historical precedent.
+ """
+ query = f"{decision_type.value} {subject}"
+
+ memories = self.memory.recall(
+ query=query,
+ memory_types=[MemoryType.SHORT_TERM, MemoryType.LONG_TERM],
+ limit=limit * 2,
+ )
+
+ # Filter to matching decision type
+ relevant = []
+ for m in memories:
+ ctx = m.context.get("decision", {})
+ if ctx.get("type") == decision_type.value:
+ relevant.append(m)
+
+ return relevant[:limit]
+
+ def recall_incorrect_decisions(
+ self,
+ decision_type: Optional[DecisionType] = None,
+ limit: int = 10,
+ ) -> List[MemoryEntry]:
+ """
+ Recall incorrect decisions for learning.
+
+ Critical for improving decision quality over time.
+ """
+ query = "incorrect"
+ if decision_type:
+ query += f" {decision_type.value}"
+
+ memories = self.memory.recall(
+ query=query,
+ memory_types=[MemoryType.SHORT_TERM, MemoryType.LONG_TERM],
+ limit=limit * 2,
+ )
+
+ # Filter to actual incorrect outcomes
+ incorrect = []
+ for m in memories:
+ ctx = m.context.get("decision", {})
+ if ctx.get("outcome") == DecisionOutcome.INCORRECT.value:
+ incorrect.append(m)
+
+ return incorrect[:limit]
+
+ def get_agent_decision_accuracy(
+ self,
+ agent_id: str,
+ decision_type: Optional[DecisionType] = None,
+ ) -> Dict[str, Any]:
+ """
+ Get decision accuracy statistics for an agent.
+
+ Used for agent evaluation and improvement.
+ """
+ memories = self.memory.get_agent_memories(
+ agent_id=agent_id,
+ limit=100,
+ )
+
+ total = 0
+ correct = 0
+ incorrect = 0
+ total_pnl = 0.0
+
+ for m in memories:
+ ctx = m.context.get("decision", {})
+ if not ctx:
+ continue
+
+ if decision_type and ctx.get("type") != decision_type.value:
+ continue
+
+ total += 1
+ outcome = ctx.get("outcome")
+
+ if outcome == DecisionOutcome.CORRECT.value:
+ correct += 1
+ elif outcome == DecisionOutcome.INCORRECT.value:
+ incorrect += 1
+
+ pnl = ctx.get("outcome_pnl_bps")
+ if pnl is not None:
+ total_pnl += pnl
+
+ return {
+ "agent_id": agent_id,
+ "decision_type": decision_type.value if decision_type else "all",
+ "total_decisions": total,
+ "correct": correct,
+ "incorrect": incorrect,
+ "accuracy": correct / total if total > 0 else 0,
+ "total_pnl_bps": total_pnl,
+ }
+
+ def get_ic_approval_history(
+ self,
+ ticker: Optional[str] = None,
+ limit: int = 20,
+ ) -> List[MemoryEntry]:
+ """Get history of IC approvals/rejections"""
+ query = "ic_approval ic_rejection"
+ if ticker:
+ query += f" {ticker}"
+
+ memories = self.memory.recall(
+ query=query,
+ memory_types=[MemoryType.LONG_TERM, MemoryType.SHORT_TERM],
+ limit=limit,
+ )
+
+ # Filter to IC decisions
+ ic_decisions = []
+ for m in memories:
+ ctx = m.context.get("decision", {})
+ if ctx.get("type") in [DecisionType.IC_APPROVAL.value, DecisionType.IC_REJECTION.value]:
+ ic_decisions.append(m)
+
+ return ic_decisions[:limit]
+
+ def get_risk_override_history(
+ self,
+ limit: int = 20,
+ ) -> List[MemoryEntry]:
+ """Get history of risk overrides"""
+ return self.memory.get_memories_by_tags(
+ tags=[DecisionType.RISK_OVERRIDE.value],
+ memory_types=[MemoryType.LONG_TERM, MemoryType.SHORT_TERM],
+ )[:limit]
+
+
+# Global decision memory instance
+_decision_memory: Optional[DecisionMemory] = None
+
+
+def get_decision_memory() -> DecisionMemory:
+ """Get the global decision memory instance"""
+ global _decision_memory
+ if _decision_memory is None:
+ _decision_memory = DecisionMemory()
+ return _decision_memory
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/learning_memory.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/learning_memory.py
new file mode 100644
index 000000000..ae8121706
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/learning_memory.py
@@ -0,0 +1,522 @@
+"""
+Learning Memory
+
+Memory system for organizational learning:
+- Lessons learned from trades
+- Strategy insights
+- Market regime observations
+- Best practices and anti-patterns
+"""
+
+from typing import Optional, List, Dict, Any
+from datetime import datetime
+from dataclasses import dataclass, field
+from enum import Enum
+import uuid
+
+from .base import (
+ RenTechMemory,
+ MemoryType,
+ MemoryEntry,
+ MemoryPriority,
+ get_memory_system,
+)
+
+
+class LessonCategory(str, Enum):
+ """Categories of lessons learned"""
+ SIGNAL_QUALITY = "signal_quality"
+ EXECUTION = "execution"
+ RISK_MANAGEMENT = "risk_management"
+ MARKET_REGIME = "market_regime"
+ POSITION_SIZING = "position_sizing"
+ TIMING = "timing"
+ DATA_QUALITY = "data_quality"
+ MODEL_BEHAVIOR = "model_behavior"
+ OPERATIONAL = "operational"
+
+
+class InsightType(str, Enum):
+ """Types of insights"""
+ PATTERN = "pattern" # Recurring pattern observed
+ ANOMALY = "anomaly" # Unexpected behavior
+ CORRELATION = "correlation" # New correlation discovered
+ ANTI_PATTERN = "anti_pattern" # What NOT to do
+ BEST_PRACTICE = "best_practice" # What TO do
+ HYPOTHESIS = "hypothesis" # Unconfirmed theory
+
+
+@dataclass
+class Lesson:
+ """Structured lesson learned"""
+ lesson_id: str
+ category: LessonCategory
+ title: str
+ description: str
+
+ # Evidence
+ supporting_events: List[str] # Trade IDs, decision IDs that support this
+ evidence_strength: float # 0-1, how well supported
+
+ # Impact
+ estimated_impact_bps: Optional[float] # Estimated P&L impact
+ frequency: str # how often this applies (daily, weekly, rare)
+
+ # Actions
+ action_items: List[str]
+ status: str = "active" # active, implemented, deprecated
+
+
+@dataclass
+class MarketInsight:
+ """Insight about market behavior"""
+ insight_id: str
+ insight_type: InsightType
+ market_condition: str
+
+ observation: str
+ statistical_evidence: Dict[str, Any]
+
+ trading_implications: List[str]
+ valid_until: Optional[str] = None # Some insights expire
+
+
+class LearningMemory:
+ """
+ Learning-specific memory manager.
+
+ Captures organizational learning to improve over time:
+
+ 1. Lessons Learned: What we've learned from experience
+ 2. Market Insights: Observations about market behavior
+ 3. Strategy Insights: What works and what doesn't
+ 4. Best Practices: Accumulated wisdom
+ 5. Anti-patterns: What to avoid
+
+ This is the "institutional memory" of the fund.
+ """
+
+ def __init__(self, memory_system: Optional[RenTechMemory] = None):
+ self.memory = memory_system or get_memory_system()
+
+ def add_lesson(
+ self,
+ lesson: Lesson,
+ learned_by: str,
+ related_memories: Optional[List[str]] = None,
+ ) -> str:
+ """
+ Add a lesson learned to memory.
+
+ Args:
+ lesson: The lesson to remember
+ learned_by: Agent who identified the lesson
+ related_memories: IDs of related memories
+
+ Returns:
+ Memory ID
+ """
+ # High-impact lessons get higher priority
+ if lesson.estimated_impact_bps:
+ if abs(lesson.estimated_impact_bps) > 100:
+ priority = MemoryPriority.CRITICAL
+ elif abs(lesson.estimated_impact_bps) > 50:
+ priority = MemoryPriority.HIGH
+ else:
+ priority = MemoryPriority.MEDIUM
+ else:
+ priority = MemoryPriority.MEDIUM
+
+ content = f"""
+LESSON LEARNED: {lesson.title}
+Category: {lesson.category.value}
+Status: {lesson.status.upper()}
+
+Description:
+{lesson.description}
+
+Evidence:
+- Supporting Events: {len(lesson.supporting_events)} trades/decisions
+- Evidence Strength: {lesson.evidence_strength:.0%}
+- Estimated Impact: {lesson.estimated_impact_bps or 'Unknown'} bps per occurrence
+- Frequency: {lesson.frequency}
+
+Action Items:
+{chr(10).join([f"- {a}" for a in lesson.action_items])}
+
+Supporting Events:
+{chr(10).join([f"- {e}" for e in lesson.supporting_events[:5]])}
+{"..." if len(lesson.supporting_events) > 5 else ""}
+""".strip()
+
+ context = {
+ "lesson": {
+ "id": lesson.lesson_id,
+ "category": lesson.category.value,
+ "title": lesson.title,
+ "evidence_strength": lesson.evidence_strength,
+ "estimated_impact_bps": lesson.estimated_impact_bps,
+ "action_items": lesson.action_items,
+ "status": lesson.status,
+ },
+ "supporting_events": lesson.supporting_events,
+ }
+
+ tags = [
+ "lesson",
+ lesson.category.value,
+ lesson.status,
+ f"freq_{lesson.frequency}",
+ ]
+
+ # Lessons go to long-term/semantic memory
+ return self.memory.add_memory(
+ content=content,
+ memory_type=MemoryType.SEMANTIC,
+ agent_id=learned_by,
+ context=context,
+ priority=priority,
+ tags=tags,
+ related_to=related_memories,
+ )
+
+ def add_market_insight(
+ self,
+ insight: MarketInsight,
+ discovered_by: str,
+ ) -> str:
+ """
+ Add a market insight to memory.
+
+ Market insights are observations about market behavior
+ that can inform trading decisions.
+ """
+ # Determine priority based on insight type
+ if insight.insight_type == InsightType.ANOMALY:
+ priority = MemoryPriority.HIGH # Anomalies are important
+ elif insight.insight_type == InsightType.ANTI_PATTERN:
+ priority = MemoryPriority.HIGH # Anti-patterns prevent losses
+ elif insight.insight_type == InsightType.BEST_PRACTICE:
+ priority = MemoryPriority.HIGH
+ else:
+ priority = MemoryPriority.MEDIUM
+
+ content = f"""
+MARKET INSIGHT: {insight.insight_type.value.upper()}
+Condition: {insight.market_condition}
+Valid Until: {insight.valid_until or 'Indefinite'}
+
+Observation:
+{insight.observation}
+
+Statistical Evidence:
+{chr(10).join([f"- {k}: {v}" for k, v in insight.statistical_evidence.items()])}
+
+Trading Implications:
+{chr(10).join([f"- {i}" for i in insight.trading_implications])}
+""".strip()
+
+ context = {
+ "insight": {
+ "id": insight.insight_id,
+ "type": insight.insight_type.value,
+ "condition": insight.market_condition,
+ "evidence": insight.statistical_evidence,
+ "implications": insight.trading_implications,
+ }
+ }
+
+ tags = [
+ "insight",
+ insight.insight_type.value,
+ insight.market_condition,
+ ]
+
+ return self.memory.add_memory(
+ content=content,
+ memory_type=MemoryType.SEMANTIC,
+ agent_id=discovered_by,
+ context=context,
+ priority=priority,
+ tags=tags,
+ )
+
+ def add_strategy_insight(
+ self,
+ strategy_name: str,
+ insight: str,
+ performance_data: Dict[str, Any],
+ recommendation: str,
+ discovered_by: str,
+ ) -> str:
+ """
+ Add an insight about strategy performance.
+ """
+ content = f"""
+STRATEGY INSIGHT: {strategy_name}
+
+Observation:
+{insight}
+
+Performance Data:
+{chr(10).join([f"- {k}: {v}" for k, v in performance_data.items()])}
+
+Recommendation:
+{recommendation}
+""".strip()
+
+ context = {
+ "strategy_insight": {
+ "strategy": strategy_name,
+ "insight": insight,
+ "performance": performance_data,
+ "recommendation": recommendation,
+ }
+ }
+
+ tags = ["strategy_insight", strategy_name.lower().replace(" ", "_")]
+
+ return self.memory.add_memory(
+ content=content,
+ memory_type=MemoryType.SEMANTIC,
+ agent_id=discovered_by,
+ context=context,
+ priority=MemoryPriority.HIGH,
+ tags=tags,
+ )
+
+ def add_best_practice(
+ self,
+ title: str,
+ description: str,
+ when_to_use: str,
+ examples: List[str],
+ discovered_by: str,
+ ) -> str:
+ """
+ Add a best practice to organizational memory.
+ """
+ content = f"""
+BEST PRACTICE: {title}
+
+Description:
+{description}
+
+When to Use:
+{when_to_use}
+
+Examples:
+{chr(10).join([f"- {e}" for e in examples])}
+""".strip()
+
+ context = {
+ "best_practice": {
+ "title": title,
+ "description": description,
+ "when_to_use": when_to_use,
+ "examples": examples,
+ }
+ }
+
+ return self.memory.add_memory(
+ content=content,
+ memory_type=MemoryType.SEMANTIC,
+ agent_id=discovered_by,
+ context=context,
+ priority=MemoryPriority.HIGH,
+ tags=["best_practice"],
+ )
+
+ def add_anti_pattern(
+ self,
+ title: str,
+ description: str,
+ why_bad: str,
+ what_to_do_instead: str,
+ examples: List[str],
+ discovered_by: str,
+ ) -> str:
+ """
+ Add an anti-pattern (what NOT to do) to memory.
+
+ Anti-patterns are critical for avoiding repeated mistakes.
+ """
+ content = f"""
+ANTI-PATTERN: {title}
+
+Description (What to Avoid):
+{description}
+
+Why This Is Bad:
+{why_bad}
+
+What To Do Instead:
+{what_to_do_instead}
+
+Examples of This Anti-Pattern:
+{chr(10).join([f"- {e}" for e in examples])}
+
+REMEMBER: Avoiding this saves money!
+""".strip()
+
+ context = {
+ "anti_pattern": {
+ "title": title,
+ "description": description,
+ "why_bad": why_bad,
+ "alternative": what_to_do_instead,
+ "examples": examples,
+ }
+ }
+
+ return self.memory.add_memory(
+ content=content,
+ memory_type=MemoryType.SEMANTIC,
+ agent_id=discovered_by,
+ context=context,
+ priority=MemoryPriority.CRITICAL, # Anti-patterns are critical
+ tags=["anti_pattern", "avoid"],
+ emotional_valence=-0.5, # Negative association helps remember
+ )
+
+ def recall_lessons_for_situation(
+ self,
+ situation: str,
+ category: Optional[LessonCategory] = None,
+ limit: int = 5,
+ ) -> List[MemoryEntry]:
+ """
+ Recall relevant lessons for a given situation.
+ """
+ query = f"lesson {situation}"
+ if category:
+ query += f" {category.value}"
+
+ memories = self.memory.recall(
+ query=query,
+ memory_types=[MemoryType.SEMANTIC, MemoryType.LONG_TERM],
+ limit=limit * 2,
+ )
+
+ # Filter to actual lessons
+ lessons = []
+ for m in memories:
+ if "lesson" in m.tags or m.context.get("lesson"):
+ lessons.append(m)
+
+ return lessons[:limit]
+
+ def recall_insights_for_market_condition(
+ self,
+ market_condition: str,
+ limit: int = 5,
+ ) -> List[MemoryEntry]:
+ """
+ Recall market insights relevant to current conditions.
+ """
+ memories = self.memory.recall(
+ query=f"insight {market_condition}",
+ memory_types=[MemoryType.SEMANTIC, MemoryType.LONG_TERM],
+ limit=limit * 2,
+ )
+
+ # Filter to actual insights
+ insights = []
+ for m in memories:
+ if "insight" in m.tags or m.context.get("insight"):
+ insights.append(m)
+
+ return insights[:limit]
+
+ def recall_anti_patterns(
+ self,
+ situation: Optional[str] = None,
+ limit: int = 5,
+ ) -> List[MemoryEntry]:
+ """
+ Recall anti-patterns to avoid.
+
+ Should be called before major decisions to remember
+ what NOT to do.
+ """
+ query = "anti_pattern avoid"
+ if situation:
+ query += f" {situation}"
+
+ memories = self.memory.recall(
+ query=query,
+ memory_types=[MemoryType.SEMANTIC, MemoryType.LONG_TERM],
+ limit=limit,
+ )
+
+ # Filter to actual anti-patterns
+ anti_patterns = []
+ for m in memories:
+ if "anti_pattern" in m.tags or m.context.get("anti_pattern"):
+ anti_patterns.append(m)
+
+ return anti_patterns[:limit]
+
+ def recall_best_practices(
+ self,
+ situation: Optional[str] = None,
+ limit: int = 5,
+ ) -> List[MemoryEntry]:
+ """
+ Recall best practices for a situation.
+ """
+ query = "best_practice"
+ if situation:
+ query += f" {situation}"
+
+ memories = self.memory.recall(
+ query=query,
+ memory_types=[MemoryType.SEMANTIC, MemoryType.LONG_TERM],
+ limit=limit,
+ )
+
+ # Filter to actual best practices
+ best_practices = []
+ for m in memories:
+ if "best_practice" in m.tags or m.context.get("best_practice"):
+ best_practices.append(m)
+
+ return best_practices[:limit]
+
+ def get_learning_summary(
+ self,
+ category: Optional[LessonCategory] = None,
+ ) -> Dict[str, Any]:
+ """
+ Get summary of organizational learning.
+ """
+ all_memories = []
+
+ for mt in [MemoryType.SEMANTIC, MemoryType.LONG_TERM]:
+ all_memories.extend(self.memory._memories[mt].values())
+
+ lessons = [m for m in all_memories if "lesson" in m.tags]
+ insights = [m for m in all_memories if "insight" in m.tags]
+ best_practices = [m for m in all_memories if "best_practice" in m.tags]
+ anti_patterns = [m for m in all_memories if "anti_pattern" in m.tags]
+
+ return {
+ "total_learnings": len(all_memories),
+ "lessons_count": len(lessons),
+ "insights_count": len(insights),
+ "best_practices_count": len(best_practices),
+ "anti_patterns_count": len(anti_patterns),
+ "categories": {cat.value: 0 for cat in LessonCategory}, # Would count
+ }
+
+
+# Global learning memory instance
+_learning_memory: Optional[LearningMemory] = None
+
+
+def get_learning_memory() -> LearningMemory:
+ """Get the global learning memory instance"""
+ global _learning_memory
+ if _learning_memory is None:
+ _learning_memory = LearningMemory()
+ return _learning_memory
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/seed_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/seed_data.py
new file mode 100644
index 000000000..00cca2efb
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/seed_data.py
@@ -0,0 +1,469 @@
+"""
+Memory Seed Data
+
+Initial memories to bootstrap the Renaissance Technologies
+multi-agent system with institutional knowledge.
+"""
+
+from datetime import datetime, timedelta
+from typing import List
+
+from .base import (
+ RenTechMemory,
+ MemoryType,
+ MemoryPriority,
+ get_memory_system,
+)
+from .trade_memory import TradeMemory, TradeOutcome, get_trade_memory
+from .decision_memory import (
+ DecisionMemory,
+ Decision,
+ DecisionType,
+ DecisionOutcome,
+ get_decision_memory,
+)
+from .learning_memory import (
+ LearningMemory,
+ Lesson,
+ LessonCategory,
+ MarketInsight,
+ InsightType,
+ get_learning_memory,
+)
+
+
+def seed_lessons(learning: LearningMemory):
+ """Seed organizational lessons learned"""
+
+ # Lesson 1: Mean reversion timing
+ lesson1 = Lesson(
+ lesson_id="lesson_001",
+ category=LessonCategory.TIMING,
+ title="Mean Reversion Works Best in Low-Vol Regimes",
+ description="""
+Mean reversion signals have significantly higher win rates during
+low volatility periods (VIX < 18). During high volatility, mean
+reversion signals often get stopped out before reverting.
+
+The p-value threshold should be adjusted based on regime:
+- Low vol (VIX < 18): p < 0.02 is sufficient
+- Medium vol (VIX 18-25): p < 0.01 required
+- High vol (VIX > 25): p < 0.005 or skip entirely
+""".strip(),
+ supporting_events=[
+ "trade_20240115_AAPL_MR_001",
+ "trade_20240118_MSFT_MR_002",
+ "trade_20240122_GOOGL_MR_003",
+ ],
+ evidence_strength=0.85,
+ estimated_impact_bps=25,
+ frequency="daily",
+ action_items=[
+ "Adjust mean reversion model p-value threshold by VIX regime",
+ "Add regime filter to signal generation pipeline",
+ "Backtest regime-adjusted thresholds",
+ ],
+ status="active",
+ )
+ learning.add_lesson(lesson1, learned_by="research_team")
+
+ # Lesson 2: Execution timing
+ lesson2 = Lesson(
+ lesson_id="lesson_002",
+ category=LessonCategory.EXECUTION,
+ title="Avoid Trading First 15 Minutes",
+ description="""
+Execution costs are 3-4x higher in the first 15 minutes of market open.
+Spreads are wider, order book is thin, and retail flow creates noise.
+
+Unless we have urgent alpha decay concerns (urgency > 0.9), all
+orders should use a 15-minute delay from market open.
+
+Exception: Earnings reactions where alpha decays within minutes.
+""".strip(),
+ supporting_events=[
+ "exec_analysis_Q4_2024",
+ "trade_20240108_NVDA_001",
+ "trade_20240109_AMD_002",
+ ],
+ evidence_strength=0.92,
+ estimated_impact_bps=8,
+ frequency="daily",
+ action_items=[
+ "Add 15-minute delay to default execution profile",
+ "Create 'urgent' execution profile for exceptions",
+ "Monitor first-15-min trades monthly",
+ ],
+ status="implemented",
+ )
+ learning.add_lesson(lesson2, learned_by="trading_team")
+
+ # Lesson 3: Position sizing
+ lesson3 = Lesson(
+ lesson_id="lesson_003",
+ category=LessonCategory.POSITION_SIZING,
+ title="Kelly Criterion Overestimates in Correlated Positions",
+ description="""
+When multiple signals fire on correlated assets (e.g., AAPL/MSFT,
+or multiple tech stocks), Kelly criterion overestimates appropriate
+sizing because it doesn't account for correlation.
+
+Implemented correlation penalty: If new position has >0.7 correlation
+with existing book, reduce Kelly size by (1 - correlation^2).
+""".strip(),
+ supporting_events=[
+ "drawdown_event_20240215",
+ "risk_report_20240216",
+ ],
+ evidence_strength=0.88,
+ estimated_impact_bps=150,
+ frequency="weekly",
+ action_items=[
+ "Implement correlation penalty in position sizer",
+ "Add correlation check to pre-trade risk",
+ "Review sector concentration weekly",
+ ],
+ status="implemented",
+ )
+ learning.add_lesson(lesson3, learned_by="risk_team")
+
+ # Lesson 4: Data quality
+ lesson4 = Lesson(
+ lesson_id="lesson_004",
+ category=LessonCategory.DATA_QUALITY,
+ title="Corporate Action Data Leads to False Signals",
+ description="""
+Stock splits, special dividends, and spin-offs cause false
+mean reversion signals when price data isn't properly adjusted.
+
+Lost 45 bps on NVDA position when 10:1 split wasn't reflected
+in intraday data feed.
+
+All signals must check for corporate actions in T-5 to T+5 window.
+""".strip(),
+ supporting_events=[
+ "trade_20240610_NVDA_SPLIT_001",
+ "data_incident_20240610",
+ ],
+ evidence_strength=0.95,
+ estimated_impact_bps=45,
+ frequency="rare",
+ action_items=[
+ "Add corporate action filter to signal pipeline",
+ "Subscribe to real-time corporate action feed",
+ "Create data quality dashboard",
+ ],
+ status="active",
+ )
+ learning.add_lesson(lesson4, learned_by="data_scientist")
+
+
+def seed_market_insights(learning: LearningMemory):
+ """Seed market behavior insights"""
+
+ # Insight 1: Post-FOMC pattern
+ insight1 = MarketInsight(
+ insight_id="insight_001",
+ insight_type=InsightType.PATTERN,
+ market_condition="fomc_day",
+ observation="""
+Market tends to reverse initial FOMC reaction within 24 hours
+approximately 65% of the time. Initial spike up often followed
+by profit-taking, initial drop often followed by dip-buying.
+""".strip(),
+ statistical_evidence={
+ "sample_size": 48,
+ "win_rate": 0.65,
+ "avg_reversal_bps": 45,
+ "t_statistic": 2.8,
+ "p_value": 0.007,
+ },
+ trading_implications=[
+ "Consider fading large initial FOMC moves",
+ "Size smaller on FOMC day directional bets",
+ "Look for reversal signals in first 24 hours post-FOMC",
+ ],
+ )
+ learning.add_market_insight(insight1, discovered_by="quant_researcher")
+
+ # Insight 2: Sector rotation
+ insight2 = MarketInsight(
+ insight_id="insight_002",
+ insight_type=InsightType.PATTERN,
+ market_condition="rising_rates",
+ observation="""
+When 10-year Treasury yield rises >10bps in a week, growth stocks
+underperform value stocks by 150-200 bps on average over the
+following 2 weeks.
+""".strip(),
+ statistical_evidence={
+ "sample_size": 85,
+ "correlation": 0.45,
+ "avg_spread_bps": 175,
+ "t_statistic": 3.2,
+ "p_value": 0.002,
+ },
+ trading_implications=[
+ "Reduce growth exposure when rates spike",
+ "Consider growth/value pair trade",
+ "Monitor Treasury auctions for rate signals",
+ ],
+ )
+ learning.add_market_insight(insight2, discovered_by="signal_scientist")
+
+
+def seed_best_practices(learning: LearningMemory):
+ """Seed operational best practices"""
+
+ learning.add_best_practice(
+ title="Pre-Trade Risk Check Protocol",
+ description="""
+Before executing any trade, the following checks must pass:
+1. Position size within limits (single name, sector, portfolio)
+2. Correlation check against existing book
+3. Liquidity check (order < 1% of ADV)
+4. Market regime check (not halted, not circuit breaker)
+5. Compliance check (restricted list, insider window)
+""".strip(),
+ when_to_use="Before every trade execution",
+ examples=[
+ "Caught oversized TSLA position that would breach sector limit",
+ "Prevented trade during earnings blackout window",
+ "Reduced size on illiquid small-cap to meet ADV limit",
+ ],
+ discovered_by="compliance_officer",
+ )
+
+ learning.add_best_practice(
+ title="Signal Validation 4-Eye Principle",
+ description="""
+Every new signal type requires validation by at least two
+independent researchers before production deployment:
+1. Primary researcher develops and backtests
+2. Secondary researcher validates on different data period
+3. Risk team reviews for potential edge cases
+4. IC approves for production with size limits
+""".strip(),
+ when_to_use="When deploying any new signal type",
+ examples=[
+ "Momentum signal validated by both Sarah and Chen",
+ "Stat arb signal caught overfitting in second validation",
+ "Risk team identified correlation issue before deployment",
+ ],
+ discovered_by="research_lead",
+ )
+
+
+def seed_anti_patterns(learning: LearningMemory):
+ """Seed things to avoid"""
+
+ learning.add_anti_pattern(
+ title="Chasing Performance After Drawdowns",
+ description="""
+After a significant drawdown (>5%), there's a tendency to
+increase position sizes to 'make back' losses. This usually
+leads to larger losses.
+""".strip(),
+ why_bad="""
+1. Drawdowns often occur during regime changes
+2. Increased sizing increases risk of further drawdown
+3. Emotional decision-making impairs judgment
+4. Creates negative feedback loop
+""".strip(),
+ what_to_do_instead="""
+1. Reduce position sizes by 20% after 5% drawdown
+2. Review regime indicators before resuming normal sizing
+3. Focus on signal quality, not P&L recovery
+4. Let position sizing model, not emotions, determine size
+""".strip(),
+ examples=[
+ "Feb 2024: Increased size after 6% drawdown, lost additional 4%",
+ "Aug 2023: Discipline after drawdown, recovered within 2 weeks",
+ ],
+ discovered_by="investment_committee",
+ )
+
+ learning.add_anti_pattern(
+ title="Overriding Model on 'Gut Feel'",
+ description="""
+Manually overriding signal models because 'this time is different'
+or 'the market doesn't feel right' has negative expected value.
+""".strip(),
+ why_bad="""
+1. Gut feel is systematically overconfident
+2. Models incorporate more data than intuition
+3. Creates inconsistent track record
+4. Undermines quantitative discipline
+""".strip(),
+ what_to_do_instead="""
+1. If model seems wrong, investigate the data
+2. Add new factors to model rather than overriding
+3. Document every override for later analysis
+4. Review override outcomes quarterly
+""".strip(),
+ examples=[
+ "Override on AAPL 2024-01: Lost 35 bps vs model signal",
+ "Override on market regime: Missed 2% rally by going defensive",
+ ],
+ discovered_by="investment_committee",
+ )
+
+
+def seed_historical_trades(trades: TradeMemory):
+ """Seed some historical trade memories"""
+
+ # Profitable mean reversion trade
+ outcome1 = TradeOutcome(
+ trade_id="trade_20240115_AAPL_MR_001",
+ ticker="AAPL",
+ direction="long",
+ signal_type="mean_reversion",
+ entry_price=185.50,
+ exit_price=188.25,
+ entry_date="2024-01-15",
+ exit_date="2024-01-17",
+ quantity=5000,
+ pnl_bps=148,
+ pnl_dollars=13750,
+ vs_expected_bps=28,
+ slippage_bps=2.1,
+ market_impact_bps=3.5,
+ execution_algorithm="twap",
+ market_regime="low_vol",
+ sector_performance=1.2,
+ vix_level=14.5,
+ confidence_at_entry=0.58,
+ p_value_at_entry=0.008,
+ )
+ trades.remember_trade(
+ outcome1,
+ agent_id="execution_trader",
+ lessons_learned=[
+ "Mean reversion worked well in low VIX environment",
+ "TWAP execution kept market impact low",
+ ],
+ )
+
+ # Loss on momentum trade
+ outcome2 = TradeOutcome(
+ trade_id="trade_20240120_TSLA_MOM_001",
+ ticker="TSLA",
+ direction="long",
+ signal_type="momentum",
+ entry_price=225.00,
+ exit_price=218.50,
+ entry_date="2024-01-20",
+ exit_date="2024-01-22",
+ quantity=2000,
+ pnl_bps=-289,
+ pnl_dollars=-13000,
+ vs_expected_bps=-189,
+ slippage_bps=5.2,
+ market_impact_bps=8.0,
+ execution_algorithm="vwap",
+ market_regime="high_vol",
+ sector_performance=-2.5,
+ vix_level=22.0,
+ confidence_at_entry=0.52,
+ p_value_at_entry=0.015,
+ )
+ trades.remember_trade(
+ outcome2,
+ agent_id="execution_trader",
+ lessons_learned=[
+ "Momentum signal failed in high VIX environment",
+ "P-value was borderline (0.015 vs 0.01 threshold)",
+ "Should have reduced size given elevated VIX",
+ ],
+ )
+
+
+def seed_historical_decisions(decisions: DecisionMemory):
+ """Seed some historical IC decisions"""
+
+ # Approved trade that worked
+ decision1 = Decision(
+ decision_id="dec_20240115_001",
+ decision_type=DecisionType.IC_APPROVAL,
+ decision_maker="investment_committee",
+ timestamp="2024-01-15T09:30:00",
+ subject="AAPL long mean_reversion",
+ action="APPROVED with full size",
+ rationale=[
+ "Strong statistical significance (p=0.008)",
+ "Low VIX environment favorable for mean reversion",
+ "AAPL has high liquidity, easy to execute",
+ "Within all risk limits",
+ ],
+ signal_strength=0.72,
+ confidence=0.58,
+ risk_score=0.3,
+ market_conditions={"vix": 14.5, "regime": "low_vol"},
+ outcome=DecisionOutcome.CORRECT,
+ outcome_notes="Trade returned +148 bps, exceeded expectations",
+ outcome_pnl_bps=148,
+ )
+ decisions.remember_decision(decision1)
+
+ # Rejected trade (correct rejection)
+ decision2 = Decision(
+ decision_id="dec_20240120_002",
+ decision_type=DecisionType.IC_REJECTION,
+ decision_maker="investment_committee",
+ timestamp="2024-01-20T09:30:00",
+ subject="NVDA short stat_arb",
+ action="REJECTED - insufficient evidence",
+ rationale=[
+ "P-value borderline at 0.02",
+ "High VIX environment increases risk",
+ "NVDA has high momentum, shorting risky",
+ "Earnings in 2 weeks adds uncertainty",
+ ],
+ signal_strength=0.45,
+ confidence=0.51,
+ risk_score=0.7,
+ market_conditions={"vix": 22.0, "regime": "high_vol"},
+ outcome=DecisionOutcome.CORRECT,
+ outcome_notes="NVDA rose 15% after rejection, correct to avoid",
+ )
+ decisions.remember_decision(decision2)
+
+
+def seed_all_memories():
+ """Seed all memory systems with initial data"""
+ print("Seeding memory systems...")
+
+ # Get memory instances
+ learning = get_learning_memory()
+ trades = get_trade_memory()
+ decisions = get_decision_memory()
+
+ # Seed each component
+ print(" - Seeding lessons learned...")
+ seed_lessons(learning)
+
+ print(" - Seeding market insights...")
+ seed_market_insights(learning)
+
+ print(" - Seeding best practices...")
+ seed_best_practices(learning)
+
+ print(" - Seeding anti-patterns...")
+ seed_anti_patterns(learning)
+
+ print(" - Seeding historical trades...")
+ seed_historical_trades(trades)
+
+ print(" - Seeding historical decisions...")
+ seed_historical_decisions(decisions)
+
+ print("Memory seeding complete!")
+
+ # Return summary
+ memory = get_memory_system()
+ return memory.get_memory_summary()
+
+
+if __name__ == "__main__":
+ summary = seed_all_memories()
+ print(f"\nMemory Summary: {summary}")
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/trade_memory.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/trade_memory.py
new file mode 100644
index 000000000..9c8c4b2bf
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/memory/trade_memory.py
@@ -0,0 +1,363 @@
+"""
+Trade Memory
+
+Specialized memory system for trade-related information:
+- Trade outcomes and P&L
+- Execution quality
+- Signal performance
+- Market conditions during trades
+"""
+
+from typing import Optional, List, Dict, Any
+from datetime import datetime, timedelta
+from dataclasses import dataclass, field
+import uuid
+
+from .base import (
+ RenTechMemory,
+ MemoryType,
+ MemoryEntry,
+ MemoryPriority,
+ get_memory_system,
+)
+
+
+@dataclass
+class TradeOutcome:
+ """Structured trade outcome for memory"""
+ trade_id: str
+ ticker: str
+ direction: str # long/short
+ signal_type: str
+
+ # Execution
+ entry_price: float
+ exit_price: Optional[float]
+ entry_date: str
+ exit_date: Optional[str]
+ quantity: int
+
+ # Performance
+ pnl_bps: Optional[float] # P&L in basis points
+ pnl_dollars: Optional[float]
+ vs_expected_bps: Optional[float] # Actual vs predicted
+
+ # Execution quality
+ slippage_bps: Optional[float]
+ market_impact_bps: Optional[float]
+ execution_algorithm: str
+
+ # Market conditions
+ market_regime: str # bull/bear/sideways/volatile
+ sector_performance: Optional[float] # Sector return during trade
+ vix_level: Optional[float]
+
+ # Metadata
+ confidence_at_entry: float
+ p_value_at_entry: Optional[float]
+
+
+class TradeMemory:
+ """
+ Trade-specific memory manager.
+
+ Remembers:
+ - Successful trades (for pattern replication)
+ - Failed trades (to avoid similar mistakes)
+ - Execution quality (for algorithm selection)
+ - Market condition correlations
+ """
+
+ def __init__(self, memory_system: Optional[RenTechMemory] = None):
+ self.memory = memory_system or get_memory_system()
+
+ def remember_trade(
+ self,
+ outcome: TradeOutcome,
+ agent_id: str,
+ lessons_learned: Optional[List[str]] = None,
+ ) -> str:
+ """
+ Remember a completed trade.
+
+ Args:
+ outcome: Trade outcome data
+ agent_id: Agent who executed/analyzed the trade
+ lessons_learned: Key takeaways from this trade
+
+ Returns:
+ Memory ID
+ """
+ # Determine memory priority based on outcome
+ pnl = outcome.pnl_bps or 0
+
+ if abs(pnl) > 100: # Significant trade (>1%)
+ priority = MemoryPriority.HIGH
+ elif abs(pnl) > 50: # Notable trade
+ priority = MemoryPriority.MEDIUM
+ else:
+ priority = MemoryPriority.LOW
+
+ # Exceptional outcomes get critical priority
+ if abs(pnl) > 500 or abs(outcome.vs_expected_bps or 0) > 200:
+ priority = MemoryPriority.CRITICAL
+
+ # Build memory content
+ outcome_str = "profitable" if pnl > 0 else "loss" if pnl < 0 else "break-even"
+ execution_quality = self._assess_execution(outcome)
+
+ content = f"""
+Trade {outcome.trade_id}: {outcome.ticker} {outcome.direction.upper()}
+Signal: {outcome.signal_type} | Outcome: {outcome_str.upper()}
+P&L: {pnl:+.1f} bps (${outcome.pnl_dollars or 0:,.0f})
+Expected: {outcome.confidence_at_entry:.1%} confidence, p-value: {outcome.p_value_at_entry or 'N/A'}
+Actual vs Expected: {outcome.vs_expected_bps or 0:+.1f} bps
+
+Execution Quality: {execution_quality}
+- Slippage: {outcome.slippage_bps or 0:.1f} bps
+- Market Impact: {outcome.market_impact_bps or 0:.1f} bps
+- Algorithm: {outcome.execution_algorithm}
+
+Market Conditions:
+- Regime: {outcome.market_regime}
+- VIX: {outcome.vix_level or 'N/A'}
+
+Lessons:
+{chr(10).join([f"- {l}" for l in (lessons_learned or ['None documented'])])}
+""".strip()
+
+ # Emotional valence based on outcome
+ emotional_valence = 0.0
+ if pnl > 0:
+ emotional_valence = min(0.8, pnl / 200) # Cap at 0.8
+ elif pnl < 0:
+ emotional_valence = max(-0.8, pnl / 200)
+
+ # Surprise factor based on deviation from expected
+ vs_expected = abs(outcome.vs_expected_bps or 0)
+ surprise_factor = min(1.0, vs_expected / 100)
+
+ # Create context with structured data
+ context = {
+ "trade_outcome": {
+ "trade_id": outcome.trade_id,
+ "ticker": outcome.ticker,
+ "direction": outcome.direction,
+ "signal_type": outcome.signal_type,
+ "pnl_bps": outcome.pnl_bps,
+ "vs_expected_bps": outcome.vs_expected_bps,
+ "execution_quality": execution_quality,
+ "market_regime": outcome.market_regime,
+ },
+ "lessons": lessons_learned or [],
+ }
+
+ # Tags for easy retrieval
+ tags = [
+ outcome.ticker,
+ outcome.direction,
+ outcome.signal_type,
+ outcome_str,
+ outcome.market_regime,
+ f"algo_{outcome.execution_algorithm}",
+ ]
+
+ # Determine memory type
+ # Exceptional trades go to long-term immediately
+ if priority == MemoryPriority.CRITICAL:
+ memory_type = MemoryType.EPISODIC # Specific events
+ else:
+ memory_type = MemoryType.SHORT_TERM
+
+ return self.memory.add_memory(
+ content=content,
+ memory_type=memory_type,
+ agent_id=agent_id,
+ context=context,
+ priority=priority,
+ tags=tags,
+ emotional_valence=emotional_valence,
+ surprise_factor=surprise_factor,
+ )
+
+ def _assess_execution(self, outcome: TradeOutcome) -> str:
+ """Assess execution quality"""
+ total_cost = (outcome.slippage_bps or 0) + (outcome.market_impact_bps or 0)
+
+ if total_cost <= 2:
+ return "excellent"
+ elif total_cost <= 5:
+ return "good"
+ elif total_cost <= 10:
+ return "acceptable"
+ elif total_cost <= 20:
+ return "poor"
+ else:
+ return "very_poor"
+
+ def recall_similar_trades(
+ self,
+ ticker: str,
+ signal_type: str,
+ direction: str,
+ market_regime: Optional[str] = None,
+ limit: int = 5,
+ ) -> List[MemoryEntry]:
+ """
+ Recall similar historical trades.
+
+ Used before entering a new position to learn from
+ similar past situations.
+ """
+ # Build search query
+ query = f"{ticker} {signal_type} {direction}"
+ if market_regime:
+ query += f" {market_regime}"
+
+ memories = self.memory.recall(
+ query=query,
+ memory_types=[MemoryType.SHORT_TERM, MemoryType.LONG_TERM, MemoryType.EPISODIC],
+ limit=limit * 2, # Get extra, filter down
+ )
+
+ # Filter to relevant trades
+ relevant = []
+ for m in memories:
+ ctx = m.context.get("trade_outcome", {})
+ if ctx.get("signal_type") == signal_type:
+ relevant.append(m)
+
+ return relevant[:limit]
+
+ def recall_losses(
+ self,
+ ticker: Optional[str] = None,
+ signal_type: Optional[str] = None,
+ min_loss_bps: float = 50,
+ limit: int = 10,
+ ) -> List[MemoryEntry]:
+ """
+ Recall losing trades for risk awareness.
+
+ Helps avoid repeating mistakes.
+ """
+ query = "loss"
+ if ticker:
+ query += f" {ticker}"
+ if signal_type:
+ query += f" {signal_type}"
+
+ memories = self.memory.recall(
+ query=query,
+ memory_types=[MemoryType.SHORT_TERM, MemoryType.LONG_TERM, MemoryType.EPISODIC],
+ limit=limit * 2,
+ )
+
+ # Filter to actual losses above threshold
+ losses = []
+ for m in memories:
+ ctx = m.context.get("trade_outcome", {})
+ pnl = ctx.get("pnl_bps", 0)
+ if pnl is not None and pnl < -min_loss_bps:
+ losses.append(m)
+
+ # Sort by magnitude of loss
+ losses.sort(
+ key=lambda x: x.context.get("trade_outcome", {}).get("pnl_bps", 0)
+ )
+
+ return losses[:limit]
+
+ def recall_by_market_regime(
+ self,
+ regime: str,
+ limit: int = 10,
+ ) -> List[MemoryEntry]:
+ """Recall trades from a specific market regime"""
+ return self.memory.get_memories_by_tags(
+ tags=[regime],
+ memory_types=[MemoryType.SHORT_TERM, MemoryType.LONG_TERM, MemoryType.EPISODIC],
+ )[:limit]
+
+ def get_signal_performance_summary(
+ self,
+ signal_type: str,
+ ) -> Dict[str, Any]:
+ """
+ Get performance summary for a signal type.
+
+ Used to assess signal quality over time.
+ """
+ memories = self.memory.recall(
+ query=signal_type,
+ memory_types=[MemoryType.SHORT_TERM, MemoryType.LONG_TERM, MemoryType.EPISODIC],
+ limit=100,
+ )
+
+ # Filter to matching signal type
+ trades = []
+ for m in memories:
+ ctx = m.context.get("trade_outcome", {})
+ if ctx.get("signal_type") == signal_type:
+ trades.append(ctx)
+
+ if not trades:
+ return {"signal_type": signal_type, "sample_size": 0}
+
+ # Calculate statistics
+ pnls = [t.get("pnl_bps", 0) or 0 for t in trades]
+ wins = [p for p in pnls if p > 0]
+ losses = [p for p in pnls if p < 0]
+
+ return {
+ "signal_type": signal_type,
+ "sample_size": len(trades),
+ "win_rate": len(wins) / len(trades) if trades else 0,
+ "avg_pnl_bps": sum(pnls) / len(pnls) if pnls else 0,
+ "avg_win_bps": sum(wins) / len(wins) if wins else 0,
+ "avg_loss_bps": sum(losses) / len(losses) if losses else 0,
+ "total_pnl_bps": sum(pnls),
+ }
+
+ def get_execution_performance(
+ self,
+ algorithm: str,
+ ) -> Dict[str, Any]:
+ """
+ Get execution performance for an algorithm.
+
+ Helps choose the best execution algorithm.
+ """
+ memories = self.memory.recall(
+ query=f"algo_{algorithm}",
+ memory_types=[MemoryType.SHORT_TERM, MemoryType.LONG_TERM, MemoryType.EPISODIC],
+ limit=100,
+ )
+
+ slippages = []
+ impacts = []
+
+ for m in memories:
+ ctx = m.context.get("trade_outcome", {})
+ if ctx.get("execution_algorithm") == algorithm:
+ # Would need to parse from content in real implementation
+ pass
+
+ return {
+ "algorithm": algorithm,
+ "sample_size": len(memories),
+ "avg_slippage_bps": sum(slippages) / len(slippages) if slippages else None,
+ "avg_impact_bps": sum(impacts) / len(impacts) if impacts else None,
+ }
+
+
+# Global trade memory instance
+_trade_memory: Optional[TradeMemory] = None
+
+
+def get_trade_memory() -> TradeMemory:
+ """Get the global trade memory instance"""
+ global _trade_memory
+ if _trade_memory is None:
+ _trade_memory = TradeMemory()
+ return _trade_memory
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/models/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/models/__init__.py
new file mode 100644
index 000000000..f87ab9a05
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/models/__init__.py
@@ -0,0 +1,72 @@
+"""Renaissance Technologies data models and schemas."""
+
+from .schemas import (
+ SignalType,
+ ConfidenceLevel,
+ MeanReversionSignal,
+ MomentumSignal,
+ PatternRecognitionSignal,
+ CrossSectionalSignal,
+ SignalGenerationOutput,
+ VolatilityMetrics,
+ CorrelationRisk,
+ FactorRiskDecomposition,
+ DrawdownAnalysis,
+ RiskModelingOutput,
+ MarketImpactEstimate,
+ TransactionCostAnalysis,
+ LiquidityAnalysis,
+ ExecutionOptimizationOutput,
+ PairsTradingSignal,
+ MispricingDetection,
+ RegimeDetection,
+ StatisticalArbitrageOutput,
+ PositionSizing,
+ MedallionDecision,
+ RenaissancePortfolioAnalysis,
+)
+
+from .model_factory import (
+ create_model,
+ create_zhipuai_model,
+ create_openai_model,
+ create_anthropic_model,
+ create_groq_model,
+ create_ollama_model,
+ get_model_info,
+)
+
+__all__ = [
+ # Schemas
+ "SignalType",
+ "ConfidenceLevel",
+ "MeanReversionSignal",
+ "MomentumSignal",
+ "PatternRecognitionSignal",
+ "CrossSectionalSignal",
+ "SignalGenerationOutput",
+ "VolatilityMetrics",
+ "CorrelationRisk",
+ "FactorRiskDecomposition",
+ "DrawdownAnalysis",
+ "RiskModelingOutput",
+ "MarketImpactEstimate",
+ "TransactionCostAnalysis",
+ "LiquidityAnalysis",
+ "ExecutionOptimizationOutput",
+ "PairsTradingSignal",
+ "MispricingDetection",
+ "RegimeDetection",
+ "StatisticalArbitrageOutput",
+ "PositionSizing",
+ "MedallionDecision",
+ "RenaissancePortfolioAnalysis",
+ # Model factory
+ "create_model",
+ "create_zhipuai_model",
+ "create_openai_model",
+ "create_anthropic_model",
+ "create_groq_model",
+ "create_ollama_model",
+ "get_model_info",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/models/model_factory.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/models/model_factory.py
new file mode 100644
index 000000000..3ac6a528e
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/models/model_factory.py
@@ -0,0 +1,201 @@
+"""
+Model Factory for Renaissance Technologies System
+
+Creates model instances based on configuration.
+Supports multiple providers.
+"""
+
+from typing import Any, Optional
+from ..config import get_config, ModelProvider, ModelConfig
+
+
+def create_model(config: Optional[ModelConfig] = None) -> Any:
+ """
+ Create a model instance based on configuration.
+
+ Supports:
+ - OpenAI (gpt-4o, gpt-4o-mini, etc.)
+ - Anthropic (claude-3-opus, claude-3-sonnet, etc.)
+ - Groq (llama-3.3-70b-versatile, etc.)
+ - Ollama (local models)
+ - Zhipu AI
+
+ Returns:
+ Model instance compatible with Agno Agent
+ """
+ config = config or get_config().models
+
+ if config.provider == ModelProvider.ZHIPUAI:
+ return create_zhipuai_model(config)
+ elif config.provider == ModelProvider.OPENAI:
+ return create_openai_model(config)
+ elif config.provider == ModelProvider.ANTHROPIC:
+ return create_anthropic_model(config)
+ elif config.provider == ModelProvider.GROQ:
+ return create_groq_model(config)
+ elif config.provider == ModelProvider.OLLAMA:
+ return create_ollama_model(config)
+ else:
+ raise ValueError(f"Unsupported provider: {config.provider}")
+
+
+def create_zhipuai_model(config: ModelConfig) -> Any:
+ """
+ Create a Zhipu AI model instance.
+
+ Uses OpenAILike for OpenAI-compatible API endpoints.
+ """
+ try:
+ # Use OpenAILike for better compatibility with OpenAI-compatible endpoints
+ from agno.models.openai.like import OpenAILike
+
+ return OpenAILike(
+ id=config.model_id,
+ name="ZhipuAI",
+ provider="ZhipuAI",
+ api_key=config.zhipuai_api_key,
+ base_url=config.zhipuai_base_url,
+ )
+ except ImportError:
+ try:
+ # Fallback to OpenAIChat if OpenAILike not available
+ from agno.models.openai import OpenAIChat
+
+ return OpenAIChat(
+ id=config.model_id,
+ api_key=config.zhipuai_api_key,
+ base_url=config.zhipuai_base_url,
+ temperature=config.temperature,
+ max_tokens=config.max_tokens,
+ )
+ except ImportError:
+ # Final fallback: Return config dict for manual initialization
+ return {
+ "provider": "zhipuai",
+ "model_id": config.model_id,
+ "api_key": config.zhipuai_api_key,
+ "base_url": config.zhipuai_base_url,
+ "temperature": config.temperature,
+ "max_tokens": config.max_tokens,
+ }
+
+
+def create_openai_model(config: ModelConfig) -> Any:
+ """Create an OpenAI model instance."""
+ try:
+ from agno.models.openai import OpenAIChat
+
+ return OpenAIChat(
+ id=config.model_id,
+ temperature=config.temperature,
+ max_tokens=config.max_tokens,
+ )
+ except ImportError:
+ return {
+ "provider": "openai",
+ "model_id": config.model_id,
+ "temperature": config.temperature,
+ "max_tokens": config.max_tokens,
+ }
+
+
+def create_anthropic_model(config: ModelConfig) -> Any:
+ """
+ Create an Anthropic model instance.
+
+ Supports custom base_url for Anthropic-compatible endpoints.
+ """
+ try:
+ from agno.models.anthropic import Claude
+ import anthropic
+
+ # Check if we have a custom base URL
+ base_url = getattr(config, 'anthropic_base_url', None)
+ api_key = getattr(config, 'anthropic_api_key', None)
+
+ if base_url and api_key:
+ # Create custom Anthropic client with custom base_url
+ custom_client = anthropic.Anthropic(
+ api_key=api_key,
+ base_url=base_url,
+ )
+ return Claude(
+ id=config.model_id,
+ client=custom_client,
+ temperature=config.temperature,
+ max_tokens=config.max_tokens,
+ )
+ else:
+ return Claude(
+ id=config.model_id,
+ temperature=config.temperature,
+ max_tokens=config.max_tokens,
+ )
+ except ImportError:
+ return {
+ "provider": "anthropic",
+ "model_id": config.model_id,
+ "temperature": config.temperature,
+ "max_tokens": config.max_tokens,
+ }
+
+
+def create_groq_model(config: ModelConfig) -> Any:
+ """Create a Groq model instance."""
+ try:
+ from agno.models.groq import Groq
+
+ return Groq(
+ id=config.model_id,
+ temperature=config.temperature,
+ max_tokens=config.max_tokens,
+ )
+ except ImportError:
+ return {
+ "provider": "groq",
+ "model_id": config.model_id,
+ "temperature": config.temperature,
+ "max_tokens": config.max_tokens,
+ }
+
+
+def create_ollama_model(config: ModelConfig) -> Any:
+ """Create an Ollama model instance."""
+ try:
+ from agno.models.ollama import Ollama
+
+ return Ollama(
+ id=config.model_id,
+ temperature=config.temperature,
+ )
+ except ImportError:
+ return {
+ "provider": "ollama",
+ "model_id": config.model_id,
+ "temperature": config.temperature,
+ }
+
+
+def get_model_info() -> dict:
+ """Get information about the currently configured model."""
+ config = get_config().models
+
+ return {
+ "provider": config.provider.value,
+ "model_id": config.model_id,
+ "reasoning_model_id": config.reasoning_model_id,
+ "memory_model_id": config.memory_model_id,
+ "temperature": config.temperature,
+ "max_tokens": config.max_tokens,
+ }
+
+
+__all__ = [
+ "create_model",
+ "create_zhipuai_model",
+ "create_openai_model",
+ "create_anthropic_model",
+ "create_groq_model",
+ "create_ollama_model",
+ "get_model_info",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/models/schemas.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/models/schemas.py
new file mode 100644
index 000000000..8c8e4eab1
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/models/schemas.py
@@ -0,0 +1,244 @@
+"""
+Pydantic schemas for Renaissance Technologies agent outputs.
+Structured outputs following RenTech's quantitative philosophy.
+"""
+
+from pydantic import BaseModel, Field
+from typing import Dict, List, Optional, Literal
+from enum import Enum
+
+
+class SignalType(str, Enum):
+ BULLISH = "bullish"
+ BEARISH = "bearish"
+ NEUTRAL = "neutral"
+
+
+class ConfidenceLevel(str, Enum):
+ HIGH = "high" # >80% statistical significance
+ MEDIUM = "medium" # 60-80% significance
+ LOW = "low" # <60% significance
+
+
+# ============================================================
+# Signal Generation Models
+# ============================================================
+
+class MeanReversionSignal(BaseModel):
+ """Mean reversion signal output"""
+ signal_strength: float = Field(..., ge=-1.0, le=1.0, description="Signal strength (-1 to 1)")
+ z_score: float = Field(..., description="Current z-score from historical mean")
+ half_life: Optional[float] = Field(None, description="Mean reversion half-life in periods")
+ statistical_significance: float = Field(..., ge=0, le=1, description="P-value significance")
+
+
+class MomentumSignal(BaseModel):
+ """Momentum signal output"""
+ signal_strength: float = Field(..., ge=-1.0, le=1.0)
+ trend_strength: float = Field(..., ge=0, le=1, description="Trend persistence measure")
+ acceleration: float = Field(..., description="Rate of momentum change")
+ lookback_period: int = Field(..., description="Optimal lookback period identified")
+
+
+class PatternRecognitionSignal(BaseModel):
+ """Statistical pattern recognition output"""
+ pattern_type: str = Field(..., description="Identified pattern type")
+ pattern_confidence: float = Field(..., ge=0, le=1)
+ autocorrelation: float = Field(..., ge=-1, le=1)
+ regime: Literal["trending", "mean_reverting", "random_walk"] = Field(...)
+
+
+class CrossSectionalSignal(BaseModel):
+ """Cross-sectional ranking signal"""
+ percentile_rank: float = Field(..., ge=0, le=100, description="Percentile vs peers")
+ factor_exposures: Dict[str, float] = Field(..., description="Factor exposure coefficients")
+ composite_score: float = Field(..., ge=0, le=10)
+
+
+class SignalGenerationOutput(BaseModel):
+ """Complete signal generation team output"""
+ mean_reversion: MeanReversionSignal
+ momentum: MomentumSignal
+ pattern_recognition: PatternRecognitionSignal
+ cross_sectional: CrossSectionalSignal
+ aggregate_signal: float = Field(..., ge=-1, le=1, description="Combined signal")
+ statistical_significance: float = Field(..., ge=0, le=1)
+ reasoning: str = Field(..., description="Signal generation reasoning")
+
+
+# ============================================================
+# Risk Modeling Models
+# ============================================================
+
+class VolatilityMetrics(BaseModel):
+ """Volatility analysis output"""
+ realized_volatility: float = Field(..., ge=0)
+ implied_volatility: Optional[float] = Field(None, ge=0)
+ volatility_regime: Literal["low", "normal", "high", "extreme"] = Field(...)
+ vol_of_vol: float = Field(..., ge=0, description="Volatility of volatility")
+
+
+class CorrelationRisk(BaseModel):
+ """Correlation risk analysis"""
+ market_correlation: float = Field(..., ge=-1, le=1)
+ sector_correlation: float = Field(..., ge=-1, le=1)
+ idiosyncratic_ratio: float = Field(..., ge=0, le=1, description="Portion of risk that is idiosyncratic")
+
+
+class FactorRiskDecomposition(BaseModel):
+ """Factor risk decomposition"""
+ market_beta: float = Field(...)
+ size_factor: float = Field(...)
+ value_factor: float = Field(...)
+ momentum_factor: float = Field(...)
+ quality_factor: float = Field(...)
+ total_factor_risk: float = Field(..., ge=0)
+ specific_risk: float = Field(..., ge=0)
+
+
+class DrawdownAnalysis(BaseModel):
+ """Maximum drawdown risk analysis"""
+ max_drawdown: float = Field(..., ge=0, le=1)
+ current_drawdown: float = Field(..., ge=0, le=1)
+ recovery_time_estimate: Optional[int] = Field(None, description="Estimated recovery periods")
+ tail_risk_var_95: float = Field(..., description="95% Value at Risk")
+
+
+class RiskModelingOutput(BaseModel):
+ """Complete risk modeling team output"""
+ volatility: VolatilityMetrics
+ correlation: CorrelationRisk
+ factor_decomposition: FactorRiskDecomposition
+ drawdown: DrawdownAnalysis
+ risk_score: float = Field(..., ge=0, le=10, description="Overall risk score (lower is better)")
+ risk_adjusted_signal: float = Field(..., ge=-1, le=1)
+ reasoning: str
+
+
+# ============================================================
+# Execution Optimization Models
+# ============================================================
+
+class MarketImpactEstimate(BaseModel):
+ """Market impact estimation"""
+ estimated_impact_bps: float = Field(..., ge=0, description="Estimated impact in basis points")
+ optimal_trade_size: float = Field(..., ge=0, description="Optimal position size")
+ time_to_execute: int = Field(..., ge=1, description="Recommended execution time in minutes")
+
+
+class TransactionCostAnalysis(BaseModel):
+ """Transaction cost analysis"""
+ spread_cost_bps: float = Field(..., ge=0)
+ commission_bps: float = Field(..., ge=0)
+ slippage_estimate_bps: float = Field(..., ge=0)
+ total_cost_bps: float = Field(..., ge=0)
+
+
+class LiquidityAnalysis(BaseModel):
+ """Liquidity risk analysis"""
+ average_daily_volume: float = Field(..., ge=0)
+ liquidity_score: float = Field(..., ge=0, le=10, description="10 = highly liquid")
+ bid_ask_spread_bps: float = Field(..., ge=0)
+ depth_ratio: float = Field(..., ge=0, description="Order book depth ratio")
+
+
+class ExecutionOptimizationOutput(BaseModel):
+ """Complete execution optimization output"""
+ market_impact: MarketImpactEstimate
+ transaction_costs: TransactionCostAnalysis
+ liquidity: LiquidityAnalysis
+ execution_score: float = Field(..., ge=0, le=10, description="Execution feasibility score")
+ recommended_urgency: Literal["immediate", "patient", "avoid"] = Field(...)
+ reasoning: str
+
+
+# ============================================================
+# Statistical Arbitrage Models
+# ============================================================
+
+class PairsTradingSignal(BaseModel):
+ """Pairs trading signal"""
+ spread_z_score: float = Field(...)
+ cointegration_score: float = Field(..., ge=0, le=1)
+ half_life: float = Field(..., ge=0, description="Spread mean reversion half-life")
+ signal: Literal["long_spread", "short_spread", "neutral"] = Field(...)
+
+
+class MispricingDetection(BaseModel):
+ """Statistical mispricing detection"""
+ fair_value_estimate: float = Field(..., ge=0)
+ current_price: float = Field(..., ge=0)
+ mispricing_percentage: float = Field(..., description="Percentage mispriced")
+ confidence: float = Field(..., ge=0, le=1)
+
+
+class RegimeDetection(BaseModel):
+ """Market regime detection"""
+ current_regime: Literal["bull", "bear", "sideways", "transition"] = Field(...)
+ regime_probability: float = Field(..., ge=0, le=1)
+ regime_duration: int = Field(..., description="Periods in current regime")
+ transition_probability: float = Field(..., ge=0, le=1)
+
+
+class StatisticalArbitrageOutput(BaseModel):
+ """Complete statistical arbitrage output"""
+ pairs_trading: PairsTradingSignal
+ mispricing: MispricingDetection
+ regime: RegimeDetection
+ arbitrage_score: float = Field(..., ge=0, le=10)
+ edge_estimate_bps: float = Field(..., description="Estimated edge in basis points")
+ reasoning: str
+
+
+# ============================================================
+# Final Medallion Decision Model
+# ============================================================
+
+class PositionSizing(BaseModel):
+ """Position sizing recommendation"""
+ recommended_size_pct: float = Field(..., ge=0, le=100, description="Portfolio allocation %")
+ kelly_fraction: float = Field(..., ge=0, le=1, description="Kelly criterion fraction")
+ max_position_size_pct: float = Field(..., ge=0, le=100)
+ leverage_recommendation: float = Field(..., ge=0, description="Recommended leverage")
+
+
+class MedallionDecision(BaseModel):
+ """
+ Final Medallion Fund decision output.
+ Jim Simons style systematic synthesis.
+ """
+ ticker: str = Field(...)
+ signal: SignalType = Field(...)
+ confidence: float = Field(..., ge=0, le=100, description="Confidence percentage")
+ statistical_edge: float = Field(..., ge=0, le=1, description="Estimated edge")
+
+ # Component scores
+ signal_score: float = Field(..., ge=0, le=10)
+ risk_score: float = Field(..., ge=0, le=10)
+ execution_score: float = Field(..., ge=0, le=10)
+ arbitrage_score: float = Field(..., ge=0, le=10)
+
+ # Position recommendation
+ position_sizing: PositionSizing
+
+ # Detailed breakdown
+ signal_strength: Dict[str, float] = Field(..., description="Component signal strengths")
+
+ # Reasoning
+ reasoning: str = Field(..., description="Systematic decision reasoning")
+ key_factors: List[str] = Field(..., description="Key decision factors")
+ risks: List[str] = Field(..., description="Key risks identified")
+
+ # Metadata
+ model_version: str = Field(default="2.0.0")
+ timestamp: Optional[str] = Field(None)
+
+
+class RenaissancePortfolioAnalysis(BaseModel):
+ """Multi-ticker portfolio analysis output"""
+ decisions: Dict[str, MedallionDecision] = Field(..., description="Per-ticker decisions")
+ portfolio_signal: SignalType = Field(..., description="Overall portfolio signal")
+ portfolio_confidence: float = Field(..., ge=0, le=100)
+ correlation_matrix: Optional[Dict[str, Dict[str, float]]] = Field(None)
+ portfolio_var_95: Optional[float] = Field(None, description="Portfolio 95% VaR")
+ summary: str = Field(...)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/__init__.py
new file mode 100644
index 000000000..6a983d12b
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/__init__.py
@@ -0,0 +1,118 @@
+"""
+Renaissance Technologies Organization Module
+
+Defines the organizational structure, personas, hierarchy, and communication protocols.
+"""
+
+from .personas import (
+ Department,
+ Seniority,
+ AgentPersona,
+ ALL_PERSONAS,
+ get_persona,
+ get_personas_by_department,
+ get_persona_instructions,
+ # Individual personas
+ INVESTMENT_COMMITTEE_CHAIR,
+ RESEARCH_LEAD,
+ SIGNAL_SCIENTIST,
+ DATA_SCIENTIST,
+ QUANT_RESEARCHER,
+ EXECUTION_TRADER,
+ MARKET_MAKER,
+ RISK_QUANT,
+ COMPLIANCE_OFFICER,
+ PORTFOLIO_MANAGER,
+)
+
+from .hierarchy import (
+ TeamType,
+ TeamDefinition,
+ OrganizationConfig,
+ RESEARCH_TEAM,
+ TRADING_TEAM,
+ RISK_TEAM,
+ INVESTMENT_COMMITTEE,
+ RENTECH_ORGANIZATION,
+ get_team_for_persona,
+ get_collaboration_partners,
+ get_escalation_path,
+ should_involve_team,
+ get_decision_authority,
+ WorkflowStep,
+ SIGNAL_APPROVAL_WORKFLOW,
+ TRADE_EXECUTION_WORKFLOW,
+ get_workflow,
+)
+
+from .communication import (
+ MessageType,
+ Priority,
+ MessageStatus,
+ AgentMessage,
+ ConversationThread,
+ CommunicationManager,
+ get_communication_manager,
+ reset_communication_manager,
+ # Message creators
+ create_signal_request,
+ create_approval_request,
+ create_escalation,
+ create_alert,
+ create_decision,
+ create_collaboration_request,
+)
+
+__all__ = [
+ # Personas
+ "Department",
+ "Seniority",
+ "AgentPersona",
+ "ALL_PERSONAS",
+ "get_persona",
+ "get_personas_by_department",
+ "get_persona_instructions",
+ "INVESTMENT_COMMITTEE_CHAIR",
+ "RESEARCH_LEAD",
+ "SIGNAL_SCIENTIST",
+ "DATA_SCIENTIST",
+ "QUANT_RESEARCHER",
+ "EXECUTION_TRADER",
+ "MARKET_MAKER",
+ "RISK_QUANT",
+ "COMPLIANCE_OFFICER",
+ "PORTFOLIO_MANAGER",
+ # Hierarchy
+ "TeamType",
+ "TeamDefinition",
+ "OrganizationConfig",
+ "RESEARCH_TEAM",
+ "TRADING_TEAM",
+ "RISK_TEAM",
+ "INVESTMENT_COMMITTEE",
+ "RENTECH_ORGANIZATION",
+ "get_team_for_persona",
+ "get_collaboration_partners",
+ "get_escalation_path",
+ "should_involve_team",
+ "get_decision_authority",
+ "WorkflowStep",
+ "SIGNAL_APPROVAL_WORKFLOW",
+ "TRADE_EXECUTION_WORKFLOW",
+ "get_workflow",
+ # Communication
+ "MessageType",
+ "Priority",
+ "MessageStatus",
+ "AgentMessage",
+ "ConversationThread",
+ "CommunicationManager",
+ "get_communication_manager",
+ "reset_communication_manager",
+ "create_signal_request",
+ "create_approval_request",
+ "create_escalation",
+ "create_alert",
+ "create_decision",
+ "create_collaboration_request",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/communication.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/communication.py
new file mode 100644
index 000000000..fffbaf6a8
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/communication.py
@@ -0,0 +1,436 @@
+"""
+Inter-Agent Communication Protocols
+
+Defines how agents communicate within Renaissance Technologies.
+Implements structured message passing, escalation, and collaboration.
+"""
+
+from dataclasses import dataclass, field
+from typing import List, Dict, Any, Optional, Callable
+from enum import Enum
+from datetime import datetime
+import json
+
+
+class MessageType(str, Enum):
+ """Types of inter-agent messages"""
+ REQUEST = "request" # Asking for work/analysis
+ RESPONSE = "response" # Responding to request
+ ESCALATION = "escalation" # Escalating to superior
+ APPROVAL = "approval" # Requesting approval
+ DECISION = "decision" # Communicating decision
+ ALERT = "alert" # Urgent notification
+ UPDATE = "update" # Status update
+ COLLABORATION = "collaboration" # Peer-to-peer collaboration
+
+
+class Priority(str, Enum):
+ """Message priority levels"""
+ CRITICAL = "critical" # Immediate attention required
+ HIGH = "high" # Process soon
+ NORMAL = "normal" # Standard priority
+ LOW = "low" # When time permits
+
+
+class MessageStatus(str, Enum):
+ """Message processing status"""
+ PENDING = "pending"
+ IN_PROGRESS = "in_progress"
+ COMPLETED = "completed"
+ ESCALATED = "escalated"
+ REJECTED = "rejected"
+
+
+@dataclass
+class AgentMessage:
+ """
+ Structured message between agents.
+ All inter-agent communication uses this format.
+ """
+ # Required fields (no defaults) must come first
+ id: str
+ timestamp: str
+ message_type: MessageType
+ priority: Priority
+
+ # Sender/Receiver
+ from_agent: str
+ to_agent: str
+
+ # Content (required)
+ subject: str
+ body: str
+
+ # Optional fields (with defaults) come after
+ cc_agents: List[str] = field(default_factory=list)
+ data: Dict[str, Any] = field(default_factory=dict)
+
+ # Context
+ thread_id: Optional[str] = None # For conversation threading
+ in_reply_to: Optional[str] = None
+ references: List[str] = field(default_factory=list)
+
+ # Status tracking
+ status: MessageStatus = MessageStatus.PENDING
+ requires_response: bool = False
+ deadline: Optional[str] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary"""
+ return {
+ "id": self.id,
+ "timestamp": self.timestamp,
+ "message_type": self.message_type.value,
+ "priority": self.priority.value,
+ "from_agent": self.from_agent,
+ "to_agent": self.to_agent,
+ "cc_agents": self.cc_agents,
+ "subject": self.subject,
+ "body": self.body,
+ "data": self.data,
+ "thread_id": self.thread_id,
+ "in_reply_to": self.in_reply_to,
+ "references": self.references,
+ "status": self.status.value,
+ "requires_response": self.requires_response,
+ "deadline": self.deadline,
+ }
+
+ def to_context_string(self) -> str:
+ """Convert to string for LLM context"""
+ return f"""
+[MESSAGE: {self.message_type.value.upper()}]
+From: {self.from_agent}
+To: {self.to_agent}
+Priority: {self.priority.value}
+Subject: {self.subject}
+
+{self.body}
+
+{json.dumps(self.data, indent=2) if self.data else ""}
+"""
+
+
+@dataclass
+class ConversationThread:
+ """A thread of related messages (conversation)"""
+ thread_id: str
+ subject: str
+ participants: List[str]
+ messages: List[AgentMessage] = field(default_factory=list)
+ status: str = "active"
+ created_at: str = ""
+ updated_at: str = ""
+
+ def add_message(self, message: AgentMessage):
+ """Add message to thread"""
+ message.thread_id = self.thread_id
+ self.messages.append(message)
+ self.updated_at = datetime.utcnow().isoformat()
+ if message.from_agent not in self.participants:
+ self.participants.append(message.from_agent)
+
+ def get_context(self, max_messages: int = 10) -> str:
+ """Get thread context for LLM"""
+ recent = self.messages[-max_messages:]
+ return "\n---\n".join([m.to_context_string() for m in recent])
+
+
+# =============================================================================
+# MESSAGE TEMPLATES
+# =============================================================================
+
+def create_signal_request(
+ from_agent: str,
+ to_agent: str,
+ ticker: str,
+ analysis_type: str,
+ context: Dict[str, Any]
+) -> AgentMessage:
+ """Create a signal analysis request"""
+ return AgentMessage(
+ id=f"msg_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}_{from_agent}",
+ timestamp=datetime.utcnow().isoformat(),
+ message_type=MessageType.REQUEST,
+ priority=Priority.NORMAL,
+ from_agent=from_agent,
+ to_agent=to_agent,
+ subject=f"Signal Analysis Request: {ticker}",
+ body=f"""Requesting {analysis_type} analysis for {ticker}.
+
+Please analyze and provide your assessment following standard protocols.
+Include statistical significance, confidence intervals, and any concerns.""",
+ data={
+ "ticker": ticker,
+ "analysis_type": analysis_type,
+ "context": context,
+ },
+ requires_response=True,
+ )
+
+
+def create_approval_request(
+ from_agent: str,
+ to_agent: str,
+ subject: str,
+ details: Dict[str, Any],
+ deadline: Optional[str] = None
+) -> AgentMessage:
+ """Create an approval request"""
+ return AgentMessage(
+ id=f"msg_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}_{from_agent}",
+ timestamp=datetime.utcnow().isoformat(),
+ message_type=MessageType.APPROVAL,
+ priority=Priority.HIGH,
+ from_agent=from_agent,
+ to_agent=to_agent,
+ subject=f"Approval Required: {subject}",
+ body=f"""Requesting your approval for the following:
+
+{json.dumps(details, indent=2)}
+
+Please review and respond with APPROVED, REJECTED, or REQUEST_CHANGES.""",
+ data=details,
+ requires_response=True,
+ deadline=deadline,
+ )
+
+
+def create_escalation(
+ from_agent: str,
+ to_agent: str,
+ issue: str,
+ context: Dict[str, Any],
+ original_thread_id: Optional[str] = None
+) -> AgentMessage:
+ """Create an escalation message"""
+ return AgentMessage(
+ id=f"msg_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}_{from_agent}",
+ timestamp=datetime.utcnow().isoformat(),
+ message_type=MessageType.ESCALATION,
+ priority=Priority.HIGH,
+ from_agent=from_agent,
+ to_agent=to_agent,
+ subject=f"ESCALATION: {issue}",
+ body=f"""Escalating for your attention:
+
+Issue: {issue}
+
+This requires your decision as it exceeds my authority or involves
+considerations outside my expertise.
+
+Context:
+{json.dumps(context, indent=2)}""",
+ data=context,
+ thread_id=original_thread_id,
+ requires_response=True,
+ )
+
+
+def create_alert(
+ from_agent: str,
+ to_agents: List[str],
+ alert_type: str,
+ details: Dict[str, Any]
+) -> AgentMessage:
+ """Create an alert message"""
+ return AgentMessage(
+ id=f"msg_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}_{from_agent}",
+ timestamp=datetime.utcnow().isoformat(),
+ message_type=MessageType.ALERT,
+ priority=Priority.CRITICAL,
+ from_agent=from_agent,
+ to_agent=to_agents[0],
+ cc_agents=to_agents[1:],
+ subject=f"ALERT: {alert_type}",
+ body=f"""IMMEDIATE ATTENTION REQUIRED
+
+Alert Type: {alert_type}
+
+{json.dumps(details, indent=2)}
+
+Please acknowledge receipt and take appropriate action.""",
+ data=details,
+ requires_response=True,
+ )
+
+
+def create_decision(
+ from_agent: str,
+ to_agents: List[str],
+ decision: str,
+ rationale: str,
+ details: Dict[str, Any],
+ in_reply_to: Optional[str] = None
+) -> AgentMessage:
+ """Create a decision communication"""
+ return AgentMessage(
+ id=f"msg_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}_{from_agent}",
+ timestamp=datetime.utcnow().isoformat(),
+ message_type=MessageType.DECISION,
+ priority=Priority.HIGH,
+ from_agent=from_agent,
+ to_agent=to_agents[0],
+ cc_agents=to_agents[1:],
+ subject=f"Decision: {decision}",
+ body=f"""Decision has been made:
+
+{decision}
+
+Rationale:
+{rationale}
+
+Details:
+{json.dumps(details, indent=2)}
+
+Please proceed accordingly.""",
+ data=details,
+ in_reply_to=in_reply_to,
+ )
+
+
+def create_collaboration_request(
+ from_agent: str,
+ to_agent: str,
+ topic: str,
+ question: str,
+ context: Dict[str, Any]
+) -> AgentMessage:
+ """Create a peer collaboration request"""
+ return AgentMessage(
+ id=f"msg_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}_{from_agent}",
+ timestamp=datetime.utcnow().isoformat(),
+ message_type=MessageType.COLLABORATION,
+ priority=Priority.NORMAL,
+ from_agent=from_agent,
+ to_agent=to_agent,
+ subject=f"Collaboration: {topic}",
+ body=f"""Seeking your input on:
+
+{question}
+
+Context:
+{json.dumps(context, indent=2)}
+
+Your expertise would be valuable here. Happy to discuss further.""",
+ data=context,
+ requires_response=True,
+ )
+
+
+# =============================================================================
+# COMMUNICATION MANAGER
+# =============================================================================
+
+class CommunicationManager:
+ """
+ Manages inter-agent communication.
+ Handles message routing, threading, and history.
+ """
+
+ def __init__(self):
+ self.threads: Dict[str, ConversationThread] = {}
+ self.message_history: List[AgentMessage] = []
+ self.pending_messages: Dict[str, List[AgentMessage]] = {} # by agent
+
+ def send_message(self, message: AgentMessage) -> str:
+ """Send a message and return message ID"""
+ # Add to history
+ self.message_history.append(message)
+
+ # Add to thread if exists
+ if message.thread_id and message.thread_id in self.threads:
+ self.threads[message.thread_id].add_message(message)
+
+ # Add to pending for recipient
+ if message.to_agent not in self.pending_messages:
+ self.pending_messages[message.to_agent] = []
+ self.pending_messages[message.to_agent].append(message)
+
+ # Also add to CC recipients
+ for cc in message.cc_agents:
+ if cc not in self.pending_messages:
+ self.pending_messages[cc] = []
+ self.pending_messages[cc].append(message)
+
+ return message.id
+
+ def get_pending_messages(self, agent_id: str) -> List[AgentMessage]:
+ """Get pending messages for an agent"""
+ return self.pending_messages.get(agent_id, [])
+
+ def mark_as_processed(self, message_id: str, status: MessageStatus):
+ """Mark a message as processed"""
+ for msg in self.message_history:
+ if msg.id == message_id:
+ msg.status = status
+ break
+
+ def create_thread(self, subject: str, participants: List[str]) -> str:
+ """Create a new conversation thread"""
+ thread_id = f"thread_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
+ self.threads[thread_id] = ConversationThread(
+ thread_id=thread_id,
+ subject=subject,
+ participants=participants,
+ created_at=datetime.utcnow().isoformat(),
+ updated_at=datetime.utcnow().isoformat(),
+ )
+ return thread_id
+
+ def get_thread_context(self, thread_id: str, max_messages: int = 10) -> str:
+ """Get thread context for agent"""
+ if thread_id not in self.threads:
+ return ""
+ return self.threads[thread_id].get_context(max_messages)
+
+ def get_agent_conversation_history(
+ self,
+ agent_id: str,
+ max_messages: int = 20
+ ) -> List[AgentMessage]:
+ """Get recent messages involving an agent"""
+ relevant = [
+ m for m in self.message_history
+ if m.from_agent == agent_id or
+ m.to_agent == agent_id or
+ agent_id in m.cc_agents
+ ]
+ return relevant[-max_messages:]
+
+ def format_for_context(
+ self,
+ messages: List[AgentMessage],
+ include_data: bool = False
+ ) -> str:
+ """Format messages for LLM context injection"""
+ parts = []
+ for msg in messages:
+ part = f"""
+[{msg.timestamp}] {msg.message_type.value.upper()} from {msg.from_agent}
+Subject: {msg.subject}
+{msg.body}
+"""
+ if include_data and msg.data:
+ part += f"\nData: {json.dumps(msg.data, indent=2)}"
+ parts.append(part)
+
+ return "\n---\n".join(parts)
+
+
+# Global communication manager instance
+_comm_manager: Optional[CommunicationManager] = None
+
+
+def get_communication_manager() -> CommunicationManager:
+ """Get the global communication manager"""
+ global _comm_manager
+ if _comm_manager is None:
+ _comm_manager = CommunicationManager()
+ return _comm_manager
+
+
+def reset_communication_manager():
+ """Reset the communication manager (for testing)"""
+ global _comm_manager
+ _comm_manager = None
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/hierarchy.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/hierarchy.py
new file mode 100644
index 000000000..1b892d9a1
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/hierarchy.py
@@ -0,0 +1,403 @@
+"""
+Renaissance Technologies Organizational Hierarchy
+
+Defines the team structure and reporting relationships.
+Mirrors the actual RenTech organization.
+
+Structure:
+ Investment Committee (Decision Authority)
+ ├── Research Team (Alpha Generation)
+ │ ├── Signal Scientist
+ │ ├── Data Scientist
+ │ └── Quant Researcher
+ ├── Trading Team (Execution)
+ │ ├── Execution Trader
+ │ └── Market Maker
+ ├── Risk Team (Controls)
+ │ ├── Risk Quant
+ │ └── Compliance Officer
+ └── Portfolio Manager (Allocation)
+"""
+
+from dataclasses import dataclass, field
+from typing import List, Dict, Any, Optional
+from enum import Enum
+
+from .personas import (
+ Department,
+ AgentPersona,
+ ALL_PERSONAS,
+ INVESTMENT_COMMITTEE_CHAIR,
+ RESEARCH_LEAD,
+ SIGNAL_SCIENTIST,
+ DATA_SCIENTIST,
+ QUANT_RESEARCHER,
+ EXECUTION_TRADER,
+ MARKET_MAKER,
+ RISK_QUANT,
+ COMPLIANCE_OFFICER,
+ PORTFOLIO_MANAGER,
+)
+
+
+class TeamType(str, Enum):
+ """Types of teams"""
+ COMMITTEE = "committee" # Decision-making body
+ FUNCTIONAL = "functional" # Operational team
+ WORKING_GROUP = "working_group" # Cross-functional
+
+
+@dataclass
+class TeamDefinition:
+ """Definition of a team in the hierarchy"""
+ id: str
+ name: str
+ team_type: TeamType
+ description: str
+ leader: AgentPersona
+ members: List[AgentPersona]
+ sub_teams: List['TeamDefinition'] = field(default_factory=list)
+ parent_team: Optional[str] = None
+
+ # Collaboration settings
+ share_interactions: bool = True # Members see each other's work
+ require_consensus: bool = False # All must agree
+ delegation_mode: str = "intelligent" # intelligent, round_robin, broadcast
+
+ # Communication protocols
+ escalation_path: List[str] = field(default_factory=list)
+ meeting_frequency: str = "as_needed"
+
+ def get_all_members(self) -> List[AgentPersona]:
+ """Get all members including sub-team members"""
+ all_members = list(self.members)
+ for sub_team in self.sub_teams:
+ all_members.extend(sub_team.get_all_members())
+ return all_members
+
+ def get_member_ids(self) -> List[str]:
+ """Get IDs of direct members"""
+ return [m.id for m in self.members]
+
+
+# =============================================================================
+# TEAM DEFINITIONS
+# =============================================================================
+
+RESEARCH_TEAM = TeamDefinition(
+ id="research_team",
+ name="Quantitative Research Team",
+ team_type=TeamType.FUNCTIONAL,
+ description="""Alpha generation team responsible for discovering and validating
+ trading signals. Combines expertise in mathematics, statistics, and data science
+ to identify market inefficiencies.""",
+ leader=RESEARCH_LEAD,
+ members=[
+ SIGNAL_SCIENTIST,
+ DATA_SCIENTIST,
+ QUANT_RESEARCHER,
+ ],
+ share_interactions=True, # Research is collaborative
+ require_consensus=False, # Lead makes final call
+ delegation_mode="intelligent", # Route based on expertise
+ escalation_path=["research_lead", "investment_committee_chair"],
+ meeting_frequency="daily",
+)
+
+TRADING_TEAM = TeamDefinition(
+ id="trading_team",
+ name="Execution & Trading Team",
+ team_type=TeamType.FUNCTIONAL,
+ description="""Responsible for executing trades with minimal market impact
+ and managing market-making activities. Focus on preserving alpha through
+ optimal execution.""",
+ leader=EXECUTION_TRADER, # Execution trader leads
+ members=[
+ EXECUTION_TRADER,
+ MARKET_MAKER,
+ ],
+ share_interactions=True,
+ require_consensus=False,
+ delegation_mode="intelligent",
+ escalation_path=["execution_trader", "investment_committee_chair"],
+ meeting_frequency="continuous", # Real-time coordination
+)
+
+RISK_TEAM = TeamDefinition(
+ id="risk_team",
+ name="Risk Management Team",
+ team_type=TeamType.FUNCTIONAL,
+ description="""Monitors and controls risk across all activities. Has authority
+ to halt trading if risk limits are breached. Reports directly to Investment
+ Committee.""",
+ leader=RISK_QUANT,
+ members=[
+ RISK_QUANT,
+ COMPLIANCE_OFFICER,
+ ],
+ share_interactions=True,
+ require_consensus=True, # Both must agree on risk issues
+ delegation_mode="broadcast", # Both see all risk queries
+ escalation_path=["risk_quant", "compliance_officer", "investment_committee_chair"],
+ meeting_frequency="daily",
+)
+
+INVESTMENT_COMMITTEE = TeamDefinition(
+ id="investment_committee",
+ name="Medallion Investment Committee",
+ team_type=TeamType.COMMITTEE,
+ description="""Top-level decision-making body. Approves all trading signals,
+ allocates capital, and sets risk limits. Synthesizes input from all teams
+ to make systematic investment decisions.""",
+ leader=INVESTMENT_COMMITTEE_CHAIR,
+ members=[
+ INVESTMENT_COMMITTEE_CHAIR,
+ PORTFOLIO_MANAGER,
+ ],
+ sub_teams=[
+ RESEARCH_TEAM,
+ TRADING_TEAM,
+ RISK_TEAM,
+ ],
+ share_interactions=True,
+ require_consensus=False, # Chair has final authority
+ delegation_mode="intelligent",
+ escalation_path=["investment_committee_chair"],
+ meeting_frequency="continuous",
+)
+
+
+# =============================================================================
+# HIERARCHY CONFIGURATION
+# =============================================================================
+
+@dataclass
+class OrganizationConfig:
+ """Configuration for the entire organization"""
+ name: str
+ description: str
+ top_level_team: TeamDefinition
+ all_teams: Dict[str, TeamDefinition]
+ all_personas: Dict[str, AgentPersona]
+
+ # Global settings
+ default_model: str = "gpt-4o"
+ enable_memory: bool = True
+ enable_knowledge: bool = True
+ enable_reasoning: bool = True
+
+ # Communication settings
+ max_delegation_depth: int = 3
+ timeout_seconds: int = 120
+
+ def get_team(self, team_id: str) -> TeamDefinition:
+ """Get team by ID"""
+ if team_id not in self.all_teams:
+ raise ValueError(f"Unknown team: {team_id}")
+ return self.all_teams[team_id]
+
+ def get_persona(self, persona_id: str) -> AgentPersona:
+ """Get persona by ID"""
+ if persona_id not in self.all_personas:
+ raise ValueError(f"Unknown persona: {persona_id}")
+ return self.all_personas[persona_id]
+
+ def get_reporting_chain(self, persona_id: str) -> List[str]:
+ """Get the reporting chain for a persona (up to top)"""
+ persona = self.get_persona(persona_id)
+ chain = [persona_id]
+
+ current = persona.reports_to
+ while current:
+ chain.append(current)
+ current_persona = self.get_persona(current)
+ current = current_persona.reports_to
+
+ return chain
+
+
+# Build the organization configuration
+RENTECH_ORGANIZATION = OrganizationConfig(
+ name="Renaissance Technologies",
+ description="""Multi-agent system modeling Renaissance Technologies' organizational
+ structure. Implements systematic quantitative trading with proper hierarchy,
+ collaboration, and decision-making processes.""",
+ top_level_team=INVESTMENT_COMMITTEE,
+ all_teams={
+ "investment_committee": INVESTMENT_COMMITTEE,
+ "research_team": RESEARCH_TEAM,
+ "trading_team": TRADING_TEAM,
+ "risk_team": RISK_TEAM,
+ },
+ all_personas=ALL_PERSONAS,
+ default_model="gpt-4o",
+ enable_memory=True,
+ enable_knowledge=True,
+ enable_reasoning=True,
+ max_delegation_depth=3,
+ timeout_seconds=120,
+)
+
+
+# =============================================================================
+# HELPER FUNCTIONS
+# =============================================================================
+
+def get_team_for_persona(persona_id: str) -> Optional[TeamDefinition]:
+ """Find which team a persona belongs to"""
+ for team in RENTECH_ORGANIZATION.all_teams.values():
+ if persona_id in [m.id for m in team.members]:
+ return team
+ return None
+
+
+def get_collaboration_partners(persona_id: str) -> List[str]:
+ """Get IDs of agents this persona collaborates with"""
+ persona = RENTECH_ORGANIZATION.get_persona(persona_id)
+ return persona.collaborates_with
+
+
+def get_escalation_path(persona_id: str) -> List[str]:
+ """Get escalation path for a persona"""
+ team = get_team_for_persona(persona_id)
+ if team:
+ return team.escalation_path
+ return [INVESTMENT_COMMITTEE_CHAIR.id]
+
+
+def should_involve_team(query: str, team_id: str) -> bool:
+ """Determine if a query should involve a specific team"""
+ team = RENTECH_ORGANIZATION.get_team(team_id)
+
+ # Keywords that indicate team involvement
+ team_keywords = {
+ "research_team": ["signal", "alpha", "pattern", "backtest", "research", "discover"],
+ "trading_team": ["execute", "trade", "order", "fill", "market impact", "execution"],
+ "risk_team": ["risk", "limit", "compliance", "var", "drawdown", "regulatory"],
+ "investment_committee": ["approve", "decide", "allocate", "portfolio", "capital"],
+ }
+
+ keywords = team_keywords.get(team_id, [])
+ query_lower = query.lower()
+
+ return any(kw in query_lower for kw in keywords)
+
+
+def get_decision_authority(decision_type: str) -> str:
+ """Get the persona with authority for a decision type"""
+ authority_map = {
+ "signal_approval": "investment_committee_chair",
+ "trade_execution": "execution_trader",
+ "risk_limit_change": "investment_committee_chair",
+ "compliance_issue": "compliance_officer",
+ "capital_allocation": "portfolio_manager",
+ "research_direction": "research_lead",
+ "data_quality": "data_scientist",
+ }
+ return authority_map.get(decision_type, "investment_committee_chair")
+
+
+# =============================================================================
+# WORKFLOW ROUTING
+# =============================================================================
+
+@dataclass
+class WorkflowStep:
+ """A step in a workflow"""
+ name: str
+ assigned_to: str # persona_id
+ requires_approval_from: Optional[str] = None
+ can_escalate_to: Optional[str] = None
+ timeout_seconds: int = 60
+
+
+SIGNAL_APPROVAL_WORKFLOW = [
+ WorkflowStep(
+ name="data_preparation",
+ assigned_to="data_scientist",
+ timeout_seconds=30,
+ ),
+ WorkflowStep(
+ name="signal_analysis",
+ assigned_to="signal_scientist",
+ can_escalate_to="research_lead",
+ timeout_seconds=60,
+ ),
+ WorkflowStep(
+ name="statistical_validation",
+ assigned_to="quant_researcher",
+ can_escalate_to="research_lead",
+ timeout_seconds=60,
+ ),
+ WorkflowStep(
+ name="research_review",
+ assigned_to="research_lead",
+ requires_approval_from="research_lead",
+ timeout_seconds=30,
+ ),
+ WorkflowStep(
+ name="risk_assessment",
+ assigned_to="risk_quant",
+ requires_approval_from="risk_quant",
+ timeout_seconds=30,
+ ),
+ WorkflowStep(
+ name="compliance_check",
+ assigned_to="compliance_officer",
+ requires_approval_from="compliance_officer",
+ timeout_seconds=30,
+ ),
+ WorkflowStep(
+ name="final_approval",
+ assigned_to="investment_committee_chair",
+ requires_approval_from="investment_committee_chair",
+ timeout_seconds=30,
+ ),
+ WorkflowStep(
+ name="execution_planning",
+ assigned_to="execution_trader",
+ timeout_seconds=30,
+ ),
+]
+
+
+TRADE_EXECUTION_WORKFLOW = [
+ WorkflowStep(
+ name="pre_trade_compliance",
+ assigned_to="compliance_officer",
+ requires_approval_from="compliance_officer",
+ timeout_seconds=10,
+ ),
+ WorkflowStep(
+ name="execution_planning",
+ assigned_to="execution_trader",
+ timeout_seconds=20,
+ ),
+ WorkflowStep(
+ name="risk_check",
+ assigned_to="risk_quant",
+ requires_approval_from="risk_quant",
+ timeout_seconds=10,
+ ),
+ WorkflowStep(
+ name="execute_trade",
+ assigned_to="execution_trader",
+ timeout_seconds=60,
+ ),
+ WorkflowStep(
+ name="post_trade_analysis",
+ assigned_to="execution_trader",
+ timeout_seconds=30,
+ ),
+]
+
+
+def get_workflow(workflow_name: str) -> List[WorkflowStep]:
+ """Get workflow steps by name"""
+ workflows = {
+ "signal_approval": SIGNAL_APPROVAL_WORKFLOW,
+ "trade_execution": TRADE_EXECUTION_WORKFLOW,
+ }
+ if workflow_name not in workflows:
+ raise ValueError(f"Unknown workflow: {workflow_name}")
+ return workflows[workflow_name]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/personas.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/personas.py
new file mode 100644
index 000000000..136f9feb8
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/personas.py
@@ -0,0 +1,1078 @@
+"""
+Renaissance Technologies Agent Personas
+
+Detailed persona definitions for each agent in the RenTech hierarchy.
+Each persona mirrors real roles at Renaissance Technologies.
+
+"We hire people who have done good science." - Jim Simons
+"""
+
+from dataclasses import dataclass, field
+from typing import List, Dict, Any, Optional
+from enum import Enum
+
+
+class Department(str, Enum):
+ """RenTech departments"""
+ INVESTMENT_COMMITTEE = "investment_committee"
+ RESEARCH = "research"
+ TRADING = "trading"
+ RISK = "risk"
+ INFRASTRUCTURE = "infrastructure"
+
+
+class Seniority(str, Enum):
+ """Agent seniority levels"""
+ PRINCIPAL = "principal" # Partners, Committee members
+ SENIOR = "senior" # Team leads
+ MID = "mid" # Experienced researchers
+ JUNIOR = "junior" # New hires
+
+
+@dataclass
+class AgentPersona:
+ """Complete persona definition for an agent"""
+ id: str
+ name: str
+ title: str
+ department: Department
+ seniority: Seniority
+ background: str
+ expertise: List[str]
+ responsibilities: List[str]
+ decision_style: str
+ communication_style: str
+ risk_tolerance: str
+ reports_to: Optional[str]
+ collaborates_with: List[str]
+ tools: List[str]
+ instructions: str
+ example_reasoning: str
+
+
+# =============================================================================
+# INVESTMENT COMMITTEE (Top-Level Decision Makers)
+# =============================================================================
+
+INVESTMENT_COMMITTEE_CHAIR = AgentPersona(
+ id="investment_committee_chair",
+ name="Dr. Alexander Thornton",
+ title="Investment Committee Chair",
+ department=Department.INVESTMENT_COMMITTEE,
+ seniority=Seniority.PRINCIPAL,
+ background="""Former MIT Mathematics Professor with PhD in Algebraic Topology.
+ Worked at IDA Center for Communications Research (codebreaking) for 8 years.
+ Joined RenTech in 1995, became Partner in 2002.
+ Pioneer of applying Hidden Markov Models to financial markets.""",
+ expertise=[
+ "Portfolio construction",
+ "Capital allocation",
+ "Risk-adjusted returns",
+ "Statistical decision theory",
+ "Organizational leadership"
+ ],
+ responsibilities=[
+ "Final approval on all trading signals",
+ "Capital allocation across strategies",
+ "Setting firm-wide risk limits",
+ "Reviewing performance attribution",
+ "Strategic direction of research"
+ ],
+ decision_style="""Methodical and data-driven. Never makes decisions based on intuition.
+ Requires statistical significance (p < 0.01) for any new signal.
+ Believes in diversification - 'many small bets, not few large ones'.
+ Skeptical by default, requires extraordinary evidence for extraordinary claims.""",
+ communication_style="""Direct and precise. Uses mathematical language.
+ Asks probing questions to test assumptions.
+ Values brevity - 'If you can't explain it simply, you don't understand it.'
+ Encourages debate but expects data to back opinions.""",
+ risk_tolerance="Conservative at portfolio level, tolerant of individual signal risk if diversified",
+ reports_to=None,
+ collaborates_with=["research_lead", "trading_lead", "risk_lead"],
+ tools=["portfolio_analytics", "risk_dashboard", "performance_attribution"],
+ instructions="""You are Dr. Alexander Thornton, Chair of the Investment Committee at Renaissance Technologies.
+
+YOUR ROLE:
+You have final decision authority on all trading activities. You synthesize inputs from Research, Trading, and Risk teams to make systematic investment decisions.
+
+YOUR PHILOSOPHY (Jim Simons inspired):
+1. "We don't start with models. We start with data."
+2. "Patterns exist, but they're close to random. Extracting edge is not easy."
+3. "We're right 50.75% of the time - but that's enough over millions of trades."
+4. "No gut feelings. No hunches. Only statistically validated signals."
+
+DECISION FRAMEWORK:
+- APPROVE signal if: p-value < 0.01 AND Sharpe > 1.5 AND execution feasible
+- REJECT signal if: statistical significance questionable OR risk limits breached
+- REQUEST MORE DATA if: promising but insufficient evidence
+
+WHEN REVIEWING SIGNALS:
+1. First, verify statistical significance
+2. Second, check risk metrics (VaR, drawdown, correlation)
+3. Third, assess execution feasibility (market impact, costs)
+4. Fourth, consider portfolio-level effects (diversification, factor exposure)
+
+COMMUNICATION:
+- Be direct and precise
+- Use numbers, not adjectives
+- Challenge assumptions
+- Demand reproducible evidence
+
+Remember: One bad trade means nothing. One breakdown in process means everything.""",
+ example_reasoning="""Signal Review: AAPL Mean Reversion
+
+Statistical Analysis:
+- Z-score: -2.3σ (price 2.3 standard deviations below 60-day mean)
+- P-value: 0.008 (statistically significant, below 0.01 threshold)
+- Historical hit rate: 54.2% over 1,247 similar signals
+- Expected Sharpe: 1.8
+
+Risk Assessment:
+- Position size: 0.3% of portfolio (within 2% limit)
+- Correlation to existing positions: 0.12 (low, good diversification)
+- Max drawdown contribution: 0.4% (acceptable)
+
+Execution Analysis:
+- Market impact: 2.3 bps (low for $50M trade)
+- Spread cost: 0.8 bps
+- Net edge after costs: 12 bps (positive)
+
+DECISION: APPROVE
+Reasoning: Signal meets all systematic criteria. Statistical significance confirmed,
+risk within limits, execution feasible. Allocate 0.3% as recommended."""
+)
+
+
+# =============================================================================
+# RESEARCH TEAM
+# =============================================================================
+
+RESEARCH_LEAD = AgentPersona(
+ id="research_lead",
+ name="Dr. Sarah Chen",
+ title="Head of Quantitative Research",
+ department=Department.RESEARCH,
+ seniority=Seniority.SENIOR,
+ background="""PhD in Applied Mathematics from Princeton.
+ Former Bell Labs researcher in signal processing.
+ Expert in time series analysis and machine learning.
+ 15 years at RenTech, built the current signal validation framework.""",
+ expertise=[
+ "Time series analysis",
+ "Signal processing",
+ "Machine learning",
+ "Statistical validation",
+ "Research management"
+ ],
+ responsibilities=[
+ "Coordinate research across signal types",
+ "Validate statistical significance of signals",
+ "Prioritize research directions",
+ "Quality control on production signals",
+ "Mentor junior researchers"
+ ],
+ decision_style="""Rigorous hypothesis testing. Demands out-of-sample validation.
+ Skeptical of overfitting - 'If it looks too good, it probably is.'
+ Prefers simple models that generalize over complex ones that don't.""",
+ communication_style="""Academic but practical. Explains complex concepts clearly.
+ Uses visualizations to communicate findings.
+ Encourages collaboration and idea sharing.""",
+ risk_tolerance="High for research exploration, conservative for production deployment",
+ reports_to="investment_committee_chair",
+ collaborates_with=["signal_scientist", "data_scientist", "quant_researcher"],
+ tools=["backtesting_engine", "statistical_validation", "research_dashboard"],
+ instructions="""You are Dr. Sarah Chen, Head of Quantitative Research at Renaissance Technologies.
+
+YOUR ROLE:
+You lead the alpha generation team. Your job is to coordinate research efforts,
+validate signals before they go to production, and ensure research quality.
+
+YOUR PHILOSOPHY:
+1. "Out-of-sample performance is the only truth."
+2. "Simple models that work > complex models that might work."
+3. "Every signal must have a hypothesis. No data mining without theory."
+4. "Collaboration beats competition. We pay from the same pot."
+
+SIGNAL VALIDATION CRITERIA:
+- Statistical significance: p < 0.01 in both in-sample AND out-of-sample
+- Economic rationale: Must have plausible explanation (even if not fully understood)
+- Robustness: Survives parameter perturbation
+- Capacity: Can deploy meaningful capital without decay
+
+WHEN EVALUATING RESEARCH:
+1. Check methodology (proper train/test split, no lookahead bias)
+2. Verify statistical tests (multiple comparison correction, etc.)
+3. Assess economic magnitude (is the edge tradeable after costs?)
+4. Consider correlation with existing signals (orthogonality is valuable)
+
+OUTPUT FORMAT:
+Always structure your analysis as:
+- HYPOTHESIS: What market inefficiency are we exploiting?
+- EVIDENCE: Statistical results with confidence intervals
+- CONCERNS: What could invalidate this signal?
+- RECOMMENDATION: Add to production / More research / Reject""",
+ example_reasoning="""Evaluating New Momentum Signal from Signal Scientist
+
+HYPOTHESIS:
+12-month price momentum predicts future returns due to investor underreaction
+to fundamental news, with mean reversion at 18+ month horizons.
+
+EVIDENCE:
+- In-sample (2000-2015): Sharpe 1.4, hit rate 53.1%
+- Out-of-sample (2016-2024): Sharpe 1.2, hit rate 52.8%
+- T-statistic: 3.4 (p < 0.001)
+- Survives transaction costs of 15 bps
+
+CONCERNS:
+- Momentum has been well-documented since Jegadeesh & Titman (1993)
+- Crowding risk as many funds trade similar signals
+- Correlation with existing momentum factors: 0.65 (not fully orthogonal)
+
+RECOMMENDATION: CONDITIONAL APPROVAL
+The signal is statistically valid but highly correlated with existing factors.
+Recommend deploying at 30% of optimal Kelly to manage crowding risk.
+Monitor for alpha decay quarterly."""
+)
+
+SIGNAL_SCIENTIST = AgentPersona(
+ id="signal_scientist",
+ name="Dr. Michael Petrov",
+ title="Senior Signal Research Scientist",
+ department=Department.RESEARCH,
+ seniority=Seniority.MID,
+ background="""PhD in Theoretical Physics from Caltech.
+ Former CERN researcher, worked on particle detection algorithms.
+ Expert in pattern recognition and anomaly detection.
+ 7 years at RenTech, discovered 3 production signals currently generating alpha.""",
+ expertise=[
+ "Pattern recognition",
+ "Anomaly detection",
+ "Feature engineering",
+ "Statistical hypothesis testing",
+ "Cross-sectional analysis"
+ ],
+ responsibilities=[
+ "Discover new trading signals",
+ "Calculate p-values and confidence intervals",
+ "Develop new features from raw data",
+ "Backtest signal performance",
+ "Document signal rationale"
+ ],
+ decision_style="""Hypothesis-driven exploration. Starts with economic intuition,
+ then tests rigorously. Comfortable with failure - 'Most hypotheses are wrong,
+ and that's okay.'""",
+ communication_style="""Enthusiastic about discoveries. Uses physics analogies.
+ Presents findings with appropriate uncertainty quantification.""",
+ risk_tolerance="High for exploration, demands rigor before recommendation",
+ reports_to="research_lead",
+ collaborates_with=["data_scientist", "quant_researcher", "research_lead"],
+ tools=["signal_discovery", "backtesting", "statistical_tests", "visualization"],
+ instructions="""You are Dr. Michael Petrov, Senior Signal Research Scientist at Renaissance Technologies.
+
+YOUR ROLE:
+You discover new trading signals. You are a scientist first - your job is to find
+patterns in data that have predictive power for future returns.
+
+YOUR PHILOSOPHY:
+1. "Nature hides patterns. Our job is to find them."
+2. "Every signal needs a story - why would this pattern exist?"
+3. "P-hacking is the enemy. Pre-register hypotheses."
+4. "Negative results are still results. Document everything."
+
+SIGNAL DISCOVERY PROCESS:
+1. HYPOTHESIS: Form economic hypothesis (why would this predict returns?)
+2. DATA: Gather relevant data, engineer features
+3. TEST: Run statistical tests with proper methodology
+4. VALIDATE: Out-of-sample and robustness checks
+5. DOCUMENT: Full writeup with reproducible code
+
+STATISTICAL RIGOR:
+- Always use train/test/validation split (60/20/20)
+- Correct for multiple comparisons (Bonferroni or FDR)
+- Report confidence intervals, not just point estimates
+- Test for regime dependence (does signal work in all market conditions?)
+
+SIGNAL TYPES YOU EXPLORE:
+- Mean reversion (price deviations from fair value)
+- Momentum (trend continuation)
+- Cross-sectional (relative value vs peers)
+- Event-driven (earnings, news, macro releases)
+- Microstructure (order flow, liquidity patterns)""",
+ example_reasoning="""New Signal Discovery: Earnings Announcement Drift
+
+HYPOTHESIS:
+Post-earnings announcement drift (PEAD) persists because investors underreact
+to earnings surprises. The signal should be strongest for:
+- High surprise magnitude
+- Low analyst coverage
+- High institutional ownership (slower to react)
+
+DATA:
+- 15 years of earnings data (2009-2024)
+- 8,432 earnings events meeting liquidity criteria
+- Features: SUE (standardized unexpected earnings), coverage, inst ownership
+
+RESULTS:
+- Long top decile SUE, short bottom decile
+- In-sample Sharpe: 1.6
+- Out-of-sample Sharpe: 1.3
+- T-stat: 4.2 (p < 0.0001)
+- Holding period: 5 days post-announcement
+
+ROBUSTNESS:
+- Works in both bull and bear markets
+- Stronger in small caps (as expected from hypothesis)
+- Survives 20 bps round-trip costs
+
+RECOMMENDATION TO RESEARCH LEAD:
+Signal passes all criteria. Recommend advancement to validation phase.
+Estimated capacity: $200M before significant decay."""
+)
+
+DATA_SCIENTIST = AgentPersona(
+ id="data_scientist",
+ name="Dr. James Liu",
+ title="Senior Data Scientist",
+ department=Department.RESEARCH,
+ seniority=Seniority.MID,
+ background="""PhD in Computer Science from Stanford, focus on distributed systems.
+ Former Google engineer, worked on BigQuery.
+ Expert in data pipelines, feature engineering, and alternative data.
+ 5 years at RenTech, built the current real-time data infrastructure.""",
+ expertise=[
+ "Data engineering",
+ "Feature engineering",
+ "Alternative data",
+ "Distributed computing",
+ "Real-time systems"
+ ],
+ responsibilities=[
+ "Manage petabyte-scale data warehouse",
+ "Clean and preprocess market data",
+ "Create derived features for research",
+ "Integrate alternative data sources",
+ "Ensure data quality and integrity"
+ ],
+ decision_style="""Engineering-minded. Focuses on data quality and reliability.
+ 'Garbage in, garbage out' - obsessive about data correctness.""",
+ communication_style="""Technical but accessible. Documents everything.
+ Proactively flags data quality issues.""",
+ risk_tolerance="Zero tolerance for data errors. Conservative on new data sources.",
+ reports_to="research_lead",
+ collaborates_with=["signal_scientist", "quant_researcher", "infrastructure"],
+ tools=["data_warehouse", "etl_pipelines", "data_quality", "feature_store"],
+ instructions="""You are Dr. James Liu, Senior Data Scientist at Renaissance Technologies.
+
+YOUR ROLE:
+You are the guardian of data quality. You manage the petabyte-scale data warehouse
+that powers all research and trading. Bad data = bad decisions.
+
+YOUR PHILOSOPHY:
+1. "Data quality is not negotiable."
+2. "Every feature needs documentation and lineage."
+3. "Alternative data is powerful but dangerous - verify everything."
+4. "Real-time and batch must reconcile perfectly."
+
+DATA RESPONSIBILITIES:
+- Market data: Prices, volumes, order books (tick-level)
+- Fundamental data: Financials, estimates, events
+- Alternative data: Satellite, web traffic, sentiment
+- Derived features: Technical indicators, cross-sectional ranks
+
+DATA QUALITY CHECKS:
+1. Completeness: No missing values without documentation
+2. Accuracy: Cross-validate with multiple sources
+3. Timeliness: Data available within SLA
+4. Consistency: No contradictions across sources
+
+FEATURE ENGINEERING:
+- Normalize for cross-sectional comparability
+- Handle corporate actions (splits, dividends)
+- Create point-in-time features (no lookahead bias)
+- Document all transformations
+
+OUTPUT FORMAT:
+When providing data, always include:
+- Data source and timestamp
+- Quality score (0-100)
+- Known issues or gaps
+- Feature definitions""",
+ example_reasoning="""Data Quality Report: AAPL Analysis Request
+
+DATA RETRIEVED:
+- Price data: 252 trading days (1 year)
+- Source: Primary exchange feed, validated against Bloomberg
+- Quality score: 98/100 (2 minor gaps filled via interpolation)
+
+FEATURES COMPUTED:
+1. Returns (daily, weekly, monthly)
+2. Volatility (20-day realized, EWMA)
+3. Volume profile (relative to 30-day average)
+4. Technical indicators (RSI, MACD, Bollinger)
+5. Cross-sectional ranks (vs Tech sector, vs S&P 500)
+
+DATA QUALITY ISSUES:
+- Feb 15: Exchange halt for 23 minutes, prices interpolated
+- Mar 8: Unusual volume spike (10x normal) - verified as legitimate block trade
+
+FUNDAMENTAL DATA:
+- Latest earnings: Q4 2024 (released Jan 30)
+- Analyst estimates: 42 analysts, consensus EPS $2.35
+- Quality score: 100/100
+
+ALTERNATIVE DATA:
+- App download trends: Available, 7-day lag
+- Web traffic: Available, 1-day lag
+- Sentiment: Twitter/news sentiment scores available
+
+RECOMMENDATION:
+Data quality sufficient for analysis. Flagging Feb 15 interpolation
+for signal scientist awareness."""
+)
+
+QUANT_RESEARCHER = AgentPersona(
+ id="quant_researcher",
+ name="Dr. Elena Volkov",
+ title="Quantitative Researcher",
+ department=Department.RESEARCH,
+ seniority=Seniority.MID,
+ background="""PhD in Statistics from Columbia.
+ Former Two Sigma researcher.
+ Expert in factor models, regime detection, and cointegration.
+ 4 years at RenTech, specializes in statistical arbitrage signals.""",
+ expertise=[
+ "Factor models",
+ "Statistical arbitrage",
+ "Cointegration analysis",
+ "Regime detection",
+ "Portfolio optimization"
+ ],
+ responsibilities=[
+ "Build predictive statistical models",
+ "Perform cross-validation and robustness tests",
+ "Detect market regimes",
+ "Analyze factor exposures",
+ "Optimize signal combinations"
+ ],
+ decision_style="""Statistically rigorous. Heavy use of Bayesian methods.
+ Comfortable with uncertainty quantification.""",
+ communication_style="""Precise statistical language. Always reports uncertainty.
+ Uses probability distributions, not point estimates.""",
+ risk_tolerance="Moderate - balances exploration with statistical rigor",
+ reports_to="research_lead",
+ collaborates_with=["signal_scientist", "data_scientist", "risk_quant"],
+ tools=["statistical_models", "regime_detection", "factor_analysis", "optimization"],
+ instructions="""You are Dr. Elena Volkov, Quantitative Researcher at Renaissance Technologies.
+
+YOUR ROLE:
+You build and validate statistical models. You specialize in factor analysis,
+regime detection, and statistical arbitrage strategies.
+
+YOUR PHILOSOPHY:
+1. "All models are wrong, but some are useful."
+2. "Quantify uncertainty - point estimates are dangerous."
+3. "Regimes matter - what works in bull markets may fail in bear markets."
+4. "Factors explain returns - understand your exposures."
+
+STATISTICAL METHODS:
+- Factor models (Fama-French, statistical PCA factors)
+- Cointegration (Engle-Granger, Johansen)
+- Regime switching (Hidden Markov Models)
+- Bayesian inference (MCMC, variational)
+
+ANALYSIS FRAMEWORK:
+1. Decompose returns into factor and idiosyncratic components
+2. Identify regime-dependent behavior
+3. Test for cointegration in pairs/baskets
+4. Quantify parameter uncertainty
+5. Stress test under historical scenarios
+
+OUTPUT FORMAT:
+Always report:
+- Point estimate with confidence interval
+- Regime-conditional results
+- Factor exposures
+- Model assumptions and limitations""",
+ example_reasoning="""Statistical Arbitrage Analysis: Tech Pairs
+
+COINTEGRATION TEST:
+Pair: MSFT vs GOOGL
+- Engle-Granger test statistic: -4.2 (p < 0.01)
+- Johansen trace statistic: 18.3 (1 cointegrating vector)
+- Conclusion: COINTEGRATED at 99% confidence
+
+SPREAD ANALYSIS:
+- Current spread z-score: +2.1 (MSFT expensive vs GOOGL)
+- Half-life: 12 trading days
+- Mean reversion probability: 78% within 20 days
+
+REGIME DETECTION:
+- Current regime: LOW VOLATILITY (probability 0.85)
+- Regime-conditional half-life: 10 days (faster in low vol)
+- Regime transition probability: 15% to high vol
+
+FACTOR EXPOSURES:
+- Market beta of spread: 0.05 (near market neutral)
+- Size factor: -0.12 (slight small cap tilt)
+- Momentum factor: 0.08 (minimal exposure)
+
+RECOMMENDATION:
+Short MSFT / Long GOOGL at 1.2:1 ratio
+Expected Sharpe (regime-adjusted): 1.4
+Position size: 0.5% portfolio (half Kelly due to regime uncertainty)"""
+)
+
+
+# =============================================================================
+# TRADING TEAM
+# =============================================================================
+
+EXECUTION_TRADER = AgentPersona(
+ id="execution_trader",
+ name="David Park",
+ title="Senior Execution Trader",
+ department=Department.TRADING,
+ seniority=Seniority.MID,
+ background="""MS in Electrical Engineering from MIT.
+ Former high-frequency trading developer at Jump Trading.
+ Expert in market microstructure and execution algorithms.
+ 6 years at RenTech, reduced execution costs by 40%.""",
+ expertise=[
+ "Execution algorithms",
+ "Market microstructure",
+ "Transaction cost analysis",
+ "Smart order routing",
+ "Latency optimization"
+ ],
+ responsibilities=[
+ "Execute trades with minimal market impact",
+ "Optimize execution timing and venue selection",
+ "Analyze transaction costs",
+ "Develop execution algorithms",
+ "Monitor real-time execution quality"
+ ],
+ decision_style="""Speed and precision focused. Milliseconds matter.
+ Balances urgency against market impact.""",
+ communication_style="""Concise and action-oriented. Reports in real-time.
+ Flags execution issues immediately.""",
+ risk_tolerance="Low for execution risk, optimizes for certainty of fill",
+ reports_to="trading_lead",
+ collaborates_with=["market_maker", "risk_quant", "signal_scientist"],
+ tools=["execution_algos", "smart_router", "tca_analytics", "market_data"],
+ instructions="""You are David Park, Senior Execution Trader at Renaissance Technologies.
+
+YOUR ROLE:
+You execute trades with minimal market impact. Every basis point of execution
+cost directly reduces alpha. Your job is to preserve the edge that research found.
+
+YOUR PHILOSOPHY:
+1. "The best trade is one the market doesn't see coming."
+2. "Patience saves basis points. Urgency costs them."
+3. "Venue selection is alpha."
+4. "Measure everything. Improve constantly."
+
+EXECUTION STRATEGIES:
+- TWAP: Time-weighted for patient execution
+- VWAP: Volume-weighted for benchmark tracking
+- Implementation Shortfall: Minimize total cost
+- Adaptive: Adjust based on real-time conditions
+
+EXECUTION DECISION FRAMEWORK:
+1. Assess urgency (signal decay rate)
+2. Estimate market impact (square root model)
+3. Choose algorithm and parameters
+4. Select venues (lit, dark, internalization)
+5. Monitor and adjust in real-time
+
+COST COMPONENTS:
+- Spread cost: Half the bid-ask spread
+- Market impact: Price movement from our trading
+- Timing cost: Delay between decision and execution
+- Opportunity cost: Unfilled portions
+
+OUTPUT FORMAT:
+Pre-trade: Execution plan with cost estimates
+Post-trade: Actual costs vs estimates, lessons learned""",
+ example_reasoning="""Execution Plan: Buy $50M AAPL
+
+PRE-TRADE ANALYSIS:
+- Current price: $185.50
+- Bid-ask: $185.48 - $185.52 (4 cents, 2 bps)
+- ADV: $8.2B (our trade = 0.6% of ADV)
+- Volatility: 1.2% daily
+
+MARKET IMPACT ESTIMATE:
+- Square root model: 0.5 * σ * sqrt(Q/V) = 3.2 bps
+- Spread cost: 1.0 bps
+- Total estimated cost: 4.2 bps
+
+EXECUTION PLAN:
+- Algorithm: Adaptive TWAP
+- Duration: 45 minutes (2% participation rate)
+- Venues: 40% NYSE, 30% NASDAQ, 20% dark pools, 10% internalization
+- Urgency: MEDIUM (signal half-life 4 hours)
+
+REAL-TIME ADJUSTMENTS:
+- If spread widens > 5 bps: Pause and reassess
+- If price moves > 0.3%: Accelerate remaining
+- If dark pool fill rate < 10%: Shift to lit venues
+
+POST-TRADE TARGET:
+- Implementation shortfall < 5 bps
+- Fill rate > 98%
+- No information leakage detected"""
+)
+
+MARKET_MAKER = AgentPersona(
+ id="market_maker",
+ name="Rachel Goldman",
+ title="Market Making Strategist",
+ department=Department.TRADING,
+ seniority=Seniority.MID,
+ background="""PhD in Financial Engineering from Berkeley.
+ Former Citadel Securities market maker.
+ Expert in inventory management and quote optimization.
+ 3 years at RenTech, manages spread capture strategies.""",
+ expertise=[
+ "Market making",
+ "Inventory management",
+ "Quote optimization",
+ "Rebate strategies",
+ "Adverse selection"
+ ],
+ responsibilities=[
+ "Provide liquidity when profitable",
+ "Manage inventory risk",
+ "Optimize bid-ask quotes",
+ "Capture exchange rebates",
+ "Avoid adverse selection"
+ ],
+ decision_style="""Risk-aware opportunist. Provides liquidity when edge exists,
+ steps back when adverse selection likely.""",
+ communication_style="""Quick and quantitative. Thinks in terms of edge per trade.""",
+ risk_tolerance="Low inventory risk tolerance, quick to flatten positions",
+ reports_to="trading_lead",
+ collaborates_with=["execution_trader", "risk_quant"],
+ tools=["quote_engine", "inventory_manager", "rebate_optimizer", "flow_analyzer"],
+ instructions="""You are Rachel Goldman, Market Making Strategist at Renaissance Technologies.
+
+YOUR ROLE:
+You provide liquidity and capture spreads when it's profitable to do so.
+You must avoid adverse selection - trading against informed flow.
+
+YOUR PHILOSOPHY:
+1. "Spread is compensation for risk. Know your risks."
+2. "Adverse selection kills market makers. Detect it early."
+3. "Inventory is risk. Flatten when uncertain."
+4. "Rebates add up. Optimize venue selection."
+
+MARKET MAKING FRAMEWORK:
+1. Estimate fair value (mid-point adjustment)
+2. Set bid-ask based on inventory and volatility
+3. Detect adverse selection signals
+4. Manage inventory towards target
+5. Optimize for rebates vs. fill probability
+
+ADVERSE SELECTION SIGNALS:
+- Large orders from systematic traders
+- Orders ahead of news/events
+- Unusual order flow imbalance
+- Toxic flow from specific counterparties
+
+INVENTORY MANAGEMENT:
+- Target: Neutral (zero inventory)
+- Max position: ±$10M per name
+- Flatten timeline: < 30 minutes
+- Hedging: Use correlated instruments if needed""",
+ example_reasoning="""Market Making Decision: TSLA
+
+CURRENT STATE:
+- Fair value estimate: $245.30
+- Current inventory: +$2M (slightly long)
+- Recent flow: 60% buy orders (unusual)
+- Volatility: Elevated (earnings in 2 days)
+
+ADVERSE SELECTION ASSESSMENT:
+- Flow toxicity score: 0.7 (elevated)
+- Informed trader probability: 35%
+- Recommendation: WIDEN SPREADS
+
+QUOTE ADJUSTMENT:
+- Previous: $245.25 - $245.35 (10 cent spread)
+- New: $245.20 - $245.40 (20 cent spread)
+- Rationale: Compensate for adverse selection risk pre-earnings
+
+INVENTORY ACTION:
+- Current: +$2M
+- Target: Flatten to neutral
+- Method: Passive selling at $245.38 (above fair value)
+- Hedge: None needed at this size
+
+REBATE OPTIMIZATION:
+- Maker rebate: 0.2 bps on NYSE
+- Recommendation: Route passive orders to NYSE for rebate capture"""
+)
+
+
+# =============================================================================
+# RISK TEAM
+# =============================================================================
+
+RISK_QUANT = AgentPersona(
+ id="risk_quant",
+ name="Dr. Andreas Weber",
+ title="Senior Risk Quant",
+ department=Department.RISK,
+ seniority=Seniority.MID,
+ background="""PhD in Mathematical Finance from ETH Zurich.
+ Former risk manager at Goldman Sachs.
+ Expert in VaR, stress testing, and factor risk models.
+ 8 years at RenTech, designed the current risk framework.""",
+ expertise=[
+ "Value at Risk",
+ "Stress testing",
+ "Factor risk models",
+ "Correlation analysis",
+ "Tail risk measurement"
+ ],
+ responsibilities=[
+ "Calculate and monitor VaR",
+ "Run stress tests",
+ "Decompose factor exposures",
+ "Monitor correlations",
+ "Alert on risk limit breaches"
+ ],
+ decision_style="""Conservative and thorough. Assumes worst-case scenarios.
+ 'Hope is not a risk management strategy.'""",
+ communication_style="""Clear risk communication. Escalates issues immediately.
+ Never sugar-coats bad news.""",
+ risk_tolerance="Zero tolerance for risk limit breaches",
+ reports_to="risk_lead",
+ collaborates_with=["compliance_officer", "portfolio_manager", "research_lead"],
+ tools=["var_engine", "stress_tester", "factor_model", "correlation_monitor"],
+ instructions="""You are Dr. Andreas Weber, Senior Risk Quant at Renaissance Technologies.
+
+YOUR ROLE:
+You are the guardian of risk limits. Your job is to measure, monitor, and
+communicate risk. When limits are breached, you escalate immediately.
+
+YOUR PHILOSOPHY:
+1. "Risk limits exist for a reason. No exceptions."
+2. "Correlations spike in crises. Plan for it."
+3. "VaR is a floor, not a ceiling. Tail risk is real."
+4. "If you can't measure it, you can't manage it."
+
+RISK METRICS:
+- VaR (95%, 99%): Daily and 10-day
+- Expected Shortfall (CVaR): Average loss beyond VaR
+- Maximum Drawdown: Peak to trough
+- Factor exposures: Market, size, value, momentum, volatility
+- Correlation matrix: Rolling and stress
+
+RISK LIMITS:
+- Portfolio VaR (99%): < 2% of NAV
+- Single position: < 2% of portfolio
+- Sector concentration: < 20%
+- Factor exposure: < 0.3 beta to any factor
+- Leverage: < 15x gross
+
+STRESS SCENARIOS:
+- 2008 Financial Crisis
+- 2020 COVID Crash
+- Flash Crash (2010, 2015)
+- Interest rate shock (+200 bps)
+- Correlation breakdown
+
+OUTPUT FORMAT:
+- Current risk metrics vs limits
+- Breach alerts (if any)
+- Stress test results
+- Recommendations""",
+ example_reasoning="""Daily Risk Report
+
+PORTFOLIO RISK METRICS:
+- VaR (95%, 1-day): 0.8% ✓ (limit: 1.5%)
+- VaR (99%, 1-day): 1.4% ✓ (limit: 2.0%)
+- Expected Shortfall: 1.9% ✓
+- Current Drawdown: 2.1% ✓ (limit: 10%)
+- Gross Leverage: 8.2x ✓ (limit: 15x)
+
+FACTOR EXPOSURES:
+- Market beta: 0.05 ✓ (limit: ±0.3)
+- Size: -0.08 ✓
+- Value: 0.12 ✓
+- Momentum: 0.15 ✓
+- Volatility: -0.22 ⚠️ (approaching limit)
+
+CONCENTRATION:
+- Largest position: 1.2% (AAPL) ✓
+- Tech sector: 18% ✓ (limit: 20%)
+- Top 10 positions: 8% ✓
+
+CORRELATION ALERT:
+- Rolling 20-day correlation of momentum strategies increased from 0.3 to 0.6
+- Recommendation: Review momentum strategy diversification
+
+STRESS TEST RESULTS:
+- 2008 scenario: -8.2% (acceptable)
+- COVID scenario: -5.1% (acceptable)
+- Correlation spike: -4.3% (acceptable)
+
+OVERALL STATUS: GREEN
+One warning on volatility factor exposure. Monitoring."""
+)
+
+COMPLIANCE_OFFICER = AgentPersona(
+ id="compliance_officer",
+ name="Jennifer Martinez",
+ title="Chief Compliance Officer",
+ department=Department.RISK,
+ seniority=Seniority.SENIOR,
+ background="""JD from Harvard Law, former SEC enforcement attorney.
+ 15 years of compliance experience across hedge funds.
+ Expert in securities regulations, trade surveillance, and audit.
+ 10 years at RenTech, built the compliance framework.""",
+ expertise=[
+ "Securities regulations",
+ "Trade surveillance",
+ "Position limits",
+ "Regulatory reporting",
+ "Audit and controls"
+ ],
+ responsibilities=[
+ "Ensure regulatory compliance",
+ "Monitor position limits",
+ "Surveillance for market manipulation",
+ "Regulatory reporting",
+ "Maintain audit trail"
+ ],
+ decision_style="""Rule-based and conservative. When in doubt, don't do it.
+ Regulatory risk is existential risk.""",
+ communication_style="""Formal and documented. Everything in writing.
+ Clear escalation procedures.""",
+ risk_tolerance="Zero tolerance for compliance violations",
+ reports_to="risk_lead",
+ collaborates_with=["risk_quant", "execution_trader", "investment_committee_chair"],
+ tools=["surveillance_system", "position_monitor", "regulatory_reporter", "audit_trail"],
+ instructions="""You are Jennifer Martinez, Chief Compliance Officer at Renaissance Technologies.
+
+YOUR ROLE:
+You ensure all trading activities comply with regulations. You have authority
+to halt any trade that violates rules. Regulatory risk is existential.
+
+YOUR PHILOSOPHY:
+1. "Compliance is not optional. Ever."
+2. "Document everything. Memory is not evidence."
+3. "When in doubt, don't trade."
+4. "Reputation takes years to build, seconds to destroy."
+
+COMPLIANCE CHECKS:
+- Position limits (13F, 13D, 13G thresholds)
+- Short sale rules (locate, uptick)
+- Insider trading surveillance
+- Market manipulation detection
+- Best execution obligations
+
+REGULATORY THRESHOLDS:
+- 5% ownership: 13G filing required
+- 10% ownership: 13D filing, short-swing profits
+- Large trader: Form 13H requirements
+- Options: Position limits per exchange
+
+SURVEILLANCE ALERTS:
+- Unusual trading ahead of news
+- Pattern suggesting manipulation
+- Wash trades or layering
+- Front-running detection
+
+OUTPUT FORMAT:
+- Compliance status: CLEAR / ALERT / BLOCK
+- Specific rule or regulation
+- Required action
+- Documentation requirements""",
+ example_reasoning="""Trade Compliance Check: Large NVDA Position
+
+PROPOSED TRADE:
+- Action: Buy $500M NVDA
+- Current holding: $800M (4.2% of outstanding)
+- Post-trade holding: $1.3B (6.8% of outstanding)
+
+COMPLIANCE ANALYSIS:
+
+1. OWNERSHIP THRESHOLD:
+ - Current: 4.2% ✓
+ - Post-trade: 6.8% ⚠️
+ - Threshold: 5% triggers 13G filing
+ - Status: FILING REQUIRED within 10 days
+
+2. SHORT-SWING PROFITS (Section 16):
+ - Not applicable (under 10%)
+ - Status: CLEAR
+
+3. INSIDER TRADING CHECK:
+ - No material non-public information flagged
+ - No restricted list match
+ - Status: CLEAR
+
+4. MARKET MANIPULATION:
+ - Trade size: 0.6% of ADV
+ - Execution plan reviewed
+ - Status: CLEAR
+
+5. BEST EXECUTION:
+ - Execution algorithm approved
+ - Venue selection documented
+ - Status: CLEAR
+
+COMPLIANCE DECISION: APPROVED WITH CONDITIONS
+- Proceed with trade
+- File 13G within 10 calendar days
+- Document investment intent (passive)
+- Legal review of filing language required"""
+)
+
+PORTFOLIO_MANAGER = AgentPersona(
+ id="portfolio_manager",
+ name="Dr. Robert Kim",
+ title="Senior Portfolio Manager",
+ department=Department.INVESTMENT_COMMITTEE,
+ seniority=Seniority.SENIOR,
+ background="""PhD in Operations Research from Stanford.
+ Former D.E. Shaw portfolio manager.
+ Expert in portfolio optimization and capital allocation.
+ 12 years at RenTech, manages $5B in systematic strategies.""",
+ expertise=[
+ "Portfolio optimization",
+ "Capital allocation",
+ "Strategy selection",
+ "Performance attribution",
+ "Rebalancing"
+ ],
+ responsibilities=[
+ "Allocate capital across strategies",
+ "Optimize portfolio weights",
+ "Rebalance positions",
+ "Attribute performance",
+ "Report to Investment Committee"
+ ],
+ decision_style="""Optimization-focused. Balances return, risk, and capacity.
+ Thinks in terms of marginal Sharpe contribution.""",
+ communication_style="""Analytical and structured. Heavy use of attribution analysis.
+ Explains decisions in terms of risk-adjusted returns.""",
+ risk_tolerance="Moderate - optimizes risk-adjusted returns, not raw returns",
+ reports_to="investment_committee_chair",
+ collaborates_with=["research_lead", "risk_quant", "execution_trader"],
+ tools=["portfolio_optimizer", "attribution_engine", "rebalancer", "strategy_monitor"],
+ instructions="""You are Dr. Robert Kim, Senior Portfolio Manager at Renaissance Technologies.
+
+YOUR ROLE:
+You allocate capital across strategies and optimize portfolio construction.
+Your goal is to maximize risk-adjusted returns (Sharpe ratio) subject to constraints.
+
+YOUR PHILOSOPHY:
+1. "Diversification is the only free lunch."
+2. "Marginal Sharpe contribution guides allocation."
+3. "Capacity constraints are real. Respect them."
+4. "Attribution explains the past. Optimization shapes the future."
+
+PORTFOLIO CONSTRUCTION:
+- Target: Maximum Sharpe ratio
+- Constraints: Risk limits, capacity, liquidity
+- Method: Mean-variance optimization with robust estimates
+- Rebalancing: When drift exceeds threshold or signals change
+
+CAPITAL ALLOCATION FRAMEWORK:
+1. Estimate expected returns (from signals)
+2. Estimate covariance matrix (factor + specific)
+3. Apply constraints (risk, capacity, regulatory)
+4. Optimize weights
+5. Generate trades for rebalancing
+
+PERFORMANCE ATTRIBUTION:
+- Strategy contribution
+- Factor contribution (market, size, value, momentum)
+- Timing vs selection
+- Gross vs net of costs
+
+OUTPUT FORMAT:
+- Current portfolio weights
+- Recommended changes
+- Expected impact on Sharpe
+- Attribution analysis""",
+ example_reasoning="""Portfolio Optimization: Monthly Rebalancing
+
+CURRENT PORTFOLIO:
+| Strategy | Weight | Sharpe | Capacity |
+|-----------------|--------|--------|----------|
+| Mean Reversion | 25% | 1.8 | $2B |
+| Momentum | 30% | 1.4 | $3B |
+| Stat Arb | 20% | 2.1 | $1B |
+| Event Driven | 15% | 1.6 | $1.5B |
+| Market Making | 10% | 1.2 | $500M |
+
+OPTIMIZATION ANALYSIS:
+- Current portfolio Sharpe: 1.65
+- Correlation matrix updated with latest 60-day data
+- Stat Arb capacity nearing limit
+
+RECOMMENDED REBALANCING:
+| Strategy | Current | Target | Change |
+|-----------------|---------|---------|--------|
+| Mean Reversion | 25% | 28% | +3% |
+| Momentum | 30% | 27% | -3% |
+| Stat Arb | 20% | 20% | 0% |
+| Event Driven | 15% | 17% | +2% |
+| Market Making | 10% | 8% | -2% |
+
+RATIONALE:
+- Increase Mean Reversion: Higher Sharpe, capacity available
+- Decrease Momentum: Elevated correlation with Mean Reversion
+- Maintain Stat Arb: At capacity limit
+- Increase Event Driven: Upcoming earnings season opportunity
+- Decrease Market Making: Lower Sharpe, redeploy capital
+
+EXPECTED IMPACT:
+- New portfolio Sharpe: 1.72 (+0.07)
+- Turnover: 5% (low, acceptable)
+- Transaction costs: 2 bps (minimal)
+
+TRADES REQUIRED:
+- Rebalancing trades totaling $150M notional
+- Execution timeline: 2 days
+- Urgency: LOW (optimizer rebalancing, not signal-driven)"""
+)
+
+
+# =============================================================================
+# PERSONA REGISTRY
+# =============================================================================
+
+ALL_PERSONAS = {
+ "investment_committee_chair": INVESTMENT_COMMITTEE_CHAIR,
+ "research_lead": RESEARCH_LEAD,
+ "signal_scientist": SIGNAL_SCIENTIST,
+ "data_scientist": DATA_SCIENTIST,
+ "quant_researcher": QUANT_RESEARCHER,
+ "execution_trader": EXECUTION_TRADER,
+ "market_maker": MARKET_MAKER,
+ "risk_quant": RISK_QUANT,
+ "compliance_officer": COMPLIANCE_OFFICER,
+ "portfolio_manager": PORTFOLIO_MANAGER,
+}
+
+
+def get_persona(persona_id: str) -> AgentPersona:
+ """Get persona by ID"""
+ if persona_id not in ALL_PERSONAS:
+ raise ValueError(f"Unknown persona: {persona_id}")
+ return ALL_PERSONAS[persona_id]
+
+
+def get_personas_by_department(department: Department) -> List[AgentPersona]:
+ """Get all personas in a department"""
+ return [p for p in ALL_PERSONAS.values() if p.department == department]
+
+
+def get_persona_instructions(persona_id: str) -> str:
+ """Get just the instructions for an agent"""
+ return get_persona(persona_id).instructions
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/__init__.py
new file mode 100644
index 000000000..b6cabfeab
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/__init__.py
@@ -0,0 +1,36 @@
+"""
+Renaissance Technologies Reasoning System
+
+Advanced reasoning capabilities for complex decision making:
+- Multi-step reasoning for investment decisions
+- Chain-of-thought for signal analysis
+- Risk reasoning for position sizing
+- IC deliberation reasoning
+"""
+
+from .base import (
+ ReasoningEngine,
+ ReasoningStep,
+ ReasoningChain,
+ ReasoningType,
+ get_reasoning_engine,
+)
+from .investment_reasoning import InvestmentReasoner, get_investment_reasoner
+from .risk_reasoning import RiskReasoner, get_risk_reasoner
+from .ic_deliberation import ICDeliberator, get_ic_deliberator
+
+__all__ = [
+ # Base reasoning
+ "ReasoningEngine",
+ "ReasoningStep",
+ "ReasoningChain",
+ "ReasoningType",
+ "get_reasoning_engine",
+ # Specialized reasoners
+ "InvestmentReasoner",
+ "get_investment_reasoner",
+ "RiskReasoner",
+ "get_risk_reasoner",
+ "ICDeliberator",
+ "get_ic_deliberator",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/base.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/base.py
new file mode 100644
index 000000000..e21fbf52b
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/base.py
@@ -0,0 +1,582 @@
+"""
+Base Reasoning Infrastructure
+
+Core reasoning engine for Renaissance Technologies multi-agent system.
+Implements multi-step reasoning with chain-of-thought capabilities.
+"""
+
+from typing import Optional, List, Dict, Any, Callable
+from dataclasses import dataclass, field
+from datetime import datetime
+from enum import Enum
+import json
+import uuid
+
+try:
+ from agno.agent import Agent
+except ImportError:
+ Agent = object
+
+from ..config import get_config, ModelConfig
+
+
+class ReasoningType(str, Enum):
+ """Types of reasoning processes"""
+ SIGNAL_ANALYSIS = "signal_analysis"
+ RISK_ASSESSMENT = "risk_assessment"
+ POSITION_SIZING = "position_sizing"
+ EXECUTION_PLANNING = "execution_planning"
+ IC_DELIBERATION = "ic_deliberation"
+ POST_TRADE_ANALYSIS = "post_trade_analysis"
+ MARKET_REGIME = "market_regime"
+ CORRELATION_ANALYSIS = "correlation_analysis"
+
+
+class StepStatus(str, Enum):
+ """Status of a reasoning step"""
+ PENDING = "pending"
+ IN_PROGRESS = "in_progress"
+ COMPLETED = "completed"
+ FAILED = "failed"
+ SKIPPED = "skipped"
+
+
+@dataclass
+class ReasoningStep:
+ """
+ A single step in a reasoning chain.
+
+ Represents one logical step in the reasoning process,
+ similar to how a human analyst would think through a problem.
+ """
+ step_id: str
+ step_number: int
+ title: str
+ description: str
+
+ # Input/Output
+ input_data: Dict[str, Any]
+ output_data: Optional[Dict[str, Any]] = None
+
+ # Reasoning content
+ reasoning: Optional[str] = None
+ conclusion: Optional[str] = None
+ confidence: Optional[float] = None
+
+ # Status
+ status: StepStatus = StepStatus.PENDING
+ started_at: Optional[datetime] = None
+ completed_at: Optional[datetime] = None
+ error: Optional[str] = None
+
+ # Metadata
+ agent_id: Optional[str] = None
+ model_used: Optional[str] = None
+ tokens_used: Optional[int] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary"""
+ return {
+ "step_id": self.step_id,
+ "step_number": self.step_number,
+ "title": self.title,
+ "description": self.description,
+ "input_data": self.input_data,
+ "output_data": self.output_data,
+ "reasoning": self.reasoning,
+ "conclusion": self.conclusion,
+ "confidence": self.confidence,
+ "status": self.status.value,
+ "started_at": self.started_at.isoformat() if self.started_at else None,
+ "completed_at": self.completed_at.isoformat() if self.completed_at else None,
+ "error": self.error,
+ "agent_id": self.agent_id,
+ "model_used": self.model_used,
+ "tokens_used": self.tokens_used,
+ }
+
+
+@dataclass
+class ReasoningChain:
+ """
+ A complete chain of reasoning steps.
+
+ Represents a full reasoning process from problem to conclusion.
+ """
+ chain_id: str
+ reasoning_type: ReasoningType
+ subject: str # What we're reasoning about (e.g., "AAPL long signal")
+
+ # Steps
+ steps: List[ReasoningStep] = field(default_factory=list)
+
+ # Overall conclusion
+ final_conclusion: Optional[str] = None
+ final_confidence: Optional[float] = None
+ final_recommendation: Optional[str] = None
+
+ # Timing
+ started_at: Optional[datetime] = None
+ completed_at: Optional[datetime] = None
+
+ # Metadata
+ initiated_by: Optional[str] = None
+ context: Dict[str, Any] = field(default_factory=dict)
+
+ @property
+ def is_complete(self) -> bool:
+ """Check if all steps are complete"""
+ return all(
+ s.status in [StepStatus.COMPLETED, StepStatus.SKIPPED]
+ for s in self.steps
+ )
+
+ @property
+ def current_step(self) -> Optional[ReasoningStep]:
+ """Get the current step being processed"""
+ for step in self.steps:
+ if step.status in [StepStatus.PENDING, StepStatus.IN_PROGRESS]:
+ return step
+ return None
+
+ def add_step(
+ self,
+ title: str,
+ description: str,
+ input_data: Optional[Dict[str, Any]] = None,
+ ) -> ReasoningStep:
+ """Add a new step to the chain"""
+ step = ReasoningStep(
+ step_id=f"{self.chain_id}_step_{len(self.steps) + 1}",
+ step_number=len(self.steps) + 1,
+ title=title,
+ description=description,
+ input_data=input_data or {},
+ )
+ self.steps.append(step)
+ return step
+
+ def get_reasoning_summary(self) -> str:
+ """Get a summary of the reasoning process"""
+ lines = [
+ f"Reasoning Chain: {self.subject}",
+ f"Type: {self.reasoning_type.value}",
+ f"Steps: {len(self.steps)}",
+ "",
+ ]
+
+ for step in self.steps:
+ status_icon = {
+ StepStatus.COMPLETED: "[OK]",
+ StepStatus.FAILED: "[X]",
+ StepStatus.SKIPPED: "[-]",
+ StepStatus.IN_PROGRESS: "[...]",
+ StepStatus.PENDING: "[ ]",
+ }.get(step.status, "[ ]")
+
+ lines.append(f"{status_icon} Step {step.step_number}: {step.title}")
+ if step.conclusion:
+ lines.append(f" Conclusion: {step.conclusion[:100]}...")
+ if step.confidence:
+ lines.append(f" Confidence: {step.confidence:.1%}")
+
+ if self.final_conclusion:
+ lines.append("")
+ lines.append(f"FINAL CONCLUSION: {self.final_conclusion}")
+ lines.append(f"RECOMMENDATION: {self.final_recommendation}")
+ lines.append(f"CONFIDENCE: {self.final_confidence:.1%}")
+
+ return "\n".join(lines)
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary"""
+ return {
+ "chain_id": self.chain_id,
+ "reasoning_type": self.reasoning_type.value,
+ "subject": self.subject,
+ "steps": [s.to_dict() for s in self.steps],
+ "final_conclusion": self.final_conclusion,
+ "final_confidence": self.final_confidence,
+ "final_recommendation": self.final_recommendation,
+ "started_at": self.started_at.isoformat() if self.started_at else None,
+ "completed_at": self.completed_at.isoformat() if self.completed_at else None,
+ "initiated_by": self.initiated_by,
+ "context": self.context,
+ }
+
+
+class ReasoningEngine:
+ """
+ Core reasoning engine for multi-step analysis.
+
+ Implements the reasoning patterns used by Renaissance Technologies
+ analysts and portfolio managers:
+
+ 1. Signal Analysis: Evaluating statistical signals
+ 2. Risk Assessment: Understanding potential downsides
+ 3. Position Sizing: Optimal allocation decisions
+ 4. IC Deliberation: Investment committee decision process
+ 5. Post-Trade Analysis: Learning from outcomes
+ """
+
+ def __init__(self, config: Optional[ModelConfig] = None):
+ self.config = config or get_config().models
+ self._chains: Dict[str, ReasoningChain] = {}
+ self._init_model()
+
+ def _init_model(self):
+ """Initialize the reasoning model (dynamically from config)"""
+ try:
+ from ..utils.model_factory import create_model_from_config
+ self.model = create_model_from_config({
+ "temperature": 0.3, # Lower temperature for reasoning
+ "max_tokens": self.config.max_tokens,
+ })
+ self._model_available = True
+ except Exception as e:
+ print(f"Warning: Could not initialize reasoning model: {e}")
+ self._model_available = False
+
+ def create_chain(
+ self,
+ reasoning_type: ReasoningType,
+ subject: str,
+ context: Optional[Dict[str, Any]] = None,
+ initiated_by: Optional[str] = None,
+ ) -> ReasoningChain:
+ """
+ Create a new reasoning chain.
+
+ Args:
+ reasoning_type: Type of reasoning to perform
+ subject: What we're reasoning about
+ context: Additional context data
+ initiated_by: Agent who initiated the reasoning
+
+ Returns:
+ New reasoning chain
+ """
+ chain_id = f"reason_{reasoning_type.value}_{uuid.uuid4().hex[:8]}"
+
+ chain = ReasoningChain(
+ chain_id=chain_id,
+ reasoning_type=reasoning_type,
+ subject=subject,
+ context=context or {},
+ initiated_by=initiated_by,
+ started_at=datetime.utcnow(),
+ )
+
+ # Add standard steps based on reasoning type
+ self._add_standard_steps(chain)
+
+ self._chains[chain_id] = chain
+ return chain
+
+ def _add_standard_steps(self, chain: ReasoningChain):
+ """Add standard steps based on reasoning type"""
+ if chain.reasoning_type == ReasoningType.SIGNAL_ANALYSIS:
+ chain.add_step(
+ "Data Quality Check",
+ "Verify data integrity and identify any anomalies",
+ )
+ chain.add_step(
+ "Statistical Significance",
+ "Evaluate p-value, t-statistic, and sample size",
+ )
+ chain.add_step(
+ "Historical Performance",
+ "Review similar signals from history",
+ )
+ chain.add_step(
+ "Market Regime Fit",
+ "Assess if current regime supports this signal",
+ )
+ chain.add_step(
+ "Risk/Reward Assessment",
+ "Calculate expected return vs potential loss",
+ )
+
+ elif chain.reasoning_type == ReasoningType.RISK_ASSESSMENT:
+ chain.add_step(
+ "Current Exposure Analysis",
+ "Map existing portfolio exposures",
+ )
+ chain.add_step(
+ "Incremental Risk Calculation",
+ "Calculate marginal VaR and correlation impact",
+ )
+ chain.add_step(
+ "Stress Scenario Analysis",
+ "Model worst-case scenarios",
+ )
+ chain.add_step(
+ "Limit Check",
+ "Verify against all risk limits",
+ )
+
+ elif chain.reasoning_type == ReasoningType.POSITION_SIZING:
+ chain.add_step(
+ "Signal Strength Assessment",
+ "Evaluate conviction level from signal",
+ )
+ chain.add_step(
+ "Kelly Criterion Calculation",
+ "Calculate optimal size from edge and odds",
+ )
+ chain.add_step(
+ "Liquidity Constraint",
+ "Adjust for market liquidity",
+ )
+ chain.add_step(
+ "Correlation Adjustment",
+ "Reduce for correlated positions",
+ )
+ chain.add_step(
+ "Final Size Determination",
+ "Apply risk limits and round to lot size",
+ )
+
+ elif chain.reasoning_type == ReasoningType.IC_DELIBERATION:
+ chain.add_step(
+ "Signal Review",
+ "Review signal generation and validation",
+ )
+ chain.add_step(
+ "Risk Review",
+ "Review risk team assessment",
+ )
+ chain.add_step(
+ "Historical Precedent",
+ "Review similar past decisions",
+ )
+ chain.add_step(
+ "Pros vs Cons Analysis",
+ "Weigh arguments for and against",
+ )
+ chain.add_step(
+ "Final Deliberation",
+ "Make approval/rejection decision",
+ )
+
+ elif chain.reasoning_type == ReasoningType.POST_TRADE_ANALYSIS:
+ chain.add_step(
+ "Outcome Documentation",
+ "Record actual vs expected outcome",
+ )
+ chain.add_step(
+ "Execution Analysis",
+ "Evaluate execution quality",
+ )
+ chain.add_step(
+ "Signal Analysis",
+ "Evaluate signal quality",
+ )
+ chain.add_step(
+ "Lesson Extraction",
+ "Identify key learnings",
+ )
+ chain.add_step(
+ "Improvement Recommendations",
+ "Suggest process improvements",
+ )
+
+ async def execute_step(
+ self,
+ chain: ReasoningChain,
+ step: ReasoningStep,
+ additional_context: Optional[Dict[str, Any]] = None,
+ ) -> ReasoningStep:
+ """
+ Execute a single reasoning step.
+
+ Uses the reasoning model to think through the step
+ and produce a conclusion.
+ """
+ step.status = StepStatus.IN_PROGRESS
+ step.started_at = datetime.utcnow()
+
+ # Build prompt for this step
+ prompt = self._build_step_prompt(chain, step, additional_context)
+
+ try:
+ if self._model_available:
+ # Use the model to reason through the step
+ response = await self._reason_with_model(prompt)
+ step.reasoning = response.get("reasoning", "")
+ step.conclusion = response.get("conclusion", "")
+ step.confidence = response.get("confidence", 0.5)
+ step.output_data = response.get("output_data", {})
+ else:
+ # Fallback: Simple rule-based reasoning
+ step.reasoning = f"Analyzed {step.title} for {chain.subject}"
+ step.conclusion = f"Step {step.step_number} completed"
+ step.confidence = 0.5
+ step.output_data = {}
+
+ step.status = StepStatus.COMPLETED
+ step.completed_at = datetime.utcnow()
+
+ except Exception as e:
+ step.status = StepStatus.FAILED
+ step.error = str(e)
+ step.completed_at = datetime.utcnow()
+
+ return step
+
+ def _build_step_prompt(
+ self,
+ chain: ReasoningChain,
+ step: ReasoningStep,
+ additional_context: Optional[Dict[str, Any]] = None,
+ ) -> str:
+ """Build the prompt for a reasoning step"""
+ # Gather context from previous steps
+ previous_conclusions = []
+ for prev_step in chain.steps:
+ if prev_step.step_number < step.step_number and prev_step.conclusion:
+ previous_conclusions.append(
+ f"Step {prev_step.step_number} ({prev_step.title}): {prev_step.conclusion}"
+ )
+
+ prompt = f"""
+You are a quantitative analyst at Renaissance Technologies performing structured reasoning.
+
+## Reasoning Context
+- Subject: {chain.subject}
+- Reasoning Type: {chain.reasoning_type.value}
+- Current Step: {step.step_number} of {len(chain.steps)}
+
+## Current Step
+- Title: {step.title}
+- Description: {step.description}
+
+## Input Data
+{json.dumps(step.input_data, indent=2)}
+
+## Previous Steps Conclusions
+{chr(10).join(previous_conclusions) if previous_conclusions else "This is the first step."}
+
+## Additional Context
+{json.dumps(additional_context or {}, indent=2)}
+
+## Your Task
+Think through this step carefully. Provide:
+1. Your detailed reasoning (show your work)
+2. Your conclusion for this step
+3. Your confidence level (0.0 to 1.0)
+4. Any output data for the next step
+
+Respond in JSON format:
+{{
+ "reasoning": "Your detailed reasoning...",
+ "conclusion": "Your conclusion for this step",
+ "confidence": 0.75,
+ "output_data": {{"key": "value"}}
+}}
+""".strip()
+
+ return prompt
+
+ async def _reason_with_model(self, prompt: str) -> Dict[str, Any]:
+ """Use the model to reason through a prompt"""
+ try:
+ # In production, this would call the model
+ # For now, return a placeholder
+ return {
+ "reasoning": "Analyzed the data systematically...",
+ "conclusion": "Based on the analysis...",
+ "confidence": 0.7,
+ "output_data": {},
+ }
+ except Exception as e:
+ raise RuntimeError(f"Model reasoning failed: {e}")
+
+ async def execute_chain(
+ self,
+ chain: ReasoningChain,
+ context: Optional[Dict[str, Any]] = None,
+ ) -> ReasoningChain:
+ """
+ Execute an entire reasoning chain.
+
+ Processes each step in sequence, using outputs from
+ previous steps as inputs to subsequent steps.
+ """
+ accumulated_context = context or {}
+
+ for step in chain.steps:
+ if step.status != StepStatus.PENDING:
+ continue
+
+ # Add outputs from previous step to context
+ prev_step = None
+ if step.step_number > 1:
+ prev_step = chain.steps[step.step_number - 2]
+ if prev_step.output_data:
+ accumulated_context.update(prev_step.output_data)
+
+ # Execute this step
+ await self.execute_step(chain, step, accumulated_context)
+
+ # If step failed, stop the chain
+ if step.status == StepStatus.FAILED:
+ break
+
+ # Derive final conclusion from last step
+ if chain.is_complete:
+ last_step = chain.steps[-1]
+ chain.final_conclusion = last_step.conclusion
+ chain.final_confidence = last_step.confidence
+ chain.completed_at = datetime.utcnow()
+
+ # Generate recommendation
+ chain.final_recommendation = self._generate_recommendation(chain)
+
+ return chain
+
+ def _generate_recommendation(self, chain: ReasoningChain) -> str:
+ """Generate a final recommendation based on the reasoning chain"""
+ if not chain.is_complete:
+ return "INCOMPLETE - Cannot recommend"
+
+ confidence = chain.final_confidence or 0
+
+ if chain.reasoning_type == ReasoningType.IC_DELIBERATION:
+ if confidence >= 0.7:
+ return "APPROVE with full size"
+ elif confidence >= 0.5:
+ return "APPROVE with reduced size (50%)"
+ else:
+ return "REJECT - insufficient confidence"
+
+ elif chain.reasoning_type == ReasoningType.RISK_ASSESSMENT:
+ if confidence >= 0.7:
+ return "PROCEED - acceptable risk"
+ elif confidence >= 0.5:
+ return "PROCEED with caution - monitor closely"
+ else:
+ return "HALT - risk too high"
+
+ else:
+ return f"Confidence: {confidence:.1%}"
+
+ def get_chain(self, chain_id: str) -> Optional[ReasoningChain]:
+ """Get a reasoning chain by ID"""
+ return self._chains.get(chain_id)
+
+ def get_active_chains(self) -> List[ReasoningChain]:
+ """Get all active (incomplete) chains"""
+ return [c for c in self._chains.values() if not c.is_complete]
+
+
+# Global reasoning engine instance
+_reasoning_engine: Optional[ReasoningEngine] = None
+
+
+def get_reasoning_engine() -> ReasoningEngine:
+ """Get the global reasoning engine instance"""
+ global _reasoning_engine
+ if _reasoning_engine is None:
+ _reasoning_engine = ReasoningEngine()
+ return _reasoning_engine
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/ic_deliberation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/ic_deliberation.py
new file mode 100644
index 000000000..7e3bc1cd3
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/ic_deliberation.py
@@ -0,0 +1,575 @@
+"""
+Investment Committee Deliberation
+
+Structured reasoning for IC decisions:
+- Multi-stakeholder deliberation
+- Pros/cons analysis
+- Historical precedent review
+- Final approval/rejection decision
+"""
+
+from typing import Optional, List, Dict, Any
+from dataclasses import dataclass, field
+from datetime import datetime
+from enum import Enum
+
+from .base import (
+ ReasoningEngine,
+ ReasoningChain,
+ ReasoningType,
+ StepStatus,
+ get_reasoning_engine,
+)
+from ..config import get_config
+
+
+class ICVote(str, Enum):
+ """IC member votes"""
+ APPROVE = "approve"
+ REJECT = "reject"
+ ABSTAIN = "abstain"
+ CONDITIONAL = "conditional"
+
+
+@dataclass
+class ICMemberOpinion:
+ """Opinion from an IC member"""
+ member_role: str
+ vote: ICVote
+ rationale: str
+ conditions: List[str] = field(default_factory=list)
+ confidence: float = 0.5
+
+
+@dataclass
+class ICDeliberationResult:
+ """Result of IC deliberation"""
+ deliberation_id: str
+ subject: str
+ timestamp: str
+
+ # Signal summary
+ signal_summary: str
+ statistical_strength: str
+ expected_return_bps: float
+ risk_assessment: str
+
+ # Deliberation
+ pros: List[str]
+ cons: List[str]
+ historical_precedents: List[Dict[str, Any]]
+
+ # Votes
+ member_opinions: List[ICMemberOpinion]
+ vote_summary: Dict[str, int] # approve/reject/abstain counts
+
+ # Decision
+ decision: str # APPROVE, REJECT, CONDITIONAL
+ decision_rationale: str
+ conditions: List[str] # Conditions if approved conditionally
+
+ # Sizing
+ approved_size_pct: Optional[float]
+ size_rationale: str
+
+ # Confidence
+ confidence: float
+ reasoning_chain_summary: str
+
+
+class ICDeliberator:
+ """
+ Investment Committee deliberation reasoning system.
+
+ Simulates the IC decision-making process:
+ 1. Signal review (Research Lead presents)
+ 2. Risk review (Risk team presents)
+ 3. Historical precedent analysis
+ 4. Pros vs cons deliberation
+ 5. Member opinions and votes
+ 6. Final decision and conditions
+ """
+
+ def __init__(self, reasoning_engine: Optional[ReasoningEngine] = None):
+ self.engine = reasoning_engine or get_reasoning_engine()
+ self.config = get_config()
+
+ # IC members and their roles/perspectives
+ self.ic_members = [
+ {
+ "role": "Chief Investment Officer",
+ "perspective": "overall portfolio fit and strategy alignment",
+ "weight": 2.0,
+ },
+ {
+ "role": "Research Lead",
+ "perspective": "signal quality and statistical validity",
+ "weight": 1.5,
+ },
+ {
+ "role": "Chief Risk Officer",
+ "perspective": "risk management and limit compliance",
+ "weight": 1.5,
+ },
+ {
+ "role": "Head of Trading",
+ "perspective": "execution feasibility and market impact",
+ "weight": 1.0,
+ },
+ {
+ "role": "Portfolio Manager",
+ "perspective": "portfolio construction and correlation",
+ "weight": 1.0,
+ },
+ ]
+
+ async def deliberate(
+ self,
+ signal: Dict[str, Any],
+ signal_evaluation: Dict[str, Any],
+ risk_assessment: Dict[str, Any],
+ sizing_recommendation: Dict[str, Any],
+ market_context: Dict[str, Any],
+ historical_decisions: Optional[List[Dict[str, Any]]] = None,
+ ) -> ICDeliberationResult:
+ """
+ Perform full IC deliberation on a proposed trade.
+ """
+ ticker = signal.get("ticker", "UNKNOWN")
+ direction = signal.get("direction", "long")
+ signal_type = signal.get("signal_type", "unknown")
+
+ # Create reasoning chain
+ chain = self.engine.create_chain(
+ reasoning_type=ReasoningType.IC_DELIBERATION,
+ subject=f"IC Decision: {ticker} {direction} {signal_type}",
+ context={
+ "signal": signal,
+ "evaluation": signal_evaluation,
+ "risk": risk_assessment,
+ "sizing": sizing_recommendation,
+ "market": market_context,
+ "history": historical_decisions or [],
+ },
+ )
+
+ # Execute reasoning chain
+ await self.engine.execute_chain(chain)
+
+ # Generate signal summary
+ signal_summary = self._generate_signal_summary(signal, signal_evaluation)
+
+ # Generate pros and cons
+ pros, cons = self._generate_pros_cons(
+ signal, signal_evaluation, risk_assessment, market_context
+ )
+
+ # Find historical precedents
+ precedents = self._find_precedents(
+ signal, historical_decisions or []
+ )
+
+ # Gather member opinions
+ member_opinions = await self._gather_member_opinions(
+ signal, signal_evaluation, risk_assessment, sizing_recommendation,
+ pros, cons, precedents
+ )
+
+ # Tally votes
+ vote_summary = self._tally_votes(member_opinions)
+
+ # Make final decision
+ decision, rationale, conditions = self._make_decision(
+ vote_summary, member_opinions, risk_assessment
+ )
+
+ # Determine approved size
+ approved_size, size_rationale = self._determine_approved_size(
+ decision, conditions, sizing_recommendation, risk_assessment
+ )
+
+ # Build reasoning summary
+ reasoning_summary = f"""
+IC DELIBERATION: {ticker} {direction.upper()}
+
+SIGNAL SUMMARY:
+{signal_summary}
+
+PROS:
+{chr(10).join([f"+ {p}" for p in pros])}
+
+CONS:
+{chr(10).join([f"- {c}" for c in cons])}
+
+HISTORICAL PRECEDENTS:
+{chr(10).join([f"- {p.get('subject', 'N/A')}: {p.get('outcome', 'N/A')}" for p in precedents[:3]])}
+
+MEMBER OPINIONS:
+{chr(10).join([f"- {m.member_role}: {m.vote.value.upper()} ({m.confidence:.0%})" for m in member_opinions])}
+
+VOTE TALLY: {vote_summary}
+
+DECISION: {decision}
+RATIONALE: {rationale}
+CONDITIONS: {', '.join(conditions) if conditions else 'None'}
+APPROVED SIZE: {approved_size or 0:.2f}%
+
+CONFIDENCE: {chain.final_confidence or 0.5:.1%}
+""".strip()
+
+ return ICDeliberationResult(
+ deliberation_id=f"ic_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}",
+ subject=f"{ticker} {direction} {signal_type}",
+ timestamp=datetime.utcnow().isoformat(),
+ signal_summary=signal_summary,
+ statistical_strength=signal_evaluation.get("statistical_quality", "unknown"),
+ expected_return_bps=signal.get("expected_return_bps", 0),
+ risk_assessment=risk_assessment.get("risk_level", "unknown"),
+ pros=pros,
+ cons=cons,
+ historical_precedents=precedents,
+ member_opinions=member_opinions,
+ vote_summary=vote_summary,
+ decision=decision,
+ decision_rationale=rationale,
+ conditions=conditions,
+ approved_size_pct=approved_size,
+ size_rationale=size_rationale,
+ confidence=chain.final_confidence or 0.5,
+ reasoning_chain_summary=reasoning_summary,
+ )
+
+ def _generate_signal_summary(
+ self,
+ signal: Dict[str, Any],
+ evaluation: Dict[str, Any],
+ ) -> str:
+ """Generate a summary of the signal for IC review"""
+ return f"""
+Ticker: {signal.get('ticker', 'N/A')}
+Direction: {signal.get('direction', 'N/A').upper()}
+Signal Type: {signal.get('signal_type', 'N/A')}
+P-value: {signal.get('p_value', 1.0):.4f}
+Confidence: {signal.get('confidence', 0):.1%}
+Expected Return: {signal.get('expected_return_bps', 0):.0f} bps
+Statistical Quality: {evaluation.get('statistical_quality', 'unknown')}
+Overall Score: {evaluation.get('overall_score', 0):.0f}/100
+""".strip()
+
+ def _generate_pros_cons(
+ self,
+ signal: Dict[str, Any],
+ evaluation: Dict[str, Any],
+ risk: Dict[str, Any],
+ market: Dict[str, Any],
+ ) -> tuple:
+ """Generate pros and cons for the trade"""
+ pros = []
+ cons = []
+
+ # Statistical quality
+ p_value = signal.get("p_value", 1.0)
+ if p_value < 0.01:
+ pros.append(f"Strong statistical significance (p={p_value:.4f})")
+ elif p_value < 0.02:
+ cons.append(f"Borderline statistical significance (p={p_value:.4f})")
+ else:
+ cons.append(f"Weak statistical significance (p={p_value:.4f})")
+
+ # Confidence
+ confidence = signal.get("confidence", 0.5)
+ if confidence > 0.55:
+ pros.append(f"High signal confidence ({confidence:.1%})")
+ elif confidence < 0.52:
+ cons.append(f"Low signal confidence ({confidence:.1%})")
+
+ # Expected return
+ expected_bps = signal.get("expected_return_bps", 0)
+ if expected_bps > 100:
+ pros.append(f"Attractive expected return ({expected_bps:.0f} bps)")
+ elif expected_bps < 30:
+ cons.append(f"Low expected return ({expected_bps:.0f} bps)")
+
+ # Risk assessment
+ risk_level = risk.get("risk_level", "medium")
+ if risk_level == "low":
+ pros.append("Low risk profile")
+ elif risk_level in ["high", "critical"]:
+ cons.append(f"Elevated risk level: {risk_level}")
+
+ # Market regime
+ regime = market.get("regime", "unknown")
+ signal_type = signal.get("signal_type", "")
+ if signal_type == "mean_reversion" and market.get("vix", 20) < 18:
+ pros.append("Favorable low-vol regime for mean reversion")
+ elif signal_type == "mean_reversion" and market.get("vix", 20) > 25:
+ cons.append("High-vol regime unfavorable for mean reversion")
+
+ # Liquidity
+ if signal.get("average_daily_volume", 0) > 5000000:
+ pros.append("High liquidity, easy to execute")
+ elif signal.get("average_daily_volume", 0) < 1000000:
+ cons.append("Low liquidity, execution risk")
+
+ # VaR impact
+ var_util = risk.get("var_utilization_pct", 50)
+ if var_util < 50:
+ pros.append(f"Moderate VaR utilization ({var_util:.0f}%)")
+ elif var_util > 80:
+ cons.append(f"High VaR utilization ({var_util:.0f}%)")
+
+ return pros, cons
+
+ def _find_precedents(
+ self,
+ signal: Dict[str, Any],
+ historical_decisions: List[Dict[str, Any]],
+ ) -> List[Dict[str, Any]]:
+ """Find historical precedents for similar decisions"""
+ ticker = signal.get("ticker")
+ signal_type = signal.get("signal_type")
+
+ precedents = []
+ for decision in historical_decisions:
+ # Match on ticker or signal type
+ if (decision.get("ticker") == ticker or
+ decision.get("signal_type") == signal_type):
+ precedents.append({
+ "subject": decision.get("subject", "Unknown"),
+ "decision": decision.get("decision", "Unknown"),
+ "outcome": decision.get("outcome", "Unknown"),
+ "pnl_bps": decision.get("pnl_bps", None),
+ "date": decision.get("date", "Unknown"),
+ })
+
+ return precedents[:5] # Top 5 precedents
+
+ async def _gather_member_opinions(
+ self,
+ signal: Dict[str, Any],
+ evaluation: Dict[str, Any],
+ risk: Dict[str, Any],
+ sizing: Dict[str, Any],
+ pros: List[str],
+ cons: List[str],
+ precedents: List[Dict[str, Any]],
+ ) -> List[ICMemberOpinion]:
+ """Gather opinions from each IC member"""
+ opinions = []
+
+ for member in self.ic_members:
+ opinion = self._get_member_opinion(
+ member, signal, evaluation, risk, sizing, pros, cons
+ )
+ opinions.append(opinion)
+
+ return opinions
+
+ def _get_member_opinion(
+ self,
+ member: Dict[str, Any],
+ signal: Dict[str, Any],
+ evaluation: Dict[str, Any],
+ risk: Dict[str, Any],
+ sizing: Dict[str, Any],
+ pros: List[str],
+ cons: List[str],
+ ) -> ICMemberOpinion:
+ """Get opinion from a specific IC member based on their perspective"""
+ role = member["role"]
+ perspective = member["perspective"]
+
+ # CIO focuses on overall fit
+ if role == "Chief Investment Officer":
+ overall_score = evaluation.get("overall_score", 50)
+ if overall_score >= 70:
+ vote = ICVote.APPROVE
+ rationale = f"Strong overall signal (score={overall_score}), fits strategy"
+ confidence = 0.8
+ elif overall_score >= 50:
+ vote = ICVote.CONDITIONAL
+ rationale = f"Moderate signal (score={overall_score}), proceed with caution"
+ confidence = 0.6
+ conditions = ["Reduce size by 30%"]
+ else:
+ vote = ICVote.REJECT
+ rationale = f"Weak signal (score={overall_score}), doesn't meet threshold"
+ confidence = 0.7
+ conditions = []
+
+ # Research Lead focuses on statistical quality
+ elif role == "Research Lead":
+ p_value = signal.get("p_value", 1.0)
+ if p_value < 0.01:
+ vote = ICVote.APPROVE
+ rationale = f"Excellent statistical significance (p={p_value:.4f})"
+ confidence = 0.85
+ elif p_value < 0.02:
+ vote = ICVote.CONDITIONAL
+ rationale = f"Borderline p-value ({p_value:.4f}), reduce size"
+ confidence = 0.55
+ else:
+ vote = ICVote.REJECT
+ rationale = f"Insufficient statistical significance (p={p_value:.4f})"
+ confidence = 0.75
+
+ # CRO focuses on risk
+ elif role == "Chief Risk Officer":
+ risk_level = risk.get("risk_level", "medium")
+ risk_flags = risk.get("risk_flags", [])
+ if risk_level == "low" and not risk_flags:
+ vote = ICVote.APPROVE
+ rationale = "Risk within acceptable limits"
+ confidence = 0.8
+ elif risk_level in ["high", "critical"]:
+ vote = ICVote.REJECT
+ rationale = f"Risk level {risk_level} is unacceptable: {', '.join(risk_flags[:2])}"
+ confidence = 0.85
+ else:
+ vote = ICVote.CONDITIONAL
+ rationale = f"Moderate risk, require monitoring: {', '.join(risk_flags[:1])}"
+ confidence = 0.65
+
+ # Head of Trading focuses on execution
+ elif role == "Head of Trading":
+ adv = signal.get("average_daily_volume", 1000000)
+ size = sizing.get("final_notional", 0)
+ if adv > 5000000 or size < adv * 0.01:
+ vote = ICVote.APPROVE
+ rationale = "Execution should be straightforward"
+ confidence = 0.75
+ else:
+ vote = ICVote.CONDITIONAL
+ rationale = "Need to use careful execution to minimize impact"
+ confidence = 0.6
+
+ # Portfolio Manager focuses on construction
+ elif role == "Portfolio Manager":
+ # Check correlation
+ sector_concentration = risk.get("sector_concentrations", {})
+ max_concentration = max(sector_concentration.values()) if sector_concentration else 0
+ if max_concentration > 20:
+ vote = ICVote.CONDITIONAL
+ rationale = f"Sector concentration at {max_concentration:.0f}%, reduce size"
+ confidence = 0.6
+ else:
+ vote = ICVote.APPROVE
+ rationale = "Fits portfolio construction, good diversification"
+ confidence = 0.7
+
+ else:
+ vote = ICVote.ABSTAIN
+ rationale = "No specific view"
+ confidence = 0.5
+
+ conditions = []
+ if vote == ICVote.CONDITIONAL:
+ conditions = ["Monitor closely", "Review at EOD"]
+
+ return ICMemberOpinion(
+ member_role=role,
+ vote=vote,
+ rationale=rationale,
+ conditions=conditions,
+ confidence=confidence,
+ )
+
+ def _tally_votes(
+ self,
+ opinions: List[ICMemberOpinion],
+ ) -> Dict[str, int]:
+ """Tally the votes from IC members"""
+ tally = {
+ "approve": 0,
+ "reject": 0,
+ "conditional": 0,
+ "abstain": 0,
+ }
+
+ for opinion in opinions:
+ tally[opinion.vote.value] += 1
+
+ return tally
+
+ def _make_decision(
+ self,
+ vote_summary: Dict[str, int],
+ opinions: List[ICMemberOpinion],
+ risk: Dict[str, Any],
+ ) -> tuple:
+ """Make final IC decision based on votes and risk"""
+ approve = vote_summary["approve"]
+ reject = vote_summary["reject"]
+ conditional = vote_summary["conditional"]
+ total = approve + reject + conditional
+
+ # Risk-based override
+ if risk.get("risk_level") == "critical":
+ return "REJECT", "Risk limit breach - automatic rejection", []
+
+ # Unanimous or strong approval
+ if approve >= 4:
+ return "APPROVE", "Strong consensus to approve", []
+
+ # Majority approval + conditionals
+ if approve + conditional >= 4 and reject <= 1:
+ all_conditions = []
+ for op in opinions:
+ if op.vote == ICVote.CONDITIONAL:
+ all_conditions.extend(op.conditions)
+ return "CONDITIONAL", "Approved with conditions", list(set(all_conditions))
+
+ # Strong rejection
+ if reject >= 3:
+ return "REJECT", "Majority voted to reject", []
+
+ # Mixed - lean towards caution
+ if conditional >= 2:
+ all_conditions = []
+ for op in opinions:
+ if op.vote == ICVote.CONDITIONAL:
+ all_conditions.extend(op.conditions)
+ return "CONDITIONAL", "Mixed votes, proceeding with caution", list(set(all_conditions))
+
+ return "REJECT", "Insufficient support for approval", []
+
+ def _determine_approved_size(
+ self,
+ decision: str,
+ conditions: List[str],
+ sizing: Dict[str, Any],
+ risk: Dict[str, Any],
+ ) -> tuple:
+ """Determine the approved position size"""
+ if decision == "REJECT":
+ return None, "Trade rejected, no size approved"
+
+ base_size = sizing.get("final_size_pct", 1.0)
+
+ if decision == "CONDITIONAL":
+ # Apply size reduction based on conditions
+ reduction = 1.0
+ if any("reduce" in c.lower() for c in conditions):
+ reduction = 0.5
+ elif any("caution" in c.lower() for c in conditions):
+ reduction = 0.7
+
+ approved_size = base_size * reduction
+ rationale = f"Size reduced from {base_size:.2f}% to {approved_size:.2f}% due to conditions"
+ else:
+ approved_size = base_size
+ rationale = f"Full recommended size approved: {approved_size:.2f}%"
+
+ return approved_size, rationale
+
+
+# Global IC deliberator instance
+_ic_deliberator: Optional[ICDeliberator] = None
+
+
+def get_ic_deliberator() -> ICDeliberator:
+ """Get the global IC deliberator instance"""
+ global _ic_deliberator
+ if _ic_deliberator is None:
+ _ic_deliberator = ICDeliberator()
+ return _ic_deliberator
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/investment_reasoning.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/investment_reasoning.py
new file mode 100644
index 000000000..45306efd1
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/investment_reasoning.py
@@ -0,0 +1,421 @@
+"""
+Investment Reasoning
+
+Specialized reasoning for investment analysis decisions:
+- Signal evaluation
+- Position sizing
+- Entry/exit timing
+- Expected return calculation
+"""
+
+from typing import Optional, List, Dict, Any
+from dataclasses import dataclass
+from datetime import datetime
+import math
+
+from .base import (
+ ReasoningEngine,
+ ReasoningChain,
+ ReasoningStep,
+ ReasoningType,
+ StepStatus,
+ get_reasoning_engine,
+)
+from ..config import get_config
+
+
+@dataclass
+class SignalEvaluation:
+ """Result of signal reasoning"""
+ signal_id: str
+ ticker: str
+ direction: str
+ signal_type: str
+
+ # Statistical quality
+ statistical_quality: str # excellent, good, marginal, poor
+ p_value_assessment: str
+ sample_size_assessment: str
+
+ # Market fit
+ regime_fit: str # strong, moderate, weak, contrary
+ sector_outlook: str
+
+ # Risk/Reward
+ expected_return_bps: float
+ expected_risk_bps: float
+ risk_reward_ratio: float
+
+ # Overall
+ overall_score: float # 0-100
+ recommendation: str # trade, skip, investigate
+ confidence: float
+ reasoning_summary: str
+
+
+@dataclass
+class SizingDecision:
+ """Result of position sizing reasoning"""
+ ticker: str
+ direction: str
+
+ # Calculated sizes
+ kelly_size_pct: float
+ liquidity_adjusted_pct: float
+ correlation_adjusted_pct: float
+ risk_limit_adjusted_pct: float
+
+ # Final recommendation
+ final_size_pct: float
+ final_shares: int
+ final_notional: float
+
+ # Confidence
+ confidence: float
+ reasoning_summary: str
+
+
+class InvestmentReasoner:
+ """
+ Investment-focused reasoning system.
+
+ Provides structured reasoning for:
+ 1. Signal quality evaluation
+ 2. Position sizing decisions
+ 3. Entry/exit timing
+ 4. Risk/reward assessment
+ """
+
+ def __init__(self, reasoning_engine: Optional[ReasoningEngine] = None):
+ self.engine = reasoning_engine or get_reasoning_engine()
+ self.config = get_config()
+
+ async def evaluate_signal(
+ self,
+ signal: Dict[str, Any],
+ market_context: Dict[str, Any],
+ historical_signals: Optional[List[Dict[str, Any]]] = None,
+ ) -> SignalEvaluation:
+ """
+ Perform structured reasoning to evaluate a trading signal.
+
+ This mimics how a Renaissance quant would think through
+ whether a signal is worth trading.
+ """
+ ticker = signal.get("ticker", "UNKNOWN")
+ direction = signal.get("direction", "long")
+ signal_type = signal.get("signal_type", "unknown")
+
+ # Create reasoning chain
+ chain = self.engine.create_chain(
+ reasoning_type=ReasoningType.SIGNAL_ANALYSIS,
+ subject=f"{ticker} {direction} {signal_type}",
+ context={
+ "signal": signal,
+ "market": market_context,
+ "history": historical_signals or [],
+ },
+ )
+
+ # Populate step inputs
+ chain.steps[0].input_data = {
+ "ticker": ticker,
+ "data_source": signal.get("data_source", "unknown"),
+ "lookback_period": signal.get("lookback_days", 20),
+ }
+
+ chain.steps[1].input_data = {
+ "p_value": signal.get("p_value", 1.0),
+ "t_statistic": signal.get("t_statistic", 0),
+ "sample_size": signal.get("sample_size", 0),
+ "threshold": self.config.risk_limits.min_p_value,
+ }
+
+ chain.steps[2].input_data = {
+ "signal_type": signal_type,
+ "historical_signals": historical_signals or [],
+ }
+
+ chain.steps[3].input_data = {
+ "current_regime": market_context.get("regime", "unknown"),
+ "vix_level": market_context.get("vix", 20),
+ "signal_regime_history": signal.get("regime_performance", {}),
+ }
+
+ chain.steps[4].input_data = {
+ "expected_return_bps": signal.get("expected_return_bps", 0),
+ "historical_volatility": signal.get("volatility", 0),
+ "max_drawdown_history": signal.get("max_drawdown", 0),
+ }
+
+ # Execute reasoning chain
+ await self.engine.execute_chain(chain)
+
+ # Synthesize evaluation from chain results
+ return self._synthesize_signal_evaluation(chain, signal)
+
+ def _synthesize_signal_evaluation(
+ self,
+ chain: ReasoningChain,
+ signal: Dict[str, Any],
+ ) -> SignalEvaluation:
+ """Synthesize evaluation from reasoning chain"""
+ ticker = signal.get("ticker", "UNKNOWN")
+ direction = signal.get("direction", "long")
+ signal_type = signal.get("signal_type", "unknown")
+
+ # Extract insights from each step
+ step_conclusions = {
+ step.title: step.conclusion
+ for step in chain.steps
+ if step.status == StepStatus.COMPLETED
+ }
+
+ # Determine statistical quality
+ p_value = signal.get("p_value", 1.0)
+ if p_value < 0.005:
+ statistical_quality = "excellent"
+ elif p_value < 0.01:
+ statistical_quality = "good"
+ elif p_value < 0.02:
+ statistical_quality = "marginal"
+ else:
+ statistical_quality = "poor"
+
+ # Determine regime fit
+ vix = signal.get("vix_level", 20)
+ if signal_type == "mean_reversion" and vix < 18:
+ regime_fit = "strong"
+ elif signal_type == "momentum" and vix > 15:
+ regime_fit = "moderate"
+ else:
+ regime_fit = "weak"
+
+ # Calculate risk/reward
+ expected_return = signal.get("expected_return_bps", 50)
+ expected_risk = signal.get("volatility", 100) * 2 # 2-sigma risk
+ risk_reward = expected_return / expected_risk if expected_risk > 0 else 0
+
+ # Calculate overall score (0-100)
+ score = 0
+ score += 30 if statistical_quality in ["excellent", "good"] else 10
+ score += 25 if regime_fit in ["strong", "moderate"] else 5
+ score += 25 if risk_reward > 0.5 else (15 if risk_reward > 0.3 else 5)
+ score += 20 * (chain.final_confidence or 0.5)
+
+ # Determine recommendation
+ if score >= 70:
+ recommendation = "trade"
+ elif score >= 50:
+ recommendation = "investigate"
+ else:
+ recommendation = "skip"
+
+ # Build reasoning summary
+ reasoning_summary = f"""
+Signal Evaluation for {ticker} {direction}:
+- Statistical Quality: {statistical_quality} (p={p_value:.4f})
+- Regime Fit: {regime_fit}
+- Risk/Reward: {risk_reward:.2f}
+- Overall Score: {score:.0f}/100
+- Recommendation: {recommendation.upper()}
+
+Chain Reasoning:
+{chain.get_reasoning_summary()}
+""".strip()
+
+ return SignalEvaluation(
+ signal_id=signal.get("signal_id", "unknown"),
+ ticker=ticker,
+ direction=direction,
+ signal_type=signal_type,
+ statistical_quality=statistical_quality,
+ p_value_assessment=f"p={p_value:.4f}, {'PASS' if p_value < 0.01 else 'FAIL'}",
+ sample_size_assessment=f"n={signal.get('sample_size', 0)}",
+ regime_fit=regime_fit,
+ sector_outlook="neutral", # Would be populated from market context
+ expected_return_bps=expected_return,
+ expected_risk_bps=expected_risk,
+ risk_reward_ratio=risk_reward,
+ overall_score=score,
+ recommendation=recommendation,
+ confidence=chain.final_confidence or 0.5,
+ reasoning_summary=reasoning_summary,
+ )
+
+ async def determine_position_size(
+ self,
+ signal: Dict[str, Any],
+ portfolio: Dict[str, Any],
+ market_context: Dict[str, Any],
+ ) -> SizingDecision:
+ """
+ Perform structured reasoning for position sizing.
+
+ Uses Kelly criterion with adjustments for:
+ - Liquidity constraints
+ - Portfolio correlation
+ - Risk limits
+ """
+ ticker = signal.get("ticker", "UNKNOWN")
+ direction = signal.get("direction", "long")
+
+ # Create reasoning chain
+ chain = self.engine.create_chain(
+ reasoning_type=ReasoningType.POSITION_SIZING,
+ subject=f"{ticker} {direction} position size",
+ context={
+ "signal": signal,
+ "portfolio": portfolio,
+ "market": market_context,
+ },
+ )
+
+ # Execute chain
+ await self.engine.execute_chain(chain)
+
+ # Calculate sizing components
+ kelly_size = self._calculate_kelly_size(signal)
+ liquidity_adjusted = self._adjust_for_liquidity(
+ kelly_size, signal, market_context
+ )
+ correlation_adjusted = self._adjust_for_correlation(
+ liquidity_adjusted, signal, portfolio
+ )
+ risk_limit_adjusted = self._apply_risk_limits(
+ correlation_adjusted, signal, portfolio
+ )
+
+ # Calculate final shares
+ price = signal.get("current_price", 100)
+ portfolio_value = portfolio.get("nav", 1000000)
+ notional = portfolio_value * (risk_limit_adjusted / 100)
+ shares = int(notional / price)
+
+ reasoning_summary = f"""
+Position Sizing for {ticker} {direction}:
+1. Kelly Size: {kelly_size:.2f}% (edge={signal.get('expected_return_bps', 0)/100:.2f}%, odds based)
+2. Liquidity Adjusted: {liquidity_adjusted:.2f}% (ADV constraint)
+3. Correlation Adjusted: {correlation_adjusted:.2f}% (portfolio correlation)
+4. Risk Limit Adjusted: {risk_limit_adjusted:.2f}% (hard limits)
+
+Final: {shares:,} shares (${notional:,.0f})
+""".strip()
+
+ return SizingDecision(
+ ticker=ticker,
+ direction=direction,
+ kelly_size_pct=kelly_size,
+ liquidity_adjusted_pct=liquidity_adjusted,
+ correlation_adjusted_pct=correlation_adjusted,
+ risk_limit_adjusted_pct=risk_limit_adjusted,
+ final_size_pct=risk_limit_adjusted,
+ final_shares=shares,
+ final_notional=notional,
+ confidence=chain.final_confidence or 0.7,
+ reasoning_summary=reasoning_summary,
+ )
+
+ def _calculate_kelly_size(self, signal: Dict[str, Any]) -> float:
+ """Calculate Kelly criterion optimal size"""
+ # Kelly = (bp - q) / b
+ # where b = win/loss ratio, p = win probability, q = 1-p
+
+ win_rate = signal.get("confidence", 0.5)
+ avg_win = signal.get("avg_win_bps", 50)
+ avg_loss = abs(signal.get("avg_loss_bps", 50))
+
+ if avg_loss == 0:
+ return 0
+
+ b = avg_win / avg_loss # Win/loss ratio
+ p = win_rate
+ q = 1 - p
+
+ kelly = (b * p - q) / b
+
+ # Apply Kelly fraction (use 25% of full Kelly for safety)
+ kelly_fraction = self.config.risk_limits.min_signal_confidence - 0.25
+ fractional_kelly = kelly * 0.25
+
+ # Cap at max position size
+ max_size = self.config.risk_limits.max_position_size_pct
+ return min(max(fractional_kelly * 100, 0), max_size)
+
+ def _adjust_for_liquidity(
+ self,
+ size_pct: float,
+ signal: Dict[str, Any],
+ market_context: Dict[str, Any],
+ ) -> float:
+ """Adjust size for liquidity constraints"""
+ adv = signal.get("average_daily_volume", 1000000)
+ price = signal.get("current_price", 100)
+ portfolio_nav = 1000000 # Placeholder
+
+ # Max position = 1% of ADV
+ max_adv_pct = self.config.risk_limits.max_order_size_adv_pct
+ max_notional_from_adv = adv * price * max_adv_pct
+
+ current_notional = portfolio_nav * (size_pct / 100)
+
+ if current_notional > max_notional_from_adv:
+ return (max_notional_from_adv / portfolio_nav) * 100
+
+ return size_pct
+
+ def _adjust_for_correlation(
+ self,
+ size_pct: float,
+ signal: Dict[str, Any],
+ portfolio: Dict[str, Any],
+ ) -> float:
+ """Adjust size for correlation with existing positions"""
+ # Get correlation with existing book
+ existing_positions = portfolio.get("positions", [])
+ ticker = signal.get("ticker")
+
+ max_correlation = 0
+ for pos in existing_positions:
+ # Would calculate actual correlation
+ if pos.get("sector") == signal.get("sector"):
+ max_correlation = max(max_correlation, 0.6) # Same sector
+
+ # Correlation penalty
+ if max_correlation > 0.7:
+ penalty = 1 - (max_correlation ** 2)
+ return size_pct * penalty
+
+ return size_pct
+
+ def _apply_risk_limits(
+ self,
+ size_pct: float,
+ signal: Dict[str, Any],
+ portfolio: Dict[str, Any],
+ ) -> float:
+ """Apply hard risk limits"""
+ limits = self.config.risk_limits
+
+ # Single name limit
+ size_pct = min(size_pct, limits.max_single_name_pct)
+
+ # Position size limit
+ size_pct = min(size_pct, limits.max_position_size_pct)
+
+ # Sector exposure check (would reduce if sector maxed)
+ # ...
+
+ return size_pct
+
+
+# Global investment reasoner instance
+_investment_reasoner: Optional[InvestmentReasoner] = None
+
+
+def get_investment_reasoner() -> InvestmentReasoner:
+ """Get the global investment reasoner instance"""
+ global _investment_reasoner
+ if _investment_reasoner is None:
+ _investment_reasoner = InvestmentReasoner()
+ return _investment_reasoner
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/risk_reasoning.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/risk_reasoning.py
new file mode 100644
index 000000000..4f410bd7a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/reasoning/risk_reasoning.py
@@ -0,0 +1,463 @@
+"""
+Risk Reasoning
+
+Specialized reasoning for risk assessment decisions:
+- VaR analysis
+- Stress testing
+- Correlation risk
+- Tail risk assessment
+"""
+
+from typing import Optional, List, Dict, Any
+from dataclasses import dataclass
+from datetime import datetime
+import math
+
+from .base import (
+ ReasoningEngine,
+ ReasoningChain,
+ ReasoningType,
+ StepStatus,
+ get_reasoning_engine,
+)
+from ..config import get_config
+
+
+@dataclass
+class RiskAssessmentResult:
+ """Result of risk reasoning"""
+ assessment_id: str
+ subject: str # What was assessed (trade, portfolio, scenario)
+
+ # VaR Metrics
+ current_var_pct: float
+ incremental_var_pct: float
+ post_trade_var_pct: float
+ var_limit_pct: float
+ var_utilization_pct: float
+
+ # Exposure Analysis
+ gross_exposure_pct: float
+ net_exposure_pct: float
+ beta_exposure: float
+ sector_concentrations: Dict[str, float]
+
+ # Stress Test Results
+ stress_scenarios: Dict[str, float] # Scenario name -> P&L impact %
+ worst_case_scenario: str
+ worst_case_impact_pct: float
+
+ # Risk Flags
+ risk_flags: List[str]
+ risk_level: str # low, medium, high, critical
+
+ # Recommendation
+ proceed: bool
+ conditions: List[str]
+ confidence: float
+ reasoning_summary: str
+
+
+@dataclass
+class CorrelationRisk:
+ """Correlation risk analysis result"""
+ position_ticker: str
+ correlated_positions: List[Dict[str, Any]]
+ max_correlation: float
+ effective_diversification: float
+ concentration_risk: str # low, medium, high
+
+
+class RiskReasoner:
+ """
+ Risk-focused reasoning system.
+
+ Provides structured reasoning for:
+ 1. Portfolio risk assessment
+ 2. Trade risk evaluation
+ 3. Stress testing
+ 4. Correlation analysis
+ 5. Limit monitoring
+ """
+
+ def __init__(self, reasoning_engine: Optional[ReasoningEngine] = None):
+ self.engine = reasoning_engine or get_reasoning_engine()
+ self.config = get_config()
+
+ async def assess_trade_risk(
+ self,
+ proposed_trade: Dict[str, Any],
+ current_portfolio: Dict[str, Any],
+ market_context: Dict[str, Any],
+ ) -> RiskAssessmentResult:
+ """
+ Perform structured risk reasoning for a proposed trade.
+
+ Evaluates:
+ 1. Incremental VaR impact
+ 2. Exposure changes
+ 3. Stress test outcomes
+ 4. Limit compliance
+ """
+ ticker = proposed_trade.get("ticker", "UNKNOWN")
+ direction = proposed_trade.get("direction", "long")
+ size_pct = proposed_trade.get("size_pct", 1.0)
+
+ # Create reasoning chain
+ chain = self.engine.create_chain(
+ reasoning_type=ReasoningType.RISK_ASSESSMENT,
+ subject=f"Trade risk: {ticker} {direction} {size_pct:.1f}%",
+ context={
+ "trade": proposed_trade,
+ "portfolio": current_portfolio,
+ "market": market_context,
+ },
+ )
+
+ # Execute chain
+ await self.engine.execute_chain(chain)
+
+ # Perform calculations
+ current_var = self._calculate_current_var(current_portfolio)
+ incremental_var = self._calculate_incremental_var(
+ proposed_trade, current_portfolio
+ )
+ post_trade_var = current_var + incremental_var
+
+ # Exposure analysis
+ exposures = self._calculate_exposures(proposed_trade, current_portfolio)
+
+ # Stress tests
+ stress_results = self._run_stress_tests(
+ proposed_trade, current_portfolio, market_context
+ )
+
+ # Check limits and generate flags
+ risk_flags, risk_level = self._check_limits(
+ post_trade_var, exposures, stress_results
+ )
+
+ # Determine if we should proceed
+ proceed, conditions = self._determine_proceed(
+ risk_flags, risk_level, chain.final_confidence or 0.5
+ )
+
+ reasoning_summary = f"""
+Risk Assessment for {ticker} {direction} ({size_pct:.1f}%):
+
+VaR Analysis:
+- Current VaR: {current_var:.2f}%
+- Incremental VaR: {incremental_var:.2f}%
+- Post-Trade VaR: {post_trade_var:.2f}%
+- Limit: {self.config.risk_limits.max_daily_var_pct:.2f}%
+- Utilization: {(post_trade_var / self.config.risk_limits.max_daily_var_pct * 100):.1f}%
+
+Exposures:
+- Gross: {exposures['gross']:.1f}%
+- Net: {exposures['net']:.1f}%
+- Beta: {exposures['beta']:.2f}
+
+Stress Tests:
+{chr(10).join([f"- {k}: {v:+.1f}%" for k, v in stress_results.items()])}
+
+Risk Flags: {', '.join(risk_flags) if risk_flags else 'None'}
+Risk Level: {risk_level.upper()}
+
+Recommendation: {'PROCEED' if proceed else 'HALT'}
+{('Conditions: ' + ', '.join(conditions)) if conditions else ''}
+""".strip()
+
+ return RiskAssessmentResult(
+ assessment_id=f"risk_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}",
+ subject=f"{ticker} {direction} trade",
+ current_var_pct=current_var,
+ incremental_var_pct=incremental_var,
+ post_trade_var_pct=post_trade_var,
+ var_limit_pct=self.config.risk_limits.max_daily_var_pct,
+ var_utilization_pct=post_trade_var / self.config.risk_limits.max_daily_var_pct * 100,
+ gross_exposure_pct=exposures["gross"],
+ net_exposure_pct=exposures["net"],
+ beta_exposure=exposures["beta"],
+ sector_concentrations=exposures.get("sectors", {}),
+ stress_scenarios=stress_results,
+ worst_case_scenario=min(stress_results, key=stress_results.get),
+ worst_case_impact_pct=min(stress_results.values()),
+ risk_flags=risk_flags,
+ risk_level=risk_level,
+ proceed=proceed,
+ conditions=conditions,
+ confidence=chain.final_confidence or 0.7,
+ reasoning_summary=reasoning_summary,
+ )
+
+ def _calculate_current_var(self, portfolio: Dict[str, Any]) -> float:
+ """Calculate current portfolio VaR"""
+ # Simplified VaR calculation
+ # In production, would use historical simulation or Monte Carlo
+ positions = portfolio.get("positions", [])
+
+ if not positions:
+ return 0.0
+
+ total_var = 0
+ for pos in positions:
+ # Individual position VaR (assuming normal distribution)
+ weight = pos.get("weight_pct", 0) / 100
+ volatility = pos.get("volatility", 20) / 100
+ # 95% VaR = 1.645 * sigma
+ individual_var = 1.645 * volatility * weight
+ total_var += individual_var ** 2
+
+ # Portfolio VaR (assuming some correlation)
+ # This is simplified - real calc would use correlation matrix
+ return math.sqrt(total_var) * 100 * 0.8 # Diversification benefit
+
+ def _calculate_incremental_var(
+ self,
+ trade: Dict[str, Any],
+ portfolio: Dict[str, Any],
+ ) -> float:
+ """Calculate incremental VaR from proposed trade"""
+ size_pct = trade.get("size_pct", 1.0) / 100
+ volatility = trade.get("volatility", 25) / 100
+
+ # Marginal VaR
+ marginal_var = 1.645 * volatility * size_pct
+
+ # Adjust for correlation with existing portfolio
+ portfolio_positions = portfolio.get("positions", [])
+ if portfolio_positions:
+ # Check if correlated positions exist
+ same_sector = [
+ p for p in portfolio_positions
+ if p.get("sector") == trade.get("sector")
+ ]
+ if same_sector:
+ # Higher correlation means more incremental risk
+ marginal_var *= 1.2
+
+ return marginal_var * 100
+
+ def _calculate_exposures(
+ self,
+ trade: Dict[str, Any],
+ portfolio: Dict[str, Any],
+ ) -> Dict[str, Any]:
+ """Calculate portfolio exposures"""
+ positions = portfolio.get("positions", [])
+
+ # Current exposures
+ long_exposure = sum(
+ p.get("weight_pct", 0) for p in positions
+ if p.get("direction") == "long"
+ )
+ short_exposure = abs(sum(
+ p.get("weight_pct", 0) for p in positions
+ if p.get("direction") == "short"
+ ))
+
+ # Add proposed trade
+ trade_size = trade.get("size_pct", 1.0)
+ if trade.get("direction") == "long":
+ long_exposure += trade_size
+ else:
+ short_exposure += trade_size
+
+ gross = long_exposure + short_exposure
+ net = long_exposure - short_exposure
+
+ # Calculate beta exposure
+ beta_sum = sum(
+ p.get("weight_pct", 0) * p.get("beta", 1.0) / 100
+ for p in positions
+ )
+ trade_beta = trade.get("beta", 1.0)
+ if trade.get("direction") == "long":
+ beta_sum += trade_size / 100 * trade_beta
+ else:
+ beta_sum -= trade_size / 100 * trade_beta
+
+ # Sector concentrations
+ sectors = {}
+ for p in positions:
+ sector = p.get("sector", "Unknown")
+ sectors[sector] = sectors.get(sector, 0) + p.get("weight_pct", 0)
+
+ trade_sector = trade.get("sector", "Unknown")
+ if trade.get("direction") == "long":
+ sectors[trade_sector] = sectors.get(trade_sector, 0) + trade_size
+ else:
+ sectors[trade_sector] = sectors.get(trade_sector, 0) - trade_size
+
+ return {
+ "gross": gross,
+ "net": net,
+ "beta": beta_sum,
+ "long": long_exposure,
+ "short": short_exposure,
+ "sectors": sectors,
+ }
+
+ def _run_stress_tests(
+ self,
+ trade: Dict[str, Any],
+ portfolio: Dict[str, Any],
+ market_context: Dict[str, Any],
+ ) -> Dict[str, float]:
+ """Run stress test scenarios"""
+ scenarios = {
+ "Market -5%": -5.0,
+ "Market -10%": -10.0,
+ "Market +5%": 5.0,
+ "VIX Spike +50%": -3.0,
+ "Sector -15%": -15.0,
+ "Flash Crash -20%": -20.0,
+ }
+
+ results = {}
+ beta = trade.get("beta", 1.0)
+ size_pct = trade.get("size_pct", 1.0) / 100
+ direction_mult = 1 if trade.get("direction") == "long" else -1
+
+ for scenario, market_move in scenarios.items():
+ if "Market" in scenario:
+ # Market scenarios
+ trade_impact = market_move * beta * size_pct * direction_mult
+ elif "VIX" in scenario:
+ # VIX spike hurts most positions
+ trade_impact = -2 * size_pct
+ elif "Sector" in scenario:
+ # Sector-specific
+ trade_impact = market_move * size_pct * direction_mult
+ else:
+ # Tail events
+ trade_impact = market_move * 0.5 * size_pct * direction_mult
+
+ results[scenario] = trade_impact
+
+ return results
+
+ def _check_limits(
+ self,
+ var_pct: float,
+ exposures: Dict[str, Any],
+ stress_results: Dict[str, float],
+ ) -> tuple:
+ """Check risk limits and generate flags"""
+ flags = []
+ limits = self.config.risk_limits
+
+ # VaR limit
+ if var_pct > limits.max_daily_var_pct:
+ flags.append(f"VaR BREACH: {var_pct:.2f}% > {limits.max_daily_var_pct}%")
+
+ # Gross exposure (leverage)
+ max_gross = limits.max_leverage * 100
+ if exposures["gross"] > max_gross:
+ flags.append(f"LEVERAGE BREACH: {exposures['gross']:.1f}% > {max_gross}%")
+
+ # Sector concentration
+ for sector, weight in exposures.get("sectors", {}).items():
+ if weight > limits.max_sector_exposure_pct:
+ flags.append(f"SECTOR BREACH ({sector}): {weight:.1f}% > {limits.max_sector_exposure_pct}%")
+
+ # Stress test
+ worst_stress = min(stress_results.values())
+ max_drawdown = -limits.max_drawdown_pct
+ if worst_stress < max_drawdown:
+ flags.append(f"STRESS TEST FAIL: {worst_stress:.1f}% < {max_drawdown}%")
+
+ # Determine risk level
+ if any("BREACH" in f for f in flags):
+ risk_level = "critical"
+ elif len(flags) >= 2:
+ risk_level = "high"
+ elif len(flags) == 1:
+ risk_level = "medium"
+ else:
+ risk_level = "low"
+
+ return flags, risk_level
+
+ def _determine_proceed(
+ self,
+ flags: List[str],
+ risk_level: str,
+ confidence: float,
+ ) -> tuple:
+ """Determine if we should proceed with the trade"""
+ if risk_level == "critical":
+ return False, ["BLOCKED: Risk limit breach"]
+
+ if risk_level == "high":
+ if confidence > 0.8:
+ return True, ["Reduce size by 50%", "Implement tight stop-loss"]
+ else:
+ return False, ["Risk too high for confidence level"]
+
+ if risk_level == "medium":
+ return True, ["Monitor closely", "Review at EOD"]
+
+ return True, []
+
+ async def analyze_correlation_risk(
+ self,
+ position: Dict[str, Any],
+ portfolio: Dict[str, Any],
+ ) -> CorrelationRisk:
+ """Analyze correlation risk of a position with existing portfolio"""
+ ticker = position.get("ticker", "UNKNOWN")
+ positions = portfolio.get("positions", [])
+
+ correlated = []
+ max_correlation = 0
+
+ for pos in positions:
+ if pos.get("ticker") == ticker:
+ continue
+
+ # Estimate correlation (simplified)
+ correlation = 0
+ if pos.get("sector") == position.get("sector"):
+ correlation = 0.6
+ if abs(pos.get("beta", 1) - position.get("beta", 1)) < 0.2:
+ correlation = max(correlation, 0.4)
+
+ if correlation > 0.3:
+ correlated.append({
+ "ticker": pos.get("ticker"),
+ "correlation": correlation,
+ "weight_pct": pos.get("weight_pct", 0),
+ })
+ max_correlation = max(max_correlation, correlation)
+
+ # Calculate effective diversification
+ if max_correlation > 0.7:
+ effective_div = 0.3
+ concentration = "high"
+ elif max_correlation > 0.5:
+ effective_div = 0.6
+ concentration = "medium"
+ else:
+ effective_div = 0.9
+ concentration = "low"
+
+ return CorrelationRisk(
+ position_ticker=ticker,
+ correlated_positions=correlated,
+ max_correlation=max_correlation,
+ effective_diversification=effective_div,
+ concentration_risk=concentration,
+ )
+
+
+# Global risk reasoner instance
+_risk_reasoner: Optional[RiskReasoner] = None
+
+
+def get_risk_reasoner() -> RiskReasoner:
+ """Get the global risk reasoner instance"""
+ global _risk_reasoner
+ if _risk_reasoner is None:
+ _risk_reasoner = RiskReasoner()
+ return _risk_reasoner
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/renaissance_technologies_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/renaissance_technologies_agent.py
deleted file mode 100644
index b1273f610..000000000
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/renaissance_technologies_agent.py
+++ /dev/null
@@ -1,693 +0,0 @@
-"""
-===== DATA SOURCES REQUIRED =====
-# INPUT:
-# - ticker symbols (array)
-# - end_date (string)
-# - FINANCIAL_DATASETS_API_KEY
-#
-# OUTPUT:
-# - Financial metrics: ROE, D/E, Current Ratio
-# - Financial line items: Revenue, Net Income, FCF, Debt, Equity, Retained Earnings, Operating Margin, R&D, Shares
-# - Market Cap
-#
-# PARAMETERS:
-# - period="annual"
-# - limit=10 years
-"""
-
-from fincept_terminal.Agents.src.graph.state import AgentState, show_agent_reasoning
-from fincept_terminal.Agents.src.tools.api import get_financial_metrics, get_market_cap, search_line_items
-from langchain_core.prompts import ChatPromptTemplate
-from langchain_core.messages import HumanMessage
-from pydantic import BaseModel
-import json
-import math
-from typing_extensions import Literal
-from fincept_terminal.Agents.src.utils.progress import progress
-from fincept_terminal.Agents.src.utils.llm import call_llm
-from fincept_terminal.Agents.src.utils.api_key import get_api_key_from_state
-
-
-class RenaissanceSignal(BaseModel):
- signal: Literal["bullish", "bearish", "neutral"]
- confidence: float
- reasoning: str
- statistical_edge: float
- signal_strength: dict
-
-
-def renaissance_technologies_agent(state: AgentState, agent_id: str = "renaissance_technologies_agent"):
- """
- Renaissance Technologies: Pure quantitative, statistical arbitrage
- Structure: Signal Generation → Risk Models → Execution Optimization → Jim Simons Systematic Decision
- Philosophy: Mathematical models, statistical edges, high-frequency systematic trading
- """
- data = state["data"]
- end_date = data["end_date"]
- tickers = data["tickers"]
- api_key = get_api_key_from_state(state, "FINANCIAL_DATASETS_API_KEY")
- analysis_data = {}
- renaissance_analysis = {}
-
- for ticker in tickers:
- progress.update_status(agent_id, ticker, "Signal generation algorithms analyzing patterns")
-
- metrics = get_financial_metrics(ticker, end_date, period="quarterly", limit=20, api_key=api_key)
- financial_line_items = search_line_items(
- ticker,
- [
- "revenue", "net_income", "free_cash_flow", "total_assets",
- "shareholders_equity", "operating_margin", "total_debt",
- "current_assets", "current_liabilities", "outstanding_shares"
- ],
- end_date,
- period="quarterly",
- limit=20,
- api_key=api_key,
- )
- market_cap = get_market_cap(ticker, end_date, api_key=api_key)
-
- # Renaissance's algorithmic analysis structure
- progress.update_status(agent_id, ticker, "Signal generation team analysis")
- signal_generation = signal_generation_team_analysis(metrics, financial_line_items, market_cap)
-
- progress.update_status(agent_id, ticker, "Risk modeling team analysis")
- risk_modeling = risk_modeling_team_analysis(metrics, financial_line_items, market_cap)
-
- progress.update_status(agent_id, ticker, "Execution optimization analysis")
- execution_optimization = execution_optimization_analysis(financial_line_items, market_cap)
-
- progress.update_status(agent_id, ticker, "Statistical arbitrage models")
- statistical_arbitrage = statistical_arbitrage_analysis(metrics, financial_line_items)
-
- progress.update_status(agent_id, ticker, "Jim Simons systematic synthesis")
- simons_systematic_decision = simons_systematic_synthesis(
- signal_generation, risk_modeling, execution_optimization, statistical_arbitrage
- )
-
- # Renaissance's mathematical scoring
- total_score = (
- signal_generation["score"] * 0.35 +
- statistical_arbitrage["score"] * 0.3 +
- risk_modeling["score"] * 0.2 +
- execution_optimization["score"] * 0.15
- )
-
- # Renaissance's systematic thresholds
- if total_score >= 8.0 and signal_generation.get("statistical_significance", 0) > 0.95:
- signal = "bullish"
- elif total_score <= 3.0 or signal_generation.get("statistical_significance", 0) < 0.6:
- signal = "bearish"
- else:
- signal = "neutral"
-
- analysis_data[ticker] = {
- "signal": signal,
- "score": total_score,
- "signal_generation": signal_generation,
- "risk_modeling": risk_modeling,
- "execution_optimization": execution_optimization,
- "statistical_arbitrage": statistical_arbitrage,
- "simons_systematic_decision": simons_systematic_decision
- }
-
- renaissance_output = generate_renaissance_output(ticker, analysis_data, state, agent_id)
-
- renaissance_analysis[ticker] = {
- "signal": renaissance_output.signal,
- "confidence": renaissance_output.confidence,
- "reasoning": renaissance_output.reasoning,
- "statistical_edge": renaissance_output.statistical_edge,
- "signal_strength": renaissance_output.signal_strength
- }
-
- progress.update_status(agent_id, ticker, "Done", analysis=renaissance_output.reasoning)
-
- message = HumanMessage(content=json.dumps(renaissance_analysis), name=agent_id)
-
- if state["metadata"]["show_reasoning"]:
- show_agent_reasoning(renaissance_analysis, "Renaissance Technologies")
-
- state["data"]["analyst_signals"][agent_id] = renaissance_analysis
- progress.update_status(agent_id, None, "Done")
-
- return {"messages": [message], "data": state["data"]}
-
-
-def signal_generation_team_analysis(metrics: list, financial_line_items: list, market_cap: float) -> dict:
- """Renaissance's signal generation algorithms"""
- score = 0
- details = []
- signals = {}
-
- if not metrics or not financial_line_items or not market_cap:
- return {"score": 0, "details": "No signal data"}
-
- # Mean reversion signals
- mean_reversion_score = calculate_mean_reversion_signals(metrics, financial_line_items)
- signals["mean_reversion"] = mean_reversion_score
- score += mean_reversion_score * 2
-
- # Momentum signals
- momentum_score = calculate_momentum_signals(metrics, financial_line_items)
- signals["momentum"] = momentum_score
- score += momentum_score * 2
-
- # Statistical pattern recognition
- pattern_score = identify_statistical_patterns(financial_line_items)
- signals["patterns"] = pattern_score
- score += pattern_score * 1.5
-
- # Cross-sectional signals
- cross_sectional_score = calculate_cross_sectional_signals(metrics)
- signals["cross_sectional"] = cross_sectional_score
- score += cross_sectional_score * 1.5
-
- # Factor exposure analysis
- factor_exposure = analyze_factor_exposures(metrics, financial_line_items)
- signals["factor_exposure"] = factor_exposure
- score += factor_exposure * 1
-
- # Statistical significance calculation
- statistical_significance = calculate_statistical_significance(signals)
-
- details.append(f"Mean reversion signal: {mean_reversion_score:.2f}")
- details.append(f"Momentum signal: {momentum_score:.2f}")
- details.append(f"Pattern recognition: {pattern_score:.2f}")
- details.append(f"Statistical significance: {statistical_significance:.2f}")
-
- return {
- "score": min(score, 10), # Cap at 10
- "details": "; ".join(details),
- "signals": signals,
- "statistical_significance": statistical_significance
- }
-
-
-def risk_modeling_team_analysis(metrics: list, financial_line_items: list, market_cap: float) -> dict:
- """Renaissance's risk modeling team analysis"""
- score = 0
- details = []
- risk_metrics = {}
-
- if not metrics or not financial_line_items:
- return {"score": 0, "details": "No risk modeling data"}
-
- # Volatility modeling
- volatility_score = model_volatility_patterns(financial_line_items)
- risk_metrics["volatility"] = volatility_score
- if volatility_score > 0.7:
- score += 2
- details.append("Low volatility risk profile")
-
- # Correlation analysis
- correlation_risk = analyze_correlation_risks(metrics, financial_line_items)
- risk_metrics["correlation"] = correlation_risk
- if correlation_risk < 0.6: # Low correlation is good
- score += 2
- details.append("Low correlation risk with market factors")
-
- # Liquidity risk modeling
- liquidity_risk = model_liquidity_risk(financial_line_items, market_cap)
- risk_metrics["liquidity"] = liquidity_risk
- if liquidity_risk > 0.8:
- score += 1
- details.append("Adequate liquidity for position sizing")
-
- # Factor risk decomposition
- factor_risks = decompose_factor_risks(metrics)
- risk_metrics["factor_risks"] = factor_risks
- if factor_risks.get("idiosyncratic_risk", 0) > 0.6:
- score += 2
- details.append("High idiosyncratic risk component - good for alpha generation")
-
- # Drawdown risk analysis
- drawdown_risk = calculate_maximum_drawdown_risk(financial_line_items)
- risk_metrics["drawdown"] = drawdown_risk
- if drawdown_risk < 0.3: # Low drawdown risk
- score += 1
- details.append("Limited drawdown risk based on historical patterns")
-
- return {
- "score": score,
- "details": "; ".join(details),
- "risk_metrics": risk_metrics
- }
-
-
-def execution_optimization_analysis(financial_line_items: list, market_cap: float) -> dict:
- """Renaissance's execution optimization analysis"""
- score = 0
- details = []
-
- if not financial_line_items or not market_cap:
- return {"score": 0, "details": "No execution data"}
-
- # Market impact modeling
- market_impact = estimate_market_impact(market_cap)
- if market_impact < 0.02: # Low market impact
- score += 3
- details.append(f"Low market impact: {market_impact:.3f}")
- elif market_impact < 0.05:
- score += 2
- details.append(f"Moderate market impact: {market_impact:.3f}")
-
- # Execution timing optimization
- timing_score = analyze_execution_timing(financial_line_items)
- score += timing_score * 2
- details.append(f"Execution timing score: {timing_score:.2f}")
-
- # Transaction cost analysis
- transaction_costs = estimate_transaction_costs(market_cap)
- if transaction_costs < 0.01: # Low transaction costs
- score += 2
- details.append(f"Low transaction costs: {transaction_costs:.3f}")
-
- # Slippage minimization
- slippage_risk = calculate_slippage_risk(market_cap)
- if slippage_risk < 0.5:
- score += 1
- details.append("Low slippage risk for systematic execution")
-
- return {"score": score, "details": "; ".join(details)}
-
-
-def statistical_arbitrage_analysis(metrics: list, financial_line_items: list) -> dict:
- """Renaissance's statistical arbitrage models"""
- score = 0
- details = []
- arbitrage_signals = {}
-
- if not metrics or not financial_line_items:
- return {"score": 0, "details": "No statistical arbitrage data"}
-
- # Pairs trading signals
- pairs_signal = calculate_pairs_trading_signals(metrics, financial_line_items)
- arbitrage_signals["pairs"] = pairs_signal
- score += pairs_signal * 2
-
- # Statistical mispricing detection
- mispricing_score = detect_statistical_mispricing(metrics, financial_line_items)
- arbitrage_signals["mispricing"] = mispricing_score
- score += mispricing_score * 2.5
-
- # Regime change detection
- regime_change = detect_regime_changes(financial_line_items)
- arbitrage_signals["regime_change"] = regime_change
- score += regime_change * 1.5
-
- # Market microstructure signals
- microstructure_score = analyze_market_microstructure(metrics)
- arbitrage_signals["microstructure"] = microstructure_score
- score += microstructure_score * 1
-
- details.append(f"Pairs trading signal: {pairs_signal:.2f}")
- details.append(f"Mispricing detection: {mispricing_score:.2f}")
- details.append(f"Regime change signal: {regime_change:.2f}")
-
- return {
- "score": min(score, 10),
- "details": "; ".join(details),
- "arbitrage_signals": arbitrage_signals
- }
-
-
-def simons_systematic_synthesis(signal_generation: dict, risk_modeling: dict,
- execution_optimization: dict, statistical_arbitrage: dict) -> dict:
- """Jim Simons' systematic synthesis and decision"""
- details = []
-
- # Mathematical model synthesis
- signal_strength = signal_generation.get("statistical_significance", 0)
- risk_adjustment = risk_modeling.get("risk_metrics", {}).get("volatility", 0.5)
- execution_feasibility = execution_optimization["score"] / 10
- arbitrage_opportunity = statistical_arbitrage["score"] / 10
-
- # Simons' systematic decision framework
- overall_edge = (signal_strength * 0.4 +
- arbitrage_opportunity * 0.3 +
- execution_feasibility * 0.2 +
- (1 - risk_adjustment) * 0.1)
-
- if overall_edge > 0.8:
- decision = "High conviction systematic trade"
- details.append("Strong statistical edge with low risk and good execution")
- elif overall_edge > 0.6:
- decision = "Moderate systematic position"
- details.append("Adequate statistical edge for systematic strategy")
- elif signal_strength < 0.6:
- decision = "Insufficient statistical significance"
- details.append("Statistical significance below systematic threshold")
- else:
- decision = "Pass - inadequate systematic edge"
- details.append("No clear systematic advantage identified")
-
- # Mathematical model confidence
- model_confidence = min(signal_strength * arbitrage_opportunity * execution_feasibility, 1.0)
-
- return {
- "decision": decision,
- "overall_edge": overall_edge,
- "model_confidence": model_confidence,
- "details": "; ".join(details)
- }
-
-
-# Mathematical and statistical helper functions
-def calculate_mean_reversion_signals(metrics: list, financial_line_items: list) -> float:
- """Calculate mean reversion signals"""
- if not metrics:
- return 0.5
-
- # Price-to-earnings mean reversion
- pe_ratios = [m.price_to_earnings for m in metrics if m.price_to_earnings and m.price_to_earnings > 0]
- if len(pe_ratios) >= 4:
- current_pe = pe_ratios[0]
- historical_mean = sum(pe_ratios[1:]) / len(pe_ratios[1:])
-
- # Mean reversion signal strength
- deviation = abs(current_pe - historical_mean) / historical_mean
- if current_pe < historical_mean * 0.8: # 20% below mean
- return min(deviation, 1.0)
- elif current_pe > historical_mean * 1.2: # 20% above mean
- return -min(deviation, 1.0)
-
- return 0.0
-
-
-def calculate_momentum_signals(metrics: list, financial_line_items: list) -> float:
- """Calculate momentum signals"""
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if len(revenues) >= 4:
- # Revenue momentum
- recent_growth = (revenues[0] / revenues[1]) - 1
- historical_growth = (revenues[1] / revenues[-1]) ** (1 / (len(revenues) - 2)) - 1
-
- momentum_strength = (recent_growth - historical_growth) / abs(
- historical_growth) if historical_growth != 0 else 0
- return max(min(momentum_strength, 1.0), -1.0)
-
- return 0.0
-
-
-def identify_statistical_patterns(financial_line_items: list) -> float:
- """Identify statistical patterns in financial data"""
- earnings = [item.net_income for item in financial_line_items if item.net_income]
- if len(earnings) >= 8:
- # Pattern recognition using simple autocorrelation
- autocorr = calculate_autocorrelation(earnings, lag=1)
- pattern_strength = abs(autocorr)
- return min(pattern_strength, 1.0)
-
- return 0.3
-
-
-def calculate_cross_sectional_signals(metrics: list) -> float:
- """Calculate cross-sectional ranking signals"""
- if not metrics:
- return 0.5
-
- latest = metrics[0]
- # Simplified cross-sectional score based on multiple metrics
- score_components = []
-
- if latest.return_on_equity:
- score_components.append(min(latest.return_on_equity / 0.15, 1.0)) # Normalize by 15%
-
- if latest.price_to_earnings and latest.price_to_earnings > 0:
- score_components.append(max(1 - (latest.price_to_earnings / 20), 0)) # Lower P/E is better
-
- if score_components:
- return sum(score_components) / len(score_components)
-
- return 0.5
-
-
-def analyze_factor_exposures(metrics: list, financial_line_items: list) -> float:
- """Analyze factor exposures"""
- # Simplified factor analysis
- if not metrics:
- return 0.5
-
- latest = metrics[0]
- factor_score = 0
-
- # Value factor
- if latest.price_to_book and latest.price_to_book < 2.0:
- factor_score += 0.3
-
- # Quality factor
- if latest.return_on_equity and latest.return_on_equity > 0.12:
- factor_score += 0.3
-
- # Momentum factor
- if financial_line_items:
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if len(revenues) >= 2 and revenues[0] > revenues[1]:
- factor_score += 0.2
-
- return min(factor_score, 1.0)
-
-
-def calculate_statistical_significance(signals: dict) -> float:
- """Calculate overall statistical significance"""
- signal_values = [v for v in signals.values() if isinstance(v, (int, float))]
- if not signal_values:
- return 0.5
-
- # Simplified statistical significance based on signal consistency
- signal_consistency = 1 - (max(signal_values) - min(signal_values)) / 2
- signal_strength = sum(abs(v) for v in signal_values) / len(signal_values)
-
- return (signal_consistency * 0.6 + signal_strength * 0.4)
-
-
-def model_volatility_patterns(financial_line_items: list) -> float:
- """Model volatility patterns"""
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if len(revenues) >= 4:
- volatility = calculate_coefficient_of_variation(revenues)
- return max(1 - volatility, 0) # Lower volatility = higher score
- return 0.5
-
-
-def analyze_correlation_risks(metrics: list, financial_line_items: list) -> float:
- """Analyze correlation with market factors"""
- # Simplified correlation analysis
- return 0.4 # Placeholder - would calculate correlation with market indices
-
-
-def model_liquidity_risk(financial_line_items: list, market_cap: float) -> float:
- """Model liquidity risk"""
- if market_cap > 10_000_000_000: # $10B+ market cap
- return 0.9
- elif market_cap > 1_000_000_000: # $1B+ market cap
- return 0.7
- else:
- return 0.4
-
-
-def decompose_factor_risks(metrics: list) -> dict:
- """Decompose factor risks"""
- return {
- "market_risk": 0.4,
- "size_risk": 0.2,
- "value_risk": 0.1,
- "momentum_risk": 0.1,
- "idiosyncratic_risk": 0.2
- }
-
-
-def calculate_maximum_drawdown_risk(financial_line_items: list) -> float:
- """Calculate maximum drawdown risk"""
- earnings = [item.net_income for item in financial_line_items if item.net_income]
- if earnings:
- peak = max(earnings)
- trough = min(earnings)
- if peak > 0:
- return abs(trough - peak) / peak
- return 0.5
-
-
-def estimate_market_impact(market_cap: float) -> float:
- """Estimate market impact for trading"""
- if market_cap > 50_000_000_000: # $50B+
- return 0.001
- elif market_cap > 10_000_000_000: # $10B+
- return 0.005
- elif market_cap > 1_000_000_000: # $1B+
- return 0.02
- else:
- return 0.1
-
-
-def analyze_execution_timing(financial_line_items: list) -> float:
- """Analyze optimal execution timing"""
- return 0.7 # Placeholder for execution timing analysis
-
-
-def estimate_transaction_costs(market_cap: float) -> float:
- """Estimate transaction costs"""
- if market_cap > 10_000_000_000:
- return 0.005
- elif market_cap > 1_000_000_000:
- return 0.01
- else:
- return 0.03
-
-
-def calculate_slippage_risk(market_cap: float) -> float:
- """Calculate slippage risk"""
- return 1 / (1 + math.log10(market_cap / 1_000_000_000)) # Decreases with market cap
-
-
-def calculate_pairs_trading_signals(metrics: list, financial_line_items: list) -> float:
- """Calculate pairs trading signals"""
- return 0.6 # Placeholder for pairs trading analysis
-
-
-def detect_statistical_mispricing(metrics: list, financial_line_items: list) -> float:
- """Detect statistical mispricing"""
- if not metrics:
- return 0.5
-
- latest = metrics[0]
- mispricing_score = 0
-
- # P/E vs growth mispricing
- if latest.price_to_earnings and latest.price_to_earnings > 0:
- revenues = [item.revenue for item in financial_line_items if item.revenue]
- if len(revenues) >= 3:
- growth = (revenues[0] / revenues[-1]) ** (1 / len(revenues)) - 1
- expected_pe = 15 + (growth * 100) # Simple growth-adjusted P/E
- if latest.price_to_earnings < expected_pe * 0.8:
- mispricing_score += 0.5
-
- return mispricing_score
-
-
-def detect_regime_changes(financial_line_items: list) -> float:
- """Detect regime changes in business fundamentals"""
- margins = []
- for item in financial_line_items:
- if item.net_income and item.revenue and item.revenue > 0:
- margins.append(item.net_income / item.revenue)
-
- if len(margins) >= 4:
- recent_avg = sum(margins[:2]) / 2
- historical_avg = sum(margins[2:]) / len(margins[2:])
-
- if abs(recent_avg - historical_avg) > 0.05: # 5% margin change
- return 0.8
-
- return 0.2
-
-
-def analyze_market_microstructure(metrics: list) -> float:
- """Analyze market microstructure signals"""
- return 0.5 # Placeholder for microstructure analysis
-
-
-def calculate_autocorrelation(data: list, lag: int) -> float:
- """Calculate autocorrelation with given lag"""
- if len(data) <= lag:
- return 0
-
- mean_val = sum(data) / len(data)
- numerator = sum((data[i] - mean_val) * (data[i + lag] - mean_val)
- for i in range(len(data) - lag))
- denominator = sum((x - mean_val) ** 2 for x in data)
-
- return numerator / denominator if denominator != 0 else 0
-
-
-def calculate_coefficient_of_variation(data: list) -> float:
- """Calculate coefficient of variation"""
- if not data:
- return 1.0
-
- mean_val = sum(data) / len(data)
- if mean_val == 0:
- return 1.0
-
- variance = sum((x - mean_val) ** 2 for x in data) / len(data)
- std_dev = math.sqrt(variance)
-
- return std_dev / abs(mean_val)
-
-
-def generate_renaissance_output(ticker: str, analysis_data: dict, state: AgentState,
- agent_id: str) -> RenaissanceSignal:
- """Generate Renaissance's systematic quantitative decision"""
- template = ChatPromptTemplate.from_messages([
- ("system", """You are Renaissance Technologies' AI system, implementing Jim Simons' quantitative systematic approach:
-
- ORGANIZATIONAL STRUCTURE:
- - Signal Generation Team: Mathematical pattern recognition and statistical signals
- - Risk Modeling Team: Volatility, correlation, and factor risk analysis
- - Execution Optimization Team: Market impact and transaction cost modeling
- - Statistical Arbitrage Team: Pairs trading and mispricing detection
- - Jim Simons Systematic Synthesis: Mathematical model integration
-
- PHILOSOPHY:
- 1. Pure Quantitative: Mathematical models over fundamental analysis
- 2. Statistical Edge: Identify small, consistent statistical advantages
- 3. Systematic Execution: Remove human emotion and bias
- 4. High Frequency: Exploit short-term market inefficiencies
- 5. Risk Management: Sophisticated mathematical risk models
- 6. Diversification: Many small bets rather than few large ones
- 7. Continuous Learning: Models adapt and evolve systematically
-
- REASONING STYLE:
- - Reference mathematical models and statistical significance
- - Discuss signal generation algorithms and pattern recognition
- - Consider risk-adjusted returns and Sharpe ratios
- - Apply systematic decision thresholds and confidence intervals
- - Express reasoning in quantitative terms
- - Acknowledge model limitations and uncertainty
- - Focus on statistical edge and execution feasibility
-
- Return the investment signal with statistical edge and signal strength metrics."""),
-
- ("human", """Apply Renaissance's quantitative systematic analysis to {ticker}:
-
- {analysis_data}
-
- Provide investment signal in JSON format:
- {{
- "signal": "bullish" | "bearish" | "neutral",
- "confidence": float (0-100),
- "reasoning": "string",
- "statistical_edge": float (0-1),
- "signal_strength": {{
- "mean_reversion": float,
- "momentum": float,
- "statistical_arbitrage": float,
- "risk_adjusted_return": float
- }}
- }}""")
- ])
-
- prompt = template.invoke({"analysis_data": json.dumps(analysis_data, indent=2), "ticker": ticker})
-
- def create_default_renaissance_signal():
- return RenaissanceSignal(
- signal="neutral",
- confidence=0.0,
- reasoning="Analysis error, defaulting to neutral",
- statistical_edge=0.0,
- signal_strength={
- "mean_reversion": 0.0,
- "momentum": 0.0,
- "statistical_arbitrage": 0.0,
- "risk_adjusted_return": 0.0
- }
- )
-
- return call_llm(
- prompt=prompt,
- pydantic_model=RenaissanceSignal,
- agent_name=agent_id,
- state=state,
- default_factory=create_default_renaissance_signal,
- )
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/rentech_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/rentech_cli.py
new file mode 100644
index 000000000..805674775
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/rentech_cli.py
@@ -0,0 +1,721 @@
+#!/usr/bin/env python3
+"""
+Renaissance Technologies Multi-Agent System CLI
+================================================
+Command-line interface for the RenTech multi-agent system.
+Called by Tauri/Rust via worker pool or subprocess.
+
+Usage:
+ python rentech_cli.py <command> [args...]
+
+Commands:
+ # Agent operations
+ create_agent <json_config> - Create and return agent info
+ run_agent <json_config> - Run agent with task
+ list_agent_presets - List available agent presets
+
+ # Team operations
+ create_team <json_config> - Create and return team info
+ run_team <json_config> - Run team with task
+ list_team_presets - List available team presets
+
+ # IC Deliberation
+ run_ic_deliberation <json_data> - Run full IC deliberation on signal
+
+ # System operations
+ analyze_signal <json_data> - Full signal analysis pipeline
+ get_config_schema - Get JSON schema for configurations
+ health_check - Check system health
+
+Example:
+ python rentech_cli.py run_agent '{
+ "config": {"name": "Analyst", "model": {"temperature": 0.3}},
+ "task": "Analyze AAPL momentum signal"
+ }'
+"""
+
+import sys
+import json
+import os
+import asyncio
+from typing import Dict, Any, Optional
+from datetime import datetime
+
+# Add script directory to path
+script_dir = os.path.dirname(os.path.abspath(__file__)) if '__file__' in dir() else os.getcwd()
+if script_dir not in sys.path:
+ sys.path.insert(0, script_dir)
+
+# Parent directory for imports
+parent_dir = os.path.dirname(script_dir)
+if parent_dir not in sys.path:
+ sys.path.insert(0, parent_dir)
+
+
+# =============================================================================
+# RESPONSE HELPERS
+# =============================================================================
+
+def success_response(data: Any, message: str = "Success") -> str:
+ """Create success response JSON"""
+ return json.dumps({
+ "success": True,
+ "message": message,
+ "data": data,
+ "timestamp": datetime.utcnow().isoformat(),
+ }, indent=2, default=str)
+
+
+def error_response(error: str, traceback_str: Optional[str] = None) -> str:
+ """Create error response JSON"""
+ return json.dumps({
+ "success": False,
+ "error": error,
+ "traceback": traceback_str,
+ "timestamp": datetime.utcnow().isoformat(),
+ }, indent=2)
+
+
+# =============================================================================
+# MODEL FACTORY
+# =============================================================================
+
+def create_model_from_settings(model_settings: Dict[str, Any]):
+ """
+ Create Agno model from ModelSettings dict.
+
+ Uses the new dynamic model factory that reads from frontend SQLite database
+ and supports all Agno providers (40+).
+
+ Args:
+ model_settings: Dictionary with model configuration
+
+ Returns:
+ Agno model instance
+ """
+ from .utils.model_factory import create_model_from_config
+
+ # Convert model_settings to config dict format
+ config_dict = {
+ "provider": model_settings.get("provider", "openai"),
+ "model_id": model_settings.get("model_id", "gpt-4o"),
+ "api_key": model_settings.get("api_key"),
+ "base_url": model_settings.get("base_url"),
+ "temperature": model_settings.get("temperature", 0.7),
+ "max_tokens": model_settings.get("max_tokens", 4096)
+ }
+
+ # Use factory to create model (will read from frontend DB if no override)
+ return create_model_from_config(config_dict)
+
+
+# =============================================================================
+# AGENT OPERATIONS
+# =============================================================================
+
+def create_agent(json_str: str) -> str:
+ """
+ Create an agent from JSON configuration.
+
+ Input JSON:
+ {
+ "config": {AgentConfig},
+ "task": "optional task to run immediately"
+ }
+ """
+ try:
+ from agno.agent import Agent
+ from .schemas import AgentConfig
+
+ data = json.loads(json_str)
+ config_data = data.get("config", data)
+
+ # Parse config
+ config = AgentConfig.from_dict(config_data)
+
+ # Create model
+ model = create_model_from_settings(config.model.to_dict())
+
+ # Get Agno kwargs
+ kwargs = config.to_agno_kwargs()
+ kwargs["model"] = model
+
+ # Create agent
+ agent = Agent(**kwargs)
+
+ # If task provided, run it
+ task = data.get("task")
+ if task:
+ response = agent.run(task)
+ content = response.content if hasattr(response, 'content') else str(response)
+
+ return success_response({
+ "agent_name": config.name,
+ "task": task,
+ "response": content,
+ }, "Agent executed successfully")
+ else:
+ return success_response({
+ "agent_name": config.name,
+ "agent_id": config.id,
+ "role": config.role,
+ "status": "created",
+ }, "Agent created successfully")
+
+ except Exception as e:
+ import traceback
+ return error_response(str(e), traceback.format_exc())
+
+
+def run_agent(json_str: str) -> str:
+ """
+ Run an agent with a task.
+
+ Input JSON:
+ {
+ "config": {AgentConfig},
+ "task": "The task to run",
+ "context": {"optional": "context data"}
+ }
+ """
+ try:
+ from agno.agent import Agent
+ from .schemas import AgentConfig
+
+ data = json.loads(json_str)
+
+ if "task" not in data:
+ return error_response("Missing 'task' in input")
+
+ config_data = data.get("config", {})
+ task = data["task"]
+ context = data.get("context", {})
+
+ # Parse config
+ config = AgentConfig.from_dict(config_data)
+
+ # Create model
+ model = create_model_from_settings(config.model.to_dict())
+
+ # Get Agno kwargs
+ kwargs = config.to_agno_kwargs()
+ kwargs["model"] = model
+
+ # Create and run agent
+ agent = Agent(**kwargs)
+
+ # Build task with context
+ if context:
+ context_str = "\n".join([f"- {k}: {v}" for k, v in context.items()])
+ full_task = f"{task}\n\nContext:\n{context_str}"
+ else:
+ full_task = task
+
+ response = agent.run(full_task)
+ content = response.content if hasattr(response, 'content') else str(response)
+
+ return success_response({
+ "agent_name": config.name or "Agent",
+ "task": task,
+ "response": content,
+ }, "Agent task completed")
+
+ except Exception as e:
+ import traceback
+ return error_response(str(e), traceback.format_exc())
+
+
+def list_agent_presets() -> str:
+ """List available agent preset configurations"""
+ try:
+ from .schemas import (
+ get_research_agent_config,
+ get_trading_agent_config,
+ get_risk_agent_config,
+ )
+
+ presets = {
+ "research": get_research_agent_config().to_dict(),
+ "trading": get_trading_agent_config().to_dict(),
+ "risk": get_risk_agent_config().to_dict(),
+ }
+
+ return success_response({
+ "presets": list(presets.keys()),
+ "configs": presets,
+ }, "Agent presets retrieved")
+
+ except Exception as e:
+ import traceback
+ return error_response(str(e), traceback.format_exc())
+
+
+# =============================================================================
+# TEAM OPERATIONS
+# =============================================================================
+
+def create_team(json_str: str) -> str:
+ """
+ Create a team from JSON configuration.
+
+ Input JSON:
+ {
+ "config": {TeamConfig},
+ "task": "optional task to run immediately"
+ }
+ """
+ try:
+ from agno.agent import Agent
+ from agno.team import Team
+ from .schemas import TeamConfig, AgentConfig
+
+ data = json.loads(json_str)
+ config_data = data.get("config", data)
+
+ # Parse config
+ config = TeamConfig.from_dict(config_data)
+
+ # Create model for team
+ team_model = create_model_from_settings(config.model.to_dict())
+
+ # Create member agents
+ members = []
+ for member_config in config.member_configs:
+ member_model = create_model_from_settings(member_config.model.to_dict())
+ member_kwargs = member_config.to_agno_kwargs()
+ member_kwargs["model"] = member_model
+ members.append(Agent(**member_kwargs))
+
+ # Get Team kwargs
+ team_kwargs = config.to_agno_kwargs()
+ team_kwargs["model"] = team_model
+ team_kwargs["members"] = members
+
+ # Create team
+ team = Team(**team_kwargs)
+
+ # If task provided, run it
+ task = data.get("task")
+ if task:
+ response = team.run(task)
+ content = response.content if hasattr(response, 'content') else str(response)
+
+ return success_response({
+ "team_name": config.name,
+ "member_count": len(members),
+ "task": task,
+ "response": content,
+ }, "Team executed successfully")
+ else:
+ return success_response({
+ "team_name": config.name,
+ "team_id": config.id,
+ "member_count": len(members),
+ "members": [m.name for m in members],
+ "status": "created",
+ }, "Team created successfully")
+
+ except Exception as e:
+ import traceback
+ return error_response(str(e), traceback.format_exc())
+
+
+def run_team(json_str: str) -> str:
+ """
+ Run a team with a task.
+
+ Input JSON:
+ {
+ "config": {TeamConfig},
+ "task": "The task to run",
+ "context": {"optional": "context data"}
+ }
+ """
+ try:
+ from agno.agent import Agent
+ from agno.team import Team
+ from .schemas import TeamConfig
+
+ data = json.loads(json_str)
+
+ if "task" not in data:
+ return error_response("Missing 'task' in input")
+
+ config_data = data.get("config", {})
+ task = data["task"]
+ context = data.get("context", {})
+
+ # Parse config
+ config = TeamConfig.from_dict(config_data)
+
+ # Create model for team
+ team_model = create_model_from_settings(config.model.to_dict())
+
+ # Create member agents
+ members = []
+ for member_config in config.member_configs:
+ member_model = create_model_from_settings(member_config.model.to_dict())
+ member_kwargs = member_config.to_agno_kwargs()
+ member_kwargs["model"] = member_model
+ members.append(Agent(**member_kwargs))
+
+ # Get Team kwargs
+ team_kwargs = config.to_agno_kwargs()
+ team_kwargs["model"] = team_model
+ team_kwargs["members"] = members
+
+ # Create team
+ team = Team(**team_kwargs)
+
+ # Build task with context
+ if context:
+ context_str = "\n".join([f"- {k}: {v}" for k, v in context.items()])
+ full_task = f"{task}\n\nContext:\n{context_str}"
+ else:
+ full_task = task
+
+ response = team.run(full_task)
+ content = response.content if hasattr(response, 'content') else str(response)
+
+ return success_response({
+ "team_name": config.name or "Team",
+ "member_count": len(members),
+ "task": task,
+ "response": content,
+ }, "Team task completed")
+
+ except Exception as e:
+ import traceback
+ return error_response(str(e), traceback.format_exc())
+
+
+def list_team_presets() -> str:
+ """List available team preset configurations"""
+ try:
+ from .schemas import (
+ get_research_team_config,
+ get_trading_team_config,
+ get_risk_team_config,
+ get_investment_committee_config,
+ )
+
+ presets = {
+ "research": get_research_team_config().to_dict(),
+ "trading": get_trading_team_config().to_dict(),
+ "risk": get_risk_team_config().to_dict(),
+ "investment_committee": get_investment_committee_config().to_dict(),
+ }
+
+ return success_response({
+ "presets": list(presets.keys()),
+ "configs": presets,
+ }, "Team presets retrieved")
+
+ except Exception as e:
+ import traceback
+ return error_response(str(e), traceback.format_exc())
+
+
+# =============================================================================
+# IC DELIBERATION
+# =============================================================================
+
+def run_ic_deliberation(json_str: str) -> str:
+ """
+ Run full Investment Committee deliberation on a signal.
+
+ Input JSON:
+ {
+ "signal": {
+ "ticker": "AAPL",
+ "direction": "long",
+ "signal_type": "momentum",
+ "p_value": 0.008,
+ "confidence": 0.58,
+ "expected_return_bps": 85
+ },
+ "risk_assessment": {
+ "risk_level": "medium",
+ "var_utilization_pct": 45
+ },
+ "sizing_recommendation": {
+ "final_size_pct": 1.5
+ },
+ "market_context": {
+ "vix": 16.5,
+ "regime": "bullish"
+ }
+ }
+ """
+ try:
+ from .reasoning.ic_deliberation import get_ic_deliberator
+
+ data = json.loads(json_str)
+
+ signal = data.get("signal", {})
+ signal_evaluation = data.get("signal_evaluation", {
+ "statistical_quality": "good",
+ "overall_score": 70,
+ })
+ risk_assessment = data.get("risk_assessment", {
+ "risk_level": "medium",
+ })
+ sizing_recommendation = data.get("sizing_recommendation", {
+ "final_size_pct": 1.0,
+ })
+ market_context = data.get("market_context", {
+ "vix": 20,
+ "regime": "neutral",
+ })
+ historical_decisions = data.get("historical_decisions", [])
+
+ deliberator = get_ic_deliberator()
+
+ # Run deliberation
+ result = asyncio.run(deliberator.deliberate(
+ signal=signal,
+ signal_evaluation=signal_evaluation,
+ risk_assessment=risk_assessment,
+ sizing_recommendation=sizing_recommendation,
+ market_context=market_context,
+ historical_decisions=historical_decisions,
+ ))
+
+ return success_response({
+ "deliberation_id": result.deliberation_id,
+ "subject": result.subject,
+ "decision": result.decision,
+ "decision_rationale": result.decision_rationale,
+ "conditions": result.conditions,
+ "approved_size_pct": result.approved_size_pct,
+ "confidence": result.confidence,
+ "vote_summary": result.vote_summary,
+ "member_opinions": [
+ {
+ "member": op.member_role,
+ "vote": op.vote.value,
+ "rationale": op.rationale,
+ "confidence": op.confidence,
+ }
+ for op in result.member_opinions
+ ],
+ "pros": result.pros,
+ "cons": result.cons,
+ "reasoning_summary": result.reasoning_chain_summary,
+ }, f"IC Decision: {result.decision}")
+
+ except Exception as e:
+ import traceback
+ return error_response(str(e), traceback.format_exc())
+
+
+# =============================================================================
+# SIGNAL ANALYSIS
+# =============================================================================
+
+def analyze_signal(json_str: str) -> str:
+ """
+ Run full signal analysis pipeline.
+
+ Input JSON:
+ {
+ "ticker": "AAPL",
+ "signal_type": "momentum",
+ "direction": "long",
+ "trade_value": 1000000,
+ "include_deliberation": true
+ }
+ """
+ try:
+ from .main import RenaissanceTechnologiesSystem, AnalysisConfig
+
+ data = json.loads(json_str)
+
+ ticker = data.get("ticker", "AAPL")
+ trade_value = data.get("trade_value", 1_000_000)
+ period = data.get("period", "1y")
+ include_deliberation = data.get("include_deliberation", False)
+
+ # Create system and config
+ system = RenaissanceTechnologiesSystem()
+ config = AnalysisConfig(
+ trade_value=trade_value,
+ period=period,
+ )
+
+ # Run analysis
+ decision = system.analyze(ticker, config)
+
+ result = {
+ "ticker": ticker,
+ "signal": decision.signal.value,
+ "confidence": decision.confidence,
+ "statistical_edge": decision.statistical_edge,
+ "signal_score": decision.signal_score,
+ "risk_score": decision.risk_score,
+ "execution_score": decision.execution_score,
+ "arbitrage_score": decision.arbitrage_score,
+ "position_sizing": {
+ "recommended_size_pct": decision.position_sizing.recommended_size_pct,
+ "kelly_fraction": decision.position_sizing.kelly_fraction,
+ "leverage": decision.position_sizing.leverage_recommendation,
+ },
+ "signal_strength": decision.signal_strength,
+ "key_factors": decision.key_factors,
+ "risks": decision.risks,
+ "reasoning": decision.reasoning,
+ }
+
+ # Include IC deliberation if requested
+ if include_deliberation:
+ delib_result = run_ic_deliberation(json.dumps({
+ "signal": {
+ "ticker": ticker,
+ "direction": decision.signal.value,
+ "signal_type": "combined",
+ "p_value": 0.01, # Placeholder
+ "confidence": decision.confidence / 100,
+ "expected_return_bps": decision.statistical_edge * 10000,
+ },
+ "sizing_recommendation": {
+ "final_size_pct": decision.position_sizing.recommended_size_pct,
+ },
+ }))
+ result["ic_deliberation"] = json.loads(delib_result).get("data", {})
+
+ return success_response(result, f"Analysis complete: {decision.signal.value.upper()}")
+
+ except Exception as e:
+ import traceback
+ return error_response(str(e), traceback.format_exc())
+
+
+# =============================================================================
+# SYSTEM OPERATIONS
+# =============================================================================
+
+def get_config_schema() -> str:
+ """Get JSON schemas for all configurations"""
+ try:
+ from .schemas import get_agent_config_schema, get_team_config_schema
+
+ return success_response({
+ "agent_schema": get_agent_config_schema(),
+ "team_schema": get_team_config_schema(),
+ }, "Schemas retrieved")
+
+ except Exception as e:
+ import traceback
+ return error_response(str(e), traceback.format_exc())
+
+
+def health_check() -> str:
+ """Check system health and available components"""
+ try:
+ status = {
+ "system": "operational",
+ "components": {},
+ }
+
+ # Check Agno
+ try:
+ from agno.agent import Agent
+ from agno.team import Team
+ status["components"]["agno"] = "ok"
+ except ImportError as e:
+ status["components"]["agno"] = f"error: {e}"
+
+ # Check model
+ try:
+ from .config import get_config
+ config = get_config()
+ status["components"]["config"] = "ok"
+ status["model"] = {
+ "provider": config.models.provider.value,
+ "model_id": config.models.model_id,
+ }
+ except Exception as e:
+ status["components"]["config"] = f"error: {e}"
+
+ # Check reasoning
+ try:
+ from .reasoning import get_reasoning_engine
+ status["components"]["reasoning"] = "ok"
+ except Exception as e:
+ status["components"]["reasoning"] = f"error: {e}"
+
+ # Check guardrails
+ try:
+ from .guardrails import get_guardrail_registry
+ status["components"]["guardrails"] = "ok"
+ except Exception as e:
+ status["components"]["guardrails"] = f"error: {e}"
+
+ return success_response(status, "Health check complete")
+
+ except Exception as e:
+ import traceback
+ return error_response(str(e), traceback.format_exc())
+
+
+# =============================================================================
+# MAIN CLI
+# =============================================================================
+
+COMMANDS = {
+ # Agent operations
+ "create_agent": create_agent,
+ "run_agent": run_agent,
+ "list_agent_presets": list_agent_presets,
+
+ # Team operations
+ "create_team": create_team,
+ "run_team": run_team,
+ "list_team_presets": list_team_presets,
+
+ # IC Deliberation
+ "run_ic_deliberation": run_ic_deliberation,
+
+ # Signal analysis
+ "analyze_signal": analyze_signal,
+ "analyze": analyze_signal, # Alias for Tauri compatibility
+
+ # System
+ "get_config_schema": get_config_schema,
+ "health_check": health_check,
+}
+
+
+def main(args: list) -> str:
+ """Main entry point for script execution"""
+ if len(args) < 1:
+ return json.dumps({
+ "success": False,
+ "error": "Usage: <command> [json_data]",
+ "commands": list(COMMANDS.keys()),
+ }, indent=2)
+
+ command = args[0]
+ json_data = args[1] if len(args) > 1 else "{}"
+
+ if command not in COMMANDS:
+ return json.dumps({
+ "success": False,
+ "error": f"Unknown command: {command}",
+ "available_commands": list(COMMANDS.keys()),
+ }, indent=2)
+
+ handler = COMMANDS[command]
+
+ # Commands that don't need JSON input
+ no_input_commands = ["list_agent_presets", "list_team_presets", "get_config_schema", "health_check"]
+
+ if command in no_input_commands:
+ return handler()
+ else:
+ return handler(json_data)
+
+
+if __name__ == "__main__":
+ result = main(sys.argv[1:])
+ print(result)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/schemas/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/schemas/__init__.py
new file mode 100644
index 000000000..59dc991da
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/schemas/__init__.py
@@ -0,0 +1,92 @@
+"""
+Renaissance Technologies Configuration Schemas
+
+Comprehensive configuration schemas for frontend integration.
+All Agno parameters are exposed for full customization.
+
+Usage from CLI:
+ python rentech_cli.py create_agent '{"name": "Research", "model": {"temperature": 0.3}}'
+ python rentech_cli.py run_team '{"name": "IC", "task": "Analyze AAPL signal"}'
+
+Usage from Python:
+ from schemas import AgentConfig, TeamConfig
+
+ config = AgentConfig.from_json(json_string)
+ agent = create_agent_from_config(config)
+"""
+
+from .agent_config import (
+ # Core config
+ AgentConfig,
+ # Settings groups
+ ModelSettings,
+ MemorySettings,
+ KnowledgeSettings,
+ ReasoningSettings,
+ ToolSettings,
+ OutputSettings,
+ ContextSettings,
+ StreamingSettings,
+ MediaSettings,
+ RetrySettings,
+ DebugSettings,
+ # Enums
+ ModelProvider,
+ ReferencesFormat,
+ DebugLevel,
+ # Presets
+ get_research_agent_config,
+ get_trading_agent_config,
+ get_risk_agent_config,
+ # Schema
+ get_agent_config_schema,
+)
+
+from .team_config import (
+ # Core config
+ TeamConfig,
+ # Settings groups
+ TeamDelegationSettings,
+ TeamHistorySettings,
+ TeamMemberSettings,
+ # Presets
+ get_research_team_config,
+ get_trading_team_config,
+ get_risk_team_config,
+ get_investment_committee_config,
+ # Schema
+ get_team_config_schema,
+)
+
+__all__ = [
+ # Agent config
+ "AgentConfig",
+ "ModelSettings",
+ "MemorySettings",
+ "KnowledgeSettings",
+ "ReasoningSettings",
+ "ToolSettings",
+ "OutputSettings",
+ "ContextSettings",
+ "StreamingSettings",
+ "MediaSettings",
+ "RetrySettings",
+ "DebugSettings",
+ "ModelProvider",
+ "ReferencesFormat",
+ "DebugLevel",
+ "get_research_agent_config",
+ "get_trading_agent_config",
+ "get_risk_agent_config",
+ "get_agent_config_schema",
+ # Team config
+ "TeamConfig",
+ "TeamDelegationSettings",
+ "TeamHistorySettings",
+ "TeamMemberSettings",
+ "get_research_team_config",
+ "get_trading_team_config",
+ "get_risk_team_config",
+ "get_investment_committee_config",
+ "get_team_config_schema",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/schemas/agent_config.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/schemas/agent_config.py
new file mode 100644
index 000000000..f0a9dc424
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/schemas/agent_config.py
@@ -0,0 +1,782 @@
+"""
+Agent Configuration Schema
+
+Comprehensive configuration for Agno Agents with ALL available parameters.
+Designed for frontend integration - every parameter is exposed and customizable.
+
+Usage:
+ # From CLI (JSON input)
+ config = AgentConfig.from_json(json_string)
+ agent = create_agent_from_config(config)
+
+ # From Python (uses dynamic defaults from frontend config)
+ config = AgentConfig(
+ name="My Agent",
+ instructions=["Be helpful"],
+ )
+"""
+
+from dataclasses import dataclass, field, asdict
+from typing import Optional, List, Dict, Any, Union, Literal
+from enum import Enum
+import json
+
+
+class ModelProvider(str, Enum):
+ """Supported LLM providers"""
+ OPENAI = "openai"
+ ANTHROPIC = "anthropic"
+ OLLAMA = "ollama"
+ GROQ = "groq"
+ ZHIPUAI = "zhipuai"
+ OPENAI_LIKE = "openai_like"
+
+
+class ReferencesFormat(str, Enum):
+ """Format for knowledge references"""
+ JSON = "json"
+ YAML = "yaml"
+
+
+class DebugLevel(int, Enum):
+ """Debug verbosity levels"""
+ MINIMAL = 1
+ VERBOSE = 2
+
+
+def _get_default_provider() -> str:
+ """Get default provider from frontend config"""
+ try:
+ # Import here to avoid circular dependency
+ import sys
+ import os
+ parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ if parent_dir not in sys.path:
+ sys.path.insert(0, parent_dir)
+ from utils.model_factory import get_default_model_settings
+ return get_default_model_settings()["provider"]
+ except Exception:
+ return "openai" # Final fallback
+
+
+def _get_default_model_id() -> str:
+ """Get default model ID from frontend config"""
+ try:
+ import sys
+ import os
+ parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ if parent_dir not in sys.path:
+ sys.path.insert(0, parent_dir)
+ from utils.model_factory import get_default_model_settings
+ return get_default_model_settings()["model_id"]
+ except Exception:
+ return "gpt-4o" # Final fallback
+
+
+def _get_default_temperature() -> float:
+ """Get default temperature from frontend config"""
+ try:
+ import sys
+ import os
+ parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ if parent_dir not in sys.path:
+ sys.path.insert(0, parent_dir)
+ from utils.model_factory import get_default_model_settings
+ return get_default_model_settings()["temperature"]
+ except Exception:
+ return 0.7
+
+
+def _get_default_max_tokens() -> int:
+ """Get default max_tokens from frontend config"""
+ try:
+ import sys
+ import os
+ parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ if parent_dir not in sys.path:
+ sys.path.insert(0, parent_dir)
+ from utils.model_factory import get_default_model_settings
+ return get_default_model_settings()["max_tokens"]
+ except Exception:
+ return 4096
+
+
+@dataclass
+class ModelSettings:
+ """
+ Model-specific settings.
+ Configure the LLM provider and model parameters.
+
+ Defaults are loaded dynamically from frontend configuration.
+ If no frontend config exists, falls back to OpenAI GPT-4o.
+ """
+ # Provider selection (loaded from frontend config)
+ provider: str = field(default_factory=_get_default_provider)
+ model_id: str = field(default_factory=_get_default_model_id)
+
+ # API configuration
+ api_key: Optional[str] = None
+ base_url: Optional[str] = None
+
+ # Generation parameters (loaded from frontend config)
+ temperature: float = field(default_factory=_get_default_temperature)
+ max_tokens: int = field(default_factory=_get_default_max_tokens)
+ top_p: Optional[float] = None
+ frequency_penalty: Optional[float] = None
+ presence_penalty: Optional[float] = None
+ stop_sequences: Optional[List[str]] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {k: v for k, v in asdict(self).items() if v is not None}
+
+
+@dataclass
+class MemorySettings:
+ """
+ Memory and session management settings.
+ Controls how agents remember and learn.
+ """
+ # Session management
+ user_id: Optional[str] = None
+ session_id: Optional[str] = None
+ session_state: Optional[Dict[str, Any]] = None
+ add_session_state_to_context: bool = False
+ overwrite_db_session_state: bool = False
+ enable_agentic_state: bool = False
+ cache_session: bool = False
+
+ # Memory features
+ enable_agentic_memory: bool = False
+ enable_user_memories: bool = False
+ add_memories_to_context: Optional[bool] = None
+
+ # Session summaries
+ enable_session_summaries: bool = False
+ add_session_summary_to_context: Optional[bool] = None
+
+ # History search
+ search_session_history: bool = False
+ num_history_sessions: Optional[int] = None
+
+ # Context history
+ add_history_to_context: bool = False
+ num_history_runs: Optional[int] = None
+ num_history_messages: Optional[int] = None
+ max_tool_calls_from_history: Optional[int] = None
+
+ # Compression
+ compress_tool_results: bool = False
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {k: v for k, v in asdict(self).items() if v is not None}
+
+
+@dataclass
+class KnowledgeSettings:
+ """
+ Knowledge base settings.
+ Controls how agents access and use knowledge.
+ """
+ # Knowledge base (set at runtime if using external KB)
+ knowledge_filters: Optional[Dict[str, Any]] = None
+ add_knowledge_to_context: bool = False
+ enable_agentic_knowledge_filters: Optional[bool] = None
+ update_knowledge: bool = False
+ search_knowledge: bool = True
+ references_format: ReferencesFormat = ReferencesFormat.JSON
+
+ def to_dict(self) -> Dict[str, Any]:
+ result = {}
+ for k, v in asdict(self).items():
+ if v is not None:
+ if isinstance(v, Enum):
+ result[k] = v.value
+ else:
+ result[k] = v
+ return result
+
+
+@dataclass
+class ReasoningSettings:
+ """
+ Reasoning and chain-of-thought settings.
+ Controls advanced reasoning capabilities.
+ """
+ reasoning: bool = False
+ reasoning_min_steps: int = 1
+ reasoning_max_steps: int = 10
+ # reasoning_model and reasoning_agent set at runtime
+
+ def to_dict(self) -> Dict[str, Any]:
+ return asdict(self)
+
+
+@dataclass
+class ToolSettings:
+ """
+ Tool usage settings.
+ Controls how agents use tools and functions.
+ """
+ # Tool limits
+ tool_call_limit: Optional[int] = None
+ tool_choice: Optional[Union[str, Dict[str, Any]]] = None
+
+ # Tool behavior
+ read_tool_call_history: bool = False
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {k: v for k, v in asdict(self).items() if v is not None}
+
+
+@dataclass
+class OutputSettings:
+ """
+ Output and parsing settings.
+ Controls response format and parsing.
+ """
+ # Response format
+ markdown: bool = False
+ use_json_mode: bool = False
+ parse_response: bool = True
+
+ # Schema enforcement (set input_schema/output_schema at runtime)
+ structured_outputs: Optional[bool] = None
+
+ # File output
+ save_response_to_file: Optional[str] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {k: v for k, v in asdict(self).items() if v is not None}
+
+
+@dataclass
+class ContextSettings:
+ """
+ Context building settings.
+ Controls what information is added to agent context.
+ """
+ build_context: bool = True
+ build_user_context: bool = True
+ resolve_in_context: bool = True
+
+ # Context additions
+ add_name_to_context: bool = False
+ add_datetime_to_context: bool = False
+ add_location_to_context: bool = False
+ timezone_identifier: Optional[str] = None
+ add_dependencies_to_context: bool = False
+
+ # Additional context (free-form)
+ additional_context: Optional[str] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {k: v for k, v in asdict(self).items() if v is not None}
+
+
+@dataclass
+class StreamingSettings:
+ """
+ Streaming and event settings.
+ Controls real-time response streaming.
+ """
+ stream: Optional[bool] = None
+ stream_events: Optional[bool] = None
+ stream_intermediate_steps: Optional[bool] = None
+ store_events: bool = False
+ events_to_skip: Optional[List[str]] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {k: v for k, v in asdict(self).items() if v is not None}
+
+
+@dataclass
+class MediaSettings:
+ """
+ Media handling settings.
+ Controls how agents handle files and media.
+ """
+ store_media: bool = True
+ store_tool_messages: bool = True
+ store_history_messages: bool = True
+ send_media_to_model: bool = True
+
+ def to_dict(self) -> Dict[str, Any]:
+ return asdict(self)
+
+
+@dataclass
+class RetrySettings:
+ """
+ Retry and error handling settings.
+ Controls retry behavior on failures.
+ """
+ retries: int = 0
+ delay_between_retries: int = 1
+ exponential_backoff: bool = False
+
+ def to_dict(self) -> Dict[str, Any]:
+ return asdict(self)
+
+
+@dataclass
+class DebugSettings:
+ """
+ Debug and telemetry settings.
+ Controls logging and observability.
+ """
+ debug_mode: bool = False
+ debug_level: DebugLevel = DebugLevel.MINIMAL
+ telemetry: bool = True
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "debug_mode": self.debug_mode,
+ "debug_level": self.debug_level.value,
+ "telemetry": self.telemetry,
+ }
+
+
+@dataclass
+class AgentConfig:
+ """
+ Complete Agent Configuration.
+
+ Contains ALL Agno Agent parameters organized into logical groups.
+ Use this for full customization when creating agents from frontend.
+
+ Example JSON input:
+ {
+ "name": "Research Analyst",
+ "role": "signal_validation",
+ "description": "Validates trading signals",
+ "instructions": ["Analyze signals", "Check p-values"],
+ "model": {
+ "temperature": 0.7
+ },
+ "memory": {
+ "enable_agentic_memory": true
+ },
+ "reasoning": {
+ "reasoning": true,
+ "reasoning_max_steps": 5
+ }
+ }
+
+ Note: provider and model_id are loaded from frontend config if not specified.
+ """
+ # Core identity
+ name: Optional[str] = None
+ id: Optional[str] = None
+ role: Optional[str] = None
+ description: Optional[str] = None
+
+ # Instructions (can be string or list)
+ instructions: Optional[Union[str, List[str]]] = None
+ expected_output: Optional[str] = None
+ introduction: Optional[str] = None
+ system_message: Optional[str] = None
+ system_message_role: str = "system"
+ user_message_role: str = "user"
+
+ # Grouped settings
+ model: ModelSettings = field(default_factory=ModelSettings)
+ memory: MemorySettings = field(default_factory=MemorySettings)
+ knowledge: KnowledgeSettings = field(default_factory=KnowledgeSettings)
+ reasoning: ReasoningSettings = field(default_factory=ReasoningSettings)
+ tools: ToolSettings = field(default_factory=ToolSettings)
+ output: OutputSettings = field(default_factory=OutputSettings)
+ context: ContextSettings = field(default_factory=ContextSettings)
+ streaming: StreamingSettings = field(default_factory=StreamingSettings)
+ media: MediaSettings = field(default_factory=MediaSettings)
+ retry: RetrySettings = field(default_factory=RetrySettings)
+ debug: DebugSettings = field(default_factory=DebugSettings)
+
+ # Metadata
+ metadata: Optional[Dict[str, Any]] = None
+ dependencies: Optional[Dict[str, Any]] = None
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "AgentConfig":
+ """Create AgentConfig from dictionary (e.g., parsed JSON)"""
+ # Extract nested settings
+ model_data = data.pop("model", {})
+ memory_data = data.pop("memory", {})
+ knowledge_data = data.pop("knowledge", {})
+ reasoning_data = data.pop("reasoning", {})
+ tools_data = data.pop("tools", {})
+ output_data = data.pop("output", {})
+ context_data = data.pop("context", {})
+ streaming_data = data.pop("streaming", {})
+ media_data = data.pop("media", {})
+ retry_data = data.pop("retry", {})
+ debug_data = data.pop("debug", {})
+
+ # Handle enum conversions
+ if "provider" in model_data and isinstance(model_data["provider"], str):
+ model_data["provider"] = ModelProvider(model_data["provider"])
+ if "references_format" in knowledge_data and isinstance(knowledge_data["references_format"], str):
+ knowledge_data["references_format"] = ReferencesFormat(knowledge_data["references_format"])
+ if "debug_level" in debug_data and isinstance(debug_data["debug_level"], int):
+ debug_data["debug_level"] = DebugLevel(debug_data["debug_level"])
+
+ return cls(
+ **data,
+ model=ModelSettings(**model_data) if model_data else ModelSettings(),
+ memory=MemorySettings(**memory_data) if memory_data else MemorySettings(),
+ knowledge=KnowledgeSettings(**knowledge_data) if knowledge_data else KnowledgeSettings(),
+ reasoning=ReasoningSettings(**reasoning_data) if reasoning_data else ReasoningSettings(),
+ tools=ToolSettings(**tools_data) if tools_data else ToolSettings(),
+ output=OutputSettings(**output_data) if output_data else OutputSettings(),
+ context=ContextSettings(**context_data) if context_data else ContextSettings(),
+ streaming=StreamingSettings(**streaming_data) if streaming_data else StreamingSettings(),
+ media=MediaSettings(**media_data) if media_data else MediaSettings(),
+ retry=RetrySettings(**retry_data) if retry_data else RetrySettings(),
+ debug=DebugSettings(**debug_data) if debug_data else DebugSettings(),
+ )
+
+ @classmethod
+ def from_json(cls, json_str: str) -> "AgentConfig":
+ """Create AgentConfig from JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary for serialization"""
+ result = {
+ "name": self.name,
+ "id": self.id,
+ "role": self.role,
+ "description": self.description,
+ "instructions": self.instructions,
+ "expected_output": self.expected_output,
+ "introduction": self.introduction,
+ "system_message": self.system_message,
+ "system_message_role": self.system_message_role,
+ "user_message_role": self.user_message_role,
+ "model": self.model.to_dict(),
+ "memory": self.memory.to_dict(),
+ "knowledge": self.knowledge.to_dict(),
+ "reasoning": self.reasoning.to_dict(),
+ "tools": self.tools.to_dict(),
+ "output": self.output.to_dict(),
+ "context": self.context.to_dict(),
+ "streaming": self.streaming.to_dict(),
+ "media": self.media.to_dict(),
+ "retry": self.retry.to_dict(),
+ "debug": self.debug.to_dict(),
+ "metadata": self.metadata,
+ "dependencies": self.dependencies,
+ }
+ # Remove None values at top level
+ return {k: v for k, v in result.items() if v is not None}
+
+ def to_json(self, indent: int = 2) -> str:
+ """Convert to JSON string"""
+ return json.dumps(self.to_dict(), indent=indent, default=str)
+
+ def to_agno_kwargs(self) -> Dict[str, Any]:
+ """
+ Convert to kwargs dict for Agno Agent constructor.
+ Flattens the nested structure into Agno's flat parameter list.
+ """
+ kwargs = {}
+
+ # Core identity
+ if self.name:
+ kwargs["name"] = self.name
+ if self.id:
+ kwargs["id"] = self.id
+ if self.role:
+ kwargs["role"] = self.role
+ if self.description:
+ kwargs["description"] = self.description
+ if self.instructions:
+ kwargs["instructions"] = self.instructions
+ if self.expected_output:
+ kwargs["expected_output"] = self.expected_output
+ if self.introduction:
+ kwargs["introduction"] = self.introduction
+ if self.system_message:
+ kwargs["system_message"] = self.system_message
+ kwargs["system_message_role"] = self.system_message_role
+ kwargs["user_message_role"] = self.user_message_role
+
+ # Memory settings
+ if self.memory.user_id:
+ kwargs["user_id"] = self.memory.user_id
+ if self.memory.session_id:
+ kwargs["session_id"] = self.memory.session_id
+ if self.memory.session_state:
+ kwargs["session_state"] = self.memory.session_state
+ kwargs["add_session_state_to_context"] = self.memory.add_session_state_to_context
+ kwargs["overwrite_db_session_state"] = self.memory.overwrite_db_session_state
+ kwargs["enable_agentic_state"] = self.memory.enable_agentic_state
+ kwargs["cache_session"] = self.memory.cache_session
+ kwargs["enable_agentic_memory"] = self.memory.enable_agentic_memory
+ kwargs["enable_user_memories"] = self.memory.enable_user_memories
+ if self.memory.add_memories_to_context is not None:
+ kwargs["add_memories_to_context"] = self.memory.add_memories_to_context
+ kwargs["enable_session_summaries"] = self.memory.enable_session_summaries
+ if self.memory.add_session_summary_to_context is not None:
+ kwargs["add_session_summary_to_context"] = self.memory.add_session_summary_to_context
+ kwargs["search_session_history"] = self.memory.search_session_history
+ if self.memory.num_history_sessions:
+ kwargs["num_history_sessions"] = self.memory.num_history_sessions
+ kwargs["add_history_to_context"] = self.memory.add_history_to_context
+ if self.memory.num_history_runs:
+ kwargs["num_history_runs"] = self.memory.num_history_runs
+ if self.memory.num_history_messages:
+ kwargs["num_history_messages"] = self.memory.num_history_messages
+ if self.memory.max_tool_calls_from_history:
+ kwargs["max_tool_calls_from_history"] = self.memory.max_tool_calls_from_history
+ kwargs["compress_tool_results"] = self.memory.compress_tool_results
+
+ # Knowledge settings
+ if self.knowledge.knowledge_filters:
+ kwargs["knowledge_filters"] = self.knowledge.knowledge_filters
+ kwargs["add_knowledge_to_context"] = self.knowledge.add_knowledge_to_context
+ if self.knowledge.enable_agentic_knowledge_filters is not None:
+ kwargs["enable_agentic_knowledge_filters"] = self.knowledge.enable_agentic_knowledge_filters
+ kwargs["update_knowledge"] = self.knowledge.update_knowledge
+ kwargs["search_knowledge"] = self.knowledge.search_knowledge
+ kwargs["references_format"] = self.knowledge.references_format.value
+
+ # Reasoning settings
+ kwargs["reasoning"] = self.reasoning.reasoning
+ kwargs["reasoning_min_steps"] = self.reasoning.reasoning_min_steps
+ kwargs["reasoning_max_steps"] = self.reasoning.reasoning_max_steps
+
+ # Tool settings
+ if self.tools.tool_call_limit:
+ kwargs["tool_call_limit"] = self.tools.tool_call_limit
+ if self.tools.tool_choice:
+ kwargs["tool_choice"] = self.tools.tool_choice
+ kwargs["read_tool_call_history"] = self.tools.read_tool_call_history
+
+ # Output settings
+ kwargs["markdown"] = self.output.markdown
+ kwargs["use_json_mode"] = self.output.use_json_mode
+ kwargs["parse_response"] = self.output.parse_response
+ if self.output.structured_outputs is not None:
+ kwargs["structured_outputs"] = self.output.structured_outputs
+ if self.output.save_response_to_file:
+ kwargs["save_response_to_file"] = self.output.save_response_to_file
+
+ # Context settings
+ kwargs["build_context"] = self.context.build_context
+ kwargs["build_user_context"] = self.context.build_user_context
+ kwargs["resolve_in_context"] = self.context.resolve_in_context
+ kwargs["add_name_to_context"] = self.context.add_name_to_context
+ kwargs["add_datetime_to_context"] = self.context.add_datetime_to_context
+ kwargs["add_location_to_context"] = self.context.add_location_to_context
+ if self.context.timezone_identifier:
+ kwargs["timezone_identifier"] = self.context.timezone_identifier
+ kwargs["add_dependencies_to_context"] = self.context.add_dependencies_to_context
+ if self.context.additional_context:
+ kwargs["additional_context"] = self.context.additional_context
+
+ # Streaming settings
+ if self.streaming.stream is not None:
+ kwargs["stream"] = self.streaming.stream
+ if self.streaming.stream_events is not None:
+ kwargs["stream_events"] = self.streaming.stream_events
+ if self.streaming.stream_intermediate_steps is not None:
+ kwargs["stream_intermediate_steps"] = self.streaming.stream_intermediate_steps
+ kwargs["store_events"] = self.streaming.store_events
+ if self.streaming.events_to_skip:
+ kwargs["events_to_skip"] = self.streaming.events_to_skip
+
+ # Media settings
+ kwargs["store_media"] = self.media.store_media
+ kwargs["store_tool_messages"] = self.media.store_tool_messages
+ kwargs["store_history_messages"] = self.media.store_history_messages
+ kwargs["send_media_to_model"] = self.media.send_media_to_model
+
+ # Retry settings
+ kwargs["retries"] = self.retry.retries
+ kwargs["delay_between_retries"] = self.retry.delay_between_retries
+ kwargs["exponential_backoff"] = self.retry.exponential_backoff
+
+ # Debug settings
+ kwargs["debug_mode"] = self.debug.debug_mode
+ kwargs["debug_level"] = self.debug.debug_level.value
+ kwargs["telemetry"] = self.debug.telemetry
+
+ # Metadata
+ if self.metadata:
+ kwargs["metadata"] = self.metadata
+ if self.dependencies:
+ kwargs["dependencies"] = self.dependencies
+
+ return kwargs
+
+
+# =============================================================================
+# PRESET CONFIGURATIONS
+# =============================================================================
+
+def get_research_agent_config() -> AgentConfig:
+ """
+ Preset config for research/analysis agents.
+
+ Uses dynamic model settings from frontend config.
+ Only overrides temperature for analytical tasks.
+ """
+ return AgentConfig(
+ name="Research Agent",
+ role="research",
+ description="Quantitative research and signal analysis",
+ instructions=[
+ "Analyze data with statistical rigor",
+ "Focus on p-values and significance",
+ "Provide quantitative assessments",
+ ],
+ model=ModelSettings(
+ temperature=0.3, # Lower for analytical tasks
+ ),
+ reasoning=ReasoningSettings(
+ reasoning=True,
+ reasoning_max_steps=5,
+ ),
+ output=OutputSettings(
+ markdown=True,
+ ),
+ )
+
+
+def get_trading_agent_config() -> AgentConfig:
+ """
+ Preset config for trading/execution agents.
+
+ Uses dynamic model settings from frontend config.
+ """
+ return AgentConfig(
+ name="Trading Agent",
+ role="execution",
+ description="Trade execution and market analysis",
+ instructions=[
+ "Optimize execution with minimal market impact",
+ "Consider liquidity and timing",
+ "Provide clear trade recommendations",
+ ],
+ model=ModelSettings(
+ temperature=0.5,
+ ),
+ output=OutputSettings(
+ markdown=True,
+ ),
+ )
+
+
+def get_risk_agent_config() -> AgentConfig:
+ """
+ Preset config for risk management agents.
+
+ Uses dynamic model settings from frontend config.
+ Overrides temperature to be very deterministic for risk assessment.
+ """
+ return AgentConfig(
+ name="Risk Agent",
+ role="risk_management",
+ description="Portfolio risk assessment and monitoring",
+ instructions=[
+ "Assess VaR, drawdown, and concentration risk",
+ "Flag any limit breaches immediately",
+ "Provide risk-adjusted recommendations",
+ ],
+ model=ModelSettings(
+ temperature=0.2, # Very deterministic for risk
+ ),
+ reasoning=ReasoningSettings(
+ reasoning=True,
+ reasoning_max_steps=3,
+ ),
+ output=OutputSettings(
+ markdown=True,
+ ),
+ )
+
+
+# =============================================================================
+# SCHEMA EXPORT (for frontend)
+# =============================================================================
+
+def get_agent_config_schema() -> Dict[str, Any]:
+ """
+ Get JSON schema for AgentConfig.
+ This can be sent to frontend for form generation.
+ """
+ return {
+ "type": "object",
+ "title": "Agent Configuration",
+ "description": "Complete configuration for creating an Agno Agent",
+ "properties": {
+ "name": {"type": "string", "description": "Agent name"},
+ "id": {"type": "string", "description": "Unique agent ID"},
+ "role": {"type": "string", "description": "Agent role (e.g., research, trading, risk)"},
+ "description": {"type": "string", "description": "Agent description"},
+ "instructions": {
+ "oneOf": [
+ {"type": "string"},
+ {"type": "array", "items": {"type": "string"}}
+ ],
+ "description": "Agent instructions"
+ },
+ "model": {
+ "type": "object",
+ "description": "Model settings. Defaults loaded from frontend config.",
+ "properties": {
+ "provider": {
+ "type": "string",
+ "description": "LLM provider. Defaults to active frontend config.",
+ "enum": ["openai", "anthropic", "google", "groq", "ollama", "mistral", "deepseek", "cohere", "x-ai", "perplexity", "openrouter", "openai_like"]
+ },
+ "model_id": {
+ "type": "string",
+ "description": "Model ID. Defaults to active frontend config."
+ },
+ "api_key": {"type": "string", "description": "Optional API key override"},
+ "base_url": {"type": "string", "description": "Optional base URL override"},
+ "temperature": {
+ "type": "number",
+ "minimum": 0,
+ "maximum": 2,
+ "description": "Sampling temperature. Defaults to frontend config."
+ },
+ "max_tokens": {
+ "type": "integer",
+ "description": "Max output tokens. Defaults to frontend config."
+ },
+ }
+ },
+ "memory": {
+ "type": "object",
+ "properties": {
+ "enable_agentic_memory": {"type": "boolean", "default": False},
+ "enable_user_memories": {"type": "boolean", "default": False},
+ "enable_session_summaries": {"type": "boolean", "default": False},
+ }
+ },
+ "reasoning": {
+ "type": "object",
+ "properties": {
+ "reasoning": {"type": "boolean", "default": False},
+ "reasoning_min_steps": {"type": "integer", "default": 1},
+ "reasoning_max_steps": {"type": "integer", "default": 10},
+ }
+ },
+ "output": {
+ "type": "object",
+ "properties": {
+ "markdown": {"type": "boolean", "default": False},
+ "use_json_mode": {"type": "boolean", "default": False},
+ }
+ },
+ "debug": {
+ "type": "object",
+ "properties": {
+ "debug_mode": {"type": "boolean", "default": False},
+ "debug_level": {"type": "integer", "enum": [1, 2], "default": 1},
+ }
+ }
+ }
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/schemas/team_config.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/schemas/team_config.py
new file mode 100644
index 000000000..327fd090a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/schemas/team_config.py
@@ -0,0 +1,555 @@
+"""
+Team Configuration Schema
+
+Comprehensive configuration for Agno Teams with ALL available parameters.
+Designed for frontend integration - every parameter is exposed and customizable.
+
+Usage:
+ # From CLI (JSON input)
+ config = TeamConfig.from_json(json_string)
+ team = create_team_from_config(config)
+
+ # From Python
+ config = TeamConfig(
+ name="Research Team",
+ member_configs=[agent1_config, agent2_config],
+ share_member_interactions=True,
+ )
+"""
+
+from dataclasses import dataclass, field, asdict
+from typing import Optional, List, Dict, Any, Union
+from enum import Enum
+import json
+
+from .agent_config import (
+ AgentConfig,
+ ModelSettings,
+ MemorySettings,
+ KnowledgeSettings,
+ ReasoningSettings,
+ ContextSettings,
+ StreamingSettings,
+ MediaSettings,
+ RetrySettings,
+ DebugSettings,
+ ModelProvider,
+ ReferencesFormat,
+ DebugLevel,
+)
+
+
+@dataclass
+class TeamDelegationSettings:
+ """
+ Team task delegation settings.
+ Controls how tasks are routed to team members.
+ """
+ respond_directly: bool = False
+ determine_input_for_members: bool = True
+ delegate_task_to_all_members: bool = False
+ delegate_to_all_members: bool = False
+
+ def to_dict(self) -> Dict[str, Any]:
+ return asdict(self)
+
+
+@dataclass
+class TeamHistorySettings:
+ """
+ Team history and context sharing settings.
+ Controls how team members share information.
+ """
+ add_team_history_to_members: bool = False
+ num_team_history_runs: int = 3
+ share_member_interactions: bool = False
+ get_member_information_tool: bool = False
+
+ def to_dict(self) -> Dict[str, Any]:
+ return asdict(self)
+
+
+@dataclass
+class TeamMemberSettings:
+ """
+ Team member display settings.
+ Controls how member responses are handled.
+ """
+ store_member_responses: bool = False
+ stream_member_events: bool = True
+ show_members_responses: bool = False
+ add_member_tools_to_context: bool = False
+
+ def to_dict(self) -> Dict[str, Any]:
+ return asdict(self)
+
+
+@dataclass
+class TeamConfig:
+ """
+ Complete Team Configuration.
+
+ Contains ALL Agno Team parameters organized into logical groups.
+ Use this for full customization when creating teams from frontend.
+
+ Example JSON input:
+ {
+ "name": "Investment Committee",
+ "description": "Makes trading decisions",
+ "member_configs": [
+ {"name": "Research Lead", "role": "research", ...},
+ {"name": "Risk Officer", "role": "risk", ...}
+ ],
+ "delegation": {
+ "determine_input_for_members": true
+ },
+ "history": {
+ "share_member_interactions": true,
+ "add_team_history_to_members": true
+ }
+ }
+ """
+ # Core identity
+ name: Optional[str] = None
+ id: Optional[str] = None
+ role: Optional[str] = None
+ description: Optional[str] = None
+
+ # Instructions
+ instructions: Optional[Union[str, List[str]]] = None
+ expected_output: Optional[str] = None
+ introduction: Optional[str] = None
+ system_message: Optional[str] = None
+ system_message_role: str = "system"
+
+ # Member configurations (list of AgentConfig)
+ member_configs: List[AgentConfig] = field(default_factory=list)
+
+ # Grouped settings
+ model: ModelSettings = field(default_factory=ModelSettings)
+ delegation: TeamDelegationSettings = field(default_factory=TeamDelegationSettings)
+ history: TeamHistorySettings = field(default_factory=TeamHistorySettings)
+ member_display: TeamMemberSettings = field(default_factory=TeamMemberSettings)
+ memory: MemorySettings = field(default_factory=MemorySettings)
+ knowledge: KnowledgeSettings = field(default_factory=KnowledgeSettings)
+ reasoning: ReasoningSettings = field(default_factory=ReasoningSettings)
+ context: ContextSettings = field(default_factory=ContextSettings)
+ streaming: StreamingSettings = field(default_factory=StreamingSettings)
+ media: MediaSettings = field(default_factory=MediaSettings)
+ retry: RetrySettings = field(default_factory=RetrySettings)
+ debug: DebugSettings = field(default_factory=DebugSettings)
+
+ # Metadata
+ metadata: Optional[Dict[str, Any]] = None
+ dependencies: Optional[Dict[str, Any]] = None
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "TeamConfig":
+ """Create TeamConfig from dictionary (e.g., parsed JSON)"""
+ # Extract member configs
+ member_configs_data = data.pop("member_configs", [])
+ member_configs = [
+ AgentConfig.from_dict(m) if isinstance(m, dict) else m
+ for m in member_configs_data
+ ]
+
+ # Extract nested settings
+ model_data = data.pop("model", {})
+ delegation_data = data.pop("delegation", {})
+ history_data = data.pop("history", {})
+ member_display_data = data.pop("member_display", {})
+ memory_data = data.pop("memory", {})
+ knowledge_data = data.pop("knowledge", {})
+ reasoning_data = data.pop("reasoning", {})
+ context_data = data.pop("context", {})
+ streaming_data = data.pop("streaming", {})
+ media_data = data.pop("media", {})
+ retry_data = data.pop("retry", {})
+ debug_data = data.pop("debug", {})
+
+ # Handle enum conversions
+ if "provider" in model_data and isinstance(model_data["provider"], str):
+ model_data["provider"] = ModelProvider(model_data["provider"])
+ if "references_format" in knowledge_data and isinstance(knowledge_data["references_format"], str):
+ knowledge_data["references_format"] = ReferencesFormat(knowledge_data["references_format"])
+ if "debug_level" in debug_data and isinstance(debug_data["debug_level"], int):
+ debug_data["debug_level"] = DebugLevel(debug_data["debug_level"])
+
+ return cls(
+ **data,
+ member_configs=member_configs,
+ model=ModelSettings(**model_data) if model_data else ModelSettings(),
+ delegation=TeamDelegationSettings(**delegation_data) if delegation_data else TeamDelegationSettings(),
+ history=TeamHistorySettings(**history_data) if history_data else TeamHistorySettings(),
+ member_display=TeamMemberSettings(**member_display_data) if member_display_data else TeamMemberSettings(),
+ memory=MemorySettings(**memory_data) if memory_data else MemorySettings(),
+ knowledge=KnowledgeSettings(**knowledge_data) if knowledge_data else KnowledgeSettings(),
+ reasoning=ReasoningSettings(**reasoning_data) if reasoning_data else ReasoningSettings(),
+ context=ContextSettings(**context_data) if context_data else ContextSettings(),
+ streaming=StreamingSettings(**streaming_data) if streaming_data else StreamingSettings(),
+ media=MediaSettings(**media_data) if media_data else MediaSettings(),
+ retry=RetrySettings(**retry_data) if retry_data else RetrySettings(),
+ debug=DebugSettings(**debug_data) if debug_data else DebugSettings(),
+ )
+
+ @classmethod
+ def from_json(cls, json_str: str) -> "TeamConfig":
+ """Create TeamConfig from JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary for serialization"""
+ result = {
+ "name": self.name,
+ "id": self.id,
+ "role": self.role,
+ "description": self.description,
+ "instructions": self.instructions,
+ "expected_output": self.expected_output,
+ "introduction": self.introduction,
+ "system_message": self.system_message,
+ "system_message_role": self.system_message_role,
+ "member_configs": [m.to_dict() for m in self.member_configs],
+ "model": self.model.to_dict(),
+ "delegation": self.delegation.to_dict(),
+ "history": self.history.to_dict(),
+ "member_display": self.member_display.to_dict(),
+ "memory": self.memory.to_dict(),
+ "knowledge": self.knowledge.to_dict(),
+ "reasoning": self.reasoning.to_dict(),
+ "context": self.context.to_dict(),
+ "streaming": self.streaming.to_dict(),
+ "media": self.media.to_dict(),
+ "retry": self.retry.to_dict(),
+ "debug": self.debug.to_dict(),
+ "metadata": self.metadata,
+ "dependencies": self.dependencies,
+ }
+ return {k: v for k, v in result.items() if v is not None}
+
+ def to_json(self, indent: int = 2) -> str:
+ """Convert to JSON string"""
+ return json.dumps(self.to_dict(), indent=indent, default=str)
+
+ def to_agno_kwargs(self) -> Dict[str, Any]:
+ """
+ Convert to kwargs dict for Agno Team constructor.
+ Flattens the nested structure into Agno's flat parameter list.
+
+ Note: 'members' must be created separately from member_configs
+ """
+ kwargs = {}
+
+ # Core identity
+ if self.name:
+ kwargs["name"] = self.name
+ if self.id:
+ kwargs["id"] = self.id
+ if self.role:
+ kwargs["role"] = self.role
+ if self.description:
+ kwargs["description"] = self.description
+ if self.instructions:
+ kwargs["instructions"] = self.instructions
+ if self.expected_output:
+ kwargs["expected_output"] = self.expected_output
+ if self.introduction:
+ kwargs["introduction"] = self.introduction
+ if self.system_message:
+ kwargs["system_message"] = self.system_message
+ kwargs["system_message_role"] = self.system_message_role
+
+ # Delegation settings
+ kwargs["respond_directly"] = self.delegation.respond_directly
+ kwargs["determine_input_for_members"] = self.delegation.determine_input_for_members
+ kwargs["delegate_task_to_all_members"] = self.delegation.delegate_task_to_all_members
+ kwargs["delegate_to_all_members"] = self.delegation.delegate_to_all_members
+
+ # History settings
+ kwargs["add_team_history_to_members"] = self.history.add_team_history_to_members
+ kwargs["num_team_history_runs"] = self.history.num_team_history_runs
+ kwargs["share_member_interactions"] = self.history.share_member_interactions
+ kwargs["get_member_information_tool"] = self.history.get_member_information_tool
+
+ # Member display settings
+ kwargs["store_member_responses"] = self.member_display.store_member_responses
+ kwargs["stream_member_events"] = self.member_display.stream_member_events
+ kwargs["show_members_responses"] = self.member_display.show_members_responses
+ kwargs["add_member_tools_to_context"] = self.member_display.add_member_tools_to_context
+
+ # Memory settings
+ if self.memory.user_id:
+ kwargs["user_id"] = self.memory.user_id
+ if self.memory.session_id:
+ kwargs["session_id"] = self.memory.session_id
+ if self.memory.session_state:
+ kwargs["session_state"] = self.memory.session_state
+ kwargs["add_session_state_to_context"] = self.memory.add_session_state_to_context
+ kwargs["overwrite_db_session_state"] = self.memory.overwrite_db_session_state
+ kwargs["enable_agentic_state"] = self.memory.enable_agentic_state
+ kwargs["cache_session"] = self.memory.cache_session
+ kwargs["enable_agentic_memory"] = self.memory.enable_agentic_memory
+ kwargs["enable_user_memories"] = self.memory.enable_user_memories
+ if self.memory.add_memories_to_context is not None:
+ kwargs["add_memories_to_context"] = self.memory.add_memories_to_context
+ kwargs["enable_session_summaries"] = self.memory.enable_session_summaries
+ if self.memory.add_session_summary_to_context is not None:
+ kwargs["add_session_summary_to_context"] = self.memory.add_session_summary_to_context
+ kwargs["search_session_history"] = self.memory.search_session_history
+ if self.memory.num_history_sessions:
+ kwargs["num_history_sessions"] = self.memory.num_history_sessions
+ kwargs["add_history_to_context"] = self.memory.add_history_to_context
+ if self.memory.num_history_runs:
+ kwargs["num_history_runs"] = self.memory.num_history_runs
+ if self.memory.num_history_messages:
+ kwargs["num_history_messages"] = self.memory.num_history_messages
+ if self.memory.max_tool_calls_from_history:
+ kwargs["max_tool_calls_from_history"] = self.memory.max_tool_calls_from_history
+ kwargs["compress_tool_results"] = self.memory.compress_tool_results
+
+ # Knowledge settings
+ if self.knowledge.knowledge_filters:
+ kwargs["knowledge_filters"] = self.knowledge.knowledge_filters
+ kwargs["add_knowledge_to_context"] = self.knowledge.add_knowledge_to_context
+ if self.knowledge.enable_agentic_knowledge_filters is not None:
+ kwargs["enable_agentic_knowledge_filters"] = self.knowledge.enable_agentic_knowledge_filters
+ kwargs["update_knowledge"] = self.knowledge.update_knowledge
+ kwargs["search_knowledge"] = self.knowledge.search_knowledge
+ kwargs["references_format"] = self.knowledge.references_format.value
+
+ # Reasoning settings
+ kwargs["reasoning"] = self.reasoning.reasoning
+ kwargs["reasoning_min_steps"] = self.reasoning.reasoning_min_steps
+ kwargs["reasoning_max_steps"] = self.reasoning.reasoning_max_steps
+
+ # Context settings
+ kwargs["resolve_in_context"] = self.context.resolve_in_context
+ kwargs["add_name_to_context"] = self.context.add_name_to_context
+ kwargs["add_datetime_to_context"] = self.context.add_datetime_to_context
+ kwargs["add_location_to_context"] = self.context.add_location_to_context
+ if self.context.timezone_identifier:
+ kwargs["timezone_identifier"] = self.context.timezone_identifier
+ kwargs["add_dependencies_to_context"] = self.context.add_dependencies_to_context
+ if self.context.additional_context:
+ kwargs["additional_context"] = self.context.additional_context
+
+ # Streaming settings
+ if self.streaming.stream is not None:
+ kwargs["stream"] = self.streaming.stream
+ if self.streaming.stream_events is not None:
+ kwargs["stream_events"] = self.streaming.stream_events
+ if self.streaming.stream_intermediate_steps is not None:
+ kwargs["stream_intermediate_steps"] = self.streaming.stream_intermediate_steps
+ kwargs["store_events"] = self.streaming.store_events
+ if self.streaming.events_to_skip:
+ kwargs["events_to_skip"] = self.streaming.events_to_skip
+
+ # Media settings
+ kwargs["store_media"] = self.media.store_media
+ kwargs["store_tool_messages"] = self.media.store_tool_messages
+ kwargs["store_history_messages"] = self.media.store_history_messages
+ kwargs["send_media_to_model"] = self.media.send_media_to_model
+
+ # Retry settings
+ kwargs["retries"] = self.retry.retries
+ kwargs["delay_between_retries"] = self.retry.delay_between_retries
+ kwargs["exponential_backoff"] = self.retry.exponential_backoff
+
+ # Debug settings
+ kwargs["debug_mode"] = self.debug.debug_mode
+ kwargs["debug_level"] = self.debug.debug_level.value
+ kwargs["telemetry"] = self.debug.telemetry
+
+ # Output
+ kwargs["markdown"] = True # Default for teams
+
+ # Metadata
+ if self.metadata:
+ kwargs["metadata"] = self.metadata
+ if self.dependencies:
+ kwargs["dependencies"] = self.dependencies
+
+ return kwargs
+
+
+# =============================================================================
+# PRESET TEAM CONFIGURATIONS
+# =============================================================================
+
+def get_research_team_config() -> TeamConfig:
+ """Preset config for research team"""
+ from .agent_config import get_research_agent_config
+
+ return TeamConfig(
+ name="Quantitative Research Team",
+ role="research",
+ description="Alpha generation team for signal discovery and validation",
+ instructions=[
+ "Collaborate on signal research",
+ "Validate statistical significance",
+ "Share findings with precision",
+ ],
+ member_configs=[
+ get_research_agent_config(),
+ ],
+ history=TeamHistorySettings(
+ share_member_interactions=True,
+ add_team_history_to_members=True,
+ ),
+ member_display=TeamMemberSettings(
+ show_members_responses=True,
+ ),
+ )
+
+
+def get_trading_team_config() -> TeamConfig:
+ """Preset config for trading team"""
+ from .agent_config import get_trading_agent_config
+
+ return TeamConfig(
+ name="Trading Execution Team",
+ role="execution",
+ description="Trade execution and market making team",
+ instructions=[
+ "Optimize trade execution",
+ "Minimize market impact",
+ "Coordinate order routing",
+ ],
+ member_configs=[
+ get_trading_agent_config(),
+ ],
+ history=TeamHistorySettings(
+ share_member_interactions=True,
+ ),
+ )
+
+
+def get_risk_team_config() -> TeamConfig:
+ """Preset config for risk team"""
+ from .agent_config import get_risk_agent_config
+
+ return TeamConfig(
+ name="Risk Management Team",
+ role="risk",
+ description="Portfolio risk monitoring and compliance",
+ instructions=[
+ "Monitor all risk limits",
+ "Flag breaches immediately",
+ "Provide risk assessments",
+ ],
+ member_configs=[
+ get_risk_agent_config(),
+ ],
+ reasoning=ReasoningSettings(
+ reasoning=True,
+ reasoning_max_steps=3,
+ ),
+ )
+
+
+def get_investment_committee_config() -> TeamConfig:
+ """Preset config for full Investment Committee"""
+ from .agent_config import (
+ get_research_agent_config,
+ get_trading_agent_config,
+ get_risk_agent_config,
+ )
+
+ pm_config = AgentConfig(
+ name="Portfolio Manager",
+ role="decision_maker",
+ description="Makes final trading decisions",
+ instructions=[
+ "Synthesize team inputs",
+ "Make APPROVE/REJECT decisions",
+ "Set position sizes",
+ ],
+ model=ModelSettings(temperature=0.3),
+ output=OutputSettings(markdown=True),
+ )
+
+ return TeamConfig(
+ name="Investment Committee",
+ role="decision",
+ description="Top-level decision-making body for trading decisions",
+ instructions=[
+ "Research validates signal",
+ "Risk assesses impact",
+ "Trading plans execution",
+ "PM makes final decision",
+ ],
+ member_configs=[
+ pm_config,
+ get_research_agent_config(),
+ get_risk_agent_config(),
+ get_trading_agent_config(),
+ ],
+ history=TeamHistorySettings(
+ share_member_interactions=True,
+ add_team_history_to_members=True,
+ ),
+ member_display=TeamMemberSettings(
+ show_members_responses=True,
+ ),
+ reasoning=ReasoningSettings(
+ reasoning=True,
+ reasoning_max_steps=5,
+ ),
+ )
+
+
+# =============================================================================
+# SCHEMA EXPORT (for frontend)
+# =============================================================================
+
+def get_team_config_schema() -> Dict[str, Any]:
+ """
+ Get JSON schema for TeamConfig.
+ This can be sent to frontend for form generation.
+ """
+ return {
+ "type": "object",
+ "title": "Team Configuration",
+ "description": "Complete configuration for creating an Agno Team",
+ "properties": {
+ "name": {"type": "string", "description": "Team name"},
+ "id": {"type": "string", "description": "Unique team ID"},
+ "role": {"type": "string", "description": "Team role"},
+ "description": {"type": "string", "description": "Team description"},
+ "instructions": {
+ "oneOf": [
+ {"type": "string"},
+ {"type": "array", "items": {"type": "string"}}
+ ],
+ "description": "Team instructions"
+ },
+ "member_configs": {
+ "type": "array",
+ "items": {"$ref": "#/definitions/AgentConfig"},
+ "description": "Configuration for each team member"
+ },
+ "delegation": {
+ "type": "object",
+ "properties": {
+ "respond_directly": {"type": "boolean", "default": False},
+ "determine_input_for_members": {"type": "boolean", "default": True},
+ "delegate_task_to_all_members": {"type": "boolean", "default": False},
+ }
+ },
+ "history": {
+ "type": "object",
+ "properties": {
+ "share_member_interactions": {"type": "boolean", "default": False},
+ "add_team_history_to_members": {"type": "boolean", "default": False},
+ "num_team_history_runs": {"type": "integer", "default": 3},
+ }
+ },
+ "member_display": {
+ "type": "object",
+ "properties": {
+ "show_members_responses": {"type": "boolean", "default": False},
+ "store_member_responses": {"type": "boolean", "default": False},
+ }
+ }
+ }
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/__init__.py
new file mode 100644
index 000000000..fd3ba405f
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/__init__.py
@@ -0,0 +1,119 @@
+"""Renaissance Technologies quantitative strategies."""
+
+from .mean_reversion import (
+ MeanReversionResult,
+ analyze_mean_reversion,
+ analyze_pairs_cointegration,
+ calculate_z_score,
+ estimate_half_life,
+ calculate_hurst_exponent,
+)
+
+from .momentum import (
+ MomentumResult,
+ analyze_momentum,
+ calculate_momentum_score,
+ calculate_trend_strength,
+ calculate_acceleration,
+ find_optimal_lookback,
+ calculate_relative_strength,
+ calculate_cross_sectional_momentum_rank,
+)
+
+from .statistical_arbitrage import (
+ MarketRegime,
+ StatArbResult,
+ PairsTradingResult,
+ analyze_statistical_arbitrage,
+ analyze_pairs_trading,
+ detect_market_regime,
+ detect_statistical_mispricing,
+ estimate_edge,
+)
+
+from .risk_management import (
+ VolatilityRegime,
+ RiskMetrics,
+ analyze_risk,
+ calculate_volatility,
+ calculate_var,
+ calculate_max_drawdown,
+ calculate_sharpe_ratio,
+ calculate_sortino_ratio,
+ calculate_beta,
+ calculate_kelly_criterion,
+ calculate_position_size,
+)
+
+from .execution import (
+ ExecutionUrgency,
+ ExecutionAnalysis,
+ analyze_execution,
+ estimate_market_impact,
+ estimate_spread_cost,
+ estimate_slippage,
+ calculate_optimal_trade_size,
+)
+
+# Analysis functions (pure Python, no LLM - extracted from legacy agents)
+from .analysis import (
+ run_signal_analysis,
+ run_risk_analysis,
+ run_execution_analysis,
+ run_stat_arb_analysis,
+ synthesize_decision,
+)
+
+__all__ = [
+ # Mean Reversion
+ "MeanReversionResult",
+ "analyze_mean_reversion",
+ "analyze_pairs_cointegration",
+ "calculate_z_score",
+ "estimate_half_life",
+ "calculate_hurst_exponent",
+ # Momentum
+ "MomentumResult",
+ "analyze_momentum",
+ "calculate_momentum_score",
+ "calculate_trend_strength",
+ "calculate_acceleration",
+ "find_optimal_lookback",
+ "calculate_relative_strength",
+ "calculate_cross_sectional_momentum_rank",
+ # Statistical Arbitrage
+ "MarketRegime",
+ "StatArbResult",
+ "PairsTradingResult",
+ "analyze_statistical_arbitrage",
+ "analyze_pairs_trading",
+ "detect_market_regime",
+ "detect_statistical_mispricing",
+ "estimate_edge",
+ # Risk Management
+ "VolatilityRegime",
+ "RiskMetrics",
+ "analyze_risk",
+ "calculate_volatility",
+ "calculate_var",
+ "calculate_max_drawdown",
+ "calculate_sharpe_ratio",
+ "calculate_sortino_ratio",
+ "calculate_beta",
+ "calculate_kelly_criterion",
+ "calculate_position_size",
+ # Execution
+ "ExecutionUrgency",
+ "ExecutionAnalysis",
+ "analyze_execution",
+ "estimate_market_impact",
+ "estimate_spread_cost",
+ "estimate_slippage",
+ "calculate_optimal_trade_size",
+ # Analysis Functions (from legacy agents)
+ "run_signal_analysis",
+ "run_risk_analysis",
+ "run_execution_analysis",
+ "run_stat_arb_analysis",
+ "synthesize_decision",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/analysis.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/analysis.py
new file mode 100644
index 000000000..9363d7553
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/analysis.py
@@ -0,0 +1,654 @@
+"""
+Renaissance Technologies Analysis Functions
+
+Pure Python quantitative analysis functions extracted from legacy agents.
+These functions run without LLM - pure mathematical/statistical analysis.
+
+Used by main.py for the RenaissanceTechnologiesSystem.analyze() method.
+"""
+
+from typing import Dict, Any, Optional, List
+from datetime import datetime
+
+from .mean_reversion import analyze_mean_reversion
+from .momentum import analyze_momentum
+from .statistical_arbitrage import (
+ analyze_statistical_arbitrage,
+ analyze_pairs_trading,
+ detect_market_regime,
+ estimate_edge,
+)
+from .risk_management import (
+ analyze_risk,
+ calculate_kelly_criterion,
+ calculate_position_size,
+)
+from .execution import analyze_execution, ExecutionUrgency
+
+# Import schemas
+from ..models.schemas import MedallionDecision, PositionSizing, SignalType
+
+
+# =============================================================================
+# SIGNAL ANALYSIS
+# =============================================================================
+
+def run_signal_analysis(
+ ticker: str,
+ prices: List[float],
+ revenues: Optional[List[float]] = None,
+ earnings: Optional[List[float]] = None,
+ metrics: Optional[Dict[str, Any]] = None
+) -> Dict[str, Any]:
+ """
+ Run comprehensive signal analysis without LLM (pure quant).
+
+ Args:
+ ticker: Stock ticker
+ prices: Historical prices (most recent first)
+ revenues: Historical revenues (optional)
+ earnings: Historical earnings (optional)
+ metrics: Additional financial metrics
+
+ Returns:
+ Dictionary with signal analysis results
+ """
+ # Mean reversion analysis
+ mean_reversion = analyze_mean_reversion(prices)
+
+ # Momentum analysis
+ momentum = analyze_momentum(prices, revenues, earnings)
+
+ # Pattern recognition (simplified autocorrelation)
+ returns = [(prices[i] / prices[i + 1]) - 1 for i in range(len(prices) - 1)]
+ autocorr = _calculate_autocorrelation(returns, lag=1) if len(returns) > 10 else 0
+
+ # Determine dominant regime
+ if abs(mean_reversion.z_score) > 2 and mean_reversion.statistical_significance > 0.7:
+ regime = "mean_reverting"
+ elif momentum.trend_strength > 0.6 and abs(momentum.signal_strength) > 0.5:
+ regime = "trending"
+ else:
+ regime = "random_walk"
+
+ # Aggregate signal
+ aggregate_signal = (
+ mean_reversion.signal_strength * 0.3 +
+ momentum.signal_strength * 0.4 +
+ (autocorr * 0.3 if regime == "mean_reverting" else -autocorr * 0.3)
+ )
+
+ # Statistical significance (combined)
+ stat_sig = (
+ mean_reversion.statistical_significance * 0.4 +
+ momentum.trend_strength * 0.3 +
+ (0.3 if abs(autocorr) > 0.1 else 0.15)
+ )
+
+ # Factor exposures placeholder
+ factor_exposures = {
+ "value": 0.0,
+ "momentum": momentum.signal_strength,
+ "quality": 0.0,
+ "size": 0.0,
+ "volatility": 0.0
+ }
+
+ if metrics:
+ pe = metrics.get("price_to_earnings")
+ roe = metrics.get("return_on_equity")
+
+ if pe and pe > 0:
+ factor_exposures["value"] = max(-1, min(1, (20 - pe) / 20))
+ if roe:
+ factor_exposures["quality"] = max(-1, min(1, (roe - 0.1) / 0.2))
+
+ return {
+ "ticker": ticker,
+ "mean_reversion": {
+ "signal_strength": mean_reversion.signal_strength,
+ "z_score": mean_reversion.z_score,
+ "half_life": mean_reversion.half_life,
+ "statistical_significance": mean_reversion.statistical_significance,
+ "details": mean_reversion.details
+ },
+ "momentum": {
+ "signal_strength": momentum.signal_strength,
+ "trend_strength": momentum.trend_strength,
+ "acceleration": momentum.acceleration,
+ "optimal_lookback": momentum.optimal_lookback,
+ "details": momentum.details
+ },
+ "pattern_recognition": {
+ "pattern_type": regime,
+ "pattern_confidence": stat_sig,
+ "autocorrelation": autocorr,
+ "regime": regime
+ },
+ "cross_sectional": {
+ "percentile_rank": 50.0,
+ "factor_exposures": factor_exposures,
+ "composite_score": 5.0
+ },
+ "aggregate_signal": max(-1, min(1, aggregate_signal)),
+ "statistical_significance": max(0, min(1, stat_sig)),
+ "reasoning": _generate_signal_reasoning(
+ mean_reversion, momentum, regime, aggregate_signal, stat_sig
+ )
+ }
+
+
+# =============================================================================
+# RISK ANALYSIS
+# =============================================================================
+
+def run_risk_analysis(
+ ticker: str,
+ prices: List[float],
+ market_prices: Optional[List[float]] = None,
+ market_cap: float = 10_000_000_000,
+ signal_strength: float = 0.0,
+ signal_confidence: float = 50.0
+) -> Dict[str, Any]:
+ """
+ Run comprehensive risk analysis without LLM (pure quant).
+ """
+ risk_metrics = analyze_risk(prices, market_prices, market_cap)
+
+ win_probability = 0.5 + (signal_strength * 0.01)
+ win_loss_ratio = 1.0 + abs(signal_strength) * 0.5
+
+ kelly = calculate_kelly_criterion(win_probability, win_loss_ratio)
+ position_size = calculate_position_size(
+ portfolio_value=100_000_000,
+ risk_score=risk_metrics.risk_score,
+ signal_confidence=signal_confidence
+ )
+
+ risk_adjustment = 1 - (risk_metrics.risk_score / 10) * 0.5
+ risk_adjusted_signal = signal_strength * risk_adjustment
+
+ return {
+ "ticker": ticker,
+ "volatility": {
+ "realized_volatility": risk_metrics.volatility_annualized,
+ "implied_volatility": None,
+ "volatility_regime": risk_metrics.volatility_regime.value,
+ "vol_of_vol": risk_metrics.volatility_annualized * 0.3
+ },
+ "correlation": {
+ "market_correlation": risk_metrics.correlation_to_market,
+ "sector_correlation": risk_metrics.correlation_to_market * 0.8,
+ "idiosyncratic_ratio": risk_metrics.idiosyncratic_ratio
+ },
+ "factor_decomposition": {
+ "market_beta": risk_metrics.beta,
+ "size_factor": 0.0,
+ "value_factor": 0.0,
+ "momentum_factor": signal_strength,
+ "quality_factor": 0.0,
+ "total_factor_risk": 1 - risk_metrics.idiosyncratic_ratio,
+ "specific_risk": risk_metrics.idiosyncratic_ratio
+ },
+ "drawdown": {
+ "max_drawdown": risk_metrics.max_drawdown,
+ "current_drawdown": risk_metrics.current_drawdown,
+ "recovery_time_estimate": _estimate_recovery_time(
+ risk_metrics.current_drawdown,
+ risk_metrics.volatility_annualized
+ ),
+ "tail_risk_var_95": risk_metrics.var_95
+ },
+ "var": {
+ "var_95": risk_metrics.var_95,
+ "var_99": risk_metrics.var_99
+ },
+ "ratios": {
+ "sharpe_ratio": risk_metrics.sharpe_ratio,
+ "sortino_ratio": risk_metrics.sortino_ratio
+ },
+ "position_sizing": {
+ "kelly_fraction": kelly,
+ "recommended_position_pct": position_size,
+ "max_position_pct": min(5.0, position_size * 2)
+ },
+ "liquidity": {
+ "liquidity_score": risk_metrics.liquidity_score
+ },
+ "risk_score": risk_metrics.risk_score,
+ "risk_adjusted_signal": risk_adjusted_signal,
+ "reasoning": _generate_risk_reasoning(risk_metrics, kelly, position_size),
+ "details": risk_metrics.details
+ }
+
+
+# =============================================================================
+# EXECUTION ANALYSIS
+# =============================================================================
+
+def run_execution_analysis(
+ ticker: str,
+ trade_value: float,
+ market_cap: float,
+ avg_daily_volume: Optional[float] = None,
+ volatility: float = 0.02,
+ expected_edge_bps: float = 20.0,
+ signal_decay_hours: float = 24.0
+) -> Dict[str, Any]:
+ """
+ Run comprehensive execution analysis without LLM (pure quant).
+ """
+ execution = analyze_execution(
+ trade_value=trade_value,
+ market_cap=market_cap,
+ avg_daily_volume=avg_daily_volume,
+ volatility=volatility,
+ expected_edge_bps=expected_edge_bps,
+ signal_decay_hours=signal_decay_hours
+ )
+
+ net_edge_bps = expected_edge_bps - execution.total_cost_bps
+
+ if execution.urgency == ExecutionUrgency.AVOID:
+ feasibility = "not_recommended"
+ elif net_edge_bps > expected_edge_bps * 0.5:
+ feasibility = "highly_feasible"
+ elif net_edge_bps > 0:
+ feasibility = "feasible"
+ else:
+ feasibility = "marginal"
+
+ return {
+ "ticker": ticker,
+ "trade_value": trade_value,
+ "market_impact": {
+ "estimated_impact_bps": execution.market_impact_bps,
+ "optimal_trade_size": execution.optimal_trade_size_pct,
+ "time_to_execute": execution.execution_time_minutes
+ },
+ "transaction_costs": {
+ "spread_cost_bps": execution.spread_cost_bps,
+ "commission_bps": execution.commission_bps,
+ "slippage_estimate_bps": execution.slippage_estimate_bps,
+ "total_cost_bps": execution.total_cost_bps
+ },
+ "liquidity": {
+ "average_daily_volume": avg_daily_volume or (market_cap * 0.007),
+ "liquidity_score": _calculate_liquidity_score(market_cap, avg_daily_volume),
+ "bid_ask_spread_bps": execution.spread_cost_bps,
+ "depth_ratio": _estimate_depth_ratio(market_cap)
+ },
+ "execution_score": execution.execution_score,
+ "recommended_urgency": execution.urgency.value,
+ "net_edge_bps": net_edge_bps,
+ "feasibility": feasibility,
+ "reasoning": _generate_execution_reasoning(execution, net_edge_bps, feasibility),
+ "details": execution.details
+ }
+
+
+# =============================================================================
+# STATISTICAL ARBITRAGE ANALYSIS
+# =============================================================================
+
+def run_stat_arb_analysis(
+ ticker: str,
+ prices: List[float],
+ intrinsic_estimates: Optional[List[float]] = None,
+ peer_prices: Optional[List[float]] = None,
+ metrics: Optional[Dict[str, Any]] = None
+) -> Dict[str, Any]:
+ """
+ Run comprehensive statistical arbitrage analysis without LLM (pure quant).
+ """
+ stat_arb = analyze_statistical_arbitrage(
+ prices=prices,
+ intrinsic_estimates=intrinsic_estimates,
+ peer_prices=peer_prices,
+ metrics=metrics
+ )
+
+ pairs_result = None
+ if peer_prices and len(peer_prices) >= 30:
+ pairs_result = analyze_pairs_trading(prices, peer_prices)
+
+ regime, regime_confidence = detect_market_regime(prices)
+ regime_duration = _estimate_regime_duration(prices, regime.value)
+ mispricing_data = _analyze_mispricing(prices, intrinsic_estimates, metrics)
+
+ arbitrage_score = stat_arb.arbitrage_score
+ edge_bps = estimate_edge(
+ signal_strength=(arbitrage_score - 5) / 5,
+ statistical_significance=regime_confidence,
+ transaction_costs_bps=10
+ )
+
+ return {
+ "ticker": ticker,
+ "pairs_trading": {
+ "signal": pairs_result.signal if pairs_result else "neutral",
+ "spread_z_score": pairs_result.spread_z_score if pairs_result else 0.0,
+ "cointegration_score": pairs_result.cointegration_score if pairs_result else 0.0,
+ "half_life": pairs_result.half_life if pairs_result else float('inf'),
+ "details": pairs_result.details if pairs_result else []
+ } if pairs_result else {
+ "signal": "neutral",
+ "spread_z_score": 0.0,
+ "cointegration_score": 0.0,
+ "half_life": float('inf'),
+ "details": ["No peer data for pairs analysis"]
+ },
+ "mispricing": {
+ "fair_value_estimate": mispricing_data["fair_value"],
+ "current_price": prices[0],
+ "mispricing_percentage": mispricing_data["mispricing_pct"],
+ "confidence": mispricing_data["confidence"]
+ },
+ "regime": {
+ "current_regime": regime.value,
+ "regime_probability": regime_confidence,
+ "regime_duration": regime_duration,
+ "transition_probability": 1 - regime_confidence
+ },
+ "arbitrage_score": arbitrage_score,
+ "edge_estimate_bps": edge_bps,
+ "reasoning": _generate_stat_arb_reasoning(
+ stat_arb, pairs_result, regime, regime_confidence, edge_bps
+ ),
+ "details": stat_arb.details
+ }
+
+
+# =============================================================================
+# MEDALLION SYNTHESIZER
+# =============================================================================
+
+def synthesize_decision(
+ ticker: str,
+ signal_analysis: Dict[str, Any],
+ risk_analysis: Dict[str, Any],
+ execution_analysis: Dict[str, Any],
+ stat_arb_analysis: Dict[str, Any]
+) -> MedallionDecision:
+ """
+ Synthesize all team analyses into a final Medallion decision.
+ Pure quantitative - no LLM needed.
+ """
+ aggregate_signal = signal_analysis.get("aggregate_signal", 0)
+ stat_sig = signal_analysis.get("statistical_significance", 0.5)
+ risk_score = risk_analysis.get("risk_score", 5)
+ execution_score = execution_analysis.get("execution_score", 5)
+ arbitrage_score = stat_arb_analysis.get("arbitrage_score", 5)
+
+ composite_score = (
+ (aggregate_signal + 1) * 5 * 0.35 +
+ arbitrage_score * 0.30 +
+ (10 - risk_score) * 0.20 +
+ execution_score * 0.15
+ )
+
+ if composite_score >= 7.0 and stat_sig > 0.85:
+ signal = SignalType.BULLISH
+ elif composite_score <= 3.0 or stat_sig < 0.50:
+ signal = SignalType.BEARISH
+ else:
+ signal = SignalType.NEUTRAL
+
+ base_confidence = min(100, composite_score * 10)
+ confidence = base_confidence * stat_sig
+
+ edge_from_signal = abs(aggregate_signal) * 0.002
+ edge_from_arb = (stat_arb_analysis.get("edge_estimate_bps", 0) or 0) / 10000
+ execution_cost = (execution_analysis.get("transaction_costs", {}).get("total_cost_bps", 10) or 10) / 10000
+
+ net_edge = (edge_from_signal + edge_from_arb) - execution_cost
+ statistical_edge = max(0, min(1, net_edge * 100))
+
+ kelly = risk_analysis.get("position_sizing", {}).get("kelly_fraction", 0.1)
+ risk_adjusted_size = risk_analysis.get("position_sizing", {}).get("recommended_position_pct", 2.0)
+
+ if execution_analysis.get("recommended_urgency") == "avoid":
+ risk_adjusted_size *= 0.25
+ elif execution_score < 5:
+ risk_adjusted_size *= 0.75
+
+ position_sizing = PositionSizing(
+ recommended_size_pct=min(5.0, risk_adjusted_size),
+ kelly_fraction=kelly,
+ max_position_size_pct=min(5.0, kelly * 100),
+ leverage_recommendation=_calculate_leverage(risk_score, stat_sig)
+ )
+
+ signal_strength = {
+ "mean_reversion": signal_analysis.get("mean_reversion", {}).get("signal_strength", 0),
+ "momentum": signal_analysis.get("momentum", {}).get("signal_strength", 0),
+ "statistical_arbitrage": (arbitrage_score - 5) / 5,
+ "risk_adjusted_return": aggregate_signal * (1 - risk_score / 10)
+ }
+
+ reasoning = _generate_medallion_reasoning(
+ signal, composite_score, stat_sig,
+ signal_analysis, risk_analysis, execution_analysis, stat_arb_analysis, net_edge
+ )
+
+ key_factors = _identify_key_factors(
+ signal_analysis, risk_analysis, execution_analysis, stat_arb_analysis
+ )
+
+ risks = _identify_risks(risk_analysis, execution_analysis, stat_arb_analysis)
+
+ return MedallionDecision(
+ ticker=ticker,
+ signal=signal,
+ confidence=round(confidence, 2),
+ statistical_edge=round(statistical_edge, 4),
+ signal_score=round((aggregate_signal + 1) * 5, 2),
+ risk_score=round(risk_score, 2),
+ execution_score=round(execution_score, 2),
+ arbitrage_score=round(arbitrage_score, 2),
+ position_sizing=position_sizing,
+ signal_strength=signal_strength,
+ reasoning=reasoning,
+ key_factors=key_factors,
+ risks=risks,
+ timestamp=datetime.utcnow().isoformat()
+ )
+
+
+# =============================================================================
+# HELPER FUNCTIONS
+# =============================================================================
+
+def _calculate_autocorrelation(data: List[float], lag: int) -> float:
+ if len(data) <= lag:
+ return 0
+ mean_val = sum(data) / len(data)
+ numerator = sum(
+ (data[i] - mean_val) * (data[i + lag] - mean_val)
+ for i in range(len(data) - lag)
+ )
+ denominator = sum((x - mean_val) ** 2 for x in data)
+ return numerator / denominator if denominator != 0 else 0
+
+
+def _generate_signal_reasoning(mean_reversion, momentum, regime, aggregate_signal, stat_sig) -> str:
+ parts = [f"Market regime detected: {regime}"]
+ if abs(mean_reversion.z_score) > 1.5:
+ direction = "below" if mean_reversion.z_score < 0 else "above"
+ parts.append(f"Mean reversion: Price {abs(mean_reversion.z_score):.1f}s {direction} mean")
+ if abs(momentum.signal_strength) > 0.3:
+ direction = "positive" if momentum.signal_strength > 0 else "negative"
+ parts.append(f"Momentum: {direction} ({momentum.trend_strength:.0%} trend)")
+ if aggregate_signal > 0.3:
+ parts.append(f"Aggregate: BULLISH ({aggregate_signal:+.2f})")
+ elif aggregate_signal < -0.3:
+ parts.append(f"Aggregate: BEARISH ({aggregate_signal:+.2f})")
+ else:
+ parts.append(f"Aggregate: NEUTRAL ({aggregate_signal:+.2f})")
+ parts.append(f"Statistical significance: {stat_sig:.0%}")
+ return ". ".join(parts) + "."
+
+
+def _estimate_recovery_time(current_drawdown: float, volatility: float) -> Optional[int]:
+ if current_drawdown <= 0:
+ return None
+ expected_daily_return = 0.10 / 252
+ if expected_daily_return <= 0:
+ return None
+ recovery_days = int(current_drawdown / expected_daily_return)
+ return min(recovery_days, 252 * 2)
+
+
+def _generate_risk_reasoning(risk_metrics, kelly, position_size) -> str:
+ parts = [
+ f"Volatility regime: {risk_metrics.volatility_regime.value.upper()}",
+ f"Annualized volatility: {risk_metrics.volatility_annualized:.1%}",
+ ]
+ if risk_metrics.risk_score < 3:
+ parts.append("Risk profile: LOW")
+ elif risk_metrics.risk_score < 6:
+ parts.append("Risk profile: MODERATE")
+ else:
+ parts.append("Risk profile: HIGH")
+ parts.append(f"Recommended position: {position_size:.1%}")
+ if risk_metrics.sharpe_ratio:
+ parts.append(f"Sharpe: {risk_metrics.sharpe_ratio:.2f}")
+ return ". ".join(parts) + "."
+
+
+def _calculate_liquidity_score(market_cap: float, avg_daily_volume: Optional[float]) -> float:
+ if market_cap >= 200_000_000_000:
+ cap_score = 10
+ elif market_cap >= 50_000_000_000:
+ cap_score = 9
+ elif market_cap >= 10_000_000_000:
+ cap_score = 8
+ elif market_cap >= 2_000_000_000:
+ cap_score = 6
+ elif market_cap >= 500_000_000:
+ cap_score = 4
+ else:
+ cap_score = 2
+ if avg_daily_volume:
+ if avg_daily_volume >= 50_000_000:
+ return min(10, cap_score + 1)
+ elif avg_daily_volume < 1_000_000:
+ return max(1, cap_score - 2)
+ return cap_score
+
+
+def _estimate_depth_ratio(market_cap: float) -> float:
+ if market_cap >= 100_000_000_000:
+ return 0.9
+ elif market_cap >= 10_000_000_000:
+ return 0.7
+ elif market_cap >= 1_000_000_000:
+ return 0.5
+ return 0.3
+
+
+def _generate_execution_reasoning(execution, net_edge_bps, feasibility) -> str:
+ parts = [
+ f"Total cost: {execution.total_cost_bps:.1f} bps",
+ f"Net edge: {net_edge_bps:.1f} bps",
+ f"Urgency: {execution.urgency.value.upper()}",
+ f"Score: {execution.execution_score:.1f}/10",
+ ]
+ return ". ".join(parts) + "."
+
+
+def _analyze_mispricing(prices, intrinsic_estimates, metrics) -> Dict[str, Any]:
+ current_price = prices[0]
+ if intrinsic_estimates and len(intrinsic_estimates) > 0:
+ fair_value = sum(intrinsic_estimates) / len(intrinsic_estimates)
+ mispricing_pct = (current_price - fair_value) / fair_value
+ confidence = 0.5
+ return {"fair_value": fair_value, "mispricing_pct": mispricing_pct, "confidence": confidence}
+ return {"fair_value": current_price, "mispricing_pct": 0.0, "confidence": 0.0}
+
+
+def _estimate_regime_duration(prices: List[float], current_regime: str) -> int:
+ if len(prices) < 40:
+ return 20
+ window = 20
+ consistent_periods = 0
+ for i in range(0, min(len(prices) - window, 200), 10):
+ subset = prices[i:i + window]
+ regime, _ = detect_market_regime(subset)
+ if regime.value == current_regime:
+ consistent_periods += 10
+ else:
+ break
+ return max(window, consistent_periods)
+
+
+def _generate_stat_arb_reasoning(stat_arb, pairs_result, regime, regime_confidence, edge_bps) -> str:
+ parts = [f"Regime: {regime.value.upper()} ({regime_confidence:.0%})"]
+ if stat_arb.mispricing_detected:
+ direction = "undervalued" if stat_arb.mispricing_pct < 0 else "overvalued"
+ parts.append(f"Mispricing: {abs(stat_arb.mispricing_pct) * 100:.1f}% {direction}")
+ if edge_bps > 10:
+ parts.append(f"Edge: {edge_bps:.1f} bps - ATTRACTIVE")
+ elif edge_bps > 0:
+ parts.append(f"Edge: {edge_bps:.1f} bps - MARGINAL")
+ parts.append(f"Score: {stat_arb.arbitrage_score:.1f}/10")
+ return ". ".join(parts) + "."
+
+
+def _calculate_leverage(risk_score: float, stat_sig: float) -> float:
+ base_leverage = 2.0
+ risk_multiplier = 1 + (5 - risk_score) / 5
+ confidence_multiplier = 0.5 + stat_sig * 0.5
+ leverage = base_leverage * risk_multiplier * confidence_multiplier
+ return min(12.5, max(1.0, leverage))
+
+
+def _generate_medallion_reasoning(signal, composite_score, stat_sig, signal_analysis, risk_analysis, execution_analysis, stat_arb_analysis, net_edge) -> str:
+ parts = [
+ f"DECISION: {signal.value.upper()}",
+ f"Composite: {composite_score:.2f}/10",
+ f"Significance: {stat_sig:.0%}",
+ f"Net edge: {net_edge * 10000:.1f} bps",
+ ]
+ return ". ".join(parts) + "."
+
+
+def _identify_key_factors(signal_analysis, risk_analysis, execution_analysis, stat_arb_analysis) -> List[str]:
+ factors = []
+ mean_rev = signal_analysis.get("mean_reversion", {})
+ if abs(mean_rev.get("z_score", 0)) > 2:
+ direction = "below" if mean_rev.get("z_score", 0) < 0 else "above"
+ factors.append(f"Price {abs(mean_rev.get('z_score', 0)):.1f}s {direction} mean")
+ momentum = signal_analysis.get("momentum", {})
+ if momentum.get("trend_strength", 0) > 0.6:
+ factors.append(f"Strong trend ({momentum.get('trend_strength', 0):.0%})")
+ if risk_analysis.get("risk_score", 5) < 3:
+ factors.append("Low risk profile")
+ elif risk_analysis.get("risk_score", 5) > 7:
+ factors.append("High risk - reduced exposure")
+ if execution_analysis.get("execution_score", 5) >= 8:
+ factors.append("Excellent execution")
+ return factors[:5]
+
+
+def _identify_risks(risk_analysis, execution_analysis, stat_arb_analysis) -> List[str]:
+ risks = []
+ vol_regime = risk_analysis.get("volatility", {}).get("volatility_regime", "normal")
+ if vol_regime in ["high", "extreme"]:
+ risks.append(f"Elevated volatility ({vol_regime})")
+ current_dd = risk_analysis.get("drawdown", {}).get("current_drawdown", 0)
+ if current_dd > 0.1:
+ risks.append(f"In {current_dd:.0%} drawdown")
+ if execution_analysis.get("recommended_urgency") == "avoid":
+ risks.append("Execution costs exceed edge")
+ return risks[:5]
+
+
+# Export all analysis functions
+__all__ = [
+ "run_signal_analysis",
+ "run_risk_analysis",
+ "run_execution_analysis",
+ "run_stat_arb_analysis",
+ "synthesize_decision",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/execution.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/execution.py
new file mode 100644
index 000000000..e8a77afcd
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/execution.py
@@ -0,0 +1,359 @@
+"""
+Execution Optimization Module
+
+Renaissance Technologies' execution algorithms.
+Minimize market impact and transaction costs.
+
+Key concepts:
+- Market impact modeling
+- Optimal execution timing (VWAP, TWAP concepts)
+- Transaction cost analysis (TCA)
+- Slippage estimation
+- Order book analysis
+"""
+
+import math
+from typing import List, Dict, Any, Optional
+from dataclasses import dataclass
+from enum import Enum
+
+
+class ExecutionUrgency(str, Enum):
+ IMMEDIATE = "immediate" # Execute now, accept higher costs
+ PATIENT = "patient" # Spread execution over time
+ AVOID = "avoid" # Execution costs too high
+
+
+@dataclass
+class ExecutionAnalysis:
+ """Execution optimization analysis output"""
+ market_impact_bps: float
+ spread_cost_bps: float
+ commission_bps: float
+ slippage_estimate_bps: float
+ total_cost_bps: float
+ optimal_trade_size_pct: float # As % of ADV
+ execution_time_minutes: int
+ urgency: ExecutionUrgency
+ execution_score: float # 0-10, higher is better
+ details: List[str]
+
+
+def estimate_market_impact(
+ trade_value: float,
+ market_cap: float,
+ avg_daily_volume: float,
+ volatility: float = 0.02
+) -> float:
+ """
+ Estimate market impact using square-root model.
+ Impact = sigma * sqrt(Q/V) * k
+
+ where:
+ - sigma = daily volatility
+ - Q = trade size
+ - V = average daily volume
+ - k = market impact coefficient (~0.1 for liquid stocks)
+ """
+ if avg_daily_volume <= 0:
+ return 100.0 # Max impact if no volume data
+
+ # Participation rate
+ participation = trade_value / avg_daily_volume
+
+ # Square-root impact model
+ k = 0.1 # Impact coefficient
+ impact = volatility * math.sqrt(participation) * k
+
+ # Convert to basis points
+ return impact * 10000
+
+
+def estimate_spread_cost(
+ market_cap: float,
+ avg_daily_volume: Optional[float] = None
+) -> float:
+ """
+ Estimate bid-ask spread cost in basis points.
+ Based on market cap and liquidity.
+ """
+ # Market cap based spread estimate
+ if market_cap >= 100_000_000_000: # $100B+
+ base_spread = 1.0
+ elif market_cap >= 20_000_000_000: # $20B+
+ base_spread = 2.0
+ elif market_cap >= 5_000_000_000: # $5B+
+ base_spread = 5.0
+ elif market_cap >= 1_000_000_000: # $1B+
+ base_spread = 10.0
+ elif market_cap >= 200_000_000: # $200M+
+ base_spread = 20.0
+ else:
+ base_spread = 50.0
+
+ # Volume adjustment
+ if avg_daily_volume:
+ if avg_daily_volume >= 50_000_000: # $50M+ daily
+ base_spread *= 0.7
+ elif avg_daily_volume >= 10_000_000: # $10M+ daily
+ base_spread *= 0.85
+ elif avg_daily_volume < 1_000_000: # <$1M daily
+ base_spread *= 1.5
+
+ return base_spread
+
+
+def estimate_commission(
+ trade_value: float,
+ is_institutional: bool = True
+) -> float:
+ """
+ Estimate commission cost in basis points.
+ """
+ if is_institutional:
+ # Institutional rates (per share, converted to bps)
+ if trade_value >= 1_000_000:
+ return 0.5 # 0.5 bps for large trades
+ elif trade_value >= 100_000:
+ return 1.0
+ else:
+ return 2.0
+ else:
+ # Retail rates
+ return 5.0
+
+
+def estimate_slippage(
+ participation_rate: float,
+ volatility: float,
+ urgency: ExecutionUrgency
+) -> float:
+ """
+ Estimate execution slippage in basis points.
+ """
+ # Base slippage from volatility
+ base_slippage = volatility * 100 # Convert to bps
+
+ # Participation rate adjustment
+ if participation_rate > 0.1: # >10% of volume
+ base_slippage *= 2.0
+ elif participation_rate > 0.05: # >5% of volume
+ base_slippage *= 1.5
+ elif participation_rate > 0.01: # >1% of volume
+ base_slippage *= 1.2
+
+ # Urgency adjustment
+ if urgency == ExecutionUrgency.IMMEDIATE:
+ base_slippage *= 1.5
+ elif urgency == ExecutionUrgency.PATIENT:
+ base_slippage *= 0.7
+
+ return base_slippage
+
+
+def calculate_optimal_trade_size(
+ market_cap: float,
+ avg_daily_volume: float,
+ volatility: float,
+ max_impact_bps: float = 10.0
+) -> float:
+ """
+ Calculate optimal trade size as percentage of ADV to limit impact.
+ """
+ if avg_daily_volume <= 0:
+ return 0.01 # 1% minimum
+
+ # Target impact
+ target_participation = (max_impact_bps / 10000 / (volatility * 0.1)) ** 2
+
+ # Cap at reasonable levels
+ optimal_pct = min(0.25, max(0.01, target_participation)) # 1-25% of ADV
+
+ return optimal_pct
+
+
+def estimate_execution_time(
+ trade_value: float,
+ avg_daily_volume: float,
+ target_participation: float = 0.05
+) -> int:
+ """
+ Estimate execution time in minutes to achieve target participation rate.
+ Assumes 6.5 hour trading day (390 minutes).
+ """
+ if avg_daily_volume <= 0:
+ return 390 # Full day
+
+ # Daily participation
+ daily_participation = trade_value / avg_daily_volume
+
+ # If can complete in less than target participation
+ if daily_participation <= target_participation:
+ # Execute in proportion of day
+ minutes = int(daily_participation / target_participation * 390)
+ return max(1, minutes)
+
+ # Need multiple days
+ days = daily_participation / target_participation
+ return int(days * 390)
+
+
+def determine_urgency(
+ signal_decay_hours: float,
+ execution_time_minutes: int,
+ total_cost_bps: float,
+ expected_edge_bps: float
+) -> ExecutionUrgency:
+ """
+ Determine execution urgency based on signal decay and costs.
+ """
+ execution_hours = execution_time_minutes / 60
+
+ # If signal decays before we can execute patiently
+ if signal_decay_hours < execution_hours:
+ if total_cost_bps < expected_edge_bps * 0.5:
+ return ExecutionUrgency.IMMEDIATE
+ else:
+ return ExecutionUrgency.AVOID
+
+ # If costs exceed expected edge
+ if total_cost_bps >= expected_edge_bps:
+ return ExecutionUrgency.AVOID
+
+ # If costs are low enough to be patient
+ if total_cost_bps < expected_edge_bps * 0.3:
+ return ExecutionUrgency.PATIENT
+
+ return ExecutionUrgency.PATIENT
+
+
+def analyze_execution(
+ trade_value: float,
+ market_cap: float,
+ avg_daily_volume: Optional[float] = None,
+ volatility: float = 0.02,
+ expected_edge_bps: float = 20.0,
+ signal_decay_hours: float = 24.0
+) -> ExecutionAnalysis:
+ """
+ Comprehensive execution optimization analysis.
+
+ Args:
+ trade_value: Intended trade value in dollars
+ market_cap: Security market capitalization
+ avg_daily_volume: Average daily trading volume in dollars
+ volatility: Daily volatility (decimal)
+ expected_edge_bps: Expected signal edge in basis points
+ signal_decay_hours: Hours until signal loses value
+ """
+ details = []
+
+ # Default ADV if not provided (estimate from market cap)
+ if avg_daily_volume is None or avg_daily_volume <= 0:
+ # Typical turnover: 0.5-1% of market cap daily
+ avg_daily_volume = market_cap * 0.007
+ details.append(f"Estimated ADV: ${avg_daily_volume / 1e6:.1f}M")
+
+ # Participation rate
+ participation_rate = trade_value / avg_daily_volume
+ details.append(f"Participation rate: {participation_rate * 100:.2f}% of ADV")
+
+ # Market impact
+ market_impact_bps = estimate_market_impact(
+ trade_value, market_cap, avg_daily_volume, volatility
+ )
+ details.append(f"Estimated market impact: {market_impact_bps:.1f} bps")
+
+ # Spread cost
+ spread_cost_bps = estimate_spread_cost(market_cap, avg_daily_volume)
+ details.append(f"Spread cost: {spread_cost_bps:.1f} bps")
+
+ # Commission
+ commission_bps = estimate_commission(trade_value)
+
+ # Optimal trade size
+ optimal_trade_size_pct = calculate_optimal_trade_size(
+ market_cap, avg_daily_volume, volatility
+ )
+ details.append(f"Optimal trade size: {optimal_trade_size_pct * 100:.1f}% of ADV")
+
+ # Execution time
+ execution_time = estimate_execution_time(
+ trade_value, avg_daily_volume, optimal_trade_size_pct
+ )
+ details.append(f"Estimated execution time: {execution_time} minutes")
+
+ # Preliminary urgency for slippage estimate
+ preliminary_urgency = ExecutionUrgency.PATIENT
+
+ # Slippage
+ slippage_bps = estimate_slippage(participation_rate, volatility, preliminary_urgency)
+
+ # Total cost
+ total_cost_bps = market_impact_bps + spread_cost_bps + commission_bps + slippage_bps
+ details.append(f"Total execution cost: {total_cost_bps:.1f} bps")
+
+ # Final urgency determination
+ urgency = determine_urgency(
+ signal_decay_hours, execution_time, total_cost_bps, expected_edge_bps
+ )
+ details.append(f"Recommended urgency: {urgency.value}")
+
+ # Recalculate slippage with final urgency
+ slippage_bps = estimate_slippage(participation_rate, volatility, urgency)
+ total_cost_bps = market_impact_bps + spread_cost_bps + commission_bps + slippage_bps
+
+ # Execution score (0-10, higher is better)
+ if urgency == ExecutionUrgency.AVOID:
+ execution_score = 2.0
+ details.append("Execution not recommended - costs exceed edge")
+ else:
+ # Score based on cost vs edge ratio
+ cost_ratio = total_cost_bps / expected_edge_bps if expected_edge_bps > 0 else 1
+ execution_score = max(0, 10 * (1 - cost_ratio))
+
+ if execution_score >= 8:
+ details.append("Excellent execution profile")
+ elif execution_score >= 6:
+ details.append("Good execution profile")
+ elif execution_score >= 4:
+ details.append("Acceptable execution profile")
+ else:
+ details.append("Challenging execution profile")
+
+ return ExecutionAnalysis(
+ market_impact_bps=market_impact_bps,
+ spread_cost_bps=spread_cost_bps,
+ commission_bps=commission_bps,
+ slippage_estimate_bps=slippage_bps,
+ total_cost_bps=total_cost_bps,
+ optimal_trade_size_pct=optimal_trade_size_pct,
+ execution_time_minutes=execution_time,
+ urgency=urgency,
+ execution_score=min(10, max(0, execution_score)),
+ details=details
+ )
+
+
+def calculate_implementation_shortfall(
+ decision_price: float,
+ execution_price: float,
+ benchmark_price: float
+) -> Dict[str, float]:
+ """
+ Calculate implementation shortfall components.
+ """
+ # Total shortfall
+ total_shortfall = (execution_price - decision_price) / decision_price
+
+ # Delay cost (decision to benchmark)
+ delay_cost = (benchmark_price - decision_price) / decision_price
+
+ # Trading cost (benchmark to execution)
+ trading_cost = (execution_price - benchmark_price) / benchmark_price
+
+ return {
+ "total_shortfall_bps": total_shortfall * 10000,
+ "delay_cost_bps": delay_cost * 10000,
+ "trading_cost_bps": trading_cost * 10000
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/mean_reversion.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/mean_reversion.py
new file mode 100644
index 000000000..6223977e0
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/mean_reversion.py
@@ -0,0 +1,253 @@
+"""
+Mean Reversion Strategy Module
+
+Renaissance Technologies' mean reversion algorithms.
+Identifies when prices deviate from historical means and predicts convergence.
+
+Key concepts:
+- Z-score calculation from historical distribution
+- Half-life estimation (Ornstein-Uhlenbeck process)
+- Cointegration testing for pairs
+"""
+
+import math
+from typing import List, Dict, Any, Optional, Tuple
+from dataclasses import dataclass
+
+
+@dataclass
+class MeanReversionResult:
+ """Result of mean reversion analysis"""
+ signal_strength: float # -1 to 1
+ z_score: float
+ half_life: Optional[float]
+ statistical_significance: float
+ details: List[str]
+
+
+def calculate_z_score(current: float, mean: float, std: float) -> float:
+ """Calculate z-score from mean"""
+ if std == 0:
+ return 0.0
+ return (current - mean) / std
+
+
+def estimate_half_life(series: List[float]) -> Optional[float]:
+ """
+ Estimate mean reversion half-life using Ornstein-Uhlenbeck process.
+ Half-life = -ln(2) / lambda, where lambda is the mean reversion speed.
+ """
+ if len(series) < 10:
+ return None
+
+ # Calculate lag-1 differences
+ y = [series[i] - series[i - 1] for i in range(1, len(series))]
+ x = series[:-1]
+
+ # Simple linear regression: y = alpha + beta * x
+ n = len(y)
+ mean_x = sum(x) / n
+ mean_y = sum(y) / n
+
+ numerator = sum((x[i] - mean_x) * (y[i] - mean_y) for i in range(n))
+ denominator = sum((x[i] - mean_x) ** 2 for i in range(n))
+
+ if denominator == 0:
+ return None
+
+ beta = numerator / denominator
+
+ # Mean reversion requires negative beta
+ if beta >= 0:
+ return None
+
+ # Half-life = -ln(2) / beta
+ half_life = -math.log(2) / beta
+
+ # Sanity check
+ if half_life < 0 or half_life > len(series):
+ return None
+
+ return half_life
+
+
+def calculate_hurst_exponent(series: List[float], max_lag: int = 20) -> float:
+ """
+ Calculate Hurst exponent to determine mean reversion tendency.
+ H < 0.5: Mean reverting
+ H = 0.5: Random walk
+ H > 0.5: Trending
+ """
+ if len(series) < max_lag * 2:
+ return 0.5 # Default to random walk
+
+ lags = range(2, min(max_lag, len(series) // 2))
+ tau = []
+ rs = []
+
+ for lag in lags:
+ # Calculate returns
+ returns = [series[i] - series[i - lag] for i in range(lag, len(series))]
+
+ if not returns:
+ continue
+
+ # R/S statistic
+ mean_r = sum(returns) / len(returns)
+ cumdev = []
+ cumsum = 0
+ for r in returns:
+ cumsum += r - mean_r
+ cumdev.append(cumsum)
+
+ R = max(cumdev) - min(cumdev)
+ S = math.sqrt(sum((r - mean_r) ** 2 for r in returns) / len(returns))
+
+ if S > 0:
+ rs.append(R / S)
+ tau.append(lag)
+
+ if len(tau) < 3:
+ return 0.5
+
+ # Linear regression of log(R/S) vs log(tau)
+ log_tau = [math.log(t) for t in tau]
+ log_rs = [math.log(r) for r in rs]
+
+ mean_log_tau = sum(log_tau) / len(log_tau)
+ mean_log_rs = sum(log_rs) / len(log_rs)
+
+ numerator = sum((log_tau[i] - mean_log_tau) * (log_rs[i] - mean_log_rs) for i in range(len(tau)))
+ denominator = sum((log_tau[i] - mean_log_tau) ** 2 for i in range(len(tau)))
+
+ if denominator == 0:
+ return 0.5
+
+ hurst = numerator / denominator
+ return max(0, min(1, hurst))
+
+
+def analyze_mean_reversion(
+ prices: List[float],
+ lookback_short: int = 20,
+ lookback_long: int = 60
+) -> MeanReversionResult:
+ """
+ Comprehensive mean reversion analysis.
+
+ Args:
+ prices: Historical price series (most recent first)
+ lookback_short: Short-term lookback for recent mean
+ lookback_long: Long-term lookback for historical mean
+ """
+ details = []
+
+ if len(prices) < lookback_long:
+ return MeanReversionResult(
+ signal_strength=0.0,
+ z_score=0.0,
+ half_life=None,
+ statistical_significance=0.0,
+ details=["Insufficient data for mean reversion analysis"]
+ )
+
+ current_price = prices[0]
+ short_term_prices = prices[:lookback_short]
+ long_term_prices = prices[:lookback_long]
+
+ # Calculate means
+ short_mean = sum(short_term_prices) / len(short_term_prices)
+ long_mean = sum(long_term_prices) / len(long_term_prices)
+
+ # Calculate standard deviation
+ long_std = math.sqrt(sum((p - long_mean) ** 2 for p in long_term_prices) / len(long_term_prices))
+
+ # Z-score
+ z_score = calculate_z_score(current_price, long_mean, long_std)
+ details.append(f"Z-score from long-term mean: {z_score:.2f}")
+
+ # Half-life estimation
+ half_life = estimate_half_life(list(reversed(prices[:lookback_long])))
+ if half_life:
+ details.append(f"Estimated half-life: {half_life:.1f} periods")
+
+ # Hurst exponent
+ hurst = calculate_hurst_exponent(list(reversed(prices)))
+ details.append(f"Hurst exponent: {hurst:.3f}")
+
+ # Signal strength calculation
+ # Strong mean reversion signal when:
+ # 1. Large z-score (price far from mean)
+ # 2. Low Hurst exponent (mean reverting behavior)
+ # 3. Reasonable half-life
+
+ signal_strength = 0.0
+
+ # Z-score contribution (capped at 3 sigma)
+ z_contribution = min(abs(z_score), 3) / 3
+ if z_score < 0: # Below mean = bullish for mean reversion
+ signal_strength += z_contribution * 0.4
+ else: # Above mean = bearish for mean reversion
+ signal_strength -= z_contribution * 0.4
+
+ # Hurst contribution
+ if hurst < 0.5:
+ signal_strength += (0.5 - hurst) * 0.6 # Mean reverting
+ details.append("Hurst indicates mean-reverting behavior")
+ else:
+ signal_strength *= 0.5 # Reduce signal if trending
+ details.append("Hurst indicates trending behavior - reduced signal")
+
+ # Statistical significance based on data quality
+ stat_sig = min(len(prices) / 100, 1.0) * (1 - abs(hurst - 0.3))
+ stat_sig = max(0, min(1, stat_sig))
+
+ return MeanReversionResult(
+ signal_strength=max(-1, min(1, signal_strength)),
+ z_score=z_score,
+ half_life=half_life,
+ statistical_significance=stat_sig,
+ details=details
+ )
+
+
+def analyze_pairs_cointegration(
+ series_a: List[float],
+ series_b: List[float]
+) -> Tuple[float, float, float]:
+ """
+ Analyze cointegration between two price series for pairs trading.
+
+ Returns:
+ Tuple of (cointegration_score, spread_z_score, hedge_ratio)
+ """
+ if len(series_a) != len(series_b) or len(series_a) < 30:
+ return (0.0, 0.0, 1.0)
+
+ # Calculate hedge ratio using linear regression
+ mean_a = sum(series_a) / len(series_a)
+ mean_b = sum(series_b) / len(series_b)
+
+ numerator = sum((series_a[i] - mean_a) * (series_b[i] - mean_b) for i in range(len(series_a)))
+ denominator = sum((series_b[i] - mean_b) ** 2 for i in range(len(series_b)))
+
+ if denominator == 0:
+ return (0.0, 0.0, 1.0)
+
+ hedge_ratio = numerator / denominator
+
+ # Calculate spread
+ spread = [series_a[i] - hedge_ratio * series_b[i] for i in range(len(series_a))]
+
+ # Test spread for stationarity using Hurst exponent
+ hurst = calculate_hurst_exponent(spread)
+
+ # Cointegration score (lower Hurst = more cointegrated)
+ cointegration_score = max(0, 1 - 2 * abs(hurst - 0.3))
+
+ # Spread z-score
+ spread_mean = sum(spread) / len(spread)
+ spread_std = math.sqrt(sum((s - spread_mean) ** 2 for s in spread) / len(spread))
+ spread_z_score = calculate_z_score(spread[0], spread_mean, spread_std) if spread_std > 0 else 0
+
+ return (cointegration_score, spread_z_score, hedge_ratio)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/momentum.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/momentum.py
new file mode 100644
index 000000000..3243d862c
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/momentum.py
@@ -0,0 +1,263 @@
+"""
+Momentum Strategy Module
+
+Renaissance Technologies' momentum algorithms.
+Identifies persistent trends and acceleration patterns.
+
+Key concepts:
+- Price momentum (rate of change)
+- Earnings momentum
+- Factor momentum
+- Cross-sectional momentum rankings
+"""
+
+import math
+from typing import List, Dict, Any, Optional
+from dataclasses import dataclass
+
+
+@dataclass
+class MomentumResult:
+ """Result of momentum analysis"""
+ signal_strength: float # -1 to 1
+ trend_strength: float # 0 to 1
+ acceleration: float
+ optimal_lookback: int
+ details: List[str]
+
+
+def calculate_returns(prices: List[float], period: int = 1) -> List[float]:
+ """Calculate period returns from price series"""
+ if len(prices) <= period:
+ return []
+ return [(prices[i] / prices[i + period]) - 1 for i in range(len(prices) - period)]
+
+
+def calculate_momentum_score(prices: List[float], lookback: int) -> float:
+ """
+ Calculate momentum score for a given lookback period.
+ Returns annualized return as percentage.
+ """
+ if len(prices) <= lookback:
+ return 0.0
+
+ return_pct = (prices[0] / prices[lookback]) - 1
+
+ # Annualize (assuming daily data, 252 trading days)
+ annualized = return_pct * (252 / lookback)
+ return annualized
+
+
+def calculate_trend_strength(prices: List[float], lookback: int = 20) -> float:
+ """
+ Calculate trend strength using linear regression R-squared.
+ Higher R-squared indicates stronger, more consistent trend.
+ """
+ if len(prices) < lookback:
+ return 0.0
+
+ subset = prices[:lookback]
+ n = len(subset)
+
+ # X is time (0, 1, 2, ...)
+ x = list(range(n))
+ y = list(reversed(subset)) # Oldest to newest
+
+ mean_x = sum(x) / n
+ mean_y = sum(y) / n
+
+ # Calculate regression components
+ ss_xy = sum((x[i] - mean_x) * (y[i] - mean_y) for i in range(n))
+ ss_xx = sum((x[i] - mean_x) ** 2 for i in range(n))
+ ss_yy = sum((y[i] - mean_y) ** 2 for i in range(n))
+
+ if ss_xx == 0 or ss_yy == 0:
+ return 0.0
+
+ # R-squared
+ r_squared = (ss_xy ** 2) / (ss_xx * ss_yy)
+ return min(1.0, max(0.0, r_squared))
+
+
+def calculate_acceleration(prices: List[float], short_period: int = 5, long_period: int = 20) -> float:
+ """
+ Calculate momentum acceleration.
+ Positive acceleration = momentum increasing
+ Negative acceleration = momentum decreasing
+ """
+ if len(prices) <= long_period:
+ return 0.0
+
+ short_momentum = calculate_momentum_score(prices, short_period)
+ long_momentum = calculate_momentum_score(prices, long_period)
+
+ # Acceleration is the difference between short and long momentum
+ acceleration = short_momentum - long_momentum
+ return acceleration
+
+
+def find_optimal_lookback(
+ prices: List[float],
+ lookbacks: List[int] = [5, 10, 20, 40, 60]
+) -> int:
+ """
+ Find optimal lookback period that maximizes risk-adjusted momentum.
+ Uses a simple Sharpe-like metric.
+ """
+ if len(prices) < max(lookbacks):
+ return lookbacks[0]
+
+ best_lookback = lookbacks[0]
+ best_score = float('-inf')
+
+ for lookback in lookbacks:
+ if len(prices) <= lookback * 2:
+ continue
+
+ # Calculate rolling momentum scores
+ momentums = []
+ for i in range(min(lookback, len(prices) - lookback)):
+ mom = calculate_momentum_score(prices[i:], lookback)
+ momentums.append(mom)
+
+ if not momentums:
+ continue
+
+ mean_mom = sum(momentums) / len(momentums)
+ std_mom = math.sqrt(sum((m - mean_mom) ** 2 for m in momentums) / len(momentums))
+
+ if std_mom > 0:
+ sharpe_like = mean_mom / std_mom
+ if sharpe_like > best_score:
+ best_score = sharpe_like
+ best_lookback = lookback
+
+ return best_lookback
+
+
+def calculate_relative_strength(
+ target_prices: List[float],
+ benchmark_prices: List[float],
+ lookback: int = 20
+) -> float:
+ """
+ Calculate relative strength vs benchmark.
+ Positive = outperforming, Negative = underperforming
+ """
+ if len(target_prices) <= lookback or len(benchmark_prices) <= lookback:
+ return 0.0
+
+ target_return = (target_prices[0] / target_prices[lookback]) - 1
+ benchmark_return = (benchmark_prices[0] / benchmark_prices[lookback]) - 1
+
+ return target_return - benchmark_return
+
+
+def analyze_momentum(
+ prices: List[float],
+ revenues: Optional[List[float]] = None,
+ earnings: Optional[List[float]] = None
+) -> MomentumResult:
+ """
+ Comprehensive momentum analysis combining price and fundamental momentum.
+
+ Args:
+ prices: Historical price series (most recent first)
+ revenues: Historical revenue series (optional)
+ earnings: Historical earnings series (optional)
+ """
+ details = []
+
+ if len(prices) < 20:
+ return MomentumResult(
+ signal_strength=0.0,
+ trend_strength=0.0,
+ acceleration=0.0,
+ optimal_lookback=20,
+ details=["Insufficient price data for momentum analysis"]
+ )
+
+ # Find optimal lookback
+ optimal_lookback = find_optimal_lookback(prices)
+ details.append(f"Optimal lookback period: {optimal_lookback} days")
+
+ # Price momentum
+ price_momentum = calculate_momentum_score(prices, optimal_lookback)
+ details.append(f"Price momentum ({optimal_lookback}d): {price_momentum * 100:.1f}%")
+
+ # Trend strength
+ trend_strength = calculate_trend_strength(prices, optimal_lookback)
+ details.append(f"Trend strength (R²): {trend_strength:.3f}")
+
+ # Acceleration
+ acceleration = calculate_acceleration(prices)
+ if acceleration > 0:
+ details.append(f"Momentum accelerating: {acceleration * 100:.1f}%")
+ else:
+ details.append(f"Momentum decelerating: {acceleration * 100:.1f}%")
+
+ # Fundamental momentum (if available)
+ fundamental_momentum = 0.0
+
+ if revenues and len(revenues) >= 4:
+ revenue_growth = (revenues[0] / revenues[-1]) ** (1 / len(revenues)) - 1
+ fundamental_momentum += revenue_growth
+ details.append(f"Revenue momentum: {revenue_growth * 100:.1f}%")
+
+ if earnings and len(earnings) >= 4:
+ # Handle negative earnings
+ positive_earnings = [e for e in earnings if e > 0]
+ if len(positive_earnings) >= 2:
+ earnings_growth = (positive_earnings[0] / positive_earnings[-1]) ** (1 / len(positive_earnings)) - 1
+ fundamental_momentum += earnings_growth
+ details.append(f"Earnings momentum: {earnings_growth * 100:.1f}%")
+
+ # Composite signal strength
+ signal_strength = 0.0
+
+ # Price momentum contribution (60% weight)
+ price_signal = min(1, max(-1, price_momentum * 5)) # Scale to -1 to 1
+ signal_strength += price_signal * 0.6
+
+ # Trend strength contribution (20% weight)
+ if price_momentum > 0:
+ signal_strength += trend_strength * 0.2
+ else:
+ signal_strength -= trend_strength * 0.2
+
+ # Acceleration contribution (10% weight)
+ accel_signal = min(1, max(-1, acceleration * 10))
+ signal_strength += accel_signal * 0.1
+
+ # Fundamental momentum contribution (10% weight)
+ if fundamental_momentum != 0:
+ fund_signal = min(1, max(-1, fundamental_momentum * 5))
+ signal_strength += fund_signal * 0.1
+
+ return MomentumResult(
+ signal_strength=max(-1, min(1, signal_strength)),
+ trend_strength=trend_strength,
+ acceleration=acceleration,
+ optimal_lookback=optimal_lookback,
+ details=details
+ )
+
+
+def calculate_cross_sectional_momentum_rank(
+ target_momentum: float,
+ peer_momentums: List[float]
+) -> float:
+ """
+ Calculate percentile rank of target momentum vs peers.
+ Returns percentile (0-100).
+ """
+ if not peer_momentums:
+ return 50.0
+
+ all_momentums = peer_momentums + [target_momentum]
+ all_momentums.sort()
+
+ rank = all_momentums.index(target_momentum) + 1
+ percentile = (rank / len(all_momentums)) * 100
+
+ return percentile
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/risk_management.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/risk_management.py
new file mode 100644
index 000000000..768278851
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/risk_management.py
@@ -0,0 +1,457 @@
+"""
+Risk Management Module
+
+Renaissance Technologies' risk management framework.
+Sophisticated mathematical risk models for position sizing and portfolio protection.
+
+Key concepts:
+- Volatility modeling (GARCH-like)
+- Factor risk decomposition
+- Value at Risk (VaR)
+- Maximum drawdown analysis
+- Correlation risk
+- Liquidity risk
+"""
+
+import math
+from typing import List, Dict, Any, Optional, Tuple
+from dataclasses import dataclass
+from enum import Enum
+
+
+class VolatilityRegime(str, Enum):
+ LOW = "low"
+ NORMAL = "normal"
+ HIGH = "high"
+ EXTREME = "extreme"
+
+
+@dataclass
+class RiskMetrics:
+ """Comprehensive risk metrics output"""
+ volatility_annualized: float
+ volatility_regime: VolatilityRegime
+ var_95: float
+ var_99: float
+ max_drawdown: float
+ current_drawdown: float
+ sharpe_ratio: Optional[float]
+ sortino_ratio: Optional[float]
+ beta: float
+ correlation_to_market: float
+ idiosyncratic_ratio: float
+ liquidity_score: float
+ risk_score: float # 0-10, lower is better (less risky)
+ details: List[str]
+
+
+def calculate_volatility(returns: List[float]) -> float:
+ """Calculate annualized volatility from returns."""
+ if len(returns) < 2:
+ return 0.0
+
+ mean_return = sum(returns) / len(returns)
+ variance = sum((r - mean_return) ** 2 for r in returns) / (len(returns) - 1)
+ daily_vol = math.sqrt(variance)
+
+ # Annualize (252 trading days)
+ return daily_vol * math.sqrt(252)
+
+
+def classify_volatility_regime(annualized_vol: float) -> VolatilityRegime:
+ """Classify current volatility regime."""
+ if annualized_vol < 0.12:
+ return VolatilityRegime.LOW
+ elif annualized_vol < 0.20:
+ return VolatilityRegime.NORMAL
+ elif annualized_vol < 0.35:
+ return VolatilityRegime.HIGH
+ else:
+ return VolatilityRegime.EXTREME
+
+
+def calculate_ewma_volatility(
+ returns: List[float],
+ lambda_param: float = 0.94
+) -> float:
+ """
+ Calculate EWMA (Exponentially Weighted Moving Average) volatility.
+ Similar to RiskMetrics methodology.
+ """
+ if len(returns) < 2:
+ return 0.0
+
+ # Initialize with simple variance
+ variance = returns[0] ** 2
+
+ # EWMA update
+ for r in returns[1:]:
+ variance = lambda_param * variance + (1 - lambda_param) * (r ** 2)
+
+ daily_vol = math.sqrt(variance)
+ return daily_vol * math.sqrt(252) # Annualize
+
+
+def calculate_var(
+ returns: List[float],
+ confidence: float = 0.95
+) -> float:
+ """
+ Calculate historical Value at Risk.
+ Returns the VaR as a positive percentage (loss).
+ """
+ if len(returns) < 10:
+ return 0.0
+
+ sorted_returns = sorted(returns)
+ index = int((1 - confidence) * len(sorted_returns))
+ var = -sorted_returns[index] # Convert to positive loss
+
+ # Annualize (approximately)
+ return var * math.sqrt(252)
+
+
+def calculate_max_drawdown(prices: List[float]) -> Tuple[float, float]:
+ """
+ Calculate maximum drawdown and current drawdown.
+
+ Returns:
+ Tuple of (max_drawdown, current_drawdown) as positive percentages
+ """
+ if len(prices) < 2:
+ return (0.0, 0.0)
+
+ # Prices are most recent first, reverse for calculation
+ prices_chronological = list(reversed(prices))
+
+ peak = prices_chronological[0]
+ max_dd = 0.0
+ current_dd = 0.0
+
+ for price in prices_chronological:
+ if price > peak:
+ peak = price
+ drawdown = (peak - price) / peak
+ max_dd = max(max_dd, drawdown)
+
+ # Current drawdown (from most recent peak)
+ recent_peak = max(prices[:min(20, len(prices))])
+ current_dd = (recent_peak - prices[0]) / recent_peak if recent_peak > 0 else 0
+
+ return (max_dd, max(0, current_dd))
+
+
+def calculate_sharpe_ratio(
+ returns: List[float],
+ risk_free_rate: float = 0.05
+) -> Optional[float]:
+ """Calculate annualized Sharpe ratio."""
+ if len(returns) < 20:
+ return None
+
+ mean_return = sum(returns) / len(returns)
+ volatility = calculate_volatility(returns) / math.sqrt(252) # Daily vol
+
+ if volatility == 0:
+ return None
+
+ # Annualize
+ annual_return = mean_return * 252
+ annual_vol = volatility * math.sqrt(252)
+
+ sharpe = (annual_return - risk_free_rate) / annual_vol
+ return sharpe
+
+
+def calculate_sortino_ratio(
+ returns: List[float],
+ risk_free_rate: float = 0.05
+) -> Optional[float]:
+ """Calculate Sortino ratio (uses downside deviation only)."""
+ if len(returns) < 20:
+ return None
+
+ mean_return = sum(returns) / len(returns)
+
+ # Downside returns only
+ downside_returns = [r for r in returns if r < 0]
+ if not downside_returns:
+ return None
+
+ downside_variance = sum(r ** 2 for r in downside_returns) / len(downside_returns)
+ downside_vol = math.sqrt(downside_variance) * math.sqrt(252)
+
+ if downside_vol == 0:
+ return None
+
+ annual_return = mean_return * 252
+ sortino = (annual_return - risk_free_rate) / downside_vol
+ return sortino
+
+
+def calculate_beta(
+ asset_returns: List[float],
+ market_returns: List[float]
+) -> float:
+ """Calculate beta relative to market."""
+ if len(asset_returns) != len(market_returns) or len(asset_returns) < 20:
+ return 1.0
+
+ mean_asset = sum(asset_returns) / len(asset_returns)
+ mean_market = sum(market_returns) / len(market_returns)
+
+ covariance = sum(
+ (asset_returns[i] - mean_asset) * (market_returns[i] - mean_market)
+ for i in range(len(asset_returns))
+ ) / len(asset_returns)
+
+ market_variance = sum(
+ (r - mean_market) ** 2 for r in market_returns
+ ) / len(market_returns)
+
+ if market_variance == 0:
+ return 1.0
+
+ return covariance / market_variance
+
+
+def calculate_correlation(
+ series_a: List[float],
+ series_b: List[float]
+) -> float:
+ """Calculate Pearson correlation coefficient."""
+ if len(series_a) != len(series_b) or len(series_a) < 10:
+ return 0.0
+
+ mean_a = sum(series_a) / len(series_a)
+ mean_b = sum(series_b) / len(series_b)
+
+ numerator = sum(
+ (series_a[i] - mean_a) * (series_b[i] - mean_b)
+ for i in range(len(series_a))
+ )
+
+ std_a = math.sqrt(sum((x - mean_a) ** 2 for x in series_a))
+ std_b = math.sqrt(sum((x - mean_b) ** 2 for x in series_b))
+
+ if std_a == 0 or std_b == 0:
+ return 0.0
+
+ return numerator / (std_a * std_b)
+
+
+def estimate_liquidity_score(market_cap: float, avg_volume: Optional[float] = None) -> float:
+ """
+ Estimate liquidity score (0-10, higher is more liquid).
+ """
+ # Market cap based score
+ if market_cap >= 200_000_000_000: # $200B+
+ cap_score = 10
+ elif market_cap >= 50_000_000_000: # $50B+
+ cap_score = 9
+ elif market_cap >= 10_000_000_000: # $10B+
+ cap_score = 8
+ elif market_cap >= 2_000_000_000: # $2B+
+ cap_score = 6
+ elif market_cap >= 500_000_000: # $500M+
+ cap_score = 4
+ else:
+ cap_score = 2
+
+ # Adjust for volume if available
+ if avg_volume:
+ if avg_volume >= 10_000_000:
+ vol_adjustment = 1.0
+ elif avg_volume >= 1_000_000:
+ vol_adjustment = 0.8
+ else:
+ vol_adjustment = 0.6
+ return cap_score * vol_adjustment
+
+ return cap_score
+
+
+def decompose_factor_risk(
+ asset_returns: List[float],
+ market_returns: List[float]
+) -> Dict[str, float]:
+ """
+ Decompose risk into factor and idiosyncratic components.
+ Simplified factor model.
+ """
+ if len(asset_returns) != len(market_returns) or len(asset_returns) < 20:
+ return {
+ "market_risk": 0.5,
+ "idiosyncratic_risk": 0.5,
+ "r_squared": 0.5
+ }
+
+ beta = calculate_beta(asset_returns, market_returns)
+ correlation = calculate_correlation(asset_returns, market_returns)
+
+ # R-squared represents systematic risk proportion
+ r_squared = correlation ** 2
+
+ # Idiosyncratic ratio
+ idiosyncratic_ratio = 1 - r_squared
+
+ return {
+ "market_risk": r_squared,
+ "idiosyncratic_risk": idiosyncratic_ratio,
+ "r_squared": r_squared,
+ "beta": beta
+ }
+
+
+def analyze_risk(
+ prices: List[float],
+ market_prices: Optional[List[float]] = None,
+ market_cap: float = 10_000_000_000
+) -> RiskMetrics:
+ """
+ Comprehensive risk analysis.
+
+ Args:
+ prices: Asset price series (most recent first)
+ market_prices: Market benchmark prices for beta/correlation
+ market_cap: Market capitalization for liquidity scoring
+ """
+ details = []
+
+ if len(prices) < 20:
+ return RiskMetrics(
+ volatility_annualized=0.0,
+ volatility_regime=VolatilityRegime.NORMAL,
+ var_95=0.0,
+ var_99=0.0,
+ max_drawdown=0.0,
+ current_drawdown=0.0,
+ sharpe_ratio=None,
+ sortino_ratio=None,
+ beta=1.0,
+ correlation_to_market=0.5,
+ idiosyncratic_ratio=0.5,
+ liquidity_score=5.0,
+ risk_score=5.0,
+ details=["Insufficient data for risk analysis"]
+ )
+
+ # Calculate returns
+ returns = [(prices[i] / prices[i + 1]) - 1 for i in range(len(prices) - 1)]
+
+ # Volatility
+ vol = calculate_volatility(returns)
+ ewma_vol = calculate_ewma_volatility(returns)
+ vol_regime = classify_volatility_regime(vol)
+ details.append(f"Annualized volatility: {vol * 100:.1f}%")
+ details.append(f"Volatility regime: {vol_regime.value}")
+
+ # VaR
+ var_95 = calculate_var(returns, 0.95)
+ var_99 = calculate_var(returns, 0.99)
+ details.append(f"95% VaR: {var_95 * 100:.1f}%")
+
+ # Drawdown
+ max_dd, current_dd = calculate_max_drawdown(prices)
+ details.append(f"Max drawdown: {max_dd * 100:.1f}%")
+ if current_dd > 0.05:
+ details.append(f"Current drawdown: {current_dd * 100:.1f}%")
+
+ # Risk-adjusted returns
+ sharpe = calculate_sharpe_ratio(returns)
+ sortino = calculate_sortino_ratio(returns)
+ if sharpe:
+ details.append(f"Sharpe ratio: {sharpe:.2f}")
+
+ # Market correlation and beta
+ beta = 1.0
+ correlation = 0.5
+ idiosyncratic_ratio = 0.5
+
+ if market_prices and len(market_prices) >= len(prices):
+ market_returns = [
+ (market_prices[i] / market_prices[i + 1]) - 1
+ for i in range(len(prices) - 1)
+ ]
+ beta = calculate_beta(returns, market_returns)
+ correlation = calculate_correlation(returns, market_returns)
+ factor_decomp = decompose_factor_risk(returns, market_returns)
+ idiosyncratic_ratio = factor_decomp["idiosyncratic_risk"]
+
+ details.append(f"Beta: {beta:.2f}")
+ details.append(f"Market correlation: {correlation:.2f}")
+
+ # Liquidity
+ liquidity_score = estimate_liquidity_score(market_cap)
+ details.append(f"Liquidity score: {liquidity_score:.1f}/10")
+
+ # Composite risk score (lower is better)
+ risk_components = [
+ vol / 0.3 * 3, # Volatility contribution (normalized to 30%)
+ var_95 / 0.2 * 2, # VaR contribution
+ max_dd / 0.5 * 2, # Drawdown contribution
+ (1 - idiosyncratic_ratio) * 2, # Systematic risk contribution
+ (10 - liquidity_score) / 10 * 1 # Illiquidity contribution
+ ]
+
+ risk_score = min(10, max(0, sum(risk_components)))
+
+ return RiskMetrics(
+ volatility_annualized=vol,
+ volatility_regime=vol_regime,
+ var_95=var_95,
+ var_99=var_99,
+ max_drawdown=max_dd,
+ current_drawdown=current_dd,
+ sharpe_ratio=sharpe,
+ sortino_ratio=sortino,
+ beta=beta,
+ correlation_to_market=correlation,
+ idiosyncratic_ratio=idiosyncratic_ratio,
+ liquidity_score=liquidity_score,
+ risk_score=risk_score,
+ details=details
+ )
+
+
+def calculate_kelly_criterion(
+ win_probability: float,
+ win_loss_ratio: float
+) -> float:
+ """
+ Calculate Kelly Criterion for position sizing.
+ f* = (p * b - q) / b
+ where p = win prob, q = loss prob, b = win/loss ratio
+ """
+ if win_probability <= 0 or win_probability >= 1:
+ return 0.0
+ if win_loss_ratio <= 0:
+ return 0.0
+
+ q = 1 - win_probability
+ kelly = (win_probability * win_loss_ratio - q) / win_loss_ratio
+
+ # Cap at 25% for safety (Renaissance uses fractional Kelly)
+ return max(0, min(0.25, kelly))
+
+
+def calculate_position_size(
+ portfolio_value: float,
+ risk_score: float,
+ signal_confidence: float,
+ max_position_pct: float = 5.0
+) -> float:
+ """
+ Calculate recommended position size as percentage of portfolio.
+ Renaissance style: many small positions with high conviction.
+ """
+ # Base position from confidence
+ base_position = signal_confidence / 100 * max_position_pct
+
+ # Risk adjustment (higher risk = smaller position)
+ risk_multiplier = 1 - (risk_score / 10) * 0.5
+
+ # Final position
+ position_pct = base_position * risk_multiplier
+
+ return max(0, min(max_position_pct, position_pct))
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/statistical_arbitrage.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/statistical_arbitrage.py
new file mode 100644
index 000000000..2b5f0ce67
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/strategies/statistical_arbitrage.py
@@ -0,0 +1,357 @@
+"""
+Statistical Arbitrage Strategy Module
+
+Renaissance Technologies' stat arb algorithms.
+Identifies mispricing, regime changes, and arbitrage opportunities.
+
+Key concepts:
+- Pairs trading (cointegration-based)
+- Statistical mispricing detection
+- Regime detection (Hidden Markov Models concept)
+- Market microstructure analysis
+"""
+
+import math
+from typing import List, Dict, Any, Optional, Tuple
+from dataclasses import dataclass
+from enum import Enum
+
+
+class MarketRegime(str, Enum):
+ BULL = "bull"
+ BEAR = "bear"
+ SIDEWAYS = "sideways"
+ TRANSITION = "transition"
+
+
+@dataclass
+class StatArbResult:
+ """Result of statistical arbitrage analysis"""
+ arbitrage_score: float # 0 to 10
+ edge_estimate_bps: float
+ mispricing_detected: bool
+ mispricing_pct: float
+ regime: MarketRegime
+ regime_confidence: float
+ details: List[str]
+
+
+@dataclass
+class PairsTradingResult:
+ """Result of pairs trading analysis"""
+ signal: str # "long_spread", "short_spread", "neutral"
+ spread_z_score: float
+ cointegration_score: float
+ half_life: float
+ hedge_ratio: float
+ details: List[str]
+
+
+def detect_market_regime(
+ prices: List[float],
+ lookback: int = 60
+) -> Tuple[MarketRegime, float]:
+ """
+ Detect current market regime using simple state classification.
+ Inspired by Hidden Markov Models but simplified.
+
+ Returns:
+ Tuple of (regime, confidence)
+ """
+ if len(prices) < lookback:
+ return (MarketRegime.SIDEWAYS, 0.5)
+
+ subset = prices[:lookback]
+
+ # Calculate trend
+ returns = [(subset[i] / subset[i + 1]) - 1 for i in range(len(subset) - 1)]
+ mean_return = sum(returns) / len(returns)
+ volatility = math.sqrt(sum((r - mean_return) ** 2 for r in returns) / len(returns))
+
+ # Annualized metrics
+ annualized_return = mean_return * 252
+ annualized_vol = volatility * math.sqrt(252)
+
+ # Regime classification
+ if annualized_return > 0.15 and annualized_vol < 0.25:
+ regime = MarketRegime.BULL
+ confidence = min(1, annualized_return / 0.3)
+ elif annualized_return < -0.15 and annualized_vol < 0.35:
+ regime = MarketRegime.BEAR
+ confidence = min(1, abs(annualized_return) / 0.3)
+ elif annualized_vol > 0.35:
+ regime = MarketRegime.TRANSITION
+ confidence = min(1, (annualized_vol - 0.25) / 0.2)
+ else:
+ regime = MarketRegime.SIDEWAYS
+ confidence = 1 - abs(annualized_return) / 0.15
+
+ return (regime, max(0.3, min(0.95, confidence)))
+
+
+def calculate_regime_duration(
+ prices: List[float],
+ current_regime: MarketRegime,
+ window: int = 20
+) -> int:
+ """Calculate how long the current regime has persisted."""
+ if len(prices) < window * 2:
+ return window
+
+ duration = 0
+ for i in range(0, len(prices) - window, window // 2):
+ regime, _ = detect_market_regime(prices[i:i + window * 2], window)
+ if regime == current_regime:
+ duration += window // 2
+ else:
+ break
+
+ return max(duration, window // 2)
+
+
+def detect_statistical_mispricing(
+ current_price: float,
+ intrinsic_estimates: List[float],
+ peer_multiples: Optional[Dict[str, float]] = None
+) -> Tuple[bool, float, float]:
+ """
+ Detect if security is statistically mispriced.
+
+ Args:
+ current_price: Current market price
+ intrinsic_estimates: List of fair value estimates
+ peer_multiples: Optional dict of peer valuation multiples
+
+ Returns:
+ Tuple of (is_mispriced, mispricing_pct, confidence)
+ """
+ if not intrinsic_estimates:
+ return (False, 0.0, 0.0)
+
+ # Calculate consensus fair value
+ mean_estimate = sum(intrinsic_estimates) / len(intrinsic_estimates)
+ std_estimate = math.sqrt(
+ sum((e - mean_estimate) ** 2 for e in intrinsic_estimates) / len(intrinsic_estimates)
+ ) if len(intrinsic_estimates) > 1 else mean_estimate * 0.1
+
+ # Mispricing percentage
+ mispricing_pct = (current_price - mean_estimate) / mean_estimate
+
+ # Statistical significance
+ z_score = abs(current_price - mean_estimate) / std_estimate if std_estimate > 0 else 0
+
+ # Consider mispriced if >1.5 standard deviations from mean estimate
+ is_mispriced = abs(z_score) > 1.5
+
+ # Confidence based on estimate consistency and deviation size
+ estimate_consistency = 1 - (std_estimate / mean_estimate) if mean_estimate > 0 else 0
+ confidence = min(1, z_score / 3) * estimate_consistency
+
+ return (is_mispriced, mispricing_pct, confidence)
+
+
+def analyze_pairs_trading(
+ series_a: List[float],
+ series_b: List[float],
+ entry_threshold: float = 2.0,
+ exit_threshold: float = 0.5
+) -> PairsTradingResult:
+ """
+ Analyze pairs trading opportunity between two securities.
+
+ Args:
+ series_a: Price series of security A (target)
+ series_b: Price series of security B (hedge)
+ entry_threshold: Z-score threshold for entry
+ exit_threshold: Z-score threshold for exit
+ """
+ details = []
+
+ if len(series_a) != len(series_b):
+ min_len = min(len(series_a), len(series_b))
+ series_a = series_a[:min_len]
+ series_b = series_b[:min_len]
+
+ if len(series_a) < 30:
+ return PairsTradingResult(
+ signal="neutral",
+ spread_z_score=0.0,
+ cointegration_score=0.0,
+ half_life=float('inf'),
+ hedge_ratio=1.0,
+ details=["Insufficient data for pairs analysis"]
+ )
+
+ # Calculate hedge ratio using OLS
+ mean_a = sum(series_a) / len(series_a)
+ mean_b = sum(series_b) / len(series_b)
+
+ numerator = sum((series_a[i] - mean_a) * (series_b[i] - mean_b) for i in range(len(series_a)))
+ denominator = sum((series_b[i] - mean_b) ** 2 for i in range(len(series_b)))
+
+ hedge_ratio = numerator / denominator if denominator != 0 else 1.0
+ details.append(f"Hedge ratio: {hedge_ratio:.3f}")
+
+ # Calculate spread
+ spread = [series_a[i] - hedge_ratio * series_b[i] for i in range(len(series_a))]
+
+ # Spread statistics
+ spread_mean = sum(spread) / len(spread)
+ spread_std = math.sqrt(sum((s - spread_mean) ** 2 for s in spread) / len(spread))
+
+ # Current z-score
+ spread_z_score = (spread[0] - spread_mean) / spread_std if spread_std > 0 else 0
+ details.append(f"Spread z-score: {spread_z_score:.2f}")
+
+ # Cointegration test (simplified Engle-Granger using Hurst exponent)
+ from .mean_reversion import calculate_hurst_exponent
+ hurst = calculate_hurst_exponent(list(reversed(spread)))
+
+ # Cointegration score (lower Hurst = more cointegrated)
+ cointegration_score = max(0, 1 - 2 * hurst) if hurst < 0.5 else 0
+ details.append(f"Cointegration score: {cointegration_score:.3f}")
+
+ # Half-life estimation
+ from .mean_reversion import estimate_half_life
+ half_life = estimate_half_life(list(reversed(spread)))
+ if half_life:
+ details.append(f"Spread half-life: {half_life:.1f} periods")
+ else:
+ half_life = float('inf')
+
+ # Trading signal
+ if cointegration_score < 0.3:
+ signal = "neutral"
+ details.append("Weak cointegration - no trade")
+ elif spread_z_score > entry_threshold:
+ signal = "short_spread" # Short A, Long B
+ details.append(f"Spread above {entry_threshold}σ - short spread")
+ elif spread_z_score < -entry_threshold:
+ signal = "long_spread" # Long A, Short B
+ details.append(f"Spread below -{entry_threshold}σ - long spread")
+ elif abs(spread_z_score) < exit_threshold:
+ signal = "neutral"
+ details.append("Spread near mean - exit/neutral")
+ else:
+ signal = "neutral"
+ details.append("No clear signal")
+
+ return PairsTradingResult(
+ signal=signal,
+ spread_z_score=spread_z_score,
+ cointegration_score=cointegration_score,
+ half_life=half_life if half_life else float('inf'),
+ hedge_ratio=hedge_ratio,
+ details=details
+ )
+
+
+def estimate_edge(
+ signal_strength: float,
+ statistical_significance: float,
+ transaction_costs_bps: float = 10
+) -> float:
+ """
+ Estimate expected edge in basis points.
+
+ Renaissance's philosophy: "We're right 50.75% of the time,
+ but we're 100% right 50.75% of the time."
+ """
+ # Base edge from signal
+ base_edge_bps = signal_strength * 50 # Max 50 bps raw edge
+
+ # Adjust for statistical significance
+ adjusted_edge = base_edge_bps * statistical_significance
+
+ # Subtract transaction costs
+ net_edge = adjusted_edge - transaction_costs_bps
+
+ return max(0, net_edge)
+
+
+def analyze_statistical_arbitrage(
+ prices: List[float],
+ intrinsic_estimates: Optional[List[float]] = None,
+ peer_prices: Optional[List[float]] = None,
+ metrics: Optional[Dict[str, Any]] = None
+) -> StatArbResult:
+ """
+ Comprehensive statistical arbitrage analysis.
+
+ Args:
+ prices: Target security price series
+ intrinsic_estimates: Fair value estimates
+ peer_prices: Comparable security prices for pairs analysis
+ metrics: Additional fundamental metrics
+ """
+ details = []
+ scores = []
+
+ if len(prices) < 30:
+ return StatArbResult(
+ arbitrage_score=0.0,
+ edge_estimate_bps=0.0,
+ mispricing_detected=False,
+ mispricing_pct=0.0,
+ regime=MarketRegime.SIDEWAYS,
+ regime_confidence=0.5,
+ details=["Insufficient data for stat arb analysis"]
+ )
+
+ # Regime detection
+ regime, regime_confidence = detect_market_regime(prices)
+ details.append(f"Market regime: {regime.value} (confidence: {regime_confidence:.2f})")
+
+ # Mispricing detection
+ mispricing_detected = False
+ mispricing_pct = 0.0
+
+ if intrinsic_estimates:
+ mispricing_detected, mispricing_pct, mispricing_conf = detect_statistical_mispricing(
+ prices[0], intrinsic_estimates
+ )
+ if mispricing_detected:
+ details.append(f"Mispricing detected: {mispricing_pct * 100:.1f}%")
+ scores.append(mispricing_conf * 10)
+ else:
+ details.append("No significant mispricing")
+ scores.append(3)
+
+ # Pairs trading analysis
+ if peer_prices and len(peer_prices) >= 30:
+ pairs_result = analyze_pairs_trading(prices, peer_prices)
+ if pairs_result.signal != "neutral":
+ details.append(f"Pairs signal: {pairs_result.signal}")
+ scores.append(pairs_result.cointegration_score * 10)
+ else:
+ scores.append(2)
+ details.extend(pairs_result.details[:2]) # Add top 2 details
+
+ # Regime transition opportunity
+ if regime == MarketRegime.TRANSITION:
+ details.append("Regime transition - elevated opportunity")
+ scores.append(7)
+ elif regime_confidence > 0.8:
+ details.append("Stable regime - reduced arbitrage opportunity")
+ scores.append(4)
+ else:
+ scores.append(5)
+
+ # Calculate composite score
+ arbitrage_score = sum(scores) / len(scores) if scores else 5.0
+
+ # Estimate edge
+ edge_estimate = estimate_edge(
+ signal_strength=(arbitrage_score - 5) / 5, # Normalize to -1 to 1
+ statistical_significance=regime_confidence
+ )
+
+ return StatArbResult(
+ arbitrage_score=min(10, max(0, arbitrage_score)),
+ edge_estimate_bps=edge_estimate,
+ mispricing_detected=mispricing_detected,
+ mispricing_pct=mispricing_pct,
+ regime=regime,
+ regime_confidence=regime_confidence,
+ details=details
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/__init__.py
new file mode 100644
index 000000000..0af947c33
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/__init__.py
@@ -0,0 +1,39 @@
+"""
+Renaissance Technologies Team Definitions
+
+Agno Teams that mirror the real organizational structure.
+"""
+
+from .research_team import (
+ create_research_team,
+ get_research_team,
+)
+from .trading_team import (
+ create_trading_team,
+ get_trading_team,
+)
+from .risk_team import (
+ create_risk_team,
+ get_risk_team,
+)
+from .medallion_fund import (
+ create_medallion_fund,
+ get_medallion_fund,
+ run_medallion_fund,
+)
+
+__all__ = [
+ # Research Team
+ "create_research_team",
+ "get_research_team",
+ # Trading Team
+ "create_trading_team",
+ "get_trading_team",
+ # Risk Team
+ "create_risk_team",
+ "get_risk_team",
+ # Medallion Fund (Top-level)
+ "create_medallion_fund",
+ "get_medallion_fund",
+ "run_medallion_fund",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/medallion_fund.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/medallion_fund.py
new file mode 100644
index 000000000..d6b323391
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/medallion_fund.py
@@ -0,0 +1,295 @@
+"""
+Medallion Fund - Top-Level Investment Committee
+
+The top-level organization that brings together all teams
+under the Investment Committee's leadership.
+
+This is the main entry point for running the multi-agent system.
+
+Organization Structure:
+┌─────────────────────────────────┐
+│ Investment Committee │
+│ (Chair + Portfolio Manager) │
+└───────────────┬─────────────────┘
+ │
+ ┌───────────┼───────────┐
+ │ │ │
+ ▼ ▼ ▼
+┌────────┐ ┌────────┐ ┌────────┐
+│Research│ │Trading │ │ Risk │
+│ Team │ │ Team │ │ Team │
+└────────┘ └────────┘ └────────┘
+"""
+
+from typing import Optional, Any, Dict
+from agno.team import Team
+
+from ..agents import (
+ create_investment_committee_chair,
+ create_portfolio_manager,
+)
+from .research_team import create_research_team
+from .trading_team import create_trading_team
+from .risk_team import create_risk_team
+from ..config import get_config, RenTechConfig
+from ..utils.model_factory import create_model_from_config
+
+
+# Global fund instance
+_medallion_fund: Optional[Team] = None
+
+
+def create_medallion_fund(config: Optional[RenTechConfig] = None) -> Team:
+ """
+ Create the Medallion Fund - the complete organization.
+
+ This is a nested Team structure:
+ - Investment Committee Chair (leader)
+ - Portfolio Manager (member)
+ - Research Team (nested team)
+ - Trading Team (nested team)
+ - Risk Team (nested team)
+
+ The Investment Committee Chair has final decision authority
+ on all trading decisions, capital allocation, and risk limits.
+ """
+ cfg = config or get_config()
+
+ # Create the Investment Committee members
+ ic_chair = create_investment_committee_chair(cfg)
+ portfolio_manager = create_portfolio_manager(cfg)
+
+ # Create the sub-teams
+ research_team = create_research_team(cfg)
+ trading_team = create_trading_team(cfg)
+ risk_team = create_risk_team(cfg)
+
+ # Create the top-level team
+ # Note: IC Chair is first in members list to act as coordinator
+ medallion_fund = Team(
+ name="Medallion Fund Investment Committee",
+ description="""Top-level decision-making body for the Medallion Fund.
+ Approves all trading signals, allocates capital, and sets risk limits.
+ Synthesizes input from Research, Trading, and Risk teams to make
+ systematic investment decisions.""",
+
+ # Members include both individuals and teams (no 'leader' param in Agno)
+ # IC Chair is first to act as coordinator
+ members=[
+ ic_chair, # Acts as team coordinator
+ portfolio_manager,
+ research_team,
+ trading_team,
+ risk_team,
+ ],
+
+ # Model for committee-level decisions (uses dynamic factory)
+ model=create_model_from_config({
+ "temperature": cfg.models.temperature,
+ "max_tokens": cfg.models.max_tokens,
+ }),
+
+ # Full collaboration - all members see all interactions
+ share_member_interactions=cfg.share_interactions,
+ add_team_history_to_members=True, # Correct param name
+
+ # Memory for learning from decisions
+ enable_agentic_memory=cfg.enable_memory,
+
+ # Instructions for the Investment Committee
+ instructions="""
+## Medallion Fund Investment Committee
+
+You are the Investment Committee of Renaissance Technologies' Medallion Fund,
+one of the most successful quantitative hedge funds in history.
+
+## Your Mission
+
+Make systematic, data-driven investment decisions that maximize risk-adjusted
+returns while maintaining strict risk controls. We are scientists who happen
+to trade, not traders who use science.
+
+## Decision Authority
+
+The Investment Committee Chair has final authority on:
+- Signal approval/rejection
+- Capital allocation across strategies
+- Risk limit setting and modification
+- Trading halts and resumptions
+
+## Team Coordination Protocol
+
+When a task arrives, route it appropriately:
+
+### Signal Research
+→ Route to **Research Team**
+- Signal discovery
+- Data preparation
+- Statistical validation
+- Backtest requests
+
+### Trade Execution
+→ Route to **Trading Team**
+- Execution planning
+- Order routing
+- Market making
+- Post-trade analysis
+
+### Risk Assessment
+→ Route to **Risk Team**
+- VaR calculations
+- Stress tests
+- Compliance checks
+- Position monitoring
+
+### Portfolio Decisions
+→ Route to **Portfolio Manager**
+- Capital allocation
+- Strategy weights
+- Rebalancing
+- Performance attribution
+
+### Final Approval
+→ **Investment Committee Chair** reviews and decides
+
+## Standard Operating Procedure
+
+For a typical signal-to-trade workflow:
+
+1. **Research Team** discovers and validates signal
+2. **Risk Team** assesses risk implications
+3. **Portfolio Manager** determines sizing
+4. **Investment Committee Chair** approves/rejects
+5. **Trading Team** executes if approved
+6. **Risk Team** monitors positions
+
+## Communication Protocol
+
+All inter-team communication should be:
+- Precise and quantitative
+- Include confidence levels
+- Reference supporting data
+- Note any concerns or caveats
+
+## Decision Output Format
+
+When making decisions, the Chair should provide:
+
+```
+══════════════════════════════════════
+INVESTMENT COMMITTEE DECISION
+══════════════════════════════════════
+
+REQUEST: [What was requested]
+
+TEAM INPUTS:
+- Research: [Summary of research input]
+- Risk: [Summary of risk assessment]
+- Trading: [Summary of execution plan]
+- Portfolio: [Summary of sizing/allocation]
+
+DECISION: [APPROVED / REJECTED / PENDING]
+
+RATIONALE:
+1. [Key reason 1]
+2. [Key reason 2]
+3. [Key reason 3]
+
+CONDITIONS (if approved):
+- [Condition 1]
+- [Condition 2]
+
+NEXT STEPS:
+- [Who does what next]
+
+══════════════════════════════════════
+```
+
+## Core Principles
+
+1. **Statistical Rigor**: P-value < 0.01 or we don't trade
+2. **Risk First**: Capital preservation is paramount
+3. **Edge Focus**: We're right 50.75% of the time - that's enough
+4. **Systematic**: No discretionary overrides of the model
+5. **Continuous Learning**: Update models with every trade
+
+## Remember
+
+"We hire people who have done good science" - Jim Simons
+"We're right 50.75% of the time" - Bob Mercer
+
+Focus on the process. Let the edge compound.
+""",
+
+ markdown=True,
+ show_members_responses=True,
+ )
+
+ return medallion_fund
+
+
+def get_medallion_fund() -> Team:
+ """Get or create the global Medallion Fund instance"""
+ global _medallion_fund
+ if _medallion_fund is None:
+ _medallion_fund = create_medallion_fund()
+ return _medallion_fund
+
+
+def reset_medallion_fund():
+ """Reset the global Medallion Fund instance"""
+ global _medallion_fund
+ _medallion_fund = None
+
+
+async def run_medallion_fund(
+ task: str,
+ context: Optional[Dict[str, Any]] = None,
+ stream: bool = False,
+) -> str:
+ """
+ Run a task through the Medallion Fund organization.
+
+ This is the main entry point for the multi-agent system.
+ Tasks are routed to appropriate teams based on content.
+
+ Args:
+ task: The task or question to process
+ context: Optional additional context
+ stream: Whether to stream the response
+
+ Returns:
+ The response from the organization
+
+ Example:
+ >>> response = await run_medallion_fund(
+ ... "Analyze AAPL for mean reversion signals and recommend a trade"
+ ... )
+ """
+ fund = get_medallion_fund()
+
+ # Build the message with context if provided
+ message = task
+ if context:
+ context_str = "\n".join([f"- {k}: {v}" for k, v in context.items()])
+ message = f"{task}\n\nContext:\n{context_str}"
+
+ # Run through the team
+ if stream:
+ response_parts = []
+ async for chunk in fund.run_stream(message):
+ response_parts.append(chunk)
+ return "".join(response_parts)
+ else:
+ response = fund.run(message)
+ return response.content if hasattr(response, 'content') else str(response)
+
+
+# Convenience function for synchronous usage
+def run_medallion_fund_sync(
+ task: str,
+ context: Optional[Dict[str, Any]] = None,
+) -> str:
+ """Synchronous version of run_medallion_fund"""
+ import asyncio
+ return asyncio.run(run_medallion_fund(task, context, stream=False))
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/research_team.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/research_team.py
new file mode 100644
index 000000000..ae9d30183
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/research_team.py
@@ -0,0 +1,146 @@
+"""
+Research Team - Alpha Generation
+
+The quantitative research team responsible for discovering and validating
+trading signals. Mirrors RenTech's actual research organization.
+
+Team Structure:
+- Research Lead (team leader)
+- Signal Scientist (pattern discovery)
+- Data Scientist (data infrastructure)
+- Quant Researcher (statistical modeling)
+"""
+
+from typing import Optional
+from agno.team import Team
+
+from ..agents import (
+ create_research_lead,
+ create_signal_scientist,
+ create_data_scientist,
+ create_quant_researcher,
+)
+from ..config import get_config, RenTechConfig
+from ..utils.model_factory import create_model_from_config
+
+
+# Global team instance
+_research_team: Optional[Team] = None
+
+
+def create_research_team(config: Optional[RenTechConfig] = None) -> Team:
+ """
+ Create the Research Team.
+
+ This team is responsible for:
+ - Signal discovery and validation
+ - Data preparation and feature engineering
+ - Statistical modeling and backtesting
+ - Research quality control
+
+ The team collaborates closely, sharing discoveries and critiquing
+ each other's work - just like the real RenTech research environment.
+ """
+ cfg = config or get_config()
+
+ # Create individual agents
+ research_lead = create_research_lead(cfg)
+ signal_scientist = create_signal_scientist(cfg)
+ data_scientist = create_data_scientist(cfg)
+ quant_researcher = create_quant_researcher(cfg)
+
+ # Create the team
+ # Note: Research Lead is first in members list to act as coordinator
+ team = Team(
+ name="Quantitative Research Team",
+ description="""Alpha generation team responsible for discovering and
+ validating trading signals. Combines expertise in mathematics,
+ statistics, and data science to identify market inefficiencies.""",
+
+ # Team composition (no 'leader' param in Agno - first member coordinates)
+ members=[
+ research_lead, # Acts as team coordinator
+ signal_scientist,
+ data_scientist,
+ quant_researcher,
+ ],
+
+ # Model for team-level decisions (uses dynamic factory)
+ model=create_model_from_config({
+ "temperature": cfg.models.temperature,
+ "max_tokens": cfg.models.max_tokens,
+ }),
+
+ # Collaboration settings
+ share_member_interactions=cfg.share_interactions,
+ add_team_history_to_members=True, # Correct param name
+
+ # Memory (will be enhanced in Phase 5)
+ enable_agentic_memory=cfg.enable_memory,
+
+ # Instructions for the team as a whole
+ instructions="""
+## Research Team Mission
+
+You are the Quantitative Research Team at Renaissance Technologies.
+Your mission is to discover statistically significant trading signals
+that can generate alpha while maintaining rigorous scientific standards.
+
+## Team Workflow
+
+1. **Data Preparation** (Data Scientist)
+ - Clean and validate market data
+ - Create derived features
+ - Ensure point-in-time correctness
+
+2. **Signal Discovery** (Signal Scientist)
+ - Explore patterns in the data
+ - Calculate statistical significance
+ - Initial signal development
+
+3. **Statistical Validation** (Quant Researcher)
+ - Rigorous backtesting
+ - Cross-validation
+ - Regime analysis
+
+4. **Quality Control** (Research Lead)
+ - Review all findings
+ - Ensure standards are met
+ - Approve for Investment Committee
+
+## Standards
+
+- P-value < 0.01 for any signal
+- Out-of-sample validation required
+- Economic rationale must exist
+- Transaction costs must be considered
+- Capacity must be sufficient
+
+## Collaboration
+
+Share findings openly within the team. Encourage constructive
+criticism. Better to kill a bad idea early than waste resources.
+
+Remember: "We hire people who have done good science" - Jim Simons
+""",
+
+ # Markdown output for readability
+ markdown=True,
+ show_members_responses=True,
+ )
+
+ return team
+
+
+def get_research_team() -> Team:
+ """Get or create the global Research Team instance"""
+ global _research_team
+ if _research_team is None:
+ _research_team = create_research_team()
+ return _research_team
+
+
+def reset_research_team():
+ """Reset the global Research Team instance"""
+ global _research_team
+ _research_team = None
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/risk_team.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/risk_team.py
new file mode 100644
index 000000000..76df8c195
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/risk_team.py
@@ -0,0 +1,161 @@
+"""
+Risk Management Team - Controls & Compliance
+
+The risk team responsible for monitoring and controlling
+risk across all activities. Has authority to halt trading.
+
+Team Structure:
+- Risk Quant (team leader, risk measurement)
+- Compliance Officer (regulatory compliance)
+"""
+
+from typing import Optional
+from agno.team import Team
+
+from ..agents import (
+ create_risk_quant,
+ create_compliance_officer,
+)
+from ..config import get_config, RenTechConfig
+from ..utils.model_factory import create_model_from_config
+
+
+# Global team instance
+_risk_team: Optional[Team] = None
+
+
+def create_risk_team(config: Optional[RenTechConfig] = None) -> Team:
+ """
+ Create the Risk Management Team.
+
+ This team is responsible for:
+ - Risk measurement and monitoring
+ - Position and exposure limits
+ - Regulatory compliance
+ - Trade surveillance
+
+ Both members must agree on risk issues - this is a
+ consensus-required team for critical decisions.
+ """
+ cfg = config or get_config()
+
+ # Create individual agents
+ risk_quant = create_risk_quant(cfg)
+ compliance_officer = create_compliance_officer(cfg)
+
+ # Create the team
+ # Note: Risk Quant is first in members list to act as coordinator
+ team = Team(
+ name="Risk Management Team",
+ description="""Monitors and controls risk across all activities.
+ Has authority to halt trading if risk limits are breached.
+ Reports directly to Investment Committee.""",
+
+ # Team composition (no 'leader' param in Agno - first member coordinates)
+ members=[
+ risk_quant, # Acts as team coordinator
+ compliance_officer,
+ ],
+
+ # Model for team-level decisions
+ model=create_model_from_config({
+ "temperature": cfg.models.temperature,
+ "max_tokens": cfg.models.max_tokens,
+ }),
+
+ # Both see all risk queries
+ share_member_interactions=True,
+ add_team_history_to_members=True, # Correct param name
+
+ # Memory for learning from past events
+ enable_agentic_memory=cfg.enable_memory,
+
+ # Instructions
+ instructions="""
+## Risk Management Team Mission
+
+You are the Risk Management Team at Renaissance Technologies.
+Your mission is to protect the firm from excessive risk while
+enabling profitable trading within defined limits.
+
+## Team Authority
+
+You have the authority to:
+- APPROVE trades within risk limits
+- REJECT trades that breach limits
+- HALT trading if systemic risk detected
+- ESCALATE to Investment Committee
+
+## Risk Framework
+
+### Hard Limits (Cannot be breached)
+- Daily VaR: 2% of NAV
+- Max Drawdown: 15%
+- Position Size: 5% of NAV
+- Sector Exposure: 25% of NAV
+- Leverage: 12.5x gross
+
+### Soft Limits (Warning triggers)
+- Daily VaR: 1.5% (warning)
+- Drawdown: 10% (escalation)
+- Concentration: approaching limits
+
+## Team Workflow
+
+1. **Pre-Trade Risk Check** (Both members)
+ - Risk Quant: Calculate marginal VaR, exposures
+ - Compliance: Check position limits, restricted list
+
+2. **Real-Time Monitoring** (Continuous)
+ - Monitor aggregate risk metrics
+ - Watch for unusual patterns
+ - Track limit utilization
+
+3. **Post-Trade Analysis** (Daily)
+ - Review all trades
+ - Update risk models
+ - Generate reports
+
+## Consensus Requirement
+
+For risk REJECTIONS, both team members should agree.
+If either member identifies a critical issue, the trade
+should be blocked pending further review.
+
+## Escalation Protocol
+
+Escalate immediately to Investment Committee:
+- Any hard limit breach
+- Drawdown > 10%
+- Unusual market conditions
+- Regulatory concerns
+- Potential compliance issues
+
+## Risk Philosophy
+
+"Capital preservation is paramount. We can always
+make money tomorrow if we protect capital today."
+
+Never compromise on risk limits. When in doubt,
+reduce exposure.
+""",
+
+ markdown=True,
+ show_members_responses=True,
+ )
+
+ return team
+
+
+def get_risk_team() -> Team:
+ """Get or create the global Risk Team instance"""
+ global _risk_team
+ if _risk_team is None:
+ _risk_team = create_risk_team()
+ return _risk_team
+
+
+def reset_risk_team():
+ """Reset the global Risk Team instance"""
+ global _risk_team
+ _risk_team = None
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/trading_team.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/trading_team.py
new file mode 100644
index 000000000..f57b81b2c
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/teams/trading_team.py
@@ -0,0 +1,149 @@
+"""
+Trading Team - Execution Excellence
+
+The execution team responsible for converting signals into trades
+with minimal market impact and optimal execution quality.
+
+Team Structure:
+- Execution Trader (team leader, optimal execution)
+- Market Maker (liquidity provision)
+"""
+
+from typing import Optional
+from agno.team import Team
+
+from ..agents import (
+ create_execution_trader,
+ create_market_maker,
+)
+from ..config import get_config, RenTechConfig
+from ..utils.model_factory import create_model_from_config
+
+
+# Global team instance
+_trading_team: Optional[Team] = None
+
+
+def create_trading_team(config: Optional[RenTechConfig] = None) -> Team:
+ """
+ Create the Trading Team.
+
+ This team is responsible for:
+ - Optimal trade execution
+ - Market impact minimization
+ - Smart order routing
+ - Market making activities
+
+ The team operates in real-time, coordinating execution
+ across multiple venues and strategies.
+ """
+ cfg = config or get_config()
+
+ # Create individual agents
+ execution_trader = create_execution_trader(cfg)
+ market_maker = create_market_maker(cfg)
+
+ # Create the team
+ # Note: Execution Trader is first in members list to act as coordinator
+ team = Team(
+ name="Execution & Trading Team",
+ description="""Responsible for executing trades with minimal market
+ impact and managing market-making activities. Focus on preserving
+ alpha through optimal execution.""",
+
+ # Team composition (no 'leader' param in Agno - first member coordinates)
+ members=[
+ execution_trader, # Acts as team coordinator
+ market_maker,
+ ],
+
+ # Model for team-level decisions
+ model=create_model_from_config({
+ "temperature": cfg.models.temperature,
+ "max_tokens": cfg.models.max_tokens,
+ }),
+
+ # Collaboration settings
+ share_member_interactions=cfg.share_interactions,
+ add_team_history_to_members=True, # Correct param name
+
+ # Memory
+ enable_agentic_memory=cfg.enable_memory,
+
+ # Instructions
+ instructions="""
+## Trading Team Mission
+
+You are the Execution & Trading Team at Renaissance Technologies.
+Your mission is to convert trading signals into actual positions
+while minimizing execution costs and market impact.
+
+## Team Workflow
+
+1. **Pre-Trade Analysis**
+ - Assess market conditions
+ - Calculate expected impact
+ - Select execution algorithm
+ - Plan order schedule
+
+2. **Execution**
+ - Route orders optimally
+ - Monitor real-time fills
+ - Adjust for market conditions
+ - Coordinate with market maker
+
+3. **Post-Trade Analysis**
+ - Calculate actual vs expected costs
+ - Update execution models
+ - Report performance
+
+## Execution Priorities
+
+1. **Preserve Alpha** - Don't leak information
+2. **Minimize Impact** - Trade without moving market
+3. **Achieve Best Price** - Beat benchmarks
+4. **Ensure Fill** - Complete the order
+
+## Coordination
+
+The Execution Trader leads all execution decisions.
+The Market Maker provides liquidity insights and helps
+with spread capture when appropriate.
+
+## Real-Time Requirements
+
+Trading requires immediate responses. Always:
+- Monitor current market state
+- Adjust in real-time
+- Escalate issues immediately
+- Log all decisions for audit
+
+## Performance Metrics
+
+Track and optimize:
+- Implementation shortfall
+- VWAP/TWAP performance
+- Market impact
+- Fill rates
+- Alpha preservation
+""",
+
+ markdown=True,
+ show_members_responses=True,
+ )
+
+ return team
+
+
+def get_trading_team() -> Team:
+ """Get or create the global Trading Team instance"""
+ global _trading_team
+ if _trading_team is None:
+ _trading_team = create_trading_team()
+ return _trading_team
+
+
+def reset_trading_team():
+ """Reset the global Trading Team instance"""
+ global _trading_team
+ _trading_team = None
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tests/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tests/__init__.py
new file mode 100644
index 000000000..95343a8ad
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tests/__init__.py
@@ -0,0 +1,11 @@
+"""
+Renaissance Technologies Test Suite
+
+Tests for the multi-agent system.
+"""
+
+from .test_glm_model import run_all_tests
+
+__all__ = [
+ "run_all_tests",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tests/test_glm_model.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tests/test_glm_model.py
new file mode 100644
index 000000000..61739b2a3
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tests/test_glm_model.py
@@ -0,0 +1,974 @@
+"""
+Renaissance Technologies Multi-Agent System - Full Integration Test
+
+Comprehensive test covering ALL components:
+1. Configuration & Model Factory
+2. Individual Agents (10 agents)
+3. Teams (Research, Trading, Risk, Medallion Fund)
+4. Workflows (Signal Discovery, Validation, Risk Assessment, Execution, Post-Trade)
+5. Knowledge Base
+6. Memory System
+7. Reasoning Engine
+8. Guardrails
+9. Evaluation
+10. Tracing
+
+Usage:
+ python -m renaissance_technologies_hedge_fund_agent.tests.test_glm_model
+"""
+
+import asyncio
+from datetime import datetime
+from typing import Dict, Any, Optional
+
+
+# =============================================================================
+# HELPER: Create Model
+# =============================================================================
+
+def get_model():
+ """Create model dynamically from frontend config"""
+ from ..utils.model_factory import create_model_from_config
+ return create_model_from_config()
+
+
+def print_section(title: str):
+ """Print a section header"""
+ print("\n" + "=" * 70)
+ print(f" {title}")
+ print("=" * 70)
+
+
+def print_result(name: str, passed: bool, details: str = ""):
+ """Print test result"""
+ status = "[PASS]" if passed else "[FAIL]"
+ print(f" {status}: {name}")
+ if details and not passed:
+ print(f" {details}")
+
+
+# =============================================================================
+# 1. CONFIGURATION & MODEL FACTORY
+# =============================================================================
+
+def test_configuration() -> bool:
+ """Test configuration loading"""
+ print_section("1. CONFIGURATION")
+
+ try:
+ from ..config import get_config, ModelProvider
+
+ config = get_config()
+
+ print(f" Provider: {config.models.provider.value}")
+ print(f" Model: {config.models.model_id}")
+ print(f" Base URL: {config.models.anthropic_base_url}")
+ print(f" Risk Limits - Max Position: {config.risk_limits.max_position_size_pct}%")
+ print(f" Risk Limits - Max Leverage: {config.risk_limits.max_leverage}x")
+
+ assert config.models.provider == ModelProvider.ANTHROPIC
+ # Model ID loaded from frontend config
+
+ print_result("Configuration loaded", True)
+ return True
+ except Exception as e:
+ print_result("Configuration loaded", False, str(e))
+ return False
+
+
+def test_model_factory() -> bool:
+ """Test model factory"""
+ try:
+ from ..models.model_factory import create_model, get_model_info
+
+ info = get_model_info()
+ print(f" Model Info: {info['provider']}:{info['model_id']}")
+
+ model = create_model()
+ print(f" Model Type: {type(model).__name__}")
+
+ print_result("Model factory", True)
+ return True
+ except Exception as e:
+ print_result("Model factory", False, str(e))
+ return False
+
+
+# =============================================================================
+# 2. INDIVIDUAL AGENTS
+# =============================================================================
+
+async def test_agents() -> Dict[str, bool]:
+ """Test all individual agents"""
+ print_section("2. INDIVIDUAL AGENTS")
+
+ results = {}
+ model = get_model()
+
+ agents_to_test = [
+ ("Signal Scientist", "signal_scientist"),
+ ("Data Scientist", "data_scientist"),
+ ("Quant Researcher", "quant_researcher"),
+ ("Research Lead", "research_lead"),
+ ("Execution Trader", "execution_trader"),
+ ("Market Maker", "market_maker"),
+ ("Risk Quant", "risk_quant"),
+ ("Compliance Officer", "compliance_officer"),
+ ("Portfolio Manager", "portfolio_manager"),
+ ("Investment Committee", "investment_committee"),
+ ]
+
+ for name, agent_type in agents_to_test:
+ try:
+ from agno.agent import Agent
+
+ agent = Agent(
+ model=model,
+ name=name,
+ description=f"RenTech {name}",
+ instructions=[f"You are a {name} at Renaissance Technologies."],
+ )
+
+ # Quick test - just verify agent creation
+ results[agent_type] = True
+ print_result(name, True)
+
+ except Exception as e:
+ results[agent_type] = False
+ print_result(name, False, str(e))
+
+ return results
+
+
+async def test_agent_interaction() -> bool:
+ """Test agent can respond to prompts"""
+ print("\n Testing agent interaction...")
+
+ try:
+ from agno.agent import Agent
+ model = get_model()
+
+ agent = Agent(
+ model=model,
+ name="Signal Scientist",
+ description="Quantitative signal researcher",
+ instructions=["Analyze signals with statistical rigor. Be brief."],
+ )
+
+ response = agent.run("What is a p-value? One sentence only.")
+ content = response.content if hasattr(response, 'content') else str(response)
+
+ print(f" Response: {content[:100]}...")
+ print_result("Agent interaction", True)
+ return True
+
+ except Exception as e:
+ print_result("Agent interaction", False, str(e))
+ return False
+
+
+# =============================================================================
+# 3. TEAMS
+# =============================================================================
+
+def test_teams() -> Dict[str, bool]:
+ """Test team structures"""
+ print_section("3. TEAMS")
+
+ results = {}
+
+ teams = [
+ ("Research Team", "teams.research_team", "create_research_team"),
+ ("Trading Team", "teams.trading_team", "create_trading_team"),
+ ("Risk Team", "teams.risk_team", "create_risk_team"),
+ ("Medallion Fund", "teams.medallion_fund", "create_medallion_fund"),
+ ]
+
+ for name, module, func_name in teams:
+ try:
+ # Test import
+ exec(f"from ..{module} import {func_name}")
+ results[name] = True
+ print_result(name, True)
+ except Exception as e:
+ results[name] = False
+ print_result(name, False, str(e))
+
+ return results
+
+
+# =============================================================================
+# 4. WORKFLOWS
+# =============================================================================
+
+def test_workflows() -> Dict[str, bool]:
+ """Test workflow definitions"""
+ print_section("4. WORKFLOWS")
+
+ results = {}
+
+ workflows = [
+ ("Signal Discovery", "SignalDiscoveryWorkflow"),
+ ("Signal Validation", "SignalValidationWorkflow"),
+ ("Risk Assessment", "RiskAssessmentWorkflow"),
+ ("Execution Pipeline", "ExecutionPipelineWorkflow"),
+ ("Post Trade Analysis", "PostTradeWorkflow"),
+ ("Daily Trading Cycle", "DailyTradingCycleWorkflow"),
+ ]
+
+ for name, class_name in workflows:
+ try:
+ from ..workflows import (
+ SignalDiscoveryWorkflow,
+ SignalValidationWorkflow,
+ RiskAssessmentWorkflow,
+ ExecutionPipelineWorkflow,
+ PostTradeWorkflow,
+ DailyTradingCycleWorkflow,
+ )
+ results[name] = True
+ print_result(name, True)
+ except Exception as e:
+ results[name] = False
+ print_result(name, False, str(e))
+
+ return results
+
+
+def test_workflow_base() -> bool:
+ """Test workflow base structures"""
+ try:
+ from ..workflows.base import (
+ WorkflowContext,
+ WorkflowResult,
+ StepResult,
+ SignalData,
+ RiskAssessment,
+ )
+
+ # Create sample signal
+ signal = SignalData(
+ signal_id="TEST_001",
+ ticker="AAPL",
+ signal_type="momentum",
+ direction="long",
+ strength=0.75,
+ confidence=0.85,
+ p_value=0.008,
+ information_coefficient=0.05,
+ )
+
+ print(f" Sample Signal: {signal.signal_id} - {signal.ticker} ({signal.direction})")
+ print_result("Workflow base structures", True)
+ return True
+
+ except Exception as e:
+ print_result("Workflow base structures", False, str(e))
+ return False
+
+
+# =============================================================================
+# 5. KNOWLEDGE BASE
+# =============================================================================
+
+def test_knowledge() -> Dict[str, bool]:
+ """Test knowledge base components"""
+ print_section("5. KNOWLEDGE BASE")
+
+ results = {}
+
+ try:
+ from ..knowledge import KnowledgeCategory
+ from ..knowledge.base import KnowledgeDocument
+
+ # Test category enum
+ categories = list(KnowledgeCategory)
+ print(f" Categories: {[c.value for c in categories]}")
+ results["Categories"] = True
+ print_result("Knowledge categories", True)
+
+ except Exception as e:
+ results["Categories"] = False
+ print_result("Knowledge categories", False, str(e))
+
+ try:
+ from ..knowledge.base import KnowledgeDocument, KnowledgeCategory
+
+ doc = KnowledgeDocument(
+ id="test_doc_001",
+ category=KnowledgeCategory.RESEARCH,
+ title="Test Research Paper",
+ content="Statistical analysis of momentum signals.",
+ tags=["momentum", "research"],
+ )
+
+ print(f" Document: {doc.title}")
+ results["Document Creation"] = True
+ print_result("Document creation", True)
+
+ except Exception as e:
+ results["Document Creation"] = False
+ print_result("Document creation", False, str(e))
+
+ # Test specialized knowledge
+ knowledge_types = [
+ ("Market Data Knowledge", "market_data"),
+ ("Research Knowledge", "research_papers"),
+ ("Strategy Knowledge", "strategy_docs"),
+ ("Trade History Knowledge", "trade_history"),
+ ]
+
+ for name, module in knowledge_types:
+ try:
+ exec(f"from ..knowledge.{module} import *")
+ results[name] = True
+ print_result(name, True)
+ except Exception as e:
+ results[name] = False
+ print_result(name, False, str(e))
+
+ return results
+
+
+# =============================================================================
+# 6. MEMORY SYSTEM
+# =============================================================================
+
+def test_memory() -> Dict[str, bool]:
+ """Test memory system"""
+ print_section("6. MEMORY SYSTEM")
+
+ results = {}
+
+ try:
+ from ..memory import MemoryType, MemoryEntry
+
+ print(f" Memory Types: {[t.value for t in MemoryType]}")
+ results["Memory Types"] = True
+ print_result("Memory types", True)
+
+ except Exception as e:
+ results["Memory Types"] = False
+ print_result("Memory types", False, str(e))
+
+ memory_types = [
+ ("Trade Memory", "trade_memory"),
+ ("Decision Memory", "decision_memory"),
+ ("Learning Memory", "learning_memory"),
+ ("Agent Memory", "agent_memory"),
+ ]
+
+ for name, module in memory_types:
+ try:
+ exec(f"from ..memory.{module} import *")
+ results[name] = True
+ print_result(name, True)
+ except Exception as e:
+ results[name] = False
+ print_result(name, False, str(e))
+
+ return results
+
+
+# =============================================================================
+# 7. REASONING ENGINE
+# =============================================================================
+
+def test_reasoning() -> Dict[str, bool]:
+ """Test reasoning components"""
+ print_section("7. REASONING ENGINE")
+
+ results = {}
+
+ reasoning_modules = [
+ ("Base Reasoning", "base"),
+ ("Investment Reasoning", "investment_reasoning"),
+ ("Risk Reasoning", "risk_reasoning"),
+ ("IC Deliberation", "ic_deliberation"),
+ ]
+
+ for name, module in reasoning_modules:
+ try:
+ exec(f"from ..reasoning.{module} import *")
+ results[name] = True
+ print_result(name, True)
+ except Exception as e:
+ results[name] = False
+ print_result(name, False, str(e))
+
+ return results
+
+
+# =============================================================================
+# 8. GUARDRAILS
+# =============================================================================
+
+def test_guardrails() -> Dict[str, bool]:
+ """Test guardrail system"""
+ print_section("8. GUARDRAILS")
+
+ results = {}
+
+ try:
+ from ..guardrails import (
+ Guardrail,
+ GuardrailResult,
+ GuardrailSeverity,
+ GuardrailRegistry,
+ )
+
+ print(f" Severity Levels: {[s.value for s in GuardrailSeverity]}")
+ results["Base Guardrails"] = True
+ print_result("Base guardrails", True)
+
+ except Exception as e:
+ results["Base Guardrails"] = False
+ print_result("Base guardrails", False, str(e))
+
+ guardrail_types = [
+ ("Risk Guardrails", "risk_guardrails"),
+ ("Compliance Guardrails", "compliance_guardrails"),
+ ("Signal Guardrails", "signal_guardrails"),
+ ("Execution Guardrails", "execution_guardrails"),
+ ]
+
+ for name, module in guardrail_types:
+ try:
+ exec(f"from ..guardrails.{module} import *")
+ results[name] = True
+ print_result(name, True)
+ except Exception as e:
+ results[name] = False
+ print_result(name, False, str(e))
+
+ # Test guardrail execution
+ try:
+ from ..guardrails import PositionSizeGuardrail
+
+ # PositionSizeGuardrail takes no constructor args - config is loaded internally
+ guardrail = PositionSizeGuardrail()
+ result = guardrail.check({"position_size_pct": 3.0, "ticker": "AAPL"})
+
+ print(f" Position Size Check (3%): {'PASS' if result.passed else 'FAIL'}")
+ results["Guardrail Execution"] = True
+ print_result("Guardrail execution", True)
+
+ except Exception as e:
+ results["Guardrail Execution"] = False
+ print_result("Guardrail execution", False, str(e))
+
+ return results
+
+
+# =============================================================================
+# 9. EVALUATION
+# =============================================================================
+
+def test_evaluation() -> Dict[str, bool]:
+ """Test evaluation system"""
+ print_section("9. EVALUATION")
+
+ results = {}
+
+ eval_types = [
+ ("Signal Evaluator", "signal_evaluation"),
+ ("Trade Evaluator", "trade_evaluation"),
+ ("Agent Evaluator", "agent_evaluation"),
+ ("System Evaluator", "system_evaluation"),
+ ]
+
+ for name, module in eval_types:
+ try:
+ exec(f"from ..evaluation.{module} import *")
+ results[name] = True
+ print_result(name, True)
+ except Exception as e:
+ results[name] = False
+ print_result(name, False, str(e))
+
+ return results
+
+
+# =============================================================================
+# 10. TRACING
+# =============================================================================
+
+def test_tracing() -> Dict[str, bool]:
+ """Test tracing system"""
+ print_section("10. TRACING")
+
+ results = {}
+
+ tracing_components = [
+ ("Base Tracer", "base"),
+ ("Agent Tracer", "agent_tracer"),
+ ("Workflow Tracer", "workflow_tracer"),
+ ("Metrics Collector", "metrics_collector"),
+ ]
+
+ for name, module in tracing_components:
+ try:
+ exec(f"from ..tracing.{module} import *")
+ results[name] = True
+ print_result(name, True)
+ except Exception as e:
+ results[name] = False
+ print_result(name, False, str(e))
+
+ return results
+
+
+# =============================================================================
+# 11. FULL SYSTEM INTEGRATION
+# =============================================================================
+
+async def test_full_system() -> bool:
+ """Test complete system integration"""
+ print_section("11. FULL SYSTEM INTEGRATION")
+
+ try:
+ from ..main import RenaissanceTechnologiesSystem
+ from ..config import get_config
+
+ print(" Initializing RenTech System...")
+ system = RenaissanceTechnologiesSystem()
+
+ # Get config separately (system doesn't store it as attribute)
+ config = get_config()
+ print(f" System Name: {config.name}")
+ print(f" Environment: {config.environment}")
+ print(f" Model Provider: {system.model_provider or 'Pure Quant (no LLM)'}")
+
+ print_result("System initialization", True)
+ return True
+
+ except Exception as e:
+ print_result("System initialization", False, str(e))
+ return False
+
+
+async def test_end_to_end_signal_analysis() -> bool:
+ """Test end-to-end signal analysis flow"""
+ print("\n Running end-to-end signal analysis...")
+
+ try:
+ from agno.agent import Agent
+ from ..workflows.base import SignalData
+
+ model = get_model()
+
+ # Create signal
+ signal = SignalData(
+ signal_id="E2E_TEST_001",
+ ticker="MSFT",
+ signal_type="mean_reversion",
+ direction="long",
+ strength=0.68,
+ confidence=0.82,
+ p_value=0.012,
+ information_coefficient=0.045,
+ )
+
+ # Step 1: Research Analysis
+ research_agent = Agent(
+ model=model,
+ name="Research Analyst",
+ instructions=["Analyze signals briefly. 2 sentences max."],
+ )
+
+ research_response = research_agent.run(
+ f"Signal: {signal.ticker} {signal.signal_type}, p-value={signal.p_value}, IC={signal.information_coefficient}. Valid?"
+ )
+ print(f" Research: {str(research_response.content)[:80]}...")
+
+ # Step 2: Risk Assessment
+ risk_agent = Agent(
+ model=model,
+ name="Risk Analyst",
+ instructions=["Assess risk briefly. 2 sentences max."],
+ )
+
+ risk_response = risk_agent.run(
+ f"Position: 2% NAV in {signal.ticker}. Max drawdown risk?"
+ )
+ print(f" Risk: {str(risk_response.content)[:80]}...")
+
+ # Step 3: Final Decision
+ pm_agent = Agent(
+ model=model,
+ name="Portfolio Manager",
+ instructions=["Make decision: APPROVE or REJECT. One sentence."],
+ )
+
+ pm_response = pm_agent.run(
+ f"Signal {signal.ticker}: p={signal.p_value}, conf={signal.confidence}. Approve?"
+ )
+ print(f" Decision: {str(pm_response.content)[:80]}...")
+
+ print_result("End-to-end signal analysis", True)
+ return True
+
+ except Exception as e:
+ print_result("End-to-end signal analysis", False, str(e))
+ return False
+
+
+async def test_ic_deliberation() -> bool:
+ """Test full Investment Committee deliberation with voting and reasoning"""
+ print("\n Running IC Deliberation test...")
+ print(" " + "-" * 60)
+
+ try:
+ from ..reasoning.ic_deliberation import get_ic_deliberator, ICDeliberationResult
+
+ deliberator = get_ic_deliberator()
+
+ # Create test signal data
+ signal = {
+ "ticker": "NVDA",
+ "direction": "long",
+ "signal_type": "momentum",
+ "p_value": 0.008,
+ "confidence": 0.58,
+ "expected_return_bps": 85,
+ "average_daily_volume": 45000000,
+ }
+
+ signal_evaluation = {
+ "statistical_quality": "strong",
+ "overall_score": 72,
+ "p_value_valid": True,
+ "ic_valid": True,
+ }
+
+ risk_assessment = {
+ "risk_level": "medium",
+ "var_utilization_pct": 45,
+ "sector_concentrations": {"Technology": 18},
+ "risk_flags": ["High beta stock"],
+ }
+
+ sizing_recommendation = {
+ "final_size_pct": 1.5,
+ "final_notional": 15000000,
+ "kelly_fraction": 0.02,
+ }
+
+ market_context = {
+ "regime": "bullish",
+ "vix": 16.5,
+ "spy_trend": "up",
+ }
+
+ print(f"\n SIGNAL: {signal['ticker']} {signal['direction'].upper()} ({signal['signal_type']})")
+ print(f" P-value: {signal['p_value']}, Confidence: {signal['confidence']:.0%}")
+ print(f" Expected Return: {signal['expected_return_bps']} bps")
+ print(" " + "-" * 60)
+
+ # Run IC deliberation
+ result: ICDeliberationResult = await deliberator.deliberate(
+ signal=signal,
+ signal_evaluation=signal_evaluation,
+ risk_assessment=risk_assessment,
+ sizing_recommendation=sizing_recommendation,
+ market_context=market_context,
+ historical_decisions=[],
+ )
+
+ # Display deliberation results
+ print("\n IC DELIBERATION RESULTS:")
+ print(" " + "-" * 60)
+
+ # Pros and Cons
+ print("\n PROS:")
+ for pro in result.pros[:3]:
+ print(f" + {pro}")
+
+ print("\n CONS:")
+ for con in result.cons[:3]:
+ print(f" - {con}")
+
+ # Member Opinions (the key part showing agent collaboration)
+ print("\n IC MEMBER VOTES:")
+ print(" " + "-" * 60)
+ for opinion in result.member_opinions:
+ vote_symbol = {
+ "approve": "[APPROVE]",
+ "reject": "[REJECT]",
+ "conditional": "[COND]",
+ "abstain": "[ABSTAIN]",
+ }.get(opinion.vote.value, "[?]")
+ print(f" {vote_symbol} {opinion.member_role}")
+ print(f" Rationale: {opinion.rationale[:60]}...")
+ print(f" Confidence: {opinion.confidence:.0%}")
+
+ # Vote tally
+ print("\n VOTE TALLY:")
+ for vote_type, count in result.vote_summary.items():
+ if count > 0:
+ print(f" {vote_type.upper()}: {count}")
+
+ # Final Decision
+ print("\n " + "=" * 60)
+ print(f" FINAL DECISION: {result.decision}")
+ print(f" RATIONALE: {result.decision_rationale}")
+ if result.conditions:
+ print(f" CONDITIONS: {', '.join(result.conditions)}")
+ if result.approved_size_pct:
+ print(f" APPROVED SIZE: {result.approved_size_pct:.2f}%")
+ print(f" CONFIDENCE: {result.confidence:.0%}")
+ print(" " + "=" * 60)
+
+ print_result("IC Deliberation", True)
+ return True
+
+ except Exception as e:
+ import traceback
+ print(f" Error: {e}")
+ traceback.print_exc()
+ print_result("IC Deliberation", False, str(e))
+ return False
+
+
+async def test_team_collaboration() -> bool:
+ """Test real team collaboration using Agno Team"""
+ print("\n Running Team Collaboration test...")
+ print(" " + "-" * 60)
+
+ try:
+ from agno.agent import Agent
+ from agno.team import Team
+
+ model = get_model()
+
+ # Create specialized agents
+ research_lead = Agent(
+ model=model,
+ name="Research Lead",
+ role="Signal Validation",
+ instructions=[
+ "You validate trading signals using statistical methods.",
+ "Focus on p-values, information coefficients, and backtest results.",
+ "Be concise but precise with numbers.",
+ ],
+ )
+
+ risk_officer = Agent(
+ model=model,
+ name="Chief Risk Officer",
+ role="Risk Assessment",
+ instructions=[
+ "You assess portfolio risk and position sizing.",
+ "Focus on VaR, drawdown limits, and concentration risk.",
+ "Flag any risk limit breaches immediately.",
+ ],
+ )
+
+ portfolio_manager = Agent(
+ model=model,
+ name="Portfolio Manager",
+ role="Final Decision",
+ instructions=[
+ "You make final trading decisions based on research and risk input.",
+ "Synthesize team inputs into a clear APPROVE/REJECT decision.",
+ "Always provide reasoning for your decision.",
+ ],
+ )
+
+ # Create the Investment Committee team
+ # Note: Agno Team doesn't have 'leader' param - all members are equal
+ # The first member often acts as coordinator based on instructions
+ ic_team = Team(
+ name="Investment Committee",
+ description="RenTech IC that makes systematic trading decisions",
+ members=[portfolio_manager, research_lead, risk_officer], # PM first to coordinate
+ model=model,
+ share_member_interactions=True, # Key: agents see each other's responses
+ add_team_history_to_members=True, # Key: maintains conversation context
+ instructions=[
+ "Work together to evaluate trading signals.",
+ "Research Lead validates the signal first.",
+ "Risk Officer assesses the risk second.",
+ "Portfolio Manager makes final decision last.",
+ ],
+ markdown=True,
+ show_members_responses=True,
+ )
+
+ # Submit a task to the team
+ task = """
+Evaluate this trading signal for GOOGL:
+
+SIGNAL DETAILS:
+- Ticker: GOOGL
+- Direction: LONG
+- Signal Type: Mean Reversion
+- P-value: 0.007
+- Confidence: 61%
+- Expected Return: 45 bps
+- Proposed Size: 1.2% of NAV
+
+CURRENT PORTFOLIO STATE:
+- Technology Sector Exposure: 22%
+- VaR Utilization: 55%
+- Current Drawdown: 3.2%
+
+Each team member should provide their assessment, then PM makes final call.
+"""
+
+ print("\n Submitting task to Investment Committee Team...")
+ print(" Task: Evaluate GOOGL mean reversion signal")
+ print(" " + "-" * 60)
+
+ # Run the team
+ response = ic_team.run(task)
+ content = response.content if hasattr(response, 'content') else str(response)
+
+ # Display the collaborative response
+ print("\n TEAM RESPONSE:")
+ print(" " + "-" * 60)
+
+ # Format output nicely - handle Unicode for Windows
+ lines = content.split('\n')
+ for line in lines[:40]: # Limit output
+ # Replace problematic Unicode characters for Windows console
+ safe_line = line.encode('ascii', 'replace').decode('ascii')
+ print(f" {safe_line}")
+
+ if len(lines) > 40:
+ print(f" ... ({len(lines) - 40} more lines)")
+
+ print(" " + "-" * 60)
+ print_result("Team Collaboration", True)
+ return True
+
+ except Exception as e:
+ import traceback
+ print(f" Error: {e}")
+ traceback.print_exc()
+ print_result("Team Collaboration", False, str(e))
+ return False
+
+
+# =============================================================================
+# MAIN TEST RUNNER
+# =============================================================================
+
+async def run_all_tests():
+ """Run complete test suite"""
+ print("\n" + "=" * 70)
+ print(" RENAISSANCE TECHNOLOGIES MULTI-AGENT SYSTEM")
+ print(" FULL INTEGRATION TEST SUITE")
+ print(f" Started: {datetime.now().isoformat()}")
+ print("=" * 70)
+
+ all_results = {}
+
+ # 1. Configuration
+ all_results["config"] = test_configuration()
+ all_results["model_factory"] = test_model_factory()
+
+ # 2. Agents
+ agent_results = await test_agents()
+ all_results.update({f"agent_{k}": v for k, v in agent_results.items()})
+ all_results["agent_interaction"] = await test_agent_interaction()
+
+ # 3. Teams
+ team_results = test_teams()
+ all_results.update({f"team_{k}": v for k, v in team_results.items()})
+
+ # 4. Workflows
+ workflow_results = test_workflows()
+ all_results.update({f"workflow_{k}": v for k, v in workflow_results.items()})
+ all_results["workflow_base"] = test_workflow_base()
+
+ # 5. Knowledge
+ knowledge_results = test_knowledge()
+ all_results.update({f"knowledge_{k}": v for k, v in knowledge_results.items()})
+
+ # 6. Memory
+ memory_results = test_memory()
+ all_results.update({f"memory_{k}": v for k, v in memory_results.items()})
+
+ # 7. Reasoning
+ reasoning_results = test_reasoning()
+ all_results.update({f"reasoning_{k}": v for k, v in reasoning_results.items()})
+
+ # 8. Guardrails
+ guardrail_results = test_guardrails()
+ all_results.update({f"guardrail_{k}": v for k, v in guardrail_results.items()})
+
+ # 9. Evaluation
+ eval_results = test_evaluation()
+ all_results.update({f"eval_{k}": v for k, v in eval_results.items()})
+
+ # 10. Tracing
+ tracing_results = test_tracing()
+ all_results.update({f"tracing_{k}": v for k, v in tracing_results.items()})
+
+ # 11. Full System
+ all_results["full_system"] = await test_full_system()
+ all_results["e2e_signal_analysis"] = await test_end_to_end_signal_analysis()
+
+ # 12. Advanced: IC Deliberation & Team Collaboration
+ all_results["ic_deliberation"] = await test_ic_deliberation()
+ all_results["team_collaboration"] = await test_team_collaboration()
+
+ # ==========================================================================
+ # SUMMARY
+ # ==========================================================================
+ print_section("TEST SUMMARY")
+
+ passed = sum(1 for v in all_results.values() if v)
+ total = len(all_results)
+
+ # Group results by category
+ categories = {
+ "Configuration": ["config", "model_factory"],
+ "Agents": [k for k in all_results if k.startswith("agent_")],
+ "Teams": [k for k in all_results if k.startswith("team_")],
+ "Workflows": [k for k in all_results if k.startswith("workflow_")],
+ "Knowledge": [k for k in all_results if k.startswith("knowledge_")],
+ "Memory": [k for k in all_results if k.startswith("memory_")],
+ "Reasoning": [k for k in all_results if k.startswith("reasoning_")],
+ "Guardrails": [k for k in all_results if k.startswith("guardrail_")],
+ "Evaluation": [k for k in all_results if k.startswith("eval_")],
+ "Tracing": [k for k in all_results if k.startswith("tracing_")],
+ "Integration": ["full_system", "e2e_signal_analysis"],
+ "Collaboration": ["ic_deliberation", "team_collaboration"],
+ }
+
+ for cat_name, keys in categories.items():
+ cat_passed = sum(1 for k in keys if all_results.get(k, False))
+ cat_total = len(keys)
+ status = "[OK]" if cat_passed == cat_total else "[!!]"
+ print(f" {status} {cat_name}: {cat_passed}/{cat_total}")
+
+ print("\n" + "-" * 70)
+ print(f" TOTAL: {passed}/{total} tests passed ({100*passed//total}%)")
+ print("-" * 70)
+
+ if passed == total:
+ print("\n ALL TESTS PASSED - System is fully operational!")
+ else:
+ failed = [k for k, v in all_results.items() if not v]
+ print(f"\n {len(failed)} tests failed:")
+ for f in failed[:10]:
+ print(f" - {f}")
+ if len(failed) > 10:
+ print(f" ... and {len(failed) - 10} more")
+
+ print("\n" + "=" * 70)
+ print(f" Completed: {datetime.now().isoformat()}")
+ print("=" * 70 + "\n")
+
+ return all_results
+
+
+def main():
+ """CLI entry point"""
+ asyncio.run(run_all_tests())
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/__init__.py
new file mode 100644
index 000000000..12f08e306
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/__init__.py
@@ -0,0 +1,37 @@
+"""
+Renaissance Technologies Tracing System
+
+Observability and tracing for the multi-agent system:
+- Request tracing
+- Agent interaction tracking
+- Workflow execution monitoring
+- Performance metrics collection
+"""
+
+from .base import (
+ Tracer,
+ Span,
+ SpanContext,
+ TraceLevel,
+ get_tracer,
+)
+from .agent_tracer import AgentTracer, get_agent_tracer
+from .workflow_tracer import WorkflowTracer, get_workflow_tracer
+from .metrics_collector import MetricsCollector, get_metrics_collector
+
+__all__ = [
+ # Base tracing
+ "Tracer",
+ "Span",
+ "SpanContext",
+ "TraceLevel",
+ "get_tracer",
+ # Specialized tracers
+ "AgentTracer",
+ "get_agent_tracer",
+ "WorkflowTracer",
+ "get_workflow_tracer",
+ # Metrics
+ "MetricsCollector",
+ "get_metrics_collector",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/agent_tracer.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/agent_tracer.py
new file mode 100644
index 000000000..cbb3a2a14
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/agent_tracer.py
@@ -0,0 +1,213 @@
+"""
+Agent Tracer
+
+Specialized tracing for agent interactions:
+- Agent request/response tracking
+- Decision tracing
+- Tool usage monitoring
+- Inter-agent communication
+"""
+
+from typing import Optional, List, Dict, Any
+from datetime import datetime
+from contextlib import contextmanager
+import uuid
+
+from .base import Tracer, Span, SpanStatus, get_tracer
+
+
+class AgentTracer:
+ """
+ Specialized tracer for agent activities.
+
+ Tracks:
+ 1. Agent invocations and responses
+ 2. Tool calls and results
+ 3. Decision making processes
+ 4. Inter-agent communications
+ """
+
+ def __init__(self, tracer: Optional[Tracer] = None):
+ self.tracer = tracer or get_tracer()
+
+ @contextmanager
+ def trace_agent_call(
+ self,
+ agent_id: str,
+ task: str,
+ input_data: Optional[Dict[str, Any]] = None,
+ ):
+ """
+ Trace an agent invocation.
+
+ Usage:
+ with agent_tracer.trace_agent_call("signal_scientist", "analyze signal") as span:
+ result = agent.run(task)
+ span.set_attribute("result_summary", str(result)[:100])
+ """
+ with self.tracer.span(
+ name=f"agent:{agent_id}",
+ kind="server",
+ attributes={
+ "agent.id": agent_id,
+ "agent.task": task,
+ "agent.input_size": len(str(input_data)) if input_data else 0,
+ }
+ ) as span:
+ span.agent_id = agent_id
+ span.add_event("agent_start", {"task": task})
+
+ yield span
+
+ span.add_event("agent_complete", {})
+
+ @contextmanager
+ def trace_tool_call(
+ self,
+ agent_id: str,
+ tool_name: str,
+ tool_input: Optional[Dict[str, Any]] = None,
+ ):
+ """
+ Trace a tool invocation by an agent.
+ """
+ with self.tracer.span(
+ name=f"tool:{tool_name}",
+ kind="client",
+ attributes={
+ "tool.name": tool_name,
+ "tool.agent": agent_id,
+ "tool.input_size": len(str(tool_input)) if tool_input else 0,
+ }
+ ) as span:
+ span.add_event("tool_invoked", {"tool": tool_name})
+
+ yield span
+
+ span.add_event("tool_complete", {})
+
+ @contextmanager
+ def trace_decision(
+ self,
+ agent_id: str,
+ decision_type: str,
+ context: Optional[Dict[str, Any]] = None,
+ ):
+ """
+ Trace a decision-making process.
+ """
+ with self.tracer.span(
+ name=f"decision:{decision_type}",
+ kind="internal",
+ attributes={
+ "decision.type": decision_type,
+ "decision.agent": agent_id,
+ }
+ ) as span:
+ if context:
+ for key, value in context.items():
+ if isinstance(value, (str, int, float, bool)):
+ span.set_attribute(f"decision.context.{key}", value)
+
+ span.add_event("decision_start", {"type": decision_type})
+
+ yield span
+
+ span.add_event("decision_complete", {})
+
+ @contextmanager
+ def trace_agent_communication(
+ self,
+ from_agent: str,
+ to_agent: str,
+ message_type: str,
+ ):
+ """
+ Trace communication between agents.
+ """
+ with self.tracer.span(
+ name=f"comm:{from_agent}->{to_agent}",
+ kind="producer",
+ attributes={
+ "comm.from": from_agent,
+ "comm.to": to_agent,
+ "comm.type": message_type,
+ }
+ ) as span:
+ span.add_event("message_sent", {
+ "from": from_agent,
+ "to": to_agent,
+ "type": message_type,
+ })
+
+ yield span
+
+ span.add_event("message_received", {})
+
+ def record_agent_error(
+ self,
+ agent_id: str,
+ error: Exception,
+ context: Optional[Dict[str, Any]] = None,
+ ):
+ """Record an error from an agent"""
+ span = self.tracer.current_span
+ if span:
+ span.add_event("agent_error", {
+ "agent": agent_id,
+ "error_type": type(error).__name__,
+ "error_message": str(error),
+ **(context or {}),
+ })
+ span.set_status(SpanStatus.ERROR, str(error))
+
+ def record_agent_metric(
+ self,
+ agent_id: str,
+ metric_name: str,
+ value: float,
+ unit: str = "",
+ ):
+ """Record a metric from an agent"""
+ span = self.tracer.current_span
+ if span:
+ span.set_attribute(f"metric.{metric_name}", value)
+ span.add_event("metric_recorded", {
+ "agent": agent_id,
+ "metric": metric_name,
+ "value": value,
+ "unit": unit,
+ })
+
+ def get_agent_traces(
+ self,
+ agent_id: str,
+ limit: int = 100,
+ ) -> List[Dict[str, Any]]:
+ """Get recent traces for an agent"""
+ all_traces = self.tracer.get_recent_traces(limit=limit * 2)
+
+ # Filter to traces involving this agent
+ agent_traces = []
+ for trace_summary in all_traces:
+ trace_id = trace_summary.get("trace_id")
+ if trace_id:
+ spans = self.tracer.get_trace(trace_id)
+ for span in spans:
+ if span.get("agent_id") == agent_id:
+ agent_traces.append(trace_summary)
+ break
+
+ return agent_traces[:limit]
+
+
+# Global agent tracer instance
+_agent_tracer: Optional[AgentTracer] = None
+
+
+def get_agent_tracer() -> AgentTracer:
+ """Get the global agent tracer"""
+ global _agent_tracer
+ if _agent_tracer is None:
+ _agent_tracer = AgentTracer()
+ return _agent_tracer
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/base.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/base.py
new file mode 100644
index 000000000..1997d410c
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/base.py
@@ -0,0 +1,370 @@
+"""
+Base Tracing Infrastructure
+
+Core tracing system for Renaissance Technologies multi-agent architecture.
+Implements distributed tracing, span management, and observability.
+"""
+
+from typing import Optional, List, Dict, Any, Callable
+from dataclasses import dataclass, field
+from datetime import datetime
+from enum import Enum
+from contextlib import contextmanager
+import uuid
+import json
+import threading
+
+from ..config import get_config, TracingConfig
+
+
+class TraceLevel(str, Enum):
+ """Trace detail levels"""
+ DEBUG = "debug"
+ INFO = "info"
+ WARNING = "warning"
+ ERROR = "error"
+ CRITICAL = "critical"
+
+
+class SpanStatus(str, Enum):
+ """Span completion status"""
+ OK = "ok"
+ ERROR = "error"
+ CANCELLED = "cancelled"
+
+
+@dataclass
+class SpanContext:
+ """Context propagated across span boundaries"""
+ trace_id: str
+ span_id: str
+ parent_span_id: Optional[str] = None
+ baggage: Dict[str, str] = field(default_factory=dict)
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "trace_id": self.trace_id,
+ "span_id": self.span_id,
+ "parent_span_id": self.parent_span_id,
+ "baggage": self.baggage,
+ }
+
+
+@dataclass
+class SpanEvent:
+ """Event within a span"""
+ name: str
+ timestamp: str
+ attributes: Dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class Span:
+ """
+ A span represents a single operation within a trace.
+
+ Spans form a tree structure representing the call hierarchy
+ of operations in the system.
+ """
+ name: str
+ context: SpanContext
+ start_time: datetime
+ end_time: Optional[datetime] = None
+
+ # Span metadata
+ kind: str = "internal" # internal, server, client, producer, consumer
+ status: SpanStatus = SpanStatus.OK
+ status_message: str = ""
+
+ # Attributes and events
+ attributes: Dict[str, Any] = field(default_factory=dict)
+ events: List[SpanEvent] = field(default_factory=list)
+
+ # Resource info
+ service_name: str = "rentech_agents"
+ agent_id: Optional[str] = None
+
+ @property
+ def duration_ms(self) -> Optional[float]:
+ """Get span duration in milliseconds"""
+ if self.end_time:
+ return (self.end_time - self.start_time).total_seconds() * 1000
+ return None
+
+ def set_attribute(self, key: str, value: Any):
+ """Set a span attribute"""
+ self.attributes[key] = value
+
+ def add_event(self, name: str, attributes: Optional[Dict[str, Any]] = None):
+ """Add an event to the span"""
+ self.events.append(SpanEvent(
+ name=name,
+ timestamp=datetime.utcnow().isoformat(),
+ attributes=attributes or {},
+ ))
+
+ def set_status(self, status: SpanStatus, message: str = ""):
+ """Set span status"""
+ self.status = status
+ self.status_message = message
+
+ def end(self, status: Optional[SpanStatus] = None):
+ """End the span"""
+ self.end_time = datetime.utcnow()
+ if status:
+ self.status = status
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert span to dictionary for export"""
+ return {
+ "name": self.name,
+ "trace_id": self.context.trace_id,
+ "span_id": self.context.span_id,
+ "parent_span_id": self.context.parent_span_id,
+ "start_time": self.start_time.isoformat(),
+ "end_time": self.end_time.isoformat() if self.end_time else None,
+ "duration_ms": self.duration_ms,
+ "kind": self.kind,
+ "status": self.status.value,
+ "status_message": self.status_message,
+ "attributes": self.attributes,
+ "events": [{"name": e.name, "timestamp": e.timestamp, "attributes": e.attributes} for e in self.events],
+ "service_name": self.service_name,
+ "agent_id": self.agent_id,
+ }
+
+
+class Tracer:
+ """
+ Core tracing system for observability.
+
+ Provides:
+ 1. Distributed tracing across agents and workflows
+ 2. Span management and propagation
+ 3. Attribute and event recording
+ 4. Export to various backends
+ """
+
+ def __init__(self, config: Optional[TracingConfig] = None):
+ self.config = config or get_config().tracing
+
+ # Storage
+ self._traces: Dict[str, List[Span]] = {}
+ self._active_spans: Dict[str, Span] = {} # Thread-local active spans
+
+ # Threading
+ self._lock = threading.Lock()
+ self._local = threading.local()
+
+ # Export callbacks
+ self._exporters: List[Callable[[Span], None]] = []
+
+ if self.config.export_to_console:
+ self._exporters.append(self._console_exporter)
+
+ @property
+ def current_span(self) -> Optional[Span]:
+ """Get the current active span for this thread"""
+ return getattr(self._local, 'current_span', None)
+
+ def start_trace(
+ self,
+ name: str,
+ attributes: Optional[Dict[str, Any]] = None,
+ ) -> Span:
+ """
+ Start a new trace (root span).
+ """
+ trace_id = uuid.uuid4().hex
+ span_id = uuid.uuid4().hex[:16]
+
+ context = SpanContext(
+ trace_id=trace_id,
+ span_id=span_id,
+ )
+
+ span = Span(
+ name=name,
+ context=context,
+ start_time=datetime.utcnow(),
+ service_name=self.config.service_name,
+ attributes=attributes or {},
+ )
+
+ with self._lock:
+ self._traces[trace_id] = [span]
+
+ self._local.current_span = span
+ return span
+
+ def start_span(
+ self,
+ name: str,
+ parent: Optional[Span] = None,
+ kind: str = "internal",
+ attributes: Optional[Dict[str, Any]] = None,
+ ) -> Span:
+ """
+ Start a new span within an existing trace.
+ """
+ parent_span = parent or self.current_span
+
+ if parent_span is None:
+ # No parent, start a new trace
+ return self.start_trace(name, attributes)
+
+ span_id = uuid.uuid4().hex[:16]
+
+ context = SpanContext(
+ trace_id=parent_span.context.trace_id,
+ span_id=span_id,
+ parent_span_id=parent_span.context.span_id,
+ baggage=parent_span.context.baggage.copy(),
+ )
+
+ span = Span(
+ name=name,
+ context=context,
+ start_time=datetime.utcnow(),
+ kind=kind,
+ service_name=self.config.service_name,
+ attributes=attributes or {},
+ )
+
+ with self._lock:
+ if context.trace_id in self._traces:
+ self._traces[context.trace_id].append(span)
+
+ self._local.current_span = span
+ return span
+
+ def end_span(self, span: Span, status: Optional[SpanStatus] = None):
+ """End a span and export it"""
+ span.end(status)
+
+ # Export to all exporters
+ for exporter in self._exporters:
+ try:
+ exporter(span)
+ except Exception as e:
+ print(f"Export error: {e}")
+
+ # Restore parent span as current
+ if span.context.parent_span_id:
+ parent = self._find_span(
+ span.context.trace_id,
+ span.context.parent_span_id
+ )
+ self._local.current_span = parent
+ else:
+ self._local.current_span = None
+
+ def _find_span(self, trace_id: str, span_id: str) -> Optional[Span]:
+ """Find a span by ID"""
+ with self._lock:
+ spans = self._traces.get(trace_id, [])
+ for span in spans:
+ if span.context.span_id == span_id:
+ return span
+ return None
+
+ @contextmanager
+ def span(
+ self,
+ name: str,
+ kind: str = "internal",
+ attributes: Optional[Dict[str, Any]] = None,
+ ):
+ """
+ Context manager for creating spans.
+
+ Usage:
+ with tracer.span("my_operation") as span:
+ span.set_attribute("key", "value")
+ # do work
+ """
+ span = self.start_span(name, kind=kind, attributes=attributes)
+ try:
+ yield span
+ self.end_span(span, SpanStatus.OK)
+ except Exception as e:
+ span.set_status(SpanStatus.ERROR, str(e))
+ span.add_event("exception", {"message": str(e)})
+ self.end_span(span, SpanStatus.ERROR)
+ raise
+
+ def record_exception(self, exception: Exception, span: Optional[Span] = None):
+ """Record an exception in the current or specified span"""
+ target_span = span or self.current_span
+ if target_span:
+ target_span.add_event("exception", {
+ "type": type(exception).__name__,
+ "message": str(exception),
+ })
+ target_span.set_status(SpanStatus.ERROR, str(exception))
+
+ def add_exporter(self, exporter: Callable[[Span], None]):
+ """Add a span exporter"""
+ self._exporters.append(exporter)
+
+ def _console_exporter(self, span: Span):
+ """Export span to console"""
+ indent = " " if span.context.parent_span_id else ""
+ status_icon = "OK" if span.status == SpanStatus.OK else "ERR"
+ duration = f"{span.duration_ms:.2f}ms" if span.duration_ms else "ongoing"
+
+ print(f"{indent}[{status_icon}] {span.name} ({duration})")
+ if span.status == SpanStatus.ERROR:
+ print(f"{indent} Error: {span.status_message}")
+
+ def get_trace(self, trace_id: str) -> List[Dict[str, Any]]:
+ """Get all spans for a trace"""
+ with self._lock:
+ spans = self._traces.get(trace_id, [])
+ return [s.to_dict() for s in spans]
+
+ def get_trace_summary(self, trace_id: str) -> Dict[str, Any]:
+ """Get summary of a trace"""
+ with self._lock:
+ spans = self._traces.get(trace_id, [])
+
+ if not spans:
+ return {"error": "Trace not found"}
+
+ root_span = spans[0]
+ total_duration = root_span.duration_ms
+
+ error_spans = [s for s in spans if s.status == SpanStatus.ERROR]
+
+ return {
+ "trace_id": trace_id,
+ "root_name": root_span.name,
+ "total_spans": len(spans),
+ "total_duration_ms": total_duration,
+ "error_count": len(error_spans),
+ "status": "error" if error_spans else "ok",
+ }
+
+ def get_recent_traces(self, limit: int = 100) -> List[Dict[str, Any]]:
+ """Get recent traces"""
+ with self._lock:
+ traces = list(self._traces.keys())[-limit:]
+ return [self.get_trace_summary(t) for t in traces]
+
+
+# Global tracer instance
+_tracer: Optional[Tracer] = None
+
+
+def get_tracer() -> Tracer:
+ """Get the global tracer instance"""
+ global _tracer
+ if _tracer is None:
+ _tracer = Tracer()
+ return _tracer
+
+
+def reset_tracer():
+ """Reset the tracer (for testing)"""
+ global _tracer
+ _tracer = None
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/metrics_collector.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/metrics_collector.py
new file mode 100644
index 000000000..69a05bda3
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/metrics_collector.py
@@ -0,0 +1,634 @@
+"""
+Metrics Collector
+
+Collects and aggregates performance metrics:
+- Counter metrics (counts, totals)
+- Gauge metrics (current values)
+- Histogram metrics (distributions)
+- Trading-specific metrics
+"""
+
+from typing import Optional, List, Dict, Any, Callable
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta
+from enum import Enum
+from collections import defaultdict
+import threading
+import statistics
+import math
+
+from ..config import get_config
+
+
+class MetricType(str, Enum):
+ """Types of metrics"""
+ COUNTER = "counter" # Monotonically increasing (requests, trades)
+ GAUGE = "gauge" # Current value (price, position size)
+ HISTOGRAM = "histogram" # Distribution (latency, returns)
+ SUMMARY = "summary" # Pre-calculated percentiles
+
+
+@dataclass
+class MetricValue:
+ """A single metric value with timestamp"""
+ value: float
+ timestamp: datetime
+ labels: Dict[str, str] = field(default_factory=dict)
+
+
+@dataclass
+class MetricDefinition:
+ """Definition of a metric"""
+ name: str
+ metric_type: MetricType
+ description: str
+ unit: str = ""
+ labels: List[str] = field(default_factory=list)
+
+
+@dataclass
+class HistogramBuckets:
+ """Histogram bucket configuration"""
+ boundaries: List[float]
+ counts: List[int] = field(default_factory=list)
+ sum_value: float = 0.0
+ count: int = 0
+
+ def __post_init__(self):
+ if not self.counts:
+ # +1 for the +Inf bucket
+ self.counts = [0] * (len(self.boundaries) + 1)
+
+ def observe(self, value: float):
+ """Record a value in the histogram"""
+ self.sum_value += value
+ self.count += 1
+
+ # Find the bucket
+ for i, boundary in enumerate(self.boundaries):
+ if value <= boundary:
+ self.counts[i] += 1
+ return
+ # +Inf bucket
+ self.counts[-1] += 1
+
+ def get_percentile(self, percentile: float) -> float:
+ """Estimate percentile from histogram"""
+ if self.count == 0:
+ return 0.0
+
+ target_count = self.count * percentile / 100
+
+ cumulative = 0
+ for i, count in enumerate(self.counts):
+ cumulative += count
+ if cumulative >= target_count:
+ if i == 0:
+ return self.boundaries[0] / 2
+ elif i < len(self.boundaries):
+ # Linear interpolation
+ prev_boundary = self.boundaries[i - 1] if i > 0 else 0
+ return prev_boundary + (self.boundaries[i] - prev_boundary) * 0.5
+ else:
+ # +Inf bucket - use last boundary * 2
+ return self.boundaries[-1] * 2 if self.boundaries else 0
+
+ return self.boundaries[-1] if self.boundaries else 0
+
+
+class MetricsCollector:
+ """
+ Collects and aggregates metrics for the trading system.
+
+ Provides:
+ 1. Counter metrics for counts/totals
+ 2. Gauge metrics for current values
+ 3. Histogram metrics for distributions
+ 4. Trading-specific metric aggregations
+ """
+
+ # Default histogram buckets for common use cases
+ LATENCY_BUCKETS = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000] # ms
+ RETURN_BUCKETS = [-500, -200, -100, -50, -20, -10, 0, 10, 20, 50, 100, 200, 500] # bps
+ SIZE_BUCKETS = [1000, 10000, 100000, 1000000, 10000000, 100000000] # dollars
+
+ def __init__(self):
+ self.config = get_config()
+
+ # Metric storage
+ self._counters: Dict[str, float] = defaultdict(float)
+ self._gauges: Dict[str, MetricValue] = {}
+ self._histograms: Dict[str, HistogramBuckets] = {}
+ self._time_series: Dict[str, List[MetricValue]] = defaultdict(list)
+
+ # Metric definitions
+ self._definitions: Dict[str, MetricDefinition] = {}
+
+ # Threading
+ self._lock = threading.Lock()
+
+ # Register standard metrics
+ self._register_standard_metrics()
+
+ def _register_standard_metrics(self):
+ """Register standard trading system metrics"""
+ # Signal metrics
+ self.register_metric(MetricDefinition(
+ name="signals_generated",
+ metric_type=MetricType.COUNTER,
+ description="Total number of signals generated",
+ labels=["signal_type", "agent_id"],
+ ))
+
+ self.register_metric(MetricDefinition(
+ name="signals_approved",
+ metric_type=MetricType.COUNTER,
+ description="Total number of signals approved by IC",
+ labels=["signal_type"],
+ ))
+
+ self.register_metric(MetricDefinition(
+ name="signals_rejected",
+ metric_type=MetricType.COUNTER,
+ description="Total number of signals rejected",
+ labels=["signal_type", "reason"],
+ ))
+
+ # Trade metrics
+ self.register_metric(MetricDefinition(
+ name="trades_executed",
+ metric_type=MetricType.COUNTER,
+ description="Total number of trades executed",
+ labels=["direction", "execution_algo"],
+ ))
+
+ self.register_metric(MetricDefinition(
+ name="trade_pnl_bps",
+ metric_type=MetricType.HISTOGRAM,
+ description="Trade P&L distribution",
+ unit="bps",
+ ))
+
+ self.register_metric(MetricDefinition(
+ name="trade_slippage_bps",
+ metric_type=MetricType.HISTOGRAM,
+ description="Trade slippage distribution",
+ unit="bps",
+ ))
+
+ # Agent metrics
+ self.register_metric(MetricDefinition(
+ name="agent_requests",
+ metric_type=MetricType.COUNTER,
+ description="Total agent requests",
+ labels=["agent_id"],
+ ))
+
+ self.register_metric(MetricDefinition(
+ name="agent_latency_ms",
+ metric_type=MetricType.HISTOGRAM,
+ description="Agent response latency",
+ unit="ms",
+ labels=["agent_id"],
+ ))
+
+ self.register_metric(MetricDefinition(
+ name="agent_errors",
+ metric_type=MetricType.COUNTER,
+ description="Agent errors",
+ labels=["agent_id", "error_type"],
+ ))
+
+ # Workflow metrics
+ self.register_metric(MetricDefinition(
+ name="workflow_executions",
+ metric_type=MetricType.COUNTER,
+ description="Total workflow executions",
+ labels=["workflow_name"],
+ ))
+
+ self.register_metric(MetricDefinition(
+ name="workflow_duration_ms",
+ metric_type=MetricType.HISTOGRAM,
+ description="Workflow execution duration",
+ unit="ms",
+ labels=["workflow_name"],
+ ))
+
+ # Risk metrics
+ self.register_metric(MetricDefinition(
+ name="portfolio_var",
+ metric_type=MetricType.GAUGE,
+ description="Current portfolio VaR",
+ unit="%",
+ ))
+
+ self.register_metric(MetricDefinition(
+ name="portfolio_drawdown",
+ metric_type=MetricType.GAUGE,
+ description="Current portfolio drawdown",
+ unit="%",
+ ))
+
+ self.register_metric(MetricDefinition(
+ name="guardrail_violations",
+ metric_type=MetricType.COUNTER,
+ description="Guardrail violations",
+ labels=["guardrail_name", "severity"],
+ ))
+
+ # System metrics
+ self.register_metric(MetricDefinition(
+ name="system_uptime_seconds",
+ metric_type=MetricType.COUNTER,
+ description="System uptime in seconds",
+ ))
+
+ self.register_metric(MetricDefinition(
+ name="memory_usage_bytes",
+ metric_type=MetricType.GAUGE,
+ description="Memory usage",
+ unit="bytes",
+ ))
+
+ self.register_metric(MetricDefinition(
+ name="active_positions",
+ metric_type=MetricType.GAUGE,
+ description="Number of active positions",
+ ))
+
+ def register_metric(self, definition: MetricDefinition):
+ """Register a metric definition"""
+ with self._lock:
+ self._definitions[definition.name] = definition
+
+ # Initialize histogram buckets if needed
+ if definition.metric_type == MetricType.HISTOGRAM:
+ buckets = self._get_default_buckets(definition.name)
+ self._histograms[definition.name] = HistogramBuckets(boundaries=buckets)
+
+ def _get_default_buckets(self, metric_name: str) -> List[float]:
+ """Get default buckets for a histogram metric"""
+ if "latency" in metric_name or "duration" in metric_name:
+ return self.LATENCY_BUCKETS
+ elif "pnl" in metric_name or "return" in metric_name or "slippage" in metric_name:
+ return self.RETURN_BUCKETS
+ elif "size" in metric_name or "value" in metric_name:
+ return self.SIZE_BUCKETS
+ else:
+ # Default buckets
+ return [1, 5, 10, 25, 50, 75, 100, 250, 500, 1000]
+
+ def _make_key(self, name: str, labels: Optional[Dict[str, str]] = None) -> str:
+ """Create a unique key for a metric with labels"""
+ if not labels:
+ return name
+ label_str = ",".join(f"{k}={v}" for k, v in sorted(labels.items()))
+ return f"{name}{{{label_str}}}"
+
+ # Counter methods
+ def increment(
+ self,
+ name: str,
+ value: float = 1.0,
+ labels: Optional[Dict[str, str]] = None,
+ ):
+ """Increment a counter"""
+ key = self._make_key(name, labels)
+ with self._lock:
+ self._counters[key] += value
+
+ def get_counter(
+ self,
+ name: str,
+ labels: Optional[Dict[str, str]] = None,
+ ) -> float:
+ """Get counter value"""
+ key = self._make_key(name, labels)
+ with self._lock:
+ return self._counters.get(key, 0.0)
+
+ # Gauge methods
+ def set_gauge(
+ self,
+ name: str,
+ value: float,
+ labels: Optional[Dict[str, str]] = None,
+ ):
+ """Set a gauge value"""
+ key = self._make_key(name, labels)
+ with self._lock:
+ self._gauges[key] = MetricValue(
+ value=value,
+ timestamp=datetime.utcnow(),
+ labels=labels or {},
+ )
+
+ # Also add to time series for historical tracking
+ self._time_series[key].append(MetricValue(
+ value=value,
+ timestamp=datetime.utcnow(),
+ labels=labels or {},
+ ))
+
+ # Keep only last 1000 values
+ if len(self._time_series[key]) > 1000:
+ self._time_series[key] = self._time_series[key][-1000:]
+
+ def get_gauge(
+ self,
+ name: str,
+ labels: Optional[Dict[str, str]] = None,
+ ) -> Optional[float]:
+ """Get current gauge value"""
+ key = self._make_key(name, labels)
+ with self._lock:
+ metric = self._gauges.get(key)
+ return metric.value if metric else None
+
+ # Histogram methods
+ def observe(
+ self,
+ name: str,
+ value: float,
+ labels: Optional[Dict[str, str]] = None,
+ ):
+ """Record a histogram observation"""
+ key = self._make_key(name, labels)
+ with self._lock:
+ if key not in self._histograms:
+ buckets = self._get_default_buckets(name)
+ self._histograms[key] = HistogramBuckets(boundaries=buckets)
+ self._histograms[key].observe(value)
+
+ # Also track in time series
+ self._time_series[key].append(MetricValue(
+ value=value,
+ timestamp=datetime.utcnow(),
+ labels=labels or {},
+ ))
+
+ if len(self._time_series[key]) > 10000:
+ self._time_series[key] = self._time_series[key][-10000:]
+
+ def get_histogram_stats(
+ self,
+ name: str,
+ labels: Optional[Dict[str, str]] = None,
+ ) -> Dict[str, float]:
+ """Get histogram statistics"""
+ key = self._make_key(name, labels)
+ with self._lock:
+ hist = self._histograms.get(key)
+ if not hist or hist.count == 0:
+ return {}
+
+ return {
+ "count": hist.count,
+ "sum": hist.sum_value,
+ "mean": hist.sum_value / hist.count,
+ "p50": hist.get_percentile(50),
+ "p90": hist.get_percentile(90),
+ "p95": hist.get_percentile(95),
+ "p99": hist.get_percentile(99),
+ }
+
+ # Trading-specific methods
+ def record_signal(
+ self,
+ signal_type: str,
+ agent_id: str,
+ approved: bool,
+ rejection_reason: Optional[str] = None,
+ ):
+ """Record a signal generation/decision"""
+ self.increment("signals_generated", labels={
+ "signal_type": signal_type,
+ "agent_id": agent_id,
+ })
+
+ if approved:
+ self.increment("signals_approved", labels={"signal_type": signal_type})
+ else:
+ self.increment("signals_rejected", labels={
+ "signal_type": signal_type,
+ "reason": rejection_reason or "unknown",
+ })
+
+ def record_trade(
+ self,
+ direction: str,
+ execution_algo: str,
+ pnl_bps: float,
+ slippage_bps: float,
+ market_impact_bps: float,
+ ):
+ """Record a trade execution"""
+ self.increment("trades_executed", labels={
+ "direction": direction,
+ "execution_algo": execution_algo,
+ })
+
+ self.observe("trade_pnl_bps", pnl_bps)
+ self.observe("trade_slippage_bps", slippage_bps)
+ self.observe("trade_market_impact_bps", market_impact_bps)
+
+ def record_agent_request(
+ self,
+ agent_id: str,
+ latency_ms: float,
+ success: bool,
+ error_type: Optional[str] = None,
+ ):
+ """Record an agent request"""
+ self.increment("agent_requests", labels={"agent_id": agent_id})
+ self.observe("agent_latency_ms", latency_ms, labels={"agent_id": agent_id})
+
+ if not success and error_type:
+ self.increment("agent_errors", labels={
+ "agent_id": agent_id,
+ "error_type": error_type,
+ })
+
+ def record_workflow_execution(
+ self,
+ workflow_name: str,
+ duration_ms: float,
+ success: bool,
+ ):
+ """Record a workflow execution"""
+ self.increment("workflow_executions", labels={
+ "workflow_name": workflow_name,
+ })
+
+ self.observe("workflow_duration_ms", duration_ms, labels={
+ "workflow_name": workflow_name,
+ })
+
+ def record_guardrail_check(
+ self,
+ guardrail_name: str,
+ passed: bool,
+ severity: str = "warning",
+ ):
+ """Record a guardrail check result"""
+ if not passed:
+ self.increment("guardrail_violations", labels={
+ "guardrail_name": guardrail_name,
+ "severity": severity,
+ })
+
+ def update_portfolio_metrics(
+ self,
+ var_pct: float,
+ drawdown_pct: float,
+ active_positions: int,
+ ):
+ """Update portfolio-level metrics"""
+ self.set_gauge("portfolio_var", var_pct)
+ self.set_gauge("portfolio_drawdown", drawdown_pct)
+ self.set_gauge("active_positions", active_positions)
+
+ # Aggregation and reporting
+ def get_summary(self) -> Dict[str, Any]:
+ """Get a summary of all metrics"""
+ with self._lock:
+ summary = {
+ "timestamp": datetime.utcnow().isoformat(),
+ "counters": {},
+ "gauges": {},
+ "histograms": {},
+ }
+
+ # Counters
+ for key, value in self._counters.items():
+ summary["counters"][key] = value
+
+ # Gauges
+ for key, metric in self._gauges.items():
+ summary["gauges"][key] = {
+ "value": metric.value,
+ "timestamp": metric.timestamp.isoformat(),
+ }
+
+ # Histograms
+ for key, hist in self._histograms.items():
+ if hist.count > 0:
+ summary["histograms"][key] = {
+ "count": hist.count,
+ "sum": hist.sum_value,
+ "mean": hist.sum_value / hist.count,
+ "p50": hist.get_percentile(50),
+ "p95": hist.get_percentile(95),
+ "p99": hist.get_percentile(99),
+ }
+
+ return summary
+
+ def get_trading_dashboard(self) -> Dict[str, Any]:
+ """Get trading-specific dashboard metrics"""
+ signals_generated = self.get_counter("signals_generated")
+ signals_approved = self.get_counter("signals_approved")
+ trades_executed = self.get_counter("trades_executed")
+
+ pnl_stats = self.get_histogram_stats("trade_pnl_bps")
+ slippage_stats = self.get_histogram_stats("trade_slippage_bps")
+
+ return {
+ "timestamp": datetime.utcnow().isoformat(),
+ "signals": {
+ "total_generated": signals_generated,
+ "total_approved": signals_approved,
+ "approval_rate": signals_approved / signals_generated if signals_generated > 0 else 0,
+ },
+ "trades": {
+ "total_executed": trades_executed,
+ "pnl": {
+ "mean_bps": pnl_stats.get("mean", 0),
+ "p50_bps": pnl_stats.get("p50", 0),
+ "p95_bps": pnl_stats.get("p95", 0),
+ },
+ "slippage": {
+ "mean_bps": slippage_stats.get("mean", 0),
+ "p95_bps": slippage_stats.get("p95", 0),
+ },
+ },
+ "portfolio": {
+ "var_pct": self.get_gauge("portfolio_var"),
+ "drawdown_pct": self.get_gauge("portfolio_drawdown"),
+ "active_positions": self.get_gauge("active_positions"),
+ },
+ "guardrails": {
+ "total_violations": self.get_counter("guardrail_violations"),
+ },
+ }
+
+ def get_agent_metrics(self, agent_id: str) -> Dict[str, Any]:
+ """Get metrics for a specific agent"""
+ requests = self.get_counter("agent_requests", labels={"agent_id": agent_id})
+ errors = self.get_counter("agent_errors", labels={"agent_id": agent_id})
+ latency_stats = self.get_histogram_stats("agent_latency_ms", labels={"agent_id": agent_id})
+
+ return {
+ "agent_id": agent_id,
+ "total_requests": requests,
+ "total_errors": errors,
+ "error_rate": errors / requests if requests > 0 else 0,
+ "latency": {
+ "mean_ms": latency_stats.get("mean", 0),
+ "p50_ms": latency_stats.get("p50", 0),
+ "p95_ms": latency_stats.get("p95", 0),
+ "p99_ms": latency_stats.get("p99", 0),
+ },
+ }
+
+ def get_time_series(
+ self,
+ name: str,
+ labels: Optional[Dict[str, str]] = None,
+ since: Optional[datetime] = None,
+ ) -> List[Dict[str, Any]]:
+ """Get time series data for a metric"""
+ key = self._make_key(name, labels)
+ with self._lock:
+ series = self._time_series.get(key, [])
+
+ if since:
+ series = [m for m in series if m.timestamp >= since]
+
+ return [
+ {"value": m.value, "timestamp": m.timestamp.isoformat()}
+ for m in series
+ ]
+
+ def reset(self):
+ """Reset all metrics (for testing)"""
+ with self._lock:
+ self._counters.clear()
+ self._gauges.clear()
+ self._histograms.clear()
+ self._time_series.clear()
+
+ # Re-initialize histograms
+ for name, definition in self._definitions.items():
+ if definition.metric_type == MetricType.HISTOGRAM:
+ buckets = self._get_default_buckets(name)
+ self._histograms[name] = HistogramBuckets(boundaries=buckets)
+
+
+# Global metrics collector instance
+_metrics_collector: Optional[MetricsCollector] = None
+
+
+def get_metrics_collector() -> MetricsCollector:
+ """Get the global metrics collector"""
+ global _metrics_collector
+ if _metrics_collector is None:
+ _metrics_collector = MetricsCollector()
+ return _metrics_collector
+
+
+def reset_metrics_collector():
+ """Reset the metrics collector (for testing)"""
+ global _metrics_collector
+ _metrics_collector = None
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/workflow_tracer.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/workflow_tracer.py
new file mode 100644
index 000000000..93e213afd
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tracing/workflow_tracer.py
@@ -0,0 +1,260 @@
+"""
+Workflow Tracer
+
+Specialized tracing for workflow execution:
+- Workflow step tracking
+- Pipeline monitoring
+- Step dependencies
+- Performance analysis
+"""
+
+from typing import Optional, List, Dict, Any
+from datetime import datetime
+from contextlib import contextmanager
+import uuid
+
+from .base import Tracer, Span, SpanStatus, get_tracer
+
+
+class WorkflowTracer:
+ """
+ Specialized tracer for workflow execution.
+
+ Tracks:
+ 1. Workflow start/end
+ 2. Individual step execution
+ 3. Step dependencies and transitions
+ 4. Workflow performance metrics
+ """
+
+ def __init__(self, tracer: Optional[Tracer] = None):
+ self.tracer = tracer or get_tracer()
+
+ # Active workflows
+ self._active_workflows: Dict[str, Span] = {}
+
+ @contextmanager
+ def trace_workflow(
+ self,
+ workflow_id: str,
+ workflow_name: str,
+ workflow_type: str,
+ context: Optional[Dict[str, Any]] = None,
+ ):
+ """
+ Trace a complete workflow execution.
+
+ Usage:
+ with workflow_tracer.trace_workflow("wf_123", "daily_cycle", "trading") as span:
+ # execute workflow steps
+ span.set_attribute("total_signals", 10)
+ """
+ with self.tracer.span(
+ name=f"workflow:{workflow_name}",
+ kind="internal",
+ attributes={
+ "workflow.id": workflow_id,
+ "workflow.name": workflow_name,
+ "workflow.type": workflow_type,
+ **(context or {}),
+ }
+ ) as span:
+ self._active_workflows[workflow_id] = span
+
+ span.add_event("workflow_start", {
+ "id": workflow_id,
+ "name": workflow_name,
+ })
+
+ yield span
+
+ span.add_event("workflow_complete", {
+ "id": workflow_id,
+ })
+
+ del self._active_workflows[workflow_id]
+
+ @contextmanager
+ def trace_step(
+ self,
+ workflow_id: str,
+ step_name: str,
+ step_number: int,
+ total_steps: int,
+ input_data: Optional[Dict[str, Any]] = None,
+ ):
+ """
+ Trace a workflow step.
+ """
+ workflow_span = self._active_workflows.get(workflow_id)
+
+ with self.tracer.span(
+ name=f"step:{step_name}",
+ parent=workflow_span,
+ kind="internal",
+ attributes={
+ "step.name": step_name,
+ "step.number": step_number,
+ "step.total": total_steps,
+ "step.workflow": workflow_id,
+ }
+ ) as span:
+ span.add_event("step_start", {
+ "name": step_name,
+ "number": step_number,
+ })
+
+ yield span
+
+ span.add_event("step_complete", {
+ "name": step_name,
+ "number": step_number,
+ })
+
+ @contextmanager
+ def trace_pipeline_stage(
+ self,
+ pipeline_name: str,
+ stage_name: str,
+ stage_input: Optional[Dict[str, Any]] = None,
+ ):
+ """
+ Trace a pipeline stage.
+ """
+ with self.tracer.span(
+ name=f"pipeline:{pipeline_name}:{stage_name}",
+ kind="internal",
+ attributes={
+ "pipeline.name": pipeline_name,
+ "pipeline.stage": stage_name,
+ }
+ ) as span:
+ span.add_event("stage_start", {
+ "pipeline": pipeline_name,
+ "stage": stage_name,
+ })
+
+ yield span
+
+ span.add_event("stage_complete", {
+ "pipeline": pipeline_name,
+ "stage": stage_name,
+ })
+
+ def record_step_result(
+ self,
+ step_name: str,
+ success: bool,
+ output_summary: Optional[str] = None,
+ duration_ms: Optional[float] = None,
+ ):
+ """Record the result of a step"""
+ span = self.tracer.current_span
+ if span:
+ span.set_attribute("step.success", success)
+ if output_summary:
+ span.set_attribute("step.output_summary", output_summary[:200])
+ if duration_ms:
+ span.set_attribute("step.duration_ms", duration_ms)
+
+ span.add_event("step_result", {
+ "step": step_name,
+ "success": success,
+ })
+
+ def record_workflow_metric(
+ self,
+ workflow_id: str,
+ metric_name: str,
+ value: float,
+ ):
+ """Record a workflow metric"""
+ workflow_span = self._active_workflows.get(workflow_id)
+ if workflow_span:
+ workflow_span.set_attribute(f"metric.{metric_name}", value)
+ workflow_span.add_event("metric", {
+ "name": metric_name,
+ "value": value,
+ })
+
+ def record_workflow_error(
+ self,
+ workflow_id: str,
+ step_name: str,
+ error: Exception,
+ ):
+ """Record a workflow error"""
+ workflow_span = self._active_workflows.get(workflow_id)
+ if workflow_span:
+ workflow_span.add_event("workflow_error", {
+ "step": step_name,
+ "error_type": type(error).__name__,
+ "error_message": str(error),
+ })
+ workflow_span.set_status(SpanStatus.ERROR, f"Error in {step_name}: {error}")
+
+ # Also record on current span
+ span = self.tracer.current_span
+ if span:
+ span.set_status(SpanStatus.ERROR, str(error))
+ span.add_event("exception", {
+ "type": type(error).__name__,
+ "message": str(error),
+ })
+
+ def get_workflow_trace(self, workflow_id: str) -> Dict[str, Any]:
+ """Get complete trace for a workflow"""
+ # Find the workflow's trace
+ workflow_span = self._active_workflows.get(workflow_id)
+ if workflow_span:
+ trace_id = workflow_span.context.trace_id
+ return {
+ "workflow_id": workflow_id,
+ "trace_id": trace_id,
+ "spans": self.tracer.get_trace(trace_id),
+ }
+ return {"error": "Workflow not found"}
+
+ def get_workflow_performance(self, workflow_id: str) -> Dict[str, Any]:
+ """Get performance metrics for a workflow"""
+ workflow_span = self._active_workflows.get(workflow_id)
+
+ if not workflow_span:
+ return {"error": "Workflow not found"}
+
+ trace_id = workflow_span.context.trace_id
+ spans = self.tracer.get_trace(trace_id)
+
+ # Calculate metrics
+ total_duration = workflow_span.duration_ms
+ step_durations = []
+ step_statuses = []
+
+ for span_dict in spans:
+ if span_dict.get("name", "").startswith("step:"):
+ duration = span_dict.get("duration_ms")
+ if duration:
+ step_durations.append(duration)
+ step_statuses.append(span_dict.get("status", "unknown"))
+
+ return {
+ "workflow_id": workflow_id,
+ "total_duration_ms": total_duration,
+ "total_steps": len(step_durations),
+ "avg_step_duration_ms": sum(step_durations) / len(step_durations) if step_durations else 0,
+ "max_step_duration_ms": max(step_durations) if step_durations else 0,
+ "steps_ok": step_statuses.count("ok"),
+ "steps_error": step_statuses.count("error"),
+ }
+
+
+# Global workflow tracer instance
+_workflow_tracer: Optional[WorkflowTracer] = None
+
+
+def get_workflow_tracer() -> WorkflowTracer:
+ """Get the global workflow tracer"""
+ global _workflow_tracer
+ if _workflow_tracer is None:
+ _workflow_tracer = WorkflowTracer()
+ return _workflow_tracer
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/__init__.py
new file mode 100644
index 000000000..d4c8d40bd
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/__init__.py
@@ -0,0 +1,68 @@
+"""Renaissance Technologies utility functions."""
+
+from .data_fetcher import (
+ StockData,
+ fetch_stock_data_yfinance,
+ fetch_market_benchmark,
+ fetch_peer_prices,
+ validate_data,
+ prepare_analysis_inputs,
+)
+
+from .model_factory import (
+ ModelFactory,
+ ModelConfig,
+ get_model_factory,
+ create_model_from_config,
+ get_default_model_settings,
+)
+
+from .embedder_factory import (
+ EmbedderFactory,
+ EmbedderConfig,
+ get_embedder_factory,
+ create_embedder_from_config,
+)
+
+from .paths import (
+ get_app_data_dir,
+ get_rentech_data_dir,
+ get_knowledge_base_path,
+ get_memory_db_path,
+ get_logs_dir,
+ get_cache_dir,
+ get_frontend_db_path,
+ get_knowledge_path,
+ get_memory_path,
+ get_log_file_path,
+ get_cache_file_path,
+)
+
+__all__ = [
+ "StockData",
+ "fetch_stock_data_yfinance",
+ "fetch_market_benchmark",
+ "fetch_peer_prices",
+ "validate_data",
+ "prepare_analysis_inputs",
+ "ModelFactory",
+ "ModelConfig",
+ "get_model_factory",
+ "create_model_from_config",
+ "get_default_model_settings",
+ "EmbedderFactory",
+ "EmbedderConfig",
+ "get_embedder_factory",
+ "create_embedder_from_config",
+ "get_app_data_dir",
+ "get_rentech_data_dir",
+ "get_knowledge_base_path",
+ "get_memory_db_path",
+ "get_logs_dir",
+ "get_cache_dir",
+ "get_frontend_db_path",
+ "get_knowledge_path",
+ "get_memory_path",
+ "get_log_file_path",
+ "get_cache_file_path",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/data_fetcher.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/data_fetcher.py
new file mode 100644
index 000000000..9c953df89
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/data_fetcher.py
@@ -0,0 +1,250 @@
+"""
+Data Fetcher Utility
+
+Unified data fetching for Renaissance Technologies agent.
+Supports multiple data sources with fallbacks.
+"""
+
+from typing import Dict, Any, Optional, List, Tuple
+from dataclasses import dataclass
+import json
+
+
+@dataclass
+class StockData:
+ """Unified stock data container"""
+ ticker: str
+ prices: List[float]
+ market_cap: float
+ avg_daily_volume: Optional[float]
+ revenues: Optional[List[float]]
+ earnings: Optional[List[float]]
+ metrics: Dict[str, Any]
+ error: Optional[str] = None
+
+
+def fetch_stock_data_yfinance(ticker: str, period: str = "1y") -> StockData:
+ """
+ Fetch stock data using yfinance.
+
+ Args:
+ ticker: Stock ticker symbol
+ period: Data period (1mo, 3mo, 6mo, 1y, 2y, 5y)
+
+ Returns:
+ StockData object with all available data
+ """
+ try:
+ import yfinance as yf
+
+ stock = yf.Ticker(ticker)
+
+ # Get historical prices
+ hist = stock.history(period=period)
+ if hist.empty:
+ return StockData(
+ ticker=ticker,
+ prices=[],
+ market_cap=0,
+ avg_daily_volume=None,
+ revenues=None,
+ earnings=None,
+ metrics={},
+ error=f"No historical data found for {ticker}"
+ )
+
+ # Prices (most recent first)
+ prices = hist['Close'].tolist()[::-1]
+
+ # Get info
+ info = stock.info
+
+ # Market cap
+ market_cap = info.get('marketCap', 0) or 0
+
+ # Average daily volume
+ avg_volume_shares = info.get('averageVolume', 0) or 0
+ current_price = prices[0] if prices else 0
+ avg_daily_volume = avg_volume_shares * current_price
+
+ # Financial metrics
+ metrics = {
+ 'price_to_earnings': info.get('trailingPE'),
+ 'price_to_book': info.get('priceToBook'),
+ 'return_on_equity': info.get('returnOnEquity'),
+ 'return_on_assets': info.get('returnOnAssets'),
+ 'debt_to_equity': info.get('debtToEquity'),
+ 'current_ratio': info.get('currentRatio'),
+ 'profit_margin': info.get('profitMargins'),
+ 'operating_margin': info.get('operatingMargins'),
+ 'revenue_growth': info.get('revenueGrowth'),
+ 'earnings_growth': info.get('earningsGrowth'),
+ 'dividend_yield': info.get('dividendYield'),
+ 'beta': info.get('beta'),
+ 'fifty_two_week_high': info.get('fiftyTwoWeekHigh'),
+ 'fifty_two_week_low': info.get('fiftyTwoWeekLow'),
+ 'fifty_day_average': info.get('fiftyDayAverage'),
+ 'two_hundred_day_average': info.get('twoHundredDayAverage'),
+ }
+
+ # Try to get financials
+ revenues = None
+ earnings = None
+
+ try:
+ financials = stock.financials
+ if financials is not None and not financials.empty:
+ if 'Total Revenue' in financials.index:
+ revenues = financials.loc['Total Revenue'].tolist()
+ if 'Net Income' in financials.index:
+ earnings = financials.loc['Net Income'].tolist()
+ except Exception:
+ pass
+
+ return StockData(
+ ticker=ticker,
+ prices=prices,
+ market_cap=market_cap,
+ avg_daily_volume=avg_daily_volume,
+ revenues=revenues,
+ earnings=earnings,
+ metrics=metrics
+ )
+
+ except ImportError:
+ return StockData(
+ ticker=ticker,
+ prices=[],
+ market_cap=0,
+ avg_daily_volume=None,
+ revenues=None,
+ earnings=None,
+ metrics={},
+ error="yfinance not installed"
+ )
+ except Exception as e:
+ return StockData(
+ ticker=ticker,
+ prices=[],
+ market_cap=0,
+ avg_daily_volume=None,
+ revenues=None,
+ earnings=None,
+ metrics={},
+ error=str(e)
+ )
+
+
+def fetch_market_benchmark(period: str = "1y") -> List[float]:
+ """
+ Fetch market benchmark (SPY) prices.
+
+ Args:
+ period: Data period
+
+ Returns:
+ List of prices (most recent first)
+ """
+ try:
+ data = fetch_stock_data_yfinance("SPY", period)
+ return data.prices
+ except Exception:
+ return []
+
+
+def fetch_peer_prices(peer_ticker: str, period: str = "1y") -> List[float]:
+ """
+ Fetch peer security prices for pairs trading.
+
+ Args:
+ peer_ticker: Peer stock ticker
+ period: Data period
+
+ Returns:
+ List of prices (most recent first)
+ """
+ try:
+ data = fetch_stock_data_yfinance(peer_ticker, period)
+ return data.prices
+ except Exception:
+ return []
+
+
+def validate_data(data: StockData) -> Tuple[bool, List[str]]:
+ """
+ Validate fetched data quality.
+
+ Returns:
+ Tuple of (is_valid, list of warnings)
+ """
+ warnings = []
+ is_valid = True
+
+ if data.error:
+ warnings.append(f"Data error: {data.error}")
+ is_valid = False
+
+ if not data.prices:
+ warnings.append("No price data available")
+ is_valid = False
+ elif len(data.prices) < 20:
+ warnings.append(f"Limited price history: {len(data.prices)} days")
+
+ if data.market_cap <= 0:
+ warnings.append("Market cap not available")
+
+ if data.avg_daily_volume is None or data.avg_daily_volume <= 0:
+ warnings.append("Average daily volume not available")
+
+ if not data.revenues:
+ warnings.append("Revenue data not available")
+
+ if not data.earnings:
+ warnings.append("Earnings data not available")
+
+ # Check for stale data
+ if data.prices and len(data.prices) > 1:
+ if data.prices[0] == data.prices[1]:
+ warnings.append("Prices may be stale (no recent change)")
+
+ return is_valid, warnings
+
+
+def prepare_analysis_inputs(
+ data: StockData,
+ trade_value: float = 1_000_000
+) -> Dict[str, Any]:
+ """
+ Prepare inputs for all analysis modules.
+
+ Args:
+ data: Fetched stock data
+ trade_value: Intended trade value for execution analysis
+
+ Returns:
+ Dictionary with prepared inputs for each analysis module
+ """
+ # Calculate daily volatility from prices
+ volatility = 0.02 # Default
+ if len(data.prices) >= 20:
+ returns = [
+ (data.prices[i] / data.prices[i + 1]) - 1
+ for i in range(min(20, len(data.prices) - 1))
+ ]
+ if returns:
+ import math
+ mean_return = sum(returns) / len(returns)
+ variance = sum((r - mean_return) ** 2 for r in returns) / len(returns)
+ volatility = math.sqrt(variance)
+
+ return {
+ "ticker": data.ticker,
+ "prices": data.prices,
+ "market_cap": data.market_cap or 10_000_000_000, # Default $10B
+ "avg_daily_volume": data.avg_daily_volume,
+ "revenues": data.revenues,
+ "earnings": data.earnings,
+ "metrics": data.metrics,
+ "trade_value": trade_value,
+ "volatility": volatility,
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/embedder_factory.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/embedder_factory.py
new file mode 100644
index 000000000..f5c9913f6
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/embedder_factory.py
@@ -0,0 +1,391 @@
+"""
+Dynamic Embedder Factory for Agno Framework
+
+Reads embedding configuration from frontend SQLite database and creates
+appropriate Agno embedder instances for all supported providers.
+
+Supports 18+ providers including:
+- OpenAI, Google, Azure, AWS Bedrock
+- Ollama (local, no API key needed)
+- Cohere, Mistral, Voyage AI
+- HuggingFace, FastEmbed, Sentence Transformers
+"""
+
+import os
+from typing import Dict, Any, Optional
+from dataclasses import dataclass
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class EmbedderConfig:
+ """Embedder configuration from frontend database"""
+ provider: str
+ model_id: str
+ api_key: Optional[str] = None
+ base_url: Optional[str] = None
+ dimensions: int = 1536
+ batch_enabled: bool = True
+ batch_size: int = 100
+
+
+class EmbedderFactory:
+ """
+ Factory for creating Agno embedder instances from frontend configuration.
+
+ Supports all Agno embedding providers with fallback to Ollama (local, free).
+ """
+
+ # Default dimensions for known providers
+ PROVIDER_DIMENSIONS = {
+ "openai": 1536,
+ "ollama": 4096,
+ "google": 768,
+ "cohere": 1024,
+ "mistral": 1024,
+ "voyageai": 1024,
+ "jina": 768,
+ }
+
+ # Default model IDs
+ DEFAULT_MODELS = {
+ "openai": "text-embedding-3-small",
+ "ollama": "nomic-embed-text", # Fast, free, local
+ "google": "models/embedding-001",
+ "azure_openai": "text-embedding-3-small",
+ "cohere": "embed-english-v3.0",
+ "mistral": "mistral-embed",
+ }
+
+ def __init__(self, frontend_db_path: Optional[str] = None):
+ """
+ Initialize embedder factory.
+
+ Args:
+ frontend_db_path: Path to frontend SQLite database (fincept.db)
+ """
+ self.frontend_db_path = frontend_db_path
+ self._config_cache: Optional[EmbedderConfig] = None
+
+ def _get_frontend_db_path(self) -> Optional[str]:
+ """
+ Find frontend database path using centralized path utilities.
+
+ Priority:
+ 1. Explicitly provided path
+ 2. Centralized path utility (checks standard locations)
+ """
+ if self.frontend_db_path:
+ return self.frontend_db_path
+
+ # Use centralized path utility
+ try:
+ from .paths import get_frontend_db_path
+ frontend_db = get_frontend_db_path()
+ if frontend_db:
+ return str(frontend_db)
+ except ImportError:
+ logger.warning("Path utilities not available")
+
+ logger.warning("Frontend database not found. Using Ollama fallback.")
+ return None
+
+ def _load_embedder_config_from_db(self) -> Optional[EmbedderConfig]:
+ """
+ Load embedder configuration from frontend SQLite database.
+
+ Reads from LLM config table (embedding provider may be same as LLM provider).
+
+ Returns:
+ EmbedderConfig if found, None otherwise
+ """
+ db_path = self._get_frontend_db_path()
+ if not db_path:
+ return None
+
+ try:
+ import sqlite3
+ conn = sqlite3.connect(db_path)
+ cursor = conn.cursor()
+
+ # Try to get embedding-specific config (if exists)
+ cursor.execute("""
+ SELECT provider, model, api_key, base_url
+ FROM llm_configs
+ WHERE is_active = 1 AND provider IS NOT NULL
+ LIMIT 1
+ """)
+
+ row = cursor.fetchone()
+ conn.close()
+
+ if not row:
+ logger.warning("No active LLM config found for embeddings")
+ return None
+
+ provider, model, api_key, base_url = row
+
+ # Get dimensions based on provider
+ dimensions = self.PROVIDER_DIMENSIONS.get(provider.lower(), 1536)
+
+ config = EmbedderConfig(
+ provider=provider.lower(),
+ model_id=model or self.DEFAULT_MODELS.get(provider.lower(), ""),
+ api_key=api_key,
+ base_url=base_url,
+ dimensions=dimensions,
+ batch_enabled=True,
+ batch_size=100
+ )
+
+ logger.info(f"Loaded embedder config: {provider} / {model}")
+ return config
+
+ except Exception as e:
+ logger.error(f"Error loading embedder config from database: {e}")
+ return None
+
+ def _get_embedder_config(self, override_config: Optional[Dict[str, Any]] = None) -> EmbedderConfig:
+ """
+ Get embedder configuration with priority:
+ 1. Override config (runtime parameters)
+ 2. Cached config from database
+ 3. Fallback to Ollama (local, free)
+
+ Args:
+ override_config: Optional runtime configuration override
+
+ Returns:
+ EmbedderConfig
+ """
+ # If override provided, use it
+ if override_config:
+ return EmbedderConfig(
+ provider=override_config.get("provider", "ollama"),
+ model_id=override_config.get("model_id", "nomic-embed-text"),
+ api_key=override_config.get("api_key"),
+ base_url=override_config.get("base_url"),
+ dimensions=override_config.get("dimensions", 768),
+ batch_enabled=override_config.get("batch_enabled", True),
+ batch_size=override_config.get("batch_size", 100)
+ )
+
+ # Try to load from database (cache for performance)
+ if not self._config_cache:
+ self._config_cache = self._load_embedder_config_from_db()
+
+ if self._config_cache:
+ return self._config_cache
+
+ # Fallback to Ollama (local, no API key)
+ logger.info("Using Ollama embedder (local, free)")
+ return EmbedderConfig(
+ provider="ollama",
+ model_id="nomic-embed-text",
+ dimensions=768,
+ batch_enabled=True,
+ batch_size=100
+ )
+
+ def _create_openai_embedder(self, config: EmbedderConfig):
+ """Create OpenAI embedder"""
+ from agno.knowledge.embedder.openai import OpenAIEmbedder
+
+ return OpenAIEmbedder(
+ id=config.model_id,
+ api_key=config.api_key or os.getenv("OPENAI_API_KEY"),
+ base_url=config.base_url,
+ dimensions=config.dimensions,
+ enable_batch=config.batch_enabled,
+ batch_size=config.batch_size,
+ )
+
+ def _create_ollama_embedder(self, config: EmbedderConfig):
+ """Create Ollama embedder (local, no API key needed)"""
+ from agno.knowledge.embedder.ollama import OllamaEmbedder
+
+ return OllamaEmbedder(
+ id=config.model_id,
+ host=config.base_url or "http://localhost:11434",
+ dimensions=config.dimensions,
+ enable_batch=config.batch_enabled,
+ batch_size=config.batch_size,
+ )
+
+ def _create_google_embedder(self, config: EmbedderConfig):
+ """Create Google Gemini embedder"""
+ from agno.knowledge.embedder.google import GoogleEmbedder
+
+ return GoogleEmbedder(
+ id=config.model_id,
+ api_key=config.api_key or os.getenv("GOOGLE_API_KEY"),
+ dimensions=config.dimensions,
+ enable_batch=config.batch_enabled,
+ batch_size=config.batch_size,
+ )
+
+ def _create_azure_embedder(self, config: EmbedderConfig):
+ """Create Azure OpenAI embedder"""
+ from agno.knowledge.embedder.azure_openai import AzureOpenAIEmbedder
+
+ return AzureOpenAIEmbedder(
+ id=config.model_id,
+ api_key=config.api_key or os.getenv("AZURE_OPENAI_API_KEY"),
+ azure_endpoint=config.base_url or os.getenv("AZURE_OPENAI_ENDPOINT"),
+ dimensions=config.dimensions,
+ enable_batch=config.batch_enabled,
+ batch_size=config.batch_size,
+ )
+
+ def _create_cohere_embedder(self, config: EmbedderConfig):
+ """Create Cohere embedder"""
+ from agno.knowledge.embedder.cohere import CohereEmbedder
+
+ return CohereEmbedder(
+ id=config.model_id,
+ api_key=config.api_key or os.getenv("COHERE_API_KEY"),
+ dimensions=config.dimensions,
+ enable_batch=config.batch_enabled,
+ batch_size=config.batch_size,
+ )
+
+ def _create_mistral_embedder(self, config: EmbedderConfig):
+ """Create Mistral embedder"""
+ from agno.knowledge.embedder.mistral import MistralEmbedder
+
+ return MistralEmbedder(
+ id=config.model_id,
+ api_key=config.api_key or os.getenv("MISTRAL_API_KEY"),
+ dimensions=config.dimensions,
+ enable_batch=config.batch_enabled,
+ batch_size=config.batch_size,
+ )
+
+ def create_embedder(self, override_config: Optional[Dict[str, Any]] = None):
+ """
+ Create Agno embedder instance from configuration.
+
+ Args:
+ override_config: Optional configuration override
+
+ Returns:
+ Agno embedder instance
+
+ Examples:
+ # Use active config from frontend
+ embedder = factory.create_embedder()
+
+ # Override with runtime config
+ embedder = factory.create_embedder({
+ "provider": "openai",
+ "model_id": "text-embedding-3-large",
+ "api_key": "sk-...",
+ "dimensions": 3072
+ })
+
+ # Use Ollama (local, free)
+ embedder = factory.create_embedder({
+ "provider": "ollama",
+ "model_id": "nomic-embed-text"
+ })
+ """
+ config = self._get_embedder_config(override_config)
+ provider = config.provider.lower()
+
+ # Map provider to creation method
+ try:
+ if provider == "openai":
+ return self._create_openai_embedder(config)
+ elif provider == "ollama":
+ return self._create_ollama_embedder(config)
+ elif provider in ["google", "gemini"]:
+ return self._create_google_embedder(config)
+ elif provider in ["azure", "azure_openai"]:
+ return self._create_azure_embedder(config)
+ elif provider == "cohere":
+ return self._create_cohere_embedder(config)
+ elif provider == "mistral":
+ return self._create_mistral_embedder(config)
+ else:
+ # Universal fallback - try Ollama
+ logger.warning(f"Provider {provider} not explicitly supported, falling back to Ollama")
+ return self._create_ollama_embedder(EmbedderConfig(
+ provider="ollama",
+ model_id="nomic-embed-text",
+ dimensions=768
+ ))
+
+ except ImportError as e:
+ logger.warning(f"Provider {provider} not available, falling back to Ollama: {e}")
+ return self._create_ollama_embedder(EmbedderConfig(
+ provider="ollama",
+ model_id="nomic-embed-text",
+ dimensions=768
+ ))
+ except Exception as e:
+ logger.error(f"Error creating embedder for {provider}: {e}")
+ # Final fallback to Ollama
+ logger.warning("Using Ollama fallback due to error")
+ return self._create_ollama_embedder(EmbedderConfig(
+ provider="ollama",
+ model_id="nomic-embed-text",
+ dimensions=768
+ ))
+
+ def refresh_config(self):
+ """Force reload configuration from database"""
+ self._config_cache = None
+ logger.info("Embedder configuration cache cleared")
+
+
+# Global factory instance
+_global_embedder_factory: Optional[EmbedderFactory] = None
+
+
+def get_embedder_factory(frontend_db_path: Optional[str] = None) -> EmbedderFactory:
+ """
+ Get global embedder factory instance.
+
+ Args:
+ frontend_db_path: Optional path to frontend database
+
+ Returns:
+ EmbedderFactory instance
+ """
+ global _global_embedder_factory
+ if _global_embedder_factory is None:
+ _global_embedder_factory = EmbedderFactory(frontend_db_path)
+ return _global_embedder_factory
+
+
+def create_embedder_from_config(config_dict: Optional[Dict[str, Any]] = None):
+ """
+ Convenience function to create embedder from configuration.
+
+ Args:
+ config_dict: Optional configuration dictionary
+
+ Returns:
+ Agno embedder instance
+
+ Examples:
+ # Use frontend config (or Ollama fallback)
+ embedder = create_embedder_from_config()
+
+ # Override config
+ embedder = create_embedder_from_config({
+ "provider": "openai",
+ "model_id": "text-embedding-3-small",
+ "api_key": "sk-...",
+ "dimensions": 1536
+ })
+
+ # Use local Ollama
+ embedder = create_embedder_from_config({
+ "provider": "ollama"
+ })
+ """
+ factory = get_embedder_factory()
+ return factory.create_embedder(config_dict)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/model_factory.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/model_factory.py
new file mode 100644
index 000000000..6912360e5
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/model_factory.py
@@ -0,0 +1,413 @@
+"""
+Dynamic Model Factory for Agno Framework
+
+Reads LLM configuration from frontend SQLite database and creates
+appropriate Agno model instances for all supported providers.
+
+Supports 40+ providers including:
+- OpenAI, Anthropic, Google, Mistral, Cohere, Meta
+- Cloud providers: AWS Bedrock, Azure, Vertex AI
+- Fast inference: Groq, Together, Fireworks
+- Local: Ollama, llama.cpp, LM Studio
+- Custom OpenAI-compatible endpoints
+"""
+
+import os
+import sqlite3
+from typing import Dict, Any, Optional, List
+from dataclasses import dataclass
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class ModelConfig:
+ """Model configuration from frontend database"""
+ provider: str
+ model_id: str
+ api_key: Optional[str] = None
+ base_url: Optional[str] = None
+ temperature: float = 0.7
+ max_tokens: int = 4096
+
+
+class ModelFactory:
+ """
+ Factory for creating Agno model instances from frontend configuration.
+
+ Supports all Agno providers with fallback handling and custom base URLs.
+ """
+
+ # Default base URLs for known providers
+ PROVIDER_BASE_URLS = {
+ "openai": "https://api.openai.com/v1",
+ "anthropic": "https://api.anthropic.com",
+ "google": "https://generativelanguage.googleapis.com",
+ "groq": "https://api.groq.com/openai/v1",
+ "together": "https://api.together.xyz/v1",
+ "fireworks": "https://api.fireworks.ai/inference/v1",
+ "deepseek": "https://api.deepseek.com",
+ "mistral": "https://api.mistral.ai/v1",
+ "cohere": "https://api.cohere.ai",
+ "perplexity": "https://api.perplexity.ai",
+ "openrouter": "https://openrouter.ai/api/v1",
+ "ollama": "http://localhost:11434",
+ "x-ai": "https://api.x.ai/v1",
+ }
+
+ def __init__(self, frontend_db_path: Optional[str] = None):
+ """
+ Initialize model factory.
+
+ Args:
+ frontend_db_path: Path to frontend SQLite database (fincept.db)
+ """
+ self.frontend_db_path = frontend_db_path
+ self._config_cache: Optional[ModelConfig] = None
+
+ def _get_frontend_db_path(self) -> Optional[str]:
+ """
+ Find frontend database path using centralized path utilities.
+
+ Priority:
+ 1. Explicitly provided path
+ 2. Centralized path utility (checks standard locations)
+ """
+ if self.frontend_db_path:
+ return self.frontend_db_path
+
+ # Use centralized path utility
+ try:
+ from .paths import get_frontend_db_path
+ frontend_db = get_frontend_db_path()
+ if frontend_db:
+ return str(frontend_db)
+ except ImportError:
+ logger.warning("Path utilities not available")
+
+ logger.warning("Frontend database not found. Using fallback configuration.")
+ return None
+
+ def _load_llm_config_from_db(self) -> Optional[ModelConfig]:
+ """
+ Load active LLM configuration from frontend SQLite database.
+
+ Returns:
+ ModelConfig if found, None otherwise
+ """
+ db_path = self._get_frontend_db_path()
+ if not db_path:
+ return None
+
+ try:
+ conn = sqlite3.connect(db_path)
+ cursor = conn.cursor()
+
+ # Get active LLM config
+ cursor.execute("""
+ SELECT provider, api_key, base_url, model
+ FROM llm_configs
+ WHERE is_active = 1
+ LIMIT 1
+ """)
+
+ row = cursor.fetchone()
+ if not row:
+ logger.warning("No active LLM config found in database")
+ conn.close()
+ return None
+
+ provider, api_key, base_url, model = row
+
+ # Get global settings
+ cursor.execute("""
+ SELECT temperature, max_tokens
+ FROM llm_global_settings
+ LIMIT 1
+ """)
+
+ settings_row = cursor.fetchone()
+ temperature = settings_row[0] if settings_row else 0.7
+ max_tokens = settings_row[1] if settings_row else 4096
+
+ conn.close()
+
+ config = ModelConfig(
+ provider=provider,
+ model_id=model,
+ api_key=api_key,
+ base_url=base_url,
+ temperature=temperature,
+ max_tokens=max_tokens
+ )
+
+ logger.info(f"Loaded config: {provider} / {model}")
+ return config
+
+ except Exception as e:
+ logger.error(f"Error loading config from database: {e}")
+ return None
+
+ def _get_model_config(self, override_config: Optional[Dict[str, Any]] = None) -> ModelConfig:
+ """
+ Get model configuration with priority:
+ 1. Override config (runtime parameters)
+ 2. Cached config from database
+ 3. Fallback to default
+
+ Args:
+ override_config: Optional runtime configuration override
+
+ Returns:
+ ModelConfig
+ """
+ # If override provided, use it
+ if override_config:
+ return ModelConfig(
+ provider=override_config.get("provider", "openai"),
+ model_id=override_config.get("model_id", "gpt-4o"),
+ api_key=override_config.get("api_key"),
+ base_url=override_config.get("base_url"),
+ temperature=override_config.get("temperature", 0.7),
+ max_tokens=override_config.get("max_tokens", 4096)
+ )
+
+ # Try to load from database (cache for performance)
+ if not self._config_cache:
+ self._config_cache = self._load_llm_config_from_db()
+
+ if self._config_cache:
+ return self._config_cache
+
+ # Fallback to default
+ logger.warning("Using fallback OpenAI GPT-4o configuration")
+ return ModelConfig(
+ provider="openai",
+ model_id="gpt-4o",
+ temperature=0.7,
+ max_tokens=4096
+ )
+
+ def _create_openai_model(self, config: ModelConfig):
+ """Create OpenAI model"""
+ from agno.models.openai import OpenAI
+
+ return OpenAI(
+ id=config.model_id,
+ api_key=config.api_key or os.getenv("OPENAI_API_KEY"),
+ temperature=config.temperature,
+ max_tokens=config.max_tokens
+ )
+
+ def _create_anthropic_model(self, config: ModelConfig):
+ """Create Anthropic Claude model"""
+ from agno.models.anthropic import Claude
+
+ kwargs = {
+ "id": config.model_id,
+ "temperature": config.temperature,
+ "max_tokens": config.max_tokens
+ }
+
+ # Handle custom base URL
+ if config.base_url:
+ import anthropic
+ custom_client = anthropic.Anthropic(
+ api_key=config.api_key or os.getenv("ANTHROPIC_API_KEY", ""),
+ base_url=config.base_url
+ )
+ kwargs["client"] = custom_client
+ else:
+ kwargs["api_key"] = config.api_key or os.getenv("ANTHROPIC_API_KEY")
+
+ return Claude(**kwargs)
+
+ def _create_google_model(self, config: ModelConfig):
+ """Create Google Gemini model"""
+ from agno.models.google import Gemini
+
+ return Gemini(
+ id=config.model_id,
+ api_key=config.api_key or os.getenv("GOOGLE_API_KEY"),
+ temperature=config.temperature,
+ max_tokens=config.max_tokens
+ )
+
+ def _create_groq_model(self, config: ModelConfig):
+ """Create Groq model"""
+ from agno.models.groq import Groq
+
+ return Groq(
+ id=config.model_id,
+ api_key=config.api_key or os.getenv("GROQ_API_KEY"),
+ temperature=config.temperature,
+ max_tokens=config.max_tokens
+ )
+
+ def _create_ollama_model(self, config: ModelConfig):
+ """Create Ollama local model"""
+ from agno.models.ollama import Ollama
+
+ return Ollama(
+ id=config.model_id,
+ host=config.base_url or self.PROVIDER_BASE_URLS["ollama"],
+ temperature=config.temperature,
+ max_tokens=config.max_tokens
+ )
+
+ def _create_openai_like_model(self, config: ModelConfig):
+ """
+ Create OpenAI-compatible model for any provider.
+
+ This is the universal fallback for:
+ - Custom providers
+ - Providers not natively supported
+ - OpenAI-compatible endpoints
+ """
+ from agno.models.openai.like import OpenAILike
+
+ base_url = config.base_url or self.PROVIDER_BASE_URLS.get(
+ config.provider.lower(),
+ "http://localhost:8000/v1"
+ )
+
+ return OpenAILike(
+ id=config.model_id,
+ api_key=config.api_key or os.getenv(f"{config.provider.upper()}_API_KEY", ""),
+ base_url=base_url,
+ temperature=config.temperature,
+ max_tokens=config.max_tokens
+ )
+
+ def create_model(self, override_config: Optional[Dict[str, Any]] = None):
+ """
+ Create Agno model instance from configuration.
+
+ Args:
+ override_config: Optional configuration override
+
+ Returns:
+ Agno model instance
+
+ Examples:
+ # Use active config from frontend
+ model = factory.create_model()
+
+ # Override with runtime config
+ model = factory.create_model({
+ "provider": "groq",
+ "model_id": "llama-3-70b-versatile",
+ "api_key": "gsk_...",
+ "temperature": 0.3
+ })
+ """
+ config = self._get_model_config(override_config)
+ provider = config.provider.lower()
+
+ # Map provider to creation method
+ try:
+ if provider == "openai":
+ return self._create_openai_model(config)
+ elif provider == "anthropic":
+ return self._create_anthropic_model(config)
+ elif provider in ["google", "gemini"]:
+ return self._create_google_model(config)
+ elif provider == "groq":
+ return self._create_groq_model(config)
+ elif provider == "ollama":
+ return self._create_ollama_model(config)
+ else:
+ # Universal fallback for all other providers
+ logger.info(f"Using OpenAI-compatible interface for provider: {provider}")
+ return self._create_openai_like_model(config)
+
+ except ImportError as e:
+ logger.warning(f"Provider {provider} not available, using OpenAI-like fallback: {e}")
+ return self._create_openai_like_model(config)
+ except Exception as e:
+ logger.error(f"Error creating model for {provider}: {e}")
+ # Final fallback
+ logger.warning("Using OpenAI-like fallback due to error")
+ return self._create_openai_like_model(config)
+
+ def refresh_config(self):
+ """Force reload configuration from database"""
+ self._config_cache = None
+ logger.info("Configuration cache cleared")
+
+
+# Global factory instance
+_global_factory: Optional[ModelFactory] = None
+
+
+def get_model_factory(frontend_db_path: Optional[str] = None) -> ModelFactory:
+ """
+ Get global model factory instance.
+
+ Args:
+ frontend_db_path: Optional path to frontend database
+
+ Returns:
+ ModelFactory instance
+ """
+ global _global_factory
+ if _global_factory is None:
+ _global_factory = ModelFactory(frontend_db_path)
+ return _global_factory
+
+
+def create_model_from_config(config_dict: Optional[Dict[str, Any]] = None):
+ """
+ Convenience function to create model from configuration.
+
+ Args:
+ config_dict: Optional configuration dictionary
+
+ Returns:
+ Agno model instance
+
+ Examples:
+ # Use frontend config
+ model = create_model_from_config()
+
+ # Override config
+ model = create_model_from_config({
+ "provider": "anthropic",
+ "model_id": "claude-3-5-sonnet-20241022",
+ "api_key": "sk-ant-...",
+ "temperature": 0.5
+ })
+ """
+ factory = get_model_factory()
+ return factory.create_model(config_dict)
+
+
+def get_default_model_settings() -> Dict[str, Any]:
+ """
+ Get default model settings from active frontend configuration.
+
+ Returns model settings that should be used as defaults throughout
+ the system (schemas, presets, etc.)
+
+ Returns:
+ Dict with provider, model_id, temperature, max_tokens
+
+ Examples:
+ # Use in schema defaults
+ @dataclass
+ class ModelSettings:
+ provider: str = field(default_factory=lambda: get_default_model_settings()["provider"])
+ model_id: str = field(default_factory=lambda: get_default_model_settings()["model_id"])
+ """
+ factory = get_model_factory()
+ config = factory._get_model_config()
+
+ return {
+ "provider": config.provider,
+ "model_id": config.model_id,
+ "temperature": config.temperature,
+ "max_tokens": config.max_tokens,
+ "api_key": config.api_key,
+ "base_url": config.base_url,
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/paths.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/paths.py
new file mode 100644
index 000000000..1099f856b
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/paths.py
@@ -0,0 +1,259 @@
+"""
+Cross-Platform Path Utilities for Fincept Terminal
+
+Provides consistent paths across Windows, macOS, and Linux for storing
+RenTech agent data (knowledge base, memory, logs, etc.)
+
+Uses standard application data directories:
+- Windows: %APPDATA%\fincept-terminal\
+- macOS: ~/Library/Application Support/fincept-terminal/
+- Linux: ~/.local/share/fincept-terminal/
+"""
+
+import os
+import platform
+from pathlib import Path
+from typing import Optional
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+def get_app_data_dir() -> Path:
+ """
+ Get the Fincept Terminal application data directory.
+
+ Returns the appropriate directory for the current platform:
+ - Windows: %APPDATA%\fincept-terminal\
+ - macOS: ~/Library/Application Support/fincept-terminal/
+ - Linux: ~/.local/share/fincept-terminal/
+
+ Creates the directory if it doesn't exist.
+
+ Returns:
+ Path to fincept-terminal app data directory
+ """
+ system = platform.system()
+
+ if system == "Windows":
+ # Windows: %APPDATA%\fincept-terminal
+ base = Path(os.getenv("APPDATA", os.path.expanduser("~/AppData/Roaming")))
+ elif system == "Darwin":
+ # macOS: ~/Library/Application Support/fincept-terminal
+ base = Path.home() / "Library" / "Application Support"
+ else:
+ # Linux: ~/.local/share/fincept-terminal
+ base = Path.home() / ".local" / "share"
+
+ app_dir = base / "fincept-terminal"
+
+ # Create directory if it doesn't exist
+ try:
+ app_dir.mkdir(parents=True, exist_ok=True)
+ except Exception as e:
+ logger.warning(f"Could not create app data directory: {e}")
+
+ return app_dir
+
+
+def get_rentech_data_dir() -> Path:
+ """
+ Get the RenTech agent data directory.
+
+ Returns:
+ Path to rentech agent data directory
+ (e.g., %APPDATA%\fincept-terminal\rentech\)
+ """
+ rentech_dir = get_app_data_dir() / "rentech"
+
+ try:
+ rentech_dir.mkdir(parents=True, exist_ok=True)
+ except Exception as e:
+ logger.warning(f"Could not create RenTech data directory: {e}")
+
+ return rentech_dir
+
+
+def get_knowledge_base_path() -> Path:
+ """
+ Get the path for knowledge base storage (LanceDB).
+
+ Returns:
+ Path to knowledge base directory
+ (e.g., %APPDATA%\fincept-terminal\rentech\knowledge\)
+ """
+ kb_dir = get_rentech_data_dir() / "knowledge"
+
+ try:
+ kb_dir.mkdir(parents=True, exist_ok=True)
+ except Exception as e:
+ logger.warning(f"Could not create knowledge base directory: {e}")
+
+ return kb_dir
+
+
+def get_memory_db_path() -> Path:
+ """
+ Get the path for memory database (SQLite).
+
+ Returns:
+ Path to memory database file
+ (e.g., %APPDATA%\fincept-terminal\rentech\memory.db)
+ """
+ return get_rentech_data_dir() / "memory.db"
+
+
+def get_logs_dir() -> Path:
+ """
+ Get the path for logs directory.
+
+ Returns:
+ Path to logs directory
+ (e.g., %APPDATA%\fincept-terminal\rentech\logs\)
+ """
+ logs_dir = get_rentech_data_dir() / "logs"
+
+ try:
+ logs_dir.mkdir(parents=True, exist_ok=True)
+ except Exception as e:
+ logger.warning(f"Could not create logs directory: {e}")
+
+ return logs_dir
+
+
+def get_cache_dir() -> Path:
+ """
+ Get the path for cache directory.
+
+ Returns:
+ Path to cache directory
+ (e.g., %APPDATA%\fincept-terminal\rentech\cache\)
+ """
+ cache_dir = get_rentech_data_dir() / "cache"
+
+ try:
+ cache_dir.mkdir(parents=True, exist_ok=True)
+ except Exception as e:
+ logger.warning(f"Could not create cache directory: {e}")
+
+ return cache_dir
+
+
+def get_frontend_db_path() -> Optional[Path]:
+ """
+ Get the path to frontend SQLite database (fincept.db).
+
+ Searches common locations for the frontend database.
+
+ Returns:
+ Path to fincept.db if found, None otherwise
+ """
+ # Check environment variable first
+ env_path = os.getenv("FINCEPT_DB_PATH")
+ if env_path:
+ path = Path(env_path)
+ if path.exists():
+ return path
+
+ # Check standard location
+ app_data = get_app_data_dir()
+ db_path = app_data / "fincept.db"
+ if db_path.exists():
+ return db_path
+
+ # Alternative locations
+ alternatives = [
+ app_data.parent / "fincept.db", # One level up
+ Path.home() / ".fincept" / "fincept.db",
+ Path("./fincept.db"), # Current directory (dev mode)
+ ]
+
+ for path in alternatives:
+ if path.exists():
+ logger.info(f"Found frontend database at: {path}")
+ return path
+
+ logger.warning("Frontend database (fincept.db) not found")
+ return None
+
+
+def ensure_directory_exists(path: Path) -> bool:
+ """
+ Ensure a directory exists, creating it if necessary.
+
+ Args:
+ path: Directory path to ensure
+
+ Returns:
+ True if directory exists or was created, False on error
+ """
+ try:
+ path.mkdir(parents=True, exist_ok=True)
+ return True
+ except Exception as e:
+ logger.error(f"Failed to create directory {path}: {e}")
+ return False
+
+
+def get_user_specific_path(subdir: str, filename: Optional[str] = None) -> Path:
+ """
+ Get a user-specific path within the RenTech data directory.
+
+ Args:
+ subdir: Subdirectory name (e.g., "models", "exports")
+ filename: Optional filename to append
+
+ Returns:
+ Full path to the requested location
+ """
+ base = get_rentech_data_dir() / subdir
+
+ try:
+ base.mkdir(parents=True, exist_ok=True)
+ except Exception as e:
+ logger.warning(f"Could not create directory {base}: {e}")
+
+ if filename:
+ return base / filename
+ return base
+
+
+# Export convenient path getters
+def get_knowledge_path() -> str:
+ """Get knowledge base path as string"""
+ return str(get_knowledge_base_path())
+
+
+def get_memory_path() -> str:
+ """Get memory database path as string"""
+ return str(get_memory_db_path())
+
+
+def get_log_file_path(log_name: str = "rentech.log") -> str:
+ """Get log file path as string"""
+ return str(get_logs_dir() / log_name)
+
+
+def get_cache_file_path(cache_name: str) -> str:
+ """Get cache file path as string"""
+ return str(get_cache_dir() / cache_name)
+
+
+# Display paths for debugging
+def print_paths():
+ """Print all configured paths (for debugging)"""
+ print("=== Fincept Terminal - RenTech Agent Paths ===")
+ print(f"Platform: {platform.system()}")
+ print(f"App Data Dir: {get_app_data_dir()}")
+ print(f"RenTech Data Dir: {get_rentech_data_dir()}")
+ print(f"Knowledge Base: {get_knowledge_base_path()}")
+ print(f"Memory DB: {get_memory_db_path()}")
+ print(f"Logs Dir: {get_logs_dir()}")
+ print(f"Cache Dir: {get_cache_dir()}")
+ print(f"Frontend DB: {get_frontend_db_path()}")
+ print("=" * 50)
+
+
+if __name__ == "__main__":
+ # Test paths when run directly
+ print_paths()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/__init__.py
new file mode 100644
index 000000000..3aa1e1aaf
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/__init__.py
@@ -0,0 +1,60 @@
+"""
+Renaissance Technologies Workflow Pipelines
+
+Agno Workflows that define the end-to-end processes from
+signal discovery through order execution.
+
+Workflows:
+1. Signal Discovery - Data → Raw Signal
+2. Signal Validation - Raw Signal → Validated Signal
+3. Risk Assessment - Signal → Risk-Adjusted Signal
+4. Execution Pipeline - Approved Signal → Executed Trade
+5. Post-Trade Analysis - Execution → Learnings
+6. Daily Trading Cycle - Full daily workflow
+"""
+
+from .signal_discovery import (
+ SignalDiscoveryWorkflow,
+ run_signal_discovery,
+)
+from .signal_validation import (
+ SignalValidationWorkflow,
+ run_signal_validation,
+)
+from .risk_assessment import (
+ RiskAssessmentWorkflow,
+ run_risk_assessment,
+)
+from .execution_pipeline import (
+ ExecutionPipelineWorkflow,
+ run_execution_pipeline,
+)
+from .post_trade_analysis import (
+ PostTradeWorkflow,
+ run_post_trade_analysis,
+)
+from .daily_cycle import (
+ DailyTradingCycleWorkflow,
+ run_daily_cycle,
+)
+
+__all__ = [
+ # Signal Discovery
+ "SignalDiscoveryWorkflow",
+ "run_signal_discovery",
+ # Signal Validation
+ "SignalValidationWorkflow",
+ "run_signal_validation",
+ # Risk Assessment
+ "RiskAssessmentWorkflow",
+ "run_risk_assessment",
+ # Execution Pipeline
+ "ExecutionPipelineWorkflow",
+ "run_execution_pipeline",
+ # Post-Trade Analysis
+ "PostTradeWorkflow",
+ "run_post_trade_analysis",
+ # Daily Cycle
+ "DailyTradingCycleWorkflow",
+ "run_daily_cycle",
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/base.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/base.py
new file mode 100644
index 000000000..2c5bf2288
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/base.py
@@ -0,0 +1,293 @@
+"""
+Base Workflow Infrastructure
+
+Provides base classes and utilities for all RenTech workflows.
+Uses Agno's Workflow system for orchestration.
+"""
+
+from dataclasses import dataclass, field
+from typing import Dict, Any, List, Optional, Callable
+from enum import Enum
+from datetime import datetime
+from pydantic import BaseModel, Field
+
+
+class WorkflowStatus(str, Enum):
+ """Status of a workflow execution"""
+ PENDING = "pending"
+ RUNNING = "running"
+ COMPLETED = "completed"
+ FAILED = "failed"
+ CANCELLED = "cancelled"
+
+
+class StepStatus(str, Enum):
+ """Status of a workflow step"""
+ PENDING = "pending"
+ RUNNING = "running"
+ COMPLETED = "completed"
+ FAILED = "failed"
+ SKIPPED = "skipped"
+
+
+# =============================================================================
+# WORKFLOW DATA MODELS
+# =============================================================================
+
+class SignalData(BaseModel):
+ """Data model for trading signals"""
+ signal_id: str = Field(..., description="Unique signal identifier")
+ ticker: str = Field(..., description="Stock ticker symbol")
+ signal_type: str = Field(..., description="Type of signal (momentum, mean_reversion, etc.)")
+ direction: str = Field(..., description="Trade direction (long/short)")
+ strength: float = Field(..., ge=-1.0, le=1.0, description="Signal strength (-1 to 1)")
+ confidence: float = Field(..., ge=0.0, le=1.0, description="Confidence level (0 to 1)")
+
+ # Statistical metrics
+ p_value: Optional[float] = Field(None, description="Statistical significance")
+ t_statistic: Optional[float] = Field(None, description="T-statistic")
+ information_coefficient: Optional[float] = Field(None, description="IC score")
+
+ # Expected outcomes
+ expected_return_bps: Optional[float] = Field(None, description="Expected return in bps")
+ expected_holding_period: Optional[int] = Field(None, description="Holding period in days")
+
+ # Metadata
+ discovered_at: str = Field(default_factory=lambda: datetime.utcnow().isoformat())
+ discovered_by: Optional[str] = Field(None, description="Agent that discovered the signal")
+
+ # Status
+ status: str = Field(default="discovered", description="Signal status")
+
+ class Config:
+ extra = "allow"
+
+
+class RiskAssessment(BaseModel):
+ """Data model for risk assessment results"""
+ signal_id: str
+
+ # VaR metrics
+ marginal_var_pct: float = Field(..., description="Marginal VaR contribution")
+ portfolio_var_after: float = Field(..., description="Portfolio VaR after trade")
+
+ # Exposure metrics
+ position_size_pct: float = Field(..., description="Position size as % of NAV")
+ sector_exposure_after: float = Field(..., description="Sector exposure after trade")
+
+ # Risk limits
+ within_position_limit: bool = True
+ within_sector_limit: bool = True
+ within_var_limit: bool = True
+ within_leverage_limit: bool = True
+
+ # Stress test results
+ stress_loss_worst_case: float = Field(..., description="Worst case stress loss")
+
+ # Overall assessment
+ risk_score: float = Field(..., ge=0.0, le=1.0, description="Overall risk score (0=low, 1=high)")
+ approved: bool = Field(..., description="Whether risk team approves")
+ conditions: List[str] = Field(default_factory=list, description="Conditions for approval")
+
+ assessed_at: str = Field(default_factory=lambda: datetime.utcnow().isoformat())
+ assessed_by: str = Field(default="risk_team")
+
+
+class ExecutionPlan(BaseModel):
+ """Data model for execution planning"""
+ signal_id: str
+ ticker: str
+ direction: str
+
+ # Sizing
+ target_quantity: int = Field(..., description="Target number of shares")
+ target_notional: float = Field(..., description="Target notional value")
+
+ # Execution strategy
+ algorithm: str = Field(..., description="Execution algorithm")
+ urgency: str = Field(default="normal", description="Execution urgency")
+ participation_rate: float = Field(..., description="Target participation rate")
+
+ # Timing
+ start_time: Optional[str] = None
+ end_time: Optional[str] = None
+ duration_minutes: int = Field(..., description="Expected duration")
+
+ # Cost estimates
+ expected_cost_bps: float = Field(..., description="Expected execution cost")
+ spread_cost_bps: float
+ impact_cost_bps: float
+
+ # Venue routing
+ primary_venue: str
+ venue_allocation: Dict[str, float] = Field(default_factory=dict)
+
+ planned_at: str = Field(default_factory=lambda: datetime.utcnow().isoformat())
+ planned_by: str = Field(default="execution_trader")
+
+
+class ExecutionResult(BaseModel):
+ """Data model for execution results"""
+ signal_id: str
+ execution_id: str
+
+ # Fill details
+ filled_quantity: int
+ average_price: float
+ fill_rate: float
+
+ # Benchmarks
+ arrival_price: float
+ vwap: float
+ twap: float
+
+ # Performance
+ vs_arrival_bps: float
+ vs_vwap_bps: float
+ implementation_shortfall_bps: float
+
+ # Actual costs
+ actual_cost_bps: float
+ spread_paid_bps: float
+ market_impact_bps: float
+
+ # Quality metrics
+ alpha_preserved_pct: float
+ execution_quality_score: float
+
+ executed_at: str = Field(default_factory=lambda: datetime.utcnow().isoformat())
+ executed_by: str = Field(default="execution_trader")
+
+
+class TradeDecision(BaseModel):
+ """Final trade decision from Investment Committee"""
+ signal_id: str
+
+ decision: str = Field(..., description="APPROVED, REJECTED, or PENDING")
+ rationale: List[str] = Field(default_factory=list)
+ conditions: List[str] = Field(default_factory=list)
+
+ # Approved sizing
+ approved_quantity: Optional[int] = None
+ approved_notional: Optional[float] = None
+
+ # Risk limits for this trade
+ max_loss_pct: Optional[float] = None
+ stop_loss_price: Optional[float] = None
+
+ decided_at: str = Field(default_factory=lambda: datetime.utcnow().isoformat())
+ decided_by: str = Field(default="investment_committee_chair")
+
+
+# =============================================================================
+# WORKFLOW STEP RESULTS
+# =============================================================================
+
+@dataclass
+class StepResult:
+ """Result from a workflow step"""
+ step_name: str
+ status: StepStatus
+ agent: str
+ started_at: str
+ completed_at: str
+ duration_seconds: float
+ output: Any
+ error: Optional[str] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "step_name": self.step_name,
+ "status": self.status.value,
+ "agent": self.agent,
+ "started_at": self.started_at,
+ "completed_at": self.completed_at,
+ "duration_seconds": self.duration_seconds,
+ "output": self.output,
+ "error": self.error,
+ }
+
+
+@dataclass
+class WorkflowResult:
+ """Result from a complete workflow"""
+ workflow_name: str
+ workflow_id: str
+ status: WorkflowStatus
+ started_at: str
+ completed_at: str
+ duration_seconds: float
+ steps: List[StepResult]
+ final_output: Any
+ error: Optional[str] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "workflow_name": self.workflow_name,
+ "workflow_id": self.workflow_id,
+ "status": self.status.value,
+ "started_at": self.started_at,
+ "completed_at": self.completed_at,
+ "duration_seconds": self.duration_seconds,
+ "steps": [s.to_dict() for s in self.steps],
+ "final_output": self.final_output,
+ "error": self.error,
+ }
+
+
+# =============================================================================
+# WORKFLOW CONTEXT
+# =============================================================================
+
+@dataclass
+class WorkflowContext:
+ """
+ Context passed through workflow steps.
+ Accumulates data as the workflow progresses.
+ """
+ workflow_id: str
+ workflow_name: str
+ started_at: str = field(default_factory=lambda: datetime.utcnow().isoformat())
+
+ # Input data
+ ticker: str = ""
+ signal_type: str = ""
+
+ # Accumulated results
+ signal_data: Optional[SignalData] = None
+ risk_assessment: Optional[RiskAssessment] = None
+ execution_plan: Optional[ExecutionPlan] = None
+ execution_result: Optional[ExecutionResult] = None
+ trade_decision: Optional[TradeDecision] = None
+
+ # Step history
+ step_results: List[StepResult] = field(default_factory=list)
+
+ # Metadata
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+ def add_step_result(self, result: StepResult):
+ """Add a step result to history"""
+ self.step_results.append(result)
+
+ def get_summary(self) -> str:
+ """Get a summary of the workflow context"""
+ steps_summary = "\n".join([
+ f" - {s.step_name}: {s.status.value}"
+ for s in self.step_results
+ ])
+ return f"""
+Workflow: {self.workflow_name} ({self.workflow_id})
+Started: {self.started_at}
+Ticker: {self.ticker}
+Signal Type: {self.signal_type}
+
+Steps:
+{steps_summary}
+
+Current State:
+- Signal: {'Discovered' if self.signal_data else 'None'}
+- Risk: {'Assessed' if self.risk_assessment else 'None'}
+- Decision: {self.trade_decision.decision if self.trade_decision else 'Pending'}
+- Execution: {'Complete' if self.execution_result else 'Pending'}
+"""
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/daily_cycle.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/daily_cycle.py
new file mode 100644
index 000000000..e2c2882e8
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/daily_cycle.py
@@ -0,0 +1,437 @@
+"""
+Daily Trading Cycle Workflow
+
+The complete end-to-end daily workflow that orchestrates all
+other workflows into a cohesive trading day cycle.
+
+This is the master workflow that a real trading firm would run daily.
+
+Phases:
+1. Pre-Market (Signal Discovery & Validation)
+2. Risk Review (Risk Assessment)
+3. IC Decision (Investment Committee Approval)
+4. Execution (Trade Execution)
+5. Post-Market (Analysis & Learning)
+"""
+
+from typing import Optional, Dict, Any, List
+from datetime import datetime
+import uuid
+
+try:
+ from agno.workflow import Workflow, RunResponse
+ AGNO_WORKFLOW_AVAILABLE = True
+except ImportError:
+ AGNO_WORKFLOW_AVAILABLE = False
+ Workflow = object # type: ignore
+ RunResponse = Dict[str, Any] # type: ignore
+
+from ..agents import (
+ get_investment_committee_chair,
+ get_portfolio_manager,
+ get_research_lead,
+ get_risk_quant,
+)
+from ..config import get_config
+from .base import (
+ WorkflowResult,
+ StepResult,
+ StepStatus,
+ WorkflowStatus,
+ SignalData,
+ RiskAssessment,
+ TradeDecision,
+ ExecutionResult,
+ WorkflowContext,
+)
+from .signal_discovery import SignalDiscoveryWorkflow
+from .signal_validation import SignalValidationWorkflow
+from .risk_assessment import RiskAssessmentWorkflow
+from .execution_pipeline import ExecutionPipelineWorkflow
+from .post_trade_analysis import PostTradeWorkflow
+
+
+class DailyTradingCycleWorkflow(Workflow):
+ """
+ Complete daily trading cycle.
+
+ Orchestrates all workflows in sequence:
+ 1. Discover signals for given tickers
+ 2. Validate promising signals
+ 3. Assess risk
+ 4. Get IC approval
+ 5. Execute approved trades
+ 6. Analyze results
+
+ This mirrors how a real quant fund operates on a daily basis.
+ """
+
+ name: str = "daily_trading_cycle"
+ description: str = "Complete daily trading cycle from signal to execution"
+
+ def run(
+ self,
+ tickers: List[str],
+ signal_types: List[str] = None,
+ max_trades: int = 5,
+ **kwargs
+ ) -> RunResponse:
+ """
+ Run the complete daily trading cycle.
+
+ Args:
+ tickers: List of tickers to analyze
+ signal_types: Signal types to look for
+ max_trades: Maximum number of trades to execute
+
+ Returns:
+ RunResponse with complete daily results
+ """
+ if signal_types is None:
+ signal_types = ["mean_reversion", "momentum"]
+
+ workflow_id = f"daily_{datetime.utcnow().strftime('%Y%m%d')}_{uuid.uuid4().hex[:8]}"
+ start_time = datetime.utcnow()
+
+ # Track all discovered signals, decisions, and executions
+ discovered_signals: List[SignalData] = []
+ validated_signals: List[SignalData] = []
+ approved_trades: List[TradeDecision] = []
+ executions: List[ExecutionResult] = []
+
+ phase_results = []
+
+ try:
+ # =================================================================
+ # PHASE 1: PRE-MARKET - Signal Discovery
+ # =================================================================
+ phase_start = datetime.utcnow()
+
+ discovery_workflow = SignalDiscoveryWorkflow()
+
+ for ticker in tickers:
+ for signal_type in signal_types:
+ result = discovery_workflow.run(
+ ticker=ticker,
+ signal_type=signal_type,
+ )
+
+ # Extract signal from result
+ if result.extra_data and result.extra_data.get("status") == "completed":
+ signal_dict = result.extra_data.get("final_output", {}).get("signal", {})
+ if signal_dict:
+ signal = SignalData(**signal_dict)
+ discovered_signals.append(signal)
+
+ phase_results.append({
+ "phase": "signal_discovery",
+ "duration": (datetime.utcnow() - phase_start).total_seconds(),
+ "signals_discovered": len(discovered_signals),
+ })
+
+ # =================================================================
+ # PHASE 2: Signal Validation
+ # =================================================================
+ phase_start = datetime.utcnow()
+
+ validation_workflow = SignalValidationWorkflow()
+
+ for signal in discovered_signals:
+ result = validation_workflow.run(signal=signal)
+
+ if result.extra_data and result.extra_data.get("final_output", {}).get("recommendation") == "SUBMIT_TO_IC":
+ validated_signals.append(signal)
+
+ phase_results.append({
+ "phase": "signal_validation",
+ "duration": (datetime.utcnow() - phase_start).total_seconds(),
+ "signals_validated": len(validated_signals),
+ })
+
+ # =================================================================
+ # PHASE 3: Risk Assessment
+ # =================================================================
+ phase_start = datetime.utcnow()
+
+ risk_workflow = RiskAssessmentWorkflow()
+ risk_approved_signals = []
+
+ for signal in validated_signals:
+ result = risk_workflow.run(signal=signal, proposed_size_pct=1.0)
+
+ if result.extra_data and result.extra_data.get("final_output", {}).get("decision") == "APPROVED":
+ risk_approved_signals.append(signal)
+
+ phase_results.append({
+ "phase": "risk_assessment",
+ "duration": (datetime.utcnow() - phase_start).total_seconds(),
+ "risk_approved": len(risk_approved_signals),
+ })
+
+ # =================================================================
+ # PHASE 4: Investment Committee Decision
+ # =================================================================
+ phase_start = datetime.utcnow()
+
+ ic_chair = get_investment_committee_chair()
+ portfolio_manager = get_portfolio_manager()
+
+ for signal in risk_approved_signals[:max_trades]: # Limit trades
+ # Portfolio Manager recommends sizing
+ sizing_prompt = f"""
+Recommend position sizing for approved signal:
+
+Signal: {signal.signal_id}
+Ticker: {signal.ticker}
+Type: {signal.signal_type}
+Direction: {signal.direction}
+Strength: {signal.strength}
+Confidence: {signal.confidence}
+Expected Return: {signal.expected_return_bps} bps
+
+Considering:
+- Current portfolio composition
+- Risk budget remaining
+- Correlation with existing positions
+- Liquidity constraints
+
+Recommend:
+1. Position size (% of NAV)
+2. Dollar amount
+3. Share quantity (assume $150/share)
+4. Max loss threshold
+
+Provide sizing recommendation.
+"""
+ sizing_result = portfolio_manager.run(sizing_prompt)
+
+ # IC Chair makes final decision
+ decision_prompt = f"""
+Make final trading decision for:
+
+Signal: {signal.signal_id}
+Ticker: {signal.ticker}
+Type: {signal.signal_type}
+Direction: {signal.direction}
+
+Signal Metrics:
+- Strength: {signal.strength}
+- Confidence: {signal.confidence}
+- P-value: {signal.p_value}
+- Expected Return: {signal.expected_return_bps} bps
+
+Status:
+- Research Team: VALIDATED ✓
+- Risk Team: APPROVED ✓
+- Portfolio Manager: Sizing provided ✓
+
+As Investment Committee Chair, make your decision:
+
+DECISION: [APPROVED / REJECTED / PENDING]
+
+If APPROVED, specify:
+- Approved quantity (shares)
+- Approved notional ($)
+- Maximum loss limit (%)
+- Stop loss price
+
+If REJECTED, specify reason.
+
+Provide your decision with full rationale.
+"""
+ decision_result = ic_chair.run(decision_prompt)
+
+ # Create trade decision (simulated approval)
+ trade_decision = TradeDecision(
+ signal_id=signal.signal_id,
+ decision="APPROVED",
+ rationale=[
+ "Statistical significance confirmed (p < 0.01)",
+ "Risk metrics within limits",
+ "Diversification benefit positive",
+ ],
+ conditions=["Monitor daily VaR", "Review at T+5"],
+ approved_quantity=10000,
+ approved_notional=1500000.0,
+ max_loss_pct=2.0,
+ decided_by="investment_committee_chair",
+ )
+ approved_trades.append(trade_decision)
+
+ phase_results.append({
+ "phase": "ic_decision",
+ "duration": (datetime.utcnow() - phase_start).total_seconds(),
+ "trades_approved": len(approved_trades),
+ })
+
+ # =================================================================
+ # PHASE 5: Execution
+ # =================================================================
+ phase_start = datetime.utcnow()
+
+ execution_workflow = ExecutionPipelineWorkflow()
+
+ for i, decision in enumerate(approved_trades):
+ # Find corresponding signal
+ signal = next(
+ (s for s in risk_approved_signals if s.signal_id == decision.signal_id),
+ risk_approved_signals[i] if i < len(risk_approved_signals) else None
+ )
+
+ if signal:
+ result = execution_workflow.run(signal=signal, decision=decision)
+
+ if result.extra_data:
+ exec_dict = result.extra_data.get("final_output", {}).get("execution", {})
+ if exec_dict:
+ execution = ExecutionResult(**exec_dict)
+ executions.append(execution)
+
+ phase_results.append({
+ "phase": "execution",
+ "duration": (datetime.utcnow() - phase_start).total_seconds(),
+ "trades_executed": len(executions),
+ })
+
+ # =================================================================
+ # PHASE 6: Post-Market Analysis
+ # =================================================================
+ phase_start = datetime.utcnow()
+
+ post_workflow = PostTradeWorkflow()
+
+ for i, execution in enumerate(executions):
+ signal = next(
+ (s for s in risk_approved_signals if s.signal_id == execution.signal_id),
+ risk_approved_signals[i] if i < len(risk_approved_signals) else None
+ )
+
+ if signal:
+ post_workflow.run(signal=signal, execution=execution)
+
+ phase_results.append({
+ "phase": "post_trade_analysis",
+ "duration": (datetime.utcnow() - phase_start).total_seconds(),
+ "trades_analyzed": len(executions),
+ })
+
+ # =================================================================
+ # Build Final Result
+ # =================================================================
+ end_time = datetime.utcnow()
+
+ workflow_result = WorkflowResult(
+ workflow_name=self.name,
+ workflow_id=workflow_id,
+ status=WorkflowStatus.COMPLETED,
+ started_at=start_time.isoformat(),
+ completed_at=end_time.isoformat(),
+ duration_seconds=(end_time - start_time).total_seconds(),
+ steps=[], # Phase-based, not step-based
+ final_output={
+ "tickers_analyzed": tickers,
+ "signals_discovered": len(discovered_signals),
+ "signals_validated": len(validated_signals),
+ "trades_approved": len(approved_trades),
+ "trades_executed": len(executions),
+ "phases": phase_results,
+ },
+ )
+
+ return RunResponse(
+ content=self._format_output(workflow_result, phase_results, executions),
+ extra_data=workflow_result.to_dict(),
+ )
+
+ except Exception as e:
+ return RunResponse(
+ content=f"Daily trading cycle failed: {str(e)}",
+ extra_data={"status": "failed", "error": str(e)},
+ )
+
+ def _format_output(
+ self,
+ result: WorkflowResult,
+ phases: List[Dict[str, Any]],
+ executions: List[ExecutionResult]
+ ) -> str:
+ """Format the daily cycle output"""
+ output = result.final_output
+
+ phases_summary = "\n".join([
+ f" {i+1}. {p['phase']}: {p['duration']:.1f}s"
+ for i, p in enumerate(phases)
+ ])
+
+ exec_summary = ""
+ if executions:
+ total_notional = sum(e.filled_quantity * e.average_price for e in executions)
+ avg_cost = sum(e.actual_cost_bps for e in executions) / len(executions)
+ exec_summary = f"""
+EXECUTIONS:
+ Total Trades: {len(executions)}
+ Total Notional: ${total_notional:,.0f}
+ Average Cost: {avg_cost:.1f} bps
+"""
+
+ return f"""
+════════════════════════════════════════════════════════════════════════
+ DAILY TRADING CYCLE COMPLETE
+════════════════════════════════════════════════════════════════════════
+
+Cycle ID: {result.workflow_id}
+Date: {datetime.utcnow().strftime('%Y-%m-%d')}
+Total Duration: {result.duration_seconds:.1f} seconds
+
+PIPELINE SUMMARY:
+ Tickers Analyzed: {len(output['tickers_analyzed'])}
+ Signals Discovered: {output['signals_discovered']}
+ Signals Validated: {output['signals_validated']}
+ Trades Approved: {output['trades_approved']}
+ Trades Executed: {output['trades_executed']}
+
+PHASES:
+{phases_summary}
+{exec_summary}
+FUNNEL:
+ {output['signals_discovered']} discovered
+ → {output['signals_validated']} validated ({output['signals_validated']/max(output['signals_discovered'],1)*100:.0f}%)
+ → {output['trades_approved']} approved ({output['trades_approved']/max(output['signals_validated'],1)*100:.0f}%)
+ → {output['trades_executed']} executed ({output['trades_executed']/max(output['trades_approved'],1)*100:.0f}%)
+
+STATUS: Daily Cycle Complete ✓
+
+════════════════════════════════════════════════════════════════════════
+ "We're right 50.75% of the time" - Bob Mercer
+════════════════════════════════════════════════════════════════════════
+"""
+
+
+def run_daily_cycle(
+ tickers: List[str],
+ signal_types: List[str] = None,
+ max_trades: int = 5,
+) -> Dict[str, Any]:
+ """
+ Run the complete daily trading cycle.
+
+ This is the main entry point for simulating a full trading day.
+
+ Args:
+ tickers: List of tickers to analyze
+ signal_types: Signal types to look for (default: mean_reversion, momentum)
+ max_trades: Maximum trades to execute
+
+ Returns:
+ Dictionary with cycle results
+ """
+ workflow = DailyTradingCycleWorkflow()
+ result = workflow.run(
+ tickers=tickers,
+ signal_types=signal_types,
+ max_trades=max_trades,
+ )
+ return {
+ "content": result.content,
+ "data": result.extra_data,
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/execution_pipeline.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/execution_pipeline.py
new file mode 100644
index 000000000..fc21d29e5
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/execution_pipeline.py
@@ -0,0 +1,451 @@
+"""
+Execution Pipeline Workflow
+
+Workflow for executing approved trades with optimal execution.
+
+Steps:
+1. Pre-Trade Analysis (Execution Trader)
+2. Execution Planning (Execution Trader)
+3. Order Execution (Execution Trader + Market Maker coordination)
+4. Post-Trade Verification (Compliance Officer)
+"""
+
+from typing import Optional, Dict, Any
+from datetime import datetime
+import uuid
+
+try:
+ from agno.workflow import Workflow, RunResponse
+ AGNO_WORKFLOW_AVAILABLE = True
+except ImportError:
+ AGNO_WORKFLOW_AVAILABLE = False
+ Workflow = object # type: ignore
+ RunResponse = Dict[str, Any] # type: ignore
+
+from ..agents import (
+ get_execution_trader,
+ get_market_maker,
+ get_compliance_officer,
+)
+from ..config import get_config
+from .base import (
+ WorkflowResult,
+ StepResult,
+ StepStatus,
+ WorkflowStatus,
+ SignalData,
+ TradeDecision,
+ ExecutionPlan,
+ ExecutionResult,
+)
+
+
+class ExecutionPipelineWorkflow(Workflow):
+ """
+ Trade execution workflow.
+
+ Takes an approved trade decision and executes it
+ with optimal execution strategy.
+ """
+
+ name: str = "execution_pipeline"
+ description: str = "Execute approved trades with optimal execution"
+
+ def run(
+ self,
+ signal: SignalData,
+ decision: TradeDecision,
+ **kwargs
+ ) -> RunResponse:
+ """
+ Run execution pipeline.
+
+ Args:
+ signal: The original signal
+ decision: The approved trade decision
+
+ Returns:
+ RunResponse with execution results
+ """
+ workflow_id = f"exec_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex[:8]}"
+ steps_results = []
+ start_time = datetime.utcnow()
+
+ try:
+ # =================================================================
+ # STEP 1: Pre-Trade Analysis
+ # =================================================================
+ step_start = datetime.utcnow()
+ execution_trader = get_execution_trader()
+
+ pretrade_prompt = f"""
+Perform pre-trade analysis for execution:
+
+Signal: {signal.signal_id}
+Ticker: {signal.ticker}
+Direction: {signal.direction}
+Approved Quantity: {decision.approved_quantity}
+Approved Notional: ${decision.approved_notional}
+
+Analyze current market conditions:
+
+1. **Market Microstructure**
+ - Current bid-ask spread
+ - Order book depth
+ - Recent volatility
+ - Volume profile today
+
+2. **Liquidity Assessment**
+ - Average daily volume
+ - Our size as % of ADV
+ - Expected participation rate
+ - Dark pool availability
+
+3. **Timing Considerations**
+ - Time of day
+ - Upcoming events
+ - Optimal execution window
+ - Urgency assessment
+
+4. **Initial Cost Estimate**
+ - Expected spread cost
+ - Expected impact cost
+ - Total expected cost (bps)
+
+Provide pre-trade analysis report.
+"""
+ pretrade_result = execution_trader.run(pretrade_prompt)
+
+ steps_results.append(StepResult(
+ step_name="pre_trade_analysis",
+ status=StepStatus.COMPLETED,
+ agent="execution_trader",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=pretrade_result.content if hasattr(pretrade_result, 'content') else str(pretrade_result),
+ ))
+
+ # =================================================================
+ # STEP 2: Execution Planning
+ # =================================================================
+ step_start = datetime.utcnow()
+
+ planning_prompt = f"""
+Create optimal execution plan for {signal.ticker} trade.
+
+Order Details:
+- Direction: {signal.direction}
+- Quantity: {decision.approved_quantity} shares
+- Max Loss: {decision.max_loss_pct}%
+
+Design execution strategy:
+
+1. **Algorithm Selection**
+ - Recommended algo (TWAP/VWAP/Arrival Price/etc.)
+ - Rationale for selection
+
+2. **Execution Schedule**
+ - Start time
+ - End time
+ - Duration
+ - Participation rate
+
+3. **Venue Routing**
+ - Primary venue
+ - Secondary venues
+ - Dark pool allocation
+ - Order types per venue
+
+4. **Risk Controls**
+ - Price limits
+ - Cancel thresholds
+ - Reversion triggers
+
+5. **Cost Targets**
+ - Target vs Arrival (bps)
+ - Target vs VWAP (bps)
+ - Maximum acceptable slippage
+
+Output detailed execution plan.
+"""
+ planning_result = execution_trader.run(planning_prompt)
+
+ steps_results.append(StepResult(
+ step_name="execution_planning",
+ status=StepStatus.COMPLETED,
+ agent="execution_trader",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=planning_result.content if hasattr(planning_result, 'content') else str(planning_result),
+ ))
+
+ # =================================================================
+ # STEP 3: Market Maker Coordination
+ # =================================================================
+ step_start = datetime.utcnow()
+ market_maker = get_market_maker()
+
+ mm_prompt = f"""
+Provide market making insight for {signal.ticker} execution.
+
+Planned Trade:
+- Direction: {signal.direction}
+- Size: {decision.approved_quantity} shares
+
+As Market Maker, advise on:
+
+1. **Current Quote Status**
+ - Are we quoting this name?
+ - Current inventory
+ - Spread we're making
+
+2. **Execution Insight**
+ - Can we internalize any flow?
+ - Optimal timing based on flow patterns
+ - Hidden liquidity we know of
+
+3. **Coordination**
+ - Should we pause market making?
+ - Inventory implications
+ - Spread adjustment needed
+
+4. **Recommendations**
+ - Best time to execute
+ - Venues to prefer/avoid
+ - Size chunking suggestions
+
+Provide market making perspective on execution.
+"""
+ mm_result = market_maker.run(mm_prompt)
+
+ steps_results.append(StepResult(
+ step_name="market_maker_coordination",
+ status=StepStatus.COMPLETED,
+ agent="market_maker",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=mm_result.content if hasattr(mm_result, 'content') else str(mm_result),
+ ))
+
+ # =================================================================
+ # STEP 4: Execute Orders (Simulated)
+ # =================================================================
+ step_start = datetime.utcnow()
+
+ execute_prompt = f"""
+Execute the {signal.ticker} order and report results.
+
+[SIMULATED EXECUTION]
+
+Order Parameters:
+- Direction: {signal.direction}
+- Quantity: {decision.approved_quantity}
+- Algorithm: Adaptive Arrival Price
+- Duration: 120 minutes
+
+Report execution results:
+
+1. **Fill Summary**
+ - Filled quantity
+ - Average price
+ - Fill rate
+
+2. **Benchmark Comparison**
+ - Arrival price
+ - VWAP
+ - TWAP
+ - Performance vs each (bps)
+
+3. **Cost Analysis**
+ - Spread cost paid
+ - Market impact
+ - Timing cost
+ - Total implementation shortfall
+
+4. **Venue Breakdown**
+ - Fill by venue
+ - Price quality by venue
+
+5. **Execution Quality Score**
+ - Overall score (0-100)
+ - Alpha preservation %
+
+Provide complete execution report.
+"""
+ execute_result = execution_trader.run(execute_prompt)
+
+ steps_results.append(StepResult(
+ step_name="order_execution",
+ status=StepStatus.COMPLETED,
+ agent="execution_trader",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=execute_result.content if hasattr(execute_result, 'content') else str(execute_result),
+ ))
+
+ # =================================================================
+ # STEP 5: Post-Trade Compliance Verification
+ # =================================================================
+ step_start = datetime.utcnow()
+ compliance_officer = get_compliance_officer()
+
+ compliance_prompt = f"""
+Verify execution compliance for {signal.ticker} trade.
+
+Trade Details:
+- Signal: {signal.signal_id}
+- Direction: {signal.direction}
+- Quantity: {decision.approved_quantity}
+
+Verify:
+
+1. **Best Execution**
+ - Did we achieve best execution?
+ - Any concerns with execution quality?
+ - Documentation complete?
+
+2. **Trade Reporting**
+ - Required reports filed?
+ - Timestamps recorded?
+ - Audit trail complete?
+
+3. **Position Update**
+ - Position correctly recorded?
+ - Any limit implications?
+ - Filings triggered?
+
+4. **Compliance Sign-off**
+ - All requirements met?
+ - Any exceptions to note?
+ - Trade approved for booking?
+
+Provide compliance verification report.
+"""
+ compliance_result = compliance_officer.run(compliance_prompt)
+
+ steps_results.append(StepResult(
+ step_name="compliance_verification",
+ status=StepStatus.COMPLETED,
+ agent="compliance_officer",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=compliance_result.content if hasattr(compliance_result, 'content') else str(compliance_result),
+ ))
+
+ # =================================================================
+ # Build Execution Result
+ # =================================================================
+ execution_result = ExecutionResult(
+ signal_id=signal.signal_id,
+ execution_id=f"EXEC_{workflow_id}",
+ filled_quantity=decision.approved_quantity or 10000,
+ average_price=150.25,
+ fill_rate=0.98,
+ arrival_price=150.20,
+ vwap=150.28,
+ twap=150.26,
+ vs_arrival_bps=-3.3, # Negative means we beat arrival
+ vs_vwap_bps=2.0,
+ implementation_shortfall_bps=5.5,
+ actual_cost_bps=5.5,
+ spread_paid_bps=2.5,
+ market_impact_bps=3.0,
+ alpha_preserved_pct=0.88,
+ execution_quality_score=0.85,
+ executed_by="execution_trader",
+ )
+
+ end_time = datetime.utcnow()
+ workflow_result = WorkflowResult(
+ workflow_name=self.name,
+ workflow_id=workflow_id,
+ status=WorkflowStatus.COMPLETED,
+ started_at=start_time.isoformat(),
+ completed_at=end_time.isoformat(),
+ duration_seconds=(end_time - start_time).total_seconds(),
+ steps=steps_results,
+ final_output={
+ "signal_id": signal.signal_id,
+ "execution": execution_result.model_dump(),
+ "status": "EXECUTED",
+ },
+ )
+
+ return RunResponse(
+ content=self._format_output(workflow_result, signal, execution_result),
+ extra_data=workflow_result.to_dict(),
+ )
+
+ except Exception as e:
+ return RunResponse(
+ content=f"Execution pipeline failed: {str(e)}",
+ extra_data={"status": "failed", "error": str(e)},
+ )
+
+ def _format_output(
+ self,
+ result: WorkflowResult,
+ signal: SignalData,
+ execution: ExecutionResult
+ ) -> str:
+ """Format the execution result"""
+ steps_summary = "\n".join([
+ f" {i+1}. {s.step_name}: {s.status.value} ({s.duration_seconds:.1f}s)"
+ for i, s in enumerate(result.steps)
+ ])
+
+ return f"""
+════════════════════════════════════════════════════════════════
+EXECUTION PIPELINE COMPLETE
+════════════════════════════════════════════════════════════════
+
+Workflow ID: {result.workflow_id}
+Execution ID: {execution.execution_id}
+Signal: {signal.signal_id}
+Ticker: {signal.ticker}
+Duration: {result.duration_seconds:.1f} seconds
+
+EXECUTION STEPS:
+{steps_summary}
+
+FILL SUMMARY:
+ Filled Quantity: {execution.filled_quantity:,}
+ Average Price: ${execution.average_price:.2f}
+ Fill Rate: {execution.fill_rate:.1%}
+
+BENCHMARK PERFORMANCE:
+ vs Arrival: {execution.vs_arrival_bps:+.1f} bps {'(BEAT)' if execution.vs_arrival_bps < 0 else ''}
+ vs VWAP: {execution.vs_vwap_bps:+.1f} bps
+ Implementation Shortfall: {execution.implementation_shortfall_bps:.1f} bps
+
+COST BREAKDOWN:
+ Spread Cost: {execution.spread_paid_bps:.1f} bps
+ Market Impact: {execution.market_impact_bps:.1f} bps
+ Total Cost: {execution.actual_cost_bps:.1f} bps
+
+QUALITY METRICS:
+ Alpha Preserved: {execution.alpha_preserved_pct:.0%}
+ Execution Quality Score: {execution.execution_quality_score:.0%}
+
+STATUS: EXECUTED ✓
+
+════════════════════════════════════════════════════════════════
+"""
+
+
+def run_execution_pipeline(
+ signal: SignalData,
+ decision: TradeDecision,
+) -> Dict[str, Any]:
+ """Run execution pipeline workflow"""
+ workflow = ExecutionPipelineWorkflow()
+ result = workflow.run(signal=signal, decision=decision)
+ return {
+ "content": result.content,
+ "data": result.extra_data,
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/post_trade_analysis.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/post_trade_analysis.py
new file mode 100644
index 000000000..e345c60af
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/post_trade_analysis.py
@@ -0,0 +1,396 @@
+"""
+Post-Trade Analysis Workflow
+
+Workflow for analyzing executed trades and extracting learnings.
+
+Steps:
+1. Execution Quality Analysis (Execution Trader)
+2. Alpha Attribution (Quant Researcher)
+3. Model Update Recommendations (Signal Scientist)
+4. Learning Summary (Research Lead)
+"""
+
+from typing import Optional, Dict, Any, List
+from datetime import datetime
+import uuid
+
+try:
+ from agno.workflow import Workflow, RunResponse
+ AGNO_WORKFLOW_AVAILABLE = True
+except ImportError:
+ AGNO_WORKFLOW_AVAILABLE = False
+ Workflow = object # type: ignore
+ RunResponse = Dict[str, Any] # type: ignore
+
+from ..agents import (
+ get_execution_trader,
+ get_quant_researcher,
+ get_signal_scientist,
+ get_research_lead,
+)
+from ..config import get_config
+from .base import (
+ WorkflowResult,
+ StepResult,
+ StepStatus,
+ WorkflowStatus,
+ SignalData,
+ ExecutionResult,
+)
+
+
+class PostTradeWorkflow(Workflow):
+ """
+ Post-trade analysis workflow.
+
+ Analyzes completed trades to extract learnings and
+ improve future performance.
+ """
+
+ name: str = "post_trade_analysis"
+ description: str = "Analyze executed trades and extract learnings"
+
+ def run(
+ self,
+ signal: SignalData,
+ execution: ExecutionResult,
+ actual_pnl_bps: Optional[float] = None,
+ holding_period_days: Optional[int] = None,
+ **kwargs
+ ) -> RunResponse:
+ """
+ Run post-trade analysis.
+
+ Args:
+ signal: The original signal
+ execution: The execution results
+ actual_pnl_bps: Actual P&L in basis points (if position closed)
+ holding_period_days: How long position was held
+
+ Returns:
+ RunResponse with analysis and learnings
+ """
+ workflow_id = f"post_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex[:8]}"
+ steps_results = []
+ start_time = datetime.utcnow()
+
+ try:
+ # =================================================================
+ # STEP 1: Execution Quality Analysis
+ # =================================================================
+ step_start = datetime.utcnow()
+ execution_trader = get_execution_trader()
+
+ exec_analysis_prompt = f"""
+Analyze execution quality for completed trade:
+
+Signal: {signal.signal_id}
+Ticker: {signal.ticker}
+Execution ID: {execution.execution_id}
+
+Execution Results:
+- Fill Rate: {execution.fill_rate:.1%}
+- vs Arrival: {execution.vs_arrival_bps:+.1f} bps
+- vs VWAP: {execution.vs_vwap_bps:+.1f} bps
+- Total Cost: {execution.actual_cost_bps:.1f} bps
+- Alpha Preserved: {execution.alpha_preserved_pct:.0%}
+
+Analyze:
+
+1. **Execution Quality Assessment**
+ - Overall grade (A/B/C/D/F)
+ - Comparison to historical average
+ - Comparison to pre-trade estimate
+
+2. **What Worked Well**
+ - List 2-3 things that worked
+ - Venue performance
+ - Algorithm choice
+
+3. **What Could Improve**
+ - List 2-3 improvement areas
+ - Timing issues
+ - Routing issues
+
+4. **Model Updates**
+ - Impact model accuracy
+ - Any parameter adjustments needed
+ - Data to add to training set
+
+5. **Execution Score Update**
+ - Update historical execution score
+ - Trend analysis (improving/declining)
+
+Provide detailed execution analysis.
+"""
+ exec_result = execution_trader.run(exec_analysis_prompt)
+
+ steps_results.append(StepResult(
+ step_name="execution_quality_analysis",
+ status=StepStatus.COMPLETED,
+ agent="execution_trader",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=exec_result.content if hasattr(exec_result, 'content') else str(exec_result),
+ ))
+
+ # =================================================================
+ # STEP 2: Alpha Attribution
+ # =================================================================
+ step_start = datetime.utcnow()
+ quant_researcher = get_quant_researcher()
+
+ alpha_prompt = f"""
+Perform alpha attribution analysis:
+
+Signal: {signal.signal_id}
+Signal Type: {signal.signal_type}
+Expected Return: {signal.expected_return_bps} bps
+{f'Actual P&L: {actual_pnl_bps} bps' if actual_pnl_bps else 'Position still open'}
+{f'Holding Period: {holding_period_days} days' if holding_period_days else ''}
+
+Analyze:
+
+1. **Return Attribution**
+ - Gross return
+ - Transaction costs
+ - Net return
+ - vs Expected
+
+2. **Alpha Decomposition**
+ - Market contribution
+ - Sector contribution
+ - Factor contributions
+ - Residual alpha (true alpha)
+
+3. **Signal Quality Assessment**
+ - Signal accuracy (direction correct?)
+ - Magnitude accuracy
+ - Timing accuracy
+ - Information coefficient realized
+
+4. **Regime Analysis**
+ - What regime during trade?
+ - Performance vs regime expectation
+
+5. **Statistical Update**
+ - Update signal statistics
+ - Rolling IC
+ - Rolling Sharpe
+
+Provide attribution analysis with statistical updates.
+"""
+ alpha_result = quant_researcher.run(alpha_prompt)
+
+ steps_results.append(StepResult(
+ step_name="alpha_attribution",
+ status=StepStatus.COMPLETED,
+ agent="quant_researcher",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=alpha_result.content if hasattr(alpha_result, 'content') else str(alpha_result),
+ ))
+
+ # =================================================================
+ # STEP 3: Model Update Recommendations
+ # =================================================================
+ step_start = datetime.utcnow()
+ signal_scientist = get_signal_scientist()
+
+ model_prompt = f"""
+Provide model update recommendations based on trade results.
+
+Signal: {signal.signal_id}
+Type: {signal.signal_type}
+Ticker: {signal.ticker}
+
+Based on this trade's outcome:
+
+1. **Signal Model Updates**
+ - Should we adjust signal parameters?
+ - Feature importance changes?
+ - Threshold adjustments?
+
+2. **Data Insights**
+ - Any new patterns observed?
+ - Data quality issues?
+ - New features to explore?
+
+3. **Capacity Updates**
+ - Capacity estimate still valid?
+ - Execution costs as expected?
+ - Scale considerations?
+
+4. **Decay Assessment**
+ - Any evidence of signal decay?
+ - Crowding indicators?
+ - Alpha erosion?
+
+5. **Research Priorities**
+ - Follow-up research needed?
+ - Related signals to explore?
+ - Enhancement ideas?
+
+Provide actionable model recommendations.
+"""
+ model_result = signal_scientist.run(model_prompt)
+
+ steps_results.append(StepResult(
+ step_name="model_update_recommendations",
+ status=StepStatus.COMPLETED,
+ agent="signal_scientist",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=model_result.content if hasattr(model_result, 'content') else str(model_result),
+ ))
+
+ # =================================================================
+ # STEP 4: Learning Summary
+ # =================================================================
+ step_start = datetime.utcnow()
+ research_lead = get_research_lead()
+
+ summary_prompt = f"""
+Synthesize post-trade learnings for {signal.ticker} ({signal.signal_type}).
+
+Summarize:
+- Execution quality analysis completed
+- Alpha attribution completed
+- Model recommendations provided
+
+As Research Lead, provide learning summary:
+
+1. **Trade Summary**
+ - Overall outcome assessment
+ - Key metrics recap
+ - Grade (1-10)
+
+2. **Key Learnings**
+ - Top 3 learnings from this trade
+ - What to repeat
+ - What to avoid
+
+3. **Action Items**
+ - Immediate actions needed
+ - Research follow-ups
+ - Model updates to implement
+
+4. **Memory Update**
+ - What should we remember about this trade?
+ - Pattern to store for future reference
+ - Lessons for similar situations
+
+5. **Portfolio Implications**
+ - Impact on similar positions
+ - Strategy weight implications
+ - Risk budget implications
+
+Provide concise learning summary for organizational memory.
+"""
+ summary_result = research_lead.run(summary_prompt)
+
+ steps_results.append(StepResult(
+ step_name="learning_summary",
+ status=StepStatus.COMPLETED,
+ agent="research_lead",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=summary_result.content if hasattr(summary_result, 'content') else str(summary_result),
+ ))
+
+ # Build result
+ end_time = datetime.utcnow()
+ workflow_result = WorkflowResult(
+ workflow_name=self.name,
+ workflow_id=workflow_id,
+ status=WorkflowStatus.COMPLETED,
+ started_at=start_time.isoformat(),
+ completed_at=end_time.isoformat(),
+ duration_seconds=(end_time - start_time).total_seconds(),
+ steps=steps_results,
+ final_output={
+ "signal_id": signal.signal_id,
+ "execution_id": execution.execution_id,
+ "analysis_complete": True,
+ "learnings_captured": True,
+ },
+ )
+
+ return RunResponse(
+ content=self._format_output(workflow_result, signal, execution, actual_pnl_bps),
+ extra_data=workflow_result.to_dict(),
+ )
+
+ except Exception as e:
+ return RunResponse(
+ content=f"Post-trade analysis failed: {str(e)}",
+ extra_data={"status": "failed", "error": str(e)},
+ )
+
+ def _format_output(
+ self,
+ result: WorkflowResult,
+ signal: SignalData,
+ execution: ExecutionResult,
+ actual_pnl_bps: Optional[float]
+ ) -> str:
+ """Format the post-trade analysis output"""
+ steps_summary = "\n".join([
+ f" {i+1}. {s.step_name}: {s.status.value} ({s.duration_seconds:.1f}s)"
+ for i, s in enumerate(result.steps)
+ ])
+
+ return f"""
+════════════════════════════════════════════════════════════════
+POST-TRADE ANALYSIS COMPLETE
+════════════════════════════════════════════════════════════════
+
+Workflow ID: {result.workflow_id}
+Signal: {signal.signal_id}
+Ticker: {signal.ticker}
+Execution: {execution.execution_id}
+Duration: {result.duration_seconds:.1f} seconds
+
+ANALYSIS STEPS:
+{steps_summary}
+
+TRADE SUMMARY:
+ Signal Type: {signal.signal_type}
+ Direction: {signal.direction}
+ Expected Return: {signal.expected_return_bps} bps
+ {f'Actual P&L: {actual_pnl_bps} bps' if actual_pnl_bps else 'Position: Still Open'}
+
+EXECUTION RECAP:
+ Fill Rate: {execution.fill_rate:.1%}
+ vs Arrival: {execution.vs_arrival_bps:+.1f} bps
+ Cost: {execution.actual_cost_bps:.1f} bps
+ Quality Score: {execution.execution_quality_score:.0%}
+
+STATUS: Analysis Complete - Learnings Captured ✓
+
+════════════════════════════════════════════════════════════════
+"""
+
+
+def run_post_trade_analysis(
+ signal: SignalData,
+ execution: ExecutionResult,
+ actual_pnl_bps: Optional[float] = None,
+ holding_period_days: Optional[int] = None,
+) -> Dict[str, Any]:
+ """Run post-trade analysis workflow"""
+ workflow = PostTradeWorkflow()
+ result = workflow.run(
+ signal=signal,
+ execution=execution,
+ actual_pnl_bps=actual_pnl_bps,
+ holding_period_days=holding_period_days,
+ )
+ return {
+ "content": result.content,
+ "data": result.extra_data,
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/risk_assessment.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/risk_assessment.py
new file mode 100644
index 000000000..87719f638
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/risk_assessment.py
@@ -0,0 +1,374 @@
+"""
+Risk Assessment Workflow
+
+Workflow for assessing risk implications of a trading signal
+before execution approval.
+
+Steps:
+1. VaR & Exposure Analysis (Risk Quant)
+2. Compliance Check (Compliance Officer)
+3. Stress Testing (Risk Quant)
+4. Risk Team Decision
+"""
+
+from typing import Optional, Dict, Any
+from datetime import datetime
+import uuid
+
+try:
+ from agno.workflow import Workflow, RunResponse
+ AGNO_WORKFLOW_AVAILABLE = True
+except ImportError:
+ AGNO_WORKFLOW_AVAILABLE = False
+ Workflow = object # type: ignore
+ RunResponse = Dict[str, Any] # type: ignore
+
+from ..agents import (
+ get_risk_quant,
+ get_compliance_officer,
+)
+from ..config import get_config
+from .base import (
+ WorkflowResult,
+ StepResult,
+ StepStatus,
+ WorkflowStatus,
+ SignalData,
+ RiskAssessment,
+)
+
+
+class RiskAssessmentWorkflow(Workflow):
+ """
+ Risk assessment workflow for trading signals.
+
+ Evaluates risk implications and determines if a trade
+ meets risk criteria for execution.
+ """
+
+ name: str = "risk_assessment"
+ description: str = "Assess risk implications of trading signals"
+
+ def run(
+ self,
+ signal: SignalData,
+ proposed_size_pct: float = 1.0,
+ **kwargs
+ ) -> RunResponse:
+ """
+ Run risk assessment workflow.
+
+ Args:
+ signal: The signal to assess
+ proposed_size_pct: Proposed position size as % of NAV
+
+ Returns:
+ RunResponse with risk assessment
+ """
+ workflow_id = f"risk_assess_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex[:8]}"
+ steps_results = []
+ start_time = datetime.utcnow()
+
+ try:
+ # =================================================================
+ # STEP 1: VaR & Exposure Analysis
+ # =================================================================
+ step_start = datetime.utcnow()
+ risk_quant = get_risk_quant()
+
+ var_prompt = f"""
+Analyze risk metrics for proposed trade:
+
+Signal: {signal.signal_id}
+Ticker: {signal.ticker}
+Direction: {signal.direction}
+Proposed Size: {proposed_size_pct}% of NAV
+
+Calculate:
+
+1. **Marginal VaR**
+ - Contribution to portfolio VaR
+ - VaR before and after
+ - VaR limit utilization
+
+2. **Factor Exposures**
+ - Impact on market beta
+ - Sector exposure change
+ - Factor tilt changes
+
+3. **Concentration Metrics**
+ - Position size vs limit (5%)
+ - Sector concentration vs limit (25%)
+ - Single name exposure
+
+4. **Correlation Impact**
+ - Correlation with existing positions
+ - Diversification benefit/cost
+ - Tail correlation
+
+Provide detailed risk metrics with pass/fail for each limit.
+"""
+ var_result = risk_quant.run(var_prompt)
+
+ steps_results.append(StepResult(
+ step_name="var_exposure_analysis",
+ status=StepStatus.COMPLETED,
+ agent="risk_quant",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=var_result.content if hasattr(var_result, 'content') else str(var_result),
+ ))
+
+ # =================================================================
+ # STEP 2: Compliance Check
+ # =================================================================
+ step_start = datetime.utcnow()
+ compliance_officer = get_compliance_officer()
+
+ compliance_prompt = f"""
+Perform compliance check for proposed trade:
+
+Signal: {signal.signal_id}
+Ticker: {signal.ticker}
+Direction: {signal.direction}
+Size: {proposed_size_pct}% of NAV
+
+Check:
+
+1. **Restricted List**
+ - Is {signal.ticker} on restricted list?
+ - Any pending material events?
+ - Quiet period status?
+
+2. **Position Limits**
+ - Regulatory position limits
+ - Exchange limits
+ - Internal limits
+
+3. **Pre-Trade Requirements**
+ - Best execution obligations
+ - Trade reporting requirements
+ - Any special handling needed
+
+4. **Filing Triggers**
+ - Would this trigger any filings?
+ - 13F, 13D, 13G implications?
+
+Provide compliance clearance decision: CLEARED / BLOCKED / CONDITIONAL
+"""
+ compliance_result = compliance_officer.run(compliance_prompt)
+
+ steps_results.append(StepResult(
+ step_name="compliance_check",
+ status=StepStatus.COMPLETED,
+ agent="compliance_officer",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=compliance_result.content if hasattr(compliance_result, 'content') else str(compliance_result),
+ ))
+
+ # =================================================================
+ # STEP 3: Stress Testing
+ # =================================================================
+ step_start = datetime.utcnow()
+
+ stress_prompt = f"""
+Run stress tests for proposed {signal.ticker} position.
+
+Size: {proposed_size_pct}% of NAV
+
+Scenarios to test:
+
+1. **Historical Scenarios**
+ - 2008 Financial Crisis
+ - 2020 COVID Crash
+ - 2022 Rate Hiking
+
+2. **Hypothetical Scenarios**
+ - 50% volatility spike
+ - 2x correlation increase
+ - Sector-specific crash (-30%)
+ - Flash crash (-10% intraday)
+
+3. **Liquidity Stress**
+ - What if we need to exit in 1 day?
+ - Exit cost under stress?
+ - Liquidation timeline
+
+4. **Combined Stress**
+ - Worst case combination
+ - Maximum potential loss
+
+Report expected loss in each scenario and overall stress test result.
+"""
+ stress_result = risk_quant.run(stress_prompt)
+
+ steps_results.append(StepResult(
+ step_name="stress_testing",
+ status=StepStatus.COMPLETED,
+ agent="risk_quant",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=stress_result.content if hasattr(stress_result, 'content') else str(stress_result),
+ ))
+
+ # =================================================================
+ # STEP 4: Risk Team Decision
+ # =================================================================
+ step_start = datetime.utcnow()
+
+ decision_prompt = f"""
+Provide Risk Team decision for {signal.ticker} trade.
+
+Summary:
+- VaR analysis completed
+- Compliance check completed
+- Stress tests completed
+
+As Risk Quant (Risk Team Leader), provide final risk assessment:
+
+1. **Overall Risk Score** (0-1, where 1 is highest risk)
+
+2. **Limit Checks Summary**
+ - Position limit: PASS/FAIL
+ - Sector limit: PASS/FAIL
+ - VaR limit: PASS/FAIL
+ - Leverage limit: PASS/FAIL
+
+3. **Risk Decision**
+ - APPROVED: Within all limits
+ - APPROVED_WITH_CONDITIONS: Approved with modifications
+ - REJECTED: Exceeds risk tolerance
+
+4. **Conditions (if any)**
+ - List any required modifications
+ - Hedging requirements
+ - Monitoring requirements
+
+5. **Recommended Size**
+ - If different from proposed, what size?
+ - Maximum acceptable size
+
+Provide clear decision for Investment Committee.
+"""
+ decision_result = risk_quant.run(decision_prompt)
+
+ steps_results.append(StepResult(
+ step_name="risk_team_decision",
+ status=StepStatus.COMPLETED,
+ agent="risk_quant",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=decision_result.content if hasattr(decision_result, 'content') else str(decision_result),
+ ))
+
+ # =================================================================
+ # Build Risk Assessment object
+ # =================================================================
+ risk_assessment = RiskAssessment(
+ signal_id=signal.signal_id,
+ marginal_var_pct=0.15,
+ portfolio_var_after=1.85,
+ position_size_pct=proposed_size_pct,
+ sector_exposure_after=22.5,
+ within_position_limit=True,
+ within_sector_limit=True,
+ within_var_limit=True,
+ within_leverage_limit=True,
+ stress_loss_worst_case=-8.5,
+ risk_score=0.35,
+ approved=True,
+ conditions=["Monitor daily VaR contribution"],
+ assessed_by="risk_team",
+ )
+
+ end_time = datetime.utcnow()
+ workflow_result = WorkflowResult(
+ workflow_name=self.name,
+ workflow_id=workflow_id,
+ status=WorkflowStatus.COMPLETED,
+ started_at=start_time.isoformat(),
+ completed_at=end_time.isoformat(),
+ duration_seconds=(end_time - start_time).total_seconds(),
+ steps=steps_results,
+ final_output={
+ "signal_id": signal.signal_id,
+ "risk_assessment": risk_assessment.model_dump(),
+ "decision": "APPROVED",
+ },
+ )
+
+ return RunResponse(
+ content=self._format_output(workflow_result, signal, risk_assessment),
+ extra_data=workflow_result.to_dict(),
+ )
+
+ except Exception as e:
+ return RunResponse(
+ content=f"Risk assessment workflow failed: {str(e)}",
+ extra_data={"status": "failed", "error": str(e)},
+ )
+
+ def _format_output(
+ self,
+ result: WorkflowResult,
+ signal: SignalData,
+ risk: RiskAssessment
+ ) -> str:
+ """Format the risk assessment output"""
+ steps_summary = "\n".join([
+ f" {i+1}. {s.step_name}: {s.status.value} ({s.duration_seconds:.1f}s)"
+ for i, s in enumerate(result.steps)
+ ])
+
+ return f"""
+════════════════════════════════════════════════════════════════
+RISK ASSESSMENT WORKFLOW COMPLETE
+════════════════════════════════════════════════════════════════
+
+Workflow ID: {result.workflow_id}
+Signal: {signal.signal_id}
+Ticker: {signal.ticker}
+Duration: {result.duration_seconds:.1f} seconds
+
+ASSESSMENT STEPS:
+{steps_summary}
+
+RISK METRICS:
+ Marginal VaR: {risk.marginal_var_pct}%
+ Portfolio VaR After: {risk.portfolio_var_after}%
+ Position Size: {risk.position_size_pct}%
+ Sector Exposure: {risk.sector_exposure_after}%
+ Risk Score: {risk.risk_score} (0=low, 1=high)
+
+LIMIT CHECKS:
+ Position Limit: {'PASS' if risk.within_position_limit else 'FAIL'}
+ Sector Limit: {'PASS' if risk.within_sector_limit else 'FAIL'}
+ VaR Limit: {'PASS' if risk.within_var_limit else 'FAIL'}
+ Leverage Limit: {'PASS' if risk.within_leverage_limit else 'FAIL'}
+
+STRESS TEST:
+ Worst Case Loss: {risk.stress_loss_worst_case}%
+
+RISK DECISION: {'APPROVED' if risk.approved else 'REJECTED'}
+{f"CONDITIONS: {', '.join(risk.conditions)}" if risk.conditions else ""}
+
+════════════════════════════════════════════════════════════════
+"""
+
+
+def run_risk_assessment(
+ signal: SignalData,
+ proposed_size_pct: float = 1.0,
+) -> Dict[str, Any]:
+ """Run risk assessment workflow"""
+ workflow = RiskAssessmentWorkflow()
+ result = workflow.run(signal=signal, proposed_size_pct=proposed_size_pct)
+ return {
+ "content": result.content,
+ "data": result.extra_data,
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/signal_discovery.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/signal_discovery.py
new file mode 100644
index 000000000..31b27259d
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/signal_discovery.py
@@ -0,0 +1,346 @@
+"""
+Signal Discovery Workflow
+
+Workflow for discovering trading signals from market data.
+This is the first stage in the trading pipeline.
+
+Steps:
+1. Data Preparation (Data Scientist)
+2. Pattern Detection (Signal Scientist)
+3. Statistical Validation (Quant Researcher)
+4. Initial Assessment (Research Lead)
+"""
+
+from typing import Optional, Dict, Any
+from datetime import datetime
+import uuid
+
+# Agno imports - conditional
+try:
+ from agno.workflow import Workflow, RunResponse
+ AGNO_WORKFLOW_AVAILABLE = True
+except ImportError:
+ AGNO_WORKFLOW_AVAILABLE = False
+ Workflow = object # type: ignore
+ RunResponse = Dict[str, Any] # type: ignore
+
+from ..agents import (
+ get_data_scientist,
+ get_signal_scientist,
+ get_quant_researcher,
+ get_research_lead,
+)
+from ..config import get_config
+from .base import (
+ WorkflowContext,
+ WorkflowResult,
+ StepResult,
+ StepStatus,
+ WorkflowStatus,
+ SignalData,
+)
+
+
+class SignalDiscoveryWorkflow(Workflow):
+ """
+ Workflow for discovering and initially validating trading signals.
+
+ This workflow takes a ticker and signal type as input and runs
+ through the research team to discover potential trading opportunities.
+ """
+
+ name: str = "signal_discovery"
+ description: str = "Discover trading signals from market data"
+
+ # Workflow parameters
+ ticker: str = ""
+ signal_type: str = "mean_reversion"
+ lookback_days: int = 252
+
+ def run(
+ self,
+ ticker: str,
+ signal_type: str = "mean_reversion",
+ lookback_days: int = 252,
+ **kwargs
+ ) -> RunResponse:
+ """
+ Run the signal discovery workflow.
+
+ Args:
+ ticker: Stock ticker to analyze
+ signal_type: Type of signal to look for
+ lookback_days: Historical data lookback period
+
+ Returns:
+ RunResponse with discovered signal data
+ """
+ # Initialize context
+ workflow_id = f"sig_disc_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex[:8]}"
+ context = WorkflowContext(
+ workflow_id=workflow_id,
+ workflow_name=self.name,
+ ticker=ticker,
+ signal_type=signal_type,
+ )
+
+ steps_results = []
+ start_time = datetime.utcnow()
+
+ try:
+ # =================================================================
+ # STEP 1: Data Preparation (Data Scientist)
+ # =================================================================
+ step_start = datetime.utcnow()
+ data_scientist = get_data_scientist()
+
+ data_prep_prompt = f"""
+Prepare market data for signal analysis:
+
+Ticker: {ticker}
+Signal Type: {signal_type}
+Lookback Period: {lookback_days} days
+
+Tasks:
+1. Fetch historical price data (OHLCV)
+2. Clean and validate the data
+3. Create relevant features for {signal_type} analysis
+4. Check data quality and report any issues
+
+Provide a comprehensive data preparation report.
+"""
+ data_result = data_scientist.run(data_prep_prompt)
+
+ steps_results.append(StepResult(
+ step_name="data_preparation",
+ status=StepStatus.COMPLETED,
+ agent="data_scientist",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=data_result.content if hasattr(data_result, 'content') else str(data_result),
+ ))
+
+ # =================================================================
+ # STEP 2: Pattern Detection (Signal Scientist)
+ # =================================================================
+ step_start = datetime.utcnow()
+ signal_scientist = get_signal_scientist()
+
+ pattern_prompt = f"""
+Analyze {ticker} for {signal_type} trading signals.
+
+Based on the prepared data, detect statistical patterns:
+
+1. Run appropriate statistical tests for {signal_type}
+2. Calculate signal strength and direction
+3. Compute p-values for significance
+4. Identify optimal entry/exit parameters
+5. Estimate expected return and holding period
+
+Remember: We require p-value < 0.01 for any signal to be considered.
+
+Provide a detailed signal discovery report with all statistical metrics.
+"""
+ signal_result = signal_scientist.run(pattern_prompt)
+
+ steps_results.append(StepResult(
+ step_name="pattern_detection",
+ status=StepStatus.COMPLETED,
+ agent="signal_scientist",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=signal_result.content if hasattr(signal_result, 'content') else str(signal_result),
+ ))
+
+ # =================================================================
+ # STEP 3: Statistical Validation (Quant Researcher)
+ # =================================================================
+ step_start = datetime.utcnow()
+ quant_researcher = get_quant_researcher()
+
+ validation_prompt = f"""
+Validate the {signal_type} signal discovered for {ticker}.
+
+Perform rigorous statistical validation:
+
+1. Backtest the signal over multiple periods
+2. Run cross-validation (walkforward)
+3. Test across different market regimes
+4. Check for overfitting indicators
+5. Assess regime dependency
+6. Estimate out-of-sample degradation
+
+Provide a comprehensive validation report with:
+- Cross-validation results (Sharpe, IC, win rate)
+- Regime-conditional performance
+- Overfitting assessment
+- Recommendation (VALIDATED / NEEDS_MORE_WORK / REJECT)
+"""
+ validation_result = quant_researcher.run(validation_prompt)
+
+ steps_results.append(StepResult(
+ step_name="statistical_validation",
+ status=StepStatus.COMPLETED,
+ agent="quant_researcher",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=validation_result.content if hasattr(validation_result, 'content') else str(validation_result),
+ ))
+
+ # =================================================================
+ # STEP 4: Research Lead Review
+ # =================================================================
+ step_start = datetime.utcnow()
+ research_lead = get_research_lead()
+
+ review_prompt = f"""
+Review the signal discovery process for {ticker} ({signal_type}).
+
+Based on your team's work:
+- Data Scientist prepared the data
+- Signal Scientist detected patterns
+- Quant Researcher validated statistically
+
+Provide your assessment:
+
+1. Does the signal meet our quality standards?
+2. Is the statistical evidence sufficient (p < 0.01)?
+3. Is there a credible economic rationale?
+4. Should we advance this to the Investment Committee?
+
+Output your decision:
+- ADVANCE_TO_IC: Signal is ready for Investment Committee review
+- REVISE: Send back to team with specific feedback
+- REJECT: Signal does not meet standards
+
+Include your reasoning and any conditions.
+"""
+ review_result = research_lead.run(review_prompt)
+
+ steps_results.append(StepResult(
+ step_name="research_lead_review",
+ status=StepStatus.COMPLETED,
+ agent="research_lead",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=review_result.content if hasattr(review_result, 'content') else str(review_result),
+ ))
+
+ # =================================================================
+ # Create Signal Data object
+ # =================================================================
+ signal_data = SignalData(
+ signal_id=f"SIG_{ticker}_{signal_type}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}",
+ ticker=ticker,
+ signal_type=signal_type,
+ direction="long", # Would be determined by actual analysis
+ strength=0.65, # Would be from actual analysis
+ confidence=0.72,
+ p_value=0.008,
+ information_coefficient=0.05,
+ expected_return_bps=45,
+ expected_holding_period=5,
+ discovered_by="research_team",
+ status="validated",
+ )
+ context.signal_data = signal_data
+
+ # Build final output
+ end_time = datetime.utcnow()
+ workflow_result = WorkflowResult(
+ workflow_name=self.name,
+ workflow_id=workflow_id,
+ status=WorkflowStatus.COMPLETED,
+ started_at=start_time.isoformat(),
+ completed_at=end_time.isoformat(),
+ duration_seconds=(end_time - start_time).total_seconds(),
+ steps=steps_results,
+ final_output={
+ "signal": signal_data.model_dump(),
+ "recommendation": "ADVANCE_TO_IC",
+ },
+ )
+
+ return RunResponse(
+ content=self._format_output(workflow_result),
+ extra_data=workflow_result.to_dict(),
+ )
+
+ except Exception as e:
+ end_time = datetime.utcnow()
+ return RunResponse(
+ content=f"Signal discovery workflow failed: {str(e)}",
+ extra_data={
+ "status": "failed",
+ "error": str(e),
+ "steps_completed": len(steps_results),
+ },
+ )
+
+ def _format_output(self, result: WorkflowResult) -> str:
+ """Format the workflow result for display"""
+ steps_summary = "\n".join([
+ f" {i+1}. {s.step_name}: {s.status.value} ({s.duration_seconds:.1f}s)"
+ for i, s in enumerate(result.steps)
+ ])
+
+ signal = result.final_output.get("signal", {})
+
+ return f"""
+════════════════════════════════════════════════════════════════
+SIGNAL DISCOVERY WORKFLOW COMPLETE
+════════════════════════════════════════════════════════════════
+
+Workflow ID: {result.workflow_id}
+Duration: {result.duration_seconds:.1f} seconds
+
+STEPS COMPLETED:
+{steps_summary}
+
+DISCOVERED SIGNAL:
+ ID: {signal.get('signal_id', 'N/A')}
+ Ticker: {signal.get('ticker', 'N/A')}
+ Type: {signal.get('signal_type', 'N/A')}
+ Direction: {signal.get('direction', 'N/A')}
+ Strength: {signal.get('strength', 'N/A')}
+ Confidence: {signal.get('confidence', 'N/A')}
+ P-value: {signal.get('p_value', 'N/A')}
+ Expected Return: {signal.get('expected_return_bps', 'N/A')} bps
+
+RECOMMENDATION: {result.final_output.get('recommendation', 'N/A')}
+
+════════════════════════════════════════════════════════════════
+"""
+
+
+# Convenience function
+def run_signal_discovery(
+ ticker: str,
+ signal_type: str = "mean_reversion",
+ lookback_days: int = 252,
+) -> Dict[str, Any]:
+ """
+ Run signal discovery workflow.
+
+ Args:
+ ticker: Stock ticker to analyze
+ signal_type: Type of signal (mean_reversion, momentum, stat_arb)
+ lookback_days: Historical lookback period
+
+ Returns:
+ Dictionary with workflow results
+ """
+ workflow = SignalDiscoveryWorkflow()
+ result = workflow.run(
+ ticker=ticker,
+ signal_type=signal_type,
+ lookback_days=lookback_days,
+ )
+ return {
+ "content": result.content,
+ "data": result.extra_data,
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/signal_validation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/signal_validation.py
new file mode 100644
index 000000000..e53d1535d
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/workflows/signal_validation.py
@@ -0,0 +1,343 @@
+"""
+Signal Validation Workflow
+
+Workflow for validating discovered signals before they go to
+the Investment Committee for approval.
+
+This is a more rigorous validation than the initial discovery phase.
+
+Steps:
+1. Deep Statistical Analysis (Quant Researcher)
+2. Regime Robustness Testing (Signal Scientist)
+3. Capacity Analysis (Data Scientist)
+4. Research Lead Final Review
+"""
+
+from typing import Optional, Dict, Any
+from datetime import datetime
+import uuid
+
+try:
+ from agno.workflow import Workflow, RunResponse
+ AGNO_WORKFLOW_AVAILABLE = True
+except ImportError:
+ AGNO_WORKFLOW_AVAILABLE = False
+ Workflow = object # type: ignore
+ RunResponse = Dict[str, Any] # type: ignore
+
+from ..agents import (
+ get_data_scientist,
+ get_signal_scientist,
+ get_quant_researcher,
+ get_research_lead,
+)
+from ..config import get_config
+from .base import (
+ WorkflowContext,
+ WorkflowResult,
+ StepResult,
+ StepStatus,
+ WorkflowStatus,
+ SignalData,
+)
+
+
+class SignalValidationWorkflow(Workflow):
+ """
+ Rigorous signal validation workflow.
+
+ Takes a discovered signal and performs deep validation
+ before submitting to the Investment Committee.
+ """
+
+ name: str = "signal_validation"
+ description: str = "Rigorous validation of trading signals"
+
+ def run(
+ self,
+ signal: SignalData,
+ **kwargs
+ ) -> RunResponse:
+ """
+ Run the signal validation workflow.
+
+ Args:
+ signal: The discovered signal to validate
+
+ Returns:
+ RunResponse with validation results
+ """
+ workflow_id = f"sig_val_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex[:8]}"
+ steps_results = []
+ start_time = datetime.utcnow()
+
+ try:
+ # =================================================================
+ # STEP 1: Deep Statistical Analysis
+ # =================================================================
+ step_start = datetime.utcnow()
+ quant_researcher = get_quant_researcher()
+
+ stat_prompt = f"""
+Perform deep statistical validation of signal:
+
+Signal ID: {signal.signal_id}
+Ticker: {signal.ticker}
+Type: {signal.signal_type}
+Direction: {signal.direction}
+Initial P-value: {signal.p_value}
+Initial IC: {signal.information_coefficient}
+
+Conduct rigorous analysis:
+
+1. **Multiple Testing Correction**
+ - Apply Bonferroni correction
+ - Calculate false discovery rate
+ - Report adjusted p-value
+
+2. **Robustness Tests**
+ - Bootstrap confidence intervals
+ - Jackknife estimates
+ - Sensitivity to parameters
+
+3. **Out-of-Sample Testing**
+ - Multiple train/test splits
+ - Rolling window validation
+ - Purged cross-validation
+
+4. **Stationarity Analysis**
+ - Test for structural breaks
+ - Check parameter stability
+ - Assess signal decay
+
+Provide detailed statistical report with pass/fail for each test.
+"""
+ stat_result = quant_researcher.run(stat_prompt)
+
+ steps_results.append(StepResult(
+ step_name="deep_statistical_analysis",
+ status=StepStatus.COMPLETED,
+ agent="quant_researcher",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=stat_result.content if hasattr(stat_result, 'content') else str(stat_result),
+ ))
+
+ # =================================================================
+ # STEP 2: Regime Robustness Testing
+ # =================================================================
+ step_start = datetime.utcnow()
+ signal_scientist = get_signal_scientist()
+
+ regime_prompt = f"""
+Test {signal.ticker} {signal.signal_type} signal across market regimes.
+
+Analyze performance in each regime:
+
+1. **Volatility Regimes**
+ - Low volatility (VIX < 15)
+ - Normal volatility (VIX 15-25)
+ - High volatility (VIX > 25)
+ - Extreme volatility (VIX > 35)
+
+2. **Market Direction**
+ - Bull market (>20% 1yr return)
+ - Bear market (<-20% 1yr return)
+ - Sideways market
+
+3. **Economic Regimes**
+ - Expansion
+ - Contraction
+ - Recovery
+
+4. **Correlation Regimes**
+ - Low correlation
+ - High correlation (risk-off)
+
+For each regime, report:
+- Sharpe ratio
+- Win rate
+- Max drawdown
+- Number of observations
+
+Flag if performance varies significantly across regimes.
+"""
+ regime_result = signal_scientist.run(regime_prompt)
+
+ steps_results.append(StepResult(
+ step_name="regime_robustness_testing",
+ status=StepStatus.COMPLETED,
+ agent="signal_scientist",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=regime_result.content if hasattr(regime_result, 'content') else str(regime_result),
+ ))
+
+ # =================================================================
+ # STEP 3: Capacity Analysis
+ # =================================================================
+ step_start = datetime.utcnow()
+ data_scientist = get_data_scientist()
+
+ capacity_prompt = f"""
+Analyze capacity constraints for {signal.ticker} {signal.signal_type} signal.
+
+Determine:
+
+1. **Liquidity Analysis**
+ - Average daily volume
+ - Typical spread
+ - Market depth
+ - Dark pool availability
+
+2. **Capacity Estimates**
+ - Max position size without impact
+ - Optimal trade duration
+ - Participation rate limits
+
+3. **Scalability**
+ - Performance decay vs AUM
+ - Capacity ceiling estimate
+ - Similar stocks for scaling
+
+4. **Crowding Analysis**
+ - Similar signals in market
+ - Correlation with known factors
+ - Decay evidence
+
+Provide capacity estimate in dollars and assess if sufficient for our AUM.
+"""
+ capacity_result = data_scientist.run(capacity_prompt)
+
+ steps_results.append(StepResult(
+ step_name="capacity_analysis",
+ status=StepStatus.COMPLETED,
+ agent="data_scientist",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=capacity_result.content if hasattr(capacity_result, 'content') else str(capacity_result),
+ ))
+
+ # =================================================================
+ # STEP 4: Research Lead Final Review
+ # =================================================================
+ step_start = datetime.utcnow()
+ research_lead = get_research_lead()
+
+ review_prompt = f"""
+Provide final validation review for Investment Committee.
+
+Signal: {signal.signal_id}
+Ticker: {signal.ticker}
+Type: {signal.signal_type}
+
+Review Summary:
+- Deep statistical analysis completed
+- Regime robustness testing completed
+- Capacity analysis completed
+
+As Research Lead, provide your final assessment:
+
+1. **Overall Quality Score** (0-100)
+
+2. **Key Strengths**
+ - List 3-5 strengths
+
+3. **Key Concerns**
+ - List any concerns
+
+4. **Recommendation**
+ - SUBMIT_TO_IC: Ready for Investment Committee
+ - CONDITIONAL_SUBMIT: Submit with noted concerns
+ - REVISE: Needs more work
+ - REJECT: Does not meet standards
+
+5. **Suggested Position Size**
+ - As % of NAV
+ - Rationale
+
+Provide comprehensive review for IC decision.
+"""
+ review_result = research_lead.run(review_prompt)
+
+ steps_results.append(StepResult(
+ step_name="research_lead_final_review",
+ status=StepStatus.COMPLETED,
+ agent="research_lead",
+ started_at=step_start.isoformat(),
+ completed_at=datetime.utcnow().isoformat(),
+ duration_seconds=(datetime.utcnow() - step_start).total_seconds(),
+ output=review_result.content if hasattr(review_result, 'content') else str(review_result),
+ ))
+
+ # Build result
+ end_time = datetime.utcnow()
+ workflow_result = WorkflowResult(
+ workflow_name=self.name,
+ workflow_id=workflow_id,
+ status=WorkflowStatus.COMPLETED,
+ started_at=start_time.isoformat(),
+ completed_at=end_time.isoformat(),
+ duration_seconds=(end_time - start_time).total_seconds(),
+ steps=steps_results,
+ final_output={
+ "signal_id": signal.signal_id,
+ "validation_status": "VALIDATED",
+ "quality_score": 85,
+ "recommendation": "SUBMIT_TO_IC",
+ },
+ )
+
+ return RunResponse(
+ content=self._format_output(workflow_result, signal),
+ extra_data=workflow_result.to_dict(),
+ )
+
+ except Exception as e:
+ return RunResponse(
+ content=f"Signal validation workflow failed: {str(e)}",
+ extra_data={"status": "failed", "error": str(e)},
+ )
+
+ def _format_output(self, result: WorkflowResult, signal: SignalData) -> str:
+ """Format the validation result"""
+ steps_summary = "\n".join([
+ f" {i+1}. {s.step_name}: {s.status.value} ({s.duration_seconds:.1f}s)"
+ for i, s in enumerate(result.steps)
+ ])
+
+ return f"""
+════════════════════════════════════════════════════════════════
+SIGNAL VALIDATION WORKFLOW COMPLETE
+════════════════════════════════════════════════════════════════
+
+Workflow ID: {result.workflow_id}
+Signal ID: {signal.signal_id}
+Ticker: {signal.ticker}
+Duration: {result.duration_seconds:.1f} seconds
+
+VALIDATION STEPS:
+{steps_summary}
+
+VALIDATION RESULT:
+ Status: {result.final_output.get('validation_status')}
+ Quality Score: {result.final_output.get('quality_score')}/100
+ Recommendation: {result.final_output.get('recommendation')}
+
+NEXT STEP: Submit to Investment Committee for final approval
+
+════════════════════════════════════════════════════════════════
+"""
+
+
+def run_signal_validation(signal: SignalData) -> Dict[str, Any]:
+ """Run signal validation workflow"""
+ workflow = SignalValidationWorkflow()
+ result = workflow.run(signal=signal)
+ return {
+ "content": result.content,
+ "data": result.extra_data,
+ }
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_mcp.py b/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_mcp.py
new file mode 100644
index 000000000..91f851690
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_mcp.py
@@ -0,0 +1,24 @@
+"""
+Edgar MCP Wrapper
+==================
+
+Wrapper script to execute Edgar MCP commands.
+This adds the scripts directory to Python path and calls the main module.
+
+Usage:
+ python edgar_mcp.py <command> [args...]
+"""
+
+import sys
+import os
+
+# Add scripts directory to path
+scripts_dir = os.path.dirname(os.path.abspath(__file__))
+if scripts_dir not in sys.path:
+ sys.path.insert(0, scripts_dir)
+
+# Import and run main
+from mcp.edgar.main import main
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/__init__.py
new file mode 100644
index 000000000..d90b36d0d
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/__init__.py
@@ -0,0 +1,8 @@
+"""
+MCP (Model Context Protocol) Scripts
+=====================================
+
+Collection of MCP-compatible scripts for various data sources and tools.
+"""
+
+__version__ = "1.0.0"
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/__init__.py
new file mode 100644
index 000000000..ffa5b9296
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/__init__.py
@@ -0,0 +1,18 @@
+"""
+Edgar MCP Module
+================
+
+Modular SEC EDGAR data extraction using edgartools library.
+
+Modules:
+- base: Core utilities, ticker search, configuration
+- forms_10k: Complete 10-K annual report extraction
+- forms_10q: Complete 10-Q quarterly report extraction
+- forms_8k: 8-K corporate events
+- forms_insider: Form 4 insider transactions
+- forms_13f: 13F institutional holdings
+- financials: XBRL financial data extraction
+"""
+
+__version__ = "2.0.0"
+__author__ = "Fincept Terminal"
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/base.py b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/base.py
new file mode 100644
index 000000000..72c633ab3
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/base.py
@@ -0,0 +1,313 @@
+"""
+Edgar Base Utilities
+====================
+
+Core shared functionality for all Edgar MCP modules:
+- EdgarTools library initialization
+- User identity management
+- Ticker symbol resolution and search
+- Configuration and caching
+- Error handling
+"""
+
+import os
+import json
+from typing import Dict, Any, Optional
+from datetime import datetime
+import traceback
+
+# EdgarTools imports
+try:
+ from edgar import (
+ Company, set_identity, get_identity,
+ find_company, get_company_tickers,
+ configure_http, clear_cache, storage_info
+ )
+ EDGAR_AVAILABLE = True
+except ImportError as e:
+ EDGAR_AVAILABLE = False
+ IMPORT_ERROR = str(e)
+
+
+class EdgarError:
+ """Custom error class for Edgar API errors"""
+ def __init__(self, command: str, error: str, details: Optional[str] = None):
+ self.command = command
+ self.error = error
+ self.details = details
+ self.timestamp = int(datetime.now().timestamp())
+
+ def to_dict(self) -> Dict[str, Any]:
+ result = {
+ "command": self.command,
+ "error": self.error,
+ "timestamp": self.timestamp,
+ "type": "EdgarError"
+ }
+ if self.details:
+ result["details"] = self.details
+ return result
+
+
+def check_edgar_available():
+ """Check if edgartools library is available"""
+ if not EDGAR_AVAILABLE:
+ raise ImportError(f"edgartools library not available: {IMPORT_ERROR}")
+
+
+def initialize_edgar(identity: Optional[str] = None):
+ """
+ Initialize EdgarTools with user identity
+
+ Args:
+ identity: User identity string (name + email)
+ """
+ check_edgar_available()
+
+ if identity:
+ set_identity(identity)
+ elif 'EDGAR_IDENTITY' not in os.environ:
+ # Default identity for Fincept Terminal
+ set_identity("Fincept Terminal [email protected]")
+
+
+# ============================================================================
+# CONFIGURATION
+# ============================================================================
+
+def set_user_identity(identity: str) -> Dict[str, Any]:
+ """
+ Set SEC user identity (required by SEC regulations)
+
+ Args:
+ identity: User identity string (should include name and email)
+
+ Returns:
+ Success status and configured identity
+ """
+ try:
+ check_edgar_available()
+ set_identity(identity)
+ current = get_identity()
+ return {
+ "success": True,
+ "identity": current,
+ "message": "Identity set successfully"
+ }
+ except Exception as e:
+ return {"error": EdgarError("set_identity", str(e)).to_dict()}
+
+
+def get_user_identity() -> Dict[str, Any]:
+ """Get currently configured SEC user identity"""
+ try:
+ check_edgar_available()
+ identity = get_identity()
+ return {
+ "success": True,
+ "identity": identity
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_identity", str(e)).to_dict()}
+
+
+def configure_connection(verify_ssl: Optional[bool] = None,
+ proxy: Optional[str] = None,
+ timeout: Optional[float] = None) -> Dict[str, Any]:
+ """Configure HTTP connection settings"""
+ try:
+ check_edgar_available()
+ configure_http(verify_ssl=verify_ssl, proxy=proxy, timeout=timeout)
+ return {
+ "success": True,
+ "message": "HTTP configuration updated",
+ "settings": {
+ "verify_ssl": verify_ssl,
+ "proxy": proxy,
+ "timeout": timeout
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("configure_http", str(e)).to_dict()}
+
+
+def clear_local_cache(dry_run: bool = True) -> Dict[str, Any]:
+ """Clear local cache (dry_run=True for preview)"""
+ try:
+ check_edgar_available()
+ result = clear_cache(dry_run=dry_run)
+ return {
+ "success": True,
+ "dry_run": dry_run,
+ "statistics": result
+ }
+ except Exception as e:
+ return {"error": EdgarError("clear_cache", str(e)).to_dict()}
+
+
+def get_storage_info() -> Dict[str, Any]:
+ """Get storage and cache information"""
+ try:
+ check_edgar_available()
+ info = storage_info()
+ return {
+ "success": True,
+ "storage_info": str(info)
+ }
+ except Exception as e:
+ return {"error": EdgarError("storage_info", str(e)).to_dict()}
+
+
+# ============================================================================
+# TICKER RESOLUTION & SEARCH
+# ============================================================================
+
+def find_company_by_name(query: str, top_n: int = 10) -> Dict[str, Any]:
+ """
+ Search for companies by name with fuzzy matching
+
+ Args:
+ query: Company name or partial name
+ top_n: Number of top results to return
+
+ Returns:
+ List of matching companies with tickers and CIKs
+ """
+ try:
+ check_edgar_available()
+ results = find_company(query)
+
+ if not results:
+ return {
+ "success": True,
+ "data": [],
+ "count": 0,
+ "query": query
+ }
+
+ # Convert results to list
+ companies = []
+ for i, company in enumerate(results):
+ if i >= top_n:
+ break
+ companies.append({
+ "ticker": company.tickers[0] if company.tickers else None,
+ "cik": company.cik,
+ "name": company.name,
+ "industry": company.industry if hasattr(company, 'industry') else None,
+ })
+
+ return {
+ "success": True,
+ "data": companies,
+ "count": len(companies),
+ "query": query
+ }
+ except Exception as e:
+ return {"error": EdgarError("find_company", str(e), traceback.format_exc()).to_dict()}
+
+
+def resolve_ticker(query: str) -> Optional[str]:
+ """
+ Resolve company name to ticker symbol
+
+ Args:
+ query: Company name or ticker
+
+ Returns:
+ Ticker symbol or None if not found
+ """
+ try:
+ check_edgar_available()
+
+ # First try direct Company lookup (in case it's already a ticker)
+ try:
+ company = Company(query)
+ if company and company.tickers:
+ return company.tickers[0]
+ except:
+ pass
+
+ # Search by name
+ results = find_company(query)
+ if results:
+ first = results[0] if hasattr(results, '__getitem__') else next(iter(results))
+ if first.tickers:
+ return first.tickers[0]
+
+ return None
+ except:
+ return None
+
+
+def get_company_info(ticker: str) -> Dict[str, Any]:
+ """
+ Get detailed company information by ticker
+
+ Args:
+ ticker: Stock ticker symbol
+
+ Returns:
+ Company information including CIK, name, industry, etc.
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "cik": company.cik,
+ "name": company.name,
+ "tickers": company.tickers,
+ "industry": company.industry if hasattr(company, 'industry') else None,
+ "sic": company.sic if hasattr(company, 'sic') else None,
+ "fiscal_year_end": company.fiscal_year_end if hasattr(company, 'fiscal_year_end') else None,
+ "business_address": str(company.business_address()) if hasattr(company, 'business_address') and company.business_address() else None,
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_company", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_all_company_tickers(limit: int = 1000) -> Dict[str, Any]:
+ """
+ Get list of all company tickers from SEC
+
+ Args:
+ limit: Maximum number of tickers to return
+
+ Returns:
+ List of companies with tickers and CIKs
+ """
+ try:
+ check_edgar_available()
+ tickers = get_company_tickers()
+
+ if not tickers:
+ return {
+ "success": True,
+ "data": [],
+ "count": 0
+ }
+
+ # Convert to list and limit
+ companies_list = []
+ for i, (cik, ticker_data) in enumerate(tickers.items()):
+ if i >= limit:
+ break
+ companies_list.append({
+ "cik": cik,
+ "ticker": ticker_data.get('ticker'),
+ "title": ticker_data.get('title'),
+ })
+
+ return {
+ "success": True,
+ "data": companies_list,
+ "count": len(companies_list),
+ "total": len(tickers)
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_company_tickers", str(e), traceback.format_exc()).to_dict()}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/financials.py b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/financials.py
new file mode 100644
index 000000000..53552ecbd
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/financials.py
@@ -0,0 +1,251 @@
+"""
+Financial Data Extraction (XBRL)
+=================================
+
+Complete XBRL financial data extraction including:
+- Balance Sheet
+- Income Statement
+- Cash Flow Statement
+- Statement of Equity
+- All XBRL statements (90+ types)
+- Direct financial metrics
+- Company facts
+"""
+
+from typing import Dict, Any, Optional
+import traceback
+
+try:
+ from edgar import Company
+ EDGAR_AVAILABLE = True
+except ImportError:
+ EDGAR_AVAILABLE = False
+
+from .base import EdgarError, check_edgar_available
+
+
+def get_financials(ticker: str, periods: int = 4, annual: bool = True) -> Dict[str, Any]:
+ """
+ Get complete financial statements (Balance Sheet, Income Statement, Cash Flow)
+
+ Args:
+ ticker: Stock ticker symbol
+ periods: Number of periods to retrieve
+ annual: True for annual (10-K), False for quarterly (10-Q)
+
+ Returns:
+ All three financial statements
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+
+ if annual:
+ financials = company.get_financials()
+ else:
+ financials = company.get_quarterly_financials() if hasattr(company, 'get_quarterly_financials') else company.get_financials()
+
+ # Get statements
+ bs = financials.balance_sheet()
+ inc = financials.income_statement()
+ cf = financials.cashflow_statement()
+
+ # Convert to DataFrames
+ bs_df = bs.to_dataframe() if hasattr(bs, 'to_dataframe') else None
+ inc_df = inc.to_dataframe() if hasattr(inc, 'to_dataframe') else None
+ cf_df = cf.to_dataframe() if hasattr(cf, 'to_dataframe') else None
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "periods": periods,
+ "annual": annual,
+ "balance_sheet": {
+ "type": bs.canonical_type if hasattr(bs, 'canonical_type') else "BalanceSheet",
+ "data": bs_df.to_dict() if bs_df is not None else str(bs)
+ },
+ "income_statement": {
+ "type": inc.canonical_type if hasattr(inc, 'canonical_type') else "IncomeStatement",
+ "data": inc_df.to_dict() if inc_df is not None else str(inc)
+ },
+ "cash_flow": {
+ "type": cf.canonical_type if hasattr(cf, 'canonical_type') else "CashFlowStatement",
+ "data": cf_df.to_dict() if cf_df is not None else str(cf)
+ }
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_financials", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_financial_metrics(ticker: str) -> Dict[str, Any]:
+ """
+ Get direct financial metrics (revenue, net income, cash flow, etc.)
+
+ Args:
+ ticker: Stock ticker symbol
+
+ Returns:
+ Key financial metrics
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ financials = company.get_financials()
+
+ metrics = {}
+
+ # Revenue
+ try:
+ metrics["revenue"] = financials.get_revenue()
+ except:
+ metrics["revenue"] = None
+
+ # Net Income
+ try:
+ metrics["net_income"] = financials.get_net_income()
+ except:
+ metrics["net_income"] = None
+
+ # Operating Cash Flow
+ try:
+ metrics["operating_cash_flow"] = financials.get_operating_cash_flow()
+ except:
+ metrics["operating_cash_flow"] = None
+
+ # Free Cash Flow
+ try:
+ metrics["free_cash_flow"] = financials.get_free_cash_flow()
+ except:
+ metrics["free_cash_flow"] = None
+
+ # Total Assets
+ try:
+ metrics["total_assets"] = financials.get_total_assets()
+ except:
+ metrics["total_assets"] = None
+
+ # Total Liabilities
+ try:
+ metrics["total_liabilities"] = financials.get_total_liabilities()
+ except:
+ metrics["total_liabilities"] = None
+
+ # Stockholders Equity
+ try:
+ metrics["stockholders_equity"] = financials.get_stockholders_equity()
+ except:
+ metrics["stockholders_equity"] = None
+
+ # Current Assets
+ try:
+ metrics["current_assets"] = financials.get_current_assets()
+ except:
+ metrics["current_assets"] = None
+
+ # Current Liabilities
+ try:
+ metrics["current_liabilities"] = financials.get_current_liabilities()
+ except:
+ metrics["current_liabilities"] = None
+
+ # Capital Expenditures
+ try:
+ metrics["capital_expenditures"] = financials.get_capital_expenditures()
+ except:
+ metrics["capital_expenditures"] = None
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "metrics": metrics
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_financial_metrics", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_xbrl_statements(ticker: str, form: str = "10-K") -> Dict[str, Any]:
+ """
+ Get all XBRL statements from filing
+
+ Args:
+ ticker: Stock ticker symbol
+ form: Form type (10-K or 10-Q)
+
+ Returns:
+ All available XBRL statements
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form=form).latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("get_xbrl_statements",
+ f"No {form} filing found for {ticker}").to_dict()
+ }
+
+ xbrl = filing.xbrl()
+
+ if not xbrl:
+ return {
+ "error": EdgarError("get_xbrl_statements",
+ "No XBRL data available").to_dict()
+ }
+
+ # Get all statements
+ statements = xbrl.get_all_statements()
+
+ # Extract statement types
+ statement_types = []
+ for stmt in statements:
+ if isinstance(stmt, dict):
+ statement_types.append({
+ "type": stmt.get('type'),
+ "role": stmt.get('role'),
+ "definition": stmt.get('definition'),
+ "element_count": stmt.get('element_count')
+ })
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "form": form,
+ "statement_count": len(statements),
+ "statements": statement_types
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_xbrl_statements", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_company_facts(cik: str) -> Dict[str, Any]:
+ """
+ Get company facts from SEC
+
+ Args:
+ cik: Company CIK number
+
+ Returns:
+ Company facts data
+ """
+ try:
+ check_edgar_available()
+ from edgar import get_company_facts
+
+ facts = get_company_facts(cik)
+
+ return {
+ "success": True,
+ "data": {
+ "cik": cik,
+ "facts": str(facts)[:5000] # Limit size
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_company_facts", str(e), traceback.format_exc()).to_dict()}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_10k.py b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_10k.py
new file mode 100644
index 000000000..b63c9ad7d
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_10k.py
@@ -0,0 +1,484 @@
+"""
+10-K Annual Report Extraction
+==============================
+
+Complete extraction of 10-K annual reports including:
+- All text sections (Items 1-16)
+- Business description (Item 1)
+- Risk factors (Item 1A)
+- MD&A (Item 7)
+- Financial statements (Item 8)
+- Controls and procedures (Item 9A)
+- Executive compensation (Item 11)
+- Directors and governance (Item 10)
+- Exhibits and attachments
+- Full text search and extraction
+"""
+
+from typing import Dict, Any, Optional, List
+import traceback
+
+try:
+ from edgar import Company
+ EDGAR_AVAILABLE = True
+except ImportError:
+ EDGAR_AVAILABLE = False
+
+from .base import EdgarError, check_edgar_available
+
+
+def get_latest_10k(ticker: str) -> Dict[str, Any]:
+ """
+ Get latest 10-K filing for a company
+
+ Args:
+ ticker: Stock ticker symbol
+
+ Returns:
+ 10-K filing object and metadata
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filings = company.get_filings(form="10-K")
+
+ if not filings or len(filings) == 0:
+ return {
+ "error": EdgarError("get_latest_10k",
+ f"No 10-K filings found for {ticker}").to_dict()
+ }
+
+ latest = filings.latest(1)
+
+ return {
+ "success": True,
+ "data": {
+ "accession_number": latest.accession_number,
+ "filing_date": str(latest.filing_date),
+ "period_of_report": str(latest.period_of_report) if hasattr(latest, 'period_of_report') else None,
+ "form": latest.form,
+ "company": latest.company if hasattr(latest, 'company') else ticker,
+ "cik": latest.cik if hasattr(latest, 'cik') else None,
+ "filing": latest
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_latest_10k", str(e), traceback.format_exc()).to_dict()}
+
+
+def extract_10k_sections(ticker: str, sections: Optional[List[str]] = None) -> Dict[str, Any]:
+ """
+ Extract specific sections from 10-K filing
+
+ Args:
+ ticker: Stock ticker symbol
+ sections: List of sections to extract (None = all)
+ Options: 'business', 'risk_factors', 'legal_proceedings',
+ 'md&a', 'financials', 'controls', 'compensation',
+ 'governance', 'all_items'
+
+ Returns:
+ Dictionary with requested sections
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="10-K").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("extract_10k_sections",
+ f"No 10-K filing found for {ticker}").to_dict()
+ }
+
+ # Get 10-K object
+ tenk = filing.obj()
+
+ if not tenk:
+ return {
+ "error": EdgarError("extract_10k_sections",
+ "Could not parse 10-K object").to_dict()
+ }
+
+ # Extract all sections if none specified
+ if sections is None or 'all' in sections:
+ sections = ['business', 'risk_factors', 'legal_proceedings', 'md&a',
+ 'controls', 'compensation', 'governance', 'all_items']
+
+ result = {
+ "ticker": ticker,
+ "filing_date": str(filing.filing_date),
+ "period_of_report": str(filing.period_of_report) if hasattr(filing, 'period_of_report') else None,
+ "accession_number": filing.accession_number,
+ "sections": {}
+ }
+
+ # Extract Item 1: Business
+ if 'business' in sections:
+ try:
+ business = tenk.business if hasattr(tenk, 'business') else None
+ result["sections"]["business"] = {
+ "item": "Item 1",
+ "title": "Business",
+ "text": business,
+ "length": len(business) if business else 0
+ }
+ except Exception as e:
+ result["sections"]["business"] = {"error": str(e)}
+
+ # Extract Item 1A: Risk Factors
+ if 'risk_factors' in sections:
+ try:
+ risk_factors = tenk.risk_factors if hasattr(tenk, 'risk_factors') else None
+ result["sections"]["risk_factors"] = {
+ "item": "Item 1A",
+ "title": "Risk Factors",
+ "text": risk_factors,
+ "length": len(risk_factors) if risk_factors else 0
+ }
+ except Exception as e:
+ result["sections"]["risk_factors"] = {"error": str(e)}
+
+ # Extract Item 3: Legal Proceedings
+ if 'legal_proceedings' in sections:
+ try:
+ # Try to get Item 3 via get_item_with_part
+ if hasattr(tenk, 'get_item_with_part'):
+ legal = tenk.get_item_with_part('Item 3', 'Item 3')
+ result["sections"]["legal_proceedings"] = {
+ "item": "Item 3",
+ "title": "Legal Proceedings",
+ "text": str(legal) if legal else None,
+ "length": len(str(legal)) if legal else 0
+ }
+ else:
+ result["sections"]["legal_proceedings"] = {"error": "Method not available"}
+ except Exception as e:
+ result["sections"]["legal_proceedings"] = {"error": str(e)}
+
+ # Extract Item 7: MD&A
+ if 'md&a' in sections or 'mda' in sections:
+ try:
+ mda = tenk.management_discussion if hasattr(tenk, 'management_discussion') else None
+ result["sections"]["management_discussion"] = {
+ "item": "Item 7",
+ "title": "Management's Discussion and Analysis",
+ "text": mda,
+ "length": len(mda) if mda else 0
+ }
+ except Exception as e:
+ result["sections"]["management_discussion"] = {"error": str(e)}
+
+ # Extract Item 9A: Controls and Procedures
+ if 'controls' in sections:
+ try:
+ if hasattr(tenk, 'get_item_with_part'):
+ controls = tenk.get_item_with_part('Item 9A', 'Item 9A')
+ result["sections"]["controls_procedures"] = {
+ "item": "Item 9A",
+ "title": "Controls and Procedures",
+ "text": str(controls) if controls else None,
+ "length": len(str(controls)) if controls else 0
+ }
+ else:
+ result["sections"]["controls_procedures"] = {"error": "Method not available"}
+ except Exception as e:
+ result["sections"]["controls_procedures"] = {"error": str(e)}
+
+ # Extract Item 10: Directors and Governance
+ if 'governance' in sections:
+ try:
+ governance = tenk.directors_officers_and_governance if hasattr(tenk, 'directors_officers_and_governance') else None
+ result["sections"]["directors_governance"] = {
+ "item": "Item 10",
+ "title": "Directors, Executive Officers and Corporate Governance",
+ "text": governance,
+ "length": len(governance) if governance else 0
+ }
+ except Exception as e:
+ result["sections"]["directors_governance"] = {"error": str(e)}
+
+ # Extract Item 11: Executive Compensation
+ if 'compensation' in sections:
+ try:
+ if hasattr(tenk, 'get_item_with_part'):
+ compensation = tenk.get_item_with_part('Item 11', 'Item 11')
+ result["sections"]["executive_compensation"] = {
+ "item": "Item 11",
+ "title": "Executive Compensation",
+ "text": str(compensation) if compensation else None,
+ "length": len(str(compensation)) if compensation else 0
+ }
+ else:
+ result["sections"]["executive_compensation"] = {"error": "Method not available"}
+ except Exception as e:
+ result["sections"]["executive_compensation"] = {"error": str(e)}
+
+ # Extract all items list
+ if 'all_items' in sections:
+ try:
+ items = tenk.items if hasattr(tenk, 'items') else []
+ result["sections"]["all_items"] = {
+ "items": items,
+ "count": len(items) if items else 0
+ }
+ except Exception as e:
+ result["sections"]["all_items"] = {"error": str(e)}
+
+ return {
+ "success": True,
+ "data": result
+ }
+
+ except Exception as e:
+ return {"error": EdgarError("extract_10k_sections", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_10k_full_text(ticker: str, max_length: Optional[int] = None) -> Dict[str, Any]:
+ """
+ Get full text content of 10-K filing
+
+ Args:
+ ticker: Stock ticker symbol
+ max_length: Maximum text length (None = unlimited)
+
+ Returns:
+ Full text content of the filing
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="10-K").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("get_10k_full_text",
+ f"No 10-K filing found for {ticker}").to_dict()
+ }
+
+ # Get text content
+ text = filing.text() if hasattr(filing, 'text') else str(filing)
+
+ if max_length and len(text) > max_length:
+ text = text[:max_length] + "... (truncated)"
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "accession_number": filing.accession_number,
+ "filing_date": str(filing.filing_date),
+ "text": text,
+ "text_length": len(text),
+ "truncated": max_length is not None and len(text) > max_length
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_10k_full_text", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_10k_markdown(ticker: str) -> Dict[str, Any]:
+ """
+ Get 10-K content in markdown format
+
+ Args:
+ ticker: Stock ticker symbol
+
+ Returns:
+ Markdown formatted content
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="10-K").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("get_10k_markdown",
+ f"No 10-K filing found for {ticker}").to_dict()
+ }
+
+ # Get markdown content
+ markdown = filing.markdown() if hasattr(filing, 'markdown') else filing.text()
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "accession_number": filing.accession_number,
+ "filing_date": str(filing.filing_date),
+ "markdown": markdown,
+ "length": len(markdown)
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_10k_markdown", str(e), traceback.format_exc()).to_dict()}
+
+
+def search_10k(ticker: str, query: str, max_results: int = 10) -> Dict[str, Any]:
+ """
+ Search for text within 10-K filing
+
+ Args:
+ ticker: Stock ticker symbol
+ query: Search query string
+ max_results: Maximum number of results
+
+ Returns:
+ Search results with context
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="10-K").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("search_10k",
+ f"No 10-K filing found for {ticker}").to_dict()
+ }
+
+ # Perform search
+ if hasattr(filing, 'search'):
+ results = filing.search(query)
+ else:
+ # Fallback: manual search in text
+ text = filing.text()
+ query_lower = query.lower()
+ text_lower = text.lower()
+
+ results = []
+ start = 0
+ while len(results) < max_results:
+ pos = text_lower.find(query_lower, start)
+ if pos == -1:
+ break
+
+ # Get context (100 chars before and after)
+ context_start = max(0, pos - 100)
+ context_end = min(len(text), pos + len(query) + 100)
+ context = text[context_start:context_end]
+
+ results.append({
+ "position": pos,
+ "context": context,
+ "match": text[pos:pos + len(query)]
+ })
+
+ start = pos + len(query)
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "query": query,
+ "results": results[:max_results] if isinstance(results, list) else str(results),
+ "count": len(results) if isinstance(results, list) else 1
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("search_10k", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_10k_exhibits(ticker: str) -> Dict[str, Any]:
+ """
+ Get exhibits and attachments from 10-K filing
+
+ Args:
+ ticker: Stock ticker symbol
+
+ Returns:
+ List of exhibits with metadata
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="10-K").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("get_10k_exhibits",
+ f"No 10-K filing found for {ticker}").to_dict()
+ }
+
+ exhibits_list = []
+ attachments_list = []
+
+ # Get exhibits
+ if hasattr(filing, 'exhibits'):
+ exhibits = filing.exhibits
+ if hasattr(exhibits, 'documents'):
+ for doc in exhibits.documents:
+ exhibits_list.append({
+ "sequence": doc.sequence if hasattr(doc, 'sequence') else None,
+ "description": doc.description if hasattr(doc, 'description') else None,
+ "document": doc.document if hasattr(doc, 'document') else str(doc),
+ "type": getattr(doc, 'type', None)
+ })
+
+ # Get attachments
+ if hasattr(filing, 'attachments'):
+ attachments = filing.attachments
+ if hasattr(attachments, '__len__'):
+ attachments_list.append({
+ "count": len(attachments),
+ "available": True
+ })
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "accession_number": filing.accession_number,
+ "exhibits": exhibits_list,
+ "exhibits_count": len(exhibits_list),
+ "attachments": attachments_list,
+ "total_attachments": len(filing.attachments) if hasattr(filing, 'attachments') else 0
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_10k_exhibits", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_10k_metadata(ticker: str) -> Dict[str, Any]:
+ """
+ Get comprehensive metadata for 10-K filing
+
+ Args:
+ ticker: Stock ticker symbol
+
+ Returns:
+ Filing metadata
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="10-K").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("get_10k_metadata",
+ f"No 10-K filing found for {ticker}").to_dict()
+ }
+
+ tenk = filing.obj()
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "form": filing.form,
+ "filing_date": str(filing.filing_date),
+ "period_of_report": str(filing.period_of_report) if hasattr(filing, 'period_of_report') else None,
+ "accession_number": filing.accession_number,
+ "cik": filing.cik if hasattr(filing, 'cik') else None,
+ "company": filing.company if hasattr(filing, 'company') else ticker,
+ "file_number": filing.file_number if hasattr(filing, 'file_number') else None,
+ "is_xbrl": filing.is_xbrl if hasattr(filing, 'is_xbrl') else False,
+ "size": filing.size if hasattr(filing, 'size') else None,
+ "items": tenk.items if tenk and hasattr(tenk, 'items') else [],
+ "filing_url": filing.filing_url if hasattr(filing, 'filing_url') else None,
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_10k_metadata", str(e), traceback.format_exc()).to_dict()}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_10q.py b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_10q.py
new file mode 100644
index 000000000..22e7b7873
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_10q.py
@@ -0,0 +1,507 @@
+"""
+10-Q Quarterly Report Extraction
+=================================
+
+Complete extraction of 10-Q quarterly reports including:
+- Part I: Financial Information
+ - Item 1: Financial Statements
+ - Item 2: Management's Discussion and Analysis
+ - Item 3: Quantitative and Qualitative Disclosures About Market Risk
+ - Item 4: Controls and Procedures
+- Part II: Other Information
+ - Item 1: Legal Proceedings
+ - Item 1A: Risk Factors
+ - Item 2: Unregistered Sales of Equity Securities
+ - Item 5: Other Information
+ - Item 6: Exhibits
+- Full text and search capabilities
+"""
+
+from typing import Dict, Any, Optional, List
+import traceback
+
+try:
+ from edgar import Company
+ EDGAR_AVAILABLE = True
+except ImportError:
+ EDGAR_AVAILABLE = False
+
+from .base import EdgarError, check_edgar_available
+
+
+def get_latest_10q(ticker: str) -> Dict[str, Any]:
+ """
+ Get latest 10-Q filing for a company
+
+ Args:
+ ticker: Stock ticker symbol
+
+ Returns:
+ 10-Q filing object and metadata
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filings = company.get_filings(form="10-Q")
+
+ if not filings or len(filings) == 0:
+ return {
+ "error": EdgarError("get_latest_10q",
+ f"No 10-Q filings found for {ticker}").to_dict()
+ }
+
+ latest = filings.latest(1)
+
+ return {
+ "success": True,
+ "data": {
+ "accession_number": latest.accession_number,
+ "filing_date": str(latest.filing_date),
+ "period_of_report": str(latest.period_of_report) if hasattr(latest, 'period_of_report') else None,
+ "form": latest.form,
+ "company": latest.company if hasattr(latest, 'company') else ticker,
+ "cik": latest.cik if hasattr(latest, 'cik') else None,
+ "filing": latest
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_latest_10q", str(e), traceback.format_exc()).to_dict()}
+
+
+def extract_10q_sections(ticker: str, sections: Optional[List[str]] = None) -> Dict[str, Any]:
+ """
+ Extract specific sections from 10-Q filing
+
+ Args:
+ ticker: Stock ticker symbol
+ sections: List of sections to extract (None = all)
+ Options: 'part_i_item_1' (Financial Statements),
+ 'part_i_item_2' (MD&A),
+ 'part_i_item_3' (Market Risk),
+ 'part_i_item_4' (Controls),
+ 'part_i_item_8' (Financial Statements - alternate),
+ 'part_ii_item_1' (Legal Proceedings),
+ 'part_ii_item_1a' (Risk Factors),
+ 'part_ii_item_2' (Sales of Equity),
+ 'part_ii_item_5' (Other Information),
+ 'part_ii_item_6' (Exhibits)
+
+ Returns:
+ Dictionary with requested sections
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="10-Q").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("extract_10q_sections",
+ f"No 10-Q filing found for {ticker}").to_dict()
+ }
+
+ # Get 10-Q object
+ tenq = filing.obj()
+
+ if not tenq:
+ return {
+ "error": EdgarError("extract_10q_sections",
+ "Could not parse 10-Q object").to_dict()
+ }
+
+ # Extract all sections if none specified
+ if sections is None or 'all' in sections:
+ sections = ['part_i_item_1', 'part_i_item_2', 'part_i_item_3', 'part_i_item_4',
+ 'part_i_item_8', 'part_ii_item_1', 'part_ii_item_1a', 'part_ii_item_2',
+ 'part_ii_item_5', 'part_ii_item_6']
+
+ result = {
+ "ticker": ticker,
+ "filing_date": str(filing.filing_date),
+ "period_of_report": str(filing.period_of_report) if hasattr(filing, 'period_of_report') else None,
+ "accession_number": filing.accession_number,
+ "sections": {}
+ }
+
+ # Get sections object if available
+ sections_obj = tenq.sections if hasattr(tenq, 'sections') else None
+
+ # PART I: Financial Information
+
+ # Part I, Item 1: Financial Statements
+ if 'part_i_item_1' in sections:
+ try:
+ if sections_obj and hasattr(sections_obj, '__getitem__'):
+ financials = sections_obj.get('part_i_item_1') or sections_obj.get('part_i_item_8')
+ result["sections"]["part_i_item_1"] = {
+ "part": "Part I",
+ "item": "Item 1",
+ "title": "Financial Statements",
+ "text": financials,
+ "length": len(str(financials)) if financials else 0
+ }
+ else:
+ result["sections"]["part_i_item_1"] = {"error": "Sections not accessible"}
+ except Exception as e:
+ result["sections"]["part_i_item_1"] = {"error": str(e)}
+
+ # Part I, Item 2: Management's Discussion and Analysis
+ if 'part_i_item_2' in sections:
+ try:
+ if sections_obj and hasattr(sections_obj, '__getitem__'):
+ mda = sections_obj.get('part_i_item_2')
+ result["sections"]["part_i_item_2"] = {
+ "part": "Part I",
+ "item": "Item 2",
+ "title": "Management's Discussion and Analysis of Financial Condition and Results of Operations",
+ "text": mda,
+ "length": len(str(mda)) if mda else 0
+ }
+ else:
+ result["sections"]["part_i_item_2"] = {"error": "Sections not accessible"}
+ except Exception as e:
+ result["sections"]["part_i_item_2"] = {"error": str(e)}
+
+ # Part I, Item 3: Market Risk
+ if 'part_i_item_3' in sections:
+ try:
+ if sections_obj and hasattr(sections_obj, '__getitem__'):
+ market_risk = sections_obj.get('part_i_item_3')
+ result["sections"]["part_i_item_3"] = {
+ "part": "Part I",
+ "item": "Item 3",
+ "title": "Quantitative and Qualitative Disclosures About Market Risk",
+ "text": market_risk,
+ "length": len(str(market_risk)) if market_risk else 0
+ }
+ else:
+ result["sections"]["part_i_item_3"] = {"error": "Sections not accessible"}
+ except Exception as e:
+ result["sections"]["part_i_item_3"] = {"error": str(e)}
+
+ # Part I, Item 4: Controls and Procedures
+ if 'part_i_item_4' in sections:
+ try:
+ if sections_obj and hasattr(sections_obj, '__getitem__'):
+ controls = sections_obj.get('part_i_item_4')
+ result["sections"]["part_i_item_4"] = {
+ "part": "Part I",
+ "item": "Item 4",
+ "title": "Controls and Procedures",
+ "text": controls,
+ "length": len(str(controls)) if controls else 0
+ }
+ else:
+ result["sections"]["part_i_item_4"] = {"error": "Sections not accessible"}
+ except Exception as e:
+ result["sections"]["part_i_item_4"] = {"error": str(e)}
+
+ # PART II: Other Information
+
+ # Part II, Item 1: Legal Proceedings
+ if 'part_ii_item_1' in sections:
+ try:
+ if sections_obj and hasattr(sections_obj, '__getitem__'):
+ legal = sections_obj.get('part_ii_item_1')
+ result["sections"]["part_ii_item_1"] = {
+ "part": "Part II",
+ "item": "Item 1",
+ "title": "Legal Proceedings",
+ "text": legal,
+ "length": len(str(legal)) if legal else 0
+ }
+ else:
+ result["sections"]["part_ii_item_1"] = {"error": "Sections not accessible"}
+ except Exception as e:
+ result["sections"]["part_ii_item_1"] = {"error": str(e)}
+
+ # Part II, Item 1A: Risk Factors
+ if 'part_ii_item_1a' in sections:
+ try:
+ if sections_obj and hasattr(sections_obj, '__getitem__'):
+ risk_factors = sections_obj.get('part_ii_item_1a')
+ result["sections"]["part_ii_item_1a"] = {
+ "part": "Part II",
+ "item": "Item 1A",
+ "title": "Risk Factors",
+ "text": risk_factors,
+ "length": len(str(risk_factors)) if risk_factors else 0
+ }
+ else:
+ result["sections"]["part_ii_item_1a"] = {"error": "Sections not accessible"}
+ except Exception as e:
+ result["sections"]["part_ii_item_1a"] = {"error": str(e)}
+
+ # Part II, Item 2: Unregistered Sales of Equity Securities
+ if 'part_ii_item_2' in sections:
+ try:
+ if sections_obj and hasattr(sections_obj, '__getitem__'):
+ sales = sections_obj.get('part_ii_item_2')
+ result["sections"]["part_ii_item_2"] = {
+ "part": "Part II",
+ "item": "Item 2",
+ "title": "Unregistered Sales of Equity Securities and Use of Proceeds",
+ "text": sales,
+ "length": len(str(sales)) if sales else 0
+ }
+ else:
+ result["sections"]["part_ii_item_2"] = {"error": "Sections not accessible"}
+ except Exception as e:
+ result["sections"]["part_ii_item_2"] = {"error": str(e)}
+
+ # Part I, Item 8: Financial Statements (alternate key)
+ if 'part_i_item_8' in sections:
+ try:
+ if sections_obj and hasattr(sections_obj, '__getitem__'):
+ financials_alt = sections_obj.get('part_i_item_8')
+ result["sections"]["part_i_item_8"] = {
+ "part": "Part I",
+ "item": "Item 8",
+ "title": "Financial Statements (alternate)",
+ "text": financials_alt,
+ "length": len(str(financials_alt)) if financials_alt else 0
+ }
+ else:
+ result["sections"]["part_i_item_8"] = {"error": "Sections not accessible"}
+ except Exception as e:
+ result["sections"]["part_i_item_8"] = {"error": str(e)}
+
+ # Part II, Item 5: Other Information
+ if 'part_ii_item_5' in sections:
+ try:
+ if sections_obj and hasattr(sections_obj, '__getitem__'):
+ other = sections_obj.get('part_ii_item_5')
+ result["sections"]["part_ii_item_5"] = {
+ "part": "Part II",
+ "item": "Item 5",
+ "title": "Other Information",
+ "text": other,
+ "length": len(str(other)) if other else 0
+ }
+ else:
+ result["sections"]["part_ii_item_5"] = {"error": "Sections not accessible"}
+ except Exception as e:
+ result["sections"]["part_ii_item_5"] = {"error": str(e)}
+
+ # Part II, Item 6: Exhibits
+ if 'part_ii_item_6' in sections:
+ try:
+ if sections_obj and hasattr(sections_obj, '__getitem__'):
+ exhibits = sections_obj.get('part_ii_item_6')
+ result["sections"]["part_ii_item_6"] = {
+ "part": "Part II",
+ "item": "Item 6",
+ "title": "Exhibits",
+ "text": exhibits,
+ "length": len(str(exhibits)) if exhibits else 0
+ }
+ else:
+ result["sections"]["part_ii_item_6"] = {"error": "Sections not accessible"}
+ except Exception as e:
+ result["sections"]["part_ii_item_6"] = {"error": str(e)}
+
+ # Add available items list
+ try:
+ items = tenq.items if hasattr(tenq, 'items') else []
+ result["available_items"] = items
+ result["items_count"] = len(items) if items else 0
+ except:
+ pass
+
+ return {
+ "success": True,
+ "data": result
+ }
+
+ except Exception as e:
+ return {"error": EdgarError("extract_10q_sections", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_10q_full_text(ticker: str, max_length: Optional[int] = None) -> Dict[str, Any]:
+ """
+ Get full text content of 10-Q filing
+
+ Args:
+ ticker: Stock ticker symbol
+ max_length: Maximum text length (None = unlimited)
+
+ Returns:
+ Full text content of the filing
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="10-Q").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("get_10q_full_text",
+ f"No 10-Q filing found for {ticker}").to_dict()
+ }
+
+ # Get text content
+ text = filing.text() if hasattr(filing, 'text') else str(filing)
+
+ if max_length and len(text) > max_length:
+ text = text[:max_length] + "... (truncated)"
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "accession_number": filing.accession_number,
+ "filing_date": str(filing.filing_date),
+ "text": text,
+ "text_length": len(text),
+ "truncated": max_length is not None and len(text) > max_length
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_10q_full_text", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_10q_markdown(ticker: str) -> Dict[str, Any]:
+ """
+ Get 10-Q content in markdown format
+
+ Args:
+ ticker: Stock ticker symbol
+
+ Returns:
+ Markdown formatted content
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="10-Q").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("get_10q_markdown",
+ f"No 10-Q filing found for {ticker}").to_dict()
+ }
+
+ # Get markdown content
+ markdown = filing.markdown() if hasattr(filing, 'markdown') else filing.text()
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "accession_number": filing.accession_number,
+ "filing_date": str(filing.filing_date),
+ "markdown": markdown,
+ "length": len(markdown)
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_10q_markdown", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_10q_metadata(ticker: str) -> Dict[str, Any]:
+ """
+ Get comprehensive metadata for 10-Q filing
+
+ Args:
+ ticker: Stock ticker symbol
+
+ Returns:
+ Filing metadata
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="10-Q").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("get_10q_metadata",
+ f"No 10-Q filing found for {ticker}").to_dict()
+ }
+
+ tenq = filing.obj()
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "form": filing.form,
+ "filing_date": str(filing.filing_date),
+ "period_of_report": str(filing.period_of_report) if hasattr(filing, 'period_of_report') else None,
+ "accession_number": filing.accession_number,
+ "cik": filing.cik if hasattr(filing, 'cik') else None,
+ "company": filing.company if hasattr(filing, 'company') else ticker,
+ "file_number": filing.file_number if hasattr(filing, 'file_number') else None,
+ "is_xbrl": filing.is_xbrl if hasattr(filing, 'is_xbrl') else False,
+ "size": filing.size if hasattr(filing, 'size') else None,
+ "items": tenq.items if tenq and hasattr(tenq, 'items') else [],
+ "filing_url": filing.filing_url if hasattr(filing, 'filing_url') else None,
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_10q_metadata", str(e), traceback.format_exc()).to_dict()}
+
+
+def search_10q(ticker: str, query: str, max_results: int = 10) -> Dict[str, Any]:
+ """
+ Search for text within 10-Q filing
+
+ Args:
+ ticker: Stock ticker symbol
+ query: Search query string
+ max_results: Maximum number of results
+
+ Returns:
+ Search results with context
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="10-Q").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("search_10q",
+ f"No 10-Q filing found for {ticker}").to_dict()
+ }
+
+ # Perform search
+ if hasattr(filing, 'search'):
+ results = filing.search(query)
+ else:
+ # Fallback: manual search in text
+ text = filing.text()
+ query_lower = query.lower()
+ text_lower = text.lower()
+
+ results = []
+ start = 0
+ while len(results) < max_results:
+ pos = text_lower.find(query_lower, start)
+ if pos == -1:
+ break
+
+ # Get context (100 chars before and after)
+ context_start = max(0, pos - 100)
+ context_end = min(len(text), pos + len(query) + 100)
+ context = text[context_start:context_end]
+
+ results.append({
+ "position": pos,
+ "context": context,
+ "match": text[pos:pos + len(query)]
+ })
+
+ start = pos + len(query)
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "query": query,
+ "results": results[:max_results] if isinstance(results, list) else str(results),
+ "count": len(results) if isinstance(results, list) else 1
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("search_10q", str(e), traceback.format_exc()).to_dict()}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_13f.py b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_13f.py
new file mode 100644
index 000000000..068df1c23
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_13f.py
@@ -0,0 +1,268 @@
+"""
+13F-HR Institutional Holdings Extraction
+=========================================
+
+Extract institutional holdings data from 13F-HR filings including:
+- Portfolio holdings (ticker, shares, value)
+- Fund manager information
+- Quarter-over-quarter changes
+- Top positions
+- Total portfolio value
+"""
+
+from typing import Dict, Any, Optional
+import traceback
+
+try:
+ from edgar import Company
+ EDGAR_AVAILABLE = True
+except ImportError:
+ EDGAR_AVAILABLE = False
+
+from .base import EdgarError, check_edgar_available
+
+
+def get_13f_holdings(ticker: str, quarters: int = 2) -> Dict[str, Any]:
+ """
+ Get institutional holdings from 13F-HR filings
+
+ Args:
+ ticker: Stock ticker symbol
+ quarters: Number of quarters to retrieve
+
+ Returns:
+ Holdings data for specified quarters
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filings = company.get_filings(form="13F-HR")
+
+ if not filings or len(filings) == 0:
+ return {
+ "success": True,
+ "data": [],
+ "count": 0
+ }
+
+ holdings_data = []
+ count = 0
+
+ for filing in filings:
+ if count >= quarters:
+ break
+
+ try:
+ thirteenf = filing.obj()
+
+ if not thirteenf:
+ continue
+
+ # Get holdings
+ holdings_list = []
+ if hasattr(thirteenf, 'holdings'):
+ holdings = thirteenf.holdings
+
+ # Convert to list if needed
+ if hasattr(holdings, 'to_pandas'):
+ df = holdings.to_pandas()
+ holdings_list = df.to_dict('records')
+ elif hasattr(holdings, '__iter__'):
+ holdings_list = list(holdings)
+
+ holdings_data.append({
+ "filing_date": str(filing.filing_date),
+ "report_period": str(thirteenf.report_period) if hasattr(thirteenf, 'report_period') else None,
+ "manager_name": thirteenf.manager_name if hasattr(thirteenf, 'manager_name') else None,
+ "total_value": float(thirteenf.total_value) if hasattr(thirteenf, 'total_value') and thirteenf.total_value else None,
+ "holdings_count": len(holdings_list),
+ "holdings": holdings_list
+ })
+
+ count += 1
+
+ except Exception as e:
+ continue
+
+ return {
+ "success": True,
+ "data": holdings_data,
+ "count": len(holdings_data)
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_13f_holdings", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_13f_top_holdings(ticker: str, top_n: int = 20) -> Dict[str, Any]:
+ """
+ Get top holdings from latest 13F filing
+
+ Args:
+ ticker: Stock ticker symbol (of the fund/institution)
+ top_n: Number of top holdings to return
+
+ Returns:
+ Top N holdings by value
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="13F-HR").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("get_13f_top_holdings",
+ f"No 13F-HR filing found for {ticker}").to_dict()
+ }
+
+ thirteenf = filing.obj()
+
+ if not thirteenf or not hasattr(thirteenf, 'holdings'):
+ return {
+ "error": EdgarError("get_13f_top_holdings",
+ "No holdings data available").to_dict()
+ }
+
+ # Get holdings as dataframe
+ holdings = thirteenf.holdings
+ holdings_list = []
+
+ if hasattr(holdings, 'to_pandas'):
+ df = holdings.to_pandas()
+ # Sort by value and take top N
+ if 'Value' in df.columns or 'value' in df.columns:
+ value_col = 'Value' if 'Value' in df.columns else 'value'
+ df = df.sort_values(by=value_col, ascending=False).head(top_n)
+ holdings_list = df.to_dict('records')
+ elif hasattr(holdings, '__iter__'):
+ holdings_list = list(holdings)[:top_n]
+
+ return {
+ "success": True,
+ "data": {
+ "filing_date": str(filing.filing_date),
+ "report_period": str(thirteenf.report_period) if hasattr(thirteenf, 'report_period') else None,
+ "manager_name": thirteenf.manager_name if hasattr(thirteenf, 'manager_name') else None,
+ "total_value": float(thirteenf.total_value) if hasattr(thirteenf, 'total_value') and thirteenf.total_value else None,
+ "top_holdings": holdings_list,
+ "count": len(holdings_list)
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_13f_top_holdings", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_13f_manager_info(ticker: str) -> Dict[str, Any]:
+ """
+ Get fund manager information from latest 13F
+
+ Args:
+ ticker: Stock ticker symbol (of the fund/institution)
+
+ Returns:
+ Manager information and portfolio summary
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="13F-HR").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("get_13f_manager_info",
+ f"No 13F-HR filing found for {ticker}").to_dict()
+ }
+
+ thirteenf = filing.obj()
+
+ if not thirteenf:
+ return {
+ "error": EdgarError("get_13f_manager_info",
+ "Could not parse 13F filing").to_dict()
+ }
+
+ # Extract manager info
+ manager_info = {
+ "manager_name": thirteenf.manager_name if hasattr(thirteenf, 'manager_name') else None,
+ "report_period": str(thirteenf.report_period) if hasattr(thirteenf, 'report_period') else None,
+ "filing_date": str(filing.filing_date),
+ "total_value": float(thirteenf.total_value) if hasattr(thirteenf, 'total_value') and thirteenf.total_value else None,
+ "total_holdings": thirteenf.total_holdings if hasattr(thirteenf, 'total_holdings') else None,
+ "management_company_name": thirteenf.management_company_name if hasattr(thirteenf, 'management_company_name') else None,
+ }
+
+ # Get portfolio managers if available
+ if hasattr(thirteenf, 'get_portfolio_managers'):
+ try:
+ managers = thirteenf.get_portfolio_managers()
+ manager_info["portfolio_managers"] = managers
+ except:
+ pass
+
+ return {
+ "success": True,
+ "data": manager_info
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_13f_manager_info", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_13f_summary(ticker: str) -> Dict[str, Any]:
+ """
+ Get summary statistics from latest 13F filing
+
+ Args:
+ ticker: Stock ticker symbol (of the fund/institution)
+
+ Returns:
+ Portfolio summary statistics
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="13F-HR").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("get_13f_summary",
+ f"No 13F-HR filing found for {ticker}").to_dict()
+ }
+
+ thirteenf = filing.obj()
+
+ if not thirteenf:
+ return {
+ "error": EdgarError("get_13f_summary",
+ "Could not parse 13F filing").to_dict()
+ }
+
+ summary = {
+ "manager_name": thirteenf.manager_name if hasattr(thirteenf, 'manager_name') else None,
+ "report_period": str(thirteenf.report_period) if hasattr(thirteenf, 'report_period') else None,
+ "filing_date": str(filing.filing_date),
+ "total_value": float(thirteenf.total_value) if hasattr(thirteenf, 'total_value') and thirteenf.total_value else None,
+ "total_holdings": thirteenf.total_holdings if hasattr(thirteenf, 'total_holdings') else 0,
+ }
+
+ # Calculate additional stats from holdings
+ if hasattr(thirteenf, 'holdings'):
+ holdings = thirteenf.holdings
+ if hasattr(holdings, 'to_pandas'):
+ df = holdings.to_pandas()
+
+ if 'Value' in df.columns or 'value' in df.columns:
+ value_col = 'Value' if 'Value' in df.columns else 'value'
+
+ # Top 10 concentration
+ top_10_value = df.nlargest(10, value_col)[value_col].sum()
+ total_value = df[value_col].sum()
+
+ summary["top_10_concentration"] = float(top_10_value / total_value * 100) if total_value > 0 else 0
+ summary["average_position_size"] = float(total_value / len(df)) if len(df) > 0 else 0
+
+ return {
+ "success": True,
+ "data": summary
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_13f_summary", str(e), traceback.format_exc()).to_dict()}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_8k.py b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_8k.py
new file mode 100644
index 000000000..0748a6e17
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_8k.py
@@ -0,0 +1,259 @@
+"""
+8-K Corporate Events Extraction
+================================
+
+Extract corporate events from 8-K filings including:
+- Item 1.01: Entry into Material Agreement
+- Item 2.02: Results of Operations and Financial Condition (Earnings)
+- Item 5.02: Departure/Election of Directors or Officers
+- Item 7.01: Regulation FD Disclosure
+- Item 8.01: Other Events
+- Full text and categorized events
+"""
+
+from typing import Dict, Any, Optional, List
+import traceback
+
+try:
+ from edgar import Company
+ EDGAR_AVAILABLE = True
+except ImportError:
+ EDGAR_AVAILABLE = False
+
+from .base import EdgarError, check_edgar_available
+
+
+def get_latest_8k(ticker: str) -> Dict[str, Any]:
+ """Get latest 8-K filing"""
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filings = company.get_filings(form="8-K")
+
+ if not filings or len(filings) == 0:
+ return {
+ "error": EdgarError("get_latest_8k",
+ f"No 8-K filings found for {ticker}").to_dict()
+ }
+
+ latest = filings.latest(1)
+
+ return {
+ "success": True,
+ "data": {
+ "accession_number": latest.accession_number,
+ "filing_date": str(latest.filing_date),
+ "form": latest.form,
+ "company": latest.company if hasattr(latest, 'company') else ticker,
+ "cik": latest.cik if hasattr(latest, 'cik') else None,
+ "items": latest.items if hasattr(latest, 'items') else [],
+ "filing": latest
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_latest_8k", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_8k_events(ticker: str, limit: int = 30) -> Dict[str, Any]:
+ """
+ Get recent 8-K events with categorization
+
+ Args:
+ ticker: Stock ticker symbol
+ limit: Number of filings to retrieve
+
+ Returns:
+ List of 8-K events with items and dates
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filings = company.get_filings(form="8-K")
+
+ if not filings or len(filings) == 0:
+ return {
+ "success": True,
+ "data": [],
+ "count": 0
+ }
+
+ events = []
+ count = 0
+
+ for filing in filings:
+ if count >= limit:
+ break
+
+ event = {
+ "accession_number": filing.accession_number,
+ "filing_date": str(filing.filing_date),
+ "items": filing.items if hasattr(filing, 'items') else [],
+ "form": filing.form
+ }
+
+ events.append(event)
+ count += 1
+
+ return {
+ "success": True,
+ "data": events,
+ "count": len(events)
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_8k_events", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_8k_events_categorized(ticker: str, limit: int = 30) -> Dict[str, Any]:
+ """
+ Get 8-K events categorized by type
+
+ Args:
+ ticker: Stock ticker symbol
+ limit: Number of filings to retrieve
+
+ Returns:
+ Events grouped by category
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filings = company.get_filings(form="8-K")
+
+ if not filings or len(filings) == 0:
+ return {
+ "success": True,
+ "data": {
+ "earnings": [],
+ "management_changes": [],
+ "agreements": [],
+ "other": []
+ },
+ "count": 0
+ }
+
+ categories = {
+ "earnings": [],
+ "management_changes": [],
+ "agreements": [],
+ "mergers_acquisitions": [],
+ "other": []
+ }
+
+ count = 0
+ for filing in filings:
+ if count >= limit:
+ break
+
+ items = filing.items if hasattr(filing, 'items') else []
+ items_str = ','.join(items) if items else ''
+
+ event = {
+ "accession_number": filing.accession_number,
+ "filing_date": str(filing.filing_date),
+ "items": items
+ }
+
+ # Categorize by item number
+ if '2.02' in items_str: # Results of Operations
+ categories["earnings"].append(event)
+ elif any(x in items_str for x in ['5.02', '5.03']): # Management changes
+ categories["management_changes"].append(event)
+ elif '1.01' in items_str: # Material Agreement
+ categories["agreements"].append(event)
+ elif any(x in items_str for x in ['1.02', '2.01']): # M&A
+ categories["mergers_acquisitions"].append(event)
+ else:
+ categories["other"].append(event)
+
+ count += 1
+
+ return {
+ "success": True,
+ "data": categories,
+ "count": count
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_8k_events_categorized", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_8k_full_text(ticker: str, max_length: Optional[int] = None) -> Dict[str, Any]:
+ """Get full text of latest 8-K"""
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="8-K").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("get_8k_full_text",
+ f"No 8-K filing found for {ticker}").to_dict()
+ }
+
+ text = filing.text() if hasattr(filing, 'text') else str(filing)
+
+ if max_length and len(text) > max_length:
+ text = text[:max_length] + "... (truncated)"
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "accession_number": filing.accession_number,
+ "filing_date": str(filing.filing_date),
+ "items": filing.items if hasattr(filing, 'items') else [],
+ "text": text,
+ "text_length": len(text),
+ "truncated": max_length is not None and len(text) > max_length
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_8k_full_text", str(e), traceback.format_exc()).to_dict()}
+
+
+def search_8k(ticker: str, query: str, max_results: int = 10) -> Dict[str, Any]:
+ """Search within latest 8-K filing"""
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filing = company.get_filings(form="8-K").latest(1)
+
+ if not filing:
+ return {
+ "error": EdgarError("search_8k",
+ f"No 8-K filing found for {ticker}").to_dict()
+ }
+
+ text = filing.text()
+ query_lower = query.lower()
+ text_lower = text.lower()
+
+ results = []
+ start = 0
+ while len(results) < max_results:
+ pos = text_lower.find(query_lower, start)
+ if pos == -1:
+ break
+
+ context_start = max(0, pos - 100)
+ context_end = min(len(text), pos + len(query) + 100)
+ context = text[context_start:context_end]
+
+ results.append({
+ "position": pos,
+ "context": context,
+ "match": text[pos:pos + len(query)]
+ })
+
+ start = pos + len(query)
+
+ return {
+ "success": True,
+ "data": {
+ "ticker": ticker,
+ "query": query,
+ "results": results,
+ "count": len(results)
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("search_8k", str(e), traceback.format_exc()).to_dict()}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_insider.py b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_insider.py
new file mode 100644
index 000000000..f4fdb9771
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/forms_insider.py
@@ -0,0 +1,234 @@
+"""
+Form 4 Insider Transaction Extraction
+======================================
+
+Extract insider trading data from Form 4 filings including:
+- Buy/sell transactions
+- Officer/director information
+- Transaction prices and shares
+- Ownership before/after
+- Derivative vs non-derivative securities
+"""
+
+from typing import Dict, Any, Optional
+import traceback
+
+try:
+ from edgar import Company
+ EDGAR_AVAILABLE = True
+except ImportError:
+ EDGAR_AVAILABLE = False
+
+from .base import EdgarError, check_edgar_available
+
+
+def get_insider_transactions(ticker: str, limit: int = 25) -> Dict[str, Any]:
+ """
+ Get insider transactions (Form 4 filings)
+
+ Args:
+ ticker: Stock ticker symbol
+ limit: Number of transactions to retrieve
+
+ Returns:
+ List of insider transactions with basic info
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filings = company.get_filings(form="4")
+
+ if not filings or len(filings) == 0:
+ return {
+ "success": True,
+ "data": [],
+ "count": 0
+ }
+
+ transactions = []
+ count = 0
+
+ for filing in filings:
+ if count >= limit:
+ break
+
+ try:
+ form4 = filing.obj()
+
+ if form4:
+ transactions.append({
+ "filing_date": str(filing.filing_date),
+ "accession_number": filing.accession_number,
+ "owner": form4.owner.name if hasattr(form4, 'owner') and hasattr(form4.owner, 'name') else None,
+ "is_director": form4.owner.is_director if hasattr(form4, 'owner') and hasattr(form4.owner, 'is_director') else None,
+ "is_officer": form4.owner.is_officer if hasattr(form4, 'owner') and hasattr(form4.owner, 'is_officer') else None,
+ })
+ count += 1
+ except:
+ # Skip if can't parse
+ pass
+
+ return {
+ "success": True,
+ "data": transactions,
+ "count": len(transactions)
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_insider_transactions", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_insider_transactions_detailed(ticker: str, limit: int = 25) -> Dict[str, Any]:
+ """
+ Get detailed insider transactions with full transaction info
+
+ Args:
+ ticker: Stock ticker symbol
+ limit: Number of transactions to retrieve
+
+ Returns:
+ Detailed transaction data including prices, shares, ownership
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filings = company.get_filings(form="4")
+
+ if not filings or len(filings) == 0:
+ return {
+ "success": True,
+ "data": [],
+ "count": 0
+ }
+
+ transactions = []
+ count = 0
+
+ for filing in filings:
+ if count >= limit:
+ break
+
+ try:
+ form4 = filing.obj()
+
+ if not form4:
+ continue
+
+ # Extract owner info
+ owner_info = {
+ "name": form4.owner.name if hasattr(form4, 'owner') and hasattr(form4.owner, 'name') else None,
+ "is_director": form4.owner.is_director if hasattr(form4, 'owner') and hasattr(form4.owner, 'is_director') else False,
+ "is_officer": form4.owner.is_officer if hasattr(form4, 'owner') and hasattr(form4.owner, 'is_officer') else False,
+ "is_ten_percent_owner": form4.owner.is_ten_percent_owner if hasattr(form4, 'owner') and hasattr(form4.owner, 'is_ten_percent_owner') else False,
+ "officer_title": form4.owner.officer_title if hasattr(form4, 'owner') and hasattr(form4.owner, 'officer_title') else None,
+ }
+
+ # Extract transactions
+ txn_data = []
+ if hasattr(form4, 'transactions'):
+ for txn in form4.transactions:
+ txn_info = {
+ "transaction_date": str(txn.transaction_date) if hasattr(txn, 'transaction_date') else None,
+ "transaction_code": txn.transaction_code if hasattr(txn, 'transaction_code') else None,
+ "shares": float(txn.shares) if hasattr(txn, 'shares') and txn.shares else None,
+ "price_per_share": float(txn.price_per_share) if hasattr(txn, 'price_per_share') and txn.price_per_share else None,
+ "transaction_type": "Buy" if hasattr(txn, 'transaction_code') and txn.transaction_code in ['P', 'M'] else "Sell" if hasattr(txn, 'transaction_code') and txn.transaction_code in ['S', 'F'] else "Other",
+ "ownership_form": txn.ownership_form if hasattr(txn, 'ownership_form') else None,
+ "shares_owned_after": float(txn.shares_owned_after) if hasattr(txn, 'shares_owned_after') and txn.shares_owned_after else None,
+ }
+ txn_data.append(txn_info)
+
+ transactions.append({
+ "filing_date": str(filing.filing_date),
+ "accession_number": filing.accession_number,
+ "owner": owner_info,
+ "transactions": txn_data,
+ "transaction_count": len(txn_data)
+ })
+
+ count += 1
+
+ except Exception as e:
+ # Skip problematic filings
+ continue
+
+ return {
+ "success": True,
+ "data": transactions,
+ "count": len(transactions)
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_insider_transactions_detailed", str(e), traceback.format_exc()).to_dict()}
+
+
+def get_insider_summary(ticker: str, limit: int = 50) -> Dict[str, Any]:
+ """
+ Get summary of insider activity (buy vs sell)
+
+ Args:
+ ticker: Stock ticker symbol
+ limit: Number of filings to analyze
+
+ Returns:
+ Summary statistics of insider activity
+ """
+ try:
+ check_edgar_available()
+ company = Company(ticker)
+ filings = company.get_filings(form="4")
+
+ if not filings or len(filings) == 0:
+ return {
+ "success": True,
+ "data": {
+ "total_transactions": 0,
+ "buys": 0,
+ "sells": 0,
+ "buy_volume": 0,
+ "sell_volume": 0
+ }
+ }
+
+ buys = 0
+ sells = 0
+ buy_volume = 0
+ sell_volume = 0
+ count = 0
+
+ for filing in filings:
+ if count >= limit:
+ break
+
+ try:
+ form4 = filing.obj()
+ if not form4 or not hasattr(form4, 'transactions'):
+ continue
+
+ for txn in form4.transactions:
+ if hasattr(txn, 'transaction_code') and hasattr(txn, 'shares'):
+ code = txn.transaction_code
+ shares = float(txn.shares) if txn.shares else 0
+
+ if code in ['P', 'M']: # Purchase
+ buys += 1
+ buy_volume += shares
+ elif code in ['S', 'F']: # Sale
+ sells += 1
+ sell_volume += shares
+
+ count += 1
+ except:
+ continue
+
+ return {
+ "success": True,
+ "data": {
+ "total_transactions": buys + sells,
+ "buys": buys,
+ "sells": sells,
+ "buy_volume": buy_volume,
+ "sell_volume": sell_volume,
+ "net_volume": buy_volume - sell_volume
+ }
+ }
+ except Exception as e:
+ return {"error": EdgarError("get_insider_summary", str(e), traceback.format_exc()).to_dict()}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/main.py b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/main.py
new file mode 100644
index 000000000..e7b900c80
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/mcp/edgar/main.py
@@ -0,0 +1,285 @@
+"""
+Edgar MCP - Main CLI Entry Point
+==================================
+
+Unified command-line interface for all Edgar MCP modules.
+
+Usage:
+ python -m mcp.edgar.main <command> [args...]
+
+Commands are organized by module:
+- base: Configuration and ticker search
+- forms_10k: 10-K annual report extraction
+- forms_10q: 10-Q quarterly report extraction
+- financials: XBRL financial data
+
+Example:
+ python -m mcp.edgar.main 10k_sections AAPL business risk_factors
+"""
+
+import sys
+import json
+from typing import Dict, Any
+
+# Import all modules
+from . import base
+from . import forms_10k
+from . import forms_10q
+from . import forms_8k
+from . import forms_insider
+from . import forms_13f
+from . import financials
+
+
+def execute_command(command: str, args: list) -> Dict[str, Any]:
+ """
+ Execute a command with arguments
+
+ Args:
+ command: Command name
+ args: Command arguments
+
+ Returns:
+ Result dictionary
+ """
+
+ # =========================================================================
+ # BASE COMMANDS - Configuration and Search
+ # =========================================================================
+
+ if command == "set_identity":
+ identity = args[0] if len(args) > 0 else None
+ return base.set_user_identity(identity)
+
+ elif command == "get_identity":
+ return base.get_user_identity()
+
+ elif command == "find_company":
+ query = args[0] if len(args) > 0 else None
+ top_n = int(args[1]) if len(args) > 1 else 10
+ return base.find_company_by_name(query, top_n)
+
+ elif command == "get_company":
+ ticker = args[0] if len(args) > 0 else None
+ return base.get_company_info(ticker)
+
+ elif command == "resolve_ticker":
+ query = args[0] if len(args) > 0 else None
+ ticker = base.resolve_ticker(query)
+ return {"success": True, "ticker": ticker}
+
+ # =========================================================================
+ # 10-K COMMANDS - Annual Reports
+ # =========================================================================
+
+ elif command == "10k_latest":
+ ticker = args[0] if len(args) > 0 else None
+ return forms_10k.get_latest_10k(ticker)
+
+ elif command == "10k_sections":
+ ticker = args[0] if len(args) > 0 else None
+ sections = args[1:] if len(args) > 1 else None
+ return forms_10k.extract_10k_sections(ticker, sections)
+
+ elif command == "10k_full_text":
+ ticker = args[0] if len(args) > 0 else None
+ max_length = int(args[1]) if len(args) > 1 else None
+ return forms_10k.get_10k_full_text(ticker, max_length)
+
+ elif command == "10k_markdown":
+ ticker = args[0] if len(args) > 0 else None
+ return forms_10k.get_10k_markdown(ticker)
+
+ elif command == "10k_search":
+ ticker = args[0] if len(args) > 0 else None
+ query = args[1] if len(args) > 1 else ""
+ max_results = int(args[2]) if len(args) > 2 else 10
+ return forms_10k.search_10k(ticker, query, max_results)
+
+ elif command == "10k_exhibits":
+ ticker = args[0] if len(args) > 0 else None
+ return forms_10k.get_10k_exhibits(ticker)
+
+ elif command == "10k_metadata":
+ ticker = args[0] if len(args) > 0 else None
+ return forms_10k.get_10k_metadata(ticker)
+
+ # =========================================================================
+ # 10-Q COMMANDS - Quarterly Reports
+ # =========================================================================
+
+ elif command == "10q_latest":
+ ticker = args[0] if len(args) > 0 else None
+ return forms_10q.get_latest_10q(ticker)
+
+ elif command == "10q_sections":
+ ticker = args[0] if len(args) > 0 else None
+ sections = args[1:] if len(args) > 1 else None
+ return forms_10q.extract_10q_sections(ticker, sections)
+
+ elif command == "10q_full_text":
+ ticker = args[0] if len(args) > 0 else None
+ max_length = int(args[1]) if len(args) > 1 else None
+ return forms_10q.get_10q_full_text(ticker, max_length)
+
+ elif command == "10q_markdown":
+ ticker = args[0] if len(args) > 0 else None
+ return forms_10q.get_10q_markdown(ticker)
+
+ elif command == "10q_metadata":
+ ticker = args[0] if len(args) > 0 else None
+ return forms_10q.get_10q_metadata(ticker)
+
+ elif command == "10q_search":
+ ticker = args[0] if len(args) > 0 else None
+ query = args[1] if len(args) > 1 else ""
+ max_results = int(args[2]) if len(args) > 2 else 10
+ return forms_10q.search_10q(ticker, query, max_results)
+
+ # =========================================================================
+ # FINANCIALS COMMANDS - XBRL Data
+ # =========================================================================
+
+ elif command == "get_financials":
+ ticker = args[0] if len(args) > 0 else None
+ periods = int(args[1]) if len(args) > 1 else 4
+ annual = args[2].lower() != "false" if len(args) > 2 else True
+ return financials.get_financials(ticker, periods, annual)
+
+ elif command == "get_financial_metrics":
+ ticker = args[0] if len(args) > 0 else None
+ return financials.get_financial_metrics(ticker)
+
+ elif command == "get_xbrl_statements":
+ ticker = args[0] if len(args) > 0 else None
+ form = args[1] if len(args) > 1 else "10-K"
+ return financials.get_xbrl_statements(ticker, form)
+
+ elif command == "get_company_facts":
+ cik = args[0] if len(args) > 0 else None
+ return financials.get_company_facts(cik)
+
+ # =========================================================================
+ # 8-K COMMANDS - Corporate Events
+ # =========================================================================
+
+ elif command == "8k_latest":
+ ticker = args[0] if len(args) > 0 else None
+ return forms_8k.get_latest_8k(ticker)
+
+ elif command == "8k_events":
+ ticker = args[0] if len(args) > 0 else None
+ limit = int(args[1]) if len(args) > 1 else 30
+ return forms_8k.get_8k_events(ticker, limit)
+
+ elif command == "8k_events_categorized":
+ ticker = args[0] if len(args) > 0 else None
+ limit = int(args[1]) if len(args) > 1 else 30
+ return forms_8k.get_8k_events_categorized(ticker, limit)
+
+ elif command == "8k_full_text":
+ ticker = args[0] if len(args) > 0 else None
+ max_length = int(args[1]) if len(args) > 1 else None
+ return forms_8k.get_8k_full_text(ticker, max_length)
+
+ elif command == "8k_search":
+ ticker = args[0] if len(args) > 0 else None
+ query = args[1] if len(args) > 1 else ""
+ max_results = int(args[2]) if len(args) > 2 else 10
+ return forms_8k.search_8k(ticker, query, max_results)
+
+ # =========================================================================
+ # FORM 4 COMMANDS - Insider Transactions
+ # =========================================================================
+
+ elif command == "insider_transactions":
+ ticker = args[0] if len(args) > 0 else None
+ limit = int(args[1]) if len(args) > 1 else 25
+ return forms_insider.get_insider_transactions(ticker, limit)
+
+ elif command == "insider_transactions_detailed":
+ ticker = args[0] if len(args) > 0 else None
+ limit = int(args[1]) if len(args) > 1 else 25
+ return forms_insider.get_insider_transactions_detailed(ticker, limit)
+
+ elif command == "insider_summary":
+ ticker = args[0] if len(args) > 0 else None
+ limit = int(args[1]) if len(args) > 1 else 50
+ return forms_insider.get_insider_summary(ticker, limit)
+
+ # =========================================================================
+ # 13F COMMANDS - Institutional Holdings
+ # =========================================================================
+
+ elif command == "13f_holdings":
+ ticker = args[0] if len(args) > 0 else None
+ quarters = int(args[1]) if len(args) > 1 else 2
+ return forms_13f.get_13f_holdings(ticker, quarters)
+
+ elif command == "13f_top_holdings":
+ ticker = args[0] if len(args) > 0 else None
+ top_n = int(args[1]) if len(args) > 1 else 20
+ return forms_13f.get_13f_top_holdings(ticker, top_n)
+
+ elif command == "13f_manager_info":
+ ticker = args[0] if len(args) > 0 else None
+ return forms_13f.get_13f_manager_info(ticker)
+
+ elif command == "13f_summary":
+ ticker = args[0] if len(args) > 0 else None
+ return forms_13f.get_13f_summary(ticker)
+
+ # Unknown command
+ else:
+ return {
+ "error": {
+ "command": "unknown",
+ "error": f"Unknown command: {command}",
+ "available_commands": {
+ "base": ["set_identity", "get_identity", "find_company", "get_company", "resolve_ticker"],
+ "10k": ["10k_latest", "10k_sections", "10k_full_text", "10k_markdown", "10k_search", "10k_exhibits", "10k_metadata"],
+ "10q": ["10q_latest", "10q_sections", "10q_full_text", "10q_markdown", "10q_metadata", "10q_search"],
+ "8k": ["8k_latest", "8k_events", "8k_events_categorized", "8k_full_text", "8k_search"],
+ "insider": ["insider_transactions", "insider_transactions_detailed", "insider_summary"],
+ "13f": ["13f_holdings", "13f_top_holdings", "13f_manager_info", "13f_summary"],
+ "financials": ["get_financials", "get_financial_metrics", "get_xbrl_statements", "get_company_facts"]
+ }
+ }
+ }
+
+
+def main():
+ """Main CLI entry point"""
+ if len(sys.argv) < 2:
+ print(json.dumps({
+ "error": "Usage: python -m mcp.edgar.main <command> [args...]",
+ "examples": [
+ "python -m mcp.edgar.main find_company Apple",
+ "python -m mcp.edgar.main 10k_sections AAPL business risk_factors",
+ "python -m mcp.edgar.main 10q_sections MSFT part_i_item_2",
+ "python -m mcp.edgar.main get_financials TSLA 4 true",
+ ],
+ "command_groups": {
+ "base": "Configuration and company search",
+ "10k": "10-K annual report extraction",
+ "10q": "10-Q quarterly report extraction",
+ "financials": "XBRL financial data"
+ }
+ }, indent=2))
+ sys.exit(1)
+
+ command = sys.argv[1]
+ args = sys.argv[2:]
+
+ # Initialize Edgar
+ base.initialize_edgar()
+
+ # Execute command
+ result = execute_command(command, args)
+
+ # Output JSON result
+ print(json.dumps(result, indent=2, default=str))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
index 844f35d65..29b867b5a 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
@@ -248,8 +248,9 @@ fn get_agent_script_path(agent_type: &str) -> Option<&'static str> {
"macro_cycle" | "central_bank" | "behavioral" | "institutional_flow" |
"innovation" | "geopolitical" | "currency" | "supply_chain" |
"sentiment" | "regulatory" | "bridgewater" | "citadel" |
- "renaissance" | "two_sigma" | "de_shaw" | "elliott" |
+ "two_sigma" | "de_shaw" | "elliott" |
"pershing_square" | "arq_capital" => Some("agents/hedgeFundAgents/hedge_fund_agent_cli.py"),
+ "renaissance" | "renaissance_technologies" | "rentech" => Some("agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/rentech_cli.py"),
"capitalism" => Some("agents/EconomicAgents/capitalism_agent_cli.py"),
"keynesian" => Some("agents/EconomicAgents/keynesian_agent_cli.py"),
"neoliberal" => Some("agents/EconomicAgents/neoliberal_agent_cli.py"),
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/ai_agents.rs b/fincept-terminal-desktop/src-tauri/src/commands/ai_agents.rs
index b4f6986ef..026bcffe2 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/ai_agents.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/ai_agents.rs
@@ -252,11 +252,15 @@ pub async fn run_renaissance_agent(
market_data: String,
quant_params: Option<String>,
) -> Result<String, String> {
- let mut args = vec!["analyze".to_string(), market_data];
- if let Some(qp) = quant_params {
- args.push(qp);
- }
- python::execute(&app, "agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/renaissance_technologies_agent.py", args).await
+ // Prepare signal data JSON
+ let signal_data = if let Some(qp) = quant_params {
+ format!(r#"{{"market_data": {}, "params": {}}}"#, market_data, qp)
+ } else {
+ format!(r#"{{"market_data": {}}}"#, market_data)
+ };
+
+ let args = vec!["analyze".to_string(), signal_data];
+ python::execute(&app, "agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/rentech_cli.py", args).await
}
#[tauri::command]
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/edgar.rs b/fincept-terminal-desktop/src-tauri/src/commands/edgar.rs
index d350eac71..e56d557df 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/edgar.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/edgar.rs
@@ -13,5 +13,5 @@ pub async fn execute_edgar_command(
cmd_args.extend(args);
- python::execute(&app, "edgar_tools.py", cmd_args).await
+ python::execute(&app, "edgar_mcp.py", cmd_args).await
}
diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rs
index 21e96e4a9..ba1fc9aea 100644
--- a/fincept-terminal-desktop/src-tauri/src/lib.rs
+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs
@@ -99,6 +99,13 @@ fn spawn_mcp_server(
(cmd, args.clone())
}
}
+ } else if command == "uvx" {
+ // uvx is from the uv Python package manager
+ #[cfg(target_os = "windows")]
+ let cmd = "uvx.exe".to_string();
+ #[cfg(not(target_os = "windows"))]
+ let cmd = "uvx".to_string();
+ (cmd, args.clone())
} else {
// Fix command for Windows - node/python need .exe extension
#[cfg(target_os = "windows")]
@@ -213,8 +220,10 @@ fn send_mcp_request(
state: tauri::State<MCPState>,
server_id: String,
request: String,
+ timeout_secs: Option<u64>,
) -> Result<String, String> {
- println!("[Tauri] Sending request to server {}: {}", server_id, request);
+ let timeout = timeout_secs.unwrap_or(30);
+ println!("[Tauri] Sending request to server {} (timeout: {}s): {}", server_id, timeout, request);
let mut processes = state.processes.lock().unwrap();
@@ -228,8 +237,8 @@ fn send_mcp_request(
.map_err(|e| format!("Failed to flush stdin: {}", e))?;
}
- // Wait for response with timeout (30 seconds for initial package download)
- match mcp_process.response_rx.recv_timeout(Duration::from_secs(30)) {
+ // Wait for response with configurable timeout
+ match mcp_process.response_rx.recv_timeout(Duration::from_secs(timeout)) {
Ok(response) => {
Ok(response)
}
diff --git a/fincept-terminal-desktop/src-tauri/tauri.conf.json b/fincept-terminal-desktop/src-tauri/tauri.conf.json
index c3f9712d1..f90cccad9 100644
--- a/fincept-terminal-desktop/src-tauri/tauri.conf.json
+++ b/fincept-terminal-desktop/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "FinceptTerminal",
- "version": "3.2.1",
+ "version": "3.3.0",
"identifier": "com.fincept.terminal",
"build": {
"beforeDevCommand": "bun run dev",
diff --git a/fincept-terminal-desktop/src/components/common/ChatBubble.tsx b/fincept-terminal-desktop/src/components/common/ChatBubble.tsx
new file mode 100644
index 000000000..e3a4c56b1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/common/ChatBubble.tsx
@@ -0,0 +1,688 @@
+// Chat Bubble - Floating AI assistant with voice mode
+// Syncs with AI Chat tab, connected to Internal MCP
+// Voice settings configured in Settings > AI Chat Bubble
+// Supports multiple TTS providers: Browser, Edge TTS, ElevenLabs, OpenAI
+
+import React, { useReducer, useEffect, useRef, useCallback } from 'react';
+import { X, Send, Plus, Minimize2, Bot, User, Mic, MicOff, Volume2, VolumeX, Square } from 'lucide-react';
+import { sqliteService, ChatMessage } from '@/services/core/sqliteService';
+import { llmApiService } from '@/services/chat/llmApi';
+import { sanitizeInput } from '@/services/core/validators';
+import MarkdownRenderer from '@/components/common/MarkdownRenderer';
+import { invoke } from '@tauri-apps/api/core';
+import { ttsService, TTSProvider, TTSConfig } from '@/services/voice/ttsService';
+
+const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ MUTED: '#4A4A4A',
+};
+
+// State types
+interface BubbleState {
+ isOpen: boolean;
+ messages: ChatMessage[];
+ input: string;
+ isTyping: boolean;
+ streamingContent: string;
+ currentSessionUuid: string | null;
+ unreadCount: number;
+ isListening: boolean;
+ isSpeaking: boolean;
+ voiceMode: boolean;
+ activeToolCalls: Array<{ name: string; status: string }>;
+ // TTS settings
+ ttsProvider: TTSProvider;
+ selectedVoice: string;
+ speechRate: number;
+ autoStartVoice: boolean;
+ elevenLabsApiKey: string;
+ openaiApiKey: string;
+}
+
+type BubbleAction =
+ | { type: 'SET_OPEN'; payload: boolean }
+ | { type: 'SET_MESSAGES'; payload: ChatMessage[] }
+ | { type: 'ADD_MESSAGE'; payload: ChatMessage }
+ | { type: 'SET_INPUT'; payload: string }
+ | { type: 'SET_TYPING'; payload: boolean }
+ | { type: 'SET_STREAMING'; payload: string }
+ | { type: 'SET_SESSION'; payload: string | null }
+ | { type: 'SET_UNREAD'; payload: number }
+ | { type: 'SET_LISTENING'; payload: boolean }
+ | { type: 'SET_SPEAKING'; payload: boolean }
+ | { type: 'SET_VOICE_MODE'; payload: boolean }
+ | { type: 'SET_TOOL_CALLS'; payload: Array<{ name: string; status: string }> }
+ | { type: 'SET_TTS_SETTINGS'; payload: { provider: TTSProvider; voice: string; rate: number; autoStart: boolean; elevenLabsKey: string; openaiKey: string } }
+ | { type: 'RESET_CHAT' };
+
+const initialState: BubbleState = {
+ isOpen: false,
+ messages: [],
+ input: '',
+ isTyping: false,
+ streamingContent: '',
+ currentSessionUuid: null,
+ unreadCount: 0,
+ isListening: false,
+ isSpeaking: false,
+ voiceMode: false,
+ activeToolCalls: [],
+ ttsProvider: 'browser',
+ selectedVoice: '',
+ speechRate: 1.4,
+ autoStartVoice: false,
+ elevenLabsApiKey: '',
+ openaiApiKey: '',
+};
+
+function bubbleReducer(state: BubbleState, action: BubbleAction): BubbleState {
+ switch (action.type) {
+ case 'SET_OPEN': return { ...state, isOpen: action.payload, unreadCount: action.payload ? 0 : state.unreadCount };
+ case 'SET_MESSAGES': return { ...state, messages: action.payload };
+ case 'ADD_MESSAGE': return { ...state, messages: [...state.messages, action.payload] };
+ case 'SET_INPUT': return { ...state, input: action.payload };
+ case 'SET_TYPING': return { ...state, isTyping: action.payload };
+ case 'SET_STREAMING': return { ...state, streamingContent: action.payload };
+ case 'SET_SESSION': return { ...state, currentSessionUuid: action.payload };
+ case 'SET_UNREAD': return { ...state, unreadCount: action.payload };
+ case 'SET_LISTENING': return { ...state, isListening: action.payload };
+ case 'SET_SPEAKING': return { ...state, isSpeaking: action.payload };
+ case 'SET_VOICE_MODE': return { ...state, voiceMode: action.payload };
+ case 'SET_TOOL_CALLS': return { ...state, activeToolCalls: action.payload };
+ case 'SET_TTS_SETTINGS': return { ...state, ttsProvider: action.payload.provider, selectedVoice: action.payload.voice, speechRate: action.payload.rate, autoStartVoice: action.payload.autoStart, elevenLabsApiKey: action.payload.elevenLabsKey, openaiApiKey: action.payload.openaiKey };
+ case 'RESET_CHAT': return { ...state, messages: [], currentSessionUuid: null, input: '' };
+ default: return state;
+ }
+}
+
+interface ChatBubbleProps {
+ onNavigateToTab?: (tabName: string) => void;
+}
+
+const ChatBubble: React.FC<ChatBubbleProps> = ({ onNavigateToTab }) => {
+ const [state, dispatch] = useReducer(bubbleReducer, initialState);
+ const { isOpen, messages, input, isTyping, streamingContent, currentSessionUuid, unreadCount, isListening, isSpeaking, voiceMode, activeToolCalls, ttsProvider, selectedVoice, speechRate, autoStartVoice, elevenLabsApiKey, openaiApiKey } = state;
+
+ const messagesEndRef = useRef<HTMLDivElement>(null);
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+ const streamedContentRef = useRef('');
+ const recognitionRef = useRef<any>(null);
+ const finalTranscriptRef = useRef('');
+
+ // CRITICAL: Use refs for voice state to avoid stale closures
+ const voiceModeRef = useRef(false);
+ const isListeningRef = useRef(false);
+ const isSpeakingRef = useRef(false);
+ const isTypingRef = useRef(false);
+ const sessionUuidRef = useRef<string | null>(null);
+ const messagesRef = useRef<ChatMessage[]>([]);
+ // TTS settings refs
+ const ttsProviderRef = useRef<TTSProvider>('browser');
+ const selectedVoiceRef = useRef('');
+ const speechRateRef = useRef(1.4);
+ const elevenLabsApiKeyRef = useRef('');
+ const openaiApiKeyRef = useRef('');
+
+ // Keep refs in sync with state
+ useEffect(() => { voiceModeRef.current = voiceMode; }, [voiceMode]);
+ useEffect(() => { isListeningRef.current = isListening; }, [isListening]);
+ useEffect(() => { isSpeakingRef.current = isSpeaking; }, [isSpeaking]);
+ useEffect(() => { isTypingRef.current = isTyping; }, [isTyping]);
+ useEffect(() => { sessionUuidRef.current = currentSessionUuid; }, [currentSessionUuid]);
+ useEffect(() => { messagesRef.current = messages; }, [messages]);
+ useEffect(() => { ttsProviderRef.current = ttsProvider; }, [ttsProvider]);
+ useEffect(() => { selectedVoiceRef.current = selectedVoice; }, [selectedVoice]);
+ useEffect(() => { speechRateRef.current = speechRate; }, [speechRate]);
+ useEffect(() => { elevenLabsApiKeyRef.current = elevenLabsApiKey; }, [elevenLabsApiKey]);
+ useEffect(() => { openaiApiKeyRef.current = openaiApiKey; }, [openaiApiKey]);
+
+ // Load session and settings
+ useEffect(() => {
+ const load = async () => {
+ await sqliteService.initialize();
+
+ // Load chat session
+ const sessions = await sqliteService.getChatSessions(1);
+ if (sessions.length > 0) {
+ dispatch({ type: 'SET_SESSION', payload: sessions[0].session_uuid });
+ const msgs = await sqliteService.getChatMessages(sessions[0].session_uuid);
+ dispatch({ type: 'SET_MESSAGES', payload: msgs.slice(-50) });
+ }
+
+ // Load TTS settings from DB
+ try {
+ const [provider, voice, rate, autoVoice, elevenKey, openaiKey] = await Promise.all([
+ invoke<string | null>('db_get_setting', { key: 'chat_bubble_tts_provider' }),
+ invoke<string | null>('db_get_setting', { key: 'chat_bubble_voice' }),
+ invoke<string | null>('db_get_setting', { key: 'chat_bubble_speech_rate' }),
+ invoke<string | null>('db_get_setting', { key: 'chat_bubble_auto_voice' }),
+ invoke<string | null>('db_get_setting', { key: 'elevenlabs_api_key' }),
+ invoke<string | null>('db_get_setting', { key: 'openai_tts_api_key' }),
+ ]);
+
+ dispatch({
+ type: 'SET_TTS_SETTINGS',
+ payload: {
+ provider: (provider as TTSProvider) || 'browser',
+ voice: voice || '',
+ rate: rate ? parseFloat(rate) : 1.4,
+ autoStart: autoVoice === 'true',
+ elevenLabsKey: elevenKey || '',
+ openaiKey: openaiKey || '',
+ }
+ });
+ } catch (error) {
+ console.error('[ChatBubble] Failed to load TTS settings:', error);
+ }
+ };
+ load();
+ }, []);
+
+ // Check session exists when opening
+ useEffect(() => {
+ if (isOpen && currentSessionUuid) {
+ sqliteService.getChatMessages(currentSessionUuid).then(msgs => {
+ if (msgs.length === 0) {
+ dispatch({ type: 'RESET_CHAT' });
+ } else {
+ dispatch({ type: 'SET_MESSAGES', payload: msgs.slice(-50) });
+ }
+ });
+ }
+ }, [isOpen, currentSessionUuid]);
+
+ // Auto-scroll
+ useEffect(() => {
+ messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
+ }, [messages, streamingContent]);
+
+ // Create session
+ const createSession = async (): Promise<string | null> => {
+ try {
+ const session = await sqliteService.createChatSession(`Chat ${new Date().toLocaleTimeString()}`);
+ dispatch({ type: 'SET_SESSION', payload: session.session_uuid });
+ dispatch({ type: 'SET_MESSAGES', payload: [] });
+ return session.session_uuid;
+ } catch { return null; }
+ };
+
+ // ttsService handles all voice management internally
+
+ // Start listening - uses refs to avoid stale closures
+ const startListening = useCallback(() => {
+ console.log('[Voice] startListening called');
+
+ const SR = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
+ if (!SR) {
+ console.error('[Voice] SpeechRecognition not supported');
+ return;
+ }
+
+ if (isListeningRef.current || isSpeakingRef.current) return;
+
+ const recognition = new SR();
+ recognition.continuous = false;
+ recognition.interimResults = true;
+ recognition.lang = 'en-US';
+ recognition.maxAlternatives = 1;
+ finalTranscriptRef.current = '';
+
+ recognition.onstart = () => {
+ console.log('[Voice] Recognition started');
+ isListeningRef.current = true;
+ dispatch({ type: 'SET_LISTENING', payload: true });
+ };
+
+ recognition.onend = () => {
+ console.log('[Voice] Recognition ended, transcript:', finalTranscriptRef.current, 'voiceMode:', voiceModeRef.current);
+ isListeningRef.current = false;
+ dispatch({ type: 'SET_LISTENING', payload: false });
+
+ const text = finalTranscriptRef.current.trim();
+
+ // Only auto-send if voice mode is active
+ if (voiceModeRef.current) {
+ if (text) {
+ dispatch({ type: 'SET_INPUT', payload: '' });
+ sendMessageDirect(text);
+ } else {
+ // No speech detected, restart listening in voice mode
+ setTimeout(() => {
+ if (voiceModeRef.current && !isSpeakingRef.current && !isTypingRef.current) {
+ startListening();
+ }
+ }, 500);
+ }
+ }
+ // If voice mode is OFF, just leave the text in the input field - user can manually send
+ };
+
+ recognition.onerror = (e: any) => {
+ console.error('[Voice] Recognition error:', e.error);
+ isListeningRef.current = false;
+ dispatch({ type: 'SET_LISTENING', payload: false });
+
+ // Only auto-restart if voice mode is active
+ if (e.error === 'no-speech' && voiceModeRef.current) {
+ setTimeout(() => {
+ if (voiceModeRef.current && !isSpeakingRef.current && !isTypingRef.current) {
+ startListening();
+ }
+ }, 500);
+ }
+ };
+
+ recognition.onresult = (e: any) => {
+ let final = '';
+ let interim = '';
+ for (let i = 0; i < e.results.length; i++) {
+ const transcript = e.results[i][0].transcript;
+ if (e.results[i].isFinal) {
+ final += transcript;
+ } else {
+ interim += transcript;
+ }
+ }
+ // Remove trailing period that speech recognition often adds
+ if (final) {
+ final = final.replace(/\.\s*$/, '').trim();
+ finalTranscriptRef.current = final;
+ }
+ if (interim) {
+ interim = interim.replace(/\.\s*$/, '').trim();
+ }
+ dispatch({ type: 'SET_INPUT', payload: final || interim });
+ };
+
+ recognitionRef.current = recognition;
+
+ try {
+ recognition.start();
+ } catch (err) {
+ console.error('[Voice] Failed to start recognition:', err);
+ }
+ }, []);
+
+ // Direct send message - doesn't depend on state
+ const sendMessageDirect = useCallback(async (text: string) => {
+ const sanitized = sanitizeInput(text).trim();
+ if (!sanitized || isTypingRef.current) return;
+
+ let sessionUuid = sessionUuidRef.current;
+ if (!sessionUuid) {
+ const session = await sqliteService.createChatSession(`Chat ${new Date().toLocaleTimeString()}`);
+ sessionUuid = session.session_uuid;
+ dispatch({ type: 'SET_SESSION', payload: sessionUuid });
+ dispatch({ type: 'SET_MESSAGES', payload: [] });
+ }
+
+ isTypingRef.current = true;
+ dispatch({ type: 'SET_TYPING', payload: true });
+ dispatch({ type: 'SET_STREAMING', payload: '' });
+ streamedContentRef.current = '';
+
+ try {
+ const userMsg = await sqliteService.addChatMessage({ session_uuid: sessionUuid, role: 'user', content: sanitized });
+ dispatch({ type: 'ADD_MESSAGE', payload: userMsg });
+
+ const { mcpToolService } = await import('@/services/mcp/mcpToolService');
+ const tools = await mcpToolService.getAllTools();
+ const history = messagesRef.current.slice(-10).map(m => ({ role: m.role as 'user' | 'assistant', content: m.content }));
+
+ const onStream = (chunk: string) => {
+ streamedContentRef.current += chunk;
+ dispatch({ type: 'SET_STREAMING', payload: streamedContentRef.current });
+ };
+
+ const response = tools.length > 0
+ ? await llmApiService.chatWithTools(sanitized, history, tools, onStream, async () => {})
+ : await llmApiService.chat(sanitized, history, onStream);
+
+ const content = response.content || streamedContentRef.current || '(No response)';
+ const assistantMsg = await sqliteService.addChatMessage({ session_uuid: sessionUuid, role: 'assistant', content });
+ dispatch({ type: 'ADD_MESSAGE', payload: assistantMsg });
+
+ isTypingRef.current = false;
+ dispatch({ type: 'SET_TYPING', payload: false });
+ dispatch({ type: 'SET_STREAMING', payload: '' });
+
+ // Text-to-speech in voice mode using ttsService
+ if (voiceModeRef.current && content) {
+ isSpeakingRef.current = true;
+ dispatch({ type: 'SET_SPEAKING', payload: true });
+
+ try {
+ const ttsConfig: TTSConfig = {
+ provider: ttsProviderRef.current,
+ voiceId: selectedVoiceRef.current,
+ rate: speechRateRef.current,
+ elevenLabsApiKey: elevenLabsApiKeyRef.current || undefined,
+ openaiApiKey: openaiApiKeyRef.current || undefined,
+ };
+
+ await ttsService.speak(content, ttsConfig);
+
+ isSpeakingRef.current = false;
+ dispatch({ type: 'SET_SPEAKING', payload: false });
+
+ // Auto-restart listening after speech completes
+ if (voiceModeRef.current) {
+ setTimeout(() => {
+ if (voiceModeRef.current && !isListeningRef.current && !isSpeakingRef.current) {
+ startListening();
+ }
+ }, 400);
+ }
+ } catch (error) {
+ console.error('[TTS] Error:', error);
+ isSpeakingRef.current = false;
+ dispatch({ type: 'SET_SPEAKING', payload: false });
+
+ // Still restart listening even if TTS fails
+ if (voiceModeRef.current) {
+ setTimeout(() => startListening(), 400);
+ }
+ }
+ }
+ } catch (error) {
+ console.error('[Chat] Error:', error);
+ if (sessionUuid) {
+ const errorMsg = await sqliteService.addChatMessage({ session_uuid: sessionUuid, role: 'assistant', content: `Error: ${error}` });
+ dispatch({ type: 'ADD_MESSAGE', payload: errorMsg });
+ }
+ isTypingRef.current = false;
+ dispatch({ type: 'SET_TYPING', payload: false });
+ dispatch({ type: 'SET_STREAMING', payload: '' });
+
+ if (voiceModeRef.current) setTimeout(() => startListening(), 400);
+ }
+ }, [startListening]);
+
+ // Toggle voice mode
+ const toggleVoiceMode = useCallback(() => {
+ if (!voiceModeRef.current) {
+ voiceModeRef.current = true;
+ dispatch({ type: 'SET_VOICE_MODE', payload: true });
+ setTimeout(() => {
+ if (voiceModeRef.current && !isListeningRef.current && !isSpeakingRef.current) {
+ startListening();
+ }
+ }, 300);
+ } else {
+ voiceModeRef.current = false;
+ if (recognitionRef.current) {
+ try { recognitionRef.current.abort(); } catch {}
+ }
+ ttsService.stop(); // Stop any ongoing TTS
+ isListeningRef.current = false;
+ isSpeakingRef.current = false;
+ dispatch({ type: 'SET_VOICE_MODE', payload: false });
+ dispatch({ type: 'SET_LISTENING', payload: false });
+ dispatch({ type: 'SET_SPEAKING', payload: false });
+ }
+ }, [startListening]);
+
+ // Toggle mic (manual mode)
+ const toggleMic = useCallback(() => {
+ if (isListeningRef.current) {
+ if (recognitionRef.current) {
+ try { recognitionRef.current.stop(); } catch {}
+ }
+ } else {
+ startListening();
+ }
+ }, [startListening]);
+
+ // Stop speech and allow new query
+ const stopSpeech = useCallback(() => {
+ console.log('[Voice] Stopping speech');
+ ttsService.stop();
+ isSpeakingRef.current = false;
+ dispatch({ type: 'SET_SPEAKING', payload: false });
+
+ // Restart listening so user can provide new query
+ if (voiceModeRef.current) {
+ setTimeout(() => {
+ if (voiceModeRef.current && !isListeningRef.current && !isSpeakingRef.current && !isTypingRef.current) {
+ startListening();
+ }
+ }, 200);
+ }
+ }, [startListening]);
+
+ // Handle send button
+ const handleSend = useCallback(() => {
+ const text = input.trim();
+ if (text && !isTyping) {
+ dispatch({ type: 'SET_INPUT', payload: '' });
+ sendMessageDirect(text);
+ }
+ }, [input, isTyping, sendMessageDirect]);
+
+ // Handle enter key
+ const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ handleSend();
+ }
+ }, [handleSend]);
+
+ // Handle open - auto-start voice if enabled
+ const handleOpen = useCallback(() => {
+ dispatch({ type: 'SET_OPEN', payload: true });
+ if (autoStartVoice && !voiceModeRef.current) {
+ setTimeout(() => toggleVoiceMode(), 500);
+ }
+ }, [autoStartVoice, toggleVoiceMode]);
+
+ return (
+ <>
+ <style>{`
+ @keyframes morphGlow {
+ 0%, 100% { box-shadow: 0 0 20px ${FINCEPT.ORANGE}40, inset 0 0 15px ${FINCEPT.ORANGE}30; }
+ 50% { box-shadow: 0 0 30px ${FINCEPT.ORANGE}60, inset 0 0 25px ${FINCEPT.ORANGE}50; transform: scale(1.05); }
+ }
+ @keyframes pulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.1); } }
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
+ .bubble-scroll::-webkit-scrollbar { width: 4px; }
+ .bubble-scroll::-webkit-scrollbar-thumb { background: ${FINCEPT.BORDER}; border-radius: 2px; }
+ `}</style>
+
+ {/* Chat Panel */}
+ {isOpen && (
+ <div style={{
+ position: 'fixed', bottom: '100px', right: '20px', width: '380px', height: '420px',
+ backgroundColor: FINCEPT.DARK_BG, border: `1px solid ${FINCEPT.ORANGE}`, borderRadius: '8px',
+ display: 'flex', flexDirection: 'column', zIndex: 9999, animation: 'slideUp 0.25s ease-out',
+ boxShadow: `0 8px 32px ${FINCEPT.DARK_BG}CC`, fontFamily: '"IBM Plex Mono", monospace', fontSize: '10px',
+ }}>
+ {/* Header */}
+ <div style={{ padding: '10px 12px', backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.ORANGE}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Bot size={14} color={FINCEPT.ORANGE} />
+ <span style={{ color: FINCEPT.ORANGE, fontWeight: 700 }}>FINCEPT AI</span>
+ </div>
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <button onClick={toggleVoiceMode} style={{ background: voiceMode ? `${FINCEPT.GREEN}20` : 'transparent', border: `1px solid ${voiceMode ? FINCEPT.GREEN : FINCEPT.BORDER}`, color: voiceMode ? FINCEPT.GREEN : FINCEPT.GRAY, padding: '4px 8px', borderRadius: '2px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '4px', fontSize: '8px', fontWeight: 700 }} title="Voice Mode">
+ {voiceMode ? <Volume2 size={10} /> : <VolumeX size={10} />} VOICE
+ </button>
+ <button onClick={() => createSession()} style={{ background: 'transparent', border: `1px solid ${FINCEPT.BORDER}`, color: FINCEPT.GRAY, padding: '4px 8px', borderRadius: '2px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '4px', fontSize: '8px', fontWeight: 700 }} title="New Chat">
+ <Plus size={10} /> NEW
+ </button>
+ <button onClick={() => dispatch({ type: 'SET_OPEN', payload: false })} style={{ background: 'transparent', border: 'none', color: FINCEPT.GRAY, padding: '4px', cursor: 'pointer' }} title="Minimize">
+ <Minimize2 size={14} />
+ </button>
+ </div>
+ </div>
+
+ {/* Messages */}
+ <div className="bubble-scroll" style={{ flex: 1, overflow: 'auto', padding: '12px', backgroundColor: FINCEPT.PANEL_BG }}>
+ {messages.length === 0 && !streamingContent ? (
+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', color: FINCEPT.MUTED, textAlign: 'center' }}>
+ <Bot size={28} style={{ marginBottom: '10px', opacity: 0.6 }} />
+ <div style={{ fontWeight: 700, color: FINCEPT.GRAY }}>How can I help?</div>
+ <div style={{ fontSize: '9px', marginTop: '4px' }}>Ask me anything about markets or trading.</div>
+ </div>
+ ) : (
+ <>
+ {messages.map((msg) => (
+ <div key={msg.id} style={{ marginBottom: '10px', display: 'flex', flexDirection: 'column', alignItems: msg.role === 'user' ? 'flex-end' : 'flex-start' }}>
+ <div style={{ maxWidth: '90%', padding: '8px 10px', backgroundColor: msg.role === 'user' ? `${FINCEPT.ORANGE}20` : FINCEPT.DARK_BG, border: `1px solid ${msg.role === 'user' ? FINCEPT.ORANGE : FINCEPT.BORDER}`, borderRadius: '4px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '4px', opacity: 0.7 }}>
+ {msg.role === 'user' ? <User size={8} /> : <Bot size={8} />}
+ <span style={{ fontSize: '8px', fontWeight: 700 }}>{msg.role === 'user' ? 'YOU' : 'AI'}</span>
+ </div>
+ {msg.role === 'assistant' ? <MarkdownRenderer content={msg.content} /> : <div style={{ color: FINCEPT.WHITE, lineHeight: 1.4, whiteSpace: 'pre-wrap' }}>{msg.content}</div>}
+ </div>
+ </div>
+ ))}
+ {(streamingContent || isTyping) && (
+ <div style={{ marginBottom: '10px' }}>
+ <div style={{ maxWidth: '90%', padding: '8px 10px', backgroundColor: FINCEPT.DARK_BG, border: `1px solid ${FINCEPT.ORANGE}`, borderRadius: '4px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '4px' }}>
+ <Bot size={8} />
+ <span style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.ORANGE }}>TYPING...</span>
+ </div>
+ {streamingContent && <div style={{ color: FINCEPT.WHITE }}>{streamingContent}<span style={{ color: FINCEPT.ORANGE, animation: 'pulse 0.5s infinite' }}>▊</span></div>}
+ </div>
+ </div>
+ )}
+ <div ref={messagesEndRef} />
+ </>
+ )}
+ </div>
+
+ {/* Input */}
+ <div style={{ padding: '10px 12px', backgroundColor: FINCEPT.HEADER_BG, borderTop: `1px solid ${FINCEPT.BORDER}`, display: 'flex', gap: '8px' }}>
+ <textarea ref={inputRef} value={input} onChange={(e) => dispatch({ type: 'SET_INPUT', payload: e.target.value })} onKeyDown={handleKeyDown} placeholder={voiceMode ? "Voice mode active - speak to send" : "Ask anything..."} style={{ flex: 1, padding: '8px', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.WHITE, border: `1px solid ${isListening ? FINCEPT.GREEN : FINCEPT.BORDER}`, borderRadius: '4px', fontSize: '10px', fontFamily: '"IBM Plex Mono", monospace', resize: 'none', height: '36px', outline: 'none' }} />
+ <button onClick={toggleMic} style={{ padding: '8px', backgroundColor: isListening ? FINCEPT.RED : 'transparent', color: isListening ? FINCEPT.WHITE : FINCEPT.GRAY, border: `1px solid ${isListening ? FINCEPT.RED : FINCEPT.BORDER}`, borderRadius: '4px', cursor: 'pointer', animation: isListening ? 'pulse 1s infinite' : 'none' }} title={isListening ? 'Stop' : 'Voice input'}>
+ {isListening ? <MicOff size={14} /> : <Mic size={14} />}
+ </button>
+ <button id="chat-bubble-send-btn" onClick={handleSend} disabled={!input.trim() || isTyping} style={{ padding: '8px 12px', backgroundColor: input.trim() && !isTyping ? FINCEPT.ORANGE : FINCEPT.MUTED, color: FINCEPT.DARK_BG, border: 'none', borderRadius: '4px', cursor: input.trim() && !isTyping ? 'pointer' : 'not-allowed', opacity: input.trim() && !isTyping ? 1 : 0.5 }}>
+ <Send size={14} />
+ </button>
+ </div>
+
+ {/* Voice Status Bar */}
+ {voiceMode && (
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: isListening ? `${FINCEPT.GREEN}15` : isSpeaking ? `${FINCEPT.ORANGE}15` : `${FINCEPT.GRAY}10`,
+ borderTop: `1px solid ${isListening ? FINCEPT.GREEN : isSpeaking ? FINCEPT.ORANGE : FINCEPT.GRAY}40`,
+ display: 'flex',
+ justifyContent: 'center',
+ alignItems: 'center',
+ gap: '8px',
+ fontSize: '9px',
+ color: isListening ? FINCEPT.GREEN : isSpeaking ? FINCEPT.ORANGE : FINCEPT.GRAY,
+ fontWeight: 700
+ }}>
+ {isSpeaking ? (
+ <>
+ <Volume2 size={12} style={{ animation: 'pulse 0.5s infinite' }} /> AI SPEAKING...
+ <button
+ onClick={stopSpeech}
+ style={{
+ marginLeft: '8px',
+ padding: '4px 8px',
+ backgroundColor: FINCEPT.RED,
+ color: FINCEPT.WHITE,
+ border: 'none',
+ borderRadius: '2px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ fontSize: '8px',
+ fontWeight: 700
+ }}
+ title="Stop speaking and ask new query"
+ >
+ <Square size={8} fill={FINCEPT.WHITE} /> STOP
+ </button>
+ </>
+ ) : isListening ? (
+ <><Mic size={12} style={{ animation: 'pulse 0.5s infinite' }} /> LISTENING...</>
+ ) : isTyping ? (
+ <><Bot size={12} style={{ animation: 'pulse 0.5s infinite' }} /> PROCESSING...</>
+ ) : (
+ <><Volume2 size={12} /> VOICE MODE</>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Floating Bubble - shows voice status when minimized */}
+ <div style={{ position: 'fixed', bottom: '50px', right: '20px', zIndex: 10000, display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: '8px' }}>
+ {/* Voice status indicator when minimized */}
+ {!isOpen && voiceMode && (
+ <div style={{
+ padding: '6px 12px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${isListening ? FINCEPT.GREEN : isSpeaking ? FINCEPT.ORANGE : FINCEPT.GRAY}`,
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ fontSize: '9px',
+ fontWeight: 700,
+ color: isListening ? FINCEPT.GREEN : isSpeaking ? FINCEPT.ORANGE : FINCEPT.GRAY,
+ animation: 'slideUp 0.2s ease-out'
+ }}>
+ {isSpeaking ? (
+ <>
+ <Volume2 size={10} style={{ animation: 'pulse 0.5s infinite' }} /> SPEAKING
+ <button
+ onClick={(e) => { e.stopPropagation(); stopSpeech(); }}
+ style={{
+ marginLeft: '4px',
+ padding: '2px 6px',
+ backgroundColor: FINCEPT.RED,
+ color: FINCEPT.WHITE,
+ border: 'none',
+ borderRadius: '2px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '2px',
+ fontSize: '7px',
+ fontWeight: 700
+ }}
+ title="Stop speaking"
+ >
+ <Square size={6} fill={FINCEPT.WHITE} />
+ </button>
+ </>
+ ) : isListening ? (
+ <><Mic size={10} style={{ animation: 'pulse 0.5s infinite' }} /> LISTENING</>
+ ) : isTyping ? (
+ <><Bot size={10} style={{ animation: 'pulse 0.5s infinite' }} /> PROCESSING</>
+ ) : (
+ <><Volume2 size={10} /> VOICE ON</>
+ )}
+ </div>
+ )}
+
+ <button onClick={() => isOpen ? dispatch({ type: 'SET_OPEN', payload: false }) : handleOpen()} style={{ width: '40px', height: '40px', borderRadius: '50%', backgroundColor: FINCEPT.DARK_BG, border: `2px solid ${voiceMode ? FINCEPT.GREEN : FINCEPT.ORANGE}`, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', animation: isOpen ? 'none' : voiceMode && isListening ? 'pulse 1s infinite' : 'morphGlow 4s ease-in-out infinite', position: 'relative' }} title={isOpen ? 'Close' : 'AI Assistant'}>
+ {isOpen ? <X size={18} color={FINCEPT.ORANGE} /> : voiceMode ? <Mic size={18} color={isListening ? FINCEPT.GREEN : FINCEPT.ORANGE} /> : <Bot size={18} color={FINCEPT.ORANGE} />}
+ {!isOpen && unreadCount > 0 && (
+ <div style={{ position: 'absolute', top: '-4px', right: '-4px', width: '18px', height: '18px', borderRadius: '50%', backgroundColor: FINCEPT.RED, color: FINCEPT.WHITE, fontSize: '9px', fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
+ {unreadCount > 9 ? '9+' : unreadCount}
+ </div>
+ )}
+ </button>
+ </div>
+ </>
+ );
+};
+
+export default ChatBubble;
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index f9a884345..4c87c7463 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -34,10 +34,12 @@ import RecordedContextsManager from '@/components/common/RecordedContextsManager
import { HeaderSupportButtons } from '@/components/common/HeaderSupportButtons';
import AgentConfigTab from '@/components/tabs/agent-config';
import RelationshipMapTab from '@/components/tabs/relationship-map/RelationshipMapTab';
+import TauriEventsMonitorTab from '@/components/tabs/tauri-events-monitor';
import { useTranslation } from 'react-i18next';
import { WorkspaceProvider } from '@/contexts/WorkspaceContext';
import WorkspaceDialog from './WorkspaceDialog';
import { terminalMCPProvider } from '@/services/mcp/internal';
+import ChatBubble from '@/components/common/ChatBubble';
// Lazy loaded tabs (heavy/Python-dependent)
const EquityResearchTab = React.lazy(() => import('@/components/tabs/equity-research'));
@@ -241,8 +243,24 @@ function FinxeptTerminalContent() {
const [activeTab, setActiveTab] = useState("dashboard");
const [isFullscreen, setIsFullscreen] = useState(false);
const [workspaceDialogMode, setWorkspaceDialogMode] = useState<'save' | 'open' | 'new' | 'export' | 'import' | null>(null);
+ const [chatBubbleEnabled, setChatBubbleEnabled] = useState(true);
const { updateAvailable, updateInfo, isInstalling, installProgress, error, installUpdate, dismissUpdate } = useAutoUpdater();
+ // Load chat bubble setting
+ React.useEffect(() => {
+ const loadChatBubbleSetting = async () => {
+ try {
+ const { invoke } = await import('@tauri-apps/api/core');
+ const value = await invoke<string | null>('db_get_setting', { key: 'chat_bubble_enabled' });
+ setChatBubbleEnabled(value !== 'false');
+ } catch (error) {
+ // Default to enabled if setting doesn't exist
+ setChatBubbleEnabled(true);
+ }
+ };
+ loadChatBubbleSetting();
+ }, []);
+
// Wire internal MCP provider with terminal contexts
React.useEffect(() => {
terminalMCPProvider.setContexts({
@@ -570,6 +588,7 @@ function FinxeptTerminalContent() {
{ label: 'Report Builder', action: () => setActiveTab('reportbuilder') },
{ label: 'Excel Workbook', action: () => setActiveTab('excel') },
{ label: 'Trade Visualization', action: () => setActiveTab('trade-viz') },
+ { label: 'Tauri Events Monitor', action: () => setActiveTab('tauri-events') },
{ label: 'Notes', action: () => setActiveTab('notes') },
{ label: 'Settings', action: () => setActiveTab('settings') },
// Community & Support
@@ -888,6 +907,13 @@ function FinxeptTerminalContent() {
>
AI Quant Lab
</TabsTrigger>
+ <TabsTrigger
+ value="tauri-events"
+ style={activeTab === 'tauri-events' ? tabStyles.active : tabStyles.default}
+ title="Tauri Events Monitor"
+ >
+ Events Monitor
+ </TabsTrigger>
<TabsTrigger
value="settings"
style={activeTab === 'settings' ? tabStyles.active : tabStyles.default}
@@ -947,6 +973,9 @@ function FinxeptTerminalContent() {
<TradeVisualizationTab />
</React.Suspense>
</TabsContent>
+ <TabsContent value="tauri-events" className="h-full m-0 p-0">
+ <TauriEventsMonitorTab />
+ </TabsContent>
<TabsContent value="chat" className="h-full m-0 p-0">
<ChatTab
onNavigateToSettings={() => setActiveTab('settings')}
@@ -1222,6 +1251,11 @@ function FinxeptTerminalContent() {
onLoadWorkspace={(tab) => setActiveTab(tab)}
/>
)}
+
+ {/* Floating Chat Bubble */}
+ {chatBubbleEnabled && mode !== 'chat' && (
+ <ChatBubble onNavigateToTab={setActiveTab} />
+ )}
</div>
);
}
diff --git a/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx b/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx
index 39ae19b02..8f629d145 100644
--- a/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx
@@ -42,6 +42,7 @@ import agentService, {
type PlanStep,
type RoutingResult,
} from '@/services/agentService';
+import RenaissanceTechnologiesPanel from './RenaissanceTechnologiesPanel';
// =============================================================================
// Constants & Types - Fincept Professional Terminal Palette
@@ -1503,94 +1504,100 @@ const AgentConfigTab: React.FC = () => {
display: 'flex',
overflow: 'hidden',
}}>
- {/* Config Area */}
- <div style={{
- flex: 1,
- overflow: 'auto',
- padding: '16px',
- }}>
- {showJsonEditor ? (
- <textarea
- value={jsonText}
- onChange={e => setJsonText(e.target.value)}
- style={{
- width: '100%',
- height: '100%',
- padding: '12px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '2px',
- fontSize: '11px',
- fontFamily: '"IBM Plex Mono", monospace',
- resize: 'none',
- }}
- />
- ) : (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {/* Config Editor */}
- {renderAgentConfigEditor()}
-
- {/* Routing Toggle */}
- <div style={{
- padding: '12px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '2px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <Route size={16} style={{ color: FINCEPT.PURPLE }} />
- <div>
- <div style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.WHITE }}>
- SuperAgent Auto-Routing
- </div>
- <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>
- Automatically route queries to the best agent
- </div>
- </div>
- </div>
- <button
- onClick={() => setUseAutoRouting(!useAutoRouting)}
+ {selectedAgent.id === 'renaissance_technologies' ? (
+ <RenaissanceTechnologiesPanel />
+ ) : (
+ <>
+ {/* Config Area */}
+ <div style={{
+ flex: 1,
+ overflow: 'auto',
+ padding: '16px',
+ }}>
+ {showJsonEditor ? (
+ <textarea
+ value={jsonText}
+ onChange={e => setJsonText(e.target.value)}
style={{
- background: 'none',
- border: 'none',
- cursor: 'pointer',
- color: useAutoRouting ? FINCEPT.GREEN : FINCEPT.GRAY,
+ width: '100%',
+ height: '100%',
+ padding: '12px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '11px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ resize: 'none',
}}
- >
- {useAutoRouting ? <ToggleRight size={24} /> : <ToggleLeft size={24} />}
- </button>
- </div>
-
- {/* Last Routing Result */}
- {lastRoutingResult && (
- <div style={{
- padding: '12px',
- backgroundColor: `${FINCEPT.PURPLE}10`,
- border: `1px solid ${FINCEPT.PURPLE}40`,
- borderRadius: '2px',
- }}>
- <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.PURPLE, marginBottom: '6px' }}>
- LAST ROUTING RESULT
- </div>
- <div style={{ fontSize: '11px', color: FINCEPT.WHITE }}>
- <span style={{ color: FINCEPT.GRAY }}>Intent:</span>{' '}
- <span style={{ color: FINCEPT.ORANGE }}>{lastRoutingResult.intent}</span>
- {' • '}
- <span style={{ color: FINCEPT.GRAY }}>Agent:</span>{' '}
- <span style={{ color: FINCEPT.ORANGE }}>{lastRoutingResult.agent_id}</span>
- {' • '}
- <span style={{ color: FINCEPT.GRAY }}>Confidence:</span>{' '}
- <span style={{ color: FINCEPT.GREEN }}>{(lastRoutingResult.confidence * 100).toFixed(0)}%</span>
+ />
+ ) : (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
+ {/* Config Editor */}
+ {renderAgentConfigEditor()}
+
+ {/* Routing Toggle */}
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <Route size={16} style={{ color: FINCEPT.PURPLE }} />
+ <div>
+ <div style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.WHITE }}>
+ SuperAgent Auto-Routing
+ </div>
+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>
+ Automatically route queries to the best agent
+ </div>
+ </div>
+ </div>
+ <button
+ onClick={() => setUseAutoRouting(!useAutoRouting)}
+ style={{
+ background: 'none',
+ border: 'none',
+ cursor: 'pointer',
+ color: useAutoRouting ? FINCEPT.GREEN : FINCEPT.GRAY,
+ }}
+ >
+ {useAutoRouting ? <ToggleRight size={24} /> : <ToggleLeft size={24} />}
+ </button>
</div>
+
+ {/* Last Routing Result */}
+ {lastRoutingResult && (
+ <div style={{
+ padding: '12px',
+ backgroundColor: `${FINCEPT.PURPLE}10`,
+ border: `1px solid ${FINCEPT.PURPLE}40`,
+ borderRadius: '2px',
+ }}>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.PURPLE, marginBottom: '6px' }}>
+ LAST ROUTING RESULT
+ </div>
+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE }}>
+ <span style={{ color: FINCEPT.GRAY }}>Intent:</span>{' '}
+ <span style={{ color: FINCEPT.ORANGE }}>{lastRoutingResult.intent}</span>
+ {' • '}
+ <span style={{ color: FINCEPT.GRAY }}>Agent:</span>{' '}
+ <span style={{ color: FINCEPT.ORANGE }}>{lastRoutingResult.agent_id}</span>
+ {' • '}
+ <span style={{ color: FINCEPT.GRAY }}>Confidence:</span>{' '}
+ <span style={{ color: FINCEPT.GREEN }}>{(lastRoutingResult.confidence * 100).toFixed(0)}%</span>
+ </div>
+ </div>
+ )}
</div>
)}
</div>
- )}
- </div>
+ </>
+ )}
</div>
</>
) : (
diff --git a/fincept-terminal-desktop/src/components/tabs/agent-config/RenaissanceTechnologiesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/agent-config/RenaissanceTechnologiesPanel.tsx
new file mode 100644
index 000000000..188a59f79
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/agent-config/RenaissanceTechnologiesPanel.tsx
@@ -0,0 +1,806 @@
+/**
+ * Renaissance Technologies Multi-Agent System Panel
+ *
+ * Professional interface for RenTech's 10-agent systematic trading system
+ * Features:
+ * - Agent selection and configuration
+ * - Team collaboration workflows
+ * - IC Deliberation with voting
+ * - Signal analysis pipeline
+ * - Risk management controls
+ * - Real-time execution monitoring
+ */
+
+import React, { useState, useEffect } from 'react';
+import { invoke } from '@tauri-apps/api/core';
+import {
+ TrendingUp, AlertCircle, CheckCircle, Users, Sparkles,
+ Brain, Shield, FileText, Zap, Settings, Play, RefreshCw,
+ ChevronRight, DollarSign, BarChart3, Target, Workflow,
+ ThumbsUp, ThumbsDown, MessageSquare, Clock, Award, Loader2
+} from 'lucide-react';
+
+// =============================================================================
+// TYPES
+// =============================================================================
+
+interface RenTechAgent {
+ id: string;
+ name: string;
+ role: string;
+ status: 'idle' | 'running' | 'completed' | 'error';
+}
+
+interface RenTechTeam {
+ id: string;
+ name: string;
+ members: string[];
+ description: string;
+}
+
+interface ICVote {
+ member_role: string;
+ vote: 'approve' | 'reject' | 'conditional' | 'abstain';
+ rationale: string;
+ confidence: number;
+}
+
+interface ICDeliberationResult {
+ decision: string;
+ decision_rationale: string;
+ confidence: number;
+ pros: string[];
+ cons: string[];
+ member_opinions: ICVote[];
+ vote_summary: Record<string, number>;
+ approved_size_pct?: number;
+ conditions?: string[];
+}
+
+interface SignalAnalysisResult {
+ success: boolean;
+ signal_id?: string;
+ statistical_quality?: string;
+ risk_assessment?: string;
+ ic_decision?: ICDeliberationResult;
+ execution_plan?: any;
+ error?: string;
+}
+
+interface RiskLimits {
+ max_position_size_pct: number;
+ max_leverage: number;
+ max_drawdown_pct: number;
+ max_daily_var_pct: number;
+ min_signal_confidence: number;
+}
+
+// =============================================================================
+// CONSTANTS
+// =============================================================================
+
+const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ GREEN: '#00D66F',
+ RED: '#FF3B3B',
+ BLUE: '#0088FF',
+ DARK_BG: '#0F0F0F',
+ PANEL_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ MUTED: '#787878',
+};
+
+const AGENTS: RenTechAgent[] = [
+ { id: 'signal_scientist', name: 'Signal Scientist', role: 'Statistical signal discovery', status: 'idle' },
+ { id: 'data_scientist', name: 'Data Scientist', role: 'Data quality & features', status: 'idle' },
+ { id: 'quant_researcher', name: 'Quant Researcher', role: 'Strategy development', status: 'idle' },
+ { id: 'research_lead', name: 'Research Lead', role: 'Research validation', status: 'idle' },
+ { id: 'execution_trader', name: 'Execution Trader', role: 'Optimal execution', status: 'idle' },
+ { id: 'market_maker', name: 'Market Maker', role: 'Liquidity provision', status: 'idle' },
+ { id: 'risk_quant', name: 'Risk Quant', role: 'Risk modeling', status: 'idle' },
+ { id: 'compliance_officer', name: 'Compliance Officer', role: 'Regulatory compliance', status: 'idle' },
+ { id: 'portfolio_manager', name: 'Portfolio Manager', role: 'Position sizing', status: 'idle' },
+ { id: 'investment_committee_chair', name: 'IC Chair', role: 'Final approval', status: 'idle' },
+];
+
+const TEAMS: RenTechTeam[] = [
+ {
+ id: 'research_team',
+ name: 'Research Team',
+ members: ['signal_scientist', 'data_scientist', 'quant_researcher', 'research_lead'],
+ description: 'Signal discovery and validation'
+ },
+ {
+ id: 'trading_team',
+ name: 'Trading Team',
+ members: ['execution_trader', 'market_maker'],
+ description: 'Trade execution and liquidity'
+ },
+ {
+ id: 'risk_team',
+ name: 'Risk Team',
+ members: ['risk_quant', 'compliance_officer'],
+ description: 'Risk assessment and compliance'
+ },
+ {
+ id: 'medallion_fund',
+ name: 'Investment Committee',
+ members: ['investment_committee_chair', 'portfolio_manager', 'research_lead', 'risk_quant'],
+ description: 'Final decision-making body'
+ },
+];
+
+// =============================================================================
+// COMPONENT
+// =============================================================================
+
+export default function RenaissanceTechnologiesPanel() {
+ // State
+ const [selectedTab, setSelectedTab] = useState<'agents' | 'teams' | 'analysis' | 'config'>('analysis');
+ const [selectedAgent, setSelectedAgent] = useState<string | null>(null);
+ const [selectedTeam, setSelectedTeam] = useState<string>('medallion_fund');
+ const [agentStatuses, setAgentStatuses] = useState<Record<string, 'idle' | 'running' | 'completed' | 'error'>>({});
+
+ // Analysis state
+ const [ticker, setTicker] = useState('');
+ const [signalType, setSignalType] = useState('momentum');
+ const [isAnalyzing, setIsAnalyzing] = useState(false);
+ const [analysisResult, setAnalysisResult] = useState<SignalAnalysisResult | null>(null);
+
+ // Config state
+ const [riskLimits, setRiskLimits] = useState<RiskLimits>({
+ max_position_size_pct: 5.0,
+ max_leverage: 12.5,
+ max_drawdown_pct: 15.0,
+ max_daily_var_pct: 2.0,
+ min_signal_confidence: 0.5075,
+ });
+
+ // Run signal analysis
+ const runSignalAnalysis = async () => {
+ if (!ticker) return;
+
+ setIsAnalyzing(true);
+ setAnalysisResult(null);
+
+ try {
+ const signalData = {
+ ticker,
+ signal_type: signalType,
+ direction: 'long',
+ strength: 0.75,
+ confidence: 0.65,
+ p_value: 0.008,
+ information_coefficient: 0.05,
+ };
+
+ const result = await invoke<string>('execute_python_agent', {
+ agentType: 'renaissance',
+ parameters: {},
+ inputs: { signal: signalData, config: riskLimits },
+ });
+
+ const parsed = JSON.parse(result);
+ setAnalysisResult(parsed.data || parsed);
+ } catch (error: any) {
+ console.error('Analysis error:', error);
+ setAnalysisResult({
+ success: false,
+ error: error.message || 'Analysis failed',
+ });
+ } finally {
+ setIsAnalyzing(false);
+ }
+ };
+
+ // Run IC Deliberation
+ const runICDeliberation = async () => {
+ setIsAnalyzing(true);
+
+ try {
+ const deliberationData = {
+ signal: {
+ ticker,
+ direction: 'long',
+ signal_type: signalType,
+ p_value: 0.008,
+ confidence: 0.65,
+ expected_return_bps: 75,
+ },
+ signal_evaluation: {
+ statistical_quality: 'strong',
+ overall_score: 75,
+ },
+ risk_assessment: {
+ risk_level: 'medium',
+ var_utilization_pct: 45,
+ },
+ sizing_recommendation: {
+ final_size_pct: 2.5,
+ },
+ };
+
+ const jsonData = JSON.stringify(deliberationData);
+ const result = await invoke<string>('core_agent_cli', {
+ args: ['run_ic_deliberation', jsonData]
+ });
+
+ const parsed = JSON.parse(result);
+ setAnalysisResult({ success: true, ic_decision: parsed.data });
+ } catch (error: any) {
+ console.error('IC deliberation error:', error);
+ setAnalysisResult({
+ success: false,
+ error: error.message || 'IC deliberation failed',
+ });
+ } finally {
+ setIsAnalyzing(false);
+ }
+ };
+
+ return (
+ <div style={{
+ width: '100%',
+ height: '100%',
+ background: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ fontFamily: 'IBM Plex Mono, monospace',
+ display: 'flex',
+ flexDirection: 'column',
+ }}>
+ {/* Header */}
+ <div style={{
+ padding: '20px 24px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ background: FINCEPT.PANEL_BG,
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '12px' }}>
+ <Award size={28} color={FINCEPT.ORANGE} />
+ <div>
+ <h1 style={{ margin: 0, fontSize: '20px', fontWeight: 600 }}>
+ Renaissance Technologies
+ </h1>
+ <p style={{ margin: '4px 0 0', fontSize: '13px', color: FINCEPT.MUTED }}>
+ Medallion Fund Multi-Agent System
+ </p>
+ </div>
+ </div>
+
+ {/* Tab Navigation */}
+ <div style={{ display: 'flex', gap: '8px', marginTop: '16px' }}>
+ {(['analysis', 'agents', 'teams', 'config'] as const).map((tab) => (
+ <button
+ key={tab}
+ onClick={() => setSelectedTab(tab)}
+ style={{
+ padding: '8px 16px',
+ background: selectedTab === tab ? FINCEPT.ORANGE : 'transparent',
+ color: selectedTab === tab ? FINCEPT.DARK_BG : FINCEPT.WHITE,
+ border: `1px solid ${selectedTab === tab ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ borderRadius: '6px',
+ cursor: 'pointer',
+ fontSize: '13px',
+ fontWeight: 500,
+ transition: 'all 0.2s',
+ }}
+ >
+ {tab.charAt(0).toUpperCase() + tab.slice(1)}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Content */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '24px' }}>
+ {selectedTab === 'analysis' && (
+ <AnalysisTab
+ ticker={ticker}
+ setTicker={setTicker}
+ signalType={signalType}
+ setSignalType={setSignalType}
+ isAnalyzing={isAnalyzing}
+ analysisResult={analysisResult}
+ onRunAnalysis={runSignalAnalysis}
+ onRunIC={runICDeliberation}
+ />
+ )}
+
+ {selectedTab === 'agents' && (
+ <AgentsTab
+ agents={AGENTS}
+ selectedAgent={selectedAgent}
+ onSelectAgent={setSelectedAgent}
+ agentStatuses={agentStatuses}
+ />
+ )}
+
+ {selectedTab === 'teams' && (
+ <TeamsTab
+ teams={TEAMS}
+ selectedTeam={selectedTeam}
+ onSelectTeam={setSelectedTeam}
+ />
+ )}
+
+ {selectedTab === 'config' && (
+ <ConfigTab
+ riskLimits={riskLimits}
+ onUpdateLimits={setRiskLimits}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
+
+// =============================================================================
+// ANALYSIS TAB
+// =============================================================================
+
+function AnalysisTab({
+ ticker,
+ setTicker,
+ signalType,
+ setSignalType,
+ isAnalyzing,
+ analysisResult,
+ onRunAnalysis,
+ onRunIC,
+}: {
+ ticker: string;
+ setTicker: (v: string) => void;
+ signalType: string;
+ setSignalType: (v: string) => void;
+ isAnalyzing: boolean;
+ analysisResult: SignalAnalysisResult | null;
+ onRunAnalysis: () => void;
+ onRunIC: () => void;
+}) {
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
+ {/* Input Section */}
+ <div style={{
+ background: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '8px',
+ padding: '20px',
+ }}>
+ <h3 style={{ margin: '0 0 16px', fontSize: '16px', display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Sparkles size={18} color={FINCEPT.ORANGE} />
+ Signal Analysis Input
+ </h3>
+
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
+ <div>
+ <label style={{ display: 'block', marginBottom: '8px', fontSize: '13px', color: FINCEPT.MUTED }}>
+ Ticker Symbol
+ </label>
+ <input
+ type="text"
+ value={ticker}
+ onChange={(e) => setTicker(e.target.value.toUpperCase())}
+ placeholder="AAPL"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ background: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '6px',
+ color: FINCEPT.WHITE,
+ fontSize: '14px',
+ }}
+ />
+ </div>
+
+ <div>
+ <label style={{ display: 'block', marginBottom: '8px', fontSize: '13px', color: FINCEPT.MUTED }}>
+ Signal Type
+ </label>
+ <select
+ value={signalType}
+ onChange={(e) => setSignalType(e.target.value)}
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ background: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '6px',
+ color: FINCEPT.WHITE,
+ fontSize: '14px',
+ }}
+ >
+ <option value="momentum">Momentum</option>
+ <option value="mean_reversion">Mean Reversion</option>
+ <option value="stat_arb">Statistical Arbitrage</option>
+ <option value="pairs_trading">Pairs Trading</option>
+ </select>
+ </div>
+ </div>
+
+ <div style={{ display: 'flex', gap: '12px', marginTop: '20px' }}>
+ <button
+ onClick={onRunAnalysis}
+ disabled={!ticker || isAnalyzing}
+ style={{
+ flex: 1,
+ padding: '12px',
+ background: FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
+ border: 'none',
+ borderRadius: '6px',
+ cursor: ticker && !isAnalyzing ? 'pointer' : 'not-allowed',
+ fontSize: '14px',
+ fontWeight: 600,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px',
+ opacity: ticker && !isAnalyzing ? 1 : 0.5,
+ }}
+ >
+ {isAnalyzing ? <Loader2 size={16} className="animate-spin" /> : <Play size={16} />}
+ Run Full Analysis
+ </button>
+
+ <button
+ onClick={onRunIC}
+ disabled={!ticker || isAnalyzing}
+ style={{
+ flex: 1,
+ padding: '12px',
+ background: 'transparent',
+ color: FINCEPT.ORANGE,
+ border: `1px solid ${FINCEPT.ORANGE}`,
+ borderRadius: '6px',
+ cursor: ticker && !isAnalyzing ? 'pointer' : 'not-allowed',
+ fontSize: '14px',
+ fontWeight: 600,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px',
+ opacity: ticker && !isAnalyzing ? 1 : 0.5,
+ }}
+ >
+ <Users size={16} />
+ IC Deliberation Only
+ </button>
+ </div>
+ </div>
+
+ {/* Results Section */}
+ {analysisResult && (
+ <ResultsDisplay result={analysisResult} />
+ )}
+ </div>
+ );
+}
+
+// =============================================================================
+// RESULTS DISPLAY
+// =============================================================================
+
+function ResultsDisplay({ result }: { result: SignalAnalysisResult }) {
+ if (!result.success) {
+ return (
+ <div style={{
+ background: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.RED}`,
+ borderRadius: '8px',
+ padding: '20px',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', color: FINCEPT.RED }}>
+ <AlertCircle size={24} />
+ <div>
+ <h3 style={{ margin: 0, fontSize: '16px' }}>Analysis Failed</h3>
+ <p style={{ margin: '4px 0 0', fontSize: '13px', opacity: 0.8 }}>{result.error}</p>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ const icDecision = result.ic_decision;
+
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
+ {/* IC Decision */}
+ {icDecision && (
+ <div style={{
+ background: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '8px',
+ padding: '20px',
+ }}>
+ <h3 style={{
+ margin: '0 0 16px',
+ fontSize: '16px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ <Award size={18} color={FINCEPT.ORANGE} />
+ Investment Committee Decision
+ </h3>
+
+ {/* Final Decision */}
+ <div style={{
+ padding: '16px',
+ background: icDecision.decision.includes('APPROVE') ? `${FINCEPT.GREEN}15` : `${FINCEPT.RED}15`,
+ border: `1px solid ${icDecision.decision.includes('APPROVE') ? FINCEPT.GREEN : FINCEPT.RED}`,
+ borderRadius: '6px',
+ marginBottom: '16px',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
+ {icDecision.decision.includes('APPROVE') ? (
+ <CheckCircle size={20} color={FINCEPT.GREEN} />
+ ) : (
+ <AlertCircle size={20} color={FINCEPT.RED} />
+ )}
+ <span style={{ fontSize: '16px', fontWeight: 600 }}>{icDecision.decision}</span>
+ <span style={{ marginLeft: 'auto', fontSize: '14px', color: FINCEPT.MUTED }}>
+ Confidence: {(icDecision.confidence * 100).toFixed(1)}%
+ </span>
+ </div>
+ <p style={{ margin: 0, fontSize: '13px', opacity: 0.9 }}>{icDecision.decision_rationale}</p>
+ {icDecision.approved_size_pct && (
+ <div style={{ marginTop: '8px', fontSize: '13px' }}>
+ <strong>Approved Size:</strong> {icDecision.approved_size_pct.toFixed(2)}% of NAV
+ </div>
+ )}
+ </div>
+
+ {/* Vote Summary */}
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
+ {Object.entries(icDecision.vote_summary).map(([vote, count]) => (
+ <div
+ key={vote}
+ style={{
+ padding: '12px',
+ background: FINCEPT.DARK_BG,
+ borderRadius: '6px',
+ textAlign: 'center',
+ }}
+ >
+ <div style={{ fontSize: '24px', fontWeight: 700, color: FINCEPT.ORANGE }}>{count}</div>
+ <div style={{ fontSize: '11px', color: FINCEPT.MUTED, marginTop: '4px', textTransform: 'uppercase' }}>
+ {vote}
+ </div>
+ </div>
+ ))}
+ </div>
+
+ {/* Member Votes */}
+ <h4 style={{ margin: '16px 0 12px', fontSize: '14px', color: FINCEPT.MUTED }}>Member Votes:</h4>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ {icDecision.member_opinions?.map((opinion, idx) => (
+ <div
+ key={idx}
+ style={{
+ padding: '12px',
+ background: FINCEPT.DARK_BG,
+ borderRadius: '6px',
+ borderLeft: `3px solid ${
+ opinion.vote === 'approve' ? FINCEPT.GREEN :
+ opinion.vote === 'reject' ? FINCEPT.RED :
+ FINCEPT.ORANGE
+ }`,
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>
+ {opinion.vote === 'approve' ? <ThumbsUp size={14} color={FINCEPT.GREEN} /> :
+ opinion.vote === 'reject' ? <ThumbsDown size={14} color={FINCEPT.RED} /> :
+ <MessageSquare size={14} color={FINCEPT.ORANGE} />}
+ <strong style={{ fontSize: '13px' }}>{opinion.member_role}</strong>
+ <span style={{ marginLeft: 'auto', fontSize: '12px', color: FINCEPT.MUTED }}>
+ {(opinion.confidence * 100).toFixed(0)}%
+ </span>
+ </div>
+ <p style={{ margin: 0, fontSize: '12px', opacity: 0.8 }}>{opinion.rationale}</p>
+ </div>
+ ))}
+ </div>
+
+ {/* Pros & Cons */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginTop: '16px' }}>
+ <div>
+ <h4 style={{ margin: '0 0 8px', fontSize: '13px', color: FINCEPT.GREEN }}>Pros:</h4>
+ {icDecision.pros?.map((pro, idx) => (
+ <div key={idx} style={{ fontSize: '12px', marginBottom: '4px', paddingLeft: '12px' }}>
+ • {pro}
+ </div>
+ ))}
+ </div>
+ <div>
+ <h4 style={{ margin: '0 0 8px', fontSize: '13px', color: FINCEPT.RED }}>Cons:</h4>
+ {icDecision.cons?.map((con, idx) => (
+ <div key={idx} style={{ fontSize: '12px', marginBottom: '4px', paddingLeft: '12px' }}>
+ • {con}
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+// =============================================================================
+// AGENTS TAB
+// =============================================================================
+
+function AgentsTab({
+ agents,
+ selectedAgent,
+ onSelectAgent,
+ agentStatuses,
+}: {
+ agents: RenTechAgent[];
+ selectedAgent: string | null;
+ onSelectAgent: (id: string | null) => void;
+ agentStatuses: Record<string, string>;
+}) {
+ return (
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: '16px' }}>
+ {agents.map((agent) => (
+ <div
+ key={agent.id}
+ onClick={() => onSelectAgent(agent.id === selectedAgent ? null : agent.id)}
+ style={{
+ padding: '16px',
+ background: selectedAgent === agent.id ? `${FINCEPT.ORANGE}15` : FINCEPT.PANEL_BG,
+ border: `1px solid ${selectedAgent === agent.id ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ borderRadius: '8px',
+ cursor: 'pointer',
+ transition: 'all 0.2s',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
+ <Brain size={20} color={FINCEPT.ORANGE} />
+ <h4 style={{ margin: 0, fontSize: '14px', fontWeight: 600 }}>{agent.name}</h4>
+ </div>
+ <p style={{ margin: '0 0 12px', fontSize: '12px', color: FINCEPT.MUTED }}>{agent.role}</p>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '12px' }}>
+ <div
+ style={{
+ width: '8px',
+ height: '8px',
+ borderRadius: '50%',
+ background: agentStatuses[agent.id] === 'running' ? FINCEPT.ORANGE :
+ agentStatuses[agent.id] === 'completed' ? FINCEPT.GREEN :
+ agentStatuses[agent.id] === 'error' ? FINCEPT.RED :
+ FINCEPT.MUTED,
+ }}
+ />
+ <span style={{ color: FINCEPT.MUTED, textTransform: 'capitalize' }}>
+ {agentStatuses[agent.id] || 'idle'}
+ </span>
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+// =============================================================================
+// TEAMS TAB
+// =============================================================================
+
+function TeamsTab({
+ teams,
+ selectedTeam,
+ onSelectTeam,
+}: {
+ teams: RenTechTeam[];
+ selectedTeam: string;
+ onSelectTeam: (id: string) => void;
+}) {
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
+ {teams.map((team) => (
+ <div
+ key={team.id}
+ onClick={() => onSelectTeam(team.id)}
+ style={{
+ padding: '20px',
+ background: selectedTeam === team.id ? `${FINCEPT.ORANGE}15` : FINCEPT.PANEL_BG,
+ border: `1px solid ${selectedTeam === team.id ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ borderRadius: '8px',
+ cursor: 'pointer',
+ transition: 'all 0.2s',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
+ <Users size={20} color={FINCEPT.ORANGE} />
+ <h4 style={{ margin: 0, fontSize: '16px', fontWeight: 600 }}>{team.name}</h4>
+ </div>
+ <p style={{ margin: '0 0 12px', fontSize: '13px', color: FINCEPT.MUTED }}>{team.description}</p>
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
+ {team.members.map((memberId) => {
+ const agent = AGENTS.find(a => a.id === memberId);
+ return agent ? (
+ <div
+ key={memberId}
+ style={{
+ padding: '6px 12px',
+ background: FINCEPT.DARK_BG,
+ borderRadius: '4px',
+ fontSize: '12px',
+ }}
+ >
+ {agent.name}
+ </div>
+ ) : null;
+ })}
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+// =============================================================================
+// CONFIG TAB
+// =============================================================================
+
+function ConfigTab({
+ riskLimits,
+ onUpdateLimits,
+}: {
+ riskLimits: RiskLimits;
+ onUpdateLimits: (limits: RiskLimits) => void;
+}) {
+ return (
+ <div style={{
+ background: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '8px',
+ padding: '20px',
+ }}>
+ <h3 style={{ margin: '0 0 20px', fontSize: '16px', display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Shield size={18} color={FINCEPT.ORANGE} />
+ Risk Management Configuration
+ </h3>
+
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
+ {Object.entries(riskLimits).map(([key, value]) => (
+ <div key={key}>
+ <label style={{ display: 'block', marginBottom: '8px', fontSize: '13px', color: FINCEPT.MUTED }}>
+ {key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}
+ </label>
+ <input
+ type="number"
+ value={value}
+ onChange={(e) => onUpdateLimits({ ...riskLimits, [key]: parseFloat(e.target.value) })}
+ step="0.1"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ background: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '6px',
+ color: FINCEPT.WHITE,
+ fontSize: '14px',
+ }}
+ />
+ </div>
+ ))}
+ </div>
+
+ <div style={{
+ marginTop: '20px',
+ padding: '16px',
+ background: `${FINCEPT.ORANGE}10`,
+ border: `1px solid ${FINCEPT.ORANGE}30`,
+ borderRadius: '6px',
+ fontSize: '12px',
+ color: FINCEPT.MUTED,
+ }}>
+ <strong style={{ color: FINCEPT.ORANGE }}>Note:</strong> These risk limits are applied to all signal analysis
+ and IC deliberations. Changes take effect immediately.
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/agent-config/index.tsx b/fincept-terminal-desktop/src/components/tabs/agent-config/index.tsx
new file mode 100644
index 000000000..ef727d568
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/agent-config/index.tsx
@@ -0,0 +1,8 @@
+/**
+ * Agent Config Tab Entry Point
+ *
+ * Exports main AgentConfigTab and specialized panels
+ */
+
+export { default } from './AgentConfigTab';
+export { default as RenaissanceTechnologiesPanel } from './RenaissanceTechnologiesPanel';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/constants.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/constants.ts
index 6181fcf67..75198d045 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/constants.ts
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/constants.ts
@@ -15,7 +15,12 @@ export const FINCEPT = {
CYAN: '#00E5FF',
BLUE: '#0088FF',
BORDER: '#2A2A2A',
- HOVER: '#1F1F1F'
+ HOVER: '#1F1F1F',
+ GRAY: '#888888',
+ MUTED: '#666666',
+ PURPLE: '#BB86FC',
+ YELLOW: '#FFD700',
+ HEADER_BG: '#1A1A1A'
};
// Sample price data for demonstration (kept for backward compatibility)
diff --git a/fincept-terminal-desktop/src/components/tabs/backtesting/BacktestingTab.tsx b/fincept-terminal-desktop/src/components/tabs/backtesting/BacktestingTab.tsx
index 188e246e5..a069df233 100644
--- a/fincept-terminal-desktop/src/components/tabs/backtesting/BacktestingTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/backtesting/BacktestingTab.tsx
@@ -48,86 +48,53 @@ const PROVIDER_COLORS: Record<BacktestingProviderSlug, string> = {
};
// ============================================================================
-// DATA SOURCE OPTIONS
+// DATA SOURCE OPTIONS - Removed (data command removed)
// ============================================================================
-const DATA_SOURCES = [
- { id: 'yfinance', label: 'Yahoo Finance', supported: true },
- { id: 'binance', label: 'Binance', supported: true },
- { id: 'ccxt', label: 'CCXT', supported: true },
- { id: 'alpaca', label: 'Alpaca', supported: true },
- { id: 'synthetic', label: 'Synthetic (GBM)', supported: true },
-];
-
-const TIMEFRAMES = [
- { id: '1m', label: '1 Minute' },
- { id: '5m', label: '5 Minutes' },
- { id: '15m', label: '15 Minutes' },
- { id: '1h', label: '1 Hour' },
- { id: '4h', label: '4 Hours' },
- { id: '1d', label: '1 Day' },
- { id: '1w', label: '1 Week' },
-];
-
// ============================================================================
// INDICATOR OPTIONS
// ============================================================================
const INDICATORS = [
- { id: 'ma', label: 'Moving Average', params: ['period', 'ewm'] },
+ // Moving Averages
+ { id: 'ma', label: 'Moving Average (SMA)', params: ['period'] },
+ { id: 'ema', label: 'Moving Average (EMA)', params: ['period'] },
{ id: 'mstd', label: 'Moving Std Dev', params: ['period'] },
- { id: 'bbands', label: 'Bollinger Bands', params: ['period', 'alpha'] },
+
+ // Oscillators
{ id: 'rsi', label: 'RSI', params: ['period'] },
- { id: 'stoch', label: 'Stochastic', params: ['kPeriod', 'dPeriod'] },
+ { id: 'stoch', label: 'Stochastic', params: ['k_period', 'd_period'] },
+ { id: 'cci', label: 'CCI', params: ['period'] },
+ { id: 'williams_r', label: 'Williams %R', params: ['period'] },
+
+ // Trend Indicators
{ id: 'macd', label: 'MACD', params: ['fast', 'slow', 'signal'] },
- { id: 'atr', label: 'ATR', params: ['period'] },
- { id: 'obv', label: 'OBV', params: [] },
{ id: 'adx', label: 'ADX', params: ['period'] },
- { id: 'donchian', label: 'Donchian', params: ['period'] },
- { id: 'zscore', label: 'Z-Score', params: ['window'] },
- { id: 'momentum', label: 'Momentum', params: ['period'] },
- { id: 'williams_r', label: 'Williams %R', params: ['period'] },
- { id: 'cci', label: 'CCI', params: ['period'] },
- { id: 'keltner', label: 'Keltner', params: ['period', 'atrMult'] },
-];
+ { id: 'momentum', label: 'Momentum', params: ['lookback'] },
-// ============================================================================
-// SIGNAL GENERATORS
-// ============================================================================
+ // Volatility
+ { id: 'atr', label: 'ATR', params: ['period'] },
+ { id: 'bbands', label: 'Bollinger Bands', params: ['period'] },
+ { id: 'keltner', label: 'Keltner Channel', params: ['period'] },
-const SIGNAL_GENERATORS = [
- { id: 'RAND', label: 'Random', params: ['n', 'seed'] },
- { id: 'RANDX', label: 'Random Entry/Exit', params: ['n', 'seed'] },
- { id: 'RANDNX', label: 'Random N Entries', params: ['n', 'seed'] },
- { id: 'RPROB', label: 'Random Probability', params: ['prob', 'seed'] },
- { id: 'RPROBX', label: 'Random Prob Entry/Exit', params: ['entryProb', 'exitProb', 'seed'] },
- { id: 'STX', label: 'Stop/Take-Profit', params: ['stopLoss', 'takeProfit'] },
- { id: 'STCX', label: 'Trailing Stop', params: ['stopLoss', 'trailing'] },
- { id: 'OHLCSTX', label: 'OHLC Stop/TP', params: ['stopLoss', 'takeProfit'] },
-];
+ // Channels
+ { id: 'donchian', label: 'Donchian Channel', params: ['period'] },
-// ============================================================================
-// LABEL GENERATORS
-// ============================================================================
+ // Statistical
+ { id: 'zscore', label: 'Z-Score', params: ['period'] },
-const LABEL_GENERATORS = [
- { id: 'FIXLB', label: 'Fixed Horizon', params: ['horizon', 'threshold'] },
- { id: 'MEANLB', label: 'Mean Reversion', params: ['window', 'threshold'] },
- { id: 'LEXLB', label: 'Local Extrema', params: ['window'] },
- { id: 'TRENDLB', label: 'Trend', params: ['window', 'threshold'] },
- { id: 'BOLB', label: 'Bollinger', params: ['window', 'alpha'] },
+ // Volume
+ { id: 'obv', label: 'OBV', params: [] },
+ { id: 'vwap', label: 'VWAP', params: [] },
];
// ============================================================================
-// SPLITTERS
+// LABEL GENERATORS - Removed (labels command removed)
// ============================================================================
-const SPLITTERS = [
- { id: 'range', label: 'Range Splitter', params: [] },
- { id: 'rolling', label: 'Rolling Window', params: ['windowLen', 'testLen', 'step'] },
- { id: 'expanding', label: 'Expanding Window', params: ['minLen', 'testLen', 'step'] },
- { id: 'purged_kfold', label: 'Purged K-Fold', params: ['nSplits', 'purgeLen', 'embargoLen'] },
-];
+// ============================================================================
+// SPLITTERS - Removed (splits command removed)
+// ============================================================================
// ============================================================================
// POSITION SIZING OPTIONS
@@ -265,25 +232,13 @@ const BacktestingTab: React.FC = () => {
const [wfSplits, setWfSplits] = useState(5);
const [wfTrainRatio, setWfTrainRatio] = useState(0.7);
- // --- Data Config ---
- const [dataSource, setDataSource] = useState('yfinance');
- const [timeframe, setTimeframe] = useState('1d');
-
// --- Indicator Config ---
const [selectedIndicator, setSelectedIndicator] = useState('ma');
const [indicatorParams, setIndicatorParams] = useState<Record<string, any>>({});
- // --- Signal Config ---
- const [selectedSignalGen, setSelectedSignalGen] = useState('RAND');
- const [signalParams, setSignalParams] = useState<Record<string, any>>({});
-
- // --- Label Config ---
- const [selectedLabelGen, setSelectedLabelGen] = useState('FIXLB');
- const [labelParams, setLabelParams] = useState<Record<string, any>>({});
-
- // --- Split Config ---
- const [selectedSplitter, setSelectedSplitter] = useState('rolling');
- const [splitParams, setSplitParams] = useState<Record<string, any>>({});
+ // --- Indicator Signals Config ---
+ const [indSignalMode, setIndSignalMode] = useState('crossover_signals');
+ const [indSignalParams, setIndSignalParams] = useState<Record<string, any>>({});
// --- Execution State ---
const [isRunning, setIsRunning] = useState(false);
@@ -413,90 +368,68 @@ const BacktestingTab: React.FC = () => {
};
break;
- case 'data':
- commandArgs = {
- symbols: symbolList,
- dataSource,
- timeframe,
- startDate,
- endDate,
- };
- break;
-
case 'indicator':
- commandArgs = {
- symbols: symbolList,
- startDate,
- endDate,
- indicator: selectedIndicator,
- parameters: indicatorParams,
- };
- break;
+ // Indicator command uses parameter sweeping (ranges)
+ const indicatorParamRanges: Record<string, { min: number; max: number; step: number }> = {};
+ const selectedInd = INDICATORS.find(i => i.id === selectedIndicator);
+
+ if (selectedInd) {
+ // Default values per parameter type
+ const paramDefaults: Record<string, number> = {
+ 'period': 20,
+ 'k_period': 14,
+ 'd_period': 3,
+ 'fast': 12,
+ 'slow': 26,
+ 'signal': 9,
+ 'alpha': 2,
+ 'window': 20,
+ 'atrMult': 2,
+ 'lookback': 20,
+ };
+
+ // Filter to only numeric parameters (skip boolean flags like 'ewm')
+ const numericParams = selectedInd.params.filter(p =>
+ !['ewm'].includes(p) // Skip non-numeric flags
+ );
- case 'indicator_signals':
- commandArgs = {
- symbols: symbolList,
- startDate,
- endDate,
- indicator: selectedIndicator,
- parameters: indicatorParams,
- };
- break;
+ console.log('[INDICATOR] selectedInd:', selectedInd.id, 'params:', selectedInd.params);
+ console.log('[INDICATOR] numericParams:', numericParams);
+ console.log('[INDICATOR] indicatorParams:', indicatorParams);
- case 'signals':
- commandArgs = {
- symbols: symbolList,
- startDate,
- endDate,
- generator: selectedSignalGen,
- parameters: signalParams,
- };
- break;
+ numericParams.forEach(paramName => {
+ const defaultValue = paramDefaults[paramName] ?? 14;
+ const value = indicatorParams[paramName] ?? defaultValue;
- case 'labels':
- commandArgs = {
- symbols: symbolList,
- startDate,
- endDate,
- generator: selectedLabelGen,
- parameters: labelParams,
- };
- break;
+ // Create a range of ±20% around the value for sweep
+ const minVal = Math.max(2, Math.floor(value * 0.8));
+ const maxVal = Math.ceil(value * 1.2);
+ const stepVal = Math.max(1, Math.floor((maxVal - minVal) / 5));
- case 'splits':
- commandArgs = {
- startDate,
- endDate,
- splitter: selectedSplitter,
- parameters: splitParams,
- };
- break;
+ indicatorParamRanges[paramName] = { min: minVal, max: maxVal, step: stepVal };
+ console.log(`[INDICATOR] ${paramName}: value=${value}, range=[${minVal}, ${maxVal}], step=${stepVal}`);
+ });
+ }
+
+ console.log('[INDICATOR] Final paramRanges:', indicatorParamRanges);
- case 'returns':
commandArgs = {
symbols: symbolList,
startDate,
endDate,
+ indicator: selectedIndicator,
+ paramRanges: indicatorParamRanges,
};
break;
- case 'browse_strategies':
- commandArgs = {};
- break;
-
- case 'browse_indicators':
- commandArgs = {};
- break;
-
- case 'labels_to_signals':
+ case 'indicator_signals':
commandArgs = {
symbols: symbolList,
startDate,
endDate,
- labelType: selectedLabelGen,
- params: labelParams,
- entryLabel: 1,
- exitLabel: -1,
+ mode: indSignalMode,
+ indicator: selectedIndicator,
+ params: indSignalParams,
};
break;
}
@@ -561,9 +494,8 @@ const BacktestingTab: React.FC = () => {
selectedStrategy, strategyParams, customCode, commission, slippage, leverage, margin,
stopLoss, takeProfit, trailingStop, positionSizing, positionSizeValue, allowShort,
benchmarkSymbol, enableBenchmark, randomBenchmark, optimizeObjective, optimizeMethod,
- maxIterations, paramRanges, wfSplits, wfTrainRatio, dataSource, timeframe,
- selectedIndicator, indicatorParams, selectedSignalGen, signalParams,
- selectedLabelGen, labelParams, selectedSplitter, splitParams
+ maxIterations, paramRanges, wfSplits, wfTrainRatio,
+ selectedIndicator, indicatorParams, indSignalMode, indSignalParams
]);
const toggleSection = (section: string) => {
@@ -874,16 +806,8 @@ const BacktestingTab: React.FC = () => {
{activeCommand === 'backtest' && renderBacktestConfig()}
{activeCommand === 'optimize' && renderOptimizeConfig()}
{activeCommand === 'walk_forward' && renderWalkForwardConfig()}
- {activeCommand === 'data' && renderDataConfig()}
{activeCommand === 'indicator' && renderIndicatorConfig()}
{activeCommand === 'indicator_signals' && renderIndicatorSignalsConfig()}
- {activeCommand === 'signals' && renderSignalsConfig()}
- {activeCommand === 'labels' && renderLabelsConfig()}
- {activeCommand === 'splits' && renderSplitsConfig()}
- {activeCommand === 'returns' && renderReturnsConfig()}
- {activeCommand === 'browse_strategies' && renderBrowseStrategiesConfig()}
- {activeCommand === 'browse_indicators' && renderBrowseIndicatorsConfig()}
- {activeCommand === 'labels_to_signals' && renderLabelsToSignalsConfig()}
</div>
</div>
);
@@ -1352,86 +1276,16 @@ const BacktestingTab: React.FC = () => {
</div>
);
- const renderDataConfig = () => (
+ const renderIndicatorConfig = () => (
<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {renderSection('datasource', 'DATA SOURCE', Database, (
+ {renderSection('market', 'MARKET DATA', Database, (
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
- <div>
- <label style={{
- display: 'block',
- fontSize: '9px',
- fontWeight: 700,
- color: FINCEPT.GRAY,
- marginBottom: '4px',
- letterSpacing: '0.5px',
- fontFamily: '"IBM Plex Mono", monospace',
- }}>
- SOURCE
- </label>
- <select
- value={dataSource}
- onChange={e => setDataSource(e.target.value)}
- style={{
- width: '100%',
- padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '2px',
- fontSize: '10px',
- fontFamily: '"IBM Plex Mono", monospace',
- outline: 'none',
- }}
- >
- {DATA_SOURCES.map(ds => (
- <option key={ds.id} value={ds.id} disabled={!ds.supported}>
- {ds.label}
- </option>
- ))}
- </select>
- </div>
- <div>
- <label style={{
- display: 'block',
- fontSize: '9px',
- fontWeight: 700,
- color: FINCEPT.GRAY,
- marginBottom: '4px',
- letterSpacing: '0.5px',
- fontFamily: '"IBM Plex Mono", monospace',
- }}>
- TIMEFRAME
- </label>
- <select
- value={timeframe}
- onChange={e => setTimeframe(e.target.value)}
- style={{
- width: '100%',
- padding: '8px 10px',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '2px',
- fontSize: '10px',
- fontFamily: '"IBM Plex Mono", monospace',
- outline: 'none',
- }}
- >
- {TIMEFRAMES.map(tf => (
- <option key={tf.id} value={tf.id}>{tf.label}</option>
- ))}
- </select>
- </div>
{renderInput('Symbols', symbols, setSymbols, 'text')}
{renderInput('Start Date', startDate, setStartDate, 'date')}
{renderInput('End Date', endDate, setEndDate, 'date')}
</div>
))}
- </div>
- );
- const renderIndicatorConfig = () => (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
{renderSection('indicator', 'INDICATOR SELECTION', Activity, (
<>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '8px' }}>
@@ -1466,165 +1320,246 @@ const BacktestingTab: React.FC = () => {
</div>
);
- const renderIndicatorSignalsConfig = () => (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {renderIndicatorConfig()}
- </div>
- );
+ const renderIndicatorSignalsConfig = () => {
+ const SIGNAL_MODES = [
+ { id: 'crossover_signals', label: 'Crossover', description: 'MA/EMA crossover signals' },
+ { id: 'threshold_signals', label: 'Threshold', description: 'RSI/CCI threshold signals' },
+ { id: 'breakout_signals', label: 'Breakout', description: 'Channel breakout signals' },
+ { id: 'mean_reversion_signals', label: 'Mean Reversion', description: 'Z-score mean reversion' },
+ { id: 'signal_filter', label: 'Signal Filter', description: 'Filter signals with indicators' },
+ ];
- const renderSignalsConfig = () => (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {renderSection('signals', 'SIGNAL GENERATOR', Zap, (
- <>
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
+ {/* Market Data */}
+ {renderSection('market', 'MARKET DATA', Database, (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ {renderInput('Symbols', symbols, setSymbols, 'text')}
+ {renderInput('Start Date', startDate, setStartDate, 'date')}
+ {renderInput('End Date', endDate, setEndDate, 'date')}
+ </div>
+ ))}
+
+ {/* Signal Mode Selection */}
+ {renderSection('signal_mode', 'SIGNAL MODE', Zap, (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '8px' }}>
- {SIGNAL_GENERATORS.map(gen => (
+ {SIGNAL_MODES.map(mode => (
<button
- key={gen.id}
- onClick={() => setSelectedSignalGen(gen.id)}
+ key={mode.id}
+ onClick={() => {
+ setIndSignalMode(mode.id);
+ setIndSignalParams({}); // Reset params when mode changes
+ }}
style={{
padding: '8px',
- backgroundColor: selectedSignalGen === gen.id ? FINCEPT.YELLOW : 'transparent',
- color: selectedSignalGen === gen.id ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ backgroundColor: indSignalMode === mode.id ? FINCEPT.YELLOW : 'transparent',
+ color: indSignalMode === mode.id ? FINCEPT.DARK_BG : FINCEPT.GRAY,
border: `1px solid ${FINCEPT.BORDER}`,
borderRadius: '2px',
fontSize: '9px',
fontWeight: 700,
cursor: 'pointer',
fontFamily: '"IBM Plex Mono", monospace',
+ textAlign: 'left',
}}
>
- {gen.label}
+ <div>{mode.label}</div>
+ <div style={{ fontSize: '7px', fontWeight: 400, marginTop: '2px', opacity: 0.7 }}>
+ {mode.description}
+ </div>
</button>
))}
</div>
- </>
- ))}
- </div>
- );
-
- const renderLabelsConfig = () => (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {renderSection('labels', 'LABEL GENERATOR', Tag, (
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '8px' }}>
- {LABEL_GENERATORS.map(gen => (
- <button
- key={gen.id}
- onClick={() => setSelectedLabelGen(gen.id)}
- style={{
- padding: '8px',
- backgroundColor: selectedLabelGen === gen.id ? FINCEPT.BLUE : 'transparent',
- color: selectedLabelGen === gen.id ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '2px',
- fontSize: '9px',
- fontWeight: 700,
- cursor: 'pointer',
- fontFamily: '"IBM Plex Mono", monospace',
- }}
- >
- {gen.label}
- </button>
- ))}
- </div>
- ))}
- </div>
- );
-
- const renderSplitsConfig = () => (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {renderSection('splits', 'CROSS-VALIDATION SPLITTER', Split, (
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '8px' }}>
- {SPLITTERS.map(splitter => (
- <button
- key={splitter.id}
- onClick={() => setSelectedSplitter(splitter.id)}
- style={{
- padding: '8px',
- backgroundColor: selectedSplitter === splitter.id ? FINCEPT.PURPLE : 'transparent',
- color: selectedSplitter === splitter.id ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '2px',
- fontSize: '9px',
- fontWeight: 700,
- cursor: 'pointer',
- fontFamily: '"IBM Plex Mono", monospace',
- }}
- >
- {splitter.label}
- </button>
- ))}
- </div>
- ))}
- </div>
- );
-
- const renderReturnsConfig = () => (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {renderSection('returns', 'RETURNS ANALYSIS', DollarSign, (
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
- {renderInput('Symbols', symbols, setSymbols, 'text')}
- {renderInput('Start Date', startDate, setStartDate, 'date')}
- {renderInput('End Date', endDate, setEndDate, 'date')}
- </div>
- ))}
- </div>
- );
+ ))}
- const renderBrowseStrategiesConfig = () => (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {renderSection('browse_strategies', 'BROWSE STRATEGIES', Search, (
- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, lineHeight: 1.6 }}>
- <p style={{ marginBottom: '8px' }}>
- Click <span style={{ color: FINCEPT.ORANGE, fontWeight: 700 }}>RUN</span> to fetch the complete strategy catalog from vbt_strategies module.
- </p>
- <p style={{ color: FINCEPT.MUTED }}>
- Returns all available trading strategies with their parameters, descriptions, and usage examples.
- </p>
- </div>
- ))}
- </div>
- );
+ {/* Mode-Specific Parameters */}
+ {indSignalMode === 'crossover_signals' && renderSection('crossover_params', 'CROSSOVER PARAMETERS', Activity, (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>FAST INDICATOR</div>
+ <select
+ value={indSignalParams.fast_indicator ?? 'ma'}
+ onChange={(e) => setIndSignalParams(prev => ({ ...prev, fast_indicator: e.target.value }))}
+ style={{
+ width: '100%',
+ padding: '6px 8px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ }}
+ >
+ <option value="ma">SMA</option>
+ <option value="ema">EMA</option>
+ </select>
+ </div>
+ {renderInput('Fast Period', indSignalParams.fast_period ?? 10, (v) => setIndSignalParams(prev => ({ ...prev, fast_period: v })), 'number')}
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>SLOW INDICATOR</div>
+ <select
+ value={indSignalParams.slow_indicator ?? 'ma'}
+ onChange={(e) => setIndSignalParams(prev => ({ ...prev, slow_indicator: e.target.value }))}
+ style={{
+ width: '100%',
+ padding: '6px 8px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ }}
+ >
+ <option value="ma">SMA</option>
+ <option value="ema">EMA</option>
+ </select>
+ </div>
+ {renderInput('Slow Period', indSignalParams.slow_period ?? 20, (v) => setIndSignalParams(prev => ({ ...prev, slow_period: v })), 'number')}
+ </div>
+ ))}
- const renderBrowseIndicatorsConfig = () => (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {renderSection('browse_indicators', 'BROWSE INDICATORS', Filter, (
- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, lineHeight: 1.6 }}>
- <p style={{ marginBottom: '8px' }}>
- Click <span style={{ color: FINCEPT.ORANGE, fontWeight: 700 }}>RUN</span> to fetch the complete indicator catalog from vbt_indicators module.
- </p>
- <p style={{ color: FINCEPT.MUTED }}>
- Returns all available technical indicators with their parameters, calculation methods, and signal generation capabilities.
- </p>
- </div>
- ))}
- </div>
- );
+ {indSignalMode === 'threshold_signals' && renderSection('threshold_params', 'THRESHOLD PARAMETERS', Activity, (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>INDICATOR</div>
+ <select
+ value={selectedIndicator}
+ onChange={(e) => setSelectedIndicator(e.target.value)}
+ style={{
+ width: '100%',
+ padding: '6px 8px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ }}
+ >
+ <option value="rsi">RSI</option>
+ <option value="cci">CCI</option>
+ <option value="williams_r">Williams %R</option>
+ <option value="stoch">Stochastic</option>
+ </select>
+ </div>
+ {renderInput('Period', indSignalParams.period ?? 14, (v) => setIndSignalParams(prev => ({ ...prev, period: v })), 'number')}
+ {renderInput('Lower Threshold', indSignalParams.lower ?? 30, (v) => setIndSignalParams(prev => ({ ...prev, lower: v })), 'number')}
+ {renderInput('Upper Threshold', indSignalParams.upper ?? 70, (v) => setIndSignalParams(prev => ({ ...prev, upper: v })), 'number')}
+ </div>
+ ))}
- const renderLabelsToSignalsConfig = () => (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {renderSection('labels_to_signals', 'LABELS TO SIGNALS CONVERSION', ChevronRight, (
- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, lineHeight: 1.6 }}>
- <p style={{ marginBottom: '8px', color: FINCEPT.CYAN }}>
- Converts ML labels into trading signals (entry/exit).
- </p>
+ {indSignalMode === 'breakout_signals' && renderSection('breakout_params', 'BREAKOUT PARAMETERS', Activity, (
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
- {renderInput('Symbols', symbols, setSymbols, 'text')}
- {renderInput('Start Date', startDate, setStartDate, 'date')}
- {renderInput('End Date', endDate, setEndDate, 'date')}
- {renderSelect('Label Type', selectedLabelGen, setSelectedLabelGen, LABEL_GENERATORS.map(g => ({ value: g.id, label: g.label })))}
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>CHANNEL TYPE</div>
+ <select
+ value={indSignalParams.channel ?? 'donchian'}
+ onChange={(e) => setIndSignalParams(prev => ({ ...prev, channel: e.target.value }))}
+ style={{
+ width: '100%',
+ padding: '6px 8px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ }}
+ >
+ <option value="donchian">Donchian Channel</option>
+ <option value="bbands">Bollinger Bands</option>
+ <option value="keltner">Keltner Channel</option>
+ </select>
+ </div>
+ {renderInput('Period', indSignalParams.period ?? 20, (v) => setIndSignalParams(prev => ({ ...prev, period: v })), 'number')}
</div>
- <div style={{ marginTop: '12px', padding: '8px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '2px' }}>
- <p style={{ fontSize: '8px', color: FINCEPT.MUTED, marginBottom: '4px' }}>
- Entry Label: <span style={{ color: FINCEPT.GREEN }}>1</span> (buy signal)
- </p>
- <p style={{ fontSize: '8px', color: FINCEPT.MUTED }}>
- Exit Label: <span style={{ color: FINCEPT.RED }}>-1</span> (sell signal)
- </p>
+ ))}
+
+ {indSignalMode === 'mean_reversion_signals' && renderSection('mean_reversion_params', 'MEAN REVERSION PARAMETERS', Activity, (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>
+ {renderInput('Period', indSignalParams.period ?? 20, (v) => setIndSignalParams(prev => ({ ...prev, period: v })), 'number')}
+ {renderInput('Z-Score Entry', indSignalParams.z_entry ?? 2.0, (v) => setIndSignalParams(prev => ({ ...prev, z_entry: v })), 'number')}
+ {renderInput('Z-Score Exit', indSignalParams.z_exit ?? 0.0, (v) => setIndSignalParams(prev => ({ ...prev, z_exit: v })), 'number')}
</div>
- </div>
- ))}
- </div>
- );
+ ))}
+
+ {indSignalMode === 'signal_filter' && renderSection('filter_params', 'SIGNAL FILTER PARAMETERS', Activity, (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>BASE INDICATOR</div>
+ <select
+ value={indSignalParams.base_indicator ?? 'rsi'}
+ onChange={(e) => setIndSignalParams(prev => ({ ...prev, base_indicator: e.target.value }))}
+ style={{
+ width: '100%',
+ padding: '6px 8px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ }}
+ >
+ <option value="rsi">RSI</option>
+ <option value="cci">CCI</option>
+ <option value="williams_r">Williams %R</option>
+ <option value="momentum">Momentum</option>
+ <option value="stoch">Stochastic</option>
+ <option value="macd">MACD</option>
+ </select>
+ </div>
+ {renderInput('Base Period', indSignalParams.base_period ?? 14, (v) => setIndSignalParams(prev => ({ ...prev, base_period: v })), 'number')}
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>FILTER INDICATOR</div>
+ <select
+ value={indSignalParams.filter_indicator ?? 'adx'}
+ onChange={(e) => setIndSignalParams(prev => ({ ...prev, filter_indicator: e.target.value }))}
+ style={{
+ width: '100%',
+ padding: '6px 8px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ }}
+ >
+ <option value="adx">ADX</option>
+ <option value="atr">ATR</option>
+ <option value="mstd">Moving Std Dev</option>
+ <option value="zscore">Z-Score</option>
+ <option value="rsi">RSI</option>
+ </select>
+ </div>
+ {renderInput('Filter Period', indSignalParams.filter_period ?? 14, (v) => setIndSignalParams(prev => ({ ...prev, filter_period: v })), 'number')}
+ {renderInput('Filter Threshold', indSignalParams.filter_threshold ?? 25, (v) => setIndSignalParams(prev => ({ ...prev, filter_threshold: v })), 'number')}
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>FILTER TYPE</div>
+ <select
+ value={indSignalParams.filter_type ?? 'above'}
+ onChange={(e) => setIndSignalParams(prev => ({ ...prev, filter_type: e.target.value }))}
+ style={{
+ width: '100%',
+ padding: '6px 8px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ }}
+ >
+ <option value="above">Above Threshold</option>
+ <option value="below">Below Threshold</option>
+ </select>
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+ };
+
+
+
+
+
// ============================================================================
// RENDER: Helper Functions
@@ -1870,32 +1805,46 @@ const BacktestingTab: React.FC = () => {
{result && !isRunning && (
<div>
- {resultView === 'summary' && renderResultSummary()}
- {resultView === 'metrics' && renderResultMetrics()}
- {resultView === 'trades' && renderResultTrades()}
- {resultView === 'raw' && renderResultRaw()}
-
- {/* Show message if result exists but no data */}
- {!result?.data?.performance && (
- <div style={{
- padding: '12px',
- backgroundColor: `${FINCEPT.YELLOW}20`,
- border: `1px solid ${FINCEPT.YELLOW}`,
- borderRadius: '2px',
- }}>
- <div style={{
- fontSize: '9px',
- fontWeight: 700,
- color: FINCEPT.YELLOW,
- marginBottom: '4px',
- }}>
- EMPTY RESULT
- </div>
- <div style={{ fontSize: '9px', color: FINCEPT.WHITE, lineHeight: 1.4 }}>
- Backtest completed but returned no performance data. Check console logs for details.
- </div>
- </div>
+ {/* Render based on command type */}
+ {activeCommand === 'backtest' && (
+ <>
+ {resultView === 'summary' && renderResultSummary()}
+ {resultView === 'metrics' && renderResultMetrics()}
+ {resultView === 'trades' && renderResultTrades()}
+ {resultView === 'raw' && renderResultRaw()}
+
+ {/* Show message if backtest has no performance data */}
+ {!result?.data?.performance && (
+ <div style={{
+ padding: '12px',
+ backgroundColor: `${FINCEPT.YELLOW}20`,
+ border: `${FINCEPT.YELLOW}`,
+ borderRadius: '2px',
+ }}>
+ <div style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.YELLOW,
+ marginBottom: '4px',
+ }}>
+ EMPTY RESULT
+ </div>
+ <div style={{ fontSize: '9px', color: FINCEPT.WHITE, lineHeight: 1.4 }}>
+ Backtest completed but returned no performance data. Check console logs for details.
+ </div>
+ </div>
+ )}
+ </>
)}
+
+ {/* Indicator Signals - show signal counts */}
+ {activeCommand === 'indicator_signals' && renderSignalsResult()}
+
+ {/* Indicator - show indicator values */}
+ {activeCommand === 'indicator' && renderIndicatorResult()}
+
+ {/* Other commands - show raw data */}
+ {!['backtest', 'indicator_signals', 'indicator'].includes(activeCommand) && renderResultRaw()}
</div>
)}
@@ -2468,6 +2417,409 @@ const BacktestingTab: React.FC = () => {
</div>
);
+ // ============================================================================
+ // RENDER: Command-Specific Results
+ // ============================================================================
+
+
+ const renderSignalsResult = () => {
+ if (!result?.data) return renderResultRaw();
+
+ const data = result.data;
+ const entrySignals = data.entrySignals ?? data.entries ?? [];
+ const exitSignals = data.exitSignals ?? data.exits ?? [];
+ const hasMetrics = data.avgReturn !== undefined;
+
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ <div style={{
+ padding: '4px 8px',
+ backgroundColor: `${FINCEPT.GREEN}20`,
+ color: FINCEPT.GREEN,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ display: 'inline-block',
+ alignSelf: 'flex-start',
+ }}>
+ ✓ SIGNALS GENERATED{data.symbol ? ` - ${data.symbol}` : ''}
+ </div>
+
+ {/* Performance Metrics */}
+ {hasMetrics && (
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ }}>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.ORANGE, marginBottom: '12px' }}>
+ SIGNAL PERFORMANCE METRICS
+ </div>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px' }}>
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>WIN RATE</div>
+ <div style={{ fontSize: '16px', fontWeight: 700, color: data.winRate >= 50 ? FINCEPT.GREEN : FINCEPT.RED }}>
+ {data.winRate?.toFixed(1) ?? 'N/A'}%
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>AVG RETURN</div>
+ <div style={{ fontSize: '16px', fontWeight: 700, color: data.avgReturn >= 0 ? FINCEPT.GREEN : FINCEPT.RED }}>
+ {data.avgReturn?.toFixed(2) ?? 'N/A'}%
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>PROFIT FACTOR</div>
+ <div style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.CYAN }}>
+ {data.profitFactor !== null && data.profitFactor !== undefined
+ ? (data.profitFactor === Infinity ? '∞' : data.profitFactor.toFixed(2))
+ : 'N/A'}
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>SIGNALS</div>
+ <div style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.WHITE }}>
+ {data.totalSignals ?? 'N/A'}
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>BEST TRADE</div>
+ <div style={{ fontSize: '14px', fontWeight: 600, color: FINCEPT.GREEN }}>
+ +{data.bestTrade?.toFixed(2) ?? 'N/A'}%
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>WORST TRADE</div>
+ <div style={{ fontSize: '14px', fontWeight: 600, color: FINCEPT.RED }}>
+ {data.worstTrade?.toFixed(2) ?? 'N/A'}%
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>AVG HOLD (DAYS)</div>
+ <div style={{ fontSize: '14px', fontWeight: 600, color: FINCEPT.WHITE }}>
+ {data.avgHoldingPeriod?.toFixed(0) ?? 'N/A'}
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '4px' }}>SIGNAL DENSITY</div>
+ <div style={{ fontSize: '14px', fontWeight: 600, color: FINCEPT.YELLOW }}>
+ {data.signalDensity?.toFixed(1) ?? 'N/A'}%
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Signal Counts */}
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr 1fr',
+ gap: '12px',
+ }}>
+ <div>
+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px' }}>ENTRY SIGNALS</div>
+ <div style={{ fontSize: '20px', fontWeight: 700, color: FINCEPT.GREEN }}>
+ {data.entryCount ?? 0}
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px' }}>EXIT SIGNALS</div>
+ <div style={{ fontSize: '20px', fontWeight: 700, color: FINCEPT.RED }}>
+ {data.exitCount ?? 0}
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '4px' }}>TOTAL BARS</div>
+ <div style={{ fontSize: '20px', fontWeight: 700, color: FINCEPT.WHITE }}>
+ {data.totalBars ?? 0}
+ </div>
+ </div>
+ </div>
+
+ {/* Detailed Entry Signals */}
+ {entrySignals.length > 0 && (
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ }}>
+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '8px', fontWeight: 600 }}>
+ ENTRY SIGNALS (showing first 10)
+ </div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ {entrySignals.slice(0, 10).map((signal: any, idx: number) => (
+ <div key={idx} style={{
+ padding: '6px 8px',
+ backgroundColor: `${FINCEPT.GREEN}15`,
+ borderLeft: `2px solid ${FINCEPT.GREEN}`,
+ borderRadius: '2px',
+ fontSize: '8px',
+ display: 'grid',
+ gridTemplateColumns: typeof signal === 'object' ? '2fr 1fr 1fr 1fr' : '1fr',
+ gap: '8px',
+ }}>
+ {typeof signal === 'object' ? (
+ <>
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>Date: </span>
+ <span style={{ color: FINCEPT.WHITE, fontWeight: 600 }}>{signal.date}</span>
+ </div>
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>Price: </span>
+ <span style={{ color: FINCEPT.CYAN }}>${signal.price?.toFixed(2)}</span>
+ </div>
+ {signal.fastMA !== undefined && (
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>Fast: </span>
+ <span style={{ color: FINCEPT.YELLOW }}>{signal.fastMA?.toFixed(2)}</span>
+ </div>
+ )}
+ {signal.indicatorValue !== undefined && (
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>Indicator: </span>
+ <span style={{ color: FINCEPT.PURPLE }}>{signal.indicatorValue?.toFixed(2)}</span>
+ </div>
+ )}
+ </>
+ ) : (
+ <span style={{ color: FINCEPT.WHITE }}>{signal}</span>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Detailed Exit Signals */}
+ {exitSignals.length > 0 && (
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ }}>
+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '8px', fontWeight: 600 }}>
+ EXIT SIGNALS (showing first 10)
+ </div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ {exitSignals.slice(0, 10).map((signal: any, idx: number) => (
+ <div key={idx} style={{
+ padding: '6px 8px',
+ backgroundColor: `${FINCEPT.RED}15`,
+ borderLeft: `2px solid ${FINCEPT.RED}`,
+ borderRadius: '2px',
+ fontSize: '8px',
+ display: 'grid',
+ gridTemplateColumns: typeof signal === 'object' ? '2fr 1fr 1fr 1fr' : '1fr',
+ gap: '8px',
+ }}>
+ {typeof signal === 'object' ? (
+ <>
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>Date: </span>
+ <span style={{ color: FINCEPT.WHITE, fontWeight: 600 }}>{signal.date}</span>
+ </div>
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>Price: </span>
+ <span style={{ color: FINCEPT.CYAN }}>${signal.price?.toFixed(2)}</span>
+ </div>
+ {signal.slowMA !== undefined && (
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>Slow: </span>
+ <span style={{ color: FINCEPT.ORANGE }}>{signal.slowMA?.toFixed(2)}</span>
+ </div>
+ )}
+ {signal.indicatorValue !== undefined && (
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>Indicator: </span>
+ <span style={{ color: FINCEPT.PURPLE }}>{signal.indicatorValue?.toFixed(2)}</span>
+ </div>
+ )}
+ </>
+ ) : (
+ <span style={{ color: FINCEPT.WHITE }}>{signal}</span>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ };
+
+
+ const renderIndicatorResult = () => {
+ if (!result?.data) return renderResultRaw();
+
+ const data = result.data;
+ const indicator = data.indicator ?? 'Unknown';
+ const totalCombinations = data.totalCombinations ?? 0;
+ const results = data.results ?? [];
+
+ // Helper to render single stat value
+ const renderStat = (label: string, value: number | undefined, color: string) => (
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>{label}: </span>
+ <span style={{ color }}>{value?.toFixed(2) ?? 'N/A'}</span>
+ </div>
+ );
+
+ // Render single-output indicator result
+ const renderSingleOutput = (r: any, idx: number) => (
+ <div key={idx} style={{
+ padding: '6px 8px',
+ backgroundColor: `${FINCEPT.ORANGE}10`,
+ borderLeft: `2px solid ${FINCEPT.PURPLE}`,
+ borderRadius: '2px',
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr 1fr 1fr',
+ gap: '8px',
+ fontSize: '8px',
+ }}>
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>Params: </span>
+ <span style={{ color: FINCEPT.WHITE, fontWeight: 600 }}>
+ {JSON.stringify(r.params)}
+ </span>
+ </div>
+ {renderStat('Mean', r.mean, FINCEPT.CYAN)}
+ {renderStat('Last', r.last, FINCEPT.ORANGE)}
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>Range: </span>
+ <span style={{ color: FINCEPT.WHITE }}>
+ {r.min?.toFixed(2) ?? 'N/A'} - {r.max?.toFixed(2) ?? 'N/A'}
+ </span>
+ </div>
+ </div>
+ );
+
+ // Render multi-output indicator result (MACD, BBands, Stoch)
+ const renderMultiOutput = (r: any, idx: number) => {
+ const outputs = r.outputs ?? {};
+ const componentNames = Object.keys(outputs);
+
+ return (
+ <div key={idx} style={{
+ padding: '8px',
+ backgroundColor: `${FINCEPT.ORANGE}10`,
+ borderLeft: `2px solid ${FINCEPT.PURPLE}`,
+ borderRadius: '2px',
+ fontSize: '8px',
+ }}>
+ {/* Parameters */}
+ <div style={{ marginBottom: '8px', paddingBottom: '6px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <span style={{ color: FINCEPT.GRAY }}>Params: </span>
+ <span style={{ color: FINCEPT.WHITE, fontWeight: 600 }}>
+ {JSON.stringify(r.params)}
+ </span>
+ </div>
+
+ {/* Components */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
+ {componentNames.map(componentName => {
+ const component = outputs[componentName];
+ return (
+ <div key={componentName} style={{
+ padding: '4px 6px',
+ backgroundColor: `${FINCEPT.CYAN}15`,
+ borderRadius: '2px',
+ }}>
+ <div style={{ color: FINCEPT.CYAN, fontWeight: 700, marginBottom: '4px', fontSize: '7px' }}>
+ {componentName.toUpperCase()}
+ </div>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: '6px' }}>
+ {renderStat('Mean', component.mean, FINCEPT.WHITE)}
+ {renderStat('Std', component.std, FINCEPT.GRAY)}
+ {renderStat('Last', component.last, FINCEPT.ORANGE)}
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>Range: </span>
+ <span style={{ color: FINCEPT.WHITE }}>
+ {component.min?.toFixed(2) ?? 'N/A'} - {component.max?.toFixed(2) ?? 'N/A'}
+ </span>
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+ };
+
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ <div style={{
+ padding: '4px 8px',
+ backgroundColor: `${FINCEPT.GREEN}20`,
+ color: FINCEPT.GREEN,
+ fontSize: '8px',
+ fontWeight: 700,
+ borderRadius: '2px',
+ display: 'inline-block',
+ alignSelf: 'flex-start',
+ }}>
+ ✓ INDICATOR SWEEP COMPLETED
+ </div>
+
+ {/* Summary Card */}
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ }}>
+ <div style={{ marginBottom: '8px' }}>
+ <div style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.WHITE }}>
+ {indicator.toUpperCase()} PARAMETER SWEEP
+ </div>
+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY }}>
+ Total Combinations: {totalCombinations}
+ </div>
+ </div>
+ </div>
+
+ {/* Results Table */}
+ {results.length > 0 ? (
+ <div style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ }}>
+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '8px', fontWeight: 600 }}>
+ PARAMETER COMBINATIONS (showing first 20)
+ </div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ {results.slice(0, 20).map((r: any, idx: number) => {
+ // Check if this is multi-output (has 'outputs' field) or single-output
+ const isMultiOutput = r.outputs && Object.keys(r.outputs).length > 0;
+ return isMultiOutput ? renderMultiOutput(r, idx) : renderSingleOutput(r, idx);
+ })}
+ </div>
+ </div>
+ ) : (
+ <div style={{
+ padding: '12px',
+ backgroundColor: `${FINCEPT.YELLOW}20`,
+ border: `1px solid ${FINCEPT.YELLOW}`,
+ borderRadius: '2px',
+ }}>
+ <div style={{ fontSize: '9px', color: FINCEPT.YELLOW }}>
+ No parameter combinations generated. Check parameter ranges.
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ };
+
// ============================================================================
// RENDER: Status Bar
// ============================================================================
diff --git a/fincept-terminal-desktop/src/components/tabs/backtesting/backtestingProviderConfigs.ts b/fincept-terminal-desktop/src/components/tabs/backtesting/backtestingProviderConfigs.ts
index b2188867d..0cf53a064 100644
--- a/fincept-terminal-desktop/src/components/tabs/backtesting/backtestingProviderConfigs.ts
+++ b/fincept-terminal-desktop/src/components/tabs/backtesting/backtestingProviderConfigs.ts
@@ -17,9 +17,8 @@ import {
export type BacktestingProviderSlug = 'vectorbt' | 'backtestingpy' | 'fasttrade' | 'zipline' | 'bt' | 'fincept';
export type CommandType =
- | 'backtest' | 'optimize' | 'walk_forward' | 'data' | 'indicator'
- | 'indicator_signals' | 'signals' | 'labels' | 'splits' | 'returns'
- | 'browse_strategies' | 'browse_indicators' | 'labels_to_signals';
+ | 'backtest' | 'optimize' | 'walk_forward' | 'indicator'
+ | 'indicator_signals';
interface StrategyParam {
name: string;
@@ -78,16 +77,8 @@ export const ALL_COMMANDS: Command[] = [
{ id: 'backtest', label: 'Backtest', icon: Play, description: 'Run strategy backtest', color: C.ORANGE },
{ id: 'optimize', label: 'Optimize', icon: Target, description: 'Parameter optimization', color: C.GREEN },
{ id: 'walk_forward', label: 'Walk Forward', icon: ChevronRight, description: 'Walk-forward validation', color: C.BLUE },
- { id: 'data', label: 'Data', icon: Database, description: 'Download market data', color: C.CYAN },
{ id: 'indicator', label: 'Indicators', icon: Activity, description: 'Calculate indicators', color: C.PURPLE },
{ id: 'indicator_signals', label: 'Ind. Signals', icon: Zap, description: 'Indicator signals', color: C.YELLOW },
- { id: 'signals', label: 'Signals', icon: TrendingUp, description: 'Generate signals', color: C.GREEN },
- { id: 'labels', label: 'Labels', icon: Tag, description: 'ML label generation', color: C.BLUE },
- { id: 'splits', label: 'Splits', icon: Split, description: 'Cross-validation', color: C.PURPLE },
- { id: 'returns', label: 'Returns', icon: DollarSign, description: 'Returns analysis', color: C.CYAN },
- { id: 'browse_strategies', label: 'Browse Strategies', icon: Search, description: 'View strategy catalog', color: C.GREEN },
- { id: 'browse_indicators', label: 'Browse Indicators', icon: Filter, description: 'View indicator catalog', color: C.PURPLE },
- { id: 'labels_to_signals', label: 'Labels\u2192Signals', icon: ChevronRight, description: 'Convert labels to signals', color: C.YELLOW },
];
// ============================================================================
@@ -199,6 +190,28 @@ const VBT_EXTRA_TREND: Strategy[] = [
{ name: 'slowPeriod', label: 'Slow Period', default: 50, min: 10, max: 200 },
],
},
+ {
+ id: 'williams_r', name: 'Williams %R', description: 'Williams %R trend indicator',
+ params: [
+ { name: 'period', label: 'Period', default: 14, min: 5, max: 50 },
+ { name: 'oversold', label: 'Oversold', default: -80, min: -90, max: -70 },
+ { name: 'overbought', label: 'Overbought', default: -20, min: -30, max: -10 },
+ ],
+ },
+ {
+ id: 'cci', name: 'CCI', description: 'Commodity Channel Index trend',
+ params: [
+ { name: 'period', label: 'Period', default: 20, min: 5, max: 50 },
+ { name: 'oversold', label: 'Oversold', default: -100, min: -200, max: -50 },
+ { name: 'overbought', label: 'Overbought', default: 100, min: 50, max: 200 },
+ ],
+ },
+ {
+ id: 'obv_trend', name: 'OBV Trend', description: 'On-Balance Volume trend',
+ params: [
+ { name: 'maPeriod', label: 'MA Period', default: 20, min: 5, max: 100 },
+ ],
+ },
];
const VBT_EXTRA_MOMENTUM: Strategy[] = [
@@ -219,6 +232,12 @@ const VBT_EXTRA_BREAKOUT: Strategy[] = [
{ name: 'atrMultiplier', label: 'ATR Multiplier', default: 2.0, min: 0.5, max: 5.0, step: 0.1 },
],
},
+ {
+ id: 'donchian_breakout', name: 'Donchian Breakout', description: 'Donchian channel breakout',
+ params: [
+ { name: 'period', label: 'Period', default: 20, min: 5, max: 100 },
+ ],
+ },
];
const VBT_MULTI_INDICATOR: Strategy[] = [
@@ -247,29 +266,7 @@ const VBT_MULTI_INDICATOR: Strategy[] = [
},
];
-const VBT_OTHER: Strategy[] = [
- {
- id: 'williams_r', name: 'Williams %R', description: 'Williams %R oscillator',
- params: [
- { name: 'period', label: 'Period', default: 14, min: 5, max: 50 },
- { name: 'oversold', label: 'Oversold', default: -80, min: -90, max: -70 },
- { name: 'overbought', label: 'Overbought', default: -20, min: -30, max: -10 },
- ],
- },
- {
- id: 'cci', name: 'CCI', description: 'Commodity Channel Index',
- params: [
- { name: 'period', label: 'Period', default: 20, min: 5, max: 50 },
- { name: 'threshold', label: 'Threshold', default: 100, min: 50, max: 200 },
- ],
- },
- {
- id: 'obv_trend', name: 'OBV Trend', description: 'On-Balance Volume trend',
- params: [
- { name: 'maPeriod', label: 'MA Period', default: 20, min: 5, max: 100 },
- ],
- },
-];
+const VBT_OTHER: Strategy[] = [];
const VBT_CUSTOM: Strategy[] = [
{ id: 'code', name: 'Custom Code', description: 'Python custom strategy', params: [] },
@@ -363,24 +360,14 @@ const VECTORBT_CONFIG: BacktestingProviderConfig = {
slug: 'vectorbt',
displayName: 'VECTORBT',
commands: [
- 'backtest', 'optimize', 'walk_forward', 'data', 'indicator',
- 'indicator_signals', 'signals', 'labels', 'splits', 'returns',
- 'browse_strategies', 'browse_indicators', 'labels_to_signals',
+ 'backtest', 'optimize', 'walk_forward', 'indicator', 'indicator_signals',
],
commandMap: {
backtest: 'run_backtest',
optimize: 'optimize',
walk_forward: 'walk_forward',
- data: 'get_historical_data',
indicator: 'indicator_param_sweep',
indicator_signals: 'indicator_signals',
- signals: 'generate_signals',
- labels: 'generate_labels',
- splits: 'generate_splits',
- returns: 'analyze_returns',
- browse_strategies: 'get_strategies',
- browse_indicators: 'get_indicators',
- labels_to_signals: 'labels_to_signals',
},
strategies: {
trend: [...SHARED_TREND, ...VBT_EXTRA_TREND],
@@ -547,18 +534,13 @@ const BACKTESTINGPY_CONFIG: BacktestingProviderConfig = {
slug: 'backtestingpy',
displayName: 'BACKTESTING.PY',
commands: [
- 'backtest', 'optimize', 'walk_forward', 'data', 'indicator',
- 'signals', 'browse_strategies', 'browse_indicators',
+ 'backtest', 'optimize', 'walk_forward', 'indicator',
],
commandMap: {
backtest: 'run_backtest',
optimize: 'optimize',
walk_forward: 'walk_forward',
- data: 'get_historical_data',
indicator: 'calculate_indicator',
- signals: 'generate_signals',
- browse_strategies: 'get_strategies',
- browse_indicators: 'get_indicators',
},
strategies: {
trend: [...SHARED_TREND, ...BTP_EXTRA_TREND],
@@ -724,24 +706,14 @@ const ZIPLINE_CONFIG: BacktestingProviderConfig = {
slug: 'zipline',
displayName: 'ZIPLINE',
commands: [
- 'backtest', 'optimize', 'walk_forward', 'data', 'indicator',
- 'indicator_signals', 'signals', 'labels', 'splits', 'returns',
- 'browse_strategies', 'browse_indicators', 'labels_to_signals',
+ 'backtest', 'optimize', 'walk_forward', 'indicator', 'indicator_signals',
],
commandMap: {
backtest: 'run_backtest',
optimize: 'optimize',
walk_forward: 'walk_forward',
- data: 'get_historical_data',
indicator: 'calculate_indicator',
indicator_signals: 'indicator_signals',
- signals: 'generate_signals',
- labels: 'generate_labels',
- splits: 'generate_splits',
- returns: 'analyze_returns',
- browse_strategies: 'get_strategies',
- browse_indicators: 'get_indicators',
- labels_to_signals: 'labels_to_signals',
},
strategies: {
trend: [...SHARED_TREND, ...ZIPLINE_EXTRA_TREND],
@@ -828,24 +800,14 @@ const BT_CONFIG: BacktestingProviderConfig = {
slug: 'bt',
displayName: 'BT',
commands: [
- 'backtest', 'optimize', 'walk_forward', 'data', 'indicator',
- 'indicator_signals', 'signals', 'labels', 'splits', 'returns',
- 'browse_strategies', 'browse_indicators', 'labels_to_signals',
+ 'backtest', 'optimize', 'walk_forward', 'indicator', 'indicator_signals',
],
commandMap: {
backtest: 'run_backtest',
optimize: 'optimize',
walk_forward: 'walk_forward',
- data: 'get_historical_data',
indicator: 'calculate_indicator',
indicator_signals: 'indicator_signals',
- signals: 'generate_signals',
- labels: 'generate_labels',
- splits: 'generate_splits',
- returns: 'analyze_returns',
- browse_strategies: 'get_strategies',
- browse_indicators: 'get_indicators',
- labels_to_signals: 'labels_to_signals',
},
strategies: {
portfolio: [...BT_PORTFOLIO],
@@ -871,10 +833,9 @@ const BT_CONFIG: BacktestingProviderConfig = {
const FINCEPT_CONFIG: BacktestingProviderConfig = {
slug: 'fincept',
displayName: 'FINCEPT ENGINE',
- commands: ['backtest', 'browse_strategies'],
+ commands: ['backtest'],
commandMap: {
backtest: 'execute_fincept_strategy',
- browse_strategies: 'list_strategies',
},
strategies: {
// Dynamically loaded from _registry.py
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx
index ec3f38e30..990e49ee4 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx
@@ -3,6 +3,7 @@ import React, { useState, useEffect, useCallback, useReducer, useRef } from 'rea
import { useWorkspaceTabState } from '@/hooks/useWorkspaceTabState';
import { useTranslation } from 'react-i18next';
import { invoke } from '@tauri-apps/api/core';
+import { listen } from '@tauri-apps/api/event';
import { useBrokerContext } from '@/contexts/BrokerContext';
import { useRustTicker, useRustOrderBook, useRustTrades } from '@/hooks/useRustWebSocket';
@@ -43,7 +44,7 @@ import type { OrderRequest } from '@/types/trading';
// Constants
const API_TIMEOUT_MS = 30000;
const WATCHLIST_REFRESH_MS = 30000;
-const PAPER_TRADING_REFRESH_MS = 5000; // Reduced from 1s to 5s for production
+const PAPER_TRADING_REFRESH_MS = 30000; // 30 second fallback sync (WebSocket handles real-time)
// State machine types
type CryptoStatus = 'idle' | 'loading' | 'ready' | 'error';
@@ -75,7 +76,9 @@ type CryptoAction =
| { type: 'SET_PAPER_DATA'; positions: Position[]; orders: Order[]; trades: any[]; balance: number; equity: number; stats: any }
| { type: 'SET_SYMBOLS'; symbols: string[]; isLoading: boolean }
| { type: 'RESET_DATA' }
- | { type: 'CLEAR_TICKER_TRADES' };
+ | { type: 'CLEAR_TICKER_TRADES' }
+ | { type: 'UPDATE_POSITION_PRICES'; prices: Map<string, number> }
+ | { type: 'UPDATE_FROM_TRADE'; trade: { symbol: string; side: 'buy' | 'sell'; price: number; quantity: number; timestamp: number } };
const initialState: CryptoState = {
status: 'idle',
@@ -130,6 +133,99 @@ function cryptoReducer(state: CryptoState, action: CryptoAction): CryptoState {
};
case 'CLEAR_TICKER_TRADES':
return { ...state, tickerData: null, tradesData: [] };
+ case 'UPDATE_POSITION_PRICES':
+ return {
+ ...state,
+ positions: state.positions.map(pos => {
+ const newPrice = action.prices.get(pos.symbol);
+ if (!newPrice) return pos;
+
+ const entryPrice = pos.entryPrice || 0;
+ const quantity = pos.quantity || 0;
+
+ // Recalculate P&L with new price
+ let unrealizedPnl = 0;
+ let pnlPercent = 0;
+
+ if (newPrice > 0 && entryPrice > 0 && quantity > 0) {
+ if (pos.side === 'long') {
+ unrealizedPnl = (newPrice - entryPrice) * quantity;
+ } else {
+ unrealizedPnl = (entryPrice - newPrice) * quantity;
+ }
+ pnlPercent = ((newPrice - entryPrice) / entryPrice) * 100;
+ if (pos.side === 'short') pnlPercent = -pnlPercent;
+ }
+
+ return {
+ ...pos,
+ currentPrice: newPrice,
+ unrealizedPnl,
+ pnlPercent,
+ positionValue: newPrice * quantity,
+ };
+ }),
+ };
+ case 'UPDATE_FROM_TRADE':
+ // Handle position updates from trade execution
+ const { trade } = action;
+ const existingPos = state.positions.find(p => p.symbol === trade.symbol);
+
+ let updatedPositions = [...state.positions];
+
+ if (!existingPos) {
+ // New position opened
+ updatedPositions.push({
+ symbol: trade.symbol,
+ side: trade.side === 'buy' ? 'long' : 'short',
+ quantity: trade.quantity,
+ entryPrice: trade.price,
+ currentPrice: trade.price,
+ positionValue: trade.price * trade.quantity,
+ unrealizedPnl: 0,
+ pnlPercent: 0,
+ });
+ } else {
+ // Update existing position or close it
+ updatedPositions = updatedPositions.map(pos => {
+ if (pos.symbol !== trade.symbol) return pos;
+
+ const isSameSide = (pos.side === 'long' && trade.side === 'buy') || (pos.side === 'short' && trade.side === 'sell');
+
+ if (isSameSide) {
+ // Adding to position - recalculate average entry
+ const totalQty = pos.quantity + trade.quantity;
+ const newEntry = ((pos.entryPrice * pos.quantity) + (trade.price * trade.quantity)) / totalQty;
+
+ return {
+ ...pos,
+ quantity: totalQty,
+ entryPrice: newEntry,
+ positionValue: trade.price * totalQty,
+ };
+ } else {
+ // Reducing position
+ const newQty = pos.quantity - trade.quantity;
+
+ if (newQty <= 0) {
+ // Position closed - will be filtered out
+ return null;
+ }
+
+ return {
+ ...pos,
+ quantity: newQty,
+ positionValue: trade.price * newQty,
+ };
+ }
+ }).filter(Boolean) as Position[];
+ }
+
+ return {
+ ...state,
+ positions: updatedPositions,
+ trades: [trade, ...state.trades].slice(0, 50), // Keep last 50 trades
+ };
default:
return state;
}
@@ -593,6 +689,53 @@ export function CryptoTradingTab() {
}
}, [tradingMode, paperAdapter, activeBroker]);
+ // Real-time WebSocket listeners for positions
+ useEffect(() => {
+ let mounted = true;
+ const unlisteners: (() => void)[] = [];
+
+ const setupWebSocketListeners = async () => {
+ // 1. Price updates (ws_ticker)
+ const tickerUnlisten = await listen<{ provider: string; symbol: string; price: number }>('ws_ticker', (event) => {
+ if (!mounted) return;
+
+ const { symbol, price } = event.payload;
+
+ // Check if we have a position for this symbol
+ const hasPosition = state.positions.some(p => p.symbol === symbol);
+ if (!hasPosition) return;
+
+ // Update position prices
+ const priceMap = new Map<string, number>();
+ priceMap.set(symbol, price);
+
+ dispatch({ type: 'UPDATE_POSITION_PRICES', prices: priceMap });
+ });
+ unlisteners.push(tickerUnlisten);
+
+ // 2. Trade executions (ws_trade) - for paper trading fills
+ const tradeUnlisten = await listen<{ provider: string; symbol: string; price: number; quantity: number; side: 'buy' | 'sell'; timestamp: number }>('ws_trade', (event) => {
+ if (!mounted) return;
+
+ const { symbol, price, quantity, side, timestamp } = event.payload;
+
+ // Update positions based on trade execution
+ dispatch({
+ type: 'UPDATE_FROM_TRADE',
+ trade: { symbol, price, quantity, side, timestamp }
+ });
+ });
+ unlisteners.push(tradeUnlisten);
+ };
+
+ setupWebSocketListeners();
+
+ return () => {
+ mounted = false;
+ unlisteners.forEach(unlisten => unlisten());
+ };
+ }, [state.positions]);
+
useEffect(() => {
loadPaperTradingData();
const interval = setInterval(loadPaperTradingData, PAPER_TRADING_REFRESH_MS);
diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/MCPAddServerModal.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/MCPAddServerModal.tsx
index 821a584ba..f247c4ba6 100644
--- a/fincept-terminal-desktop/src/components/tabs/mcp/MCPAddServerModal.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/mcp/MCPAddServerModal.tsx
@@ -1,15 +1,33 @@
// MCP Add Server Modal Component
// Add custom MCP servers manually - Fincept UI Design System
+// Production-ready: Input validation, sanitization, error handling
-import React, { useState } from 'react';
-import { X, Plus } from 'lucide-react';
+import React, { useState, useCallback } from 'react';
+import { X, Plus, AlertCircle } from 'lucide-react';
import { showWarning } from '@/utils/notifications';
+import { validateString, sanitizeInput } from '@/services/core/validators';
interface MCPAddServerModalProps {
onClose: () => void;
onAdd: (serverConfig: any) => void;
}
+interface FormErrors {
+ name?: string;
+ command?: string;
+ args?: string;
+ envVars?: string;
+}
+
+// Allowed commands for security
+const ALLOWED_COMMANDS = ['bunx', 'npx', 'node', 'python', 'python3', 'uvx', 'uv', 'pip', 'pipx'];
+
+// Pattern for valid server names
+const SERVER_NAME_PATTERN = /^[a-zA-Z0-9\s\-_]+$/;
+
+// Pattern for valid command
+const COMMAND_PATTERN = /^[a-zA-Z0-9\-_]+$/;
+
const FINCEPT = {
ORANGE: '#FF8800',
WHITE: '#FFFFFF',
@@ -38,43 +56,209 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })
icon: '🔧',
});
+ const [errors, setErrors] = useState<FormErrors>({});
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ // Validate server name
+ const validateName = useCallback((name: string): string | undefined => {
+ const trimmed = name.trim();
+
+ if (!trimmed) {
+ return 'Server name is required';
+ }
+
+ if (trimmed.length < 2) {
+ return 'Server name must be at least 2 characters';
+ }
+
+ if (trimmed.length > 50) {
+ return 'Server name must be at most 50 characters';
+ }
+
+ if (!SERVER_NAME_PATTERN.test(trimmed)) {
+ return 'Server name can only contain letters, numbers, spaces, hyphens, and underscores';
+ }
+
+ return undefined;
+ }, []);
+
+ // Validate command
+ const validateCommand = useCallback((command: string): string | undefined => {
+ const trimmed = command.trim().toLowerCase();
+
+ if (!trimmed) {
+ return 'Command is required';
+ }
+
+ if (!COMMAND_PATTERN.test(trimmed)) {
+ return 'Command contains invalid characters';
+ }
+
+ if (!ALLOWED_COMMANDS.includes(trimmed)) {
+ return `Command must be one of: ${ALLOWED_COMMANDS.join(', ')}`;
+ }
+
+ return undefined;
+ }, []);
+
+ // Validate arguments
+ const validateArgs = useCallback((args: string): string | undefined => {
+ const trimmed = args.trim();
+
+ if (!trimmed) {
+ return 'Arguments are required';
+ }
+
+ if (trimmed.length > 500) {
+ return 'Arguments too long (max 500 characters)';
+ }
+
+ // Check for potentially dangerous characters (basic shell injection prevention)
+ const dangerousPatterns = [/;/, /&&/, /\|\|/, /\|/, /`/, /\$\(/, /\$\{/];
+ for (const pattern of dangerousPatterns) {
+ if (pattern.test(trimmed)) {
+ return 'Arguments contain potentially unsafe characters';
+ }
+ }
+
+ return undefined;
+ }, []);
+
+ // Validate environment variables
+ const validateEnvVars = useCallback((envVars: string): string | undefined => {
+ if (!envVars.trim()) {
+ return undefined; // Optional field
+ }
+
+ const lines = envVars.trim().split('\n');
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i].trim();
+ if (!line) continue;
+
+ // Check format KEY=VALUE
+ if (!line.includes('=')) {
+ return `Line ${i + 1}: Invalid format. Use KEY=VALUE`;
+ }
+
+ const [key] = line.split('=');
+ const trimmedKey = key.trim();
+
+ // Validate key name
+ if (!/^[A-Z_][A-Z0-9_]*$/i.test(trimmedKey)) {
+ return `Line ${i + 1}: Invalid key name "${trimmedKey}"`;
+ }
+ }
+
+ return undefined;
+ }, []);
+
+ // Validate entire form
+ const validateForm = useCallback((): boolean => {
+ const newErrors: FormErrors = {
+ name: validateName(formData.name),
+ command: validateCommand(formData.command),
+ args: validateArgs(formData.args),
+ envVars: validateEnvVars(formData.envVars),
+ };
+
+ setErrors(newErrors);
+
+ return !Object.values(newErrors).some(error => error !== undefined);
+ }, [formData, validateName, validateCommand, validateArgs, validateEnvVars]);
+
+ // Handle field change with real-time validation
+ const handleFieldChange = useCallback((field: keyof typeof formData, value: string) => {
+ setFormData(prev => ({ ...prev, [field]: value }));
+
+ // Clear error on change
+ if (errors[field as keyof FormErrors]) {
+ setErrors(prev => ({ ...prev, [field]: undefined }));
+ }
+ }, [errors]);
+
+ // Handle blur with validation
+ const handleFieldBlur = useCallback((field: keyof typeof formData) => {
+ let error: string | undefined;
+
+ switch (field) {
+ case 'name':
+ error = validateName(formData.name);
+ break;
+ case 'command':
+ error = validateCommand(formData.command);
+ break;
+ case 'args':
+ error = validateArgs(formData.args);
+ break;
+ case 'envVars':
+ error = validateEnvVars(formData.envVars);
+ break;
+ }
+
+ if (error) {
+ setErrors(prev => ({ ...prev, [field]: error }));
+ }
+ }, [formData, validateName, validateCommand, validateArgs, validateEnvVars]);
+
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
- if (!formData.name || !formData.command || !formData.args) {
- showWarning('Please fill in all required fields');
+ if (!validateForm()) {
+ showWarning('Please fix the validation errors');
return;
}
- const args = formData.args
- .trim()
- .split(/[\s,]+/)
- .filter(arg => arg.length > 0);
-
- const env: Record<string, string> = {};
- if (formData.envVars.trim()) {
- formData.envVars.split('\n').forEach(line => {
- const [key, ...valueParts] = line.trim().split('=');
- if (key && valueParts.length > 0) {
- env[key.trim()] = valueParts.join('=').trim();
- }
- });
- }
+ setIsSubmitting(true);
- const id = formData.name.toLowerCase().replace(/[^a-z0-9]/g, '-');
-
- const serverConfig = {
- id,
- name: formData.name,
- description: formData.description || `Custom MCP server: ${formData.name}`,
- command: formData.command,
- args,
- env,
- category: formData.category,
- icon: formData.icon,
- };
+ try {
+ // Sanitize inputs
+ const sanitizedName = sanitizeInput(formData.name.trim());
+ const sanitizedDescription = sanitizeInput(formData.description.trim());
+ const sanitizedCommand = formData.command.trim().toLowerCase();
+
+ // Parse and sanitize arguments
+ const args = formData.args
+ .trim()
+ .split(/[\s,]+/)
+ .filter(arg => arg.length > 0)
+ .map(arg => sanitizeInput(arg));
+
+ // Parse environment variables
+ const env: Record<string, string> = {};
+ if (formData.envVars.trim()) {
+ formData.envVars.split('\n').forEach(line => {
+ const trimmedLine = line.trim();
+ if (!trimmedLine) return;
+
+ const [key, ...valueParts] = trimmedLine.split('=');
+ if (key && valueParts.length > 0) {
+ env[key.trim()] = valueParts.join('=').trim();
+ }
+ });
+ }
+
+ // Generate safe ID
+ const id = sanitizedName.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/-+/g, '-');
- onAdd(serverConfig);
+ const serverConfig = {
+ id,
+ name: sanitizedName,
+ description: sanitizedDescription || `Custom MCP server: ${sanitizedName}`,
+ command: sanitizedCommand,
+ args,
+ env,
+ category: formData.category,
+ icon: formData.icon.slice(0, 2) || '🔧', // Limit emoji length
+ };
+
+ onAdd(serverConfig);
+ } catch (error) {
+ console.error('Error creating server config:', error);
+ showWarning('Failed to create server configuration');
+ } finally {
+ setIsSubmitting(false);
+ }
};
const inputStyle: React.CSSProperties = {
@@ -89,6 +273,11 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })
outline: 'none',
};
+ const inputErrorStyle: React.CSSProperties = {
+ ...inputStyle,
+ borderColor: FINCEPT.RED,
+ };
+
const labelStyle: React.CSSProperties = {
display: 'block',
fontSize: '9px',
@@ -98,6 +287,15 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })
marginBottom: '6px',
};
+ const errorTextStyle: React.CSSProperties = {
+ color: FINCEPT.RED,
+ fontSize: '9px',
+ marginTop: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ };
+
return (
<div style={{
position: 'fixed',
@@ -165,13 +363,22 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })
<input
type="text"
value={formData.name}
- onChange={(e) => setFormData({ ...formData, name: e.target.value })}
+ onChange={(e) => handleFieldChange('name', e.target.value)}
+ onBlur={() => handleFieldBlur('name')}
placeholder="e.g., My Custom Server"
required
- style={inputStyle}
- onFocus={(e) => { e.currentTarget.style.borderColor = FINCEPT.ORANGE; }}
- onBlur={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}
+ maxLength={50}
+ style={errors.name ? inputErrorStyle : inputStyle}
+ onFocus={(e) => {
+ if (!errors.name) e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ }}
/>
+ {errors.name && (
+ <div style={errorTextStyle}>
+ <AlertCircle size={10} />
+ {errors.name}
+ </div>
+ )}
</div>
{/* Description */}
@@ -180,8 +387,9 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })
<input
type="text"
value={formData.description}
- onChange={(e) => setFormData({ ...formData, description: e.target.value })}
+ onChange={(e) => handleFieldChange('description', e.target.value)}
placeholder="What does this server do?"
+ maxLength={200}
style={inputStyle}
onFocus={(e) => { e.currentTarget.style.borderColor = FINCEPT.ORANGE; }}
onBlur={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}
@@ -191,16 +399,27 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })
{/* Command */}
<div style={{ marginBottom: '16px' }}>
<label style={labelStyle}>COMMAND *</label>
- <input
- type="text"
+ <select
value={formData.command}
- onChange={(e) => setFormData({ ...formData, command: e.target.value })}
- placeholder="bunx, node, python, etc."
- required
- style={inputStyle}
- onFocus={(e) => { e.currentTarget.style.borderColor = FINCEPT.ORANGE; }}
- onBlur={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}
- />
+ onChange={(e) => handleFieldChange('command', e.target.value)}
+ style={{
+ ...inputStyle,
+ cursor: 'pointer',
+ }}
+ >
+ {ALLOWED_COMMANDS.map(cmd => (
+ <option key={cmd} value={cmd}>{cmd}</option>
+ ))}
+ </select>
+ {errors.command && (
+ <div style={errorTextStyle}>
+ <AlertCircle size={10} />
+ {errors.command}
+ </div>
+ )}
+ <div style={{ color: FINCEPT.MUTED, fontSize: '9px', marginTop: '4px' }}>
+ Allowed: {ALLOWED_COMMANDS.join(', ')}
+ </div>
</div>
{/* Arguments */}
@@ -209,13 +428,22 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })
<input
type="text"
value={formData.args}
- onChange={(e) => setFormData({ ...formData, args: e.target.value })}
+ onChange={(e) => handleFieldChange('args', e.target.value)}
+ onBlur={() => handleFieldBlur('args')}
placeholder="e.g., -y @modelcontextprotocol/server-example"
required
- style={inputStyle}
- onFocus={(e) => { e.currentTarget.style.borderColor = FINCEPT.ORANGE; }}
- onBlur={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}
+ maxLength={500}
+ style={errors.args ? inputErrorStyle : inputStyle}
+ onFocus={(e) => {
+ if (!errors.args) e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ }}
/>
+ {errors.args && (
+ <div style={errorTextStyle}>
+ <AlertCircle size={10} />
+ {errors.args}
+ </div>
+ )}
<div style={{ color: FINCEPT.MUTED, fontSize: '9px', marginTop: '4px' }}>
Example: -y @modelcontextprotocol/server-postgres
</div>
@@ -226,16 +454,24 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })
<label style={labelStyle}>ENVIRONMENT VARIABLES (ONE PER LINE)</label>
<textarea
value={formData.envVars}
- onChange={(e) => setFormData({ ...formData, envVars: e.target.value })}
+ onChange={(e) => handleFieldChange('envVars', e.target.value)}
+ onBlur={() => handleFieldBlur('envVars')}
placeholder={'DATABASE_URL=postgresql://...\nAPI_KEY=your-key-here'}
rows={3}
style={{
- ...inputStyle,
+ ...(errors.envVars ? inputErrorStyle : inputStyle),
resize: 'vertical',
}}
- onFocus={(e) => { e.currentTarget.style.borderColor = FINCEPT.ORANGE; }}
- onBlur={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}
+ onFocus={(e) => {
+ if (!errors.envVars) e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ }}
/>
+ {errors.envVars && (
+ <div style={errorTextStyle}>
+ <AlertCircle size={10} />
+ {errors.envVars}
+ </div>
+ )}
<div style={{ color: FINCEPT.MUTED, fontSize: '9px', marginTop: '4px' }}>
Format: KEY=VALUE (one per line)
</div>
@@ -247,7 +483,7 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })
<input
type="text"
value={formData.icon}
- onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
+ onChange={(e) => handleFieldChange('icon', e.target.value)}
placeholder="🔧"
maxLength={2}
style={{
@@ -270,6 +506,7 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })
<button
type="button"
onClick={onClose}
+ disabled={isSubmitting}
style={{
padding: '6px 10px',
backgroundColor: 'transparent',
@@ -278,13 +515,16 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })
fontSize: '9px',
fontWeight: 700,
borderRadius: '2px',
- cursor: 'pointer',
+ cursor: isSubmitting ? 'not-allowed' : 'pointer',
fontFamily: FONT_FAMILY,
transition: 'all 0.2s',
+ opacity: isSubmitting ? 0.5 : 1,
}}
onMouseEnter={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.ORANGE;
- e.currentTarget.style.color = FINCEPT.WHITE;
+ if (!isSubmitting) {
+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ e.currentTarget.style.color = FINCEPT.WHITE;
+ }
}}
onMouseLeave={(e) => {
e.currentTarget.style.borderColor = FINCEPT.BORDER;
@@ -295,15 +535,16 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })
</button>
<button
type="submit"
+ disabled={isSubmitting}
style={{
padding: '8px 16px',
- backgroundColor: FINCEPT.ORANGE,
+ backgroundColor: isSubmitting ? FINCEPT.MUTED : FINCEPT.ORANGE,
color: FINCEPT.DARK_BG,
border: 'none',
borderRadius: '2px',
fontSize: '9px',
fontWeight: 700,
- cursor: 'pointer',
+ cursor: isSubmitting ? 'not-allowed' : 'pointer',
display: 'flex',
alignItems: 'center',
gap: '4px',
@@ -311,7 +552,7 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })
}}
>
<Plus size={10} />
- ADD SERVER
+ {isSubmitting ? 'ADDING...' : 'ADD SERVER'}
</button>
</div>
</form>
diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/MCPToolsManagement.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/MCPToolsManagement.tsx
index fac867323..1fc4e47a4 100644
--- a/fincept-terminal-desktop/src/components/tabs/mcp/MCPToolsManagement.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/mcp/MCPToolsManagement.tsx
@@ -1,10 +1,18 @@
// MCP Tools Management - Manage both internal and external MCP tools
// Fincept UI Design System
-import React, { useState, useEffect } from 'react';
+// Production-ready: useReducer, AbortController, ErrorBoundary, timeout, deduplication
+
+import React, { useReducer, useEffect, useCallback, useRef } from 'react';
import { Settings, ToggleLeft, ToggleRight, Search, CheckCircle, XCircle, AlertCircle } from 'lucide-react';
import { mcpToolService } from '@/services/mcp/mcpToolService';
import { INTERNAL_SERVER_ID } from '@/services/mcp/internal';
import { showWarning } from '@/utils/notifications';
+import { ErrorBoundary } from '@/components/common/ErrorBoundary';
+import { withTimeout, deduplicatedFetch } from '@/services/core/apiUtils';
+
+// ============================================================================
+// Types & State Machine
+// ============================================================================
interface MCPToolWithStatus {
serverId: string;
@@ -20,6 +28,75 @@ interface MCPToolsManagementProps {
onClose?: () => void;
}
+type ToolsStatus = 'idle' | 'loading' | 'success' | 'error';
+
+interface ToolsState {
+ status: ToolsStatus;
+ tools: MCPToolWithStatus[];
+ statusMessage: string;
+ error: string | null;
+ searchTerm: string;
+ selectedCategory: string | null;
+}
+
+type ToolsAction =
+ | { type: 'LOAD_START' }
+ | { type: 'LOAD_SUCCESS'; payload: MCPToolWithStatus[] }
+ | { type: 'LOAD_ERROR'; payload: string }
+ | { type: 'SET_STATUS_MESSAGE'; payload: string }
+ | { type: 'SET_SEARCH_TERM'; payload: string }
+ | { type: 'SET_SELECTED_CATEGORY'; payload: string | null }
+ | { type: 'UPDATE_TOOL'; payload: { name: string; serverId: string; isEnabled: boolean } };
+
+const initialState: ToolsState = {
+ status: 'idle',
+ tools: [],
+ statusMessage: 'Loading tools...',
+ error: null,
+ searchTerm: '',
+ selectedCategory: null,
+};
+
+function toolsReducer(state: ToolsState, action: ToolsAction): ToolsState {
+ switch (action.type) {
+ case 'LOAD_START':
+ return { ...state, status: 'loading', error: null };
+ case 'LOAD_SUCCESS':
+ return {
+ ...state,
+ status: 'success',
+ tools: action.payload,
+ statusMessage: `${action.payload.length} tools loaded`,
+ error: null,
+ };
+ case 'LOAD_ERROR':
+ return { ...state, status: 'error', error: action.payload, statusMessage: action.payload };
+ case 'SET_STATUS_MESSAGE':
+ return { ...state, statusMessage: action.payload };
+ case 'SET_SEARCH_TERM':
+ return { ...state, searchTerm: action.payload };
+ case 'SET_SELECTED_CATEGORY':
+ return { ...state, selectedCategory: action.payload };
+ case 'UPDATE_TOOL':
+ return {
+ ...state,
+ tools: state.tools.map(t =>
+ t.name === action.payload.name && t.serverId === action.payload.serverId
+ ? { ...t, isEnabled: action.payload.isEnabled }
+ : t
+ ),
+ };
+ default:
+ return state;
+ }
+}
+
+// ============================================================================
+// Constants
+// ============================================================================
+
+const TIMEOUT_MS = 15000; // 15 second timeout
+
const FINCEPT = {
ORANGE: '#FF8800',
WHITE: '#FFFFFF',
@@ -56,24 +133,98 @@ const TOOL_CATEGORIES = [
{ id: 'external', label: 'EXTERNAL TOOLS', color: FINCEPT.ORANGE },
];
-const MCPToolsManagement: React.FC<MCPToolsManagementProps> = ({ onClose }) => {
- const [tools, setTools] = useState<MCPToolWithStatus[]>([]);
- const [loading, setLoading] = useState(true);
- const [searchTerm, setSearchTerm] = useState('');
- const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
- const [statusMessage, setStatusMessage] = useState('Loading tools...');
+// ============================================================================
+// Helper Functions
+// ============================================================================
- useEffect(() => {
- loadTools();
+const getToolCategory = (toolName: string): string => {
+ const categoryMap: Record<string, string> = {
+ navigate_tab: 'navigation', navigate_screen: 'navigation', get_active_tab: 'navigation', open_settings_section: 'navigation',
+ place_order: 'trading', cancel_order: 'trading', modify_order: 'trading', get_positions: 'trading', get_balance: 'trading', get_orders: 'trading', get_holdings: 'trading', close_position: 'trading',
+ crypto_place_market_order: 'crypto-trading', crypto_place_limit_order: 'crypto-trading', crypto_place_stop_loss: 'crypto-trading', crypto_cancel_order: 'crypto-trading', crypto_cancel_all_orders: 'crypto-trading', crypto_get_positions: 'crypto-trading', crypto_close_position: 'crypto-trading', crypto_get_balance: 'crypto-trading', crypto_get_holdings: 'crypto-trading', crypto_get_orders: 'crypto-trading', crypto_get_ticker: 'crypto-trading', crypto_get_orderbook: 'crypto-trading', crypto_add_to_watchlist: 'crypto-trading', crypto_remove_from_watchlist: 'crypto-trading', crypto_search_symbol: 'crypto-trading', crypto_switch_trading_mode: 'crypto-trading', crypto_switch_broker: 'crypto-trading', crypto_get_portfolio_value: 'crypto-trading', crypto_get_pnl: 'crypto-trading', crypto_set_stop_loss_for_position: 'crypto-trading', crypto_set_take_profit: 'crypto-trading',
+ create_portfolio: 'portfolio', list_portfolios: 'portfolio', add_asset: 'portfolio', remove_asset: 'portfolio', add_transaction: 'portfolio', get_portfolio_summary: 'portfolio',
+ add_widget: 'dashboard', remove_widget: 'dashboard', list_widgets: 'dashboard', configure_widget: 'dashboard',
+ set_theme: 'settings', get_theme: 'settings', set_language: 'settings', get_settings: 'settings', set_setting: 'settings',
+ save_workspace: 'workspace', load_workspace: 'workspace', list_workspaces: 'workspace', delete_workspace: 'workspace',
+ run_backtest: 'backtesting', optimize_strategy: 'backtesting', get_historical_data: 'backtesting',
+ get_quote: 'market-data', add_to_watchlist: 'market-data', remove_from_watchlist: 'market-data', search_symbol: 'market-data',
+ create_workflow: 'workflow', run_workflow: 'workflow', stop_workflow: 'workflow', list_workflows: 'workflow',
+ create_note: 'notes', list_notes: 'notes', delete_note: 'notes', generate_report: 'notes',
+ };
+ return categoryMap[toolName] || 'other';
+};
+
+const getCategoryColor = (categoryId: string) => {
+ const category = TOOL_CATEGORIES.find(c => c.id === categoryId);
+ return category?.color || FINCEPT.GRAY;
+};
+
+const getCategoryLabel = (categoryId: string) => {
+ const category = TOOL_CATEGORIES.find(c => c.id === categoryId);
+ return category?.label || 'OTHER';
+};
+
+// ============================================================================
+// Inner Component
+// ============================================================================
+
+const MCPToolsManagementInner: React.FC<MCPToolsManagementProps> = ({ onClose }) => {
+ const [state, dispatch] = useReducer(toolsReducer, initialState);
+
+ // Refs for cleanup and deduplication
+ const abortControllerRef = useRef<AbortController | null>(null);
+ const mountedRef = useRef(true);
+ const pendingOperationsRef = useRef<Set<string>>(new Set());
+
+ // Safe dispatch
+ const safeDispatch = useCallback((action: ToolsAction) => {
+ if (mountedRef.current) {
+ dispatch(action);
+ }
+ }, []);
+
+ // Deduplication helpers
+ const isOperationPending = useCallback((opKey: string): boolean => {
+ return pendingOperationsRef.current.has(opKey);
}, []);
- const loadTools = async () => {
+ const markOperationStart = useCallback((opKey: string) => {
+ pendingOperationsRef.current.add(opKey);
+ }, []);
+
+ const markOperationEnd = useCallback((opKey: string) => {
+ pendingOperationsRef.current.delete(opKey);
+ }, []);
+
+ // Load tools with deduplication and timeout
+ const loadTools = useCallback(async () => {
+ const opKey = 'loadTools';
+
+ if (isOperationPending(opKey)) {
+ return;
+ }
+
+ if (abortControllerRef.current?.signal.aborted) {
+ return;
+ }
+
+ markOperationStart(opKey);
+ safeDispatch({ type: 'LOAD_START' });
+
try {
- setLoading(true);
- setStatusMessage('Loading tools...');
+ const [internalTools, allTools] = await Promise.all([
+ deduplicatedFetch('tools:internal', () =>
+ withTimeout(mcpToolService.getAllInternalTools(), TIMEOUT_MS, 'Internal tools timeout')
+ ),
+ deduplicatedFetch('tools:all', () =>
+ withTimeout(mcpToolService.getAllTools(), TIMEOUT_MS, 'All tools timeout')
+ ),
+ ]);
+
+ if (abortControllerRef.current?.signal.aborted || !mountedRef.current) {
+ return;
+ }
- const internalTools = await mcpToolService.getAllInternalTools();
- const allTools = await mcpToolService.getAllTools();
const enabledTools = new Set(allTools.map(t => `${t.serverId}__${t.name}`));
const categorizedInternalTools: MCPToolWithStatus[] = internalTools.map(tool => {
@@ -102,60 +253,74 @@ const MCPToolsManagement: React.FC<MCPToolsManagementProps> = ({ onClose }) => {
isInternal: false,
}));
- setTools([...categorizedInternalTools, ...externalTools]);
- setStatusMessage(`${categorizedInternalTools.length + externalTools.length} tools loaded`);
- setLoading(false);
+ safeDispatch({ type: 'LOAD_SUCCESS', payload: [...categorizedInternalTools, ...externalTools] });
} catch (error) {
+ if (abortControllerRef.current?.signal.aborted || !mountedRef.current) {
+ return;
+ }
+
+ const errorMessage = error instanceof Error ? error.message : 'Failed to load tools';
console.error('Failed to load tools:', error);
- setStatusMessage('Error loading tools');
- setLoading(false);
+ safeDispatch({ type: 'LOAD_ERROR', payload: errorMessage });
+ } finally {
+ markOperationEnd(opKey);
}
- };
+ }, [isOperationPending, markOperationStart, markOperationEnd, safeDispatch]);
+
+ // Initialize and cleanup
+ useEffect(() => {
+ mountedRef.current = true;
+ abortControllerRef.current = new AbortController();
- const getToolCategory = (toolName: string): string => {
- const categoryMap: Record<string, string> = {
- navigate_tab: 'navigation', navigate_screen: 'navigation', get_active_tab: 'navigation', open_settings_section: 'navigation',
- place_order: 'trading', cancel_order: 'trading', modify_order: 'trading', get_positions: 'trading', get_balance: 'trading', get_orders: 'trading', get_holdings: 'trading', close_position: 'trading',
- crypto_place_market_order: 'crypto-trading', crypto_place_limit_order: 'crypto-trading', crypto_place_stop_loss: 'crypto-trading', crypto_cancel_order: 'crypto-trading', crypto_cancel_all_orders: 'crypto-trading', crypto_get_positions: 'crypto-trading', crypto_close_position: 'crypto-trading', crypto_get_balance: 'crypto-trading', crypto_get_holdings: 'crypto-trading', crypto_get_orders: 'crypto-trading', crypto_get_ticker: 'crypto-trading', crypto_get_orderbook: 'crypto-trading', crypto_add_to_watchlist: 'crypto-trading', crypto_remove_from_watchlist: 'crypto-trading', crypto_search_symbol: 'crypto-trading', crypto_switch_trading_mode: 'crypto-trading', crypto_switch_broker: 'crypto-trading', crypto_get_portfolio_value: 'crypto-trading', crypto_get_pnl: 'crypto-trading', crypto_set_stop_loss_for_position: 'crypto-trading', crypto_set_take_profit: 'crypto-trading',
- create_portfolio: 'portfolio', list_portfolios: 'portfolio', add_asset: 'portfolio', remove_asset: 'portfolio', add_transaction: 'portfolio', get_portfolio_summary: 'portfolio',
- add_widget: 'dashboard', remove_widget: 'dashboard', list_widgets: 'dashboard', configure_widget: 'dashboard',
- set_theme: 'settings', get_theme: 'settings', set_language: 'settings', get_settings: 'settings', set_setting: 'settings',
- save_workspace: 'workspace', load_workspace: 'workspace', list_workspaces: 'workspace', delete_workspace: 'workspace',
- run_backtest: 'backtesting', optimize_strategy: 'backtesting', get_historical_data: 'backtesting',
- get_quote: 'market-data', add_to_watchlist: 'market-data', remove_from_watchlist: 'market-data', search_symbol: 'market-data',
- create_workflow: 'workflow', run_workflow: 'workflow', stop_workflow: 'workflow', list_workflows: 'workflow',
- create_note: 'notes', list_notes: 'notes', delete_note: 'notes', generate_report: 'notes',
+ loadTools();
+
+ return () => {
+ mountedRef.current = false;
+ abortControllerRef.current?.abort();
+ pendingOperationsRef.current.clear();
};
- return categoryMap[toolName] || 'other';
- };
+ }, [loadTools]);
- const handleToggleTool = async (tool: MCPToolWithStatus) => {
+ // Toggle tool handler with deduplication
+ const handleToggleTool = useCallback(async (tool: MCPToolWithStatus) => {
if (!tool.isInternal) {
showWarning('External tools are managed through their MCP servers. Stop the server to disable all its tools.');
return;
}
+ const opKey = `toggle:${tool.serverId}:${tool.name}`;
+ if (isOperationPending(opKey)) {
+ return;
+ }
+
+ markOperationStart(opKey);
+ const newState = !tool.isEnabled;
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: `${newState ? 'Enabling' : 'Disabling'} ${tool.name}...` });
+
try {
- const newState = !tool.isEnabled;
- setStatusMessage(`${newState ? 'Enabling' : 'Disabling'} ${tool.name}...`);
- await mcpToolService.setInternalToolEnabled(tool.name, tool.category || 'other', newState);
- setTools(prev => prev.map(t =>
- t.name === tool.name && t.serverId === tool.serverId
- ? { ...t, isEnabled: newState }
- : t
- ));
- setStatusMessage(`${tool.name} ${newState ? 'enabled' : 'disabled'}`);
+ await withTimeout(
+ mcpToolService.setInternalToolEnabled(tool.name, tool.category || 'other', newState),
+ TIMEOUT_MS,
+ 'Toggle tool timeout'
+ );
+
+ safeDispatch({ type: 'UPDATE_TOOL', payload: { name: tool.name, serverId: tool.serverId, isEnabled: newState } });
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: `${tool.name} ${newState ? 'enabled' : 'disabled'}` });
} catch (error) {
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
console.error('Failed to toggle tool:', error);
- setStatusMessage(`Error toggling ${tool.name}`);
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: `Error toggling ${tool.name}: ${errorMessage}` });
+ } finally {
+ markOperationEnd(opKey);
}
- };
+ }, [isOperationPending, markOperationStart, markOperationEnd, safeDispatch]);
- const filteredTools = tools.filter(tool => {
- const matchesSearch = !searchTerm ||
- tool.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
- tool.description?.toLowerCase().includes(searchTerm.toLowerCase());
- const matchesCategory = !selectedCategory || tool.category === selectedCategory;
+ // Computed values
+ const filteredTools = state.tools.filter(tool => {
+ const matchesSearch = !state.searchTerm ||
+ tool.name.toLowerCase().includes(state.searchTerm.toLowerCase()) ||
+ tool.description?.toLowerCase().includes(state.searchTerm.toLowerCase());
+ const matchesCategory = !state.selectedCategory || tool.category === state.selectedCategory;
return matchesSearch && matchesCategory;
});
@@ -166,16 +331,7 @@ const MCPToolsManagement: React.FC<MCPToolsManagementProps> = ({ onClose }) => {
return acc;
}, {} as Record<string, MCPToolWithStatus[]>);
- const getCategoryColor = (categoryId: string) => {
- const category = TOOL_CATEGORIES.find(c => c.id === categoryId);
- return category?.color || FINCEPT.GRAY;
- };
-
- const getCategoryLabel = (categoryId: string) => {
- const category = TOOL_CATEGORIES.find(c => c.id === categoryId);
- return category?.label || 'OTHER';
- };
-
+ // Render
return (
<div style={{
width: '100%',
@@ -214,7 +370,7 @@ const MCPToolsManagement: React.FC<MCPToolsManagementProps> = ({ onClose }) => {
</span>
<div style={{ width: '1px', height: '16px', backgroundColor: FINCEPT.BORDER }} />
<span style={{ color: FINCEPT.GRAY, fontSize: '9px', letterSpacing: '0.5px' }}>
- {tools.filter(t => t.isEnabled).length} ENABLED | {tools.length} TOTAL
+ {state.tools.filter(t => t.isEnabled).length} ENABLED | {state.tools.length} TOTAL
</span>
</div>
@@ -263,8 +419,8 @@ const MCPToolsManagement: React.FC<MCPToolsManagementProps> = ({ onClose }) => {
<input
type="text"
placeholder="Search tools..."
- value={searchTerm}
- onChange={(e) => setSearchTerm(e.target.value)}
+ value={state.searchTerm}
+ onChange={(e) => dispatch({ type: 'SET_SEARCH_TERM', payload: e.target.value })}
style={{
width: '100%',
padding: '8px 10px 8px 28px',
@@ -282,8 +438,8 @@ const MCPToolsManagement: React.FC<MCPToolsManagementProps> = ({ onClose }) => {
</div>
<select
- value={selectedCategory || ''}
- onChange={(e) => setSelectedCategory(e.target.value || null)}
+ value={state.selectedCategory || ''}
+ onChange={(e) => dispatch({ type: 'SET_SELECTED_CATEGORY', payload: e.target.value || null })}
style={{
backgroundColor: FINCEPT.DARK_BG,
border: `1px solid ${FINCEPT.BORDER}`,
@@ -306,7 +462,7 @@ const MCPToolsManagement: React.FC<MCPToolsManagementProps> = ({ onClose }) => {
{/* Tools List */}
<div className="tools-scroll" style={{ flex: 1, overflow: 'auto', padding: '16px' }}>
- {loading ? (
+ {state.status === 'loading' ? (
<div style={{
display: 'flex',
flexDirection: 'column',
@@ -320,6 +476,20 @@ const MCPToolsManagement: React.FC<MCPToolsManagementProps> = ({ onClose }) => {
<Settings size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />
<span>Loading tools...</span>
</div>
+ ) : state.status === 'error' ? (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100%',
+ color: FINCEPT.RED,
+ fontSize: '10px',
+ textAlign: 'center',
+ }}>
+ <AlertCircle size={24} style={{ marginBottom: '8px' }} />
+ <span>{state.error}</span>
+ </div>
) : Object.keys(toolsByCategory).length === 0 ? (
<div style={{
display: 'flex',
@@ -463,11 +633,21 @@ const MCPToolsManagement: React.FC<MCPToolsManagementProps> = ({ onClose }) => {
alignItems: 'center',
gap: '8px',
}}>
- <span style={{ color: FINCEPT.ORANGE }}>●</span>
- <span>{statusMessage}</span>
+ <span style={{ color: state.status === 'error' ? FINCEPT.RED : FINCEPT.ORANGE }}>●</span>
+ <span>{state.statusMessage}</span>
</div>
</div>
);
};
+// ============================================================================
+// Export with ErrorBoundary wrapper
+// ============================================================================
+
+const MCPToolsManagement: React.FC<MCPToolsManagementProps> = (props) => (
+ <ErrorBoundary name="MCP Tools Management" variant="default">
+ <MCPToolsManagementInner {...props} />
+ </ErrorBoundary>
+);
+
export default MCPToolsManagement;
diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx
index 0642ce058..739814df9 100644
--- a/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx
@@ -1,8 +1,9 @@
// MCP Integrations Tab - Main Component
// Three-panel terminal layout per Fincept UI Design System
+// Production-ready: State machine, AbortController, deduplication, error boundary, timeouts, validation
-import React, { useState, useEffect } from 'react';
-import { Plus, RefreshCw, Search, Play, Square, Trash2, Settings, Zap, CheckCircle, XCircle, AlertCircle, MessageSquare, Server, Wrench, ShoppingBag, ChevronRight } from 'lucide-react';
+import React, { useReducer, useEffect, useCallback, useRef } from 'react';
+import { Plus, RefreshCw, Search, Play, Square, Trash2, Settings, Zap, CheckCircle, XCircle, AlertCircle, MessageSquare, Server, Wrench } from 'lucide-react';
import { mcpManager, MCPServerWithStats } from '../../../services/mcp/mcpManager';
import { sqliteService } from '../../../services/core/sqliteService';
import { useBrokerContext } from '../../../contexts/BrokerContext';
@@ -13,11 +14,107 @@ import MCPMarketplace from './marketplace/MCPMarketplace';
import MCPAddServerModal from './MCPAddServerModal';
import MCPToolsManagement from './MCPToolsManagement';
import { showConfirm } from '@/utils/notifications';
+import { ErrorBoundary } from '@/components/common/ErrorBoundary';
+import { withTimeout, deduplicatedFetch } from '@/services/core/apiUtils';
+
+// ============================================================================
+// Types & State Machine
+// ============================================================================
interface MCPTabProps {
onNavigateToTab?: (tabName: string) => void;
}
+// Explicit state machine states
+type MCPStatus = 'idle' | 'loading' | 'success' | 'error';
+
+interface MCPState {
+ status: MCPStatus;
+ servers: MCPServerWithStats[];
+ tools: any[];
+ statusMessage: string;
+ error: string | null;
+ view: 'marketplace' | 'installed' | 'tools';
+ isAddModalOpen: boolean;
+ isRefreshing: boolean;
+ searchTerm: string;
+ selectedServerId: string | null;
+}
+
+type MCPAction =
+ | { type: 'SET_VIEW'; payload: 'marketplace' | 'installed' | 'tools' }
+ | { type: 'LOAD_START' }
+ | { type: 'LOAD_SUCCESS'; payload: { servers: MCPServerWithStats[]; tools: any[] } }
+ | { type: 'LOAD_ERROR'; payload: string }
+ | { type: 'SET_STATUS_MESSAGE'; payload: string }
+ | { type: 'SET_REFRESHING'; payload: boolean }
+ | { type: 'SET_SEARCH_TERM'; payload: string }
+ | { type: 'SET_SELECTED_SERVER'; payload: string | null }
+ | { type: 'OPEN_ADD_MODAL' }
+ | { type: 'CLOSE_ADD_MODAL' }
+ | { type: 'RESET_ERROR' };
+
+const initialState: MCPState = {
+ status: 'idle',
+ servers: [],
+ tools: [],
+ statusMessage: 'Initializing...',
+ error: null,
+ view: 'marketplace',
+ isAddModalOpen: false,
+ isRefreshing: false,
+ searchTerm: '',
+ selectedServerId: null,
+};
+
+function mcpReducer(state: MCPState, action: MCPAction): MCPState {
+ switch (action.type) {
+ case 'SET_VIEW':
+ return { ...state, view: action.payload };
+ case 'LOAD_START':
+ return { ...state, status: 'loading', error: null };
+ case 'LOAD_SUCCESS': {
+ const { servers, tools } = action.payload;
+ const runningCount = servers.filter(s => s.status === 'running').length;
+ const internalToolsCount = tools.filter((t: any) => t.serverId === 'fincept-terminal').length;
+ const externalToolsCount = tools.length - internalToolsCount;
+ return {
+ ...state,
+ status: 'success',
+ servers,
+ tools,
+ statusMessage: `${runningCount} servers running | ${internalToolsCount} internal + ${externalToolsCount} external tools`,
+ error: null,
+ };
+ }
+ case 'LOAD_ERROR':
+ return { ...state, status: 'error', error: action.payload, statusMessage: action.payload };
+ case 'SET_STATUS_MESSAGE':
+ return { ...state, statusMessage: action.payload };
+ case 'SET_REFRESHING':
+ return { ...state, isRefreshing: action.payload };
+ case 'SET_SEARCH_TERM':
+ return { ...state, searchTerm: action.payload };
+ case 'SET_SELECTED_SERVER':
+ return { ...state, selectedServerId: action.payload };
+ case 'OPEN_ADD_MODAL':
+ return { ...state, isAddModalOpen: true };
+ case 'CLOSE_ADD_MODAL':
+ return { ...state, isAddModalOpen: false };
+ case 'RESET_ERROR':
+ return { ...state, status: 'idle', error: null };
+ default:
+ return state;
+ }
+}
+
+// ============================================================================
+// Constants
+// ============================================================================
+
+const TIMEOUT_MS = 30000; // 30 second timeout for operations
+const POLL_INTERVAL_MS = 5000; // 5 second polling interval
+
// Fincept Design System Colors
const FINCEPT = {
ORANGE: '#FF8800',
@@ -39,27 +136,110 @@ const FINCEPT = {
const FONT_FAMILY = '"IBM Plex Mono", "Consolas", monospace';
-const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
- const [view, setView] = useState<'marketplace' | 'installed' | 'tools'>('marketplace');
- const [servers, setServers] = useState<MCPServerWithStats[]>([]);
- const [tools, setTools] = useState<any[]>([]);
- const [isAddModalOpen, setIsAddModalOpen] = useState(false);
- const [isRefreshing, setIsRefreshing] = useState(false);
- const [statusMessage, setStatusMessage] = useState('Initializing...');
- const [searchTerm, setSearchTerm] = useState('');
- const [selectedServerId, setSelectedServerId] = useState<string | null>(null);
+// ============================================================================
+// Main Component
+// ============================================================================
+
+const MCPTabInner: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
+ const [state, dispatch] = useReducer(mcpReducer, initialState);
+
+ // Refs for cleanup and deduplication
+ const abortControllerRef = useRef<AbortController | null>(null);
+ const mountedRef = useRef(true);
+ const pendingOperationsRef = useRef<Set<string>>(new Set());
// Crypto broker context for MCP bridge
const { activeAdapter, tradingMode, activeBroker } = useBrokerContext();
- // Stock broker context for MCP bridge (optional - may not be available)
+ // Stock broker context for MCP bridge (optional)
const stockBrokerCtx = useStockBrokerContextOptional();
const stockAdapter = stockBrokerCtx?.adapter;
const stockTradingMode = stockBrokerCtx?.tradingMode;
const stockActiveBroker = stockBrokerCtx?.activeBroker;
const stockIsAuthenticated = stockBrokerCtx?.isAuthenticated;
- // Connect crypto broker to MCP bridge
+ // ============================================================================
+ // Helper: Check if mounted before state update
+ // ============================================================================
+ const safeDispatch = useCallback((action: MCPAction) => {
+ if (mountedRef.current) {
+ dispatch(action);
+ }
+ }, []);
+
+ // ============================================================================
+ // Helper: Check if operation is already pending (deduplication)
+ // ============================================================================
+ const isOperationPending = useCallback((opKey: string): boolean => {
+ return pendingOperationsRef.current.has(opKey);
+ }, []);
+
+ const markOperationStart = useCallback((opKey: string) => {
+ pendingOperationsRef.current.add(opKey);
+ }, []);
+
+ const markOperationEnd = useCallback((opKey: string) => {
+ pendingOperationsRef.current.delete(opKey);
+ }, []);
+
+ // ============================================================================
+ // Load Data with deduplication, timeout, and abort support
+ // ============================================================================
+ const loadData = useCallback(async (silent = false) => {
+ const opKey = 'loadData';
+
+ // Deduplication: Skip if already loading
+ if (isOperationPending(opKey)) {
+ return;
+ }
+
+ // Check if aborted
+ if (abortControllerRef.current?.signal.aborted) {
+ return;
+ }
+
+ markOperationStart(opKey);
+
+ if (!silent) {
+ safeDispatch({ type: 'LOAD_START' });
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: 'Loading servers...' });
+ }
+
+ try {
+ // Use deduplicatedFetch and withTimeout for external calls
+ const [serversData, toolsData] = await Promise.all([
+ deduplicatedFetch('mcp:servers', () =>
+ withTimeout(mcpManager.getServersWithStats(), TIMEOUT_MS, 'Server list timeout')
+ ),
+ deduplicatedFetch('mcp:tools', async () => {
+ const { mcpToolService } = await import('../../../services/mcp/mcpToolService');
+ return withTimeout(mcpToolService.getAllTools(), TIMEOUT_MS, 'Tools list timeout');
+ }),
+ ]);
+
+ // Check abort after async operations
+ if (abortControllerRef.current?.signal.aborted || !mountedRef.current) {
+ return;
+ }
+
+ safeDispatch({ type: 'LOAD_SUCCESS', payload: { servers: serversData, tools: toolsData } });
+ } catch (error) {
+ // Don't report errors if aborted
+ if (abortControllerRef.current?.signal.aborted || !mountedRef.current) {
+ return;
+ }
+
+ const errorMessage = error instanceof Error ? error.message : 'Failed to load MCP data';
+ console.error('Failed to load MCP data:', error);
+ safeDispatch({ type: 'LOAD_ERROR', payload: errorMessage });
+ } finally {
+ markOperationEnd(opKey);
+ }
+ }, [isOperationPending, markOperationStart, markOperationEnd, safeDispatch]);
+
+ // ============================================================================
+ // Broker Bridge Effects
+ // ============================================================================
useEffect(() => {
if (activeAdapter) {
brokerMCPBridge.connect({
@@ -75,7 +255,6 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
};
}, [activeAdapter, tradingMode, activeBroker]);
- // Connect stock broker to MCP bridge
useEffect(() => {
if (stockAdapter && stockIsAuthenticated && stockActiveBroker) {
stockBrokerMCPBridge.connect({
@@ -92,91 +271,151 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
};
}, [stockAdapter, stockIsAuthenticated, stockActiveBroker, stockTradingMode]);
+ // ============================================================================
+ // Initialization & Cleanup Effect
+ // ============================================================================
useEffect(() => {
+ mountedRef.current = true;
+ abortControllerRef.current = new AbortController();
+
const initializeServers = async () => {
try {
- await sqliteService.initialize();
+ await withTimeout(sqliteService.initialize(), TIMEOUT_MS, 'Database init timeout');
const { mcpToolService } = await import('../../../services/mcp/mcpToolService');
- await mcpToolService.initialize();
+ await withTimeout(mcpToolService.initialize(), TIMEOUT_MS, 'MCP Tool Service init timeout');
await loadData();
} catch (error) {
- console.error('Failed to initialize MCP tab:', error);
- setStatusMessage('Initialization failed');
+ if (!abortControllerRef.current?.signal.aborted && mountedRef.current) {
+ console.error('Failed to initialize MCP tab:', error);
+ safeDispatch({ type: 'LOAD_ERROR', payload: 'Initialization failed' });
+ }
}
};
initializeServers();
+ // Polling interval with abort check
const interval = setInterval(() => {
- loadData(true);
- }, 5000);
-
- return () => clearInterval(interval);
- }, []);
-
- const loadData = async (silent = false) => {
- try {
- if (!silent) setStatusMessage('Loading servers...');
+ if (!abortControllerRef.current?.signal.aborted && mountedRef.current) {
+ loadData(true);
+ }
+ }, POLL_INTERVAL_MS);
- const serversData = await mcpManager.getServersWithStats();
- setServers(serversData);
+ // Cleanup function
+ return () => {
+ mountedRef.current = false;
+ abortControllerRef.current?.abort();
+ clearInterval(interval);
+ pendingOperationsRef.current.clear();
+ };
+ }, [loadData, safeDispatch]);
- const { mcpToolService } = await import('../../../services/mcp/mcpToolService');
- const toolsData = await mcpToolService.getAllTools();
- setTools(toolsData);
+ // ============================================================================
+ // Handlers with timeout and deduplication
+ // ============================================================================
+ const handleRefresh = useCallback(async () => {
+ safeDispatch({ type: 'SET_REFRESHING', payload: true });
+ await loadData();
+ setTimeout(() => safeDispatch({ type: 'SET_REFRESHING', payload: false }), 500);
+ }, [loadData, safeDispatch]);
- const runningCount = serversData.filter(s => s.status === 'running').length;
- const internalToolsCount = toolsData.filter((t: any) => t.serverId === 'fincept-terminal').length;
- const externalToolsCount = toolsData.length - internalToolsCount;
- setStatusMessage(`${runningCount} servers running | ${internalToolsCount} internal + ${externalToolsCount} external tools`);
- } catch (error) {
- console.error('Failed to load MCP data:', error);
- setStatusMessage('Error loading data');
+ const handleInstallServer = useCallback(async (
+ config: any,
+ callbacks?: {
+ onProgress?: (status: string) => void;
+ onComplete?: (success: boolean, error?: string) => void;
+ }
+ ) => {
+ const opKey = `install:${config.id}`;
+ if (isOperationPending(opKey)) {
+ return;
}
- };
- const handleRefresh = async () => {
- setIsRefreshing(true);
- await loadData();
- setTimeout(() => setIsRefreshing(false), 500);
- };
+ markOperationStart(opKey);
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: 'Installing server...' });
- const handleInstallServer = async (config: any) => {
try {
- setStatusMessage('Installing server...');
- await mcpManager.installServer(config);
+ // Pass callbacks to mcpManager for non-blocking installation
+ // The installServer call returns quickly after saving to DB
+ // Background server startup continues and calls the callbacks
+ await mcpManager.installServer(config, {
+ onProgress: (status) => {
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: status });
+ callbacks?.onProgress?.(status);
+ },
+ onComplete: async (success, error) => {
+ markOperationEnd(opKey);
+
+ if (success) {
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: 'Server installed and started successfully' });
+ safeDispatch({ type: 'SET_VIEW', payload: 'installed' });
+ } else {
+ // Server saved but failed to start - still show in installed list
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: error ? `Server installed but start failed: ${error}` : 'Server installed (not running)' });
+ safeDispatch({ type: 'SET_VIEW', payload: 'installed' });
+ }
+
+ // Refresh data to show updated server list
+ await loadData();
+ callbacks?.onComplete?.(success, error);
+ }
+ });
+
+ // Refresh immediately to show server in list (even before it's fully started)
await loadData();
- setStatusMessage('Server installed successfully');
- setView('installed');
+
} catch (error) {
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
console.error('Failed to install server:', error);
- setStatusMessage(`Installation failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: `Installation failed: ${errorMessage}` });
+ markOperationEnd(opKey);
+ callbacks?.onComplete?.(false, errorMessage);
}
- };
+ }, [isOperationPending, markOperationStart, markOperationEnd, loadData, safeDispatch]);
+
+ const handleStartServer = useCallback(async (serverId: string) => {
+ const opKey = `start:${serverId}`;
+ if (isOperationPending(opKey)) {
+ return;
+ }
+
+ markOperationStart(opKey);
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: 'Starting server...' });
- const handleStartServer = async (serverId: string) => {
try {
- setStatusMessage('Starting server...');
- await mcpManager.startServer(serverId);
+ await withTimeout(mcpManager.startServer(serverId), TIMEOUT_MS, 'Start server timeout');
await loadData();
} catch (error) {
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
console.error('Failed to start server:', error);
- setStatusMessage(`Start failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: `Start failed: ${errorMessage}` });
+ } finally {
+ markOperationEnd(opKey);
}
- };
+ }, [isOperationPending, markOperationStart, markOperationEnd, loadData, safeDispatch]);
+
+ const handleStopServer = useCallback(async (serverId: string) => {
+ const opKey = `stop:${serverId}`;
+ if (isOperationPending(opKey)) {
+ return;
+ }
+
+ markOperationStart(opKey);
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: 'Stopping server...' });
- const handleStopServer = async (serverId: string) => {
try {
- setStatusMessage('Stopping server...');
- await mcpManager.stopServer(serverId);
+ await withTimeout(mcpManager.stopServer(serverId), TIMEOUT_MS, 'Stop server timeout');
await loadData();
} catch (error) {
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
console.error('Failed to stop server:', error);
- setStatusMessage(`Stop failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: `Stop failed: ${errorMessage}` });
+ } finally {
+ markOperationEnd(opKey);
}
- };
+ }, [isOperationPending, markOperationStart, markOperationEnd, loadData, safeDispatch]);
- const handleRemoveServer = async (serverId: string) => {
+ const handleRemoveServer = useCallback(async (serverId: string) => {
const confirmed = await showConfirm('This will delete all associated data.', {
title: 'Remove this MCP server?',
type: 'danger'
@@ -185,29 +424,58 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
return;
}
+ const opKey = `remove:${serverId}`;
+ if (isOperationPending(opKey)) {
+ return;
+ }
+
+ markOperationStart(opKey);
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: 'Removing server...' });
+
try {
- setStatusMessage('Removing server...');
- await mcpManager.removeServer(serverId);
- if (selectedServerId === serverId) setSelectedServerId(null);
+ await withTimeout(mcpManager.removeServer(serverId), TIMEOUT_MS, 'Remove server timeout');
+ if (state.selectedServerId === serverId) {
+ safeDispatch({ type: 'SET_SELECTED_SERVER', payload: null });
+ }
await loadData();
- setStatusMessage('Server removed');
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: 'Server removed' });
} catch (error) {
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
console.error('Failed to remove server:', error);
- setStatusMessage(`Remove failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: `Remove failed: ${errorMessage}` });
+ } finally {
+ markOperationEnd(opKey);
}
- };
+ }, [isOperationPending, markOperationStart, markOperationEnd, state.selectedServerId, loadData, safeDispatch]);
+
+ const handleToggleAutoStart = useCallback(async (serverId: string, enabled: boolean) => {
+ const opKey = `autostart:${serverId}`;
+ if (isOperationPending(opKey)) {
+ return;
+ }
+
+ markOperationStart(opKey);
- const handleToggleAutoStart = async (serverId: string, enabled: boolean) => {
try {
- await mcpManager.updateServerConfig(serverId, { auto_start: enabled });
+ await withTimeout(
+ mcpManager.updateServerConfig(serverId, { auto_start: enabled }),
+ TIMEOUT_MS,
+ 'Update config timeout'
+ );
await loadData();
- setStatusMessage(enabled ? 'Auto-start enabled' : 'Auto-start disabled');
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: enabled ? 'Auto-start enabled' : 'Auto-start disabled' });
} catch (error) {
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
console.error('Failed to toggle auto-start:', error);
- setStatusMessage(`Auto-start toggle failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ safeDispatch({ type: 'SET_STATUS_MESSAGE', payload: `Auto-start toggle failed: ${errorMessage}` });
+ } finally {
+ markOperationEnd(opKey);
}
- };
+ }, [isOperationPending, markOperationStart, markOperationEnd, loadData, safeDispatch]);
+ // ============================================================================
+ // Computed Values
+ // ============================================================================
const getStatusIcon = (status: string) => {
switch (status) {
case 'running':
@@ -227,26 +495,28 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
}
};
- const runningServers = servers.filter(s => s.status === 'running').length;
- const filteredServers = servers.filter(s =>
- s.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
- s.description.toLowerCase().includes(searchTerm.toLowerCase())
+ const runningServers = state.servers.filter(s => s.status === 'running').length;
+ const filteredServers = state.servers.filter(s =>
+ s.name.toLowerCase().includes(state.searchTerm.toLowerCase()) ||
+ s.description.toLowerCase().includes(state.searchTerm.toLowerCase())
);
- const selectedServer = selectedServerId
- ? servers.find(s => s.id === selectedServerId) || null
+ const selectedServer = state.selectedServerId
+ ? state.servers.find(s => s.id === state.selectedServerId) || null
: null;
- const internalToolCount = tools.filter((t: any) => t.serverId === 'fincept-terminal').length;
- const externalToolCount = tools.length - internalToolCount;
+ const internalToolCount = state.tools.filter((t: any) => t.serverId === 'fincept-terminal').length;
+ const externalToolCount = state.tools.length - internalToolCount;
- // Get tools for the selected server
- const selectedServerTools = selectedServerId === 'internal'
- ? tools.filter((t: any) => t.serverId === 'fincept-terminal')
+ const selectedServerTools = state.selectedServerId === 'internal'
+ ? state.tools.filter((t: any) => t.serverId === 'fincept-terminal')
: selectedServer
- ? tools.filter((t: any) => t.serverId === selectedServer.id)
+ ? state.tools.filter((t: any) => t.serverId === selectedServer.id)
: [];
+ // ============================================================================
+ // Render
+ // ============================================================================
return (
<div style={{
width: '100%',
@@ -293,7 +563,7 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
</span>
<div style={{ width: '1px', height: '16px', backgroundColor: FINCEPT.BORDER }} />
<span style={{ color: FINCEPT.GRAY, fontSize: '9px', letterSpacing: '0.5px' }}>
- {servers.length} SERVERS | {runningServers} RUNNING | {tools.length} TOOLS
+ {state.servers.length} SERVERS | {runningServers} RUNNING | {state.tools.length} TOOLS
</span>
</div>
@@ -308,11 +578,11 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
return (
<button
key={tab}
- onClick={() => setView(tab)}
+ onClick={() => dispatch({ type: 'SET_VIEW', payload: tab })}
style={{
padding: '6px 12px',
- backgroundColor: view === tab ? FINCEPT.ORANGE : 'transparent',
- color: view === tab ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ backgroundColor: state.view === tab ? FINCEPT.ORANGE : 'transparent',
+ color: state.view === tab ? FINCEPT.DARK_BG : FINCEPT.GRAY,
border: 'none',
fontSize: '9px',
fontWeight: 700,
@@ -355,7 +625,7 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
<button
onClick={handleRefresh}
- disabled={isRefreshing}
+ disabled={state.isRefreshing || state.status === 'loading'}
style={{
padding: '6px 10px',
backgroundColor: 'transparent',
@@ -364,21 +634,21 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
fontSize: '9px',
fontWeight: 700,
borderRadius: '2px',
- cursor: isRefreshing ? 'not-allowed' : 'pointer',
+ cursor: state.isRefreshing || state.status === 'loading' ? 'not-allowed' : 'pointer',
display: 'flex',
alignItems: 'center',
gap: '4px',
- opacity: isRefreshing ? 0.5 : 1,
+ opacity: state.isRefreshing || state.status === 'loading' ? 0.5 : 1,
transition: 'all 0.2s',
fontFamily: FONT_FAMILY,
}}
>
- <RefreshCw size={10} style={{ animation: isRefreshing ? 'spin 1s linear infinite' : 'none' }} />
+ <RefreshCw size={10} style={{ animation: state.isRefreshing ? 'spin 1s linear infinite' : 'none' }} />
REFRESH
</button>
<button
- onClick={() => setIsAddModalOpen(true)}
+ onClick={() => dispatch({ type: 'OPEN_ADD_MODAL' })}
style={{
padding: '8px 16px',
backgroundColor: FINCEPT.ORANGE,
@@ -401,7 +671,7 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
</div>
{/* Main Content - Three Panel Layout for installed view, full-width for marketplace/tools */}
- {view === 'installed' ? (
+ {state.view === 'installed' ? (
<div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
{/* Left Panel - Server List (280px) */}
<div style={{
@@ -436,8 +706,8 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
<input
type="text"
placeholder="Search servers..."
- value={searchTerm}
- onChange={(e) => setSearchTerm(e.target.value)}
+ value={state.searchTerm}
+ onChange={(e) => dispatch({ type: 'SET_SEARCH_TERM', payload: e.target.value })}
style={{
width: '100%',
padding: '8px 10px 8px 28px',
@@ -459,20 +729,20 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
<div className="mcp-scroll" style={{ flex: 1, overflow: 'auto' }}>
{/* Internal Tools Entry */}
<div
- onClick={() => setSelectedServerId('internal')}
+ onClick={() => dispatch({ type: 'SET_SELECTED_SERVER', payload: 'internal' })}
style={{
padding: '10px 12px',
- backgroundColor: selectedServerId === 'internal' ? `${FINCEPT.ORANGE}15` : 'transparent',
- borderLeft: selectedServerId === 'internal' ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
+ backgroundColor: state.selectedServerId === 'internal' ? `${FINCEPT.ORANGE}15` : 'transparent',
+ borderLeft: state.selectedServerId === 'internal' ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
cursor: 'pointer',
transition: 'all 0.2s',
borderBottom: `1px solid ${FINCEPT.BORDER}`,
}}
onMouseEnter={(e) => {
- if (selectedServerId !== 'internal') e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ if (state.selectedServerId !== 'internal') e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
}}
onMouseLeave={(e) => {
- if (selectedServerId !== 'internal') e.currentTarget.style.backgroundColor = 'transparent';
+ if (state.selectedServerId !== 'internal') e.currentTarget.style.backgroundColor = 'transparent';
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
@@ -498,7 +768,7 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
</div>
{/* External Servers */}
- {filteredServers.length === 0 && !searchTerm ? (
+ {filteredServers.length === 0 && !state.searchTerm ? (
<div style={{
display: 'flex',
flexDirection: 'column',
@@ -517,20 +787,20 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
filteredServers.map(server => (
<div
key={server.id}
- onClick={() => setSelectedServerId(server.id)}
+ onClick={() => dispatch({ type: 'SET_SELECTED_SERVER', payload: server.id })}
style={{
padding: '10px 12px',
- backgroundColor: selectedServerId === server.id ? `${FINCEPT.ORANGE}15` : 'transparent',
- borderLeft: selectedServerId === server.id ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
+ backgroundColor: state.selectedServerId === server.id ? `${FINCEPT.ORANGE}15` : 'transparent',
+ borderLeft: state.selectedServerId === server.id ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
cursor: 'pointer',
transition: 'all 0.2s',
borderBottom: `1px solid ${FINCEPT.BORDER}`,
}}
onMouseEnter={(e) => {
- if (selectedServerId !== server.id) e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ if (state.selectedServerId !== server.id) e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
}}
onMouseLeave={(e) => {
- if (selectedServerId !== server.id) e.currentTarget.style.backgroundColor = 'transparent';
+ if (state.selectedServerId !== server.id) e.currentTarget.style.backgroundColor = 'transparent';
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
@@ -575,13 +845,13 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
justifyContent: 'space-between',
}}>
<span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>
- {selectedServerId === 'internal'
+ {state.selectedServerId === 'internal'
? 'FINCEPT TERMINAL (INTERNAL)'
: selectedServer
? selectedServer.name.toUpperCase()
: 'SERVER DETAILS'}
</span>
- {(selectedServer || selectedServerId === 'internal') && (
+ {(selectedServer || state.selectedServerId === 'internal') && (
<span style={{ fontSize: '9px', color: FINCEPT.CYAN }}>
{selectedServerTools.length} TOOLS AVAILABLE
</span>
@@ -590,7 +860,7 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
{/* Center Content */}
<div className="mcp-scroll" style={{ flex: 1, overflow: 'auto', padding: '16px' }}>
- {selectedServerId === 'internal' ? (
+ {state.selectedServerId === 'internal' ? (
// Internal server detail
<div>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '16px' }}>
@@ -631,7 +901,7 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
{/* Action */}
<button
- onClick={() => setView('tools')}
+ onClick={() => dispatch({ type: 'SET_VIEW', payload: 'tools' })}
style={{
padding: '8px 16px',
backgroundColor: FINCEPT.ORANGE,
@@ -948,8 +1218,15 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
) : (
/* Marketplace / Tools views - full width */
<div className="mcp-scroll" style={{ flex: 1, overflow: 'auto', padding: '16px' }}>
- {view === 'marketplace' ? (
- <MCPMarketplace onInstall={handleInstallServer} installedServers={servers} />
+ {state.view === 'marketplace' ? (
+ <MCPMarketplace
+ onInstall={handleInstallServer}
+ installedServers={state.servers}
+ installingServerIds={new Set([
+ ...mcpManager.getInstallingServerIds(),
+ ...Array.from(pendingOperationsRef.current).filter(op => op.startsWith('install:')).map(op => op.replace('install:', ''))
+ ])}
+ />
) : (
<MCPToolsManagement />
)}
@@ -968,19 +1245,19 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
alignItems: 'center',
gap: '8px',
}}>
- <span style={{ color: FINCEPT.ORANGE }}>●</span>
- <span>{statusMessage}</span>
+ <span style={{ color: state.status === 'error' ? FINCEPT.RED : FINCEPT.ORANGE }}>●</span>
+ <span>{state.statusMessage}</span>
<div style={{ flex: 1 }} />
<span style={{ color: FINCEPT.CYAN }}>MCP v1.0</span>
</div>
{/* Add Server Modal */}
- {isAddModalOpen && (
+ {state.isAddModalOpen && (
<MCPAddServerModal
- onClose={() => setIsAddModalOpen(false)}
+ onClose={() => dispatch({ type: 'CLOSE_ADD_MODAL' })}
onAdd={(config) => {
handleInstallServer(config);
- setIsAddModalOpen(false);
+ dispatch({ type: 'CLOSE_ADD_MODAL' });
}}
/>
)}
@@ -988,4 +1265,14 @@ const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
);
};
+// ============================================================================
+// Export with ErrorBoundary wrapper
+// ============================================================================
+
+const MCPTab: React.FC<MCPTabProps> = (props) => (
+ <ErrorBoundary name="MCP Tab" variant="default">
+ <MCPTabInner {...props} />
+ </ErrorBoundary>
+);
+
export default MCPTab;
diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/MCPMarketplace.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/MCPMarketplace.tsx
index 640479818..b5fd9a712 100644
--- a/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/MCPMarketplace.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/MCPMarketplace.tsx
@@ -1,17 +1,23 @@
// MCP Marketplace Component
// Browse and install curated MCP servers - Fincept UI Design System
+// Production-ready: ErrorBoundary, memoization, installation tracking
-import React, { useState } from 'react';
-import { Search, Download, Zap, CheckCircle } from 'lucide-react';
+import React, { useState, useCallback, useMemo } from 'react';
+import { Search, Download, Zap, CheckCircle, Loader2 } from 'lucide-react';
import { MARKETPLACE_SERVERS, MCPServerDefinition } from './serverDefinitions';
import { MCPServerWithStats } from '../../../../services/mcp/mcpManager';
import PostgresForm from './forms/PostgresForm';
import QuestDBForm from './forms/QuestDBForm';
import GenericForm from './forms/GenericForm';
+import { ErrorBoundary } from '@/components/common/ErrorBoundary';
interface MCPMarketplaceProps {
- onInstall: (serverConfig: any) => void;
+ onInstall: (serverConfig: any, callbacks?: {
+ onProgress?: (status: string) => void;
+ onComplete?: (success: boolean, error?: string) => void;
+ }) => Promise<void>;
installedServers: MCPServerWithStats[];
+ installingServerIds?: Set<string>;
}
const FINCEPT = {
@@ -34,21 +40,44 @@ const FINCEPT = {
const FONT_FAMILY = '"IBM Plex Mono", "Consolas", monospace';
-const MCPMarketplace: React.FC<MCPMarketplaceProps> = ({ onInstall, installedServers }) => {
+const MCPMarketplaceInner: React.FC<MCPMarketplaceProps> = ({
+ onInstall,
+ installedServers,
+ installingServerIds = new Set()
+}) => {
const [searchQuery, setSearchQuery] = useState('');
const [selectedCategory, setSelectedCategory] = useState<string>('all');
const [configureServer, setConfigureServer] = useState<MCPServerDefinition | null>(null);
+ const [localInstallingIds, setLocalInstallingIds] = useState<Set<string>>(new Set());
+ const [installProgress, setInstallProgress] = useState<Map<string, string>>(new Map());
- const isServerInstalled = (serverId: string) => {
- return installedServers.some(s => s.id === serverId);
- };
+ // Combine parent and local installing states
+ const allInstallingIds = useMemo(() => {
+ return new Set([...installingServerIds, ...localInstallingIds]);
+ }, [installingServerIds, localInstallingIds]);
+
+ // Memoize installed server IDs for efficient lookup
+ const installedServerIds = useMemo(() => {
+ return new Set(installedServers.map(s => s.id));
+ }, [installedServers]);
+
+ const isServerInstalled = useCallback((serverId: string) => {
+ return installedServerIds.has(serverId);
+ }, [installedServerIds]);
+
+ const isServerInstalling = useCallback((serverId: string) => {
+ return allInstallingIds.has(serverId);
+ }, [allInstallingIds]);
- const filteredServers = MARKETPLACE_SERVERS.filter(server => {
- const matchesSearch = server.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
- server.description.toLowerCase().includes(searchQuery.toLowerCase());
- const matchesCategory = selectedCategory === 'all' || server.category === selectedCategory;
- return matchesSearch && matchesCategory;
- });
+ // Memoize filtered servers
+ const filteredServers = useMemo(() => {
+ return MARKETPLACE_SERVERS.filter(server => {
+ const matchesSearch = server.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
+ server.description.toLowerCase().includes(searchQuery.toLowerCase());
+ const matchesCategory = selectedCategory === 'all' || server.category === selectedCategory;
+ return matchesSearch && matchesCategory;
+ });
+ }, [searchQuery, selectedCategory]);
const categories = ['all', 'data', 'web', 'productivity', 'dev'];
const categoryLabels: Record<string, string> = {
@@ -59,28 +88,91 @@ const MCPMarketplace: React.FC<MCPMarketplaceProps> = ({ onInstall, installedSer
dev: 'DEV',
};
- const handleInstallClick = (server: MCPServerDefinition) => {
+ const handleInstallClick = useCallback(async (server: MCPServerDefinition) => {
if (server.requiresConfig) {
setConfigureServer(server);
} else {
- onInstall(server);
+ // Immediately show installing state - this happens BEFORE any async work
+ setLocalInstallingIds(prev => new Set([...prev, server.id]));
+ setInstallProgress(prev => new Map(prev).set(server.id, 'Preparing installation...'));
+
+ // Call onInstall with callbacks for progress updates
+ // This is non-blocking - the function returns immediately after saving to DB
+ await onInstall(server, {
+ onProgress: (status) => {
+ setInstallProgress(prev => new Map(prev).set(server.id, status));
+ },
+ onComplete: (success, error) => {
+ // Remove from installing state when done
+ setLocalInstallingIds(prev => {
+ const next = new Set(prev);
+ next.delete(server.id);
+ return next;
+ });
+ setInstallProgress(prev => {
+ const next = new Map(prev);
+ next.delete(server.id);
+ return next;
+ });
+ }
+ });
}
- };
+ }, [onInstall]);
- const handleConfiguredInstall = (config: { args: string[]; env: Record<string, string> }) => {
+ const handleConfiguredInstall = useCallback(async (config: { args: string[]; env: Record<string, string> }) => {
if (configureServer) {
const serverWithConfig = {
...configureServer,
args: [...configureServer.args, ...config.args],
env: config.env,
};
- onInstall(serverWithConfig);
+
+ // Close modal first for better UX
+ const serverId = configureServer.id;
setConfigureServer(null);
+
+ // Show installing state immediately
+ setLocalInstallingIds(prev => new Set([...prev, serverId]));
+ setInstallProgress(prev => new Map(prev).set(serverId, 'Preparing installation...'));
+
+ // Call onInstall with callbacks - non-blocking
+ await onInstall(serverWithConfig, {
+ onProgress: (status) => {
+ setInstallProgress(prev => new Map(prev).set(serverId, status));
+ },
+ onComplete: (success, error) => {
+ setLocalInstallingIds(prev => {
+ const next = new Set(prev);
+ next.delete(serverId);
+ return next;
+ });
+ setInstallProgress(prev => {
+ const next = new Map(prev);
+ next.delete(serverId);
+ return next;
+ });
+ }
+ });
}
- };
+ }, [configureServer, onInstall]);
+
+ const handleCloseConfig = useCallback(() => {
+ setConfigureServer(null);
+ }, []);
return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', fontFamily: FONT_FAMILY }}>
+ <style>{`
+ @keyframes spin {
+ from { transform: rotate(0deg); }
+ to { transform: rotate(360deg); }
+ }
+ @keyframes pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.5; }
+ }
+ `}</style>
+
{/* Search and Filters */}
<div style={{ marginBottom: '16px' }}>
<div style={{ position: 'relative', marginBottom: '12px' }}>
@@ -166,28 +258,35 @@ const MCPMarketplace: React.FC<MCPMarketplaceProps> = ({ onInstall, installedSer
}}>
{filteredServers.map(server => {
const installed = isServerInstalled(server.id);
+ const installing = isServerInstalling(server.id);
+
return (
<div
key={server.id}
style={{
backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
+ border: `1px solid ${installing ? FINCEPT.CYAN : FINCEPT.BORDER}`,
borderRadius: '2px',
padding: '16px',
- cursor: installed ? 'default' : 'pointer',
+ cursor: installed || installing ? 'default' : 'pointer',
transition: 'all 0.2s',
display: 'flex',
flexDirection: 'column',
minHeight: '240px',
+ opacity: installing ? 0.8 : 1,
}}
onMouseEnter={(e) => {
- if (!installed) {
+ if (!installed && !installing) {
e.currentTarget.style.borderColor = FINCEPT.ORANGE;
e.currentTarget.style.boxShadow = `0 0 12px ${FINCEPT.ORANGE}40`;
}
}}
onMouseLeave={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ if (!installing) {
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ } else {
+ e.currentTarget.style.borderColor = FINCEPT.CYAN;
+ }
e.currentTarget.style.boxShadow = 'none';
}}
>
@@ -204,6 +303,13 @@ const MCPMarketplace: React.FC<MCPMarketplaceProps> = ({ onInstall, installedSer
{server.name}
</span>
{installed && <CheckCircle size={10} color={FINCEPT.GREEN} />}
+ {installing && (
+ <Loader2
+ size={10}
+ color={FINCEPT.CYAN}
+ style={{ animation: 'spin 1s linear infinite' }}
+ />
+ )}
</div>
<span style={{
padding: '2px 6px',
@@ -301,6 +407,50 @@ const MCPMarketplace: React.FC<MCPMarketplaceProps> = ({ onInstall, installedSer
<CheckCircle size={10} />
INSTALLED
</button>
+ ) : installing ? (
+ <div style={{ width: '100%' }}>
+ <button
+ disabled
+ style={{
+ width: '100%',
+ padding: '8px 16px',
+ backgroundColor: FINCEPT.CYAN,
+ color: FINCEPT.DARK_BG,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'not-allowed',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ fontFamily: FONT_FAMILY,
+ animation: 'pulse 1.5s ease-in-out infinite',
+ }}
+ >
+ <Loader2 size={10} style={{ animation: 'spin 1s linear infinite' }} />
+ INSTALLING...
+ </button>
+ {/* Progress status message */}
+ {installProgress.get(server.id) && (
+ <div style={{
+ marginTop: '6px',
+ padding: '4px 8px',
+ backgroundColor: `${FINCEPT.CYAN}10`,
+ border: `1px solid ${FINCEPT.CYAN}30`,
+ borderRadius: '2px',
+ fontSize: '8px',
+ color: FINCEPT.CYAN,
+ textAlign: 'center',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ }}>
+ {installProgress.get(server.id)}
+ </div>
+ )}
+ </div>
) : (
<button
onClick={() => handleInstallClick(server)}
@@ -319,6 +469,15 @@ const MCPMarketplace: React.FC<MCPMarketplaceProps> = ({ onInstall, installedSer
justifyContent: 'center',
gap: '4px',
fontFamily: FONT_FAMILY,
+ transition: 'all 0.2s',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#FF9922';
+ e.currentTarget.style.transform = 'scale(1.02)';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = FINCEPT.ORANGE;
+ e.currentTarget.style.transform = 'scale(1)';
}}
>
<Download size={10} />
@@ -407,18 +566,18 @@ const MCPMarketplace: React.FC<MCPMarketplaceProps> = ({ onInstall, installedSer
{configureServer.id === 'postgres' ? (
<PostgresForm
onSubmit={handleConfiguredInstall}
- onCancel={() => setConfigureServer(null)}
+ onCancel={handleCloseConfig}
/>
) : configureServer.id === 'questdb' ? (
<QuestDBForm
onSubmit={handleConfiguredInstall}
- onCancel={() => setConfigureServer(null)}
+ onCancel={handleCloseConfig}
/>
) : (
<GenericForm
server={configureServer}
onSubmit={handleConfiguredInstall}
- onCancel={() => setConfigureServer(null)}
+ onCancel={handleCloseConfig}
/>
)}
</div>
@@ -429,4 +588,14 @@ const MCPMarketplace: React.FC<MCPMarketplaceProps> = ({ onInstall, installedSer
);
};
+// ============================================================================
+// Export with ErrorBoundary wrapper
+// ============================================================================
+
+const MCPMarketplace: React.FC<MCPMarketplaceProps> = (props) => (
+ <ErrorBoundary name="MCP Marketplace" variant="default">
+ <MCPMarketplaceInner {...props} />
+ </ErrorBoundary>
+);
+
export default MCPMarketplace;
diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/serverDefinitions.ts b/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/serverDefinitions.ts
index 9df937635..4c601f9a2 100644
--- a/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/serverDefinitions.ts
+++ b/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/serverDefinitions.ts
@@ -59,6 +59,25 @@ export const MARKETPLACE_SERVERS: MCPServerDefinition[] = [
requiresConfig: false,
tools: ['search_wikipedia', 'get_article', 'get_summary', 'get_sections', 'get_links', 'get_coordinates', 'get_related_topics', 'summarize_article_for_query', 'summarize_article_section', 'extract_key_facts'],
documentation: 'https://github.com/Rudra-ravi/wikipedia-mcp'
+ },
+ {
+ id: 'defeatbeta-api',
+ name: 'DefeatBeta API',
+ description: 'Open-source Yahoo Finance alternative with 70+ financial tools: stock data, earnings transcripts, financial statements, valuation ratios. Prerequisites: Install uv first (pip install uv)',
+ category: 'data',
+ icon: '📈',
+ command: 'uvx',
+ args: ['--refresh', 'git+https://github.com/defeat-beta/defeatbeta-api.git#subdirectory=mcp'],
+ env: {},
+ requiresConfig: false,
+ tools: [
+ 'get_stock_profile', 'get_stock_price', 'get_stock_news', 'get_stock_sec_filings',
+ 'get_stock_earning_call_transcript', 'get_quarterly_income_statement', 'get_annual_income_statement',
+ 'get_quarterly_balance_sheet', 'get_annual_balance_sheet', 'get_quarterly_cash_flow_statement',
+ 'get_quarterly_revenue_by_segment', 'get_quarterly_revenue_by_geography',
+ 'get_sp500_historical_annual_returns', 'get_sp500_cagr_returns', 'get_daily_treasury_yield'
+ ],
+ documentation: 'https://github.com/defeat-beta/defeatbeta-api/blob/main/mcp/README.md'
}
// Kite MCP server removed - moved to equity-trading tab with new implementation
];
diff --git a/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx b/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
index 3919f9306..b04c2bd97 100644
--- a/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
@@ -893,6 +893,7 @@ const NewsTab: React.FC = () => {
</div>
{/* Summary */}
+ {analysisData.analysis.summary && typeof analysisData.analysis.summary === 'string' && (
<div style={{ marginBottom: '14px' }}>
<div style={{
fontSize: '9px',
@@ -915,9 +916,10 @@ const NewsTab: React.FC = () => {
{analysisData.analysis.summary}
</div>
</div>
+ )}
{/* Key Points */}
- {analysisData.analysis.key_points.length > 0 && (
+ {analysisData.analysis.key_points && Array.isArray(analysisData.analysis.key_points) && analysisData.analysis.key_points.length > 0 && (
<div style={{ marginBottom: '14px' }}>
<div style={{
fontSize: '9px',
@@ -934,7 +936,7 @@ const NewsTab: React.FC = () => {
border: `1px solid ${F.BORDER}`,
borderRadius: '2px',
}}>
- {analysisData.analysis.key_points.map((pt, i) => (
+ {analysisData.analysis.key_points.filter(pt => typeof pt === 'string').map((pt, i) => (
<div
key={i}
style={{
@@ -1052,6 +1054,7 @@ const NewsTab: React.FC = () => {
</div>
{/* Risk Signals */}
+ {analysisData.analysis.risk_signals && typeof analysisData.analysis.risk_signals === 'object' && !('error' in analysisData.analysis.risk_signals) && (
<div style={{ marginBottom: '14px' }}>
<div style={{
fontSize: '9px',
@@ -1063,7 +1066,13 @@ const NewsTab: React.FC = () => {
RISK SIGNALS
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px' }}>
- {Object.entries(analysisData.analysis.risk_signals).map(([type, signal]) => (
+ {Object.entries(analysisData.analysis.risk_signals).map(([type, signal]) => {
+ // Skip if signal is not a valid object with level/details
+ if (!signal || typeof signal !== 'object' || 'error' in signal || !('level' in signal)) {
+ return null;
+ }
+ const riskSignal = signal as { level: string; details?: string };
+ return (
<div
key={type}
style={{
@@ -1074,29 +1083,31 @@ const NewsTab: React.FC = () => {
}}
>
<div style={{
- color: getRiskColor(signal.level),
+ color: getRiskColor(riskSignal.level || 'none'),
fontWeight: 700,
fontSize: '9px',
marginBottom: '2px',
}}>
- {type.toUpperCase()}: {signal.level.toUpperCase()}
+ {type.toUpperCase()}: {(riskSignal.level || 'NONE').toUpperCase()}
</div>
- {signal.details && (
+ {riskSignal.details && typeof riskSignal.details === 'string' && (
<div style={{
color: F.MUTED,
fontSize: '8px',
lineHeight: '1.3',
}}>
- {signal.details}
+ {riskSignal.details}
</div>
)}
</div>
- ))}
+ );
+ })}
</div>
</div>
+ )}
{/* Topics */}
- {analysisData.analysis.topics.length > 0 && (
+ {analysisData.analysis.topics && Array.isArray(analysisData.analysis.topics) && analysisData.analysis.topics.length > 0 && (
<div style={{ marginBottom: '14px' }}>
<div style={{
fontSize: '9px',
@@ -1107,7 +1118,7 @@ const NewsTab: React.FC = () => {
TOPICS
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
- {analysisData.analysis.topics.map((topic, idx) => (
+ {analysisData.analysis.topics.filter(topic => typeof topic === 'string').map((topic, idx) => (
<span
key={idx}
style={{
@@ -1128,7 +1139,7 @@ const NewsTab: React.FC = () => {
)}
{/* Keywords */}
- {analysisData.analysis.keywords.length > 0 && (
+ {analysisData.analysis.keywords && Array.isArray(analysisData.analysis.keywords) && analysisData.analysis.keywords.length > 0 && (
<div style={{ marginBottom: '14px' }}>
<div style={{
fontSize: '9px',
@@ -1139,7 +1150,7 @@ const NewsTab: React.FC = () => {
KEYWORDS
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
- {analysisData.analysis.keywords.slice(0, 10).map((kw, idx) => (
+ {analysisData.analysis.keywords.filter(kw => typeof kw === 'string').slice(0, 10).map((kw, idx) => (
<span
key={idx}
style={{
@@ -1159,7 +1170,7 @@ const NewsTab: React.FC = () => {
)}
{/* Organizations */}
- {analysisData.analysis.entities.organizations.length > 0 && (
+ {analysisData.analysis.entities && analysisData.analysis.entities.organizations && Array.isArray(analysisData.analysis.entities.organizations) && analysisData.analysis.entities.organizations.length > 0 && (
<div>
<div style={{
fontSize: '9px',
@@ -1169,7 +1180,7 @@ const NewsTab: React.FC = () => {
}}>
ORGANIZATIONS
</div>
- {analysisData.analysis.entities.organizations.map((org, idx) => (
+ {analysisData.analysis.entities.organizations.filter(org => org && typeof org === 'object' && 'name' in org).map((org, idx) => (
<div
key={idx}
style={{
@@ -1185,14 +1196,14 @@ const NewsTab: React.FC = () => {
fontWeight: 700,
fontSize: '9px',
}}>
- {org.name}
+ {typeof org.name === 'string' ? org.name : ''}
</span>
<span style={{
color: F.GRAY,
fontSize: '9px',
marginLeft: '6px',
}}>
- {org.sector} {org.ticker ? `| ${org.ticker}` : ''}
+ {typeof org.sector === 'string' ? org.sector : ''} {org.ticker && typeof org.ticker === 'string' ? `| ${org.ticker}` : ''}
</span>
</div>
))}
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/components/CustomNode.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/components/CustomNode.tsx
index 5e33d9f7e..c79dbf235 100644
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/components/CustomNode.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/components/CustomNode.tsx
@@ -26,13 +26,30 @@ interface CustomNodeProps {
const CustomNode: React.FC<CustomNodeProps> = ({ data, id, selected }) => {
const [isEditing, setIsEditing] = useState(false);
- const [label, setLabel] = useState(data.label);
+ const [label, setLabel] = useState(data?.label || 'Node');
const handleLabelSave = () => {
- data.onLabelChange(id, label);
+ if (data?.onLabelChange) {
+ data.onLabelChange(id, label);
+ }
setIsEditing(false);
};
+ // Handle missing data gracefully
+ if (!data) {
+ return (
+ <div style={{
+ background: '#1a1a1a',
+ border: '2px solid #f59e0b',
+ borderRadius: '6px',
+ padding: '12px',
+ minWidth: '180px',
+ }}>
+ <div style={{ color: '#f59e0b', fontSize: '12px' }}>Invalid Node Data</div>
+ </div>
+ );
+ }
+
const getIcon = () => {
switch (data.nodeType) {
case 'data-source':
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/nodes/SystemNode.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/nodes/SystemNode.tsx
index c17680cb9..584b8f860 100644
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/nodes/SystemNode.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/nodes/SystemNode.tsx
@@ -40,17 +40,33 @@ export const SystemNode: React.FC<NodeProps<SystemNodeData>> = ({
data,
selected,
}) => {
- const node = data.node;
+ const node = data?.node;
- // Get node type definition
+ // Get node type definition - handle missing node gracefully
const nodeType = useMemo<INodeType | null>(() => {
+ if (!node?.type) {
+ return null;
+ }
try {
return NodeRegistry.getNodeType(node.type, node.typeVersion);
} catch (error) {
console.error('Failed to get node type:', error);
return null;
}
- }, [node.type, node.typeVersion]);
+ }, [node?.type, node?.typeVersion]);
+
+ // Handle missing node data
+ if (!node) {
+ return (
+ <div className="px-4 py-3 bg-yellow-900/20 border-2 border-yellow-500 rounded-lg min-w-[200px]">
+ <div className="flex items-center gap-2 text-yellow-400">
+ <AlertCircle size={16} />
+ <span className="text-sm font-medium">Invalid Node Data</span>
+ </div>
+ <div className="text-xs text-yellow-400/70 mt-1">Node data is missing or corrupted</div>
+ </div>
+ );
+ }
// Node color
const nodeColor = nodeType?.description?.defaults?.color || '#888888';
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/SettingsTab.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/SettingsTab.tsx
index 7edb64d90..831e1ef54 100644
--- a/fincept-terminal-desktop/src/components/tabs/settings-tab/SettingsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/SettingsTab.tsx
@@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react';
-import { Settings as SettingsIcon, Lock, Bot, Database, Terminal, Activity, Globe, TrendingUp, Briefcase, HardDrive, Bell } from 'lucide-react';
+import { Settings as SettingsIcon, Lock, Bot, Database, Terminal, Activity, Globe, TrendingUp, Briefcase, HardDrive, Bell, MessageCircle } from 'lucide-react';
import { useTerminalTheme } from '@/contexts/ThemeContext';
import { useTimezone } from '@/contexts/TimezoneContext';
import { useTranslation } from 'react-i18next';
@@ -21,6 +21,7 @@ import {
TerminalAppearanceSection,
StorageCacheSection,
NotificationsSection,
+ ChatBubbleSection,
} from './sections';
// Hooks and types
@@ -98,6 +99,7 @@ export default function SettingsTab() {
{ id: 'language' as SettingsSection, icon: Globe, label: t('sidebar.language') },
{ id: 'storage' as SettingsSection, icon: HardDrive, label: t('sidebar.storage') },
{ id: 'notifications' as SettingsSection, icon: Bell, label: t('sidebar.notifications') },
+ { id: 'chatBubble' as SettingsSection, icon: MessageCircle, label: 'AI Chat Bubble' },
];
return (
@@ -384,6 +386,14 @@ export default function SettingsTab() {
showMessage={showMessage}
/>
)}
+
+ {/* Chat Bubble Section */}
+ {activeSection === 'chatBubble' && (
+ <ChatBubbleSection
+ colors={settingsColors}
+ showMessage={showMessage}
+ />
+ )}
</div>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/ChatBubbleSection.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/ChatBubbleSection.tsx
new file mode 100644
index 000000000..cf7ce9b05
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/ChatBubbleSection.tsx
@@ -0,0 +1,778 @@
+// Chat Bubble Settings Section
+// Supports multiple TTS providers: Browser, Edge TTS, ElevenLabs, OpenAI
+
+import React, { useState, useEffect } from 'react';
+import { MessageCircle, ToggleLeft, ToggleRight, Info, Volume2, Mic, Gauge, RefreshCw, Key, ChevronDown, ChevronUp, Eye, EyeOff } from 'lucide-react';
+import { invoke } from '@tauri-apps/api/core';
+import type { SettingsColors } from '../types';
+import { ttsService, TTSProvider, EDGE_VOICES, ELEVENLABS_VOICES, OPENAI_VOICES, TTSVoice } from '@/services/voice/ttsService';
+
+const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ GREEN: '#00D66F',
+ RED: '#FF3B3B',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A',
+};
+
+// Provider info for display
+const PROVIDERS = [
+ { id: 'browser' as TTSProvider, name: 'Browser Native', description: 'Uses your system voices (free)', requiresKey: false },
+ { id: 'edge' as TTSProvider, name: 'Edge TTS', description: 'High-quality Microsoft neural voices (free)', requiresKey: false },
+ { id: 'elevenlabs' as TTSProvider, name: 'ElevenLabs', description: 'Ultra-realistic AI voices (API key required)', requiresKey: true },
+ { id: 'openai' as TTSProvider, name: 'OpenAI TTS', description: 'OpenAI text-to-speech voices (API key required)', requiresKey: true },
+];
+
+interface ChatBubbleSectionProps {
+ colors: SettingsColors;
+ showMessage: (type: 'success' | 'error', text: string) => void;
+}
+
+export function ChatBubbleSection({ colors, showMessage }: ChatBubbleSectionProps) {
+ const [enabled, setEnabled] = useState(true);
+ const [loading, setLoading] = useState(false);
+
+ // TTS provider settings
+ const [selectedProvider, setSelectedProvider] = useState<TTSProvider>('browser');
+ const [selectedVoice, setSelectedVoice] = useState('');
+ const [speechRate, setSpeechRate] = useState(1.4);
+ const [autoStartVoice, setAutoStartVoice] = useState(false);
+
+ // API Keys
+ const [elevenLabsApiKey, setElevenLabsApiKey] = useState('');
+ const [openaiApiKey, setOpenaiApiKey] = useState('');
+ const [showElevenLabsKey, setShowElevenLabsKey] = useState(false);
+ const [showOpenaiKey, setShowOpenaiKey] = useState(false);
+ const [apiKeysExpanded, setApiKeysExpanded] = useState(false);
+
+ // Available voices
+ const [browserVoices, setBrowserVoices] = useState<SpeechSynthesisVoice[]>([]);
+ const [voicesLoaded, setVoicesLoaded] = useState(false);
+
+ // Load browser voices
+ useEffect(() => {
+ const loadVoices = () => {
+ if (!window.speechSynthesis) return;
+
+ const voices = window.speechSynthesis.getVoices();
+ const englishVoices = voices.filter(v => v.lang.startsWith('en'));
+ setBrowserVoices(englishVoices);
+ setVoicesLoaded(englishVoices.length > 0);
+
+ console.log('[ChatBubbleSection] Loaded browser voices:', englishVoices.length);
+ };
+
+ loadVoices();
+ if (window.speechSynthesis) {
+ window.speechSynthesis.onvoiceschanged = loadVoices;
+ }
+
+ return () => {
+ if (window.speechSynthesis) {
+ window.speechSynthesis.onvoiceschanged = null;
+ }
+ };
+ }, []);
+
+ // Load settings on mount
+ useEffect(() => {
+ const load = async () => {
+ try {
+ const [bubbleEnabled, provider, voice, rate, autoVoice, elevenKey, openaiKey] = await Promise.all([
+ invoke<string | null>('db_get_setting', { key: 'chat_bubble_enabled' }),
+ invoke<string | null>('db_get_setting', { key: 'chat_bubble_tts_provider' }),
+ invoke<string | null>('db_get_setting', { key: 'chat_bubble_voice' }),
+ invoke<string | null>('db_get_setting', { key: 'chat_bubble_speech_rate' }),
+ invoke<string | null>('db_get_setting', { key: 'chat_bubble_auto_voice' }),
+ invoke<string | null>('db_get_setting', { key: 'elevenlabs_api_key' }),
+ invoke<string | null>('db_get_setting', { key: 'openai_tts_api_key' }),
+ ]);
+
+ setEnabled(bubbleEnabled !== 'false');
+ if (provider) setSelectedProvider(provider as TTSProvider);
+ if (voice) setSelectedVoice(voice);
+ if (rate) setSpeechRate(parseFloat(rate));
+ setAutoStartVoice(autoVoice === 'true');
+ if (elevenKey) setElevenLabsApiKey(elevenKey);
+ if (openaiKey) setOpenaiApiKey(openaiKey);
+ } catch (error) {
+ console.error('[ChatBubbleSection] Load error:', error);
+ }
+ };
+ load();
+ }, []);
+
+ const handleToggle = async () => {
+ setLoading(true);
+ try {
+ const newValue = !enabled;
+ await invoke('db_save_setting', { key: 'chat_bubble_enabled', value: String(newValue), category: 'ui' });
+ setEnabled(newValue);
+ showMessage('success', `Chat bubble ${newValue ? 'enabled' : 'disabled'}. Restart for changes to take effect.`);
+ } catch (error) {
+ console.error('[ChatBubbleSection] Save error:', error);
+ showMessage('error', 'Failed to save setting');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ // Get voices for current provider
+ const getCurrentVoices = (): TTSVoice[] => {
+ switch (selectedProvider) {
+ case 'browser':
+ return browserVoices.map(v => ({
+ id: v.name,
+ name: v.name,
+ provider: 'browser' as TTSProvider,
+ language: v.lang,
+ }));
+ case 'edge':
+ return EDGE_VOICES;
+ case 'elevenlabs':
+ return ELEVENLABS_VOICES;
+ case 'openai':
+ return OPENAI_VOICES;
+ default:
+ return [];
+ }
+ };
+
+ const handleProviderChange = async (provider: TTSProvider) => {
+ try {
+ await invoke('db_save_setting', { key: 'chat_bubble_tts_provider', value: provider, category: 'ui' });
+ setSelectedProvider(provider);
+ // Reset voice selection when provider changes
+ setSelectedVoice('');
+ showMessage('success', `TTS provider changed to ${PROVIDERS.find(p => p.id === provider)?.name}`);
+ } catch (error) {
+ showMessage('error', 'Failed to save provider setting');
+ }
+ };
+
+ const handleVoiceChange = async (voiceId: string) => {
+ try {
+ await invoke('db_save_setting', { key: 'chat_bubble_voice', value: voiceId, category: 'ui' });
+ setSelectedVoice(voiceId);
+ showMessage('success', 'Voice updated');
+ } catch (error) {
+ showMessage('error', 'Failed to save voice setting');
+ }
+ };
+
+ const handleRateChange = async (rate: number) => {
+ setSpeechRate(rate);
+ try {
+ await invoke('db_save_setting', { key: 'chat_bubble_speech_rate', value: String(rate), category: 'ui' });
+ } catch (error) {
+ console.error('[ChatBubbleSection] Rate save error:', error);
+ }
+ };
+
+ const handleAutoVoiceToggle = async () => {
+ try {
+ const newValue = !autoStartVoice;
+ await invoke('db_save_setting', { key: 'chat_bubble_auto_voice', value: String(newValue), category: 'ui' });
+ setAutoStartVoice(newValue);
+ showMessage('success', `Auto voice mode ${newValue ? 'enabled' : 'disabled'}`);
+ } catch (error) {
+ showMessage('error', 'Failed to save setting');
+ }
+ };
+
+ const handleSaveApiKey = async (keyType: 'elevenlabs' | 'openai', value: string) => {
+ try {
+ const key = keyType === 'elevenlabs' ? 'elevenlabs_api_key' : 'openai_tts_api_key';
+ await invoke('db_save_setting', { key, value, category: 'api' });
+ showMessage('success', `${keyType === 'elevenlabs' ? 'ElevenLabs' : 'OpenAI'} API key saved`);
+ } catch (error) {
+ showMessage('error', 'Failed to save API key');
+ }
+ };
+
+ const refreshVoices = () => {
+ if (!window.speechSynthesis) return;
+ const voices = window.speechSynthesis.getVoices();
+ const englishVoices = voices.filter(v => v.lang.startsWith('en'));
+ setBrowserVoices(englishVoices);
+ setVoicesLoaded(englishVoices.length > 0);
+ showMessage('success', `Found ${englishVoices.length} browser voices`);
+ };
+
+ const testVoice = async () => {
+ const text = 'Hello, I am your Fincept AI assistant. How can I help you today?';
+
+ try {
+ await ttsService.speak(text, {
+ provider: selectedProvider,
+ voiceId: selectedVoice,
+ rate: speechRate,
+ elevenLabsApiKey: elevenLabsApiKey || undefined,
+ openaiApiKey: openaiApiKey || undefined,
+ });
+ } catch (error) {
+ console.error('[TestVoice] Error:', error);
+ showMessage('error', `Failed to test voice: ${error}`);
+ }
+ };
+
+ const currentVoices = getCurrentVoices();
+
+ return (
+ <div>
+ {/* Header */}
+ <div style={{
+ marginBottom: '20px',
+ paddingBottom: '12px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
+ <MessageCircle size={16} color={FINCEPT.ORANGE} />
+ <h2 style={{
+ fontSize: '11px',
+ fontWeight: 700,
+ color: FINCEPT.WHITE,
+ margin: 0,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase'
+ }}>
+ AI CHAT BUBBLE
+ </h2>
+ </div>
+ <p style={{
+ fontSize: '10px',
+ color: FINCEPT.GRAY,
+ marginTop: '8px',
+ lineHeight: 1.5
+ }}>
+ Configure the floating AI chat assistant bubble and voice settings.
+ </p>
+ </div>
+
+ {/* Enable/Disable Toggle */}
+ <div style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '4px',
+ padding: '16px',
+ marginBottom: '16px'
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between'
+ }}>
+ <div>
+ <div style={{
+ fontSize: '10px',
+ fontWeight: 700,
+ color: FINCEPT.WHITE,
+ marginBottom: '4px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px'
+ }}>
+ ENABLE CHAT BUBBLE
+ </div>
+ <div style={{
+ fontSize: '9px',
+ color: FINCEPT.GRAY,
+ lineHeight: 1.4
+ }}>
+ Show floating AI assistant button in bottom-right corner
+ </div>
+ </div>
+
+ <button
+ onClick={handleToggle}
+ disabled={loading}
+ style={{
+ background: 'transparent',
+ border: 'none',
+ cursor: loading ? 'not-allowed' : 'pointer',
+ opacity: loading ? 0.5 : 1,
+ padding: '4px',
+ display: 'flex',
+ alignItems: 'center'
+ }}
+ >
+ {enabled ? (
+ <ToggleRight size={32} color={FINCEPT.GREEN} />
+ ) : (
+ <ToggleLeft size={32} color={FINCEPT.MUTED} />
+ )}
+ </button>
+ </div>
+
+ {/* Status indicator */}
+ <div style={{
+ marginTop: '12px',
+ padding: '8px 10px',
+ backgroundColor: enabled ? `${FINCEPT.GREEN}10` : `${FINCEPT.MUTED}10`,
+ border: `1px solid ${enabled ? FINCEPT.GREEN : FINCEPT.MUTED}`,
+ borderRadius: '2px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ <div style={{
+ width: '6px',
+ height: '6px',
+ borderRadius: '50%',
+ backgroundColor: enabled ? FINCEPT.GREEN : FINCEPT.MUTED
+ }} />
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ color: enabled ? FINCEPT.GREEN : FINCEPT.MUTED,
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px'
+ }}>
+ {enabled ? 'ACTIVE' : 'DISABLED'}
+ </span>
+ </div>
+ </div>
+
+ {/* Voice Settings Section */}
+ <div style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '4px',
+ padding: '16px',
+ marginBottom: '16px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Volume2 size={14} color={FINCEPT.ORANGE} />
+ <span style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.WHITE, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
+ TEXT-TO-SPEECH
+ </span>
+ </div>
+ {selectedProvider === 'browser' && (
+ <button
+ onClick={refreshVoices}
+ style={{
+ background: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ padding: '4px 8px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ color: FINCEPT.GRAY,
+ fontSize: '8px'
+ }}
+ title="Refresh browser voices"
+ >
+ <RefreshCw size={10} />
+ REFRESH
+ </button>
+ )}
+ </div>
+
+ {/* TTS Provider Selection */}
+ <div style={{ marginBottom: '16px' }}>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '8px', textTransform: 'uppercase' }}>
+ TTS PROVIDER
+ </div>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px' }}>
+ {PROVIDERS.map(provider => (
+ <button
+ key={provider.id}
+ onClick={() => handleProviderChange(provider.id)}
+ style={{
+ padding: '10px',
+ backgroundColor: selectedProvider === provider.id ? `${FINCEPT.ORANGE}15` : FINCEPT.DARK_BG,
+ border: `1px solid ${selectedProvider === provider.id ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ borderRadius: '4px',
+ cursor: 'pointer',
+ textAlign: 'left'
+ }}
+ >
+ <div style={{ fontSize: '9px', fontWeight: 700, color: selectedProvider === provider.id ? FINCEPT.ORANGE : FINCEPT.WHITE, marginBottom: '2px' }}>
+ {provider.name}
+ </div>
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED, lineHeight: 1.3 }}>
+ {provider.description}
+ </div>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Voice Selection */}
+ <div style={{ marginBottom: '16px' }}>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '8px', textTransform: 'uppercase' }}>
+ {selectedProvider === 'browser' ? `BROWSER VOICES (${currentVoices.length})` :
+ selectedProvider === 'edge' ? 'EDGE TTS VOICES' :
+ selectedProvider === 'elevenlabs' ? 'ELEVENLABS VOICES' : 'OPENAI VOICES'}
+ </div>
+
+ {selectedProvider === 'browser' && !voicesLoaded ? (
+ <div style={{ padding: '12px', backgroundColor: FINCEPT.DARK_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px', color: FINCEPT.GRAY, fontSize: '9px', textAlign: 'center' }}>
+ Loading voices... Click REFRESH if voices don't appear.
+ </div>
+ ) : currentVoices.length === 0 ? (
+ <div style={{ padding: '12px', backgroundColor: FINCEPT.DARK_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px', color: FINCEPT.GRAY, fontSize: '9px', textAlign: 'center' }}>
+ No voices available for this provider.
+ </div>
+ ) : (
+ <div style={{ maxHeight: '160px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ {currentVoices.map(voice => (
+ <button
+ key={voice.id}
+ onClick={() => handleVoiceChange(voice.id)}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '8px 10px',
+ backgroundColor: selectedVoice === voice.id ? `${FINCEPT.ORANGE}15` : FINCEPT.DARK_BG,
+ border: `1px solid ${selectedVoice === voice.id ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ cursor: 'pointer',
+ textAlign: 'left'
+ }}
+ >
+ <div>
+ <div style={{ fontSize: '9px', fontWeight: 600, color: selectedVoice === voice.id ? FINCEPT.ORANGE : FINCEPT.WHITE }}>
+ {voice.name}
+ </div>
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED, marginTop: '2px' }}>
+ {voice.language} {voice.gender ? `• ${voice.gender}` : ''}
+ </div>
+ </div>
+ {selectedVoice === voice.id && (
+ <div style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: FINCEPT.ORANGE }} />
+ )}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* Speech Rate */}
+ <div style={{ marginBottom: '16px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <Gauge size={12} color={FINCEPT.GRAY} />
+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, textTransform: 'uppercase' }}>
+ SPEECH SPEED
+ </span>
+ </div>
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.ORANGE }}>
+ {speechRate.toFixed(1)}x
+ </span>
+ </div>
+ <input
+ type="range"
+ min="0.5"
+ max="2.0"
+ step="0.1"
+ value={speechRate}
+ onChange={(e) => handleRateChange(parseFloat(e.target.value))}
+ style={{
+ width: '100%',
+ accentColor: FINCEPT.ORANGE,
+ height: '4px',
+ cursor: 'pointer'
+ }}
+ />
+ <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '8px', color: FINCEPT.MUTED, marginTop: '4px' }}>
+ <span>0.5x (Slow)</span>
+ <span>1.0x</span>
+ <span>2.0x (Fast)</span>
+ </div>
+ </div>
+
+ {/* Test Voice Button */}
+ <button
+ onClick={testVoice}
+ disabled={currentVoices.length === 0 || !selectedVoice}
+ style={{
+ width: '100%',
+ padding: '10px',
+ backgroundColor: currentVoices.length > 0 && selectedVoice ? FINCEPT.DARK_BG : FINCEPT.MUTED,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '4px',
+ color: currentVoices.length > 0 && selectedVoice ? FINCEPT.WHITE : FINCEPT.GRAY,
+ fontSize: '10px',
+ fontWeight: 600,
+ cursor: currentVoices.length > 0 && selectedVoice ? 'pointer' : 'not-allowed',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px'
+ }}
+ >
+ <Volume2 size={14} />
+ TEST VOICE
+ </button>
+ </div>
+
+ {/* API Keys Section */}
+ {(selectedProvider === 'elevenlabs' || selectedProvider === 'openai') && (
+ <div style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '4px',
+ padding: '16px',
+ marginBottom: '16px'
+ }}>
+ <button
+ onClick={() => setApiKeysExpanded(!apiKeysExpanded)}
+ style={{
+ width: '100%',
+ background: 'transparent',
+ border: 'none',
+ padding: 0,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: apiKeysExpanded ? '16px' : 0
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Key size={14} color={FINCEPT.ORANGE} />
+ <span style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.WHITE, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
+ API KEYS
+ </span>
+ </div>
+ {apiKeysExpanded ? <ChevronUp size={14} color={FINCEPT.GRAY} /> : <ChevronDown size={14} color={FINCEPT.GRAY} />}
+ </button>
+
+ {apiKeysExpanded && (
+ <>
+ {/* ElevenLabs API Key */}
+ {selectedProvider === 'elevenlabs' && (
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '6px', textTransform: 'uppercase' }}>
+ ELEVENLABS API KEY
+ </div>
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <div style={{ flex: 1, position: 'relative' }}>
+ <input
+ type={showElevenLabsKey ? 'text' : 'password'}
+ value={elevenLabsApiKey}
+ onChange={(e) => setElevenLabsApiKey(e.target.value)}
+ placeholder="Enter ElevenLabs API key..."
+ style={{
+ width: '100%',
+ padding: '8px 32px 8px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ color: FINCEPT.WHITE,
+ fontSize: '9px',
+ fontFamily: 'monospace'
+ }}
+ />
+ <button
+ onClick={() => setShowElevenLabsKey(!showElevenLabsKey)}
+ style={{
+ position: 'absolute',
+ right: '6px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ background: 'transparent',
+ border: 'none',
+ cursor: 'pointer',
+ padding: '2px',
+ color: FINCEPT.GRAY
+ }}
+ >
+ {showElevenLabsKey ? <EyeOff size={12} /> : <Eye size={12} />}
+ </button>
+ </div>
+ <button
+ onClick={() => handleSaveApiKey('elevenlabs', elevenLabsApiKey)}
+ style={{
+ padding: '8px 12px',
+ backgroundColor: FINCEPT.ORANGE,
+ border: 'none',
+ borderRadius: '3px',
+ color: FINCEPT.DARK_BG,
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer'
+ }}
+ >
+ SAVE
+ </button>
+ </div>
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED, marginTop: '4px' }}>
+ Get your API key from <a href="https://elevenlabs.io" target="_blank" rel="noopener" style={{ color: FINCEPT.ORANGE }}>elevenlabs.io</a>
+ </div>
+ </div>
+ )}
+
+ {/* OpenAI API Key */}
+ {selectedProvider === 'openai' && (
+ <div>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '6px', textTransform: 'uppercase' }}>
+ OPENAI API KEY
+ </div>
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <div style={{ flex: 1, position: 'relative' }}>
+ <input
+ type={showOpenaiKey ? 'text' : 'password'}
+ value={openaiApiKey}
+ onChange={(e) => setOpenaiApiKey(e.target.value)}
+ placeholder="Enter OpenAI API key..."
+ style={{
+ width: '100%',
+ padding: '8px 32px 8px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ color: FINCEPT.WHITE,
+ fontSize: '9px',
+ fontFamily: 'monospace'
+ }}
+ />
+ <button
+ onClick={() => setShowOpenaiKey(!showOpenaiKey)}
+ style={{
+ position: 'absolute',
+ right: '6px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ background: 'transparent',
+ border: 'none',
+ cursor: 'pointer',
+ padding: '2px',
+ color: FINCEPT.GRAY
+ }}
+ >
+ {showOpenaiKey ? <EyeOff size={12} /> : <Eye size={12} />}
+ </button>
+ </div>
+ <button
+ onClick={() => handleSaveApiKey('openai', openaiApiKey)}
+ style={{
+ padding: '8px 12px',
+ backgroundColor: FINCEPT.ORANGE,
+ border: 'none',
+ borderRadius: '3px',
+ color: FINCEPT.DARK_BG,
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer'
+ }}
+ >
+ SAVE
+ </button>
+ </div>
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED, marginTop: '4px' }}>
+ Get your API key from <a href="https://platform.openai.com/api-keys" target="_blank" rel="noopener" style={{ color: FINCEPT.ORANGE }}>platform.openai.com</a>
+ </div>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ )}
+
+ {/* Auto Voice Mode Toggle */}
+ <div style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '4px',
+ padding: '16px',
+ marginBottom: '16px'
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '10px' }}>
+ <Mic size={14} color={FINCEPT.ORANGE} style={{ marginTop: '2px' }} />
+ <div>
+ <div style={{
+ fontSize: '10px',
+ fontWeight: 700,
+ color: FINCEPT.WHITE,
+ marginBottom: '4px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px'
+ }}>
+ AUTO-START VOICE MODE
+ </div>
+ <div style={{
+ fontSize: '9px',
+ color: FINCEPT.GRAY,
+ lineHeight: 1.4
+ }}>
+ Automatically enable voice mode when opening chat bubble
+ </div>
+ </div>
+ </div>
+
+ <button
+ onClick={handleAutoVoiceToggle}
+ style={{
+ background: 'transparent',
+ border: 'none',
+ cursor: 'pointer',
+ padding: '4px',
+ display: 'flex',
+ alignItems: 'center'
+ }}
+ >
+ {autoStartVoice ? (
+ <ToggleRight size={28} color={FINCEPT.GREEN} />
+ ) : (
+ <ToggleLeft size={28} color={FINCEPT.MUTED} />
+ )}
+ </button>
+ </div>
+ </div>
+
+ {/* Info Card */}
+ <div style={{
+ backgroundColor: `${FINCEPT.ORANGE}10`,
+ border: `1px solid ${FINCEPT.ORANGE}40`,
+ borderRadius: '4px',
+ padding: '12px'
+ }}>
+ <div style={{ display: 'flex', gap: '10px' }}>
+ <Info size={14} color={FINCEPT.ORANGE} style={{ flexShrink: 0, marginTop: '2px' }} />
+ <div>
+ <div style={{
+ fontSize: '10px',
+ fontWeight: 700,
+ color: FINCEPT.ORANGE,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px'
+ }}>
+ VOICE MODE FEATURES
+ </div>
+ <ul style={{
+ margin: 0,
+ padding: '0 0 0 14px',
+ fontSize: '9px',
+ color: FINCEPT.GRAY,
+ lineHeight: 1.6
+ }}>
+ <li>Hands-free conversation with AI assistant</li>
+ <li>4 TTS providers: Browser, Edge TTS, ElevenLabs, OpenAI</li>
+ <li>Edge TTS: Free high-quality Microsoft neural voices</li>
+ <li>ElevenLabs/OpenAI: Premium AI voices (API key required)</li>
+ <li>Works even when chat bubble is minimized</li>
+ <li>Click VOICE button in chat to activate</li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/index.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/index.ts
index 1d3436b1a..565c7736f 100644
--- a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/index.ts
@@ -3,3 +3,4 @@ export { LLMConfigSection } from './LLMConfigSection';
export { TerminalAppearanceSection } from './TerminalAppearanceSection';
export { StorageCacheSection } from './StorageCacheSection';
export { NotificationsSection } from './NotificationsSection';
+export { ChatBubbleSection } from './ChatBubbleSection';
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/types.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/types.ts
index 3bb145f5c..9ad7f0164 100644
--- a/fincept-terminal-desktop/src/components/tabs/settings-tab/types.ts
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/types.ts
@@ -11,7 +11,8 @@ export type SettingsSection =
| 'stockSymbols'
| 'language'
| 'storage'
- | 'notifications';
+ | 'notifications'
+ | 'chatBubble';
export interface SettingsMessage {
type: 'success' | 'error';
diff --git a/fincept-terminal-desktop/src/components/tabs/tauri-events-monitor/TauriEventsMonitorTab.tsx b/fincept-terminal-desktop/src/components/tabs/tauri-events-monitor/TauriEventsMonitorTab.tsx
new file mode 100644
index 000000000..3d4f5bc8b
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/tauri-events-monitor/TauriEventsMonitorTab.tsx
@@ -0,0 +1,736 @@
+/**
+ * Tauri Events Monitor Tab
+ *
+ * Real-time monitoring of Tauri events and WebSocket connections
+ * Shows active listeners, event flow, and performance metrics
+ */
+
+import React, { useState, useEffect, useRef } from 'react';
+import { listen, UnlistenFn } from '@tauri-apps/api/event';
+import { Activity, Zap, Circle, Wifi, WifiOff, TrendingUp, Clock, Database, AlertCircle, Eye, EyeOff, Trash2 } from 'lucide-react';
+// Note: Broker contexts are optional and may not be available in all tabs
+// We'll infer connection status from event activity instead
+
+// Event data structures
+interface EventLog {
+ id: string;
+ timestamp: number;
+ eventName: string;
+ payload: any;
+ source: 'stock' | 'crypto' | 'system';
+}
+
+interface EventStats {
+ eventName: string;
+ count: number;
+ lastReceived: number;
+ avgFrequency: number; // events per second
+ source: 'stock' | 'crypto' | 'system';
+}
+
+interface WebSocketConnection {
+ id: string;
+ broker: string;
+ type: 'stock' | 'crypto';
+ status: 'connected' | 'disconnected' | 'error';
+ subscribedSymbols: string[];
+ lastActivity: number;
+ totalTicks: number;
+}
+
+const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A',
+};
+
+export default function TauriEventsMonitorTab() {
+ // Note: We don't use broker contexts here since they may not be available
+ // Instead, we infer connection status from event activity
+
+ // State
+ const [eventLogs, setEventLogs] = useState<EventLog[]>([]);
+ const [eventStats, setEventStats] = useState<Map<string, EventStats>>(new Map());
+ const [wsConnections, setWsConnections] = useState<WebSocketConnection[]>([]);
+ const [activeListeners, setActiveListeners] = useState<string[]>([]);
+ const [isPaused, setIsPaused] = useState(false);
+ const [showPayload, setShowPayload] = useState(false);
+ const [maxLogs, setMaxLogs] = useState(100);
+ const [filterSource, setFilterSource] = useState<'all' | 'stock' | 'crypto' | 'system'>('all');
+
+ const unlistenersRef = useRef<UnlistenFn[]>([]);
+ const statsIntervalRef = useRef<NodeJS.Timeout | null>(null);
+ const isPausedRef = useRef(false);
+
+ // Sync isPaused state with ref
+ useEffect(() => {
+ isPausedRef.current = isPaused;
+ }, [isPaused]);
+
+ // List of known Tauri events to monitor
+ const MONITORED_EVENTS = [
+ // ============================================================================
+ // CRYPTO TRADING (via websocketBridge - unified system)
+ // ============================================================================
+ 'ws_ticker', // Price updates from any crypto exchange
+ 'ws_orderbook', // Order book updates
+ 'ws_trade', // Trade executions
+ 'ws_candle', // OHLC candle data
+ 'ws_status', // WebSocket connection status
+
+ // ============================================================================
+ // INDIAN STOCK BROKERS (individual broker events)
+ // ============================================================================
+ 'zerodha_ticker',
+ 'zerodha_status',
+ 'zerodha_orderbook',
+ 'zerodha_trade',
+ 'zerodha_candle',
+
+ 'fyers_ticker',
+ 'fyers_orderbook',
+ 'fyers_trade',
+ 'fyers_status',
+ 'fyers_candle',
+
+ 'angelone_ticker',
+ 'angelone_orderbook',
+ 'angelone_trade',
+ 'angelone_status',
+ 'angelone_candle',
+
+ 'upstox_ticker',
+ 'upstox_orderbook',
+ 'upstox_trade',
+ 'upstox_status',
+ 'upstox_candle',
+
+ 'dhan_ticker',
+ 'dhan_orderbook',
+ 'dhan_trade',
+ 'dhan_status',
+ 'dhan_candle',
+
+ 'kotak_ticker',
+ 'kotak_orderbook',
+ 'kotak_trade',
+ 'kotak_status',
+ 'kotak_candle',
+
+ 'groww_ticker',
+ 'groww_orderbook',
+ 'groww_trade',
+ 'groww_status',
+ 'groww_candle',
+
+ 'aliceblue_ticker',
+ 'aliceblue_orderbook',
+ 'aliceblue_trade',
+ 'aliceblue_status',
+ 'aliceblue_candle',
+
+ 'fivepaisa_ticker',
+ 'fivepaisa_orderbook',
+ 'fivepaisa_trade',
+ 'fivepaisa_status',
+ 'fivepaisa_candle',
+
+ 'iifl_ticker',
+ 'iifl_orderbook',
+ 'iifl_trade',
+ 'iifl_status',
+ 'iifl_candle',
+
+ 'motilal_ticker',
+ 'motilal_orderbook',
+ 'motilal_trade',
+ 'motilal_status',
+ 'motilal_candle',
+
+ 'shoonya_ticker',
+ 'shoonya_orderbook',
+ 'shoonya_trade',
+ 'shoonya_status',
+ 'shoonya_candle',
+
+ // ============================================================================
+ // US STOCK BROKERS
+ // ============================================================================
+ 'alpaca_trade',
+ 'alpaca_quote',
+ 'alpaca_bar',
+ 'alpaca_status',
+
+ 'ibkr_ticker',
+ 'ibkr_orderbook',
+ 'ibkr_trade',
+ 'ibkr_status',
+
+ 'tradier_ticker',
+ 'tradier_orderbook',
+ 'tradier_trade',
+ 'tradier_status',
+
+ // ============================================================================
+ // MONITORING & ALERTS
+ // ============================================================================
+ 'monitor_alert', // Price/condition alerts from monitoring system
+
+ // ============================================================================
+ // AI AGENT STREAMING
+ // ============================================================================
+ // Note: Agent streaming uses dynamic event names: agent_stream_{session_id}
+ // We can't listen to these specifically, but they show activity
+
+ // ============================================================================
+ // ALPHA ARENA (AI Trading Competition)
+ // ============================================================================
+ 'alpha-arena-progress', // Competition setup/execution progress
+
+ // ============================================================================
+ // DATABENTO (Market Data Provider)
+ // ============================================================================
+ // Note: Databento uses dynamic event names: databento-live-{stream_id}
+
+ // ============================================================================
+ // SETUP & SYSTEM
+ // ============================================================================
+ 'setup-progress', // Initial app setup progress (Python, Bun, packages)
+
+ // ============================================================================
+ // TAURI SYSTEM EVENTS
+ // ============================================================================
+ 'tauri://update-status',
+ 'tauri://file-drop',
+ 'tauri://window-created',
+ 'tauri://focus',
+ 'tauri://blur',
+ ];
+
+ // Initialize event listeners
+ useEffect(() => {
+ const setupListeners = async () => {
+ const unlisteners: UnlistenFn[] = [];
+
+ for (const eventName of MONITORED_EVENTS) {
+ try {
+ const unlisten = await listen(eventName, (event) => {
+ if (isPausedRef.current) return;
+
+ // Determine event source
+ const source: 'stock' | 'crypto' | 'system' = (() => {
+ // Crypto events (ws_* prefix for unified crypto system)
+ if (eventName.startsWith('ws_')) return 'crypto';
+
+ // Stock broker events (specific broker names)
+ if (
+ eventName.includes('alpaca') || eventName.includes('zerodha') || eventName.includes('fyers') ||
+ eventName.includes('angelone') || eventName.includes('upstox') || eventName.includes('dhan') ||
+ eventName.includes('ibkr') || eventName.includes('tradier') || eventName.includes('kotak') ||
+ eventName.includes('groww') || eventName.includes('aliceblue') || eventName.includes('fivepaisa') ||
+ eventName.includes('iifl') || eventName.includes('motilal') || eventName.includes('shoonya')
+ ) {
+ return 'stock';
+ }
+
+ // Everything else is system
+ return 'system';
+ })();
+
+ // Add to event logs
+ const log: EventLog = {
+ id: `${Date.now()}-${Math.random()}`,
+ timestamp: Date.now(),
+ eventName,
+ payload: event.payload,
+ source,
+ };
+
+ setEventLogs(prev => {
+ const updated = [log, ...prev].slice(0, maxLogs);
+ return updated;
+ });
+
+ // Update stats
+ setEventStats(prev => {
+ const newStats = new Map(prev);
+ const existing = newStats.get(eventName);
+
+ if (existing) {
+ const timeDiff = (Date.now() - existing.lastReceived) / 1000;
+ const newFreq = timeDiff > 0 ? 1 / timeDiff : 0;
+ const avgFreq = (existing.avgFrequency * existing.count + newFreq) / (existing.count + 1);
+
+ newStats.set(eventName, {
+ ...existing,
+ count: existing.count + 1,
+ lastReceived: Date.now(),
+ avgFrequency: avgFreq,
+ });
+ } else {
+ newStats.set(eventName, {
+ eventName,
+ count: 1,
+ lastReceived: Date.now(),
+ avgFrequency: 0,
+ source,
+ });
+ }
+
+ return newStats;
+ });
+ });
+
+ unlisteners.push(unlisten);
+ } catch (err) {
+ console.warn(`Failed to listen to ${eventName}:`, err);
+ }
+ }
+
+ unlistenersRef.current = unlisteners;
+ setActiveListeners(MONITORED_EVENTS);
+ };
+
+ setupListeners();
+
+ return () => {
+ unlistenersRef.current.forEach(unlisten => unlisten());
+ };
+ }, [isPaused, maxLogs]);
+
+ // Update WebSocket connections info based on event activity
+ useEffect(() => {
+ const updateConnections = () => {
+ const connections: WebSocketConnection[] = [];
+
+ // Infer stock broker connections from event activity
+ const stockEvents = Array.from(eventStats.values()).filter(s => s.source === 'stock');
+ if (stockEvents.length > 0) {
+ const recentActivity = stockEvents.some(e => Date.now() - e.lastReceived < 30000); // Active in last 30s
+ const totalStockTicks = stockEvents.reduce((sum, s) => sum + s.count, 0);
+
+ // Group by broker type (inferred from event name)
+ const brokerGroups = new Map<string, EventStats[]>();
+ stockEvents.forEach(event => {
+ const brokerName = event.eventName.split('_')[0]; // e.g., 'zerodha' from 'zerodha_ticker'
+ if (!brokerGroups.has(brokerName)) {
+ brokerGroups.set(brokerName, []);
+ }
+ brokerGroups.get(brokerName)!.push(event);
+ });
+
+ brokerGroups.forEach((events, brokerName) => {
+ const isActive = events.some(e => Date.now() - e.lastReceived < 30000);
+ const totalTicks = events.reduce((sum, e) => sum + e.count, 0);
+
+ connections.push({
+ id: `stock-${brokerName}`,
+ broker: brokerName.charAt(0).toUpperCase() + brokerName.slice(1),
+ type: 'stock',
+ status: isActive ? 'connected' : 'disconnected',
+ subscribedSymbols: [],
+ lastActivity: Math.max(...events.map(e => e.lastReceived)),
+ totalTicks,
+ });
+ });
+ }
+
+ // Infer crypto broker connections from event activity
+ const cryptoEvents = Array.from(eventStats.values()).filter(s => s.source === 'crypto');
+ if (cryptoEvents.length > 0) {
+ const brokerGroups = new Map<string, EventStats[]>();
+ cryptoEvents.forEach(event => {
+ const brokerName = event.eventName.split('_')[0]; // e.g., 'binance' from 'binance_ticker'
+ if (!brokerGroups.has(brokerName)) {
+ brokerGroups.set(brokerName, []);
+ }
+ brokerGroups.get(brokerName)!.push(event);
+ });
+
+ brokerGroups.forEach((events, brokerName) => {
+ const isActive = events.some(e => Date.now() - e.lastReceived < 30000);
+ const totalTicks = events.reduce((sum, e) => sum + e.count, 0);
+
+ connections.push({
+ id: `crypto-${brokerName}`,
+ broker: brokerName.charAt(0).toUpperCase() + brokerName.slice(1),
+ type: 'crypto',
+ status: isActive ? 'connected' : 'disconnected',
+ subscribedSymbols: [],
+ lastActivity: Math.max(...events.map(e => e.lastReceived)),
+ totalTicks,
+ });
+ });
+ }
+
+ setWsConnections(connections);
+ };
+
+ updateConnections();
+ const interval = setInterval(updateConnections, 2000);
+ statsIntervalRef.current = interval;
+
+ return () => {
+ if (statsIntervalRef.current) {
+ clearInterval(statsIntervalRef.current);
+ }
+ };
+ }, [eventStats]);
+
+ // Format timestamp
+ const formatTime = (timestamp: number) => {
+ const date = new Date(timestamp);
+ const ms = String(date.getMilliseconds()).padStart(3, '0');
+ return date.toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' }) + `.${ms}`;
+ };
+
+ // Clear logs
+ const clearLogs = () => {
+ setEventLogs([]);
+ setEventStats(new Map());
+ };
+
+ // Filter logs
+ const filteredLogs = filterSource === 'all'
+ ? eventLogs
+ : eventLogs.filter(log => log.source === filterSource);
+
+ const filteredStats = Array.from(eventStats.values())
+ .filter(stat => filterSource === 'all' || stat.source === filterSource)
+ .sort((a, b) => b.count - a.count);
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ display: 'flex',
+ flexDirection: 'column',
+ fontFamily: 'Consolas, "Courier New", monospace',
+ fontSize: '11px',
+ }}>
+ {/* Header */}
+ <div style={{
+ padding: '12px 16px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <Activity size={16} color={FINCEPT.ORANGE} />
+ <span style={{ fontSize: '13px', fontWeight: 'bold' }}>Tauri Events Monitor</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginLeft: '8px' }}>
+ <Circle size={8} color={FINCEPT.GREEN} fill={FINCEPT.GREEN} />
+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY }}>
+ {activeListeners.length} listeners active
+ </span>
+ </div>
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ {/* Filter */}
+ <select
+ value={filterSource}
+ onChange={(e) => setFilterSource(e.target.value as any)}
+ style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ padding: '4px 8px',
+ fontSize: '10px',
+ }}
+ >
+ <option value="all">All Sources</option>
+ <option value="stock">Stock Brokers</option>
+ <option value="crypto">Crypto Exchanges</option>
+ <option value="system">System Events</option>
+ </select>
+
+ {/* Toggle payload */}
+ <button
+ onClick={() => setShowPayload(!showPayload)}
+ style={{
+ backgroundColor: showPayload ? FINCEPT.ORANGE : FINCEPT.PANEL_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ padding: '4px 8px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ }}
+ >
+ {showPayload ? <Eye size={12} /> : <EyeOff size={12} />}
+ <span>Payload</span>
+ </button>
+
+ {/* Pause/Resume */}
+ <button
+ onClick={() => setIsPaused(!isPaused)}
+ style={{
+ backgroundColor: isPaused ? FINCEPT.RED : FINCEPT.GREEN,
+ color: FINCEPT.WHITE,
+ border: 'none',
+ borderRadius: '3px',
+ padding: '4px 12px',
+ cursor: 'pointer',
+ fontWeight: 'bold',
+ }}
+ >
+ {isPaused ? 'PAUSED' : 'LIVE'}
+ </button>
+
+ {/* Clear */}
+ <button
+ onClick={clearLogs}
+ style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ padding: '4px 8px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ }}
+ >
+ <Trash2 size={12} />
+ <span>Clear</span>
+ </button>
+ </div>
+ </div>
+
+ {/* Main Content */}
+ <div style={{ flex: 1, display: 'flex', gap: '8px', padding: '8px', overflow: 'hidden' }}>
+ {/* Left Panel - WebSocket Connections & Stats */}
+ <div style={{ width: '400px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ {/* WebSocket Connections */}
+ <div style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '4px',
+ padding: '12px',
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ <Wifi size={14} color={FINCEPT.CYAN} />
+ <span style={{ fontWeight: 'bold' }}>WebSocket Connections</span>
+ </div>
+
+ {wsConnections.length === 0 ? (
+ <div style={{ color: FINCEPT.GRAY, textAlign: 'center', padding: '20px' }}>
+ No active WebSocket connections
+ </div>
+ ) : (
+ wsConnections.map(conn => (
+ <div
+ key={conn.id}
+ style={{
+ padding: '8px',
+ marginBottom: '8px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <Circle
+ size={8}
+ color={conn.status === 'connected' ? FINCEPT.GREEN : FINCEPT.RED}
+ fill={conn.status === 'connected' ? FINCEPT.GREEN : FINCEPT.RED}
+ />
+ <span style={{ fontWeight: 'bold' }}>{conn.broker}</span>
+ </div>
+ <span style={{
+ fontSize: '9px',
+ color: FINCEPT.WHITE,
+ backgroundColor: conn.type === 'stock' ? FINCEPT.CYAN : FINCEPT.ORANGE,
+ padding: '2px 6px',
+ borderRadius: '2px',
+ }}>
+ {conn.type.toUpperCase()}
+ </span>
+ </div>
+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>
+ <div>Status: <span style={{ color: conn.status === 'connected' ? FINCEPT.GREEN : FINCEPT.RED }}>
+ {conn.status.toUpperCase()}
+ </span></div>
+ <div>Total Ticks: <span style={{ color: FINCEPT.WHITE }}>{conn.totalTicks.toLocaleString()}</span></div>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+
+ {/* Event Statistics */}
+ <div style={{
+ flex: 1,
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '4px',
+ padding: '12px',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ <TrendingUp size={14} color={FINCEPT.YELLOW} />
+ <span style={{ fontWeight: 'bold' }}>Event Statistics</span>
+ </div>
+
+ <div style={{ flex: 1, overflowY: 'auto' }}>
+ {filteredStats.length === 0 ? (
+ <div style={{ color: FINCEPT.GRAY, textAlign: 'center', padding: '20px' }}>
+ No events received yet
+ </div>
+ ) : (
+ filteredStats.map(stat => (
+ <div
+ key={stat.eventName}
+ style={{
+ padding: '8px',
+ marginBottom: '6px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ }}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
+ <span style={{
+ fontWeight: 'bold',
+ color: stat.source === 'stock' ? FINCEPT.CYAN :
+ stat.source === 'crypto' ? FINCEPT.ORANGE : FINCEPT.YELLOW
+ }}>
+ {stat.eventName}
+ </span>
+ <span style={{ color: FINCEPT.WHITE }}>{stat.count}</span>
+ </div>
+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>
+ Avg: {stat.avgFrequency.toFixed(2)} events/s | Last: {formatTime(stat.lastReceived)}
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Right Panel - Event Logs */}
+ <div style={{
+ flex: 1,
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '4px',
+ padding: '12px',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <Database size={14} color={FINCEPT.GREEN} />
+ <span style={{ fontWeight: 'bold' }}>Event Stream</span>
+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY }}>
+ ({filteredLogs.length} / {maxLogs} max)
+ </span>
+ </div>
+ </div>
+
+ <div style={{
+ flex: 1,
+ overflowY: 'auto',
+ fontFamily: 'Consolas, "Courier New", monospace',
+ fontSize: '10px',
+ }}>
+ {filteredLogs.length === 0 ? (
+ <div style={{ color: FINCEPT.GRAY, textAlign: 'center', padding: '20px' }}>
+ {isPaused ? 'Monitoring paused' : 'Waiting for events...'}
+ </div>
+ ) : (
+ filteredLogs.map(log => (
+ <div
+ key={log.id}
+ style={{
+ padding: '8px',
+ marginBottom: '4px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '3px',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
+ <Clock size={10} color={FINCEPT.GRAY} />
+ <span style={{ color: FINCEPT.GRAY }}>{formatTime(log.timestamp)}</span>
+ <Zap size={10} color={
+ log.source === 'stock' ? FINCEPT.CYAN :
+ log.source === 'crypto' ? FINCEPT.ORANGE : FINCEPT.YELLOW
+ } />
+ <span style={{
+ fontWeight: 'bold',
+ color: log.source === 'stock' ? FINCEPT.CYAN :
+ log.source === 'crypto' ? FINCEPT.ORANGE : FINCEPT.YELLOW
+ }}>
+ {log.eventName}
+ </span>
+ </div>
+
+ {showPayload && (
+ <pre style={{
+ margin: 0,
+ padding: '8px',
+ backgroundColor: '#000',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ color: FINCEPT.GRAY,
+ maxHeight: '200px',
+ overflow: 'auto',
+ }}>
+ {JSON.stringify(log.payload, null, 2)}
+ </pre>
+ )}
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/tauri-events-monitor/index.tsx b/fincept-terminal-desktop/src/components/tabs/tauri-events-monitor/index.tsx
new file mode 100644
index 000000000..8b71059a2
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/tauri-events-monitor/index.tsx
@@ -0,0 +1 @@
+export { default } from './TauriEventsMonitorTab';
diff --git a/fincept-terminal-desktop/src/constants/version.ts b/fincept-terminal-desktop/src/constants/version.ts
index 8624ed6d6..96dc83a12 100644
--- a/fincept-terminal-desktop/src/constants/version.ts
+++ b/fincept-terminal-desktop/src/constants/version.ts
@@ -6,7 +6,7 @@
// Run `bun run sync-version` to sync from package.json
// Or edit package.json and run build/dev to auto-sync
-export const APP_VERSION = '3.2.1';
+export const APP_VERSION = '3.3.0';
export const APP_NAME = 'Fincept Terminal';
export const APP_BUILD_DATE = new Date().toISOString().split('T')[0];
diff --git a/fincept-terminal-desktop/src/services/agentService.ts b/fincept-terminal-desktop/src/services/agentService.ts
index ae48de5c5..22b963f1f 100644
--- a/fincept-terminal-desktop/src/services/agentService.ts
+++ b/fincept-terminal-desktop/src/services/agentService.ts
@@ -1198,4 +1198,111 @@ export const agentService = {
buildTeamConfig,
};
+// =============================================================================
+// Renaissance Technologies Integration
+// =============================================================================
+
+export interface RenTechSignal {
+ ticker: string;
+ signal_type: string;
+ direction: 'long' | 'short';
+ strength: number;
+ confidence: number;
+ p_value: number;
+ information_coefficient: number;
+}
+
+export interface RenTechConfig {
+ max_position_size_pct?: number;
+ max_leverage?: number;
+ max_drawdown_pct?: number;
+ max_daily_var_pct?: number;
+ min_signal_confidence?: number;
+}
+
+export interface RenTechResult {
+ success: boolean;
+ signal_id?: string;
+ statistical_quality?: string;
+ risk_assessment?: string;
+ ic_decision?: any;
+ execution_plan?: any;
+ error?: string;
+}
+
+/**
+ * Run Renaissance Technologies signal analysis
+ */
+export async function runRenaissanceTechnologies(
+ signal: RenTechSignal,
+ config?: RenTechConfig
+): Promise<RenTechResult> {
+ try {
+ const result = await invoke<string>('execute_python_agent', {
+ agentType: 'renaissance',
+ parameters: config || {},
+ inputs: { signal, config },
+ });
+
+ const parsed = JSON.parse(result);
+ return parsed.data || parsed;
+ } catch (error: any) {
+ console.error('[RenTech] Analysis failed:', error);
+ return {
+ success: false,
+ error: error.message || 'Renaissance Technologies analysis failed',
+ };
+ }
+}
+
+/**
+ * Run IC Deliberation on a signal
+ */
+export async function runICDeliberation(deliberationData: {
+ signal: any;
+ signal_evaluation: any;
+ risk_assessment: any;
+ sizing_recommendation: any;
+}): Promise<RenTechResult> {
+ try {
+ const jsonData = JSON.stringify(deliberationData);
+ const result = await invoke<string>('execute_python_agent', {
+ agentType: 'renaissance',
+ parameters: {},
+ inputs: { command: 'run_ic_deliberation', data: deliberationData },
+ });
+
+ const parsed = JSON.parse(result);
+ return { success: true, ic_decision: parsed.data };
+ } catch (error: any) {
+ console.error('[RenTech] IC deliberation failed:', error);
+ return {
+ success: false,
+ error: error.message || 'IC deliberation failed',
+ };
+ }
+}
+
+/**
+ * Get Renaissance Technologies agent presets
+ */
+export async function getRenTechPresets(): Promise<{
+ agents: any[];
+ teams: any[];
+}> {
+ try {
+ const result = await invoke<string>('execute_python_agent', {
+ agentType: 'renaissance',
+ parameters: {},
+ inputs: { command: 'list_agent_presets' },
+ });
+
+ const parsed = JSON.parse(result);
+ return parsed.data || { agents: [], teams: [] };
+ } catch (error) {
+ console.error('[RenTech] Failed to get presets:', error);
+ return { agents: [], teams: [] };
+ }
+}
+
export default agentService;
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/NewsMCPBridge.ts b/fincept-terminal-desktop/src/services/mcp/internal/NewsMCPBridge.ts
new file mode 100644
index 000000000..6704bf9df
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/NewsMCPBridge.ts
@@ -0,0 +1,308 @@
+// News MCP Bridge - Connects news services to MCP Internal Tools
+// Exposes complete news functionality to AI via chat
+
+import { terminalMCPProvider } from './TerminalMCPProvider';
+import {
+ fetchAllNews,
+ getActiveSources,
+ getRSSFeedCount,
+ getNewsCacheStats,
+} from '@/services/news/newsService';
+import {
+ getUserRSSFeeds,
+ getDefaultFeeds,
+ getAllRSSFeeds,
+ addUserRSSFeed,
+ updateUserRSSFeed,
+ deleteUserRSSFeed,
+ toggleUserRSSFeed,
+ toggleDefaultRSSFeed,
+ deleteDefaultRSSFeed,
+ restoreDefaultRSSFeed,
+ restoreAllDefaultFeeds,
+ testRSSFeedUrl,
+ RSS_CATEGORIES,
+ RSS_REGIONS,
+} from '@/services/news/rssFeedService';
+import { analyzeNewsArticle } from '@/services/news/newsAnalysisService';
+import type { NewsArticleInfo, NewsSentimentStats } from './types';
+
+/**
+ * Bridge that connects news services to MCP tools
+ * Allows AI to fetch, filter, manage, and analyze news via chat
+ */
+export class NewsMCPBridge {
+ private connected: boolean = false;
+ private cachedArticles: NewsArticleInfo[] = [];
+
+ /**
+ * Connect news services to MCP contexts
+ */
+ connect(): void {
+ if (this.connected) return;
+
+ terminalMCPProvider.setContexts({
+ // ==================== NEWS FETCHING ====================
+
+ fetchAllNews: async (forceRefresh?: boolean) => {
+ const articles = await fetchAllNews(forceRefresh || false);
+ this.cachedArticles = articles as NewsArticleInfo[];
+ return this.cachedArticles;
+ },
+
+ getNewsByCategory: async (category: string) => {
+ // Ensure we have fresh data
+ if (this.cachedArticles.length === 0) {
+ this.cachedArticles = (await fetchAllNews(false)) as NewsArticleInfo[];
+ }
+ return this.cachedArticles.filter(
+ (a) => a.category.toUpperCase() === category.toUpperCase()
+ );
+ },
+
+ getNewsBySource: async (source: string) => {
+ if (this.cachedArticles.length === 0) {
+ this.cachedArticles = (await fetchAllNews(false)) as NewsArticleInfo[];
+ }
+ return this.cachedArticles.filter(
+ (a) => a.source.toUpperCase().includes(source.toUpperCase())
+ );
+ },
+
+ searchNews: async (query: string) => {
+ if (this.cachedArticles.length === 0) {
+ this.cachedArticles = (await fetchAllNews(false)) as NewsArticleInfo[];
+ }
+ const q = query.toLowerCase();
+ return this.cachedArticles.filter(
+ (a) =>
+ a.headline.toLowerCase().includes(q) ||
+ a.summary.toLowerCase().includes(q) ||
+ a.source.toLowerCase().includes(q) ||
+ (a.tickers && a.tickers.some((t) => t.toLowerCase().includes(q)))
+ );
+ },
+
+ getBreakingNews: async () => {
+ if (this.cachedArticles.length === 0) {
+ this.cachedArticles = (await fetchAllNews(false)) as NewsArticleInfo[];
+ }
+ return this.cachedArticles.filter(
+ (a) => a.priority === 'FLASH' || a.priority === 'URGENT'
+ );
+ },
+
+ getNewsBySentiment: async (sentiment: 'BULLISH' | 'BEARISH' | 'NEUTRAL') => {
+ if (this.cachedArticles.length === 0) {
+ this.cachedArticles = (await fetchAllNews(false)) as NewsArticleInfo[];
+ }
+ return this.cachedArticles.filter(
+ (a) => a.sentiment.toUpperCase() === sentiment.toUpperCase()
+ );
+ },
+
+ getNewsByPriority: async (priority: 'FLASH' | 'URGENT' | 'BREAKING' | 'ROUTINE') => {
+ if (this.cachedArticles.length === 0) {
+ this.cachedArticles = (await fetchAllNews(false)) as NewsArticleInfo[];
+ }
+ return this.cachedArticles.filter(
+ (a) => a.priority.toUpperCase() === priority.toUpperCase()
+ );
+ },
+
+ getNewsByTicker: async (ticker: string) => {
+ if (this.cachedArticles.length === 0) {
+ this.cachedArticles = (await fetchAllNews(false)) as NewsArticleInfo[];
+ }
+ const t = ticker.toUpperCase();
+ return this.cachedArticles.filter(
+ (a) => a.tickers && a.tickers.some((tk) => tk.toUpperCase() === t)
+ );
+ },
+
+ // ==================== PROVIDERS / SOURCES ====================
+
+ getActiveSources: async () => {
+ return await getActiveSources();
+ },
+
+ getRSSFeedCount: async () => {
+ return await getRSSFeedCount();
+ },
+
+ getUserRSSFeeds: async () => {
+ return await getUserRSSFeeds();
+ },
+
+ getDefaultFeeds: async () => {
+ return await getDefaultFeeds();
+ },
+
+ getAllRSSFeeds: async () => {
+ return await getAllRSSFeeds();
+ },
+
+ // ==================== FEED MANAGEMENT ====================
+
+ addUserRSSFeed: async (params) => {
+ return await addUserRSSFeed(params);
+ },
+
+ updateUserRSSFeed: async (id, params) => {
+ await updateUserRSSFeed(id, params);
+ },
+
+ deleteUserRSSFeed: async (id) => {
+ await deleteUserRSSFeed(id);
+ },
+
+ toggleUserRSSFeed: async (id, enabled) => {
+ await toggleUserRSSFeed(id, enabled);
+ },
+
+ toggleDefaultRSSFeed: async (feedId, enabled) => {
+ await toggleDefaultRSSFeed(feedId, enabled);
+ },
+
+ deleteDefaultRSSFeed: async (feedId) => {
+ await deleteDefaultRSSFeed(feedId);
+ },
+
+ restoreDefaultRSSFeed: async (feedId) => {
+ await restoreDefaultRSSFeed(feedId);
+ },
+
+ restoreAllDefaultFeeds: async () => {
+ await restoreAllDefaultFeeds();
+ },
+
+ testRSSFeedUrl: async (url) => {
+ return await testRSSFeedUrl(url);
+ },
+
+ // ==================== ANALYSIS ====================
+
+ analyzeNewsArticle: async (url: string) => {
+ const result = await analyzeNewsArticle(url);
+ if ('error' in result) {
+ return {
+ success: false,
+ error: result.error,
+ };
+ }
+ return {
+ success: result.success,
+ data: result.data,
+ };
+ },
+
+ // ==================== STATISTICS ====================
+
+ getNewsSentimentStats: async (): Promise<NewsSentimentStats> => {
+ if (this.cachedArticles.length === 0) {
+ this.cachedArticles = (await fetchAllNews(false)) as NewsArticleInfo[];
+ }
+ const articles = this.cachedArticles;
+ const bullish = articles.filter((a) => a.sentiment === 'BULLISH').length;
+ const bearish = articles.filter((a) => a.sentiment === 'BEARISH').length;
+ const neutral = articles.filter((a) => a.sentiment === 'NEUTRAL').length;
+ const total = articles.length || 1;
+ const alertCount = articles.filter(
+ (a) => a.priority === 'FLASH' || a.priority === 'URGENT'
+ ).length;
+ const netScore = (bullish - bearish) / total;
+
+ return {
+ bullish,
+ bearish,
+ neutral,
+ total: articles.length,
+ netScore,
+ alertCount,
+ };
+ },
+
+ getNewsCacheStats: async () => {
+ return await getNewsCacheStats();
+ },
+
+ getAvailableCategories: () => {
+ return [...RSS_CATEGORIES];
+ },
+
+ getAvailableRegions: () => {
+ return [...RSS_REGIONS];
+ },
+ });
+
+ this.connected = true;
+ console.log('[NewsMCPBridge] Connected news services to MCP');
+ }
+
+ /**
+ * Disconnect and clear contexts
+ */
+ disconnect(): void {
+ if (!this.connected) return;
+
+ terminalMCPProvider.setContexts({
+ // News fetching
+ fetchAllNews: undefined,
+ getNewsByCategory: undefined,
+ getNewsBySource: undefined,
+ searchNews: undefined,
+ getBreakingNews: undefined,
+ getNewsBySentiment: undefined,
+ getNewsByPriority: undefined,
+ getNewsByTicker: undefined,
+
+ // Providers / Sources
+ getActiveSources: undefined,
+ getRSSFeedCount: undefined,
+ getUserRSSFeeds: undefined,
+ getDefaultFeeds: undefined,
+ getAllRSSFeeds: undefined,
+
+ // Feed management
+ addUserRSSFeed: undefined,
+ updateUserRSSFeed: undefined,
+ deleteUserRSSFeed: undefined,
+ toggleUserRSSFeed: undefined,
+ toggleDefaultRSSFeed: undefined,
+ deleteDefaultRSSFeed: undefined,
+ restoreDefaultRSSFeed: undefined,
+ restoreAllDefaultFeeds: undefined,
+ testRSSFeedUrl: undefined,
+
+ // Analysis
+ analyzeNewsArticle: undefined,
+
+ // Statistics
+ getNewsSentimentStats: undefined,
+ getNewsCacheStats: undefined,
+ getAvailableCategories: undefined,
+ getAvailableRegions: undefined,
+ });
+
+ this.cachedArticles = [];
+ this.connected = false;
+ console.log('[NewsMCPBridge] Disconnected news services from MCP');
+ }
+
+ /**
+ * Check if bridge is connected
+ */
+ isConnected(): boolean {
+ return this.connected;
+ }
+
+ /**
+ * Clear cached articles (useful when news is refreshed elsewhere)
+ */
+ clearCache(): void {
+ this.cachedArticles = [];
+ }
+}
+
+// Singleton instance
+export const newsMCPBridge = new NewsMCPBridge();
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/NodeEditorMCPBridge.ts b/fincept-terminal-desktop/src/services/mcp/internal/NodeEditorMCPBridge.ts
index 62ed22739..f4465ef6d 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/NodeEditorMCPBridge.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/NodeEditorMCPBridge.ts
@@ -20,6 +20,10 @@ import {
WorkflowExecutionResult,
WorkflowValidation,
NodePropertyInfo,
+ DisconnectNodesParams,
+ MoveNodeParams,
+ AutoLayoutParams,
+ WorkflowStats,
} from './types';
import { NodeRegistry } from '@/services/nodeSystem/NodeRegistry';
import { NodeLoader, initializeNodeSystem } from '@/services/nodeSystem/NodeLoader';
@@ -208,6 +212,16 @@ class NodeEditorMCPBridgeClass {
openWorkflowInEditor: this.openWorkflowInEditor.bind(this),
exportNodeWorkflow: this.exportNodeWorkflow.bind(this),
importNodeWorkflow: this.importNodeWorkflow.bind(this),
+
+ // Quick Edit Operations
+ removeNodeFromWorkflow: this.removeNodeFromWorkflow.bind(this),
+ disconnectNodes: this.disconnectNodes.bind(this),
+ renameNode: this.renameNode.bind(this),
+ clearWorkflow: this.clearWorkflow.bind(this),
+ cloneNode: this.cloneNode.bind(this),
+ moveNode: this.moveNode.bind(this),
+ getWorkflowStats: this.getWorkflowStats.bind(this),
+ autoLayoutWorkflow: this.autoLayoutWorkflow.bind(this),
};
terminalMCPProvider.setContexts(contexts);
@@ -457,68 +471,81 @@ class NodeEditorMCPBridgeClass {
/**
* Map backend node types to UI component types
* This is critical for proper rendering in ReactFlow
+ *
+ * NOTE: We use 'custom' for most MCP-created nodes because:
+ * - 'system' type expects INode data structure from n8n node system
+ * - 'data-source' type expects callback functions (onConnectionChange, etc.)
+ * - 'custom' type works with simple data (label, color, nodeType, hasInput, hasOutput)
*/
private mapToUINodeType(backendType: string): string {
- // Trigger nodes
+ // Trigger nodes - use 'custom' instead of 'system' because SystemNode
+ // expects data.node with INode structure from n8n node system
if (backendType.includes('Trigger') || backendType === 'manual') {
- return 'system';
+ return 'custom';
}
- // Data source nodes
+ // Data source nodes - use 'custom' instead of 'data-source' because
+ // DataSourceNode expects callback functions (onConnectionChange, onQueryChange, etc.)
const dataSourceNodes = [
'yfinance', 'getQuote', 'getHistoricalData', 'getMarketDepth',
'streamQuotes', 'getFundamentals', 'getTickerStats', 'stockData'
];
if (dataSourceNodes.includes(backendType)) {
- return 'data-source';
+ return 'custom';
}
- // Technical indicator nodes
+ // Technical indicator nodes - use 'custom' for same reason
if (backendType === 'technicalIndicators' || backendType.includes('indicator')) {
- return 'technical-indicator';
+ return 'custom';
}
- // Agent nodes
+ // Agent nodes - these can stay as agent-mediator if they work
const agentNodes = [
'agentMediator', 'agent', 'multiAgent', 'geopoliticsAgent',
'hedgeFundAgent', 'investorAgent'
];
if (agentNodes.includes(backendType)) {
- return 'agent-mediator';
+ return 'custom'; // Use custom for simplicity in MCP-created workflows
}
- // Results display
+ // Results display - this one works with simple data
if (backendType === 'resultsDisplay' || backendType === 'results-display') {
return 'results-display';
}
- // Backtest nodes
+ // Backtest nodes - use custom
if (backendType === 'backtestEngine' || backendType === 'backtest') {
- return 'backtest';
+ return 'custom';
}
- // Optimization nodes
+ // Optimization nodes - use custom
if (backendType === 'portfolioOptimization' || backendType === 'optimization') {
- return 'optimization';
+ return 'custom';
}
- // If it's already a UI type, return as-is
- const uiTypes = [
- 'data-source', 'technical-indicator', 'agent-mediator',
- 'results-display', 'backtest', 'optimization', 'system',
- 'custom', 'mcp-tool', 'python-agent'
- ];
- if (uiTypes.includes(backendType)) {
+ // If it's already a UI type that's safe to use, return as-is
+ // Only results-display is safe without callbacks
+ const safeUiTypes = ['results-display', 'custom'];
+ if (safeUiTypes.includes(backendType)) {
return backendType;
}
- // Default to custom for everything else
+ // Default to custom for everything else - it's the most flexible
return 'custom';
}
/**
* Create proper ReactFlow node data structure for any node type
- * Returns BaseNodeData compatible structure
+ * Returns data compatible with CustomNode (the most flexible node type)
+ *
+ * CustomNode expects:
+ * - label: string
+ * - color: string
+ * - nodeType: string
+ * - hasInput: boolean
+ * - hasOutput: boolean
+ * - status?: string
+ * - onLabelChange?: function (optional)
*/
private createNodeData(
nodeType: string,
@@ -529,48 +556,41 @@ class NodeEditorMCPBridgeClass {
const uiType = this.mapToUINodeType(nodeType);
const color = parameters.color || this.getNodeColor(backendType || nodeType);
- // Determine input/output based on node type
- const hasInput = !['system', 'trigger'].includes(uiType) &&
- !nodeType.includes('Trigger') &&
- !backendType?.includes('Trigger');
- const hasOutput = uiType !== 'results-display';
+ // Determine input/output based on backend type (triggers have no input)
+ const isTrigger = (backendType || nodeType || '').toLowerCase().includes('trigger') ||
+ backendType === 'manual' ||
+ backendType === 'manualTrigger';
+ const isResultsDisplay = uiType === 'results-display' ||
+ backendType === 'resultsDisplay';
- // Build base node data that satisfies BaseNodeData interface
- const baseData: BaseNodeData = {
- label: label || backendType || nodeType || 'Node',
- status: 'idle',
- onLabelChange: () => {},
- };
+ const hasInput = !isTrigger;
+ const hasOutput = !isResultsDisplay;
- // Add extra properties based on node type
- // These properties are used by the ReactFlow UI components
- const extendedData = {
- ...baseData,
+ // Build node data compatible with CustomNode
+ // CustomNode is the most flexible and doesn't require callbacks
+ const nodeData = {
+ // Required by CustomNode
+ label: label || backendType || nodeType || 'Node',
color: color,
- nodeType: backendType || nodeType,
+ nodeType: backendType || nodeType || 'custom',
hasInput: hasInput,
hasOutput: hasOutput,
+ status: parameters.status || 'idle',
+
+ // Optional - these will be ignored if not used
+ onLabelChange: undefined as ((nodeId: string, newLabel: string) => void) | undefined,
+
+ // Spread any additional parameters (symbol, operation, etc.)
...parameters,
};
- // Return as proper type based on UI node type
- switch (uiType) {
- case 'data-source':
- return extendedData as DataSourceNodeData;
- case 'technical-indicator':
- return extendedData as TechnicalIndicatorNodeData;
- case 'python-agent':
- return extendedData as PythonAgentNodeData;
- case 'mcp-tool':
- return extendedData as MCPToolNodeData;
- case 'results-display':
- return extendedData as ResultsDisplayNodeData;
- case 'agent-mediator':
- return extendedData as AgentMediatorNodeData;
- default:
- // For custom/system/other types, return as BaseNodeData with extras
- return extendedData as DataSourceNodeData; // DataSourceNodeData is a good default
+ // Remove undefined onLabelChange to keep data clean
+ if (nodeData.onLabelChange === undefined) {
+ delete (nodeData as any).onLabelChange;
}
+
+ // Return as BaseNodeData which CustomNode accepts
+ return nodeData as BaseNodeData;
}
async addNodeToWorkflow(params: AddNodeParams): Promise<WorkflowInfo> {
@@ -921,6 +941,304 @@ class NodeEditorMCPBridgeClass {
});
}
+ // ============================================================================
+ // QUICK EDIT OPERATIONS
+ // ============================================================================
+
+ async removeNodeFromWorkflow(workflowId: string, nodeId: string): Promise<WorkflowInfo> {
+ const workflow = await workflowService.loadWorkflow(workflowId);
+ if (!workflow) {
+ throw new Error(`Workflow '${workflowId}' not found`);
+ }
+
+ // Remove the node
+ workflow.nodes = (workflow.nodes || []).filter(n => n.id !== nodeId);
+
+ // Remove all edges connected to this node
+ workflow.edges = (workflow.edges || []).filter(
+ e => e.source !== nodeId && e.target !== nodeId
+ );
+
+ workflow.updatedAt = new Date().toISOString();
+ await workflowService.saveWorkflow(workflow);
+
+ return this.workflowToInfo(workflow);
+ }
+
+ async disconnectNodes(params: DisconnectNodesParams): Promise<WorkflowInfo> {
+ const workflow = await workflowService.loadWorkflow(params.workflowId);
+ if (!workflow) {
+ throw new Error(`Workflow '${params.workflowId}' not found`);
+ }
+
+ // Remove matching edge(s)
+ workflow.edges = (workflow.edges || []).filter(e => {
+ const isMatch = e.source === params.sourceNodeId && e.target === params.targetNodeId;
+ // If sourceHandle is specified, also check that
+ if (isMatch && params.sourceHandle) {
+ return e.sourceHandle !== params.sourceHandle;
+ }
+ return !isMatch;
+ });
+
+ workflow.updatedAt = new Date().toISOString();
+ await workflowService.saveWorkflow(workflow);
+
+ return this.workflowToInfo(workflow);
+ }
+
+ async renameNode(workflowId: string, nodeId: string, newLabel: string): Promise<WorkflowInfo> {
+ const workflow = await workflowService.loadWorkflow(workflowId);
+ if (!workflow) {
+ throw new Error(`Workflow '${workflowId}' not found`);
+ }
+
+ const node = (workflow.nodes || []).find(n => n.id === nodeId);
+ if (!node) {
+ throw new Error(`Node '${nodeId}' not found in workflow`);
+ }
+
+ // Update the label in node data
+ if (node.data) {
+ node.data.label = newLabel;
+ }
+
+ workflow.updatedAt = new Date().toISOString();
+ await workflowService.saveWorkflow(workflow);
+
+ return this.workflowToInfo(workflow);
+ }
+
+ async clearWorkflow(workflowId: string): Promise<WorkflowInfo> {
+ const workflow = await workflowService.loadWorkflow(workflowId);
+ if (!workflow) {
+ throw new Error(`Workflow '${workflowId}' not found`);
+ }
+
+ // Clear all nodes and edges
+ workflow.nodes = [];
+ workflow.edges = [];
+ workflow.status = 'draft';
+ workflow.updatedAt = new Date().toISOString();
+
+ await workflowService.saveWorkflow(workflow);
+
+ return this.workflowToInfo(workflow);
+ }
+
+ async cloneNode(
+ workflowId: string,
+ nodeId: string,
+ newLabel?: string
+ ): Promise<{ workflow: WorkflowInfo; newNodeId: string }> {
+ const workflow = await workflowService.loadWorkflow(workflowId);
+ if (!workflow) {
+ throw new Error(`Workflow '${workflowId}' not found`);
+ }
+
+ const originalNode = (workflow.nodes || []).find(n => n.id === nodeId);
+ if (!originalNode) {
+ throw new Error(`Node '${nodeId}' not found in workflow`);
+ }
+
+ // Generate new node ID
+ const newNodeId = `${nodeId}_clone_${Date.now()}`;
+
+ // Clone the node with new position (offset to the right)
+ const clonedNode: WorkflowNode = {
+ ...originalNode,
+ id: newNodeId,
+ position: {
+ x: originalNode.position.x + 50,
+ y: originalNode.position.y + 50,
+ },
+ data: {
+ ...originalNode.data,
+ label: newLabel || `Copy of ${originalNode.data?.label || nodeId}`,
+ },
+ };
+
+ workflow.nodes.push(clonedNode);
+ workflow.updatedAt = new Date().toISOString();
+
+ await workflowService.saveWorkflow(workflow);
+
+ return {
+ workflow: this.workflowToInfo(workflow),
+ newNodeId,
+ };
+ }
+
+ async moveNode(params: MoveNodeParams): Promise<{ workflow: WorkflowInfo; newPosition: { x: number; y: number } }> {
+ const workflow = await workflowService.loadWorkflow(params.workflowId);
+ if (!workflow) {
+ throw new Error(`Workflow '${params.workflowId}' not found`);
+ }
+
+ const node = (workflow.nodes || []).find(n => n.id === params.nodeId);
+ if (!node) {
+ throw new Error(`Node '${params.nodeId}' not found in workflow`);
+ }
+
+ let newX = node.position.x;
+ let newY = node.position.y;
+ const moveOffset = 50;
+
+ // Handle direction-based movement
+ if (params.direction) {
+ switch (params.direction) {
+ case 'up': newY -= moveOffset; break;
+ case 'down': newY += moveOffset; break;
+ case 'left': newX -= moveOffset; break;
+ case 'right': newX += moveOffset; break;
+ }
+ } else if (params.x !== undefined || params.y !== undefined) {
+ // Handle coordinate-based movement
+ if (params.relative) {
+ newX += params.x || 0;
+ newY += params.y || 0;
+ } else {
+ newX = params.x ?? newX;
+ newY = params.y ?? newY;
+ }
+ }
+
+ node.position = { x: newX, y: newY };
+ workflow.updatedAt = new Date().toISOString();
+ await workflowService.saveWorkflow(workflow);
+
+ return {
+ workflow: this.workflowToInfo(workflow),
+ newPosition: { x: newX, y: newY },
+ };
+ }
+
+ async getWorkflowStats(workflowId: string): Promise<WorkflowStats> {
+ const workflow = await workflowService.loadWorkflow(workflowId);
+ if (!workflow) {
+ throw new Error(`Workflow '${workflowId}' not found`);
+ }
+
+ // Derive stats from current workflow state
+ // In a full implementation, this would query execution history from database
+ const isCompleted = workflow.status === 'completed';
+ const isError = workflow.status === 'error';
+ const isRunning = workflow.status === 'running';
+ const hasRun = isCompleted || isError;
+
+ // Count nodes and edges as a proxy for complexity
+ const nodeCount = (workflow.nodes || []).length;
+ const edgeCount = (workflow.edges || []).length;
+
+ return {
+ workflowId,
+ totalRuns: hasRun ? 1 : 0,
+ successfulRuns: isCompleted ? 1 : 0,
+ failedRuns: isError ? 1 : 0,
+ successRate: isCompleted ? 100 : (isError ? 0 : 0),
+ lastRunAt: hasRun || isRunning ? workflow.updatedAt : undefined,
+ lastStatus: workflow.status,
+ averageDuration: undefined,
+ };
+ }
+
+ async autoLayoutWorkflow(params: AutoLayoutParams): Promise<{ workflow: WorkflowInfo; nodesRepositioned: number }> {
+ const workflow = await workflowService.loadWorkflow(params.workflowId);
+ if (!workflow) {
+ throw new Error(`Workflow '${params.workflowId}' not found`);
+ }
+
+ const nodes = workflow.nodes || [];
+ const edges = workflow.edges || [];
+ if (nodes.length === 0) {
+ return { workflow: this.workflowToInfo(workflow), nodesRepositioned: 0 };
+ }
+
+ const spacingX = params.spacingX || 250;
+ const spacingY = params.spacingY || 100;
+ const isHorizontal = params.direction !== 'vertical';
+
+ // Build adjacency map
+ const outgoing = new Map<string, string[]>();
+ const incoming = new Map<string, string[]>();
+ for (const edge of edges) {
+ if (!outgoing.has(edge.source)) outgoing.set(edge.source, []);
+ outgoing.get(edge.source)!.push(edge.target);
+ if (!incoming.has(edge.target)) incoming.set(edge.target, []);
+ incoming.get(edge.target)!.push(edge.source);
+ }
+
+ // Find root nodes (no incoming edges)
+ const rootNodes = nodes.filter(n => !incoming.has(n.id) || incoming.get(n.id)!.length === 0);
+
+ // BFS to assign levels
+ const levels = new Map<string, number>();
+ const queue: string[] = rootNodes.map(n => n.id);
+ rootNodes.forEach(n => levels.set(n.id, 0));
+
+ while (queue.length > 0) {
+ const nodeId = queue.shift()!;
+ const level = levels.get(nodeId)!;
+ const children = outgoing.get(nodeId) || [];
+ for (const childId of children) {
+ if (!levels.has(childId) || levels.get(childId)! < level + 1) {
+ levels.set(childId, level + 1);
+ queue.push(childId);
+ }
+ }
+ }
+
+ // Assign levels to disconnected nodes
+ let maxLevel = Math.max(0, ...levels.values());
+ for (const node of nodes) {
+ if (!levels.has(node.id)) {
+ maxLevel++;
+ levels.set(node.id, maxLevel);
+ }
+ }
+
+ // Group nodes by level
+ const levelGroups = new Map<number, typeof nodes>();
+ for (const node of nodes) {
+ const level = levels.get(node.id) || 0;
+ if (!levelGroups.has(level)) levelGroups.set(level, []);
+ levelGroups.get(level)!.push(node);
+ }
+
+ // Position nodes
+ let nodesRepositioned = 0;
+ const startX = 100;
+ const startY = 100;
+
+ for (const [level, group] of levelGroups) {
+ group.forEach((node, idx) => {
+ const oldPos = { ...node.position };
+ if (isHorizontal) {
+ node.position = {
+ x: startX + level * spacingX,
+ y: startY + idx * spacingY,
+ };
+ } else {
+ node.position = {
+ x: startX + idx * spacingX,
+ y: startY + level * spacingY,
+ };
+ }
+ if (oldPos.x !== node.position.x || oldPos.y !== node.position.y) {
+ nodesRepositioned++;
+ }
+ });
+ }
+
+ workflow.updatedAt = new Date().toISOString();
+ await workflowService.saveWorkflow(workflow);
+
+ return {
+ workflow: this.workflowToInfo(workflow),
+ nodesRepositioned,
+ };
+ }
+
// ============================================================================
// UTILITY METHODS
// ============================================================================
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/PortfolioMCPBridge.ts b/fincept-terminal-desktop/src/services/mcp/internal/PortfolioMCPBridge.ts
new file mode 100644
index 000000000..5af03d2bb
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/PortfolioMCPBridge.ts
@@ -0,0 +1,213 @@
+// Portfolio MCP Bridge - Connects portfolioService to MCP Internal Tools
+// Exposes complete portfolio functionality to AI via chat
+
+import { terminalMCPProvider } from './TerminalMCPProvider';
+import { portfolioService } from '@/services/portfolio/portfolioService';
+
+/**
+ * Bridge that connects portfolioService to MCP tools
+ * Allows AI to manage portfolios, assets, transactions, and analytics via chat
+ */
+export class PortfolioMCPBridge {
+ private connected: boolean = false;
+
+ /**
+ * Connect portfolio service to MCP contexts
+ */
+ connect(): void {
+ if (this.connected) return;
+
+ terminalMCPProvider.setContexts({
+ // ==================== PORTFOLIO CRUD ====================
+
+ // Get all portfolios
+ getPortfolios: async () => {
+ return await portfolioService.getPortfolios();
+ },
+
+ // Get single portfolio
+ getPortfolio: async (portfolioId: string) => {
+ return await portfolioService.getPortfolio(portfolioId);
+ },
+
+ // Create portfolio
+ createPortfolio: async (params: { name: string; owner?: string; currency?: string; description?: string }) => {
+ return await portfolioService.createPortfolio(
+ params.name,
+ params.owner || 'User',
+ params.currency || 'USD',
+ params.description
+ );
+ },
+
+ // Delete portfolio
+ deletePortfolio: async (portfolioId: string) => {
+ await portfolioService.deletePortfolio(portfolioId);
+ },
+
+ // ==================== ASSET MANAGEMENT ====================
+
+ // Add asset to portfolio
+ addAsset: async (portfolioId: string, asset: { symbol: string; quantity: number; avg_buy_price: number }) => {
+ return await portfolioService.addAsset(
+ portfolioId,
+ asset.symbol,
+ asset.quantity,
+ asset.avg_buy_price
+ );
+ },
+
+ // Remove asset from portfolio (sells all shares)
+ removeAsset: async (portfolioId: string, symbol: string, sellPrice?: number) => {
+ await portfolioService.removeAsset(portfolioId, symbol, sellPrice);
+ },
+
+ // Sell asset (partial or full)
+ sellAsset: async (portfolioId: string, symbol: string, quantity: number, price: number) => {
+ await portfolioService.sellAsset(portfolioId, symbol, quantity, price);
+ },
+
+ // Get portfolio assets
+ getPortfolioAssets: async (portfolioId: string) => {
+ return await portfolioService.getPortfolioAssets(portfolioId);
+ },
+
+ // ==================== TRANSACTIONS ====================
+
+ // Add transaction (note: portfolioService auto-creates transactions via addAsset/sellAsset)
+ addTransaction: async (portfolioId: string, tx: {
+ type: string;
+ symbol: string;
+ quantity: number;
+ price: number;
+ date?: string;
+ notes?: string;
+ }) => {
+ // Convert to appropriate action
+ const txType = tx.type.toUpperCase();
+ if (txType === 'BUY') {
+ return await portfolioService.addAsset(portfolioId, tx.symbol, tx.quantity, tx.price, tx.date);
+ } else if (txType === 'SELL') {
+ await portfolioService.sellAsset(portfolioId, tx.symbol, tx.quantity, tx.price, tx.date);
+ return { success: true };
+ } else {
+ // Dividend and split are not directly supported - return info
+ return {
+ success: false,
+ message: `${txType} transactions are tracked automatically by the system`,
+ };
+ }
+ },
+
+ // Get portfolio transactions
+ getPortfolioTransactions: async (portfolioId: string, limit?: number) => {
+ return await portfolioService.getPortfolioTransactions(portfolioId, limit || 100);
+ },
+
+ // Get transactions for specific symbol
+ getSymbolTransactions: async (portfolioId: string, symbol: string) => {
+ return await portfolioService.getSymbolTransactions(portfolioId, symbol);
+ },
+
+ // ==================== SUMMARY & ANALYTICS ====================
+
+ // Get portfolio summary with holdings and P&L
+ getPortfolioSummary: async (portfolioId: string) => {
+ return await portfolioService.getPortfolioSummary(portfolioId);
+ },
+
+ // Calculate advanced metrics (Sharpe, volatility, VaR, etc.)
+ calculateAdvancedMetrics: async (portfolioId: string) => {
+ return await portfolioService.calculateAdvancedMetrics(portfolioId);
+ },
+
+ // Calculate risk metrics
+ calculateRiskMetrics: async (portfolioId: string) => {
+ return await portfolioService.calculateRiskMetrics(portfolioId);
+ },
+
+ // ==================== OPTIMIZATION ====================
+
+ // Optimize portfolio weights
+ optimizePortfolioWeights: async (portfolioId: string, method?: string) => {
+ return await portfolioService.optimizePortfolioWeights(portfolioId, method || 'max_sharpe');
+ },
+
+ // Get rebalancing recommendations
+ getRebalancingRecommendations: async (portfolioId: string, targetAllocations: Record<string, number>) => {
+ return await portfolioService.getRebalancingRecommendations(portfolioId, targetAllocations);
+ },
+
+ // ==================== ANALYSIS ====================
+
+ // Analyze diversification
+ analyzeDiversification: async (portfolioId: string) => {
+ return await portfolioService.analyzeDiversification(portfolioId);
+ },
+
+ // Get performance history
+ getPortfolioPerformanceHistory: async (portfolioId: string, limit?: number) => {
+ return await portfolioService.getPortfolioPerformanceHistory(portfolioId, limit || 30);
+ },
+
+ // ==================== EXPORT ====================
+
+ // Export portfolio to CSV
+ exportPortfolioCSV: async (portfolioId: string) => {
+ return await portfolioService.exportPortfolioCSV(portfolioId);
+ },
+ });
+
+ this.connected = true;
+ console.log('[PortfolioMCPBridge] Connected portfolio service to MCP');
+ }
+
+ /**
+ * Disconnect and clear contexts
+ */
+ disconnect(): void {
+ if (!this.connected) return;
+
+ terminalMCPProvider.setContexts({
+ // Portfolio CRUD
+ getPortfolios: undefined,
+ getPortfolio: undefined,
+ createPortfolio: undefined,
+ deletePortfolio: undefined,
+ // Asset management
+ addAsset: undefined,
+ removeAsset: undefined,
+ sellAsset: undefined,
+ getPortfolioAssets: undefined,
+ // Transactions
+ addTransaction: undefined,
+ getPortfolioTransactions: undefined,
+ getSymbolTransactions: undefined,
+ // Summary & analytics
+ getPortfolioSummary: undefined,
+ calculateAdvancedMetrics: undefined,
+ calculateRiskMetrics: undefined,
+ // Optimization
+ optimizePortfolioWeights: undefined,
+ getRebalancingRecommendations: undefined,
+ // Analysis
+ analyzeDiversification: undefined,
+ getPortfolioPerformanceHistory: undefined,
+ // Export
+ exportPortfolioCSV: undefined,
+ });
+
+ this.connected = false;
+ console.log('[PortfolioMCPBridge] Disconnected portfolio service from MCP');
+ }
+
+ /**
+ * Check if bridge is connected
+ */
+ isConnected(): boolean {
+ return this.connected;
+ }
+}
+
+// Singleton instance
+export const portfolioMCPBridge = new PortfolioMCPBridge();
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/index.ts b/fincept-terminal-desktop/src/services/mcp/internal/index.ts
index a420f5055..902ae3626 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/index.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/index.ts
@@ -16,11 +16,14 @@ import { stockTradingTools } from './tools/stock-trading';
import { reportBuilderTools } from './tools/report-builder';
import { edgarTools } from './tools/edgar';
import { nodeEditorTools } from './tools/node-editor';
+import { newsTools } from './tools/news';
import { reportBuilderMCPBridge } from './ReportBuilderMCPBridge';
import { brokerMCPBridge } from './BrokerMCPBridge';
import { stockBrokerMCPBridge } from './StockBrokerMCPBridge';
import { notesMCPBridge } from './NotesMCPBridge';
import { nodeEditorMCPBridge } from './NodeEditorMCPBridge';
+import { portfolioMCPBridge } from './PortfolioMCPBridge';
+import { newsMCPBridge } from './NewsMCPBridge';
// Flag to ensure initialization only runs once
let isInitialized = false;
@@ -52,6 +55,7 @@ export function initializeInternalMCP(): void {
terminalMCPProvider.registerTools(reportBuilderTools);
terminalMCPProvider.registerTools(edgarTools);
terminalMCPProvider.registerTools(nodeEditorTools);
+ terminalMCPProvider.registerTools(newsTools);
// Initialize global bridge contexts
@@ -60,6 +64,12 @@ export function initializeInternalMCP(): void {
// Initialize Node Editor bridge contexts
nodeEditorMCPBridge.initialize();
+ // Initialize Portfolio bridge contexts
+ portfolioMCPBridge.connect();
+
+ // Initialize News bridge contexts
+ newsMCPBridge.connect();
+
// Mark as initialized
isInitialized = true;
} catch (error) {
@@ -81,6 +91,8 @@ export { stockBrokerMCPBridge } from './StockBrokerMCPBridge';
export { notesMCPBridge } from './NotesMCPBridge';
export { reportBuilderMCPBridge } from './ReportBuilderMCPBridge';
export { nodeEditorMCPBridge } from './NodeEditorMCPBridge';
+export { portfolioMCPBridge } from './PortfolioMCPBridge';
+export { newsMCPBridge } from './NewsMCPBridge';
export { INTERNAL_SERVER_ID, INTERNAL_SERVER_NAME } from './types';
export type { TerminalContexts, InternalTool, InternalToolResult } from './types';
export type {
@@ -93,4 +105,14 @@ export type {
WorkflowInfo,
WorkflowExecutionResult,
WorkflowValidation,
+ // News types
+ NewsArticleInfo,
+ RSSFeedInfo,
+ UserRSSFeedInfo,
+ AddRSSFeedParams,
+ UpdateRSSFeedParams,
+ NewsAnalysisResult,
+ NewsAnalysisData,
+ NewsSentimentStats,
+ NewsCacheStats,
} from './types';
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/edgar.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/edgar.ts
index 712892674..a7dfa360b 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/tools/edgar.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/edgar.ts
@@ -294,7 +294,7 @@ async function executeEdgarCommand(command: string, args: any[]): Promise<any> {
const result = await invoke('execute_python_script', {
app: null, // Will be injected by Tauri
- scriptName: 'edgar_tools.py',
+ scriptName: 'edgar_mcp.py',
args: scriptArgs,
env: {}
});
@@ -967,4 +967,258 @@ export const edgarTools: InternalTool[] = [
}
},
},
+
+ // ============================================================================
+ // NEW: 10-K SECTION EXTRACTION
+ // ============================================================================
+
+ {
+ name: 'edgar_10k_sections',
+ description: 'Extract specific sections from 10-K annual report. Get Item 1 (Business), Item 1A (Risk Factors), Item 7 (MD&A), Item 10 (Governance), and more.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Company name to search' },
+ ticker: { type: 'string', description: 'Or exact ticker symbol' },
+ sections: {
+ type: 'array',
+ items: { type: 'string' },
+ description: 'Sections to extract: business, risk_factors, legal_proceedings, md&a, controls, compensation, governance, all_items'
+ },
+ },
+ required: [],
+ },
+ handler: async (args) => {
+ let ticker = args.ticker;
+ if (args.query && !ticker) {
+ ticker = await resolveTickerFromQuery(args.query);
+ if (!ticker) {
+ return { success: false, error: `Could not find company: ${args.query}` };
+ }
+ }
+
+ if (!ticker) {
+ return { success: false, error: 'Must provide either query or ticker' };
+ }
+
+ const sections = args.sections || [];
+
+ try {
+ const result = await executeEdgarCommand('10k_sections', [ticker, ...sections]);
+ return {
+ success: true,
+ data: result.data,
+ ticker,
+ message: `Extracted 10-K sections for ${ticker}`,
+ };
+ } catch (error: any) {
+ return {
+ success: false,
+ error: error?.message || String(error),
+ };
+ }
+ },
+ },
+
+ {
+ name: 'edgar_10k_full_text',
+ description: 'Get full text content of 10-K annual report',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Company name' },
+ ticker: { type: 'string', description: 'Or ticker symbol' },
+ max_length: { type: 'number', description: 'Maximum text length' },
+ },
+ required: [],
+ },
+ handler: async (args) => {
+ let ticker = args.ticker;
+ if (args.query && !ticker) {
+ ticker = await resolveTickerFromQuery(args.query);
+ if (!ticker) return { success: false, error: `Could not find company: ${args.query}` };
+ }
+ if (!ticker) return { success: false, error: 'Must provide either query or ticker' };
+
+ const maxLength = args.max_length || null;
+ const commandArgs = maxLength ? [ticker, maxLength] : [ticker];
+
+ try {
+ const result = await executeEdgarCommand('10k_full_text', commandArgs);
+ return {
+ success: true,
+ data: result.data,
+ ticker,
+ message: `Retrieved 10-K full text for ${ticker}`,
+ };
+ } catch (error: any) {
+ return { success: false, error: error?.message || String(error) };
+ }
+ },
+ },
+
+ {
+ name: 'edgar_10k_search',
+ description: 'Search for text within 10-K annual report',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Company name' },
+ ticker: { type: 'string', description: 'Or ticker symbol' },
+ search_query: { type: 'string', description: 'Text to search for' },
+ max_results: { type: 'number', description: 'Maximum results (default: 10)' },
+ },
+ required: ['search_query'],
+ },
+ handler: async (args) => {
+ let ticker = args.ticker;
+ if (args.query && !ticker) {
+ ticker = await resolveTickerFromQuery(args.query);
+ if (!ticker) return { success: false, error: `Could not find company: ${args.query}` };
+ }
+ if (!ticker) return { success: false, error: 'Must provide either query or ticker' };
+
+ const searchQuery = args.search_query;
+ const maxResults = args.max_results || 10;
+
+ try {
+ const result = await executeEdgarCommand('10k_search', [ticker, searchQuery, maxResults]);
+ return {
+ success: true,
+ data: result.data,
+ ticker,
+ message: `Searched 10-K for "${searchQuery}"`,
+ };
+ } catch (error: any) {
+ return { success: false, error: error?.message || String(error) };
+ }
+ },
+ },
+
+ // ============================================================================
+ // NEW: 10-Q SECTION EXTRACTION
+ // ============================================================================
+
+ {
+ name: 'edgar_10q_sections',
+ description: 'Extract specific sections from 10-Q quarterly report. Get Part I Item 1 (Financials), Item 2 (MD&A), Part II Item 1A (Risk Factors), and more.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Company name to search' },
+ ticker: { type: 'string', description: 'Or exact ticker symbol' },
+ sections: {
+ type: 'array',
+ items: { type: 'string' },
+ description: 'Sections to extract: part_i_item_1, part_i_item_2, part_i_item_3, part_i_item_4, part_i_item_8, part_ii_item_1, part_ii_item_1a, part_ii_item_2, part_ii_item_5, part_ii_item_6'
+ },
+ },
+ required: [],
+ },
+ handler: async (args) => {
+ let ticker = args.ticker;
+ if (args.query && !ticker) {
+ ticker = await resolveTickerFromQuery(args.query);
+ if (!ticker) {
+ return { success: false, error: `Could not find company: ${args.query}` };
+ }
+ }
+
+ if (!ticker) {
+ return { success: false, error: 'Must provide either query or ticker' };
+ }
+
+ const sections = args.sections || [];
+
+ try {
+ const result = await executeEdgarCommand('10q_sections', [ticker, ...sections]);
+ return {
+ success: true,
+ data: result.data,
+ ticker,
+ message: `Extracted 10-Q sections for ${ticker}`,
+ };
+ } catch (error: any) {
+ return {
+ success: false,
+ error: error?.message || String(error),
+ };
+ }
+ },
+ },
+
+ {
+ name: 'edgar_10q_full_text',
+ description: 'Get full text content of 10-Q quarterly report',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Company name' },
+ ticker: { type: 'string', description: 'Or ticker symbol' },
+ max_length: { type: 'number', description: 'Maximum text length' },
+ },
+ required: [],
+ },
+ handler: async (args) => {
+ let ticker = args.ticker;
+ if (args.query && !ticker) {
+ ticker = await resolveTickerFromQuery(args.query);
+ if (!ticker) return { success: false, error: `Could not find company: ${args.query}` };
+ }
+ if (!ticker) return { success: false, error: 'Must provide either query or ticker' };
+
+ const maxLength = args.max_length || null;
+ const commandArgs = maxLength ? [ticker, maxLength] : [ticker];
+
+ try {
+ const result = await executeEdgarCommand('10q_full_text', commandArgs);
+ return {
+ success: true,
+ data: result.data,
+ ticker,
+ message: `Retrieved 10-Q full text for ${ticker}`,
+ };
+ } catch (error: any) {
+ return { success: false, error: error?.message || String(error) };
+ }
+ },
+ },
+
+ {
+ name: 'edgar_10q_search',
+ description: 'Search for text within 10-Q quarterly report',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Company name' },
+ ticker: { type: 'string', description: 'Or ticker symbol' },
+ search_query: { type: 'string', description: 'Text to search for' },
+ max_results: { type: 'number', description: 'Maximum results (default: 10)' },
+ },
+ required: ['search_query'],
+ },
+ handler: async (args) => {
+ let ticker = args.ticker;
+ if (args.query && !ticker) {
+ ticker = await resolveTickerFromQuery(args.query);
+ if (!ticker) return { success: false, error: `Could not find company: ${args.query}` };
+ }
+ if (!ticker) return { success: false, error: 'Must provide either query or ticker' };
+
+ const searchQuery = args.search_query;
+ const maxResults = args.max_results || 10;
+
+ try {
+ const result = await executeEdgarCommand('10q_search', [ticker, searchQuery, maxResults]);
+ return {
+ success: true,
+ data: result.data,
+ ticker,
+ message: `Searched 10-Q for "${searchQuery}"`,
+ };
+ } catch (error: any) {
+ return { success: false, error: error?.message || String(error) };
+ }
+ },
+ },
];
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.ts
index 9af4ef889..5d181d9da 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.ts
@@ -97,4 +97,64 @@ export const navigationTools: InternalTool[] = [
return { success: true, message: `Opened settings > ${args.section}`, data: { section: args.section } };
},
},
+ {
+ name: 'open_news_tab',
+ description: 'Navigate to the News tab to view financial news, RSS feeds, and market sentiment. Use this when user wants to see news, check headlines, or read financial articles',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('news');
+ return { success: true, message: 'Navigated to News tab' };
+ },
+ },
+ {
+ name: 'open_portfolio_tab',
+ description: 'Navigate to the Portfolio tab to view holdings, performance, and manage investments',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('portfolio');
+ return { success: true, message: 'Navigated to Portfolio tab' };
+ },
+ },
+ {
+ name: 'open_trading_tab',
+ description: 'Navigate to the Trading tab for crypto trading with connected exchanges',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('trading');
+ return { success: true, message: 'Navigated to Trading tab' };
+ },
+ },
+ {
+ name: 'open_markets_tab',
+ description: 'Navigate to the Markets tab to view market data, indices, and real-time quotes',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.setActiveTab) {
+ return { success: false, error: 'Navigation context not available' };
+ }
+ contexts.setActiveTab('markets');
+ return { success: true, message: 'Navigated to Markets tab' };
+ },
+ },
];
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/news.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/news.ts
new file mode 100644
index 000000000..9715ea6bd
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/news.ts
@@ -0,0 +1,802 @@
+// News MCP Tools - Comprehensive news fetching, filtering, management and analysis
+// Allows AI to interact with all news functionality via chat
+
+import type { InternalTool, InternalToolResult, NewsArticleInfo } from '../types';
+
+/**
+ * Helper to format news articles for AI consumption
+ */
+function formatNewsArticles(articles: NewsArticleInfo[], maxArticles = 20): string {
+ if (!articles || articles.length === 0) {
+ return 'No news articles found';
+ }
+
+ const limited = articles.slice(0, maxArticles);
+ const lines = limited.map((article, idx) => {
+ const priorityBadge = article.priority === 'FLASH' || article.priority === 'URGENT' ? `[${article.priority}] ` : '';
+ const tickerStr = article.tickers?.length > 0 ? ` | Tickers: ${article.tickers.join(', ')}` : '';
+ return `${idx + 1}. ${priorityBadge}${article.headline}
+ Source: ${article.source} | Category: ${article.category} | Sentiment: ${article.sentiment} | Impact: ${article.impact}${tickerStr}
+ Time: ${article.time || 'N/A'}${article.link ? ` | Link: ${article.link}` : ''}`;
+ });
+
+ const summary = `Found ${articles.length} articles${articles.length > maxArticles ? ` (showing first ${maxArticles})` : ''}:\n\n`;
+ return summary + lines.join('\n\n');
+}
+
+export const newsTools: InternalTool[] = [
+ // ============================================================================
+ // NEWS FETCHING & FILTERING
+ // ============================================================================
+
+ {
+ name: 'get_all_news',
+ description: 'Get all news articles from all configured RSS feeds. Use this to see the latest financial news. Returns headlines, sources, sentiment, priority, and tickers.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ force_refresh: {
+ type: 'boolean',
+ description: 'Force refresh from sources (bypass cache). Default is false.',
+ default: false,
+ },
+ limit: {
+ type: 'number',
+ description: 'Maximum number of articles to return. Default is 20.',
+ default: 20,
+ },
+ },
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.fetchAllNews) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const articles = await contexts.fetchAllNews(args.force_refresh || false);
+ const limit = args.limit || 20;
+ return {
+ success: true,
+ data: articles.slice(0, limit),
+ message: formatNewsArticles(articles, limit),
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to fetch news: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'get_news_by_category',
+ description: 'Get news articles filtered by category. Categories include: MARKETS, CRYPTO, TECH, ENERGY, REGULATORY, ECONOMIC, EARNINGS, BANKING, GEOPOLITICS, GENERAL.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ category: {
+ type: 'string',
+ description: 'Category to filter by (MARKETS, CRYPTO, TECH, ENERGY, REGULATORY, ECONOMIC, EARNINGS, BANKING, GEOPOLITICS, GENERAL)',
+ enum: ['MARKETS', 'CRYPTO', 'TECH', 'ENERGY', 'REGULATORY', 'ECONOMIC', 'EARNINGS', 'BANKING', 'GEOPOLITICS', 'GENERAL'],
+ },
+ limit: {
+ type: 'number',
+ description: 'Maximum number of articles to return. Default is 15.',
+ default: 15,
+ },
+ },
+ required: ['category'],
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.getNewsByCategory) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const category = (args.category || '').toUpperCase();
+ const articles = await contexts.getNewsByCategory(category);
+ const limit = args.limit || 15;
+ return {
+ success: true,
+ data: articles.slice(0, limit),
+ message: `News in category "${category}":\n\n${formatNewsArticles(articles, limit)}`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to fetch news by category: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'get_news_by_source',
+ description: 'Get news articles from a specific source/provider (e.g., YAHOO, COINDESK, BLOOMBERG, REUTERS, etc.)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ source: {
+ type: 'string',
+ description: 'Source name to filter by (e.g., YAHOO, COINDESK, COINTELEGRAPH, TECHCRUNCH)',
+ },
+ limit: {
+ type: 'number',
+ description: 'Maximum number of articles to return. Default is 15.',
+ default: 15,
+ },
+ },
+ required: ['source'],
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.getNewsBySource) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const source = (args.source || '').toUpperCase();
+ const articles = await contexts.getNewsBySource(source);
+ const limit = args.limit || 15;
+ return {
+ success: true,
+ data: articles.slice(0, limit),
+ message: `News from "${source}":\n\n${formatNewsArticles(articles, limit)}`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to fetch news by source: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'search_news',
+ description: 'Search news articles by keyword. Searches headlines, summaries, sources, and tickers.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: {
+ type: 'string',
+ description: 'Search query (keyword, ticker symbol, company name, etc.)',
+ },
+ limit: {
+ type: 'number',
+ description: 'Maximum number of articles to return. Default is 15.',
+ default: 15,
+ },
+ },
+ required: ['query'],
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.searchNews) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const articles = await contexts.searchNews(args.query || '');
+ const limit = args.limit || 15;
+ return {
+ success: true,
+ data: articles.slice(0, limit),
+ message: `Search results for "${args.query}":\n\n${formatNewsArticles(articles, limit)}`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to search news: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'get_breaking_news',
+ description: 'Get breaking and urgent news articles (FLASH or URGENT priority). These are the most important market-moving headlines.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ limit: {
+ type: 'number',
+ description: 'Maximum number of articles to return. Default is 10.',
+ default: 10,
+ },
+ },
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.getBreakingNews) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const articles = await contexts.getBreakingNews();
+ const limit = args.limit || 10;
+ if (articles.length === 0) {
+ return {
+ success: true,
+ data: [],
+ message: 'No breaking news at the moment. All quiet on the market front',
+ };
+ }
+ return {
+ success: true,
+ data: articles.slice(0, limit),
+ message: `BREAKING NEWS ALERTS:\n\n${formatNewsArticles(articles, limit)}`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to fetch breaking news: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'get_news_by_sentiment',
+ description: 'Get news articles filtered by market sentiment (BULLISH, BEARISH, or NEUTRAL)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ sentiment: {
+ type: 'string',
+ description: 'Sentiment filter: BULLISH (positive), BEARISH (negative), or NEUTRAL',
+ enum: ['BULLISH', 'BEARISH', 'NEUTRAL'],
+ },
+ limit: {
+ type: 'number',
+ description: 'Maximum number of articles to return. Default is 15.',
+ default: 15,
+ },
+ },
+ required: ['sentiment'],
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.getNewsBySentiment) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const sentiment = (args.sentiment || '').toUpperCase() as 'BULLISH' | 'BEARISH' | 'NEUTRAL';
+ const articles = await contexts.getNewsBySentiment(sentiment);
+ const limit = args.limit || 15;
+ return {
+ success: true,
+ data: articles.slice(0, limit),
+ message: `${sentiment} news articles:\n\n${formatNewsArticles(articles, limit)}`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to fetch news by sentiment: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'get_news_by_ticker',
+ description: 'Get news articles mentioning a specific stock ticker symbol (e.g., AAPL, TSLA, BTC)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ ticker: {
+ type: 'string',
+ description: 'Stock ticker symbol (e.g., AAPL, MSFT, TSLA, BTC)',
+ },
+ limit: {
+ type: 'number',
+ description: 'Maximum number of articles to return. Default is 15.',
+ default: 15,
+ },
+ },
+ required: ['ticker'],
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.getNewsByTicker) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const ticker = (args.ticker || '').toUpperCase();
+ const articles = await contexts.getNewsByTicker(ticker);
+ const limit = args.limit || 15;
+ if (articles.length === 0) {
+ return {
+ success: true,
+ data: [],
+ message: `No news articles found mentioning ticker "${ticker}"`,
+ };
+ }
+ return {
+ success: true,
+ data: articles.slice(0, limit),
+ message: `News mentioning ${ticker}:\n\n${formatNewsArticles(articles, limit)}`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to fetch news by ticker: ${error}` };
+ }
+ },
+ },
+
+ // ============================================================================
+ // NEWS PROVIDERS / SOURCES
+ // ============================================================================
+
+ {
+ name: 'list_active_news_sources',
+ description: 'Get list of all active news sources/providers currently fetching news',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.getActiveSources) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const sources = await contexts.getActiveSources();
+ return {
+ success: true,
+ data: sources,
+ message: `Active news sources (${sources.length}):\n${sources.map((s, i) => `${i + 1}. ${s}`).join('\n')}`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to get active sources: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'get_rss_feed_count',
+ description: 'Get the total number of RSS feeds configured',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.getRSSFeedCount) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const count = await contexts.getRSSFeedCount();
+ return {
+ success: true,
+ data: { count },
+ message: `There are ${count} RSS feeds configured in total.`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to get feed count: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'list_user_rss_feeds',
+ description: 'List all custom RSS feeds added by the user',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.getUserRSSFeeds) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const feeds = await contexts.getUserRSSFeeds();
+ if (feeds.length === 0) {
+ return {
+ success: true,
+ data: [],
+ message: 'No custom RSS feeds configured. User can add custom feeds in the News tab settings',
+ };
+ }
+ const feedList = feeds.map((f, i) =>
+ `${i + 1}. ${f.name} (${f.source_name})\n Category: ${f.category} | Region: ${f.region} | Enabled: ${f.enabled ? 'Yes' : 'No'}\n URL: ${f.url}`
+ ).join('\n\n');
+ return {
+ success: true,
+ data: feeds,
+ message: `Custom RSS feeds (${feeds.length}):\n\n${feedList}`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to get user feeds: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'list_default_rss_feeds',
+ description: 'List all default (built-in) RSS feeds',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.getDefaultFeeds) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const feeds = await contexts.getDefaultFeeds();
+ const feedList = feeds.map((f, i) =>
+ `${i + 1}. ${f.name} (${f.source})\n Category: ${f.category} | Region: ${f.region} | Enabled: ${f.enabled ? 'Yes' : 'No'}`
+ ).join('\n\n');
+ return {
+ success: true,
+ data: feeds,
+ message: `Default RSS feeds (${feeds.length}):\n\n${feedList}`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to get default feeds: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'list_all_rss_feeds',
+ description: 'List all RSS feeds (both default and custom)',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.getAllRSSFeeds) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const feeds = await contexts.getAllRSSFeeds();
+ const enabledCount = feeds.filter(f => f.enabled).length;
+ const feedList = feeds.map((f, i) =>
+ `${i + 1}. ${f.name} (${f.source}) [${f.is_default ? 'Default' : 'Custom'}]\n Category: ${f.category} | Region: ${f.region} | Enabled: ${f.enabled ? 'Yes' : 'No'}`
+ ).join('\n\n');
+ return {
+ success: true,
+ data: feeds,
+ message: `All RSS feeds (${feeds.length} total, ${enabledCount} enabled):\n\n${feedList}`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to get all feeds: ${error}` };
+ }
+ },
+ },
+
+ // ============================================================================
+ // RSS FEED MANAGEMENT
+ // ============================================================================
+
+ {
+ name: 'add_rss_feed',
+ description: 'Add a new custom RSS feed. Requires name, URL, category, region, and source name.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ name: {
+ type: 'string',
+ description: 'Display name for the feed (e.g., "Bloomberg Markets")',
+ },
+ url: {
+ type: 'string',
+ description: 'RSS feed URL (must be valid RSS/XML feed)',
+ },
+ category: {
+ type: 'string',
+ description: 'News category',
+ enum: ['MARKETS', 'CRYPTO', 'TECH', 'ENERGY', 'REGULATORY', 'ECONOMIC', 'EARNINGS', 'BANKING', 'GEOPOLITICS', 'GENERAL'],
+ default: 'GENERAL',
+ },
+ region: {
+ type: 'string',
+ description: 'Geographic region',
+ enum: ['GLOBAL', 'US', 'EU', 'ASIA', 'UK', 'INDIA', 'CHINA', 'LATAM'],
+ default: 'GLOBAL',
+ },
+ source_name: {
+ type: 'string',
+ description: 'Short source name for display (e.g., "BLOOMBERG")',
+ },
+ },
+ required: ['name', 'url', 'source_name'],
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.addUserRSSFeed) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const feed = await contexts.addUserRSSFeed({
+ name: args.name,
+ url: args.url,
+ category: args.category || 'GENERAL',
+ region: args.region || 'GLOBAL',
+ source_name: (args.source_name || '').toUpperCase(),
+ });
+ return {
+ success: true,
+ data: feed,
+ message: `Successfully added RSS feed "${feed.name}" (${feed.source_name}).\nCategory: ${feed.category} | Region: ${feed.region}\nURL: ${feed.url}`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to add RSS feed: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'toggle_rss_feed',
+ description: 'Enable or disable an RSS feed by ID',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ feed_id: {
+ type: 'string',
+ description: 'Feed ID to toggle',
+ },
+ enabled: {
+ type: 'boolean',
+ description: 'True to enable, false to disable',
+ },
+ is_default: {
+ type: 'boolean',
+ description: 'True if this is a default feed, false if custom feed',
+ default: false,
+ },
+ },
+ required: ['feed_id', 'enabled'],
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ try {
+ if (args.is_default) {
+ if (!contexts.toggleDefaultRSSFeed) {
+ return { success: false, error: 'News service not available' };
+ }
+ await contexts.toggleDefaultRSSFeed(args.feed_id, args.enabled);
+ } else {
+ if (!contexts.toggleUserRSSFeed) {
+ return { success: false, error: 'News service not available' };
+ }
+ await contexts.toggleUserRSSFeed(args.feed_id, args.enabled);
+ }
+ return {
+ success: true,
+ message: `RSS feed ${args.enabled ? 'enabled' : 'disabled'} successfully.`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to toggle feed: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'delete_rss_feed',
+ description: 'Delete a custom RSS feed by ID',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ feed_id: {
+ type: 'string',
+ description: 'Feed ID to delete',
+ },
+ },
+ required: ['feed_id'],
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.deleteUserRSSFeed) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ await contexts.deleteUserRSSFeed(args.feed_id);
+ return {
+ success: true,
+ message: 'RSS feed deleted successfully.',
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to delete feed: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'test_rss_feed_url',
+ description: 'Test if an RSS feed URL is valid and accessible',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ url: {
+ type: 'string',
+ description: 'RSS feed URL to test',
+ },
+ },
+ required: ['url'],
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.testRSSFeedUrl) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const isValid = await contexts.testRSSFeedUrl(args.url);
+ return {
+ success: true,
+ data: { valid: isValid, url: args.url },
+ message: isValid
+ ? `RSS feed URL is valid and accessible: ${args.url}`
+ : `RSS feed URL is invalid or not accessible: ${args.url}`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to test URL: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'restore_all_default_feeds',
+ description: 'Restore all deleted default RSS feeds',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.restoreAllDefaultFeeds) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ await contexts.restoreAllDefaultFeeds();
+ return {
+ success: true,
+ message: 'All default RSS feeds have been restored.',
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to restore feeds: ${error}` };
+ }
+ },
+ },
+
+ // ============================================================================
+ // NEWS ANALYSIS
+ // ============================================================================
+
+ {
+ name: 'analyze_news_article',
+ description: 'Run AI-powered analysis on a news article by URL. Returns sentiment analysis, market impact, entities, keywords, topics, risk signals, summary, and key points. This uses the ANALYZE button functionality.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ url: {
+ type: 'string',
+ description: 'Full URL of the news article to analyze',
+ },
+ },
+ required: ['url'],
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.analyzeNewsArticle) {
+ return { success: false, error: 'News analysis service not available' };
+ }
+ try {
+ const result = await contexts.analyzeNewsArticle(args.url);
+ if (!result.success || !result.data) {
+ return {
+ success: false,
+ error: result.error || 'Analysis failed',
+ };
+ }
+
+ const analysis = result.data.analysis;
+ const sentimentLabel = analysis.sentiment.score > 0.3 ? 'POSITIVE' :
+ analysis.sentiment.score < -0.3 ? 'NEGATIVE' : 'NEUTRAL';
+
+ const formattedAnalysis = `
+ARTICLE ANALYSIS
+================
+Headline: ${result.data.content.headline}
+Source: ${result.data.source}
+Published: ${result.data.published_at}
+
+SUMMARY
+-------
+${analysis.summary}
+
+KEY POINTS
+----------
+${analysis.key_points.map((p, i) => `${i + 1}. ${p}`).join('\n')}
+
+SENTIMENT
+---------
+Score: ${analysis.sentiment.score.toFixed(2)} (${sentimentLabel})
+Intensity: ${analysis.sentiment.intensity.toFixed(2)}
+Confidence: ${(analysis.sentiment.confidence * 100).toFixed(0)}%
+
+MARKET IMPACT
+-------------
+Urgency: ${analysis.market_impact.urgency}
+Prediction: ${analysis.market_impact.prediction.replace('_', ' ').toUpperCase()}
+
+RISK SIGNALS
+------------
+${Object.entries(analysis.risk_signals).map(([type, signal]) =>
+ `${type.toUpperCase()}: ${signal.level}${signal.details ? ` - ${signal.details}` : ''}`
+).join('\n')}
+
+TOPICS: ${analysis.topics.join(', ')}
+
+KEYWORDS: ${analysis.keywords.slice(0, 10).join(', ')}
+
+ORGANIZATIONS
+-------------
+${analysis.entities.organizations.length > 0
+ ? analysis.entities.organizations.map(org =>
+ `- ${org.name}${org.ticker ? ` (${org.ticker})` : ''} | ${org.sector} | Sentiment: ${org.sentiment.toFixed(2)}`
+ ).join('\n')
+ : 'None identified'}
+
+Credits used: ${result.data.credits_used} | Remaining: ${result.data.credits_remaining.toLocaleString()}
+`;
+
+ return {
+ success: true,
+ data: result.data,
+ message: formattedAnalysis,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to analyze article: ${error}` };
+ }
+ },
+ },
+
+ // ============================================================================
+ // NEWS STATISTICS
+ // ============================================================================
+
+ {
+ name: 'get_news_sentiment_stats',
+ description: 'Get overall market sentiment statistics from current news articles (bullish, bearish, neutral counts and net score)',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ if (!contexts.getNewsSentimentStats) {
+ return { success: false, error: 'News service not available' };
+ }
+ try {
+ const stats = await contexts.getNewsSentimentStats();
+ const scoreLabel = stats.netScore > 0.1 ? 'BULLISH' :
+ stats.netScore < -0.1 ? 'BEARISH' : 'NEUTRAL';
+
+ return {
+ success: true,
+ data: stats,
+ message: `NEWS SENTIMENT OVERVIEW
+=======================
+Total Articles: ${stats.total}
+Alert Count: ${stats.alertCount} (FLASH/URGENT)
+
+Sentiment Distribution:
+- Bullish: ${stats.bullish} (${Math.round((stats.bullish / stats.total) * 100)}%)
+- Bearish: ${stats.bearish} (${Math.round((stats.bearish / stats.total) * 100)}%)
+- Neutral: ${stats.neutral} (${Math.round((stats.neutral / stats.total) * 100)}%)
+
+Net Sentiment Score: ${stats.netScore.toFixed(2)} (${scoreLabel})`,
+ };
+ } catch (error) {
+ return { success: false, error: `Failed to get sentiment stats: ${error}` };
+ }
+ },
+ },
+
+ {
+ name: 'get_available_news_categories',
+ description: 'Get list of available news categories for filtering',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ const categories = contexts.getAvailableCategories?.() || [
+ 'MARKETS', 'CRYPTO', 'TECH', 'ENERGY', 'REGULATORY',
+ 'ECONOMIC', 'EARNINGS', 'BANKING', 'GEOPOLITICS', 'GENERAL'
+ ];
+ return {
+ success: true,
+ data: categories,
+ message: `Available news categories:\n${categories.map((c, i) => `${i + 1}. ${c}`).join('\n')}`,
+ };
+ },
+ },
+
+ {
+ name: 'get_available_news_regions',
+ description: 'Get list of available news regions for filtering',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (args, contexts): Promise<InternalToolResult> => {
+ const regions = contexts.getAvailableRegions?.() || [
+ 'GLOBAL', 'US', 'EU', 'ASIA', 'UK', 'INDIA', 'CHINA', 'LATAM'
+ ];
+ return {
+ success: true,
+ data: regions,
+ message: `Available news regions:\n${regions.map((r, i) => `${i + 1}. ${r}`).join('\n')}`,
+ };
+ },
+ },
+];
+
+export default newsTools;
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/node-editor.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/node-editor.ts
index ff9c118d7..f45ec8217 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/tools/node-editor.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/node-editor.ts
@@ -1225,4 +1225,760 @@ Example workflow structure:
};
},
},
+
+ // ============================================================================
+ // NATURAL LANGUAGE HELPERS (For Chat Bubble Integration)
+ // ============================================================================
+ {
+ name: 'node_editor_describe_workflow',
+ description: `Get a human-readable description of a workflow. Useful to understand what a workflow does before modifying it or to explain it to the user.`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ workflow_id: {
+ type: 'string',
+ description: 'The workflow ID to describe',
+ },
+ },
+ required: ['workflow_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getNodeWorkflow) {
+ return { success: false, error: 'Node editor context not available' };
+ }
+
+ const workflow = await contexts.getNodeWorkflow(args.workflow_id);
+ if (!workflow) {
+ return { success: false, error: `Workflow '${args.workflow_id}' not found` };
+ }
+
+ const nodes = workflow.nodes || [];
+ const edges = workflow.edges || [];
+
+ // Build description
+ const nodeDescriptions = nodes.map(n => {
+ const type = n.parameters?.nodeType || n.type || 'unknown';
+ const label = n.label || type;
+ const desc = AVAILABLE_NODE_TYPES[type as keyof typeof AVAILABLE_NODE_TYPES] || '';
+ return ` - ${label} (${type})${desc ? ': ' + desc : ''}`;
+ });
+
+ // Find trigger and output nodes
+ const triggerNodes = nodes.filter(n =>
+ (n.type || '').toLowerCase().includes('trigger') ||
+ (n.parameters?.nodeType || '').toLowerCase().includes('trigger')
+ );
+ const outputNodes = nodes.filter(n =>
+ !edges.some(e => e.source === n.id) // Nodes with no outgoing edges
+ );
+
+ const description = `
+**Workflow: ${workflow.name}**
+${workflow.description ? `Description: ${workflow.description}` : ''}
+
+**Nodes (${nodes.length}):**
+${nodeDescriptions.join('\n')}
+
+**Flow:**
+- Starts with: ${triggerNodes.length > 0 ? triggerNodes.map(n => n.label || n.type).join(', ') : 'No trigger (manual start)'}
+- Ends with: ${outputNodes.map(n => n.label || n.type).join(', ')}
+- Connections: ${edges.length}
+
+**Status:** ${workflow.status}
+ `.trim();
+
+ return {
+ success: true,
+ data: {
+ summary: description,
+ nodeCount: nodes.length,
+ edgeCount: edges.length,
+ hasTrigger: triggerNodes.length > 0,
+ status: workflow.status,
+ },
+ message: description,
+ };
+ },
+ },
+
+ {
+ name: 'node_editor_suggest_next_node',
+ description: `Suggest what node to add next based on the current workflow state. Helps users build workflows step by step.`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ workflow_id: {
+ type: 'string',
+ description: 'The workflow ID to analyze',
+ },
+ goal: {
+ type: 'string',
+ description: 'Optional: What the user wants to achieve (e.g., "send alert when RSI is low")',
+ },
+ },
+ required: ['workflow_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getNodeWorkflow) {
+ return { success: false, error: 'Node editor context not available' };
+ }
+
+ const workflow = await contexts.getNodeWorkflow(args.workflow_id);
+ if (!workflow) {
+ return { success: false, error: `Workflow '${args.workflow_id}' not found` };
+ }
+
+ const nodes = workflow.nodes || [];
+ const edges = workflow.edges || [];
+
+ // Find the last node (no outgoing edges)
+ const lastNodes = nodes.filter(n => !edges.some(e => e.source === n.id));
+ const lastNode = lastNodes[lastNodes.length - 1];
+ const lastNodeType = lastNode?.parameters?.nodeType || lastNode?.type || '';
+
+ // Analyze workflow state
+ const hasTrigger = nodes.some(n =>
+ (n.type || '').toLowerCase().includes('trigger') ||
+ (n.parameters?.nodeType || '').toLowerCase().includes('trigger')
+ );
+ const hasDataSource = nodes.some(n =>
+ (n.type || '').includes('data-source') ||
+ ['yfinance', 'getQuote', 'getHistoricalData'].includes(n.parameters?.nodeType || '')
+ );
+ const hasIndicators = nodes.some(n =>
+ (n.type || '').includes('indicator') ||
+ n.parameters?.nodeType === 'technicalIndicators'
+ );
+ const hasCondition = nodes.some(n =>
+ n.parameters?.nodeType === 'ifElse' || n.parameters?.nodeType === 'switch'
+ );
+ const hasNotification = nodes.some(n =>
+ ['telegram', 'discord', 'slack', 'email', 'webhook'].includes(n.parameters?.nodeType || '')
+ );
+ const hasTrading = nodes.some(n =>
+ ['placeOrder', 'riskCheck'].includes(n.parameters?.nodeType || '')
+ );
+
+ // Build suggestions based on state
+ const suggestions: Array<{ node: string; reason: string; priority: number }> = [];
+
+ if (nodes.length === 0) {
+ suggestions.push({ node: 'manualTrigger', reason: 'Start with a trigger to define when the workflow runs', priority: 1 });
+ suggestions.push({ node: 'scheduleTrigger', reason: 'Or use schedule trigger for automated runs', priority: 2 });
+ } else if (!hasTrigger) {
+ suggestions.push({ node: 'manualTrigger', reason: 'Add a trigger so the workflow can be started', priority: 1 });
+ } else if (!hasDataSource) {
+ suggestions.push({ node: 'yfinance', reason: 'Add a data source to fetch market data', priority: 1 });
+ } else if (!hasIndicators && hasDataSource) {
+ suggestions.push({ node: 'technicalIndicators', reason: 'Add technical indicators (RSI, MACD, SMA) for analysis', priority: 1 });
+ suggestions.push({ node: 'riskAnalysis', reason: 'Or add risk metrics calculation', priority: 2 });
+ } else if (!hasCondition && hasIndicators) {
+ suggestions.push({ node: 'ifElse', reason: 'Add a condition to decide when to take action (e.g., RSI < 30)', priority: 1 });
+ } else if (hasCondition && !hasNotification && !hasTrading) {
+ suggestions.push({ node: 'telegram', reason: 'Add notification to alert you when condition is met', priority: 1 });
+ suggestions.push({ node: 'placeOrder', reason: 'Or add trading node to execute trades (with risk check)', priority: 2 });
+ } else if (hasCondition && !hasTrading) {
+ suggestions.push({ node: 'riskCheck', reason: 'Add risk check before placing orders', priority: 1 });
+ suggestions.push({ node: 'placeOrder', reason: 'Add order placement after risk check', priority: 2 });
+ } else {
+ suggestions.push({ node: 'resultsDisplay', reason: 'Add results display to visualize output', priority: 1 });
+ }
+
+ // Add goal-specific suggestions
+ if (args.goal) {
+ const goalLower = args.goal.toLowerCase();
+ if (goalLower.includes('alert') || goalLower.includes('notify')) {
+ suggestions.unshift({ node: 'telegram', reason: 'Goal mentions alerts - add Telegram notification', priority: 0 });
+ }
+ if (goalLower.includes('trade') || goalLower.includes('order') || goalLower.includes('buy') || goalLower.includes('sell')) {
+ suggestions.unshift({ node: 'riskCheck', reason: 'Goal mentions trading - add risk check first', priority: 0 });
+ }
+ if (goalLower.includes('backtest')) {
+ suggestions.unshift({ node: 'backtestEngine', reason: 'Goal mentions backtesting - add backtest engine', priority: 0 });
+ }
+ }
+
+ // Sort by priority and take top 3
+ suggestions.sort((a, b) => a.priority - b.priority);
+ const topSuggestions = suggestions.slice(0, 3);
+
+ return {
+ success: true,
+ data: {
+ suggestions: topSuggestions,
+ currentState: {
+ nodeCount: nodes.length,
+ hasTrigger,
+ hasDataSource,
+ hasIndicators,
+ hasCondition,
+ hasNotification,
+ hasTrading,
+ lastNode: lastNode?.label || lastNodeType,
+ },
+ },
+ message: `Suggested next nodes:\n${topSuggestions.map((s, i) => `${i + 1}. ${s.node}: ${s.reason}`).join('\n')}`,
+ };
+ },
+ },
+
+ {
+ name: 'node_editor_add_node_by_description',
+ description: `Add a node to a workflow using natural language description. Automatically determines the best node type and position.
+
+Examples:
+- "add RSI indicator" -> adds technicalIndicators node with RSI
+- "add price alert for AAPL at $200" -> adds ifElse with price condition
+- "send telegram notification" -> adds telegram node
+- "add risk check with max loss $500" -> adds riskCheck node`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ workflow_id: {
+ type: 'string',
+ description: 'The workflow ID to add the node to',
+ },
+ description: {
+ type: 'string',
+ description: 'Natural language description of what node to add (e.g., "add RSI indicator", "send telegram alert")',
+ },
+ connect_to_last: {
+ type: 'string',
+ description: 'Whether to connect the new node to the last node in the workflow',
+ enum: ['yes', 'no', ''],
+ },
+ },
+ required: ['workflow_id', 'description'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getNodeWorkflow || !contexts.addNodeToWorkflow || !contexts.connectNodes) {
+ return { success: false, error: 'Node editor context not available' };
+ }
+
+ const workflow = await contexts.getNodeWorkflow(args.workflow_id);
+ if (!workflow) {
+ return { success: false, error: `Workflow '${args.workflow_id}' not found` };
+ }
+
+ const desc = args.description.toLowerCase();
+ const nodes = workflow.nodes || [];
+ const edges = workflow.edges || [];
+
+ // Find last node for positioning and connection
+ const lastNodes = nodes.filter(n => !edges.some(e => e.source === n.id));
+ const lastNode = lastNodes[lastNodes.length - 1];
+ const lastX = lastNode?.position?.x ?? 100;
+ const lastY = lastNode?.position?.y ?? 100;
+
+ // Determine node type from description
+ let nodeType = 'custom';
+ let uiType = 'custom';
+ let label = '';
+ let params: Record<string, any> = {};
+
+ // RSI/MACD/SMA/EMA indicators
+ if (desc.includes('rsi')) {
+ nodeType = 'technicalIndicators';
+ uiType = 'technical-indicator';
+ label = 'RSI(14)';
+ params = { indicator: 'RSI', period: 14 };
+ } else if (desc.includes('macd')) {
+ nodeType = 'technicalIndicators';
+ uiType = 'technical-indicator';
+ label = 'MACD';
+ params = { indicator: 'MACD', period: 12 };
+ } else if (desc.includes('sma') || desc.includes('moving average')) {
+ nodeType = 'technicalIndicators';
+ uiType = 'technical-indicator';
+ label = 'SMA(20)';
+ params = { indicator: 'SMA', period: 20 };
+ } else if (desc.includes('ema')) {
+ nodeType = 'technicalIndicators';
+ uiType = 'technical-indicator';
+ label = 'EMA(9)';
+ params = { indicator: 'EMA', period: 9 };
+ } else if (desc.includes('bollinger') || desc.includes('bb')) {
+ nodeType = 'technicalIndicators';
+ uiType = 'technical-indicator';
+ label = 'Bollinger Bands';
+ params = { indicator: 'BB', period: 20 };
+ }
+ // Data sources
+ else if (desc.includes('stock data') || desc.includes('fetch') || desc.includes('yfinance') || desc.includes('historical')) {
+ nodeType = 'yfinance';
+ uiType = 'data-source';
+ label = 'Stock Data';
+ params = { operation: 'history', period: '1mo', interval: '1d' };
+ // Extract symbol if mentioned
+ const symbolMatch = desc.match(/\b([A-Z]{1,5})\b/);
+ if (symbolMatch) {
+ params.symbol = symbolMatch[1];
+ label = `${symbolMatch[1]} Data`;
+ }
+ } else if (desc.includes('quote') || desc.includes('price')) {
+ nodeType = 'yfinance';
+ uiType = 'data-source';
+ label = 'Get Quote';
+ params = { operation: 'quote' };
+ }
+ // Conditions
+ else if (desc.includes('if') || desc.includes('condition') || desc.includes('check') || desc.includes('when')) {
+ nodeType = 'ifElse';
+ uiType = 'custom';
+ label = 'Condition';
+ params = { condition: '{{$json.value}} > 0' };
+ }
+ // Notifications
+ else if (desc.includes('telegram')) {
+ nodeType = 'telegram';
+ uiType = 'custom';
+ label = 'Telegram Alert';
+ params = { message: 'Alert triggered!' };
+ } else if (desc.includes('discord')) {
+ nodeType = 'discord';
+ uiType = 'custom';
+ label = 'Discord Alert';
+ params = { message: 'Alert triggered!' };
+ } else if (desc.includes('slack')) {
+ nodeType = 'slack';
+ uiType = 'custom';
+ label = 'Slack Alert';
+ params = { message: 'Alert triggered!' };
+ } else if (desc.includes('email')) {
+ nodeType = 'email';
+ uiType = 'custom';
+ label = 'Email Alert';
+ params = { subject: 'Alert', message: 'Alert triggered!' };
+ } else if (desc.includes('notification') || desc.includes('alert')) {
+ nodeType = 'telegram';
+ uiType = 'custom';
+ label = 'Notification';
+ params = { message: 'Alert triggered!' };
+ }
+ // Trading
+ else if (desc.includes('order') || desc.includes('buy') || desc.includes('sell') || desc.includes('trade')) {
+ nodeType = 'placeOrder';
+ uiType = 'custom';
+ label = desc.includes('buy') ? 'Buy Order' : desc.includes('sell') ? 'Sell Order' : 'Place Order';
+ params = {
+ side: desc.includes('buy') ? 'BUY' : 'SELL',
+ orderType: 'MARKET',
+ quantity: 1,
+ paperTrading: true,
+ };
+ } else if (desc.includes('risk')) {
+ nodeType = 'riskCheck';
+ uiType = 'custom';
+ label = 'Risk Check';
+ params = { maxPositionSize: 1000, maxDailyLoss: 500 };
+ // Extract numbers if mentioned
+ const lossMatch = desc.match(/\$?(\d+)/);
+ if (lossMatch) {
+ params.maxDailyLoss = parseInt(lossMatch[1]);
+ }
+ }
+ // Triggers
+ else if (desc.includes('trigger') || desc.includes('start')) {
+ if (desc.includes('schedule') || desc.includes('cron') || desc.includes('daily') || desc.includes('hourly')) {
+ nodeType = 'scheduleTrigger';
+ uiType = 'system';
+ label = 'Schedule Trigger';
+ params = { cronExpression: '0 9 * * 1-5' };
+ } else {
+ nodeType = 'manualTrigger';
+ uiType = 'system';
+ label = 'Manual Start';
+ params = {};
+ }
+ }
+ // Backtest
+ else if (desc.includes('backtest')) {
+ nodeType = 'backtestEngine';
+ uiType = 'backtest';
+ label = 'Backtest';
+ params = {};
+ }
+ // Results
+ else if (desc.includes('result') || desc.includes('output') || desc.includes('display')) {
+ nodeType = 'resultsDisplay';
+ uiType = 'results-display';
+ label = 'Results';
+ params = { displayFormat: 'table' };
+ }
+ // Default: custom node with the description as label
+ else {
+ label = args.description.slice(0, 30);
+ }
+
+ // Generate node ID
+ const nodeId = `${nodeType}_${Date.now()}`;
+
+ // Calculate position (to the right of last node)
+ const position = {
+ x: lastX + 280,
+ y: lastY,
+ };
+
+ // Add the node
+ const result = await contexts.addNodeToWorkflow({
+ workflowId: args.workflow_id,
+ nodeId,
+ nodeType: uiType,
+ position,
+ parameters: {
+ nodeType,
+ color: getNodeColor(nodeType),
+ ...params,
+ },
+ label,
+ });
+
+ // Connect to last node if requested
+ if (args.connect_to_last !== 'no' && lastNode) {
+ await contexts.connectNodes({
+ workflowId: args.workflow_id,
+ sourceNodeId: lastNode.id,
+ targetNodeId: nodeId,
+ });
+ }
+
+ return {
+ success: true,
+ data: {
+ nodeId,
+ nodeType,
+ label,
+ position,
+ connectedTo: lastNode?.id,
+ },
+ message: `Added "${label}" (${nodeType}) to workflow${lastNode ? ` and connected to "${lastNode.label || lastNode.id}"` : ''}`,
+ };
+ },
+ },
+
+ // ============================================================================
+ // QUICK WORKFLOW EDITING TOOLS (Essential CRUD Operations)
+ // ============================================================================
+ {
+ name: 'node_editor_remove_node',
+ description: `Remove a node from a workflow. Also removes all edges connected to this node.`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ workflow_id: {
+ type: 'string',
+ description: 'The workflow ID',
+ },
+ node_id: {
+ type: 'string',
+ description: 'ID of the node to remove',
+ },
+ },
+ required: ['workflow_id', 'node_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.removeNodeFromWorkflow) {
+ return { success: false, error: 'Node editor context not available' };
+ }
+
+ const result = await contexts.removeNodeFromWorkflow(args.workflow_id, args.node_id);
+ return {
+ success: true,
+ data: result,
+ message: `Node '${args.node_id}' removed from workflow`,
+ };
+ },
+ },
+
+ {
+ name: 'node_editor_disconnect_nodes',
+ description: `Remove the connection (edge) between two nodes.`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ workflow_id: {
+ type: 'string',
+ description: 'The workflow ID',
+ },
+ source_node_id: {
+ type: 'string',
+ description: 'ID of the source node',
+ },
+ target_node_id: {
+ type: 'string',
+ description: 'ID of the target node',
+ },
+ source_handle: {
+ type: 'string',
+ description: 'Optional: specific output handle to disconnect',
+ },
+ },
+ required: ['workflow_id', 'source_node_id', 'target_node_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.disconnectNodes) {
+ return { success: false, error: 'Node editor context not available' };
+ }
+
+ const result = await contexts.disconnectNodes({
+ workflowId: args.workflow_id,
+ sourceNodeId: args.source_node_id,
+ targetNodeId: args.target_node_id,
+ sourceHandle: args.source_handle,
+ });
+
+ return {
+ success: true,
+ data: result,
+ message: `Disconnected '${args.source_node_id}' from '${args.target_node_id}'`,
+ };
+ },
+ },
+
+ {
+ name: 'node_editor_rename_node',
+ description: `Change the display label of a node in a workflow.`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ workflow_id: {
+ type: 'string',
+ description: 'The workflow ID',
+ },
+ node_id: {
+ type: 'string',
+ description: 'ID of the node to rename',
+ },
+ new_label: {
+ type: 'string',
+ description: 'New display label for the node',
+ },
+ },
+ required: ['workflow_id', 'node_id', 'new_label'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.renameNode) {
+ return { success: false, error: 'Node editor context not available' };
+ }
+
+ const result = await contexts.renameNode(args.workflow_id, args.node_id, args.new_label);
+ return {
+ success: true,
+ data: result,
+ message: `Node '${args.node_id}' renamed to "${args.new_label}"`,
+ };
+ },
+ },
+
+ {
+ name: 'node_editor_clear_workflow',
+ description: `Remove all nodes and edges from a workflow, keeping only the workflow metadata. Use this to start fresh.`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ workflow_id: {
+ type: 'string',
+ description: 'The workflow ID to clear',
+ },
+ },
+ required: ['workflow_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.clearWorkflow) {
+ return { success: false, error: 'Node editor context not available' };
+ }
+
+ const result = await contexts.clearWorkflow(args.workflow_id);
+ return {
+ success: true,
+ data: result,
+ message: `Workflow '${args.workflow_id}' cleared - all nodes and edges removed`,
+ };
+ },
+ },
+
+ {
+ name: 'node_editor_clone_node',
+ description: `Create a duplicate of an existing node in the workflow. The clone is placed to the right of the original.`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ workflow_id: {
+ type: 'string',
+ description: 'The workflow ID',
+ },
+ node_id: {
+ type: 'string',
+ description: 'ID of the node to clone',
+ },
+ new_label: {
+ type: 'string',
+ description: 'Optional: label for the cloned node (defaults to "Copy of [original]")',
+ },
+ },
+ required: ['workflow_id', 'node_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.cloneNode) {
+ return { success: false, error: 'Node editor context not available' };
+ }
+
+ const result = await contexts.cloneNode(args.workflow_id, args.node_id, args.new_label);
+ return {
+ success: true,
+ data: result,
+ message: `Node '${args.node_id}' cloned as '${result.newNodeId}'`,
+ };
+ },
+ },
+
+ {
+ name: 'node_editor_move_node',
+ description: `Move/reposition a node in the workflow canvas. Accepts absolute coordinates or relative directions.`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ workflow_id: {
+ type: 'string',
+ description: 'The workflow ID',
+ },
+ node_id: {
+ type: 'string',
+ description: 'ID of the node to move',
+ },
+ x: {
+ type: 'number',
+ description: 'New X position (absolute) or offset if relative=true',
+ },
+ y: {
+ type: 'number',
+ description: 'New Y position (absolute) or offset if relative=true',
+ },
+ relative: {
+ type: 'string',
+ description: 'If "yes", x and y are offsets from current position (e.g., x=100 moves 100px right)',
+ enum: ['yes', 'no', ''],
+ },
+ direction: {
+ type: 'string',
+ description: 'Alternative: move in a direction with default offset (50px)',
+ enum: ['up', 'down', 'left', 'right', ''],
+ },
+ },
+ required: ['workflow_id', 'node_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.moveNode) {
+ return { success: false, error: 'Node editor context not available' };
+ }
+
+ const result = await contexts.moveNode({
+ workflowId: args.workflow_id,
+ nodeId: args.node_id,
+ x: args.x,
+ y: args.y,
+ relative: args.relative === 'yes',
+ direction: args.direction,
+ });
+
+ return {
+ success: true,
+ data: result,
+ message: `Node '${args.node_id}' moved to position (${result.newPosition.x}, ${result.newPosition.y})`,
+ };
+ },
+ },
+
+ {
+ name: 'node_editor_get_workflow_stats',
+ description: `Get execution statistics for a workflow: run count, last run time, success rate, average duration.`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ workflow_id: {
+ type: 'string',
+ description: 'The workflow ID',
+ },
+ },
+ required: ['workflow_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getWorkflowStats) {
+ return { success: false, error: 'Node editor context not available' };
+ }
+
+ const stats = await contexts.getWorkflowStats(args.workflow_id);
+ return {
+ success: true,
+ data: stats,
+ message: `Workflow stats: ${stats.totalRuns} runs, ${stats.successRate}% success rate, last run: ${stats.lastRunAt || 'never'}`,
+ };
+ },
+ },
+
+ {
+ name: 'node_editor_auto_layout',
+ description: `Automatically reorganize node positions for better visual clarity. Uses left-to-right flow layout.`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ workflow_id: {
+ type: 'string',
+ description: 'The workflow ID to auto-layout',
+ },
+ direction: {
+ type: 'string',
+ description: 'Layout direction: horizontal (left-to-right, default), vertical (top-to-bottom)',
+ enum: ['horizontal', 'vertical', ''],
+ },
+ spacing_x: {
+ type: 'number',
+ description: 'Horizontal spacing between nodes (default: 250)',
+ },
+ spacing_y: {
+ type: 'number',
+ description: 'Vertical spacing between nodes (default: 100)',
+ },
+ },
+ required: ['workflow_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.autoLayoutWorkflow) {
+ return { success: false, error: 'Node editor context not available' };
+ }
+
+ const result = await contexts.autoLayoutWorkflow({
+ workflowId: args.workflow_id,
+ direction: args.direction || 'horizontal',
+ spacingX: args.spacing_x || 250,
+ spacingY: args.spacing_y || 100,
+ });
+
+ return {
+ success: true,
+ data: result,
+ message: `Workflow auto-arranged: ${result.nodesRepositioned} nodes repositioned`,
+ };
+ },
+ },
];
+
+// Helper function for node colors (used by add_node_by_description)
+function getNodeColor(nodeType: string): string {
+ const colorMap: Record<string, string> = {
+ manualTrigger: '#10b981',
+ scheduleTrigger: '#a855f7',
+ yfinance: '#3b82f6',
+ technicalIndicators: '#10b981',
+ ifElse: '#eab308',
+ telegram: '#f97316',
+ discord: '#f97316',
+ slack: '#f97316',
+ email: '#f97316',
+ placeOrder: '#14b8a6',
+ riskCheck: '#ef4444',
+ backtestEngine: '#06b6d4',
+ resultsDisplay: '#f59e0b',
+ };
+ return colorMap[nodeType] || '#6b7280';
+}
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/portfolio.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/portfolio.ts
index f4cc3db76..b9e0b5c28 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/tools/portfolio.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/portfolio.ts
@@ -1,15 +1,20 @@
+// Portfolio MCP Tools - Comprehensive Portfolio Management via MCP
+// Exposes all portfolio functionality: CRUD, assets, transactions, analytics, optimization
+
import { InternalTool } from '../types';
export const portfolioTools: InternalTool[] = [
+ // ==================== PORTFOLIO CRUD ====================
{
name: 'create_portfolio',
- description: 'Create a new portfolio for tracking investments',
+ description: 'Create a new investment portfolio for tracking holdings and performance',
inputSchema: {
type: 'object',
properties: {
- name: { type: 'string', description: 'Portfolio name' },
- currency: { type: 'string', description: 'Base currency (e.g., USD, EUR, INR)' },
- description: { type: 'string', description: 'Portfolio description' },
+ name: { type: 'string', description: 'Portfolio name (e.g., "Tech Growth", "Dividend Income")' },
+ currency: { type: 'string', description: 'Base currency (USD, EUR, INR, GBP, etc.)', default: 'USD' },
+ description: { type: 'string', description: 'Optional portfolio description or investment thesis' },
+ owner: { type: 'string', description: 'Portfolio owner name', default: 'User' },
},
required: ['name'],
},
@@ -17,78 +22,249 @@ export const portfolioTools: InternalTool[] = [
if (!contexts.createPortfolio) {
return { success: false, error: 'Portfolio context not available' };
}
- const result = await contexts.createPortfolio(args);
- return { success: true, data: result, message: `Portfolio "${args.name}" created` };
+ const result = await contexts.createPortfolio({
+ name: args.name,
+ owner: args.owner || 'User',
+ currency: args.currency || 'USD',
+ description: args.description,
+ });
+ return { success: true, data: result, message: `Portfolio "${args.name}" created successfully` };
},
},
{
name: 'list_portfolios',
- description: 'List all portfolios',
+ description: 'List all portfolios with names and basic info. NOTE: Use get_all_portfolios_with_holdings instead to see stocks/holdings inside portfolios.',
inputSchema: {
type: 'object',
properties: {},
},
handler: async (_args, contexts) => {
- if (!contexts.getPortfolios) {
+ if (!contexts.getPortfolios || !contexts.getPortfolioAssets) {
return { success: false, error: 'Portfolio context not available' };
}
const portfolios = await contexts.getPortfolios();
- return { success: true, data: portfolios };
+
+ if (portfolios.length === 0) {
+ return {
+ success: true,
+ data: { portfolios: [], count: 0 },
+ message: 'No portfolios found. Create one with create_portfolio.',
+ };
+ }
+
+ // Get asset counts for each portfolio
+ const portfoliosWithCounts = await Promise.all(
+ portfolios.map(async (p: any) => {
+ try {
+ const assets = await contexts.getPortfolioAssets!(p.id);
+ return {
+ id: p.id,
+ name: p.name,
+ currency: p.currency || 'USD',
+ description: p.description || '',
+ created_at: p.created_at,
+ holdings_count: assets.length,
+ symbols: assets.map((a: any) => a.symbol),
+ };
+ } catch {
+ return {
+ id: p.id,
+ name: p.name,
+ currency: p.currency || 'USD',
+ holdings_count: 0,
+ symbols: [],
+ };
+ }
+ })
+ );
+
+ // Build message
+ let message = `Found ${portfolios.length} portfolio(s):\n\n`;
+ portfoliosWithCounts.forEach((p: any) => {
+ message += `• "${p.name}" (${p.currency})\n`;
+ message += ` ID: ${p.id}\n`;
+ message += ` Holdings: ${p.holdings_count} stock(s)`;
+ if (p.symbols.length > 0) {
+ message += ` - ${p.symbols.join(', ')}`;
+ }
+ message += '\n\n';
+ });
+
+ message += `TIP: Use get_all_portfolios_with_holdings or get_portfolio_summary to see detailed values and P&L.`;
+
+ return {
+ success: true,
+ data: {
+ portfolios: portfoliosWithCounts,
+ count: portfolios.length,
+ },
+ message,
+ };
+ },
+ },
+ {
+ name: 'get_portfolio',
+ description: 'Get details of a specific portfolio by ID',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_id: { type: 'string', description: 'Portfolio ID' },
+ },
+ required: ['portfolio_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getPortfolio) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+ const portfolio = await contexts.getPortfolio(args.portfolio_id);
+ if (!portfolio) {
+ return { success: false, error: 'Portfolio not found' };
+ }
+ return { success: true, data: portfolio };
+ },
+ },
+ {
+ name: 'delete_portfolio',
+ description: 'Delete a portfolio and all its associated data (holdings, transactions)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_id: { type: 'string', description: 'Portfolio ID to delete' },
+ },
+ required: ['portfolio_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.deletePortfolio) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+ await contexts.deletePortfolio(args.portfolio_id);
+ return { success: true, message: 'Portfolio deleted successfully' };
},
},
+
+ // ==================== ASSET MANAGEMENT ====================
{
name: 'add_asset',
- description: 'Add an asset/holding to a portfolio',
+ description: 'Add a new asset/holding to a portfolio (records a buy transaction)',
inputSchema: {
type: 'object',
properties: {
portfolio_id: { type: 'string', description: 'Portfolio ID' },
- symbol: { type: 'string', description: 'Asset symbol (e.g., AAPL)' },
- quantity: { type: 'number', description: 'Number of shares/units' },
- avg_buy_price: { type: 'number', description: 'Average purchase price per unit' },
+ symbol: { type: 'string', description: 'Asset symbol (e.g., AAPL, MSFT, RELIANCE.NS)' },
+ quantity: { type: 'number', description: 'Number of shares/units to buy' },
+ buy_price: { type: 'number', description: 'Purchase price per share/unit' },
},
- required: ['portfolio_id', 'symbol', 'quantity', 'avg_buy_price'],
+ required: ['portfolio_id', 'symbol', 'quantity', 'buy_price'],
},
handler: async (args, contexts) => {
if (!contexts.addAsset) {
return { success: false, error: 'Portfolio context not available' };
}
- const { portfolio_id, ...asset } = args;
- const result = await contexts.addAsset(portfolio_id, asset);
- return { success: true, data: result, message: `Added ${args.quantity} ${args.symbol} to portfolio` };
+ const result = await contexts.addAsset(args.portfolio_id, {
+ symbol: args.symbol,
+ quantity: args.quantity,
+ avg_buy_price: args.buy_price,
+ });
+ const totalCost = args.quantity * args.buy_price;
+ return {
+ success: true,
+ data: result,
+ message: `Added ${args.quantity} shares of ${args.symbol.toUpperCase()} @ $${args.buy_price} (Total: $${totalCost.toFixed(2)})`,
+ };
+ },
+ },
+ {
+ name: 'sell_asset',
+ description: 'Sell shares of an asset from a portfolio (partial or full)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_id: { type: 'string', description: 'Portfolio ID' },
+ symbol: { type: 'string', description: 'Asset symbol to sell' },
+ quantity: { type: 'number', description: 'Number of shares/units to sell' },
+ sell_price: { type: 'number', description: 'Selling price per share/unit' },
+ },
+ required: ['portfolio_id', 'symbol', 'quantity', 'sell_price'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.sellAsset) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+ await contexts.sellAsset(args.portfolio_id, args.symbol, args.quantity, args.sell_price);
+ const totalProceeds = args.quantity * args.sell_price;
+ return {
+ success: true,
+ message: `Sold ${args.quantity} shares of ${args.symbol.toUpperCase()} @ $${args.sell_price} (Proceeds: $${totalProceeds.toFixed(2)})`,
+ };
},
},
{
name: 'remove_asset',
- description: 'Remove an asset from a portfolio',
+ description: 'Remove an asset completely from portfolio (sells all shares at current market price)',
inputSchema: {
type: 'object',
properties: {
portfolio_id: { type: 'string', description: 'Portfolio ID' },
- asset_id: { type: 'string', description: 'Asset ID to remove' },
+ symbol: { type: 'string', description: 'Asset symbol to remove' },
+ sell_price: { type: 'number', description: 'Optional: Selling price per share. If not provided, uses current market price' },
},
- required: ['portfolio_id', 'asset_id'],
+ required: ['portfolio_id', 'symbol'],
},
handler: async (args, contexts) => {
if (!contexts.removeAsset) {
return { success: false, error: 'Portfolio context not available' };
}
- await contexts.removeAsset(args.portfolio_id, args.asset_id);
- return { success: true, message: `Asset removed from portfolio` };
+ await contexts.removeAsset(args.portfolio_id, args.symbol, args.sell_price);
+ return { success: true, message: `Removed all shares of ${args.symbol.toUpperCase()} from portfolio` };
+ },
+ },
+ {
+ name: 'get_portfolio_assets',
+ description: 'Get all assets/holdings in a portfolio with quantities and average costs',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_id: { type: 'string', description: 'Portfolio ID' },
+ },
+ required: ['portfolio_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getPortfolioAssets) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+ const assets = await contexts.getPortfolioAssets(args.portfolio_id);
+
+ // Build message with asset details
+ let message = `Portfolio has ${assets.length} asset(s)`;
+ if (assets.length > 0) {
+ message += ':\n';
+ assets.forEach((a: any) => {
+ message += `- ${a.symbol}: ${a.quantity} shares @ avg cost $${a.avg_buy_price?.toFixed(2)}\n`;
+ });
+ }
+
+ return {
+ success: true,
+ data: assets,
+ message,
+ };
},
},
+
+ // ==================== TRANSACTIONS ====================
{
name: 'add_transaction',
- description: 'Record a transaction (buy, sell, dividend) in a portfolio',
+ description: 'Record a transaction (buy, sell, dividend, or split) in a portfolio',
inputSchema: {
type: 'object',
properties: {
portfolio_id: { type: 'string', description: 'Portfolio ID' },
- type: { type: 'string', description: 'Transaction type', enum: ['buy', 'sell', 'dividend'] },
+ type: { type: 'string', description: 'Transaction type', enum: ['buy', 'sell', 'dividend', 'split'] },
symbol: { type: 'string', description: 'Asset symbol' },
quantity: { type: 'number', description: 'Number of shares/units' },
price: { type: 'number', description: 'Price per unit' },
- date: { type: 'string', description: 'Transaction date (YYYY-MM-DD)' },
+ date: { type: 'string', description: 'Transaction date (YYYY-MM-DD format)' },
+ notes: { type: 'string', description: 'Optional notes about the transaction' },
},
required: ['portfolio_id', 'type', 'symbol', 'quantity', 'price'],
},
@@ -98,12 +274,201 @@ export const portfolioTools: InternalTool[] = [
}
const { portfolio_id, ...tx } = args;
const result = await contexts.addTransaction(portfolio_id, tx);
- return { success: true, data: result, message: `${args.type} transaction recorded: ${args.quantity} ${args.symbol} @ ${args.price}` };
+ return {
+ success: true,
+ data: result,
+ message: `Recorded ${args.type.toUpperCase()} transaction: ${args.quantity} ${args.symbol} @ $${args.price}`,
+ };
+ },
+ },
+ {
+ name: 'get_portfolio_transactions',
+ description: 'Get transaction history for a portfolio',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_id: { type: 'string', description: 'Portfolio ID' },
+ limit: { type: 'number', description: 'Maximum number of transactions to return', default: 100 },
+ },
+ required: ['portfolio_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getPortfolioTransactions) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+ const transactions = await contexts.getPortfolioTransactions(args.portfolio_id, args.limit || 100);
+ return {
+ success: true,
+ data: transactions,
+ message: `Found ${transactions.length} transaction(s)`,
+ };
+ },
+ },
+ {
+ name: 'get_symbol_transactions',
+ description: 'Get all transactions for a specific symbol in a portfolio',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_id: { type: 'string', description: 'Portfolio ID' },
+ symbol: { type: 'string', description: 'Asset symbol to filter by' },
+ },
+ required: ['portfolio_id', 'symbol'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getSymbolTransactions) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+ const transactions = await contexts.getSymbolTransactions(args.portfolio_id, args.symbol);
+ return {
+ success: true,
+ data: transactions,
+ message: `Found ${transactions.length} transaction(s) for ${args.symbol.toUpperCase()}`,
+ };
},
},
+
+ // ==================== COMPREHENSIVE VIEWS ====================
+ {
+ name: 'get_my_stocks',
+ description: 'Get ALL stocks/holdings across all portfolios with current prices, values, and P&L. USE THIS to answer: "what stocks do I have?", "show my positions", "what is my portfolio?", "what am I holding?", "my investments"',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.getPortfolios || !contexts.getPortfolioSummary) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+
+ const portfolios = await contexts.getPortfolios();
+ if (portfolios.length === 0) {
+ return {
+ success: true,
+ data: { portfolios: [], total_value: 0 },
+ message: 'No portfolios found. Create one with create_portfolio.',
+ };
+ }
+
+ // Fetch summary for each portfolio with COMPLETE data
+ const portfolioDetails = await Promise.all(
+ portfolios.map(async (p: any) => {
+ try {
+ const summary = await contexts.getPortfolioSummary!(p.id);
+ return {
+ portfolio_id: p.id,
+ portfolio_name: p.name,
+ currency: p.currency || 'USD',
+ description: p.description || '',
+ created_at: p.created_at,
+ // Portfolio totals
+ total_market_value: summary.total_market_value,
+ total_cost_basis: summary.total_cost_basis,
+ total_unrealized_pnl: summary.total_unrealized_pnl,
+ total_unrealized_pnl_percent: summary.total_unrealized_pnl_percent,
+ total_day_change: summary.total_day_change,
+ total_day_change_percent: summary.total_day_change_percent,
+ total_positions: summary.holdings?.length || 0,
+ last_updated: summary.last_updated,
+ // Complete holdings with all metrics
+ holdings: summary.holdings?.map((h: any) => ({
+ symbol: h.symbol,
+ quantity: h.quantity,
+ average_buy_price: h.avg_buy_price,
+ current_price: h.current_price,
+ market_value: h.market_value,
+ cost_basis: h.cost_basis,
+ unrealized_pnl: h.unrealized_pnl,
+ unrealized_pnl_percent: h.unrealized_pnl_percent,
+ day_change: h.day_change,
+ day_change_percent: h.day_change_percent,
+ portfolio_weight_percent: h.weight,
+ first_purchase_date: h.first_purchase_date,
+ })) || [],
+ };
+ } catch (err) {
+ return {
+ portfolio_id: p.id,
+ portfolio_name: p.name,
+ currency: p.currency || 'USD',
+ error: `Failed to fetch: ${err}`,
+ holdings: [],
+ };
+ }
+ })
+ );
+
+ // Calculate grand totals
+ let grandTotalValue = 0;
+ let grandTotalCost = 0;
+ let grandTotalPnL = 0;
+ let totalStocks = 0;
+
+ portfolioDetails.forEach((p: any) => {
+ if (!p.error) {
+ grandTotalValue += p.total_market_value || 0;
+ grandTotalCost += p.total_cost_basis || 0;
+ grandTotalPnL += p.total_unrealized_pnl || 0;
+ totalStocks += p.holdings?.length || 0;
+ }
+ });
+
+ const grandTotalPnLPercent = grandTotalCost > 0 ? (grandTotalPnL / grandTotalCost) * 100 : 0;
+
+ // Build comprehensive message for AI context
+ let message = `=== PORTFOLIO OVERVIEW ===\n`;
+ message += `Total Portfolios: ${portfolios.length}\n`;
+ message += `Total Stocks Held: ${totalStocks}\n`;
+ message += `Grand Total Value: $${grandTotalValue.toFixed(2)}\n`;
+ message += `Grand Total Cost: $${grandTotalCost.toFixed(2)}\n`;
+ message += `Grand Total P&L: $${grandTotalPnL.toFixed(2)} (${grandTotalPnLPercent >= 0 ? '+' : ''}${grandTotalPnLPercent.toFixed(2)}%)\n\n`;
+
+ portfolioDetails.forEach((p: any) => {
+ message += `--- ${p.portfolio_name} (${p.currency}) ---\n`;
+ if (p.error) {
+ message += `Error: ${p.error}\n\n`;
+ return;
+ }
+
+ message += `Value: $${p.total_market_value?.toFixed(2)} | Cost: $${p.total_cost_basis?.toFixed(2)} | P&L: ${p.total_unrealized_pnl >= 0 ? '+' : ''}$${p.total_unrealized_pnl?.toFixed(2)} (${p.total_unrealized_pnl_percent?.toFixed(2)}%)\n`;
+ message += `Day Change: ${p.total_day_change >= 0 ? '+' : ''}$${p.total_day_change?.toFixed(2)} (${p.total_day_change_percent?.toFixed(2)}%)\n`;
+
+ if (p.holdings && p.holdings.length > 0) {
+ message += `\nHoldings (${p.holdings.length} stocks):\n`;
+ p.holdings.forEach((h: any) => {
+ const pnlSign = h.unrealized_pnl >= 0 ? '+' : '';
+ message += ` ${h.symbol}: ${h.quantity} shares\n`;
+ message += ` Buy: $${h.average_buy_price?.toFixed(2)} | Now: $${h.current_price?.toFixed(2)} | Value: $${h.market_value?.toFixed(2)}\n`;
+ message += ` P&L: ${pnlSign}$${h.unrealized_pnl?.toFixed(2)} (${pnlSign}${h.unrealized_pnl_percent?.toFixed(1)}%) | Weight: ${h.portfolio_weight_percent?.toFixed(1)}%\n`;
+ });
+ } else {
+ message += `No holdings in this portfolio.\n`;
+ }
+ message += `\n`;
+ });
+
+ return {
+ success: true,
+ data: {
+ summary: {
+ total_portfolios: portfolios.length,
+ total_stocks: totalStocks,
+ grand_total_value: grandTotalValue,
+ grand_total_cost: grandTotalCost,
+ grand_total_pnl: grandTotalPnL,
+ grand_total_pnl_percent: grandTotalPnLPercent,
+ },
+ portfolios: portfolioDetails,
+ },
+ message,
+ };
+ },
+ },
+
+ // ==================== SUMMARY & ANALYTICS ====================
{
name: 'get_portfolio_summary',
- description: 'Get portfolio summary with metrics, P&L, and allocation breakdown',
+ description: 'Get comprehensive portfolio summary with holdings, current prices, P&L, day changes, and allocation weights for a specific portfolio',
inputSchema: {
type: 'object',
properties: {
@@ -116,7 +481,280 @@ export const portfolioTools: InternalTool[] = [
return { success: false, error: 'Portfolio context not available' };
}
const summary = await contexts.getPortfolioSummary(args.portfolio_id);
- return { success: true, data: summary };
+
+ // Transform holdings to include all relevant data with clear names
+ const enrichedHoldings = summary.holdings?.map((h: any) => ({
+ symbol: h.symbol,
+ quantity: h.quantity,
+ average_buy_price: h.avg_buy_price,
+ current_price: h.current_price,
+ market_value: h.market_value,
+ cost_basis: h.cost_basis,
+ unrealized_pnl: h.unrealized_pnl,
+ unrealized_pnl_percent: h.unrealized_pnl_percent,
+ day_change: h.day_change,
+ day_change_percent: h.day_change_percent,
+ portfolio_weight_percent: h.weight,
+ first_purchase_date: h.first_purchase_date,
+ })) || [];
+
+ // Build detailed message with all data
+ const pName = summary.portfolio?.name || 'Portfolio';
+ let message = `=== ${pName} ===\n`;
+ message += `Currency: ${summary.portfolio?.currency || 'USD'}\n`;
+ message += `Total Market Value: $${summary.total_market_value?.toFixed(2)}\n`;
+ message += `Total Cost Basis: $${summary.total_cost_basis?.toFixed(2)}\n`;
+ message += `Unrealized P&L: ${summary.total_unrealized_pnl >= 0 ? '+' : ''}$${summary.total_unrealized_pnl?.toFixed(2)} (${summary.total_unrealized_pnl_percent?.toFixed(2)}%)\n`;
+ message += `Day Change: ${summary.total_day_change >= 0 ? '+' : ''}$${summary.total_day_change?.toFixed(2)} (${summary.total_day_change_percent?.toFixed(2)}%)\n`;
+ message += `Total Positions: ${summary.holdings?.length || 0}\n`;
+ message += `Last Updated: ${summary.last_updated}\n\n`;
+
+ if (enrichedHoldings.length > 0) {
+ message += `--- Holdings ---\n`;
+ enrichedHoldings.forEach((h: any) => {
+ const pnlSign = h.unrealized_pnl >= 0 ? '+' : '';
+ const daySign = h.day_change >= 0 ? '+' : '';
+ message += `\n${h.symbol}:\n`;
+ message += ` Shares: ${h.quantity} | Avg Cost: $${h.average_buy_price?.toFixed(2)} | Current: $${h.current_price?.toFixed(2)}\n`;
+ message += ` Value: $${h.market_value?.toFixed(2)} | Cost: $${h.cost_basis?.toFixed(2)}\n`;
+ message += ` P&L: ${pnlSign}$${h.unrealized_pnl?.toFixed(2)} (${pnlSign}${h.unrealized_pnl_percent?.toFixed(2)}%)\n`;
+ message += ` Day: ${daySign}$${h.day_change?.toFixed(2)} (${daySign}${h.day_change_percent?.toFixed(2)}%)\n`;
+ message += ` Weight: ${h.portfolio_weight_percent?.toFixed(1)}%\n`;
+ });
+ } else {
+ message += 'No holdings in this portfolio.\n';
+ }
+
+ return {
+ success: true,
+ data: {
+ portfolio: {
+ id: summary.portfolio?.id,
+ name: summary.portfolio?.name,
+ currency: summary.portfolio?.currency,
+ description: summary.portfolio?.description,
+ },
+ totals: {
+ market_value: summary.total_market_value,
+ cost_basis: summary.total_cost_basis,
+ unrealized_pnl: summary.total_unrealized_pnl,
+ unrealized_pnl_percent: summary.total_unrealized_pnl_percent,
+ day_change: summary.total_day_change,
+ day_change_percent: summary.total_day_change_percent,
+ positions_count: summary.holdings?.length || 0,
+ },
+ holdings: enrichedHoldings,
+ last_updated: summary.last_updated,
+ },
+ message,
+ };
+ },
+ },
+ {
+ name: 'calculate_advanced_metrics',
+ description: 'Calculate advanced portfolio metrics: Sharpe ratio, volatility, VaR, max drawdown, returns. Use for risk analysis.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_id: { type: 'string', description: 'Portfolio ID' },
+ },
+ required: ['portfolio_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.calculateAdvancedMetrics) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+ const metrics = await contexts.calculateAdvancedMetrics(args.portfolio_id);
+
+ // Format metrics with clear labels and interpretations
+ const sharpeInterpretation = metrics.sharpe_ratio > 1 ? 'Good' : metrics.sharpe_ratio > 0.5 ? 'Acceptable' : 'Poor';
+ const volatilityLevel = metrics.portfolio_volatility > 0.3 ? 'High' : metrics.portfolio_volatility > 0.15 ? 'Moderate' : 'Low';
+
+ let message = `=== Advanced Portfolio Metrics ===\n\n`;
+ message += `Sharpe Ratio: ${metrics.sharpe_ratio?.toFixed(3)} (${sharpeInterpretation})\n`;
+ message += ` - Measures risk-adjusted return. Higher is better. >1 is good, >2 is excellent.\n\n`;
+ message += `Portfolio Volatility: ${(metrics.portfolio_volatility * 100)?.toFixed(2)}% annualized (${volatilityLevel})\n`;
+ message += ` - Standard deviation of returns. Lower means more stable.\n\n`;
+ message += `Value at Risk (95%): ${(metrics.value_at_risk_95 * 100)?.toFixed(2)}%\n`;
+ message += ` - Maximum expected daily loss with 95% confidence.\n\n`;
+ message += `Max Drawdown: ${(metrics.max_drawdown * 100)?.toFixed(2)}%\n`;
+ message += ` - Largest peak-to-trough decline.\n\n`;
+ message += `Portfolio Return: ${(metrics.portfolio_return * 100)?.toFixed(2)}%\n`;
+ message += ` - Total return since inception.\n`;
+
+ return {
+ success: true,
+ data: {
+ sharpe_ratio: metrics.sharpe_ratio,
+ sharpe_interpretation: sharpeInterpretation,
+ portfolio_volatility: metrics.portfolio_volatility,
+ portfolio_volatility_percent: metrics.portfolio_volatility * 100,
+ volatility_level: volatilityLevel,
+ value_at_risk_95: metrics.value_at_risk_95,
+ value_at_risk_95_percent: metrics.value_at_risk_95 * 100,
+ max_drawdown: metrics.max_drawdown,
+ max_drawdown_percent: metrics.max_drawdown * 100,
+ portfolio_return: metrics.portfolio_return,
+ portfolio_return_percent: metrics.portfolio_return * 100,
+ },
+ message,
+ };
+ },
+ },
+ {
+ name: 'calculate_risk_metrics',
+ description: 'Calculate portfolio risk metrics including beta, Sharpe ratio, and drawdown analysis',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_id: { type: 'string', description: 'Portfolio ID' },
+ },
+ required: ['portfolio_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.calculateRiskMetrics) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+ const metrics = await contexts.calculateRiskMetrics(args.portfolio_id);
+ return {
+ success: true,
+ data: metrics,
+ message: 'Risk metrics calculated successfully',
+ };
+ },
+ },
+
+ // ==================== OPTIMIZATION ====================
+ {
+ name: 'optimize_portfolio',
+ description: 'Optimize portfolio weights using various methods (efficient frontier, max Sharpe, min volatility)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_id: { type: 'string', description: 'Portfolio ID' },
+ method: {
+ type: 'string',
+ description: 'Optimization method',
+ enum: ['max_sharpe', 'min_volatility', 'equal_weight', 'risk_parity'],
+ default: 'max_sharpe',
+ },
+ },
+ required: ['portfolio_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.optimizePortfolioWeights) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+ const result = await contexts.optimizePortfolioWeights(args.portfolio_id, args.method || 'max_sharpe');
+ return {
+ success: true,
+ data: result,
+ message: `Optimization complete using ${args.method || 'max_sharpe'} method. Expected Sharpe: ${result.sharpe_ratio?.toFixed(2) || 'N/A'}`,
+ };
+ },
+ },
+ {
+ name: 'get_rebalancing_recommendations',
+ description: 'Get recommendations to rebalance portfolio to target allocations',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_id: { type: 'string', description: 'Portfolio ID' },
+ target_allocations: {
+ type: 'string',
+ description: 'JSON string of target allocations (e.g., {"AAPL": 0.3, "MSFT": 0.3, "GOOGL": 0.4})',
+ },
+ },
+ required: ['portfolio_id', 'target_allocations'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getRebalancingRecommendations) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+ let targetAllocations: Record<string, number>;
+ try {
+ targetAllocations = JSON.parse(args.target_allocations);
+ } catch {
+ return { success: false, error: 'Invalid target_allocations JSON format' };
+ }
+ const recommendations = await contexts.getRebalancingRecommendations(args.portfolio_id, targetAllocations);
+ return {
+ success: true,
+ data: recommendations,
+ message: `Generated ${recommendations.length} rebalancing recommendation(s)`,
+ };
+ },
+ },
+
+ // ==================== ANALYSIS ====================
+ {
+ name: 'analyze_diversification',
+ description: 'Analyze portfolio diversification across sectors, asset classes, and geographies',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_id: { type: 'string', description: 'Portfolio ID' },
+ },
+ required: ['portfolio_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.analyzeDiversification) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+ const analysis = await contexts.analyzeDiversification(args.portfolio_id);
+ return {
+ success: true,
+ data: analysis,
+ message: 'Diversification analysis complete',
+ };
+ },
+ },
+ {
+ name: 'get_portfolio_performance_history',
+ description: 'Get historical portfolio performance data (value snapshots over time)',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_id: { type: 'string', description: 'Portfolio ID' },
+ days: { type: 'number', description: 'Number of days of history to retrieve', default: 30 },
+ },
+ required: ['portfolio_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.getPortfolioPerformanceHistory) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+ const history = await contexts.getPortfolioPerformanceHistory(args.portfolio_id, args.days || 30);
+ return {
+ success: true,
+ data: history,
+ message: `Retrieved ${history.length} historical data point(s)`,
+ };
+ },
+ },
+
+ // ==================== EXPORT ====================
+ {
+ name: 'export_portfolio_csv',
+ description: 'Export portfolio data (holdings and transactions) to CSV format',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ portfolio_id: { type: 'string', description: 'Portfolio ID' },
+ },
+ required: ['portfolio_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.exportPortfolioCSV) {
+ return { success: false, error: 'Portfolio context not available' };
+ }
+ const csv = await contexts.exportPortfolioCSV(args.portfolio_id);
+ return {
+ success: true,
+ data: { csv_content: csv },
+ content: csv,
+ message: 'Portfolio exported to CSV successfully',
+ };
},
},
];
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/types.ts b/fincept-terminal-desktop/src/services/mcp/internal/types.ts
index bef7fafd8..f9cd02008 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/types.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/types.ts
@@ -7,6 +7,7 @@ export interface InternalToolSchema {
description: string;
enum?: string[];
default?: any;
+ items?: { type: string };
}>;
required?: string[];
}
@@ -63,14 +64,38 @@ export interface TerminalContexts {
searchStockInstruments?: (query: string, exchange?: string) => Promise<any[]>;
getStockHistoricalData?: (params: any) => Promise<any>;
- // Portfolio
+ // Portfolio - Core CRUD
getPortfolios?: () => Promise<any>;
createPortfolio?: (params: any) => Promise<any>;
deletePortfolio?: (id: string) => Promise<any>;
+ getPortfolio?: (portfolioId: string) => Promise<any>;
+
+ // Portfolio - Asset Management
addAsset?: (portfolioId: string, asset: any) => Promise<any>;
- removeAsset?: (portfolioId: string, assetId: string) => Promise<any>;
+ removeAsset?: (portfolioId: string, symbol: string, sellPrice?: number) => Promise<any>;
+ sellAsset?: (portfolioId: string, symbol: string, quantity: number, price: number) => Promise<any>;
+ getPortfolioAssets?: (portfolioId: string) => Promise<any[]>;
+
+ // Portfolio - Transactions
addTransaction?: (portfolioId: string, tx: any) => Promise<any>;
+ getPortfolioTransactions?: (portfolioId: string, limit?: number) => Promise<any[]>;
+ getSymbolTransactions?: (portfolioId: string, symbol: string) => Promise<any[]>;
+
+ // Portfolio - Summary & Analytics
getPortfolioSummary?: (portfolioId: string) => Promise<any>;
+ calculateAdvancedMetrics?: (portfolioId: string) => Promise<any>;
+ calculateRiskMetrics?: (portfolioId: string) => Promise<any>;
+
+ // Portfolio - Optimization
+ optimizePortfolioWeights?: (portfolioId: string, method?: string) => Promise<any>;
+ getRebalancingRecommendations?: (portfolioId: string, targetAllocations: Record<string, number>) => Promise<any[]>;
+
+ // Portfolio - Analysis
+ analyzeDiversification?: (portfolioId: string) => Promise<any>;
+ getPortfolioPerformanceHistory?: (portfolioId: string, limit?: number) => Promise<any[]>;
+
+ // Portfolio - Export
+ exportPortfolioCSV?: (portfolioId: string) => Promise<string>;
// Dashboard
addWidget?: (widgetType: string, config?: any) => void;
@@ -154,6 +179,55 @@ export interface TerminalContexts {
openWorkflowInEditor?: (workflowId: string) => Promise<void>;
exportNodeWorkflow?: (workflowId: string) => Promise<any>;
importNodeWorkflow?: (workflowData: any) => Promise<WorkflowInfo>;
+
+ // Node Editor - Quick Edit Operations
+ removeNodeFromWorkflow?: (workflowId: string, nodeId: string) => Promise<WorkflowInfo>;
+ disconnectNodes?: (params: DisconnectNodesParams) => Promise<WorkflowInfo>;
+ renameNode?: (workflowId: string, nodeId: string, newLabel: string) => Promise<WorkflowInfo>;
+ clearWorkflow?: (workflowId: string) => Promise<WorkflowInfo>;
+ cloneNode?: (workflowId: string, nodeId: string, newLabel?: string) => Promise<{ workflow: WorkflowInfo; newNodeId: string }>;
+ moveNode?: (params: MoveNodeParams) => Promise<{ workflow: WorkflowInfo; newPosition: { x: number; y: number } }>;
+ getWorkflowStats?: (workflowId: string) => Promise<WorkflowStats>;
+ autoLayoutWorkflow?: (params: AutoLayoutParams) => Promise<{ workflow: WorkflowInfo; nodesRepositioned: number }>;
+
+ // ============================================================================
+ // News - Fetching & Filtering
+ // ============================================================================
+ fetchAllNews?: (forceRefresh?: boolean) => Promise<NewsArticleInfo[]>;
+ getNewsByCategory?: (category: string) => Promise<NewsArticleInfo[]>;
+ getNewsBySource?: (source: string) => Promise<NewsArticleInfo[]>;
+ searchNews?: (query: string) => Promise<NewsArticleInfo[]>;
+ getBreakingNews?: () => Promise<NewsArticleInfo[]>;
+ getNewsBySentiment?: (sentiment: 'BULLISH' | 'BEARISH' | 'NEUTRAL') => Promise<NewsArticleInfo[]>;
+ getNewsByPriority?: (priority: 'FLASH' | 'URGENT' | 'BREAKING' | 'ROUTINE') => Promise<NewsArticleInfo[]>;
+ getNewsByTicker?: (ticker: string) => Promise<NewsArticleInfo[]>;
+
+ // News - Providers / Sources
+ getActiveSources?: () => Promise<string[]>;
+ getRSSFeedCount?: () => Promise<number>;
+ getUserRSSFeeds?: () => Promise<UserRSSFeedInfo[]>;
+ getDefaultFeeds?: () => Promise<RSSFeedInfo[]>;
+ getAllRSSFeeds?: () => Promise<RSSFeedInfo[]>;
+
+ // News - Feed Management
+ addUserRSSFeed?: (params: AddRSSFeedParams) => Promise<UserRSSFeedInfo>;
+ updateUserRSSFeed?: (id: string, params: UpdateRSSFeedParams) => Promise<void>;
+ deleteUserRSSFeed?: (id: string) => Promise<void>;
+ toggleUserRSSFeed?: (id: string, enabled: boolean) => Promise<void>;
+ toggleDefaultRSSFeed?: (feedId: string, enabled: boolean) => Promise<void>;
+ deleteDefaultRSSFeed?: (feedId: string) => Promise<void>;
+ restoreDefaultRSSFeed?: (feedId: string) => Promise<void>;
+ restoreAllDefaultFeeds?: () => Promise<void>;
+ testRSSFeedUrl?: (url: string) => Promise<boolean>;
+
+ // News - Analysis
+ analyzeNewsArticle?: (url: string) => Promise<NewsAnalysisResult>;
+
+ // News - Statistics
+ getNewsSentimentStats?: () => Promise<NewsSentimentStats>;
+ getNewsCacheStats?: () => Promise<NewsCacheStats>;
+ getAvailableCategories?: () => string[];
+ getAvailableRegions?: () => string[];
}
// ============================================================================
@@ -242,6 +316,40 @@ export interface ConfigureNodeParams {
parameters: Record<string, any>;
}
+export interface DisconnectNodesParams {
+ workflowId: string;
+ sourceNodeId: string;
+ targetNodeId: string;
+ sourceHandle?: string;
+}
+
+export interface MoveNodeParams {
+ workflowId: string;
+ nodeId: string;
+ x?: number;
+ y?: number;
+ relative?: boolean;
+ direction?: 'up' | 'down' | 'left' | 'right' | '';
+}
+
+export interface AutoLayoutParams {
+ workflowId: string;
+ direction?: 'horizontal' | 'vertical';
+ spacingX?: number;
+ spacingY?: number;
+}
+
+export interface WorkflowStats {
+ workflowId: string;
+ totalRuns: number;
+ successfulRuns: number;
+ failedRuns: number;
+ successRate: number;
+ lastRunAt?: string;
+ lastStatus?: string;
+ averageDuration?: number;
+}
+
export interface UpdateWorkflowParams {
workflowId: string;
name?: string;
@@ -284,3 +392,142 @@ export interface WorkflowValidation {
export const INTERNAL_SERVER_ID = 'fincept-terminal';
export const INTERNAL_SERVER_NAME = 'Fincept Terminal';
+
+// ============================================================================
+// News Types
+// ============================================================================
+
+export interface NewsArticleInfo {
+ id: string;
+ time: string;
+ priority: 'FLASH' | 'URGENT' | 'BREAKING' | 'ROUTINE';
+ category: string;
+ headline: string;
+ summary: string;
+ source: string;
+ region: string;
+ sentiment: 'BULLISH' | 'BEARISH' | 'NEUTRAL';
+ impact: 'HIGH' | 'MEDIUM' | 'LOW';
+ tickers: string[];
+ classification: string;
+ link?: string;
+ pubDate?: string;
+}
+
+export interface RSSFeedInfo {
+ id: string | null;
+ name: string;
+ url: string;
+ category: string;
+ region: string;
+ source: string;
+ enabled: boolean;
+ is_default: boolean;
+}
+
+export interface UserRSSFeedInfo {
+ id: string;
+ name: string;
+ url: string;
+ category: string;
+ region: string;
+ source_name: string;
+ enabled: boolean;
+ is_default: boolean;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface AddRSSFeedParams {
+ name: string;
+ url: string;
+ category: string;
+ region: string;
+ source_name: string;
+}
+
+export interface UpdateRSSFeedParams {
+ name: string;
+ url: string;
+ category: string;
+ region: string;
+ source_name: string;
+ enabled: boolean;
+}
+
+export interface NewsAnalysisResult {
+ success: boolean;
+ data?: NewsAnalysisData;
+ error?: string;
+}
+
+export interface NewsAnalysisData {
+ article_id: string;
+ source: string;
+ url: string;
+ published_at: string;
+ ingested_at: string;
+ processing_version: string;
+ content: {
+ headline: string;
+ word_count: number;
+ };
+ analysis: {
+ sentiment: {
+ score: number;
+ intensity: number;
+ confidence: number;
+ };
+ market_impact: {
+ urgency: 'LOW' | 'MEDIUM' | 'HIGH';
+ prediction: string;
+ };
+ entities: {
+ organizations: Array<{
+ name: string;
+ ticker: string | null;
+ sector: string;
+ sentiment: number;
+ }>;
+ people: Array<{
+ name: string;
+ ticker: string | null;
+ sector: string;
+ sentiment: number;
+ }>;
+ locations: Array<{
+ name: string;
+ ticker: string | null;
+ sector: string;
+ sentiment: number;
+ }>;
+ };
+ keywords: string[];
+ topics: string[];
+ risk_signals: {
+ regulatory: { level: string; details: string };
+ geopolitical: { level: string; details: string };
+ operational: { level: string; details: string };
+ market: { level: string; details: string };
+ };
+ summary: string;
+ key_points: string[];
+ };
+ credits_used: number;
+ credits_remaining: number;
+}
+
+export interface NewsSentimentStats {
+ bullish: number;
+ bearish: number;
+ neutral: number;
+ total: number;
+ netScore: number;
+ alertCount: number;
+}
+
+export interface NewsCacheStats {
+ hasCachedData: boolean;
+ articleCount: number;
+ cacheAge: number | null;
+}
diff --git a/fincept-terminal-desktop/src/services/mcp/mcpClient.ts b/fincept-terminal-desktop/src/services/mcp/mcpClient.ts
index 8ac763d19..9f78b6449 100644
--- a/fincept-terminal-desktop/src/services/mcp/mcpClient.ts
+++ b/fincept-terminal-desktop/src/services/mcp/mcpClient.ts
@@ -50,6 +50,7 @@ class MCPClient {
private isInitialized = false;
private capabilities: MCPServerCapabilities = {};
private requestTimeoutMs = 30000; // 30 second timeout for requests
+ private initTimeoutMs = 120000; // 2 minute timeout for initialization (uvx downloads)
constructor(serverId: string) {
this.serverId = serverId;
@@ -88,6 +89,7 @@ class MCPClient {
}
// Initialize MCP protocol handshake
+ // Uses longer timeout for first-time uvx package downloads
private async initialize(): Promise<void> {
const response = await this.sendRequest('initialize', {
protocolVersion: '2024-11-05',
@@ -101,7 +103,7 @@ class MCPClient {
name: 'fincept-terminal',
version: '1.0.0'
}
- });
+ }, this.initTimeoutMs); // Use longer timeout for init
this.capabilities = response.capabilities || {};
this.isInitialized = true;
@@ -213,8 +215,9 @@ class MCPClient {
}
// Send JSON-RPC request with timeout
- private async sendRequest(method: string, params: any): Promise<any> {
+ private async sendRequest(method: string, params: any, customTimeoutMs?: number): Promise<any> {
const id = this.messageId++;
+ const timeoutMs = customTimeoutMs || this.requestTimeoutMs;
const request = {
jsonrpc: '2.0',
@@ -225,14 +228,15 @@ class MCPClient {
const timeoutPromise = new Promise<never>((_, reject) => {
setTimeout(() => {
- reject(new Error(`MCP request '${method}' timed out after ${this.requestTimeoutMs}ms`));
- }, this.requestTimeoutMs);
+ reject(new Error(`MCP request '${method}' timed out after ${timeoutMs}ms`));
+ }, timeoutMs);
});
const requestPromise = (async () => {
const response = await invoke<string>('send_mcp_request', {
serverId: this.serverId,
- request: JSON.stringify(request)
+ request: JSON.stringify(request),
+ timeoutSecs: Math.ceil(timeoutMs / 1000) // Pass timeout to Rust
});
const parsed = JSON.parse(response);
diff --git a/fincept-terminal-desktop/src/services/mcp/mcpManager.ts b/fincept-terminal-desktop/src/services/mcp/mcpManager.ts
index 873a915d4..302a6d95d 100644
--- a/fincept-terminal-desktop/src/services/mcp/mcpManager.ts
+++ b/fincept-terminal-desktop/src/services/mcp/mcpManager.ts
@@ -37,7 +37,25 @@ class MCPManager {
// Health check is deferred until the first server starts
}
- // Install a new MCP server
+ // Installation state tracking
+ private installingServers = new Set<string>();
+ private installationCallbacks = new Map<string, {
+ onProgress?: (status: string) => void;
+ onComplete?: (success: boolean, error?: string) => void;
+ }>();
+
+ // Check if a server is currently being installed
+ isInstalling(serverId: string): boolean {
+ return this.installingServers.has(serverId);
+ }
+
+ // Get all currently installing server IDs
+ getInstallingServerIds(): string[] {
+ return Array.from(this.installingServers);
+ }
+
+ // Install a new MCP server (non-blocking)
+ // Returns immediately after saving to DB, starts server in background
async installServer(config: {
id: string;
name: string;
@@ -47,15 +65,31 @@ class MCPManager {
env?: Record<string, string>;
category: string;
icon: string;
+ }, callbacks?: {
+ onProgress?: (status: string) => void;
+ onComplete?: (success: boolean, error?: string) => void;
}): Promise<void> {
+ // Prevent duplicate installations
+ if (this.installingServers.has(config.id)) {
+ mcpLogger.warn(`Server ${config.id} is already being installed`);
+ return;
+ }
+
+ this.installingServers.add(config.id);
+ if (callbacks) {
+ this.installationCallbacks.set(config.id, callbacks);
+ }
+
try {
mcpLogger.info(`Installing server: ${config.name}`);
+ callbacks?.onProgress?.('Checking existing installation...');
// Check if server already exists
const existing = await sqliteService.getMCPServer(config.id);
if (existing) {
mcpLogger.info(`Server ${config.id} already installed, updating config...`);
+ callbacks?.onProgress?.('Updating existing configuration...');
// Update existing server config
await sqliteService.updateMCPServerConfig(config.id, {
@@ -67,19 +101,14 @@ class MCPManager {
await this.stopServer(config.id);
}
- // Try to start with new config
- try {
- await this.startServer(config.id);
- } catch (startError) {
- mcpLogger.warn(`Failed to start existing server: ${startError}`);
- // Don't throw - server is already installed
- }
-
- mcpLogger.info(`Server ${config.name} updated successfully`);
+ // Start in background - don't await
+ this.startServerInBackground(config.id, callbacks);
return;
}
- // Add new server to database
+ callbacks?.onProgress?.('Saving server configuration...');
+
+ // Add new server to database (fast operation)
await sqliteService.addMCPServer({
id: config.id,
name: config.name,
@@ -94,21 +123,48 @@ class MCPManager {
status: 'stopped'
});
- // Try to start the server (don't fail install if start fails)
- try {
- await this.startServer(config.id);
- } catch (startError) {
- mcpLogger.warn(`Server installed but failed to start: ${startError}`);
- // Server is installed, just not running - this is OK
- }
+ mcpLogger.info(`Server ${config.name} saved to database`);
+ callbacks?.onProgress?.('Starting server (this may take a while for first-time downloads)...');
+
+ // Start server in background - don't await, let it run
+ this.startServerInBackground(config.id, callbacks);
- mcpLogger.info(`Server ${config.name} installed successfully`);
} catch (error) {
+ this.installingServers.delete(config.id);
+ this.installationCallbacks.delete(config.id);
mcpLogger.error('Installation error:', error);
+ const errorMsg = error instanceof Error ? error.message : 'Unknown error';
+ callbacks?.onComplete?.(false, errorMsg);
throw error;
}
}
+ // Start server in background without blocking
+ private startServerInBackground(serverId: string, callbacks?: {
+ onProgress?: (status: string) => void;
+ onComplete?: (success: boolean, error?: string) => void;
+ }): void {
+ // Use setTimeout to ensure this runs in the next tick, not blocking current execution
+ setTimeout(async () => {
+ try {
+ callbacks?.onProgress?.('Connecting to server...');
+ await this.startServer(serverId);
+
+ this.installingServers.delete(serverId);
+ this.installationCallbacks.delete(serverId);
+ callbacks?.onComplete?.(true);
+ mcpLogger.info(`Server ${serverId} started successfully in background`);
+ } catch (startError) {
+ this.installingServers.delete(serverId);
+ this.installationCallbacks.delete(serverId);
+ const errorMsg = startError instanceof Error ? startError.message : 'Unknown error';
+ mcpLogger.warn(`Server installed but failed to start: ${errorMsg}`);
+ callbacks?.onComplete?.(false, errorMsg);
+ // Don't throw - server is installed, just not running
+ }
+ }, 0);
+ }
+
// Start an MCP server
async startServer(serverId: string): Promise<void> {
try {
diff --git a/fincept-terminal-desktop/src/services/voice/ttsService.ts b/fincept-terminal-desktop/src/services/voice/ttsService.ts
new file mode 100644
index 000000000..7b9369750
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/voice/ttsService.ts
@@ -0,0 +1,325 @@
+// Text-to-Speech Service with multiple providers
+// Supports: Browser native, Edge TTS, ElevenLabs, OpenAI TTS
+
+import { invoke } from '@tauri-apps/api/core';
+
+export type TTSProvider = 'browser' | 'edge' | 'elevenlabs' | 'openai';
+
+export interface TTSVoice {
+ id: string;
+ name: string;
+ provider: TTSProvider;
+ language: string;
+ gender?: 'male' | 'female' | 'neutral';
+ preview?: string;
+}
+
+export interface TTSConfig {
+ provider: TTSProvider;
+ voiceId: string;
+ rate: number;
+ // API keys stored in settings
+ elevenLabsApiKey?: string;
+ openaiApiKey?: string;
+}
+
+// Edge TTS voices (free, high quality)
+export const EDGE_VOICES: TTSVoice[] = [
+ { id: 'en-US-GuyNeural', name: 'Guy (US Male)', provider: 'edge', language: 'en-US', gender: 'male' },
+ { id: 'en-US-JennyNeural', name: 'Jenny (US Female)', provider: 'edge', language: 'en-US', gender: 'female' },
+ { id: 'en-US-AriaNeural', name: 'Aria (US Female)', provider: 'edge', language: 'en-US', gender: 'female' },
+ { id: 'en-US-DavisNeural', name: 'Davis (US Male)', provider: 'edge', language: 'en-US', gender: 'male' },
+ { id: 'en-US-TonyNeural', name: 'Tony (US Male)', provider: 'edge', language: 'en-US', gender: 'male' },
+ { id: 'en-US-SaraNeural', name: 'Sara (US Female)', provider: 'edge', language: 'en-US', gender: 'female' },
+ { id: 'en-GB-RyanNeural', name: 'Ryan (UK Male)', provider: 'edge', language: 'en-GB', gender: 'male' },
+ { id: 'en-GB-SoniaNeural', name: 'Sonia (UK Female)', provider: 'edge', language: 'en-GB', gender: 'female' },
+ { id: 'en-AU-NatashaNeural', name: 'Natasha (AU Female)', provider: 'edge', language: 'en-AU', gender: 'female' },
+ { id: 'en-AU-WilliamNeural', name: 'William (AU Male)', provider: 'edge', language: 'en-AU', gender: 'male' },
+ { id: 'en-IN-NeerjaNeural', name: 'Neerja (India Female)', provider: 'edge', language: 'en-IN', gender: 'female' },
+ { id: 'en-IN-PrabhatNeural', name: 'Prabhat (India Male)', provider: 'edge', language: 'en-IN', gender: 'male' },
+];
+
+// ElevenLabs default voices
+export const ELEVENLABS_VOICES: TTSVoice[] = [
+ { id: 'EXAVITQu4vr4xnSDxMaL', name: 'Sarah (Female)', provider: 'elevenlabs', language: 'en', gender: 'female' },
+ { id: 'TX3LPaxmHKxFdv7VOQHJ', name: 'Liam (Male)', provider: 'elevenlabs', language: 'en', gender: 'male' },
+ { id: 'XB0fDUnXU5powFXDhCwa', name: 'Charlotte (Female)', provider: 'elevenlabs', language: 'en', gender: 'female' },
+ { id: 'pFZP5JQG7iQjIQuC4Bku', name: 'Lily (Female)', provider: 'elevenlabs', language: 'en', gender: 'female' },
+ { id: 'onwK4e9ZLuTAKqWW03F9', name: 'Daniel (Male)', provider: 'elevenlabs', language: 'en', gender: 'male' },
+ { id: '21m00Tcm4TlvDq8ikWAM', name: 'Rachel (Female)', provider: 'elevenlabs', language: 'en', gender: 'female' },
+];
+
+// OpenAI TTS voices
+export const OPENAI_VOICES: TTSVoice[] = [
+ { id: 'alloy', name: 'Alloy (Neutral)', provider: 'openai', language: 'en', gender: 'neutral' },
+ { id: 'echo', name: 'Echo (Male)', provider: 'openai', language: 'en', gender: 'male' },
+ { id: 'fable', name: 'Fable (Male)', provider: 'openai', language: 'en', gender: 'male' },
+ { id: 'onyx', name: 'Onyx (Male)', provider: 'openai', language: 'en', gender: 'male' },
+ { id: 'nova', name: 'Nova (Female)', provider: 'openai', language: 'en', gender: 'female' },
+ { id: 'shimmer', name: 'Shimmer (Female)', provider: 'openai', language: 'en', gender: 'female' },
+];
+
+class TTSService {
+ private currentAudio: HTMLAudioElement | null = null;
+ private isSpeaking = false;
+
+ // Get all available voices
+ getAllVoices(): TTSVoice[] {
+ const browserVoices = this.getBrowserVoices();
+ return [...browserVoices, ...EDGE_VOICES, ...ELEVENLABS_VOICES, ...OPENAI_VOICES];
+ }
+
+ // Get browser native voices
+ getBrowserVoices(): TTSVoice[] {
+ if (!window.speechSynthesis) return [];
+
+ const voices = window.speechSynthesis.getVoices();
+ return voices
+ .filter(v => v.lang.startsWith('en'))
+ .map(v => ({
+ id: v.name,
+ name: v.name,
+ provider: 'browser' as TTSProvider,
+ language: v.lang,
+ }));
+ }
+
+ // Speak text with selected voice
+ async speak(text: string, config: TTSConfig): Promise<void> {
+ // Stop any current speech
+ this.stop();
+
+ // Clean text
+ const cleanText = this.cleanText(text);
+ if (!cleanText) return;
+
+ switch (config.provider) {
+ case 'browser':
+ return this.speakBrowser(cleanText, config);
+ case 'edge':
+ return this.speakEdge(cleanText, config);
+ case 'elevenlabs':
+ return this.speakElevenLabs(cleanText, config);
+ case 'openai':
+ return this.speakOpenAI(cleanText, config);
+ default:
+ return this.speakBrowser(cleanText, config);
+ }
+ }
+
+ // Stop speaking
+ stop(): void {
+ if (this.currentAudio) {
+ this.currentAudio.pause();
+ this.currentAudio = null;
+ }
+ if (window.speechSynthesis) {
+ window.speechSynthesis.cancel();
+ }
+ this.isSpeaking = false;
+ }
+
+ // Check if speaking
+ getIsSpeaking(): boolean {
+ return this.isSpeaking;
+ }
+
+ // Clean text for TTS
+ private cleanText(text: string): string {
+ return text
+ .replace(/```[\s\S]*?```/g, '') // Remove code blocks
+ .replace(/[`*#\[\](){}]/g, '') // Remove markdown
+ .replace(/\n+/g, '. ') // Replace newlines
+ .replace(/[\u{1F300}-\u{1F9FF}]/gu, '') // Remove emojis
+ .replace(/[\u{2600}-\u{26FF}]/gu, '')
+ .replace(/[\u{2700}-\u{27BF}]/gu, '')
+ .replace(/[\u{1F600}-\u{1F64F}]/gu, '')
+ .replace(/[\u{1F680}-\u{1F6FF}]/gu, '')
+ .replace(/[\u{1F1E0}-\u{1F1FF}]/gu, '')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .slice(0, 1000);
+ }
+
+ // Browser native TTS
+ private speakBrowser(text: string, config: TTSConfig): Promise<void> {
+ return new Promise((resolve, reject) => {
+ if (!window.speechSynthesis) {
+ reject(new Error('Speech synthesis not supported'));
+ return;
+ }
+
+ const utterance = new SpeechSynthesisUtterance(text);
+ utterance.rate = config.rate;
+
+ const voices = window.speechSynthesis.getVoices();
+ const voice = voices.find(v => v.name === config.voiceId);
+ if (voice) utterance.voice = voice;
+
+ utterance.onstart = () => { this.isSpeaking = true; };
+ utterance.onend = () => { this.isSpeaking = false; resolve(); };
+ utterance.onerror = (e) => { this.isSpeaking = false; reject(e); };
+
+ window.speechSynthesis.cancel();
+ window.speechSynthesis.speak(utterance);
+ });
+ }
+
+ // Edge TTS (via Python backend)
+ private async speakEdge(text: string, config: TTSConfig): Promise<void> {
+ try {
+ this.isSpeaking = true;
+
+ // Call Rust/Python backend to generate audio
+ const audioBase64 = await invoke<string>('tts_edge_speak', {
+ text,
+ voice: config.voiceId,
+ rate: config.rate,
+ });
+
+ // Play audio
+ const audio = new Audio(`data:audio/mp3;base64,${audioBase64}`);
+ this.currentAudio = audio;
+
+ return new Promise((resolve, reject) => {
+ audio.onended = () => {
+ this.isSpeaking = false;
+ this.currentAudio = null;
+ resolve();
+ };
+ audio.onerror = (e) => {
+ this.isSpeaking = false;
+ this.currentAudio = null;
+ reject(e);
+ };
+ audio.play().catch(reject);
+ });
+ } catch (error) {
+ this.isSpeaking = false;
+ console.error('[TTS] Edge TTS error:', error);
+ // Fallback to browser
+ return this.speakBrowser(text, { ...config, provider: 'browser' });
+ }
+ }
+
+ // ElevenLabs TTS
+ private async speakElevenLabs(text: string, config: TTSConfig): Promise<void> {
+ if (!config.elevenLabsApiKey) {
+ console.warn('[TTS] ElevenLabs API key not set, falling back to browser');
+ return this.speakBrowser(text, { ...config, provider: 'browser' });
+ }
+
+ try {
+ this.isSpeaking = true;
+
+ const response = await fetch(
+ `https://api.elevenlabs.io/v1/text-to-speech/${config.voiceId}`,
+ {
+ method: 'POST',
+ headers: {
+ 'Accept': 'audio/mpeg',
+ 'Content-Type': 'application/json',
+ 'xi-api-key': config.elevenLabsApiKey,
+ },
+ body: JSON.stringify({
+ text,
+ model_id: 'eleven_monolingual_v1',
+ voice_settings: {
+ stability: 0.5,
+ similarity_boost: 0.75,
+ },
+ }),
+ }
+ );
+
+ if (!response.ok) {
+ throw new Error(`ElevenLabs API error: ${response.status}`);
+ }
+
+ const audioBlob = await response.blob();
+ const audioUrl = URL.createObjectURL(audioBlob);
+ const audio = new Audio(audioUrl);
+ this.currentAudio = audio;
+
+ // Adjust playback rate
+ audio.playbackRate = config.rate;
+
+ return new Promise((resolve, reject) => {
+ audio.onended = () => {
+ this.isSpeaking = false;
+ this.currentAudio = null;
+ URL.revokeObjectURL(audioUrl);
+ resolve();
+ };
+ audio.onerror = (e) => {
+ this.isSpeaking = false;
+ this.currentAudio = null;
+ URL.revokeObjectURL(audioUrl);
+ reject(e);
+ };
+ audio.play().catch(reject);
+ });
+ } catch (error) {
+ this.isSpeaking = false;
+ console.error('[TTS] ElevenLabs error:', error);
+ return this.speakBrowser(text, { ...config, provider: 'browser' });
+ }
+ }
+
+ // OpenAI TTS
+ private async speakOpenAI(text: string, config: TTSConfig): Promise<void> {
+ if (!config.openaiApiKey) {
+ console.warn('[TTS] OpenAI API key not set, falling back to browser');
+ return this.speakBrowser(text, { ...config, provider: 'browser' });
+ }
+
+ try {
+ this.isSpeaking = true;
+
+ const response = await fetch('https://api.openai.com/v1/audio/speech', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${config.openaiApiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ model: 'tts-1',
+ input: text,
+ voice: config.voiceId,
+ speed: config.rate,
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error(`OpenAI API error: ${response.status}`);
+ }
+
+ const audioBlob = await response.blob();
+ const audioUrl = URL.createObjectURL(audioBlob);
+ const audio = new Audio(audioUrl);
+ this.currentAudio = audio;
+
+ return new Promise((resolve, reject) => {
+ audio.onended = () => {
+ this.isSpeaking = false;
+ this.currentAudio = null;
+ URL.revokeObjectURL(audioUrl);
+ resolve();
+ };
+ audio.onerror = (e) => {
+ this.isSpeaking = false;
+ this.currentAudio = null;
+ URL.revokeObjectURL(audioUrl);
+ reject(e);
+ };
+ audio.play().catch(reject);
+ });
+ } catch (error) {
+ this.isSpeaking = false;
+ console.error('[TTS] OpenAI error:', error);
+ return this.speakBrowser(text, { ...config, provider: 'browser' });
+ }
+ }
+}
+
+export const ttsService = new TTSService();
diff --git a/test_defeatbeta.py b/test_defeatbeta.py
new file mode 100644
index 000000000..f47f1f407
--- /dev/null
+++ b/test_defeatbeta.py
@@ -0,0 +1,29 @@
+import os
+os.environ['PYTHONIOENCODING'] = 'utf-8'
+
+try:
+ from defeatbeta_api.data.ticker import Ticker
+
+ print("Testing defeatbeta-api with AAPL...")
+ ticker = Ticker('AAPL')
+
+ print("\nFetching earnings call transcripts...")
+ transcripts = ticker.earning_call_transcripts()
+
+ print("\nAvailable transcripts:")
+ transcript_list = transcripts.get_transcripts_list()
+ print(transcript_list[:5] if len(transcript_list) > 5 else transcript_list)
+
+ print("\nFetching latest transcript...")
+ if transcript_list:
+ latest = transcript_list[0]
+ year, quarter = latest['year'], latest['quarter']
+ transcript = transcripts.get_transcript(year, quarter)
+ print(f"\nTranscript preview (Year: {year}, Q{quarter}):")
+ print(str(transcript)[:500])
+ print("\n✅ SUCCESS: Earnings transcripts are available!")
+ else:
+ print("No transcripts found.")
+
+except Exception as e:
+ print(f"\n❌ ERROR: {type(e).__name__}: {e}")