refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack

- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched)
- Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations()
- Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation
- Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims
- Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution
- Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
This commit is contained in:
Boki 2026-11-27 00:11:50 -05:00
parent ce9e2df67c
commit 4cd6038063
432 changed files with 1247 additions and 44469 deletions

35
.env
View file

@ -27,31 +27,31 @@ WEBSHARE_API_URL=https://proxy.webshare.io/api/v2/
# Dragonfly/Redis Configuration
DRAGONFLY_HOST=localhost
DRAGONFLY_PORT=6379
DRAGONFLY_PORT=6380
DRAGONFLY_PASSWORD=
# PostgreSQL Configuration
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DATABASE=trading_bot
POSTGRES_USERNAME=trading_user
POSTGRES_PASSWORD=trading_pass_dev
POSTGRES_PORT=5433
POSTGRES_DATABASE=trading_bot_dev
POSTGRES_USERNAME=dev_user
POSTGRES_PASSWORD=dev_pass
POSTGRES_SSL=false
# QuestDB Configuration
QUESTDB_HOST=localhost
QUESTDB_PORT=9000
QUESTDB_PORT=9100
QUESTDB_DB=qdb
QUESTDB_USERNAME=admin
QUESTDB_PASSWORD=quest
# MongoDB Configuration
MONGODB_HOST=localhost
MONGODB_PORT=27017
MONGODB_DATABASE=stock
MONGODB_USERNAME=trading_admin
MONGODB_PASSWORD=trading_mongo_dev
MONGODB_URI=mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin
MONGODB_PORT=27018
MONGODB_DATABASE=stock_dev
MONGODB_USERNAME=dev_admin
MONGODB_PASSWORD=dev_mongo_pass
MONGODB_URI=mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin
# ===========================================
# DATA PROVIDER CONFIGURATIONS
@ -154,7 +154,6 @@ SOURCE_MAPS=true
# ===========================================
# Docker-specific settings (used in docker-compose)
COMPOSE_PROJECT_NAME=stock-bot
DOCKER_BUILDKIT=1
# ===========================================
@ -171,7 +170,11 @@ APP_DESCRIPTION="Advanced Stock Trading and Analysis Platform"
# PostgreSQL
DATABASE_POSTGRES_HOST=localhost
DATABASE_POSTGRES_PORT=5432
DATABASE_POSTGRES_DATABASE=trading_bot
DATABASE_POSTGRES_USER=trading_user
DATABASE_POSTGRES_PASSWORD=trading_pass_dev
DATABASE_POSTGRES_PORT=5433
DATABASE_POSTGRES_DATABASE=trading_bot_dev
DATABASE_POSTGRES_USER=dev_user
DATABASE_POSTGRES_PASSWORD=dev_pass
QUESTDB_HTTP_PORT=9100
QUESTDB_PG_PORT=8813
QUESTDB_ILP_PORT=9010
QUEUE_ENABLE_SCHEDULED_JOBS=false

View file

@ -36,8 +36,17 @@ MONGODB_URI=mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSou
# QA MongoDB READ-ONLY connection (used by dev data-pipeline to read ingested provider data)
MONGODB_READ_URI=mongodb://studio_stock_bot_read:<QA_READ_PASSWORD>@localhost:27017/stock?authSource=stock
# Dev Dragonfly / QuestDB
# Dev Dragonfly / QuestDB / Queue
DRAGONFLY_HOST=localhost
DRAGONFLY_PORT=6380
QUESTDB_HOST=localhost
QUESTDB_PORT=9100
QUESTDB_HTTP_PORT=9100
QUESTDB_PG_PORT=8813
QUESTDB_ILP_PORT=9010
QUEUE_ENABLE_SCHEDULED_JOBS=false
# DuckDB per-connection budget (prevents default 80% host-RAM allocation)
DUCKDB_MEMORY_LIMIT=2GB
DUCKDB_THREADS=2
DUCKDB_TEMP_DIR=/tmp/stock-bot-duckdb-dev

View file

@ -35,8 +35,17 @@ MONGODB_URI=mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?auth
# Optional: restrict QA data-pipeline to read-only MongoDB credentials too
# MONGODB_READ_URI=mongodb://studio_stock_bot_read:<QA_READ_PASSWORD>@localhost:27017/stock?authSource=stock
# QA Dragonfly / QuestDB
# QA Dragonfly / QuestDB / Queue
DRAGONFLY_HOST=localhost
DRAGONFLY_PORT=6379
QUESTDB_HOST=localhost
QUESTDB_PORT=9000
QUESTDB_HTTP_PORT=9000
QUESTDB_PG_PORT=8812
QUESTDB_ILP_PORT=9009
QUEUE_ENABLE_SCHEDULED_JOBS=true
# DuckDB per-worker budget on quant (prevents default 80% host-RAM allocation)
DUCKDB_MEMORY_LIMIT=6GB
DUCKDB_THREADS=4
DUCKDB_TEMP_DIR=/mnt/data/stockbot/tmp/duckdb

View file

@ -70,7 +70,7 @@ Preserve the matching image and descriptor when retaining runs for reproduction.
`execution: { "kind": "isolated-candidate/v1", "warmupBars": 0 }`. Set the warmup to the
maximum required by all intended parameter combinations. Use the
[retained package contract](libs/core/types/src/strategy-version.ts) and
[strategy decision API](apps/stock/orchestrator/src/contracts/canonical-strategy.ts).
[strategy decision API](libs/research/src/strategy-api.ts).
The entry export is a synchronous factory receiving the retained selection and returning
a target-mode strategy with explicit JSON state. The CLI transpiles self-contained
TypeScript inside isolation; it does not evaluate the source or install dependencies.
@ -188,14 +188,9 @@ feature engineering. Its supported subpaths expose reviewed returns, indicators,
transforms and the previously tested orchestrator analytics/window math. The orchestrator
now consumes that library; no database, native binding, HTTP or application service is
required to import it. Existing strategy checkpoint versions and financial execution
behavior are unchanged by this relocation.
All 105 formerly active financial calculation functions remain available behind the
explicit `@stock-bot/calculations/legacy` namespace, with unchanged executable bodies.
This is preservation, not a production-correctness endorsement. All seven previously
disabled prototypes, including unique additional indicators, survive as non-executable
source-verified research snapshots. See [the calculation contract](libs/calculations/README.md)
for supported units, undefined values, alignment and the review/promotion path.
behavior are unchanged by this relocation. See
[the calculation contract](libs/calculations/README.md) for supported units, undefined
values, alignment and validation rules.
`@stock-bot/utils` retains HTTP/user-agent, proxy/sleep and validated UTC date/weekday
helpers through explicit capability subpaths. Deprecated `dateUtils` names are aliases,
@ -203,12 +198,9 @@ not an exchange holiday/session calendar. Assertions belong to `@stock-bot/invar
and domain types to `@stock-bot/types`. The coverage CLI no longer declares an unused
utility dependency, and unused `simple-statistics` is removed.
Only empty placeholder/redundant entry points remain removed; old numerical and Redis
test sources are retained as explicit legacy/research references rather than runnable
backups or claimed passing coverage. [The cleanup audit](docs/cleanup-audit.md) accounts
for every removal in this batch. [The utility contract](libs/utils/README.md) documents
the restored helpers and migration notes. Architecture tests enforce the ownership and
dependency boundaries without forbidding useful shared domain libraries.
[The utility contract](libs/utils/README.md) documents the general HTTP and user-agent
helpers. Architecture tests enforce the ownership and dependency boundaries without
forbidding useful shared domain libraries.
## Service contracts
@ -278,12 +270,7 @@ tests. Registering a factory does not bypass risk checks or the durable-checkpoi
The experimental ML strategy remains unavailable for paper execution.
Architecture tests run in `bun run check`, checking runtime dependency cycles and the
contract/domain/adapter boundaries. The run-local ledger stages only transaction writes,
indexes active work and client IDs, and binary-searches the journal; retained history is not
deep-copied for every read. Reads/writes remain detached and failed transactions publish
nothing. History is still retained in memory for the run; this is not a streaming/retention
solution. Run `bun run scripts/benchmark-execution.ts` for a local journal-read microbenchmark,
not an end-to-end backtest performance estimate.
contract/domain/adapter boundaries.
### Strategy parameters and indicator math
@ -380,26 +367,7 @@ Corrected analytics can change new-run results. Existing saved rows are not reca
no database migration/reset is performed. Native trading algorithms and engine-specific
supplemental statistics are not silently redefined by this TypeScript math refactor.
The external analytics client validates finite responses, ordered instrument/model identity,
portfolio weights and correlation matrices (including positive semidefiniteness). Requests
have a five-second timeout and one-MiB response limit. Its success cache is capped at 128
entries with per-entry TTL; failed/expired requests never become fresh fake observations.
HTTP 503 means unavailable upstream/data; 502 means an invalid upstream response; invalid
client input remains 400. No outage produces zero risk metrics, equal portfolio weights,
an identity correlation matrix or a “normal” market regime.
The Python portfolio-performance/risk, regime, correlation, saved-backtest-analysis and
attribution endpoints currently have no observed-data adapter. They now return explicit 503
instead of random samples or constant reports. They remain unavailable until real data is
integrated; research helpers are not production data sources. Optimization still consumes
caller-provided returns/symbols, and prediction requires an actual loaded model. TypeScript
maps their snake-case Python wire fields explicitly rather than guessing weights/identities.
Run `bun run check` for TypeScript/native checks and analytics regression fixtures.
Separately run `bun run test:analytics-api` for real FastAPI router HTTP tests. That optional
command needs Python 3.12 and `uv`; it obtains the FastAPI/HTTPX/Pydantic versions already
pinned by the Python service, without installing the research/ML runtime. It tests the router,
not full Python-service startup or a live upstream deployment.
## Backtest data integrity

View file

@ -1,2 +0,0 @@
__pycache__/
*.py[cod]

View file

@ -1,38 +0,0 @@
#!/usr/bin/env python3
"""
Trading Analytics Service - Main entry point
"""
import uvicorn
import logging
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def main():
"""Start the analytics service"""
host = os.getenv('ANALYTICS_HOST', '0.0.0.0')
port = int(os.getenv('ANALYTICS_PORT', '3003'))
logger.info(f"Starting Trading Analytics Service on {host}:{port}")
uvicorn.run(
"src.api.app:app",
host=host,
port=port,
reload=os.getenv('ENV') == 'development',
log_level="info"
)
if __name__ == "__main__":
main()

View file

@ -1,18 +0,0 @@
fastapi==0.104.1
uvicorn==0.24.0
pandas==2.1.3
numpy==1.26.2
scipy==1.11.4
scikit-learn==1.3.2
cvxpy==1.4.1
statsmodels==0.14.0
ta==0.10.2
plotly==5.18.0
redis==5.0.1
httpx==0.25.2
pydantic==2.5.0
python-dotenv==1.0.0
onnxruntime==1.16.3
psycopg2-binary==2.9.9
sqlalchemy==2.0.23
alembic==1.12.1

View file

@ -1,410 +0,0 @@
import numpy as np
import pandas as pd
from scipy import stats
from typing import Dict, List, Tuple, Optional
import logging
from dataclasses import dataclass
from sklearn.model_selection import TimeSeriesSplit
import warnings
logger = logging.getLogger(__name__)
@dataclass
class ValidationResult:
"""Results from statistical validation tests"""
is_overfit: bool
confidence_level: float
psr: float # Probabilistic Sharpe Ratio
dsr: float # Deflated Sharpe Ratio
monte_carlo_percentile: float
out_of_sample_degradation: float
statistical_significance: bool
warnings: List[str]
recommendations: List[str]
class StatisticalValidator:
"""
Statistical validation for backtesting results
Detects overfitting and validates strategy robustness
"""
def __init__(self, min_trades: int = 30, confidence_level: float = 0.95):
self.min_trades = min_trades
self.confidence_level = confidence_level
def validate_backtest(
self,
returns: np.ndarray,
trades: pd.DataFrame,
parameters: Dict,
market_returns: Optional[np.ndarray] = None
) -> ValidationResult:
"""
Comprehensive validation of backtest results
"""
warnings_list = []
recommendations = []
# Check minimum requirements
if len(trades) < self.min_trades:
warnings_list.append(f"Insufficient trades ({len(trades)} < {self.min_trades})")
recommendations.append("Extend backtest period or reduce trading filters")
# Calculate key metrics
sharpe = self.calculate_sharpe_ratio(returns)
psr = self.calculate_probabilistic_sharpe_ratio(sharpe, len(returns))
dsr = self.calculate_deflated_sharpe_ratio(
sharpe, len(returns), len(parameters)
)
# Monte Carlo analysis
mc_percentile = self.monte_carlo_test(returns, trades)
# Out-of-sample testing
oos_degradation = self.out_of_sample_test(returns, trades)
# Statistical significance tests
is_significant = self.test_statistical_significance(returns, market_returns)
# Overfitting detection
is_overfit = self.detect_overfitting(
psr, dsr, mc_percentile, oos_degradation, len(parameters)
)
# Generate recommendations
if dsr < 0.95:
recommendations.append("Reduce strategy complexity or increase sample size")
if mc_percentile < 0.95:
recommendations.append("Strategy may be exploiting random patterns")
if oos_degradation > 0.5:
recommendations.append("Consider walk-forward optimization")
return ValidationResult(
is_overfit=is_overfit,
confidence_level=1 - is_overfit * 0.5, # Simple confidence measure
psr=psr,
dsr=dsr,
monte_carlo_percentile=mc_percentile,
out_of_sample_degradation=oos_degradation,
statistical_significance=is_significant,
warnings=warnings_list,
recommendations=recommendations
)
def calculate_sharpe_ratio(self, returns: np.ndarray) -> float:
"""Calculate annualized Sharpe ratio"""
if len(returns) == 0:
return 0.0
# Assume daily returns
mean_return = np.mean(returns)
std_return = np.std(returns, ddof=1)
if std_return == 0:
return 0.0
# Annualize
sharpe = mean_return / std_return * np.sqrt(252)
return sharpe
def calculate_probabilistic_sharpe_ratio(
self,
sharpe: float,
num_observations: int
) -> float:
"""
Calculate Probabilistic Sharpe Ratio (PSR)
Adjusts for sample size and non-normality
"""
if num_observations < 2:
return 0.0
# Adjust for sample size
psr = stats.norm.cdf(
sharpe * np.sqrt(num_observations - 1) /
np.sqrt(1 + 0.5 * sharpe**2)
)
return psr
def calculate_deflated_sharpe_ratio(
self,
sharpe: float,
num_observations: int,
num_parameters: int,
num_trials: int = 1
) -> float:
"""
Calculate Deflated Sharpe Ratio (DSR)
Accounts for multiple testing and parameter optimization
"""
if num_observations < num_parameters + 2:
return 0.0
# Expected maximum Sharpe under null hypothesis
expected_max_sharpe = np.sqrt(2 * np.log(num_trials)) / np.sqrt(num_observations)
# Standard error of Sharpe ratio
se_sharpe = np.sqrt(
(1 + 0.5 * sharpe**2) / (num_observations - 1)
)
# Deflated Sharpe Ratio
dsr = (sharpe - expected_max_sharpe) / se_sharpe
# Convert to probability
return stats.norm.cdf(dsr)
def monte_carlo_test(
self,
returns: np.ndarray,
trades: pd.DataFrame,
num_simulations: int = 1000
) -> float:
"""
Monte Carlo permutation test
Tests if strategy is better than random
"""
original_sharpe = self.calculate_sharpe_ratio(returns)
# Generate random strategies
random_sharpes = []
for _ in range(num_simulations):
# Randomly shuffle trade outcomes
shuffled_returns = np.random.permutation(returns)
random_sharpe = self.calculate_sharpe_ratio(shuffled_returns)
random_sharpes.append(random_sharpe)
# Calculate percentile
percentile = np.sum(original_sharpe > np.array(random_sharpes)) / num_simulations
return percentile
def out_of_sample_test(
self,
returns: np.ndarray,
trades: pd.DataFrame,
test_size: float = 0.3
) -> float:
"""
Test performance degradation out-of-sample
"""
if len(returns) < 100: # Need sufficient data
return 0.0
# Split data
split_point = int(len(returns) * (1 - test_size))
in_sample_returns = returns[:split_point]
out_sample_returns = returns[split_point:]
# Calculate Sharpe ratios
is_sharpe = self.calculate_sharpe_ratio(in_sample_returns)
oos_sharpe = self.calculate_sharpe_ratio(out_sample_returns)
# Calculate degradation
if is_sharpe > 0:
degradation = max(0, 1 - oos_sharpe / is_sharpe)
else:
degradation = 1.0
return degradation
def test_statistical_significance(
self,
strategy_returns: np.ndarray,
market_returns: Optional[np.ndarray] = None
) -> bool:
"""
Test if returns are statistically significant
"""
# Test against zero returns
t_stat, p_value = stats.ttest_1samp(strategy_returns, 0)
if p_value < (1 - self.confidence_level):
return True
# If market returns provided, test for alpha
if market_returns is not None and len(market_returns) == len(strategy_returns):
excess_returns = strategy_returns - market_returns
t_stat, p_value = stats.ttest_1samp(excess_returns, 0)
return p_value < (1 - self.confidence_level)
return False
def detect_overfitting(
self,
psr: float,
dsr: float,
mc_percentile: float,
oos_degradation: float,
num_parameters: int
) -> bool:
"""
Detect potential overfitting based on multiple criteria
"""
overfitting_score = 0
# Check PSR
if psr < 0.95:
overfitting_score += 1
# Check DSR
if dsr < 0.95:
overfitting_score += 2 # More weight on DSR
# Check Monte Carlo
if mc_percentile < 0.95:
overfitting_score += 1
# Check out-of-sample degradation
if oos_degradation > 0.5:
overfitting_score += 2
# Check parameter count
if num_parameters > 10:
overfitting_score += 1
# Decision threshold
return overfitting_score >= 3
def walk_forward_analysis(
self,
data: pd.DataFrame,
strategy_func,
window_size: int,
step_size: int,
num_windows: int = 5
) -> Dict:
"""
Perform walk-forward analysis
"""
results = {
'in_sample_sharpes': [],
'out_sample_sharpes': [],
'parameters': [],
'stability_score': 0
}
tscv = TimeSeriesSplit(n_splits=num_windows)
for train_idx, test_idx in tscv.split(data):
train_data = data.iloc[train_idx]
test_data = data.iloc[test_idx]
# Optimize on training data
best_params = self.optimize_parameters(train_data, strategy_func)
results['parameters'].append(best_params)
# Test on out-of-sample data
is_returns = strategy_func(train_data, best_params)
oos_returns = strategy_func(test_data, best_params)
is_sharpe = self.calculate_sharpe_ratio(is_returns)
oos_sharpe = self.calculate_sharpe_ratio(oos_returns)
results['in_sample_sharpes'].append(is_sharpe)
results['out_sample_sharpes'].append(oos_sharpe)
# Calculate stability score
param_stability = self.calculate_parameter_stability(results['parameters'])
performance_stability = 1 - np.std(results['out_sample_sharpes']) / (np.mean(results['out_sample_sharpes']) + 1e-6)
results['stability_score'] = (param_stability + performance_stability) / 2
return results
def calculate_parameter_stability(self, parameters_list: List[Dict]) -> float:
"""
Calculate how stable parameters are across different periods
"""
if len(parameters_list) < 2:
return 1.0
# Convert to DataFrame for easier analysis
params_df = pd.DataFrame(parameters_list)
# Calculate coefficient of variation for each parameter
stabilities = []
for col in params_df.columns:
if params_df[col].dtype in [np.float64, np.int64]:
mean_val = params_df[col].mean()
std_val = params_df[col].std()
if mean_val != 0:
cv = std_val / abs(mean_val)
stability = 1 / (1 + cv) # Convert to 0-1 scale
stabilities.append(stability)
return np.mean(stabilities) if stabilities else 0.5
def optimize_parameters(self, data: pd.DataFrame, strategy_func) -> Dict:
"""
Placeholder for parameter optimization
In practice, this would use grid search, Bayesian optimization, etc.
"""
# Simple example - would be replaced with actual optimization
return {'param1': 20, 'param2': 2.0}
def bootstrap_confidence_intervals(
self,
returns: np.ndarray,
metric_func,
confidence_level: float = 0.95,
num_samples: int = 1000
) -> Tuple[float, float, float]:
"""
Calculate bootstrap confidence intervals for any metric
"""
bootstrap_metrics = []
for _ in range(num_samples):
# Resample with replacement
sample_returns = np.random.choice(returns, size=len(returns), replace=True)
metric = metric_func(sample_returns)
bootstrap_metrics.append(metric)
# Calculate percentiles
lower_percentile = (1 - confidence_level) / 2
upper_percentile = 1 - lower_percentile
lower_bound = np.percentile(bootstrap_metrics, lower_percentile * 100)
upper_bound = np.percentile(bootstrap_metrics, upper_percentile * 100)
point_estimate = metric_func(returns)
return lower_bound, point_estimate, upper_bound
def generate_report(self, validation_result: ValidationResult) -> str:
"""
Generate human-readable validation report
"""
report = f"""
Statistical Validation Report
============================
Overall Assessment: {'PASSED' if not validation_result.is_overfit else 'FAILED'}
Confidence Level: {validation_result.confidence_level:.1%}
Key Metrics:
-----------
Probabilistic Sharpe Ratio (PSR): {validation_result.psr:.3f}
Deflated Sharpe Ratio (DSR): {validation_result.dsr:.3f}
Monte Carlo Percentile: {validation_result.monte_carlo_percentile:.1%}
Out-of-Sample Degradation: {validation_result.out_of_sample_degradation:.1%}
Statistical Significance: {'Yes' if validation_result.statistical_significance else 'No'}
Warnings:
---------
"""
for warning in validation_result.warnings:
report += f"- {warning}\n"
report += """
Recommendations:
---------------
"""
for rec in validation_result.recommendations:
report += f"- {rec}\n"
return report

View file

@ -1,217 +0,0 @@
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple
import logging
logger = logging.getLogger(__name__)
class PerformanceAnalyzer:
"""
Comprehensive performance analysis for trading strategies and portfolios
"""
def __init__(self, risk_free_rate: float = 0.02):
self.risk_free_rate = risk_free_rate
def calculate_metrics(
self,
portfolio_id: str,
start_date: datetime,
end_date: datetime
) -> Dict:
"""
Calculate comprehensive performance metrics
"""
# In real implementation, would fetch data from database
# For now, generate sample data
returns = self._generate_sample_returns(start_date, end_date)
metrics = {
'total_return': self._calculate_total_return(returns),
'annualized_return': self._calculate_annualized_return(returns),
'volatility': self._calculate_volatility(returns),
'sharpe_ratio': self._calculate_sharpe_ratio(returns),
'sortino_ratio': self._calculate_sortino_ratio(returns),
'max_drawdown': self._calculate_max_drawdown(returns),
'calmar_ratio': self._calculate_calmar_ratio(returns),
'win_rate': self._calculate_win_rate(returns),
'profit_factor': self._calculate_profit_factor(returns),
'avg_win': np.mean(returns[returns > 0]) if any(returns > 0) else 0,
'avg_loss': np.mean(returns[returns < 0]) if any(returns < 0) else 0,
'total_trades': len(returns),
'best_day': np.max(returns),
'worst_day': np.min(returns),
'skewness': self._calculate_skewness(returns),
'kurtosis': self._calculate_kurtosis(returns)
}
return metrics
def calculate_risk_metrics(
self,
portfolio_id: str,
window: int = 252,
confidence_levels: List[float] = [0.95, 0.99]
) -> Dict:
"""
Calculate risk metrics including VaR and CVaR
"""
# Generate sample returns
returns = self._generate_sample_returns(
datetime.now() - timedelta(days=window),
datetime.now()
)
risk_metrics = {
'volatility': self._calculate_volatility(returns),
'downside_deviation': self._calculate_downside_deviation(returns),
'beta': self._calculate_beta(returns), # Would need market returns
'tracking_error': 0.0, # Placeholder
}
# Calculate VaR and CVaR for each confidence level
for confidence in confidence_levels:
var = self._calculate_var(returns, confidence)
cvar = self._calculate_cvar(returns, confidence)
risk_metrics[f'var_{int(confidence*100)}'] = var
risk_metrics[f'cvar_{int(confidence*100)}'] = cvar
return risk_metrics
def analyze_backtest(self, backtest_id: str) -> Dict:
"""
Analyze backtest results
"""
# In real implementation, would fetch backtest data
# For now, return comprehensive mock analysis
return {
'metrics': {
'total_return': 0.156,
'sharpe_ratio': 1.45,
'max_drawdown': 0.087,
'win_rate': 0.58,
'profit_factor': 1.78
},
'statistics': {
'total_trades': 245,
'winning_trades': 142,
'losing_trades': 103,
'avg_holding_period': 3.5,
'max_consecutive_wins': 8,
'max_consecutive_losses': 5
},
'risk_analysis': {
'var_95': 0.024,
'cvar_95': 0.031,
'downside_deviation': 0.018,
'ulcer_index': 0.045
},
'trade_analysis': {
'best_trade': 0.087,
'worst_trade': -0.043,
'avg_win': 0.023,
'avg_loss': -0.015,
'largest_winner': 0.087,
'largest_loser': -0.043
}
}
# Helper methods
def _generate_sample_returns(self, start_date: datetime, end_date: datetime) -> np.ndarray:
"""Generate sample returns for testing"""
days = (end_date - start_date).days
# Generate returns with realistic properties
returns = np.random.normal(0.0005, 0.02, days)
# Add some autocorrelation
for i in range(1, len(returns)):
returns[i] = 0.1 * returns[i-1] + 0.9 * returns[i]
return returns
def _calculate_total_return(self, returns: np.ndarray) -> float:
"""Calculate total cumulative return"""
return np.prod(1 + returns) - 1
def _calculate_annualized_return(self, returns: np.ndarray) -> float:
"""Calculate annualized return"""
total_return = self._calculate_total_return(returns)
years = len(returns) / 252
return (1 + total_return) ** (1 / years) - 1
def _calculate_volatility(self, returns: np.ndarray) -> float:
"""Calculate annualized volatility"""
return np.std(returns) * np.sqrt(252)
def _calculate_sharpe_ratio(self, returns: np.ndarray) -> float:
"""Calculate Sharpe ratio"""
excess_returns = returns - self.risk_free_rate / 252
return np.mean(excess_returns) / np.std(excess_returns) * np.sqrt(252)
def _calculate_sortino_ratio(self, returns: np.ndarray) -> float:
"""Calculate Sortino ratio"""
excess_returns = returns - self.risk_free_rate / 252
downside_returns = excess_returns[excess_returns < 0]
downside_std = np.std(downside_returns) if len(downside_returns) > 0 else 1e-6
return np.mean(excess_returns) / downside_std * np.sqrt(252)
def _calculate_max_drawdown(self, returns: np.ndarray) -> float:
"""Calculate maximum drawdown"""
cumulative = (1 + returns).cumprod()
running_max = np.maximum.accumulate(cumulative)
drawdown = (cumulative - running_max) / running_max
return np.min(drawdown)
def _calculate_calmar_ratio(self, returns: np.ndarray) -> float:
"""Calculate Calmar ratio"""
annual_return = self._calculate_annualized_return(returns)
max_dd = abs(self._calculate_max_drawdown(returns))
return annual_return / max_dd if max_dd > 0 else 0
def _calculate_win_rate(self, returns: np.ndarray) -> float:
"""Calculate win rate"""
return np.sum(returns > 0) / len(returns) if len(returns) > 0 else 0
def _calculate_profit_factor(self, returns: np.ndarray) -> float:
"""Calculate profit factor"""
gains = returns[returns > 0]
losses = returns[returns < 0]
total_gains = np.sum(gains) if len(gains) > 0 else 0
total_losses = abs(np.sum(losses)) if len(losses) > 0 else 1e-6
return total_gains / total_losses
def _calculate_downside_deviation(self, returns: np.ndarray, mar: float = 0) -> float:
"""Calculate downside deviation"""
downside_returns = returns[returns < mar]
return np.std(downside_returns) * np.sqrt(252) if len(downside_returns) > 0 else 0
def _calculate_var(self, returns: np.ndarray, confidence: float) -> float:
"""Calculate Value at Risk"""
return np.percentile(returns, (1 - confidence) * 100)
def _calculate_cvar(self, returns: np.ndarray, confidence: float) -> float:
"""Calculate Conditional Value at Risk"""
var = self._calculate_var(returns, confidence)
return np.mean(returns[returns <= var])
def _calculate_beta(self, returns: np.ndarray, market_returns: Optional[np.ndarray] = None) -> float:
"""Calculate beta relative to market"""
if market_returns is None:
# Generate mock market returns
market_returns = np.random.normal(0.0003, 0.015, len(returns))
covariance = np.cov(returns, market_returns)[0, 1]
market_variance = np.var(market_returns)
return covariance / market_variance if market_variance > 0 else 1.0
def _calculate_skewness(self, returns: np.ndarray) -> float:
"""Calculate skewness of returns"""
mean = np.mean(returns)
std = np.std(returns)
return np.mean(((returns - mean) / std) ** 3) if std > 0 else 0
def _calculate_kurtosis(self, returns: np.ndarray) -> float:
"""Calculate kurtosis of returns"""
mean = np.mean(returns)
std = np.std(returns)
return np.mean(((returns - mean) / std) ** 4) - 3 if std > 0 else 0

View file

@ -1,284 +0,0 @@
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
from typing import Dict, List, Tuple
from scipy import stats
from sklearn.mixture import GaussianMixture
import logging
logger = logging.getLogger(__name__)
class RegimeDetector:
"""
Market regime detection using various statistical and ML methods
"""
def __init__(self):
self.regimes = ['bull', 'bear', 'sideways', 'high_volatility', 'low_volatility']
def detect_current_regime(self, lookback_days: int = 60) -> Dict:
"""
Detect current market regime using multiple indicators
"""
# In real implementation, would fetch market data
# For now, generate sample data
market_data = self._generate_market_data(lookback_days)
# Calculate various regime indicators
trend_regime = self._detect_trend_regime(market_data)
volatility_regime = self._detect_volatility_regime(market_data)
momentum_regime = self._detect_momentum_regime(market_data)
# Combine indicators for final regime
regime, confidence = self._combine_regime_indicators(
trend_regime,
volatility_regime,
momentum_regime
)
return {
'regime': regime,
'confidence': confidence,
'indicators': {
'trend': trend_regime,
'volatility': volatility_regime,
'momentum': momentum_regime,
'market_breadth': self._calculate_market_breadth(market_data),
'fear_greed_index': self._calculate_fear_greed_index(market_data)
},
'sub_regimes': {
'trend_strength': self._calculate_trend_strength(market_data),
'volatility_percentile': self._calculate_volatility_percentile(market_data),
'correlation_regime': self._detect_correlation_regime(market_data)
}
}
def _generate_market_data(self, days: int) -> pd.DataFrame:
"""Generate sample market data for testing"""
dates = pd.date_range(end=datetime.now(), periods=days, freq='D')
# Generate correlated returns for multiple assets
n_assets = 10
returns = np.random.multivariate_normal(
mean=[0.0005] * n_assets,
cov=np.eye(n_assets) * 0.0004 + np.ones((n_assets, n_assets)) * 0.0001,
size=days
)
# Create price series
prices = pd.DataFrame(
(1 + returns).cumprod(axis=0) * 100,
index=dates,
columns=[f'Asset_{i}' for i in range(n_assets)]
)
# Add market index
prices['Market'] = prices.mean(axis=1)
# Add volatility index (like VIX)
prices['Volatility'] = pd.Series(returns[:, 0]).rolling(20).std() * np.sqrt(252) * 100
return prices
def _detect_trend_regime(self, data: pd.DataFrame) -> Dict:
"""Detect trend regime using moving averages and linear regression"""
market = data['Market']
# Calculate moving averages
ma_short = market.rolling(20).mean()
ma_long = market.rolling(50).mean()
# Trend strength
current_price = market.iloc[-1]
trend_score = (current_price - ma_long.iloc[-1]) / ma_long.iloc[-1]
# Linear regression trend
x = np.arange(len(market))
slope, _, r_value, _, _ = stats.linregress(x, market.values)
# Determine regime
if trend_score > 0.05 and ma_short.iloc[-1] > ma_long.iloc[-1]:
regime = 'bull'
elif trend_score < -0.05 and ma_short.iloc[-1] < ma_long.iloc[-1]:
regime = 'bear'
else:
regime = 'sideways'
return {
'regime': regime,
'trend_score': trend_score,
'slope': slope,
'r_squared': r_value ** 2
}
def _detect_volatility_regime(self, data: pd.DataFrame) -> Dict:
"""Detect volatility regime using GARCH-like analysis"""
returns = data['Market'].pct_change().dropna()
# Calculate rolling volatility
vol_short = returns.rolling(10).std() * np.sqrt(252)
vol_long = returns.rolling(30).std() * np.sqrt(252)
current_vol = vol_short.iloc[-1]
vol_percentile = stats.percentileofscore(vol_long.dropna(), current_vol)
# Volatility regime
if vol_percentile > 75:
regime = 'high_volatility'
elif vol_percentile < 25:
regime = 'low_volatility'
else:
regime = 'normal_volatility'
# Volatility of volatility
vol_of_vol = vol_short.rolling(20).std().iloc[-1]
return {
'regime': regime,
'current_volatility': current_vol,
'volatility_percentile': vol_percentile,
'vol_of_vol': vol_of_vol
}
def _detect_momentum_regime(self, data: pd.DataFrame) -> Dict:
"""Detect momentum regime using RSI and rate of change"""
market = data['Market']
# Calculate RSI
rsi = self._calculate_rsi(market, period=14)
# Rate of change
roc_short = (market.iloc[-1] / market.iloc[-5] - 1) * 100
roc_long = (market.iloc[-1] / market.iloc[-20] - 1) * 100
# Momentum regime
if rsi > 70 and roc_short > 0:
regime = 'overbought'
elif rsi < 30 and roc_short < 0:
regime = 'oversold'
elif roc_short > 2 and roc_long > 5:
regime = 'strong_momentum'
elif roc_short < -2 and roc_long < -5:
regime = 'weak_momentum'
else:
regime = 'neutral_momentum'
return {
'regime': regime,
'rsi': rsi,
'roc_short': roc_short,
'roc_long': roc_long
}
def _detect_correlation_regime(self, data: pd.DataFrame) -> str:
"""Detect correlation regime among assets"""
# Calculate rolling correlation
asset_returns = data.iloc[:, :-2].pct_change().dropna()
corr_matrix = asset_returns.rolling(30).corr()
# Average pairwise correlation
n_assets = len(asset_returns.columns)
avg_corr = (corr_matrix.sum().sum() - n_assets) / (n_assets * (n_assets - 1))
current_avg_corr = avg_corr.iloc[-1]
if current_avg_corr > 0.7:
return 'high_correlation'
elif current_avg_corr < 0.3:
return 'low_correlation'
else:
return 'normal_correlation'
def _calculate_rsi(self, prices: pd.Series, period: int = 14) -> float:
"""Calculate RSI"""
delta = prices.diff()
gain = (delta.where(delta > 0, 0)).rolling(period).mean()
loss = (-delta.where(delta < 0, 0)).rolling(period).mean()
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
return rsi.iloc[-1]
def _calculate_market_breadth(self, data: pd.DataFrame) -> float:
"""Calculate market breadth (advance/decline ratio)"""
# Calculate daily returns for all assets
returns = data.iloc[:, :-2].pct_change().iloc[-1]
advancing = (returns > 0).sum()
declining = (returns < 0).sum()
return advancing / (advancing + declining) if (advancing + declining) > 0 else 0.5
def _calculate_fear_greed_index(self, data: pd.DataFrame) -> float:
"""Simplified fear & greed index"""
# Combine multiple indicators
volatility = data['Volatility'].iloc[-1]
momentum = self._detect_momentum_regime(data)['roc_short']
breadth = self._calculate_market_breadth(data)
# Normalize and combine
vol_score = 1 - min(volatility / 40, 1) # Lower vol = higher greed
momentum_score = (momentum + 10) / 20 # Normalize to 0-1
fear_greed = (vol_score + momentum_score + breadth) / 3
return fear_greed * 100 # 0 = extreme fear, 100 = extreme greed
def _calculate_trend_strength(self, data: pd.DataFrame) -> float:
"""Calculate trend strength using ADX-like indicator"""
market = data['Market']
# Calculate directional movement
high = market.rolling(2).max()
low = market.rolling(2).min()
plus_dm = (high - high.shift(1)).where(lambda x: x > 0, 0)
minus_dm = (low.shift(1) - low).where(lambda x: x > 0, 0)
# Smooth and normalize
period = 14
plus_di = plus_dm.rolling(period).mean() / market.rolling(period).std()
minus_di = minus_dm.rolling(period).mean() / market.rolling(period).std()
# Calculate trend strength
dx = abs(plus_di - minus_di) / (plus_di + minus_di)
adx = dx.rolling(period).mean().iloc[-1]
return min(adx * 100, 100) if not np.isnan(adx) else 50
def _calculate_volatility_percentile(self, data: pd.DataFrame) -> float:
"""Calculate current volatility percentile"""
volatility_regime = self._detect_volatility_regime(data)
return volatility_regime['volatility_percentile']
def _combine_regime_indicators(
self,
trend: Dict,
volatility: Dict,
momentum: Dict
) -> Tuple[str, float]:
"""Combine multiple indicators to determine overall regime"""
# Simple weighted combination
regimes = []
weights = []
# Trend regime
if trend['regime'] in ['bull', 'bear']:
regimes.append(trend['regime'])
weights.append(abs(trend['trend_score']) * 10)
# Volatility regime
if volatility['regime'] == 'high_volatility':
regimes.append('high_volatility')
weights.append(volatility['volatility_percentile'] / 100)
# Choose dominant regime
if not regimes:
return 'sideways', 0.5
# Weight by confidence
dominant_idx = np.argmax(weights)
regime = regimes[dominant_idx]
confidence = min(weights[dominant_idx], 1.0)
return regime, confidence

View file

@ -1,63 +0,0 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import logging
from .endpoints import optimization, analytics, models
from . import capabilities
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
logger.info("Starting Trading Analytics Service...")
# Initialize connections, load models, etc.
yield
# Shutdown
logger.info("Shutting down Trading Analytics Service...")
# Create FastAPI app
app = FastAPI(
title="Trading Analytics Service",
description="Complex analytics, optimization, and ML inference for trading",
version="0.1.0",
lifespan=lifespan
)
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Configure appropriately for production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(optimization.router, prefix="/optimize", tags=["optimization"])
app.include_router(analytics.router, prefix="/analytics", tags=["analytics"])
app.include_router(models.router, prefix="/models", tags=["models"])
@app.get("/")
async def root():
return {
"service": "Trading Analytics",
"status": "available",
"version": "0.1.0"
}
@app.get("/health")
async def health_check():
return {
"status": "degraded",
"components": {
"performance_analyzer": {"status": "unavailable", "reason": "observed_data_not_integrated"},
"regime_detector": {"status": "unavailable", "reason": "observed_data_not_integrated"},
"portfolio_optimizer": capabilities.portfolio_optimizer.status(),
"model_runtime": capabilities.model_runtime.status(),
"model_upload": capabilities.model_upload.status(),
}
}

View file

@ -1,88 +0,0 @@
"""Optional runtimes are loaded on first use, independently of app/router imports."""
from dataclasses import dataclass
import logging
from threading import Lock
from typing import Any, Callable
from fastapi import HTTPException
logger = logging.getLogger(__name__)
class LazyCapability:
def __init__(self, name: str, load: Callable[[], Any]):
self.name = name
self.load = load
self._lock = Lock()
self._value = None
self._state = "uninitialized"
self._failure = None
def get(self):
with self._lock:
if self._state == "uninitialized":
try:
self._value = self.load()
self._state = "ready"
except Exception as error:
logger.exception("Optional capability %s could not initialize", self.name)
self._state = "unavailable"
self._failure = {
"code": "analytics_capability_unavailable",
"capability": self.name,
"reason": "missing_dependency" if isinstance(error, ImportError) else "initialization_failed",
"message": f"Optional analytics capability '{self.name}' is unavailable",
}
if isinstance(error, ImportError) and error.name:
self._failure["dependency"] = error.name
if self._failure is not None:
raise HTTPException(status_code=503, detail=dict(self._failure))
return self._value
def status(self):
# Health observes state; it must not load scientific runtimes as a side effect.
with self._lock:
return {"status": self._state, **(self._failure or {})}
@dataclass(frozen=True)
class OptimizationRuntime:
numpy: Any
optimizer: Any
@dataclass(frozen=True)
class ModelRuntime:
numpy: Any
onnx: Any
def _load_optimizer():
import numpy
from ..optimization.portfolio_optimizer import PortfolioOptimizer
return OptimizationRuntime(numpy, PortfolioOptimizer())
def _load_models():
import numpy
import onnxruntime
return ModelRuntime(numpy, onnxruntime)
def _load_multipart():
# FastAPI's File(...) would demand this package while registering the route.
from multipart.multipart import parse_options_header
return parse_options_header
portfolio_optimizer = LazyCapability("portfolio_optimizer", _load_optimizer)
model_runtime = LazyCapability("model_runtime", _load_models)
model_upload = LazyCapability("model_upload", _load_multipart)
def get_optimization_runtime():
return portfolio_optimizer.get()
def get_model_runtime():
return model_runtime.get()

View file

@ -1,72 +0,0 @@
"""Observed-data endpoints fail closed until an actual portfolio/history adapter exists.
Optimization and loaded-model prediction use their own caller/model inputs. These routes
must not turn random samples, placeholder attributions or constant reports into observations.
"""
from datetime import date, datetime
from typing import List, NoReturn, Optional
from fastapi import APIRouter, HTTPException, Query
router = APIRouter()
def unavailable() -> NoReturn:
raise HTTPException(
status_code=503,
detail={
"code": "analytics_data_unavailable",
"message": "Observed portfolio, benchmark and backtest data are not integrated",
},
)
@router.get("/performance/{portfolio_id}")
async def get_performance_metrics(
portfolio_id: str,
start_date: datetime = Query(...),
end_date: datetime = Query(...),
):
if end_date <= start_date:
raise HTTPException(status_code=400, detail="end_date must follow start_date")
unavailable()
@router.get("/risk/{portfolio_id}")
async def get_risk_metrics(portfolio_id: str, window: int = Query(252, ge=1)):
unavailable()
@router.get("/regime")
async def detect_market_regime(lookback_days: int = Query(60, ge=1)):
unavailable()
@router.post("/correlation")
async def calculate_correlation_matrix(
symbols: List[str],
start_date: Optional[date] = None,
end_date: Optional[date] = None,
method: str = Query("pearson", pattern="^(pearson|spearman|kendall)$"),
):
if len(symbols) < 2 or len(set(symbols)) != len(symbols):
raise HTTPException(status_code=400, detail="At least two distinct symbols are required")
unavailable()
@router.get("/backtest/{backtest_id}")
async def analyze_backtest_results(backtest_id: str):
unavailable()
@router.post("/attribution")
async def performance_attribution(
portfolio_id: str,
benchmark: str,
start_date: date,
end_date: date,
method: str = Query("brinson", pattern="^(brinson|factor|risk)$"),
):
if end_date <= start_date:
raise HTTPException(status_code=400, detail="end_date must follow start_date")
unavailable()

View file

@ -1,211 +0,0 @@
from fastapi import APIRouter, HTTPException, Request
from starlette.datastructures import UploadFile
from starlette.exceptions import HTTPException as StarletteHTTPException
from pydantic import BaseModel
from typing import Dict, Any, List, Optional, Union
import json
import logging
from ..capabilities import get_model_runtime, model_upload
logger = logging.getLogger(__name__)
router = APIRouter()
# In-memory model storage (in production, use proper model registry)
loaded_models = {}
class PredictionRequest(BaseModel):
model_id: str
features: Dict[str, float]
class PredictionResponse(BaseModel):
model_id: str
prediction: float
probability: Optional[Dict[str, float]] = None
metadata: Optional[Dict[str, Any]] = None
class ModelInfo(BaseModel):
model_id: str
name: str
version: str
type: str
input_features: List[str]
# One shape per ONNX output; dimensions may be symbolic or unspecified.
output_shape: List[List[Union[int, str, None]]]
metadata: Dict[str, Any]
@router.post("/predict", response_model=PredictionResponse)
async def predict(request: PredictionRequest):
"""
Run inference on a loaded model
"""
try:
if request.model_id not in loaded_models:
raise HTTPException(status_code=404, detail=f"Model {request.model_id} not found")
np = get_model_runtime().numpy
model_info = loaded_models[request.model_id]
session = model_info['session']
# Prepare input
input_features = model_info['input_features']
input_array = np.array([[request.features.get(f, 0.0) for f in input_features]], dtype=np.float32)
# Run inference
input_name = session.get_inputs()[0].name
output = session.run(None, {input_name: input_array})
# Process output
prediction = float(output[0][0])
# For classification models, get probabilities
probability = None
if model_info['type'] == 'classification' and len(output[0][0]) > 1:
probability = {
f"class_{i}": float(p)
for i, p in enumerate(output[0][0])
}
return PredictionResponse(
model_id=request.model_id,
prediction=prediction,
probability=probability,
metadata={
"model_version": model_info['version'],
"timestamp": np.datetime64('now').tolist()
}
)
except StarletteHTTPException:
raise
except Exception as e:
logger.error(f"Prediction failed: {str(e)}")
raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}")
@router.post("/load", openapi_extra={
"requestBody": {
"required": True,
"content": {"multipart/form-data": {"schema": {
"type": "object",
"required": ["model_file"],
"properties": {"model_file": {"type": "string", "format": "binary"}},
}}},
},
})
async def load_model(
model_id: str,
request: Request,
metadata: str = None
):
"""
Load an ONNX model for inference
"""
try:
runtime = get_model_runtime()
model_upload.get()
# Parse only on upload, so an absent multipart package cannot block app startup.
async with request.form() as form:
model_file = form.get('model_file')
if not isinstance(model_file, UploadFile):
raise HTTPException(status_code=422, detail=[{
"loc": ["body", "model_file"],
"msg": "A model_file upload is required",
"type": "value_error.missing",
}])
content = await model_file.read()
# Create ONNX session
session = runtime.onnx.InferenceSession(content)
# Parse metadata
model_metadata = json.loads(metadata) if metadata else {}
# Extract model info
input_features = [inp.name for inp in session.get_inputs()]
output_shape = [out.shape for out in session.get_outputs()]
# Store model
loaded_models[model_id] = {
'session': session,
'input_features': model_metadata.get('feature_names', input_features),
'type': model_metadata.get('model_type', 'regression'),
'version': model_metadata.get('version', '1.0'),
'metadata': model_metadata
}
return {
"message": f"Model {model_id} loaded successfully",
"input_features": input_features,
"output_shape": output_shape
}
except StarletteHTTPException:
raise
except Exception as e:
logger.error(f"Failed to load model: {str(e)}")
raise HTTPException(status_code=500, detail=f"Failed to load model: {str(e)}")
@router.get("/list", response_model=List[ModelInfo])
async def list_models():
"""
List all loaded models
"""
models = []
for model_id, info in loaded_models.items():
session = info['session']
models.append(ModelInfo(
model_id=model_id,
name=info['metadata'].get('name', model_id),
version=info['version'],
type=info['type'],
input_features=info['input_features'],
output_shape=[out.shape for out in session.get_outputs()],
metadata=info['metadata']
))
return models
@router.delete("/{model_id}")
async def unload_model(model_id: str):
"""
Unload a model from memory
"""
if model_id not in loaded_models:
raise HTTPException(status_code=404, detail=f"Model {model_id} not found")
del loaded_models[model_id]
return {"message": f"Model {model_id} unloaded successfully"}
@router.post("/batch_predict")
async def batch_predict(
model_id: str,
features: List[Dict[str, float]]
):
"""
Run batch predictions
"""
try:
if model_id not in loaded_models:
raise HTTPException(status_code=404, detail=f"Model {model_id} not found")
predictions = []
for feature_set in features:
request = PredictionRequest(model_id=model_id, features=feature_set)
result = await predict(request)
predictions.append(result.dict())
return {
"model_id": model_id,
"predictions": predictions,
"count": len(predictions)
}
except StarletteHTTPException:
raise
except Exception as e:
logger.error(f"Batch prediction failed: {str(e)}")
raise HTTPException(status_code=500, detail=f"Batch prediction failed: {str(e)}")

View file

@ -1,120 +0,0 @@
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel, Field
from typing import List, Optional, Dict
from ..capabilities import OptimizationRuntime, get_optimization_runtime
router = APIRouter()
class OptimizationConstraints(BaseModel):
min_weight: Optional[float] = Field(0.0, ge=0.0, le=1.0)
max_weight: Optional[float] = Field(1.0, ge=0.0, le=1.0)
target_return: Optional[float] = None
max_risk: Optional[float] = None
class PortfolioOptimizationRequest(BaseModel):
symbols: List[str]
returns: List[List[float]]
constraints: Optional[OptimizationConstraints] = None
method: str = Field("mean_variance", pattern="^(mean_variance|min_variance|max_sharpe|risk_parity|black_litterman)$")
class PortfolioWeights(BaseModel):
symbols: List[str]
weights: List[float]
expected_return: float
expected_risk: float
sharpe_ratio: float
@router.post("/portfolio", response_model=PortfolioWeights)
async def optimize_portfolio(
request: PortfolioOptimizationRequest,
runtime: OptimizationRuntime = Depends(get_optimization_runtime)
):
"""
Optimize portfolio weights using various methods
"""
try:
# Convert returns to numpy array
returns_array = runtime.numpy.array(request.returns)
# Validate dimensions
if len(request.symbols) != returns_array.shape[1]:
raise HTTPException(
status_code=400,
detail="Number of symbols must match number of return columns"
)
# Run optimization
result = runtime.optimizer.optimize(
returns=returns_array,
method=request.method,
constraints=request.constraints.dict() if request.constraints else None
)
return PortfolioWeights(
symbols=request.symbols,
weights=result['weights'].tolist(),
expected_return=float(result['expected_return']),
expected_risk=float(result['expected_risk']),
sharpe_ratio=float(result['sharpe_ratio'])
)
except HTTPException:
raise
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=f"Optimization failed: {str(e)}")
@router.post("/efficient_frontier")
async def calculate_efficient_frontier(
request: PortfolioOptimizationRequest,
num_portfolios: int = 100,
runtime: OptimizationRuntime = Depends(get_optimization_runtime)
):
"""
Calculate the efficient frontier for a set of assets
"""
try:
returns_array = runtime.numpy.array(request.returns)
frontier = runtime.optimizer.calculate_efficient_frontier(
returns=returns_array,
num_portfolios=num_portfolios
)
return {
"symbols": request.symbols,
"frontier": frontier
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to calculate efficient frontier: {str(e)}")
@router.post("/rebalance")
async def suggest_rebalance(
current_weights: Dict[str, float],
target_weights: Dict[str, float],
constraints: Optional[Dict[str, float]] = None
):
"""
Suggest trades to rebalance portfolio from current to target weights
"""
try:
# Calculate differences
trades = {}
for symbol in target_weights:
current = current_weights.get(symbol, 0.0)
target = target_weights[symbol]
diff = target - current
if abs(diff) > 0.001: # Ignore tiny differences
trades[symbol] = diff
return {
"trades": trades,
"total_turnover": sum(abs(t) for t in trades.values())
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Rebalance calculation failed: {str(e)}")

View file

@ -1,481 +0,0 @@
import numpy as np
import pandas as pd
from typing import Dict, List, Tuple, Optional, Union
import talib
from scipy import stats
from sklearn.preprocessing import StandardScaler, RobustScaler
import logging
logger = logging.getLogger(__name__)
class FeatureEngineer:
"""
Feature engineering for financial ML models
"""
def __init__(self, lookback_periods: List[int] = None):
self.lookback_periods = lookback_periods or [5, 10, 20, 50, 100, 200]
self.scaler = RobustScaler() # Robust to outliers
self.feature_names: List[str] = []
def create_features(
self,
data: pd.DataFrame,
include_technical: bool = True,
include_microstructure: bool = True,
include_fundamental: bool = False,
include_sentiment: bool = False
) -> pd.DataFrame:
"""
Create comprehensive feature set for ML models
"""
features = pd.DataFrame(index=data.index)
# Price-based features
logger.info("Creating price-based features...")
price_features = self._create_price_features(data)
features = pd.concat([features, price_features], axis=1)
# Technical indicators
if include_technical:
logger.info("Creating technical indicators...")
tech_features = self._create_technical_features(data)
features = pd.concat([features, tech_features], axis=1)
# Microstructure features
if include_microstructure:
logger.info("Creating microstructure features...")
micro_features = self._create_microstructure_features(data)
features = pd.concat([features, micro_features], axis=1)
# Fundamental features (if available)
if include_fundamental and 'earnings' in data.columns:
logger.info("Creating fundamental features...")
fund_features = self._create_fundamental_features(data)
features = pd.concat([features, fund_features], axis=1)
# Sentiment features (if available)
if include_sentiment and 'sentiment' in data.columns:
logger.info("Creating sentiment features...")
sent_features = self._create_sentiment_features(data)
features = pd.concat([features, sent_features], axis=1)
# Time-based features
logger.info("Creating time-based features...")
time_features = self._create_time_features(data)
features = pd.concat([features, time_features], axis=1)
# Cross-sectional features (if multiple symbols)
if 'symbol' in data.columns and data['symbol'].nunique() > 1:
logger.info("Creating cross-sectional features...")
cross_features = self._create_cross_sectional_features(data)
features = pd.concat([features, cross_features], axis=1)
# Store feature names
self.feature_names = features.columns.tolist()
# Handle missing values
features = self._handle_missing_values(features)
return features
def _create_price_features(self, data: pd.DataFrame) -> pd.DataFrame:
"""Create price-based features"""
features = pd.DataFrame(index=data.index)
# Returns at different horizons
for period in self.lookback_periods:
features[f'returns_{period}'] = data['close'].pct_change(period)
features[f'log_returns_{period}'] = np.log(data['close'] / data['close'].shift(period))
# Price ratios
features['high_low_ratio'] = data['high'] / data['low']
features['close_open_ratio'] = data['close'] / data['open']
# Price position in range
features['price_position'] = (data['close'] - data['low']) / (data['high'] - data['low']).replace(0, np.nan)
# Volume-weighted metrics
if 'volume' in data.columns:
features['vwap'] = (data['close'] * data['volume']).rolling(20).sum() / data['volume'].rolling(20).sum()
features['volume_ratio'] = data['volume'] / data['volume'].rolling(20).mean()
features['dollar_volume'] = data['close'] * data['volume']
# Volatility measures
for period in [5, 20, 50]:
features[f'volatility_{period}'] = data['close'].pct_change().rolling(period).std() * np.sqrt(252)
features[f'realized_var_{period}'] = (data['close'].pct_change() ** 2).rolling(period).sum()
# Price momentum
features['momentum_1m'] = data['close'] / data['close'].shift(20) - 1
features['momentum_3m'] = data['close'] / data['close'].shift(60) - 1
features['momentum_6m'] = data['close'] / data['close'].shift(120) - 1
# Relative strength
for short, long in [(10, 30), (20, 50), (50, 200)]:
features[f'rs_{short}_{long}'] = (
data['close'].rolling(short).mean() /
data['close'].rolling(long).mean()
)
return features
def _create_technical_features(self, data: pd.DataFrame) -> pd.DataFrame:
"""Create technical indicator features"""
features = pd.DataFrame(index=data.index)
# Moving averages
for period in self.lookback_periods:
sma = talib.SMA(data['close'].values, timeperiod=period)
ema = talib.EMA(data['close'].values, timeperiod=period)
features[f'sma_{period}'] = sma
features[f'ema_{period}'] = ema
features[f'price_to_sma_{period}'] = data['close'] / sma
# Bollinger Bands
for period in [20, 50]:
upper, middle, lower = talib.BBANDS(
data['close'].values,
timeperiod=period,
nbdevup=2,
nbdevdn=2
)
features[f'bb_upper_{period}'] = upper
features[f'bb_lower_{period}'] = lower
features[f'bb_width_{period}'] = (upper - lower) / middle
features[f'bb_position_{period}'] = (data['close'] - lower) / (upper - lower)
# RSI
for period in [14, 28]:
features[f'rsi_{period}'] = talib.RSI(data['close'].values, timeperiod=period)
# MACD
macd, signal, hist = talib.MACD(data['close'].values)
features['macd'] = macd
features['macd_signal'] = signal
features['macd_hist'] = hist
# Stochastic
slowk, slowd = talib.STOCH(
data['high'].values,
data['low'].values,
data['close'].values
)
features['stoch_k'] = slowk
features['stoch_d'] = slowd
# ADX (Average Directional Index)
features['adx'] = talib.ADX(
data['high'].values,
data['low'].values,
data['close'].values
)
# ATR (Average True Range)
for period in [14, 20]:
features[f'atr_{period}'] = talib.ATR(
data['high'].values,
data['low'].values,
data['close'].values,
timeperiod=period
)
# CCI (Commodity Channel Index)
features['cci'] = talib.CCI(
data['high'].values,
data['low'].values,
data['close'].values
)
# Williams %R
features['williams_r'] = talib.WILLR(
data['high'].values,
data['low'].values,
data['close'].values
)
# OBV (On Balance Volume)
if 'volume' in data.columns:
features['obv'] = talib.OBV(data['close'].values, data['volume'].values)
features['obv_ema'] = talib.EMA(features['obv'].values, timeperiod=20)
return features
def _create_microstructure_features(self, data: pd.DataFrame) -> pd.DataFrame:
"""Create market microstructure features"""
features = pd.DataFrame(index=data.index)
# Spread estimation (using high-low)
features['hl_spread'] = 2 * (data['high'] - data['low']) / (data['high'] + data['low'])
features['hl_spread_ma'] = features['hl_spread'].rolling(20).mean()
# Roll's implied spread
if len(data) > 2:
returns = data['close'].pct_change()
features['roll_spread'] = 2 * np.sqrt(-returns.rolling(20).cov(returns.shift(1)))
# Amihud illiquidity
if 'volume' in data.columns:
features['amihud'] = (returns.abs() / (data['volume'] * data['close'])).rolling(20).mean() * 1e6
features['log_amihud'] = np.log(features['amihud'].replace(0, np.nan) + 1e-10)
# Kyle's lambda (price impact)
if 'volume' in data.columns:
# Simplified version using rolling regression
for period in [20, 50]:
price_changes = data['close'].pct_change()
signed_volume = data['volume'] * np.sign(price_changes)
# Rolling correlation as proxy for Kyle's lambda
features[f'kyle_lambda_{period}'] = (
price_changes.rolling(period).corr(signed_volume) *
price_changes.rolling(period).std() /
signed_volume.rolling(period).std()
)
# Intraday patterns
if 'timestamp' in data.columns:
data['hour'] = pd.to_datetime(data['timestamp']).dt.hour
data['minute'] = pd.to_datetime(data['timestamp']).dt.minute
# Time since market open (assuming 9:30 AM open)
features['minutes_since_open'] = (data['hour'] - 9) * 60 + data['minute'] - 30
features['minutes_to_close'] = 390 - features['minutes_since_open'] # 6.5 hour day
# Normalized time of day
features['time_of_day_norm'] = features['minutes_since_open'] / 390
# Order flow imbalance proxy
features['high_low_imbalance'] = (data['high'] - data['close']) / (data['close'] - data['low'] + 1e-10)
features['close_position_in_range'] = (data['close'] - data['low']) / (data['high'] - data['low'] + 1e-10)
return features
def _create_fundamental_features(self, data: pd.DataFrame) -> pd.DataFrame:
"""Create fundamental analysis features"""
features = pd.DataFrame(index=data.index)
# Price to earnings
if 'earnings' in data.columns:
features['pe_ratio'] = data['close'] / data['earnings']
features['earnings_yield'] = data['earnings'] / data['close']
features['pe_relative'] = features['pe_ratio'] / features['pe_ratio'].rolling(252).mean()
# Price to book
if 'book_value' in data.columns:
features['pb_ratio'] = data['close'] / data['book_value']
features['pb_relative'] = features['pb_ratio'] / features['pb_ratio'].rolling(252).mean()
# Dividend yield
if 'dividends' in data.columns:
features['dividend_yield'] = data['dividends'].rolling(252).sum() / data['close']
features['dividend_growth'] = data['dividends'].pct_change(252)
# Sales/Revenue metrics
if 'revenue' in data.columns:
features['price_to_sales'] = data['close'] * data['shares_outstanding'] / data['revenue']
features['revenue_growth'] = data['revenue'].pct_change(4) # YoY for quarterly
# Profitability metrics
if 'net_income' in data.columns and 'total_assets' in data.columns:
features['roe'] = data['net_income'] / data['shareholders_equity']
features['roa'] = data['net_income'] / data['total_assets']
features['profit_margin'] = data['net_income'] / data['revenue']
return features
def _create_sentiment_features(self, data: pd.DataFrame) -> pd.DataFrame:
"""Create sentiment-based features"""
features = pd.DataFrame(index=data.index)
if 'sentiment' in data.columns:
# Raw sentiment
features['sentiment'] = data['sentiment']
features['sentiment_ma'] = data['sentiment'].rolling(20).mean()
features['sentiment_std'] = data['sentiment'].rolling(20).std()
# Sentiment momentum
features['sentiment_change'] = data['sentiment'].pct_change(5)
features['sentiment_momentum'] = data['sentiment'] - data['sentiment'].shift(20)
# Sentiment extremes
features['sentiment_zscore'] = (
(data['sentiment'] - features['sentiment_ma']) /
features['sentiment_std']
)
# Sentiment divergence from price
price_zscore = (data['close'] - data['close'].rolling(20).mean()) / data['close'].rolling(20).std()
features['sentiment_price_divergence'] = features['sentiment_zscore'] - price_zscore
# News volume features
if 'news_count' in data.columns:
features['news_volume'] = data['news_count']
features['news_volume_ma'] = data['news_count'].rolling(5).mean()
features['news_spike'] = data['news_count'] / features['news_volume_ma']
# Social media features
if 'twitter_mentions' in data.columns:
features['social_volume'] = data['twitter_mentions']
features['social_momentum'] = data['twitter_mentions'].pct_change(1)
features['social_vs_avg'] = data['twitter_mentions'] / data['twitter_mentions'].rolling(20).mean()
return features
def _create_time_features(self, data: pd.DataFrame) -> pd.DataFrame:
"""Create time-based features"""
features = pd.DataFrame(index=data.index)
if 'timestamp' in data.columns:
timestamps = pd.to_datetime(data['timestamp'])
# Day of week
features['day_of_week'] = timestamps.dt.dayofweek
features['is_monday'] = (features['day_of_week'] == 0).astype(int)
features['is_friday'] = (features['day_of_week'] == 4).astype(int)
# Month
features['month'] = timestamps.dt.month
features['is_quarter_end'] = timestamps.dt.month.isin([3, 6, 9, 12]).astype(int)
features['is_year_end'] = timestamps.dt.month.eq(12).astype(int)
# Trading day in month
features['trading_day_of_month'] = timestamps.dt.day
features['trading_day_of_year'] = timestamps.dt.dayofyear
# Seasonality features
features['sin_day_of_year'] = np.sin(2 * np.pi * features['trading_day_of_year'] / 365)
features['cos_day_of_year'] = np.cos(2 * np.pi * features['trading_day_of_year'] / 365)
# Options expiration week (third Friday)
features['is_opex_week'] = self._is_options_expiration_week(timestamps)
# Fed meeting weeks (approximate)
features['is_fed_week'] = self._is_fed_meeting_week(timestamps)
return features
def _create_cross_sectional_features(self, data: pd.DataFrame) -> pd.DataFrame:
"""Create features comparing across multiple symbols"""
features = pd.DataFrame(index=data.index)
# Calculate market averages
market_returns = data.groupby('timestamp')['close'].mean().pct_change()
market_volume = data.groupby('timestamp')['volume'].mean()
# Relative performance
data['returns'] = data.groupby('symbol')['close'].pct_change()
features['relative_returns'] = data['returns'] - market_returns[data['timestamp']].values
features['relative_volume'] = data['volume'] / market_volume[data['timestamp']].values
# Sector/market correlation
for period in [20, 50]:
rolling_corr = data.groupby('symbol')['returns'].rolling(period).corr(market_returns)
features[f'market_correlation_{period}'] = rolling_corr
# Cross-sectional momentum
features['cross_sectional_rank'] = data.groupby('timestamp')['returns'].rank(pct=True)
return features
def _handle_missing_values(self, features: pd.DataFrame) -> pd.DataFrame:
"""Handle missing values in features"""
# Forward fill for small gaps
features = features.fillna(method='ffill', limit=5)
# For remaining NaNs, use median of non-missing values
for col in features.columns:
if features[col].isna().any():
median_val = features[col].median()
features[col].fillna(median_val, inplace=True)
# Replace any infinities
features = features.replace([np.inf, -np.inf], np.nan)
features = features.fillna(0)
return features
def _is_options_expiration_week(self, timestamps: pd.Series) -> pd.Series:
"""Identify options expiration weeks (third Friday of month)"""
# This is a simplified version
is_third_week = (timestamps.dt.day >= 15) & (timestamps.dt.day <= 21)
is_friday = timestamps.dt.dayofweek == 4
return (is_third_week & is_friday).astype(int)
def _is_fed_meeting_week(self, timestamps: pd.Series) -> pd.Series:
"""Identify approximate Fed meeting weeks"""
# Fed typically meets 8 times per year, roughly every 6 weeks
# This is a simplified approximation
week_of_year = timestamps.dt.isocalendar().week
return (week_of_year % 6 == 0).astype(int)
def transform_features(
self,
features: pd.DataFrame,
method: str = 'robust',
clip_outliers: bool = True,
clip_quantile: float = 0.01
) -> pd.DataFrame:
"""
Transform features for ML models
"""
transformed = features.copy()
# Clip outliers if requested
if clip_outliers:
lower = features.quantile(clip_quantile)
upper = features.quantile(1 - clip_quantile)
transformed = features.clip(lower=lower, upper=upper, axis=1)
# Scale features
if method == 'robust':
scaler = RobustScaler()
elif method == 'standard':
scaler = StandardScaler()
else:
raise ValueError(f"Unknown scaling method: {method}")
scaled_values = scaler.fit_transform(transformed)
transformed = pd.DataFrame(
scaled_values,
index=features.index,
columns=features.columns
)
self.scaler = scaler
return transformed
def get_feature_importance(
self,
features: pd.DataFrame,
target: pd.Series,
method: str = 'mutual_info'
) -> pd.DataFrame:
"""
Calculate feature importance scores
"""
importance_scores = {}
if method == 'mutual_info':
from sklearn.feature_selection import mutual_info_regression
scores = mutual_info_regression(features, target)
importance_scores['mutual_info'] = scores
elif method == 'correlation':
scores = features.corrwith(target).abs()
importance_scores['correlation'] = scores.values
elif method == 'random_forest':
from sklearn.ensemble import RandomForestRegressor
rf = RandomForestRegressor(n_estimators=100, random_state=42)
rf.fit(features, target)
importance_scores['rf_importance'] = rf.feature_importances_
# Create DataFrame with results
importance_df = pd.DataFrame(
importance_scores,
index=features.columns
).sort_values(by=list(importance_scores.keys())[0], ascending=False)
return importance_df

View file

@ -1,354 +0,0 @@
import numpy as np
import pandas as pd
import cvxpy as cp
from typing import Dict, List, Optional, Tuple
import logging
logger = logging.getLogger(__name__)
class PortfolioOptimizer:
"""
Portfolio optimization using various methods
"""
def __init__(self, risk_free_rate: float = 0.02):
self.risk_free_rate = risk_free_rate
def optimize(
self,
returns: np.ndarray,
method: str = 'mean_variance',
constraints: Optional[Dict] = None
) -> Dict:
"""
Optimize portfolio weights using specified method
"""
if method == 'mean_variance':
return self._mean_variance_optimization(returns, constraints)
elif method == 'min_variance':
return self._minimum_variance_optimization(returns, constraints)
elif method == 'max_sharpe':
return self._maximum_sharpe_optimization(returns, constraints)
elif method == 'risk_parity':
return self._risk_parity_optimization(returns)
elif method == 'black_litterman':
return self._black_litterman_optimization(returns, constraints)
else:
raise ValueError(f"Unknown optimization method: {method}")
def _mean_variance_optimization(
self,
returns: np.ndarray,
constraints: Optional[Dict] = None
) -> Dict:
"""
Classical Markowitz mean-variance optimization
"""
n_assets = returns.shape[1]
# Calculate expected returns and covariance
expected_returns = np.mean(returns, axis=0)
cov_matrix = np.cov(returns.T)
# Add small value to diagonal for numerical stability
cov_matrix += np.eye(n_assets) * 1e-6
# Define optimization variables
weights = cp.Variable(n_assets)
# Define objective (maximize return - lambda * risk)
risk_aversion = 2.0 # Can be parameterized
portfolio_return = expected_returns @ weights
portfolio_risk = cp.quad_form(weights, cov_matrix)
objective = cp.Maximize(portfolio_return - risk_aversion * portfolio_risk)
# Define constraints
constraints_list = [
cp.sum(weights) == 1, # Weights sum to 1
weights >= 0, # No short selling (can be relaxed)
]
# Add custom constraints
if constraints:
if 'min_weight' in constraints:
constraints_list.append(weights >= constraints['min_weight'])
if 'max_weight' in constraints:
constraints_list.append(weights <= constraints['max_weight'])
if 'target_return' in constraints:
constraints_list.append(portfolio_return >= constraints['target_return'])
if 'max_risk' in constraints:
max_variance = constraints['max_risk'] ** 2
constraints_list.append(portfolio_risk <= max_variance)
# Solve optimization
problem = cp.Problem(objective, constraints_list)
problem.solve()
if problem.status != 'optimal':
logger.warning(f"Optimization status: {problem.status}")
# Return equal weights as fallback
weights_array = np.ones(n_assets) / n_assets
else:
weights_array = weights.value
# Calculate portfolio metrics
portfolio_return = expected_returns @ weights_array
portfolio_risk = np.sqrt(weights_array @ cov_matrix @ weights_array)
sharpe_ratio = (portfolio_return - self.risk_free_rate) / portfolio_risk
return {
'weights': weights_array,
'expected_return': portfolio_return * 252, # Annualized
'expected_risk': portfolio_risk * np.sqrt(252), # Annualized
'sharpe_ratio': sharpe_ratio * np.sqrt(252)
}
def _minimum_variance_optimization(
self,
returns: np.ndarray,
constraints: Optional[Dict] = None
) -> Dict:
"""
Minimize portfolio variance
"""
n_assets = returns.shape[1]
cov_matrix = np.cov(returns.T)
cov_matrix += np.eye(n_assets) * 1e-6
# Define optimization
weights = cp.Variable(n_assets)
portfolio_risk = cp.quad_form(weights, cov_matrix)
objective = cp.Minimize(portfolio_risk)
constraints_list = [
cp.sum(weights) == 1,
weights >= 0,
]
# Solve
problem = cp.Problem(objective, constraints_list)
problem.solve()
weights_array = weights.value if problem.status == 'optimal' else np.ones(n_assets) / n_assets
# Calculate metrics
expected_returns = np.mean(returns, axis=0)
portfolio_return = expected_returns @ weights_array
portfolio_risk = np.sqrt(weights_array @ cov_matrix @ weights_array)
sharpe_ratio = (portfolio_return - self.risk_free_rate / 252) / portfolio_risk
return {
'weights': weights_array,
'expected_return': portfolio_return * 252,
'expected_risk': portfolio_risk * np.sqrt(252),
'sharpe_ratio': sharpe_ratio * np.sqrt(252)
}
def _maximum_sharpe_optimization(
self,
returns: np.ndarray,
constraints: Optional[Dict] = None
) -> Dict:
"""
Maximize Sharpe ratio
"""
# This is a bit tricky as Sharpe ratio is not convex
# We use a trick: for each target return, find min variance
# Then select the portfolio with highest Sharpe
n_assets = returns.shape[1]
expected_returns = np.mean(returns, axis=0)
cov_matrix = np.cov(returns.T)
# Generate efficient frontier
target_returns = np.linspace(
np.min(expected_returns),
np.max(expected_returns),
50
)
best_sharpe = -np.inf
best_weights = None
for target_ret in target_returns:
weights = cp.Variable(n_assets)
portfolio_risk = cp.quad_form(weights, cov_matrix)
objective = cp.Minimize(portfolio_risk)
constraints_list = [
cp.sum(weights) == 1,
weights >= 0,
expected_returns @ weights >= target_ret
]
problem = cp.Problem(objective, constraints_list)
problem.solve()
if problem.status == 'optimal':
w = weights.value
ret = expected_returns @ w
risk = np.sqrt(w @ cov_matrix @ w)
sharpe = (ret - self.risk_free_rate / 252) / risk
if sharpe > best_sharpe:
best_sharpe = sharpe
best_weights = w
if best_weights is None:
best_weights = np.ones(n_assets) / n_assets
# Calculate final metrics
portfolio_return = expected_returns @ best_weights
portfolio_risk = np.sqrt(best_weights @ cov_matrix @ best_weights)
return {
'weights': best_weights,
'expected_return': portfolio_return * 252,
'expected_risk': portfolio_risk * np.sqrt(252),
'sharpe_ratio': best_sharpe * np.sqrt(252)
}
def _risk_parity_optimization(self, returns: np.ndarray) -> Dict:
"""
Risk parity optimization - equal risk contribution
"""
n_assets = returns.shape[1]
cov_matrix = np.cov(returns.T)
# Initial guess - equal weights
weights = np.ones(n_assets) / n_assets
# Iterative algorithm
for _ in range(100):
# Calculate marginal risk contributions
portfolio_vol = np.sqrt(weights @ cov_matrix @ weights)
marginal_contrib = cov_matrix @ weights / portfolio_vol
contrib = weights * marginal_contrib
# Target equal contribution
target_contrib = portfolio_vol / n_assets
# Update weights
weights = weights * (target_contrib / contrib)
weights = weights / np.sum(weights)
# Calculate metrics
expected_returns = np.mean(returns, axis=0)
portfolio_return = expected_returns @ weights
portfolio_risk = np.sqrt(weights @ cov_matrix @ weights)
sharpe_ratio = (portfolio_return - self.risk_free_rate / 252) / portfolio_risk
return {
'weights': weights,
'expected_return': portfolio_return * 252,
'expected_risk': portfolio_risk * np.sqrt(252),
'sharpe_ratio': sharpe_ratio * np.sqrt(252)
}
def _black_litterman_optimization(
self,
returns: np.ndarray,
constraints: Optional[Dict] = None,
views: Optional[Dict] = None
) -> Dict:
"""
Black-Litterman optimization
"""
# Simplified implementation
# In practice, would incorporate market views
n_assets = returns.shape[1]
# Market equilibrium weights (market cap weighted)
# For demo, use equal weights
market_weights = np.ones(n_assets) / n_assets
# Calculate implied returns
cov_matrix = np.cov(returns.T)
risk_aversion = 2.5
implied_returns = risk_aversion * cov_matrix @ market_weights
# Without views, this reduces to market weights
# With views, would blend implied returns with views
if views:
# Implement view blending
pass
# For now, return mean-variance with implied returns
expected_returns = implied_returns
# Run mean-variance with these returns
weights = cp.Variable(n_assets)
portfolio_return = expected_returns @ weights
portfolio_risk = cp.quad_form(weights, cov_matrix)
objective = cp.Maximize(portfolio_return - risk_aversion * portfolio_risk)
constraints_list = [
cp.sum(weights) == 1,
weights >= 0,
]
problem = cp.Problem(objective, constraints_list)
problem.solve()
weights_array = weights.value if problem.status == 'optimal' else market_weights
# Calculate metrics
portfolio_return = expected_returns @ weights_array
portfolio_risk = np.sqrt(weights_array @ cov_matrix @ weights_array)
sharpe_ratio = (portfolio_return - self.risk_free_rate / 252) / portfolio_risk
return {
'weights': weights_array,
'expected_return': portfolio_return * 252,
'expected_risk': portfolio_risk * np.sqrt(252),
'sharpe_ratio': sharpe_ratio * np.sqrt(252)
}
def calculate_efficient_frontier(
self,
returns: np.ndarray,
num_portfolios: int = 100
) -> List[Dict]:
"""
Calculate the efficient frontier
"""
n_assets = returns.shape[1]
expected_returns = np.mean(returns, axis=0)
cov_matrix = np.cov(returns.T)
# Range of target returns
min_ret = np.min(expected_returns)
max_ret = np.max(expected_returns)
target_returns = np.linspace(min_ret, max_ret, num_portfolios)
frontier = []
for target_ret in target_returns:
weights = cp.Variable(n_assets)
portfolio_risk = cp.quad_form(weights, cov_matrix)
objective = cp.Minimize(portfolio_risk)
constraints_list = [
cp.sum(weights) == 1,
weights >= 0,
expected_returns @ weights >= target_ret
]
problem = cp.Problem(objective, constraints_list)
problem.solve()
if problem.status == 'optimal':
w = weights.value
risk = np.sqrt(w @ cov_matrix @ w)
frontier.append({
'return': target_ret * 252,
'risk': risk * np.sqrt(252),
'weights': w.tolist()
})
return frontier

View file

@ -1,205 +0,0 @@
"""Import the actual service with optional scientific dependencies unavailable."""
import importlib
from io import BytesIO
import json
from pathlib import Path
import sys
import unittest
from types import SimpleNamespace
from unittest.mock import Mock, patch
from fastapi.testclient import TestClient
from starlette.datastructures import FormData, UploadFile
from starlette.exceptions import HTTPException
class UploadForm:
def __init__(self, values):
self.form = FormData(values)
async def __aenter__(self):
return self.form
async def __aexit__(self, *_):
await self.form.close()
class AnalyticsAppComposition(unittest.TestCase):
def setUp(self):
self.path = str(Path(__file__).parents[1])
sys.path.insert(0, self.path)
self.addCleanup(lambda: sys.path.remove(self.path))
for name in list(sys.modules):
if name == "src" or name.startswith("src."):
del sys.modules[name]
missing = {name: None for name in (
"numpy", "pandas", "scipy", "sklearn", "cvxpy", "onnxruntime", "multipart",
)}
self.dependencies = patch.dict(sys.modules, missing)
self.dependencies.start()
self.addCleanup(self.dependencies.stop)
self.module = importlib.import_module("src.api.app")
self.capabilities = importlib.import_module("src.api.capabilities")
self.client = self.enterContext(TestClient(self.module.app))
def test_actual_app_starts_without_optional_dependencies(self):
self.assertEqual(self.client.get("/").status_code, 200)
self.assertEqual(self.client.get("/models/list").json(), [])
self.assertEqual(self.client.get("/analytics/risk/P").status_code, 503)
response = self.client.post("/optimize/rebalance", json={
"current_weights": {"A.US": 0.25},
"target_weights": {"A.US": 0.5},
})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {"trades": {"A.US": 0.25}, "total_turnover": 0.25})
def test_health_observes_uninitialized_capabilities_without_loading_them(self):
response = self.client.get("/health")
self.assertEqual(response.status_code, 200)
health = response.json()
self.assertEqual(health["status"], "degraded")
for name in ("portfolio_optimizer", "model_runtime", "model_upload"):
self.assertEqual(health["components"][name], {"status": "uninitialized"})
for name in ("performance_analyzer", "regime_detector"):
self.assertEqual(health["components"][name], {
"status": "unavailable", "reason": "observed_data_not_integrated",
})
for name in ("src.analytics.performance", "src.analytics.regime", "src.optimization.portfolio_optimizer"):
self.assertNotIn(name, sys.modules)
schema = self.client.get("/openapi.json").json()
upload = schema["paths"]["/models/load"]["post"]["requestBody"]
self.assertTrue(upload["required"])
self.assertEqual(upload["content"]["multipart/form-data"]["schema"]["required"], ["model_file"])
def test_missing_optimizer_is_503_with_diagnostic_and_independent_health(self):
request = {"symbols": ["A.US", "B.US"], "returns": [[0.01, 0.02]]}
loader = Mock(wraps=self.capabilities.portfolio_optimizer.load)
self.capabilities.portfolio_optimizer.load = loader
for path in ("portfolio", "efficient_frontier", "portfolio"):
response = self.client.post("/optimize/" + path, json=request)
self.assertEqual(response.status_code, 503)
self.assertEqual(response.json()["detail"], {
"code": "analytics_capability_unavailable",
"capability": "portfolio_optimizer",
"reason": "missing_dependency",
"message": "Optional analytics capability 'portfolio_optimizer' is unavailable",
"dependency": "numpy",
})
loader.assert_called_once()
health = self.client.get("/health").json()["components"]
self.assertEqual(health["portfolio_optimizer"]["status"], "unavailable")
self.assertEqual(health["model_runtime"]["status"], "uninitialized")
self.assertEqual(self.client.get("/models/list").json(), [])
def test_optimizer_success_is_lazy_reused_and_preserves_input_and_output(self):
arrays = SimpleNamespace(array=Mock(return_value=SimpleNamespace(shape=(2, 2))))
optimizer = SimpleNamespace(
optimize=Mock(return_value={
"weights": SimpleNamespace(tolist=lambda: [0.25, 0.75]),
"expected_return": 0.1,
"expected_risk": 0.2,
"sharpe_ratio": 0.5,
}),
calculate_efficient_frontier=Mock(return_value=[{"risk": 0.2, "return": 0.1}]),
)
loader = Mock(return_value=self.capabilities.OptimizationRuntime(arrays, optimizer))
self.capabilities.portfolio_optimizer.load = loader
self.client.get("/health")
loader.assert_not_called()
request = {"symbols": ["A.US", "B.US"], "returns": [[0.01, 0.02], [0.03, -0.01]]}
response = self.client.post("/optimize/portfolio", json=request)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {
"symbols": request["symbols"], "weights": [0.25, 0.75],
"expected_return": 0.1, "expected_risk": 0.2, "sharpe_ratio": 0.5,
})
arrays.array.assert_called_once_with(request["returns"])
optimizer.optimize.assert_called_once_with(
returns=arrays.array.return_value, method="mean_variance", constraints=None,
)
response = self.client.post("/optimize/efficient_frontier?num_portfolios=7", json=request)
self.assertEqual(response.status_code, 200)
optimizer.calculate_efficient_frontier.assert_called_once_with(
returns=arrays.array.return_value, num_portfolios=7,
)
loader.assert_called_once()
self.assertEqual(self.client.get("/health").json()["components"]["portfolio_optimizer"], {"status": "ready"})
request["symbols"] = ["A.US"]
self.assertEqual(self.client.post("/optimize/portfolio", json=request).status_code, 400)
def test_failed_runtime_initialization_is_not_reported_ready(self):
self.capabilities.portfolio_optimizer.load = Mock(side_effect=RuntimeError("fixture failure"))
response = self.client.post("/optimize/portfolio", json={
"symbols": ["A.US"], "returns": [[0.01]],
})
self.assertEqual(response.status_code, 503)
self.assertEqual(response.json()["detail"]["reason"], "initialization_failed")
self.assertEqual(self.client.get("/health").json()["components"]["portfolio_optimizer"]["status"], "unavailable")
def test_model_absence_and_optional_model_dependencies_have_distinct_statuses(self):
self.assertEqual(self.client.post("/models/predict", json={"model_id": "missing", "features": {}}).status_code, 404)
self.assertEqual(self.client.post("/models/batch_predict?model_id=missing", json=[]).status_code, 404)
self.assertEqual(self.client.delete("/models/missing").status_code, 404)
response = self.client.post("/models/load?model_id=fixture", files={"model_file": ("model.onnx", b"fixture")})
self.assertEqual(response.status_code, 503)
self.assertEqual(response.json()["detail"]["capability"], "model_runtime")
self.assertEqual(self.client.get("/health").json()["components"]["model_runtime"]["status"], "unavailable")
def test_missing_multipart_only_disables_model_upload(self):
self.capabilities.model_runtime.load = Mock(return_value=self.capabilities.ModelRuntime(None, None))
response = self.client.post("/models/load?model_id=fixture", files={"model_file": ("model.onnx", b"fixture")})
self.assertEqual(response.status_code, 503)
self.assertEqual(response.json()["detail"]["capability"], "model_upload")
self.assertEqual(response.json()["detail"]["reason"], "missing_dependency")
self.assertEqual(self.client.get("/models/list").json(), [])
def test_model_upload_and_prediction_keep_the_existing_contract_with_runtime_stubs(self):
session = SimpleNamespace(
get_inputs=lambda: [SimpleNamespace(name="input")],
get_outputs=lambda: [SimpleNamespace(shape=["batch", 1, None])],
run=Mock(return_value=[[1.5]]),
)
arrays = SimpleNamespace(
array=Mock(return_value="feature-array"),
float32="float32",
datetime64=lambda _: SimpleNamespace(tolist=lambda: "2024-01-01T00:00:00"),
)
onnx = SimpleNamespace(InferenceSession=Mock(return_value=session))
loader = Mock(return_value=self.capabilities.ModelRuntime(arrays, onnx))
self.capabilities.model_runtime.load = loader
self.capabilities.model_upload.load = Mock(return_value=True)
file = UploadFile(filename="model.onnx", file=BytesIO(b"fixture"))
with patch("starlette.requests.Request.form", return_value=UploadForm({"model_file": file})):
response = self.client.post("/models/load", params={
"model_id": "fixture",
"metadata": json.dumps({"feature_names": ["trend", "volatility"], "version": "2"}),
})
self.assertEqual(response.status_code, 200)
self.assertTrue(file.file.closed)
onnx.InferenceSession.assert_called_once_with(b"fixture")
listed = self.client.get("/models/list")
self.assertEqual(listed.status_code, 200)
self.assertEqual(listed.json()[0]["output_shape"], [["batch", 1, None]])
self.assertEqual(listed.json()[0]["model_id"], "fixture")
response = self.client.post("/models/predict", json={
"model_id": "fixture", "features": {"trend": 0.4},
})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["prediction"], 1.5)
self.assertEqual(response.json()["metadata"]["model_version"], "2")
arrays.array.assert_called_once_with([[0.4, 0.0]], dtype="float32")
session.run.assert_called_once_with(None, {"input": "feature-array"})
loader.assert_called_once()
response = self.client.post("/models/batch_predict?model_id=fixture", json=[{"trend": 0.1}])
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["count"], 1)
self.assertEqual(self.client.delete("/models/fixture").status_code, 200)
self.assertEqual(self.client.get("/models/list").json(), [])
with patch("starlette.requests.Request.form", return_value=UploadForm({})):
self.assertEqual(self.client.post("/models/load?model_id=fixture").status_code, 422)
with patch("starlette.requests.Request.form", side_effect=HTTPException(400, "Malformed form")):
self.assertEqual(self.client.post("/models/load?model_id=fixture").status_code, 400)
if __name__ == "__main__":
unittest.main()

View file

@ -1,55 +0,0 @@
"""HTTP contract tests for the observed-data routes, without loading research/ML runtimes."""
import importlib.util
from pathlib import Path
import unittest
from fastapi import FastAPI
from fastapi.testclient import TestClient
class ObservedDataEndpoints(unittest.TestCase):
@classmethod
def setUpClass(cls):
source = Path(__file__).parents[1] / "src/api/endpoints/analytics.py"
spec = importlib.util.spec_from_file_location("observed_analytics_endpoints", source)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
app = FastAPI()
app.include_router(module.router, prefix="/analytics")
cls.client = TestClient(app)
@classmethod
def tearDownClass(cls):
cls.client.close()
def test_missing_observed_data_is_unavailable_not_generated_financial_results(self):
requests = [
("GET", "/performance/P?start_date=2024-01-01T00:00:00Z&end_date=2024-02-01T00:00:00Z", None),
("GET", "/risk/P", None),
("GET", "/regime", None),
("POST", "/correlation", ["A.US", "B.US"]),
("GET", "/backtest/run", None),
("POST", "/attribution?portfolio_id=P&benchmark=B&start_date=2024-01-01&end_date=2024-02-01", None),
]
for method, path, body in requests:
with self.subTest(path=path):
response = self.client.request(method, "/analytics" + path, json=body)
self.assertEqual(response.status_code, 503)
self.assertEqual(response.json()["detail"]["code"], "analytics_data_unavailable")
self.assertNotIn("metrics", response.json())
self.assertNotIn("matrix", response.json())
def test_invalid_ranges_and_duplicate_symbols_are_client_errors(self):
response = self.client.get("/analytics/performance/P?start_date=2024-02-01T00:00:00Z&end_date=2024-01-01T00:00:00Z")
self.assertEqual(response.status_code, 400)
response = self.client.post("/analytics/correlation", json=["A.US", "A.US"])
self.assertEqual(response.status_code, 400)
def test_framework_validates_dates_windows_and_request_shapes(self):
self.assertEqual(self.client.get("/analytics/risk/P?window=0").status_code, 422)
self.assertEqual(self.client.get("/analytics/performance/P").status_code, 422)
self.assertEqual(self.client.post("/analytics/correlation", json={"symbols": ["A.US", "B.US"]}).status_code, 422)
if __name__ == "__main__":
unittest.main()

View file

@ -22,7 +22,6 @@
},
"mongodb": {
"uri": "mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin",
"readUri": "mongodb://studio_stock_bot_read@localhost:27017/stock?authSource=stock",
"database": "stock_dev",
"poolSize": 10
},
@ -38,6 +37,7 @@
"db": 0
},
"queue": {
"enableScheduledJobs": false,
"redis": {
"host": "localhost",
"port": 6380,

View file

@ -17,6 +17,10 @@
"types": "./dist/contracts/strategy.d.ts",
"default": "./dist/contracts/strategy.js"
},
"./strategy-names": {
"types": "./dist/contracts/strategy-names.d.ts",
"default": "./dist/contracts/strategy-names.js"
},
"./canonical-replay": {
"types": "./dist/contracts/canonical-replay.d.ts",
"default": "./dist/contracts/canonical-replay.js"

View file

@ -14,7 +14,9 @@ const FORBIDDEN_PROD_SECRETS = new Set([
]);
function isLoopbackHost(host?: string): boolean {
if (!host) return false;
if (!host) {
return false;
}
return LOOPBACK_HOSTS.has(host.toLowerCase());
}
@ -24,7 +26,9 @@ function parseMongoTarget(uri?: string): {
database?: string;
username?: string;
} {
if (!uri) return {};
if (!uri) {
return {};
}
try {
const parsed = new URL(uri);
const database = parsed.pathname.replace(/^\/+/, '').split('/')[0] || undefined;

View file

@ -1,66 +0,0 @@
#!/usr/bin/env bun
/**
* Script to check intraday crawl status
*/
import { createTestContext } from '../src/test-utils';
import { QMHandler } from '../src/handlers/qm/qm.handler';
async function checkIntradayStatus() {
const context = await createTestContext();
const handler = new QMHandler(context.services);
// Wait for operation registry to initialize
await new Promise(resolve => setTimeout(resolve, 1000));
try {
const tracker = handler.operationRegistry.getTracker('qm');
// Get operation stats
const stats = await tracker.getOperationStats('intraday_bars');
console.log('Intraday Bars Operation Stats:');
console.log('------------------------------');
console.log(`Total symbols: ${stats.totalSymbols}`);
console.log(`Processed symbols: ${stats.processedSymbols}`);
console.log(`Successful symbols: ${stats.successfulSymbols}`);
console.log(`Failed symbols: ${stats.failedSymbols}`);
console.log(`Stale symbols: ${stats.staleSymbols}`);
console.log(`Finished crawls: ${stats.finishedCrawls || 0}`);
console.log('');
// Get symbols needing crawl
console.log('Symbols needing crawl (top 10):');
console.log('--------------------------------');
const needsCrawl = await tracker.getSymbolsForIntradayCrawl('intraday_bars', {
limit: 10,
targetOldestDate: new Date('2020-01-01')
});
for (const symbol of needsCrawl) {
const crawlState = symbol.operationStatus?.crawlState;
console.log(`\n${symbol.symbol}:`);
console.log(` Status: ${symbol.operationStatus?.status || 'never run'}`);
console.log(` Last run: ${symbol.operationStatus?.lastRunAt || 'never'}`);
if (crawlState) {
console.log(` Finished: ${crawlState.finished}`);
console.log(` Oldest date: ${crawlState.oldestDateReached || 'none'}`);
console.log(` Newest date: ${crawlState.newestDateReached || 'none'}`);
console.log(` Days processed: ${crawlState.totalDaysProcessed || 0}`);
}
if (symbol.gaps) {
console.log(` Gaps: ${symbol.gaps.forward ? 'new data' : ''} ${symbol.gaps.backward ? 'historical' : ''}`);
}
}
} catch (error) {
console.error('Failed to check status:', error);
} finally {
await context.cleanup();
}
}
// Run the check
checkIntradayStatus().catch(console.error);

View file

@ -1,31 +0,0 @@
#!/usr/bin/env bun
import Redis from 'ioredis';
import { Queue } from 'bullmq';
const redis = new Redis({
host: 'localhost',
port: 6379,
db: 0,
});
const queue = new Queue('{data-ingestion_webshare}', {
connection: redis,
});
async function triggerJob() {
console.log('Triggering webshare fetch-proxies job...');
const job = await queue.add('fetch-proxies', {
handler: 'webshare',
operation: 'fetch-proxies',
payload: {},
});
console.log(`Job ${job.id} added to queue`);
await redis.quit();
process.exit(0);
}
triggerJob().catch(console.error);

View file

@ -1,4 +0,0 @@
export * from './config';
export * from './session-manager';
export * from './types';
export * from './operation-provider';

View file

@ -1,3 +0,0 @@
export * from './config';
export * from './decode';
export * from './types';

View file

@ -1,2 +0,0 @@
export * from './types';
export * from './config';

View file

@ -1,10 +0,0 @@
/**
* WebShare Configuration Constants
*/
export const WEBSHARE_CONFIG = {
DEFAULT_PAGE_SIZE: 100,
DEFAULT_MODE: 'direct',
DEFAULT_PAGE: 1,
TIMEOUT: 10000,
};

View file

@ -3,12 +3,12 @@
* Simplified entry point using ServiceApplication framework
*/
import { Browser } from '@stock-bot/browser';
import { createHttpSecurity, httpSecurityOptions, ServiceApplication } from '@stock-bot/di';
import { getLogger } from '@stock-bot/logger';
import { initializeStockConfig } from '@stock-bot/stock-config';
import { createRoutes } from './routes/create-routes';
// Local imports
import { initializeAllHandlers } from './handlers';
import { createRoutes } from './routes/create-routes';
// Initialize configuration with service-specific overrides
const config = initializeStockConfig('dataIngestion');
@ -29,7 +29,7 @@ const app = new ServiceApplication(
serviceName: 'data-ingestion',
hostname: security.hostname,
enableHandlers: true,
enableScheduledJobs: true,
enableScheduledJobs: config.queue?.enableScheduledJobs ?? true,
corsConfig: {
origin: '*',
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
@ -70,6 +70,21 @@ async function createContainer(baseConfig: import('@stock-bot/config').UnifiedAp
enableBrowser: true, // Data ingestion needs browser for web scraping
enableProxy: true, // Data ingestion needs proxy for rate limiting
})
.withRegistrations((diContainer, validatedConfig, { asFunction }) => {
if (validatedConfig.browser) {
const browserOptions = {
headless: validatedConfig.browser.headless,
timeout: validatedConfig.browser.timeout,
};
diContainer.register({
browser: asFunction(({ logger: containerLogger }) => {
return new Browser(containerLogger, browserOptions);
})
.singleton()
.disposer(browser => browser.close?.()),
});
}
})
.build(); // This automatically initializes services
return container;

View file

@ -1,6 +0,0 @@
/**
* Routes index - exports all route modules
*/
export { exchangeRoutes } from './exchange.routes';
export { healthRoutes } from './health.routes';
export { createQueueRoutes } from './queue.routes';

View file

@ -1,147 +0,0 @@
/**
* Market data routes
*/
import { Hono } from 'hono';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { processItems } from '@stock-bot/queue';
const logger = getLogger('market-data-routes');
export function createMarketDataRoutes(container: IServiceContainer) {
const marketDataRoutes = new Hono();
// Market data endpoints
marketDataRoutes.get('/api/live/:symbol', async c => {
const symbol = c.req.param('symbol');
logger.info('Live data request', { symbol });
try {
// Queue job for live data using Yahoo provider
const queueManager = container.queueManager;
if (!queueManager) {
return c.json({ status: 'error', message: 'Queue manager not available' }, 503);
}
const queue = queueManager.getQueue('yahoo-finance');
const job = await queue.add('live-data', {
handler: 'yahoo-finance',
operation: 'live-data',
payload: { symbol },
});
return c.json({
status: 'success',
message: 'Live data job queued',
jobId: job.id,
symbol,
});
} catch (error) {
logger.error('Failed to queue live data job', { symbol, error });
return c.json({ status: 'error', message: 'Failed to queue live data job' }, 500);
}
});
marketDataRoutes.get('/api/historical/:symbol', async c => {
const symbol = c.req.param('symbol');
const from = c.req.query('from');
const to = c.req.query('to');
logger.info('Historical data request', { symbol, from, to });
try {
const fromDate = from ? new Date(from) : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); // 30 days ago
const toDate = to ? new Date(to) : new Date(); // Now
// Queue job for historical data using Yahoo provider
const queueManager = container.queueManager;
if (!queueManager) {
return c.json({ status: 'error', message: 'Queue manager not available' }, 503);
}
const queue = queueManager.getQueue('yahoo-finance');
const job = await queue.add('historical-data', {
handler: 'yahoo-finance',
operation: 'historical-data',
payload: {
symbol,
from: fromDate.toISOString(),
to: toDate.toISOString(),
},
});
return c.json({
status: 'success',
message: 'Historical data job queued',
jobId: job.id,
symbol,
from: fromDate,
to: toDate,
});
} catch (error) {
logger.error('Failed to queue historical data job', { symbol, from, to, error });
return c.json({ status: 'error', message: 'Failed to queue historical data job' }, 500);
}
});
// Batch processing endpoint using new queue system
marketDataRoutes.post('/api/process-symbols', async c => {
try {
const {
symbols,
provider = 'ib',
operation = 'fetch-session',
useBatching = true,
totalDelayHours = 0.0083, // ~30 seconds (30/3600 hours)
batchSize = 10,
} = await c.req.json();
if (!symbols || !Array.isArray(symbols) || symbols.length === 0) {
return c.json({ status: 'error', message: 'Invalid symbols array' }, 400);
}
logger.info('Batch processing symbols', {
count: symbols.length,
provider,
operation,
useBatching,
});
const queueManager = container.queueManager;
if (!queueManager) {
return c.json({ status: 'error', message: 'Queue manager not available' }, 503);
}
const result = await processItems(
symbols,
provider,
{
handler: provider,
operation,
totalDelayHours,
useBatching,
batchSize,
priority: 2,
retries: 2,
removeOnComplete: 100,
removeOnFail: 100,
},
queueManager
);
return c.json({
status: 'success',
message: 'Batch processing initiated',
result,
symbols: symbols.length,
});
} catch (error) {
logger.error('Failed to process symbols batch', { error });
return c.json({ status: 'error', message: 'Failed to process symbols batch' }, 500);
}
});
return marketDataRoutes;
}
// Legacy export for backward compatibility
export const marketDataRoutes = createMarketDataRoutes({} as IServiceContainer);

View file

@ -1,40 +0,0 @@
/**
* Type definitions for exchange data structures
*/
export interface IBExchange {
id: string;
country_code: string;
name: string;
code?: string;
exchange_code?: string;
currency?: string;
timezone?: string;
_id?: unknown; // MongoDB ObjectId
// Add other properties as needed
}
export interface MasterExchangeData {
id: string;
code: string;
name: string;
country: string;
currency: string;
// Add other properties as needed
}
export interface QMSymbol {
symbol: string;
exchange?: string;
name?: string;
type?: string;
// Add other properties as needed
}
export interface IBSymbol {
symbol: string;
exchange: string;
name?: string;
currency?: string;
// Add other properties as needed
}

View file

@ -1,93 +0,0 @@
/**
* Type definitions for all job payloads across data service providers
*/
// Common result types
export interface JobResult {
success: boolean;
message: string;
}
export interface CountableJobResult extends JobResult {
count: number;
}
// QM Provider Types
export interface SymbolSpiderJob {
prefix: string | null; // null = root job (A-Z)
depth: number; // 1=A, 2=AA, 3=AAA, etc.
source: string; // 'qm'
maxDepth?: number; // optional max depth limit
}
export interface CreateSessionsResult extends JobResult {
// No additional fields needed
}
export interface SearchSymbolsResult extends CountableJobResult {
symbols?: unknown[]; // First 10 symbols as sample
}
export interface SpiderSymbolSearchResult extends JobResult {
symbolsFound: number;
newSymbolsAdded: number;
duplicatesSkipped: number;
errors: number;
depth: number;
prefix: string | null;
}
// IB Provider Types
export interface FetchSessionResult extends JobResult {
sessionData?: Record<string, string>;
}
export interface FetchExchangesResult extends CountableJobResult {
exchanges?: unknown[];
}
export interface FetchSymbolsResult extends CountableJobResult {
symbols?: unknown[];
}
export interface IBExchangesAndSymbolsResult extends JobResult {
exchanges: FetchExchangesResult;
symbols: FetchSymbolsResult;
}
// Proxy Provider Types
export interface ProxyInfo {
host: string;
port: number;
protocol: 'http' | 'https' | 'socks4' | 'socks5';
username?: string;
password?: string;
country?: string;
city?: string;
isValid?: boolean;
lastChecked?: Date;
}
export interface FetchProxiesFromSourcesResult extends CountableJobResult {
proxies?: ProxyInfo[];
sources: string[];
}
export interface CheckProxyResult extends JobResult {
proxy: ProxyInfo;
responseTime?: number;
error?: string;
}
// WebShare Provider Types
export interface FetchWebShareProxiesResult extends CountableJobResult {
proxies?: ProxyInfo[];
activeProxies: number;
totalQuota: number;
remainingQuota: number;
}
// No payload job types (for operations that don't need input)
export interface NoPayload {
// Empty interface for operations that don't need payload
}

View file

@ -1,99 +0,0 @@
#!/usr/bin/env bun
import { getLogger } from '@stock-bot/logger';
const logger = getLogger('test-advanced-rate-limit');
async function testAdvancedRateLimits() {
logger.info('Testing advanced rate limit features...');
const baseUrl = 'http://localhost:3001/api';
logger.info('\n📋 Rate Limit Configuration:');
logger.info('Handler limits: 100pts/sec, 10k pts/hour, 100k pts/day');
logger.info('fetch-daily-prices: 1 point per call');
logger.info('fetch-fundamentals: 10 points per call');
logger.info('fetch-news: 50 points per call (custom limits: 10pts/min, 100pts/hour)');
// First test: test-burst operation
logger.info('\n🚀 Testing burst operation with mixed costs...');
const burstResponse = await fetch(`${baseUrl}/handlers/eod/operations/test-burst`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
operationsToTest: ['fetch-daily-prices', 'fetch-fundamentals', 'fetch-news'],
burstSize: 30,
}),
});
const burstResult = await burstResponse.json();
logger.info('Burst test result:', burstResult);
// Wait for jobs to process
logger.info('\n⏳ Waiting 10 seconds for jobs to process...');
await new Promise(resolve => setTimeout(resolve, 10000));
// Test individual operations with different costs
logger.info('\n📊 Testing individual operations:');
// Test cheap operation (1 point)
logger.info('\n1️⃣ Testing fetch-daily-prices (1 point each)...');
for (let i = 0; i < 5; i++) {
const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-daily-prices`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ test: true, index: i }),
});
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
}
// Test medium cost operation (10 points)
logger.info('\n🔟 Testing fetch-fundamentals (10 points each)...');
for (let i = 0; i < 3; i++) {
const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-fundamentals`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ test: true, index: i }),
});
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
}
// Test expensive operation (50 points)
logger.info('\n💰 Testing fetch-news (50 points each, custom limits)...');
for (let i = 0; i < 2; i++) {
const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-news`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ test: true, index: i }),
});
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
}
logger.info('\n✅ Test completed!');
logger.info('Check the data-ingestion service logs to see rate limiting in action.');
}
// Health check before running tests
async function checkService() {
try {
const response = await fetch('http://localhost:3001/health');
if (!response.ok) {
throw new Error('Service not healthy');
}
return true;
} catch (_error) {
logger.error('Data ingestion service not running. Start it with: bun run dev');
return false;
}
}
async function main() {
if (await checkService()) {
await testAdvancedRateLimits();
}
}
main().catch(error => {
logger.error('Test failed:', error);
process.exit(1);
});

View file

@ -1,163 +0,0 @@
/**
* Test script to verify intraday crawl data flow
*/
import { OperationRegistry, OperationTracker } from '../src/shared/operation-manager';
import type { DataIngestionServices } from '../src/types';
async function testIntradayDataFlow() {
console.log('=== Testing Intraday Data Flow ===\n');
// Mock services
const mockServices: DataIngestionServices = {
mongodb: {
collection: (name: string) => ({
find: () => ({
toArray: async () => {
console.log(`Mock: Query collection ${name}`);
if (name === 'qmSymbols') {
return [
{
symbol: 'X',
symbolId: 123456,
qmSearchCode: 'X:NYSE',
exchange: 'NYSE',
operations: {
intraday_bars: {
lastRunAt: new Date('2024-01-01'),
lastSuccessAt: new Date('2024-01-01'),
status: 'success',
crawlState: {
finished: false,
oldestDateReached: new Date('2023-01-01'),
newestDateReached: new Date('2024-01-01'),
lastProcessedDate: new Date('2023-06-15'),
totalDaysProcessed: 180,
},
},
},
},
];
}
return [];
},
}),
createIndex: async () => ({ ok: 1 }),
}),
find: async (collection: string, filter: any, options?: any) => {
console.log(`Mock: Direct find on ${collection}`, { filter, options });
return [
{
symbol: 'X',
qmSearchCode: 'X:NYSE',
exchange: 'NYSE',
operations: {
intraday_bars: {
crawlState: {
finished: false,
oldestDateReached: new Date('2023-01-01'),
newestDateReached: new Date('2024-01-01'),
},
},
},
},
];
},
} as any,
logger: {
info: (msg: string, data?: any) =>
console.log(`[INFO] ${msg}`, JSON.stringify(data, null, 2)),
error: (msg: string, data?: any) => console.error(`[ERROR] ${msg}`, data || ''),
warn: (msg: string, data?: any) => console.warn(`[WARN] ${msg}`, data || ''),
debug: (msg: string, data?: any) => console.debug(`[DEBUG] ${msg}`, data || ''),
},
} as DataIngestionServices;
// Create registry and provider
const _registry = new OperationRegistry(mockServices as any);
// Mock provider
const mockProvider = {
getProviderConfig: () => ({
name: 'qm',
collectionName: 'qmSymbols',
symbolField: 'qmSearchCode',
}),
getOperations: () => [
{
name: 'intraday_bars',
type: 'intraday_crawl' as const,
defaultStaleHours: 1,
},
],
validateOperation: () => true,
getOperation: () => ({ name: 'intraday_bars', type: 'intraday_crawl' }),
getDefaultStaleHours: () => 1,
initialize: async () => {},
beforeOperationUpdate: async () => {},
afterOperationUpdate: async () => {},
};
const tracker = new OperationTracker(mockServices as any, mockProvider as any);
await tracker.initialize();
// Test 1: Get symbols for intraday crawl
console.log('\nTest 1: Get symbols for intraday crawl with symbol filter');
const symbols = await tracker.getSymbolsForIntradayCrawl('intraday_bars', {
limit: 10,
targetOldestDate: new Date('2020-01-01'),
includeNewDataGaps: true,
symbolFilter: { symbol: 'X' },
});
console.log(`\nFound ${symbols.length} symbols:`);
symbols.forEach(sym => {
console.log({
symbol: sym.symbol,
qmSearchCode: sym.qmSearchCode,
exchange: sym.exchange,
gaps: sym.gaps,
crawlState: sym.operationStatus?.crawlState,
});
});
// Test 2: Verify data preservation
console.log('\n\nTest 2: Verify data is preserved through mapping');
const testSymbol = symbols[0];
if (testSymbol) {
console.log('Original data:');
console.log({
symbol: testSymbol.symbol,
hasGaps: !!testSymbol.gaps,
gaps: testSymbol.gaps,
hasOperationStatus: !!testSymbol.operationStatus,
crawlState: testSymbol.operationStatus?.crawlState,
});
// Simulate mapping
const mapped = {
...testSymbol,
symbol: 'X',
exchange: 'NYSE',
qmSearchCode: 'X:NYSE',
gaps: testSymbol.gaps,
operationStatus: testSymbol.operationStatus,
};
console.log('\nAfter mapping:');
console.log({
symbol: mapped.symbol,
exchange: mapped.exchange,
qmSearchCode: mapped.qmSearchCode,
hasGaps: !!mapped.gaps,
gaps: mapped.gaps,
hasOperationStatus: !!mapped.operationStatus,
crawlState: mapped.operationStatus?.crawlState,
});
}
console.log('\n=== Tests Complete ===');
}
// Run tests
testIntradayDataFlow().catch(console.error);

View file

@ -1,139 +0,0 @@
/**
* Examples of modifying existing functions to only work with symbol 'X'
*/
import { OperationTracker } from '../src/shared/operation-manager';
// Example 1: Modified getStaleSymbols to only return symbol X
async function getStaleSymbolsOnlyX(
operationTracker: OperationTracker,
providerName: string,
operationName: string,
options: any = {}
) {
// Method 1: Add symbolFilter to options
const modifiedOptions = {
...options,
symbolFilter: { symbol: 'X' },
};
return operationTracker.getStaleSymbols(providerName, operationName, modifiedOptions);
}
// Example 2: Modified sophisticated backtest function for symbol X only
async function _runSophisticatedBacktestOnlyX(orchestrator: any) {
const symbols = ['X']; // Only test symbol X
const backtestConfig = {
symbols,
startDate: new Date('2023-01-01'),
endDate: new Date('2024-01-01'),
strategies: ['momentum', 'mean_reversion'],
// ... rest of config
};
return orchestrator.runBacktest(backtestConfig);
}
// Example 3: Modified schedule function to only process symbol X
async function _scheduleOperationsOnlyX(handler: any) {
// Get all symbols that need updates, then filter for X
const staleSymbols = await handler.operationRegistry.getStaleSymbols('qm', 'price_update', {
minHoursSinceRun: 24,
limit: 1000,
});
// Filter to only include symbol X
const symbolXOnly = staleSymbols.filter((s: string) => s.includes('X:'));
if (symbolXOnly.length > 0) {
const symbolData = await handler.mongodb.find('qmSymbols', {
qmSearchCode: symbolXOnly[0],
});
if (symbolData.length > 0) {
await handler.scheduleOperation('update-prices', {
symbol: symbolData[0].symbol,
symbolId: symbolData[0].symbolId,
qmSearchCode: symbolData[0].qmSearchCode,
});
}
}
}
// Example 4: Modified intraday crawl for symbol X only
async function _crawlIntradayOnlyX(handler: any) {
// Direct approach - just process symbol X
const symbolX = await handler.mongodb.findOne('qmSymbols', { symbol: 'X' });
if (symbolX) {
return handler.crawlIntradayData({
symbol: symbolX.symbol,
symbolId: symbolX.symbolId,
qmSearchCode: symbolX.qmSearchCode,
mode: 'full',
targetOldestDate: new Date('2020-01-01'),
});
}
}
// Example 5: Test wrapper that ensures only symbol X is processed
function createSymbolXTestWrapper(originalFunction: Function) {
return async function (...args: any[]) {
// Check if first argument has symbol property
if (args[0] && typeof args[0] === 'object') {
// If it's a symbol-specific call, only proceed if symbol is X
if (args[0].symbol && args[0].symbol !== 'X') {
console.log(`Skipping symbol ${args[0].symbol} - only testing X`);
return { success: false, message: 'Test mode - only symbol X allowed' };
}
// If it's a batch operation, filter to only X
if (args[0].symbols && Array.isArray(args[0].symbols)) {
args[0].symbols = args[0].symbols.filter((s: string) => s === 'X');
}
}
// Call original function with potentially modified args
return originalFunction.apply(this, args);
};
}
// Example usage
async function demonstrateUsage() {
console.log('=== Demonstration of Symbol X Only Modifications ===\n');
// Mock tracker for demonstration
const mockTracker = {
getStaleSymbols: async (provider: string, operation: string, options: any) => {
console.log(`Getting stale symbols with options:`, options);
if (options.symbolFilter?.symbol === 'X') {
return ['X:NYSE'];
}
return ['AAPL:NASDAQ', 'GOOGL:NASDAQ', 'X:NYSE', 'MSFT:NASDAQ'];
},
} as any;
// Test the modified function
console.log('1. Testing getStaleSymbols with X filter:');
const xOnlySymbols = await getStaleSymbolsOnlyX(mockTracker, 'qm', 'price_update', {
minHoursSinceRun: 24,
});
console.log('Results:', xOnlySymbols);
console.log('\n2. Example of wrapper usage:');
const originalUpdate = async (input: any) => {
console.log(`Processing symbol: ${input.symbol}`);
return { success: true, symbol: input.symbol };
};
const wrappedUpdate = createSymbolXTestWrapper(originalUpdate);
await wrappedUpdate({ symbol: 'X', symbolId: 123 });
await wrappedUpdate({ symbol: 'AAPL', symbolId: 456 }); // Will be skipped
console.log('\n=== Demonstration Complete ===');
}
// Run demonstration
demonstrateUsage().catch(console.error);

View file

@ -1,163 +0,0 @@
/**
* Test script for QM operations
*/
import { QMHandler } from '../src/handlers/qm/qm.handler';
import type { DataIngestionServices } from '../src/types';
// Mock services for testing
const mockServices: Partial<DataIngestionServices> = {
mongodb: {
batchUpsert: async (collection: string, data: any[], uniqueKeys: string[]) => {
console.log(`Mock: Batch upsert to ${collection}`, {
recordCount: data.length,
uniqueKeys
});
return { insertedCount: data.length, modifiedCount: 0 };
},
find: async (collection: string, query: any, options?: any) => {
console.log(`Mock: Find from ${collection}`, { query, options });
// Return test symbol for testing
if (collection === 'qmSymbols' && query.symbol === 'X') {
return [{
symbol: 'X',
symbolId: 123456,
qmSearchCode: 'X:NYSE',
exchange: 'NYSE',
name: 'United States Steel Corporation'
}];
}
return [];
},
updateOne: async (collection: string, filter: any, update: any, options?: any) => {
console.log(`Mock: Update ${collection}`, { filter, update, options });
return { modifiedCount: 1 };
}
},
cache: {
get: async (key: string) => {
console.log(`Mock: Cache get ${key}`);
return null;
},
set: async (key: string, value: any, ttl?: number) => {
console.log(`Mock: Cache set ${key}`, { ttl });
return true;
}
},
logger: {
info: (message: string, data?: any) => {
console.log(`[INFO] ${message}`, data || '');
},
error: (message: string, data?: any) => {
console.error(`[ERROR] ${message}`, data || '');
},
warn: (message: string, data?: any) => {
console.warn(`[WARN] ${message}`, data || '');
},
debug: (message: string, data?: any) => {
console.debug(`[DEBUG] ${message}`, data || '');
}
},
// Mock operation registry
operationRegistry: {
updateOperation: async (provider: string, symbol: string, operation: string, data: any) => {
console.log(`Mock: Update operation ${provider}/${operation} for ${symbol}`, data);
return true;
},
getStaleSymbols: async (provider: string, operation: string, options: any) => {
console.log(`Mock: Get stale symbols for ${provider}/${operation}`, options);
// Return test symbol
if (options.symbolFilter?.symbol === 'X') {
return ['X:NYSE'];
}
return [];
}
}
} as DataIngestionServices;
async function testQMOperations() {
console.log('=== Testing QM Operations ===\n');
// Create handler instance
const handler = new QMHandler(mockServices);
// Wait a bit for initialization
await new Promise(resolve => setTimeout(resolve, 1000));
// Test 1: Update Insiders for symbol X
console.log('Test 1: Update Insiders for symbol X');
console.log('-------------------------------------');
try {
const insidersResult = await handler.updateInsiders({
symbol: 'X',
symbolId: 123456,
qmSearchCode: 'X:NYSE',
lookbackDays: 30
});
console.log('Result:', JSON.stringify(insidersResult, null, 2));
} catch (error) {
console.error('Failed:', error);
}
console.log('\n');
// Test 2: Update Symbol News for symbol X
console.log('Test 2: Update Symbol News for symbol X');
console.log('----------------------------------------');
try {
const newsResult = await handler.updateSymbolNews({
symbol: 'X',
symbolId: 123456,
qmSearchCode: 'X:NYSE',
lookbackDays: 7
});
console.log('Result:', JSON.stringify(newsResult, null, 2));
} catch (error) {
console.error('Failed:', error);
}
console.log('\n');
// Test 3: Update General News
console.log('Test 3: Update General News');
console.log('---------------------------');
try {
const generalNewsResult = await handler.updateGeneralNews({
categories: ['market', 'economy'],
lookbackMinutes: 60
});
console.log('Result:', JSON.stringify(generalNewsResult, null, 2));
} catch (error) {
console.error('Failed:', error);
}
console.log('\n');
// Test 4: Check available operations
console.log('Test 4: List Available Operations');
console.log('---------------------------------');
const operations = [
'create-session',
'search-symbols',
'update-symbol-info',
'update-financials',
'update-events',
'update-filings',
'update-prices',
'update-intraday-bars',
'crawl-intraday-data',
'update-insiders',
'update-symbol-news',
'update-general-news'
];
for (const op of operations) {
const hasOperation = typeof (handler as any)[op.replace(/-/g, '')] === 'function';
console.log(`${op}: ${hasOperation ? '✓' : '✗'}`);
}
console.log('\n=== Tests Complete ===');
}
// Run tests
testQMOperations().catch(console.error);

View file

@ -1,122 +0,0 @@
/**
* Test script specifically for symbol X operations
*/
import '../src/handlers/qm/qm.handler';
import { OperationTracker } from '../src/shared/operation-manager';
import type { DataIngestionServices } from '../src/types';
// Simple test to check operations for symbol X
async function testSymbolXOperations() {
console.log('=== Testing Operations for Symbol X ===\n');
// Mock minimal services needed
const mockServices: Partial<DataIngestionServices> = {
mongodb: {
collection: (name: string) => ({
find: () => ({
toArray: async () => {
console.log(`Querying collection: ${name}`);
if (name === 'qmSymbols') {
return [
{
symbol: 'X',
symbolId: 123456,
qmSearchCode: 'X:NYSE',
exchange: 'NYSE',
name: 'United States Steel Corporation',
},
];
}
return [];
},
}),
findOne: async (query: any) => {
console.log(`Finding one in ${name}:`, query);
return null;
},
updateOne: async (filter: any, update: any, _options: any) => {
console.log(`Updating ${name}:`, { filter, update });
return { modifiedCount: 1 };
},
}),
find: async (collection: string, query: any) => {
console.log(`Direct find on ${collection}:`, query);
if (collection === 'qmSymbols' && query.symbol === 'X') {
return [
{
symbol: 'X',
symbolId: 123456,
qmSearchCode: 'X:NYSE',
},
];
}
return [];
},
} as any,
logger: {
info: (msg: string, data?: any) => console.log(`[INFO] ${msg}`, data || ''),
error: (msg: string, data?: any) => console.error(`[ERROR] ${msg}`, data || ''),
warn: (msg: string, data?: any) => console.warn(`[WARN] ${msg}`, data || ''),
debug: (msg: string, data?: any) => console.debug(`[DEBUG] ${msg}`, data || ''),
},
} as DataIngestionServices;
// Test 1: Check stale operations for symbol X
console.log('Test 1: Get stale operations for symbol X');
console.log('------------------------------------------');
const tracker = new OperationTracker(mockServices as any);
try {
// Check each operation type
const operations = [
'symbol_info',
'price_update',
'intraday_bars',
'financials_update_quarterly',
'financials_update_annual',
'events_update',
'filings_update',
'insiders_update',
'news_update',
];
for (const operation of operations) {
console.log(`\nChecking ${operation}:`);
const staleSymbols = await tracker.getStaleSymbols('qm', operation, {
minHoursSinceRun: 0, // Get all symbols regardless of last run
limit: 10,
symbolFilter: { symbol: 'X' }, // Only get symbol X
});
console.log(`Found ${staleSymbols.length} stale symbols:`, staleSymbols);
}
} catch (error) {
console.error('Error checking stale symbols:', error);
}
// Test 2: Check intraday crawl status for symbol X
console.log('\n\nTest 2: Check intraday crawl status for symbol X');
console.log('------------------------------------------------');
try {
const symbolsForCrawl = await tracker.getSymbolsForIntradayCrawl('intraday_bars', {
limit: 10,
symbolFilter: { symbol: 'X' },
});
console.log(`Found ${symbolsForCrawl.length} symbols for intraday crawl`);
if (symbolsForCrawl.length > 0) {
console.log('Symbol details:', JSON.stringify(symbolsForCrawl[0], null, 2));
}
} catch (error) {
console.error('Error checking intraday crawl:', error);
}
console.log('\n=== Tests Complete ===');
}
// Run the test
testSymbolXOperations().catch(console.error);

View file

@ -6,7 +6,7 @@
"type": "module",
"scripts": {
"dev": "bun --watch src/index.ts",
"build": "bun build src/index.ts --outdir dist --target node --external chromium-bidi --external electron --external playwright --external playwright-core",
"build": "bun build src/index.ts --outdir dist --target node",
"start": "bun dist/index.js",
"test": "bun test",
"clean": "rm -rf dist"

View file

@ -1,528 +0,0 @@
import { homedir } from 'node:os';
import { join, resolve } from 'node:path';
import { parseArgs, parseEnv } from 'node:util';
import { MongoClient, type Db, type Document } from 'mongodb';
import { Client } from 'pg';
const sources = ['qm', 'eod', 'ib', 'ceo'] as const;
type Source = typeof sources[number];
type Entity = 'stock' | 'exchange' | 'country' | 'other' | 'unclassified';
const entities: Record<string, Entity> = {
qmSymbols: 'stock', eodSymbols: 'stock', ibSymbols: 'stock', ceoSymbols: 'stock',
qmExchanges: 'exchange', eodExchanges: 'exchange', ibExchanges: 'exchange', ceoExchanges: 'exchange',
teCountries: 'country', teIndicators: 'country', teData: 'country', teMarketData: 'country',
qmDividends: 'other', qmEarnings: 'other', qmFilings: 'other', qmFinancials: 'other',
'qmFinancials-old': 'other', qmIntraday: 'other', qmPrices: 'other', qmSplits: 'other',
eodFinancialsOLD: 'other', eodFundamentalsOLD: 'other', eodIntraday1H: 'other',
eodIntraday1M: 'other', eodIntraday5M: 'other', eodPrices: 'other', eodSymbolChange: 'other',
ceoPosts: 'other', ceoShorts: 'other', teUrls: 'other', ttFutures: 'other',
};
const fields = ['ticker', 'exchange', 'isin', 'figi', 'cusip', 'name', 'country', 'currency', 'mic', 'conid', 'priority'] as const;
type Field = typeof fields[number];
type Aliases = Partial<Record<Field, string[]>>;
const qmId = (field: string) => [
field, 'profile.' + field, 'profile.info.' + field, 'profile.details.' + field,
'symbolInfo.' + field, 'symbolInfo.' + field.toUpperCase(),
];
const aliases: Record<string, Aliases> = {
qmSymbols: { ticker: ['symbol'], exchange: ['exchange'], name: ['name'], country: ['countryCode'],
isin: qmId('isin'), cusip: qmId('cusip'), figi: qmId('figi'), currency: qmId('currency') },
eodSymbols: { ticker: ['Code'], exchange: ['eodExchange', 'Exchange'], isin: ['Isin', 'ISIN'],
name: ['Name'], country: ['Country'], currency: ['Currency'], cusip: ['Cusip'], figi: ['FIGI', 'Figi'] },
ibSymbols: { ticker: ['localSymbol', 'symbol'], exchange: ['exchangeId', 'exchange_id'], isin: ['isin'],
cusip: ['cusip'], figi: ['figi'], conid: ['conid'], name: ['description'], country: ['country'], currency: ['currency'] },
ceoSymbols: { ticker: ['symbol'], exchange: ['exchange'], name: ['name'], country: ['countryCode'],
currency: ['currency'], isin: ['isin'], cusip: ['cusip'], figi: ['figi'] },
qmExchanges: { exchange: ['exchange'], country: ['countryCode'], name: ['exchangeName', 'name'],
currency: ['currency'], mic: ['operatingMIC', 'mic'], priority: ['priority'] },
eodExchanges: { exchange: ['Code'], mic: ['OperatingMIC'], country: ['CountryISO2', 'Country'],
currency: ['Currency'], name: ['Name'] },
ibExchanges: { exchange: ['exchange_id', 'id'], country: ['country_code', 'country'], name: ['name'],
currency: ['currency'], mic: ['operatingMIC', 'mic'] },
ceoExchanges: { exchange: ['exchange'], country: ['countryCode'], name: ['exchangeName', 'name'],
currency: ['currency'], mic: ['operatingMIC', 'mic'] },
};
const requiredFields = fields.slice(0, 8);
const cmp = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
const upper = (value: string) => value.toUpperCase();
const sourceOf = (name: string) => /^(qm|eod|ib|ceo|te|tt)(?=[A-Z])/.exec(name)?.[1] ?? 'other';
const tupleKey = (...parts: string[]) => parts.join('\u0000');
const text = (value: unknown) => typeof value === 'string' ? value.trim() :
typeof value === 'number' && Number.isFinite(value) ? String(value) : '';
function assertReadStages(value: unknown): void {
if (!value || typeof value !== 'object') return;
for (const [key, child] of Object.entries(value)) {
if (key === '$' + 'out' || key === '$' + 'merge') throw Error('Aggregation stage is forbidden');
assertReadStages(child);
}
}
function mongoReads(db: Db) {
return {
listCollections: () => db.listCollections({}, { nameOnly: true }).toArray(),
estimatedDocumentCount: (name: string) => db.collection(name).estimatedDocumentCount(),
countDocuments: (name: string) => db.collection(name).countDocuments({}),
find: (name: string, filter: Document = {}) => ({
limit: (n: number) => {
if (!Number.isSafeInteger(n) || n < 1 || n > 2) throw Error('Expected a bounded example query');
return db.collection(name).find(filter).sort({ _id: 1 }).limit(n).toArray();
},
}),
aggregate: (name: string, stages: Document[]) => {
assertReadStages(stages);
return db.collection(name).aggregate(stages, { batchSize: 2_000 });
},
listIndexes: (name: string) => db.collection(name).listIndexes().toArray(),
runCommand: (command: { usersInfo: 1 }) => {
if (Object.keys(command).length !== 1 || command.usersInfo !== 1) throw Error('Expected usersInfo');
return db.command(command, { readPreference: 'primary' });
},
};
}
type MongoReads = ReturnType<typeof mongoReads>;
type User = { user: string; db: string; roles: { role: string; db: string }[] };
const readOnly = (user: User) => user.roles.length > 0 &&
user.roles.every(({ role }) => role === 'read' || role === 'readAnyDatabase');
const canRead = (user: User, db: string) => user.roles.some(role => role.role === 'readAnyDatabase' || role.db === db);
async function mongoUsers(client: MongoClient, name: string) {
const results = await Promise.all(['admin', name].map(db => mongoReads(client.db(db)).runCommand({ usersInfo: 1 })));
const users: User[] = results.flatMap(result => result.users.map(({ user, db, roles }: User) => ({ user, db, roles })));
return [...new Map(users.map(user => [tupleKey(user.db, user.user), user])).values()]
.sort((a, b) => cmp(tupleKey(a.db, a.user), tupleKey(b.db, b.user)));
}
function safeMongoUri(raw: string) {
const uri = new URL(raw);
if (!['localhost', '127.0.0.1', '[::1]'].includes(uri.hostname)) throw Error('Expected a local MongoDB host');
return uri;
}
async function mongoReadUri(rootUri: string, name: string, users: User[], env: Partial<Record<string, string>>) {
const available = users.filter(user => readOnly(user) && canRead(user, name));
if (!available.length) return rootUri;
const studioEnv = Bun.file(join(homedir(), '.studio', 'test-env', 'stock-bot.env'));
const candidates = [env.PHASE1_MONGO_READ_URI, rootUri, await studioEnv.exists()
? parseEnv(await studioEnv.text()).MONGODB_URI : undefined];
for (const raw of candidates) {
if (!raw) continue;
const uri = safeMongoUri(raw), username = decodeURIComponent(uri.username);
const authDb = uri.searchParams.get('authSource') ?? (uri.pathname.slice(1) || 'admin');
if (available.some(user => user.user === username && user.db === authDb)) return raw;
}
throw Error('A read-only MongoDB user exists but its URI is unavailable; supply PHASE1_MONGO_READ_URI');
}
function trimmed(doc: Document) {
return Object.fromEntries(Object.entries(doc).map(([key, value]) => {
if (Array.isArray(value)) return [key, { length: value.length, keys: [...new Set(value.slice(0, 5).flatMap(v =>
v && typeof v === 'object' ? Object.keys(v) : []))].sort(cmp) }];
if (value && Object.getPrototypeOf(value) === Object.prototype) return [key, { keys: Object.keys(value).sort(cmp) }];
return [key, typeof value === 'string' && value.length > 180 ? value.slice(0, 180) + '…' : value];
}));
}
function expression(path: string) {
return { $trim: { input: { $convert: { input: '$' + path, to: 'string', onError: '', onNull: '' } } } };
}
const limitStages = (limit: number | null) => limit === null ? [] : [{ $limit: limit }];
async function fieldCoverage(mongo: MongoReads, name: string, mapping: Aliases, limit: number | null) {
const names = fields.filter(field => requiredFields.includes(field) || mapping[field]);
const group = Object.fromEntries(names.map(field => [field, { $sum: { $cond: [
mapping[field]?.length ? { $or: mapping[field]!.map(path => ({ $ne: [expression(path), ''] })) } : false, 1, 0,
] } }]));
const [counts] = await mongo.aggregate(name, [...limitStages(limit),
{ $group: { _id: null, total: { $sum: 1 }, ...group } }]).toArray();
const total = Number(counts?.total ?? 0);
return { total, aliases: mapping, fields: Object.fromEntries(names.map(field => {
const filled = Number(counts?.[field] ?? 0);
return [field, { filled, fraction: total ? filled / total : 0 }];
})) };
}
async function inventory(mongo: MongoReads, limit: number | null, sampleMemory: () => void) {
const collections = [];
const fillRates: Record<string, Awaited<ReturnType<typeof fieldCoverage>>> = {};
const examples: Partial<Record<Entity, { collection: string; document: Document }[]>> = {};
const group: Record<string, string[]> = {};
for (const row of (await mongo.listCollections()).sort((a, b) => cmp(a.name, b.name))) {
const name = row.name, source = sourceOf(name), entity = entities[name] ?? 'unclassified';
const estimatedDocumentCount = await mongo.estimatedDocumentCount(name);
const countDocuments = estimatedDocumentCount < 1_000_000 ? await mongo.countDocuments(name) : null;
const indexes = (await mongo.listIndexes(name)).map(index => String(index.name)).sort(cmp);
const keyRows = await mongo.aggregate(name, [
{ $sample: { size: 200 } },
{ $project: { _id: 0, keys: { $map: { input: { $objectToArray: '$$ROOT' }, as: 'field', in: '$$field.k' } } } },
]).toArray();
const topLevelKeys = [...new Set<string>(keyRows.flatMap(value => value.keys))].sort(cmp);
(group[source] ??= []).push(name);
collections.push({ name, source, entity, estimatedDocumentCount, countDocuments, indexes, topLevelKeys });
const seen = examples[entity] ??= [];
if (seen.length < 2 && estimatedDocumentCount) {
for (const document of await mongo.find(name).limit(2 - seen.length)) seen.push({ collection: name, document: trimmed(document) });
}
if (aliases[name]) fillRates[name] = await fieldCoverage(mongo, name, aliases[name], limit);
sampleMemory();
console.error('Inspected ' + name);
}
return { collections, groups: group, examples, fillRates };
}
const tables = [
'exchanges', 'symbols', 'provider_mappings', 'provider_exchange_mappings', 'sync_status',
'master_exchanges', 'master_symbols', 'provider_symbol_mappings',
] as const;
type Mapping = { provider: string; code: string; master: string | null; verified: boolean | null; auto: boolean | null };
async function readPostgres(client: Client) {
await client.connect();
await client.query('BEGIN TRANSACTION READ ONLY');
try {
const counts: Record<string, number | 'missing'> = {};
for (const table of tables) {
const { rows: [row] } = await client.query('SELECT to_regclass($1) IS NOT NULL AS present', ['public.' + table]);
counts[table] = row.present
? Number((await client.query('SELECT count(*) AS total FROM public.' + table)).rows[0].total) : 'missing';
}
const present = (table: string) => counts[table] !== 'missing';
const rows = async (sql: string) => (await client.query(sql)).rows;
const exchangeStatus = present('provider_exchange_mappings') ? await rows(`
SELECT provider, master_exchange_id IS NOT NULL AS mapped, verified, active, auto_mapped, count(*)::int AS total
FROM public.provider_exchange_mappings GROUP BY 1,2,3,4,5 ORDER BY 1,2,3,4,5`) : [];
const symbolStatus = present('provider_mappings') ? await rows(`
SELECT provider, verified, count(*)::int AS total
FROM public.provider_mappings GROUP BY 1,2 ORDER BY 1,2`) : [];
const confidence = present('provider_mappings') ? await rows(`
SELECT provider, confidence, count(*)::int AS total
FROM public.provider_mappings GROUP BY 1,2 ORDER BY 1,2`) : [];
const mapping: Mapping[] = present('provider_exchange_mappings') ? await rows(`
SELECT provider, provider_exchange_code AS code, master_exchange_id AS master,
verified, auto_mapped AS auto FROM public.provider_exchange_mappings
ORDER BY provider, provider_exchange_code`) : [];
return { counts, exchangeStatus, symbolStatus, confidence, mapping };
} finally {
await client.query('ROLLBACK');
}
}
function mappingIndex(mapping: Mapping[]) {
const result = new Map<string, Mapping>();
for (const row of mapping) {
const key = tupleKey(row.provider.toLowerCase(), upper(row.code.trim())), previous = result.get(key);
if (previous?.master && row.master && previous.master !== row.master)
throw Error('Conflicting master exchange mappings for a normalized provider code');
if (!previous || row.master) result.set(key, row);
}
return result;
}
function pathValue(document: Document, path: string): unknown {
return path.split('.').reduce<unknown>((parent, key) =>
parent && typeof parent === 'object' ? (parent as Document)[key] : undefined, document);
}
function identifiers(document: Document, mapping: Aliases) {
return Object.fromEntries(fields.map(field => [field, mapping[field]?.map(path => text(pathValue(document, path))).find(Boolean) ?? ''])) as Record<Field, string>;
}
function projection(mapping: Aliases) {
return Object.fromEntries(Object.values(mapping).flat().map(path => [path, 1]));
}
function validIsin(value: string) {
if (!/^[A-Z]{2}[A-Z0-9]{9}[0-9]$/.test(value)) return false;
const digits = value.replace(/[A-Z]/g, letter => String(letter.charCodeAt(0) - 55));
let total = 0;
for (let i = digits.length - 1; i >= 0; i--) {
const n = Number(digits[i]) * ((digits.length - i) % 2 ? 1 : 2);
total += n > 9 ? n - 9 : n;
}
return total % 10 === 0;
}
const venues = 'US|CA|NASDAQ|NYSE|AMEX|NYSEARCA|TSX|TSE|TSXV|CSE|OTC';
const prefix = new RegExp('^(?:' + venues + '):');
const suffix = new RegExp(':(?:' + venues + ')$');
function tickerKey(raw: string) {
const rules: string[] = [];
let key = raw;
for (const [rule, pattern, replacement] of [
['case', /[a-z]/, upper(key)],
['venue_prefix', prefix, ''],
['venue_suffix', suffix, ''],
['us_dot_suffix', /\.US$/, ''],
['share_class_separator', /^([A-Z0-9]+)[ /-]([A-Z])$/, '$1.$2'],
['share_class_dot', /^[A-Z0-9]+\.[A-Z]$/, null],
] as const) {
if (!pattern.test(key)) continue;
rules.push(rule);
if (replacement !== null) key = rule === 'case' ? replacement : key.replace(pattern, replacement);
}
return { key, rules };
}
function countryKey(value: string) {
const code = upper(value);
return ({ USA: 'US', 'UNITED STATES': 'US', 'UNITED STATES OF AMERICA': 'US', CAN: 'CA', CANADA: 'CA',
GBR: 'GB', UK: 'GB', 'UNITED KINGDOM': 'GB', AUS: 'AU', AUSTRALIA: 'AU' } as Record<string, string>)[code] ?? code;
}
const words = (name: string) => new Set(name.toLowerCase().normalize('NFKC').match(/[\p{L}\p{N}]+/gu) ?? []);
function similar(a: string, b: string) {
if (!a || !b) return false;
if (a === b) return true;
const one = words(a), two = words(b);
let common = 0;
for (const token of one) if (two.has(token)) common++;
return common > 0 && common / (one.size + two.size - common) >= 0.8;
}
type Stock = [source: Source, id: unknown, exact: string, ticker: string, exchange: string, master: string,
rawIsin: string, isin: string, cusip: string, figi: string, name: string, country: string, currency: string];
type Index = Map<string, number[]>;
const add = (index: Index, key: string, id: number) => {
if (!key) return;
const ids = index.get(key);
if (ids) ids.push(id);
else index.set(key, [id]);
};
const marketKey = (ticker: string, market: string) => ticker && market ? tupleKey(ticker, market) : '';
const stocksFor = (source: Source) => source + 'Symbols';
const exchangeFor = (source: Source) => source + 'Exchanges';
async function gatherStocks(mongo: MongoReads, names: Set<string>, mapping: Map<string, Mapping>, limit: number | null, memory: () => void) {
const records: Stock[] = [];
const indices = { isin: new Map() as Index, cusip: new Map() as Index, figi: new Map() as Index,
markets: new Map() as Index, rawMarkets: new Map() as Index, currency: new Map() as Index, rawCurrency: new Map() as Index,
tickers: new Map() as Index };
const counts = Object.fromEntries(sources.map(source => [source, {
noExchangeCode: 0, mappingMissing: 0, mappingHasNullMaster: 0, hasMaster: 0,
normalizations: {} as Record<string, number>,
}])) as Record<Source, { noExchangeCode: number; mappingMissing: number; mappingHasNullMaster: number; hasMaster: number; normalizations: Record<string, number> }>;
for (const source of sources) {
const name = stocksFor(source);
if (!names.has(name)) continue;
const rules = aliases[name], stats = counts[source];
for await (const row of mongo.aggregate(name, [{ $project: projection(rules) }, ...limitStages(limit)])) {
const id = identifiers(row, rules), rawIsin = upper(id.isin);
const isin = validIsin(rawIsin) ? rawIsin : '';
const cusip = /^[0-9A-Z*@#]{9}$/.test(upper(id.cusip)) ? upper(id.cusip) : /^(US|CA)/.test(isin) ? isin.slice(2, 11) : '';
const figi = /^[A-Z0-9]{12}$/.test(upper(id.figi)) ? upper(id.figi) : '';
const exchange = upper(id.exchange), mapped = mapping.get(tupleKey(source, exchange));
if (!exchange) stats.noExchangeCode++;
else if (!mapped) stats.mappingMissing++;
else if (!mapped.master) stats.mappingHasNullMaster++;
else stats.hasMaster++;
const { key: ticker, rules: applied } = tickerKey(id.ticker);
for (const rule of applied) stats.normalizations[rule] = (stats.normalizations[rule] ?? 0) + 1;
const master = mapped?.master ?? '', currency = upper(id.currency);
const n = records.length;
records.push([source, row._id, id.ticker, ticker, exchange, master, rawIsin, isin, cusip, figi, id.name, countryKey(id.country), currency]);
add(indices.isin, isin, n);
add(indices.cusip, cusip, n);
add(indices.figi, figi, n);
add(indices.tickers, ticker, n);
add(indices.markets, marketKey(ticker, master), n);
add(indices.rawMarkets, marketKey(id.ticker, master), n);
if (master && id.name) {
add(indices.currency, marketKey(ticker, currency), n);
add(indices.rawCurrency, marketKey(id.ticker, currency), n);
}
if (n % 2048 === 0) memory();
}
console.error('Projected ' + name);
}
return { records, indices, counts };
}
type StockData = Awaited<ReturnType<typeof gatherStocks>>;
const tally = () => ({ total: 0, strong: 0, weak_only: 0, unmatched: 0, exact_after_trim: 0, normalized: 0 });
type Tally = ReturnType<typeof tally>;
const sourceBit = Object.fromEntries(sources.map((source, n) => [source, 1 << n])) as Record<Source, number>;
function hitBits(records: Stock[], ids: number[] | undefined, source: Source, predicate?: (record: Stock) => boolean) {
let bits = 0;
for (const id of ids ?? []) {
const other = records[id];
if (other[0] !== source && (!predicate || predicate(other))) bits |= sourceBit[other[0]];
}
return bits;
}
function countRecord(counts: Tally, mask: number, strong: number, exact: number, normal: number) {
counts.total++;
if (strong & mask) { counts.strong++; return; }
if (exact & mask) counts.exact_after_trim++;
if (normal & mask) counts.normalized++;
if ((exact | normal) & mask) counts.weak_only++;
else counts.unmatched++;
}
function measureStocks(data: StockData, memory: () => void) {
const { records, indices, counts: coverage } = data;
const bySource = Object.fromEntries(sources.map(source => [source, tally()])) as Record<Source, Tally>;
const byPair: Record<string, Tally> = {};
for (const source of sources) for (const target of sources) if (source !== target) byPair[source + '→' + target] = tally();
for (let i = 0; i < records.length; i++) {
const [source, , raw, ticker, , master, , isin, cusip, figi, name, , currency] = records[i];
const hits = (index: Index, key: string) => key ? hitBits(records, index.get(key), source) : 0;
const strong = hits(indices.isin, isin) | hits(indices.cusip, cusip) | hits(indices.figi, figi);
const compareName = (row: Stock) => similar(name, row[10]);
const nameHits = (index: Index, ticker: string) => master && name && ticker && currency
? hitBits(records, index.get(marketKey(ticker, currency)), source, compareName) : 0;
const exact = hits(indices.rawMarkets, marketKey(raw, master)) | nameHits(indices.rawCurrency, raw);
const normal = hits(indices.markets, marketKey(ticker, master)) | nameHits(indices.currency, ticker);
countRecord(bySource[source], 15, strong, exact, normal);
for (const target of sources) if (source !== target)
countRecord(byPair[source + '→' + target], sourceBit[target], strong, exact, normal);
if (i % 2048 === 0) memory();
}
return { bySource, byPair, mappingCoverage: coverage };
}
async function measureExchanges(mongo: MongoReads, names: Set<string>, mapping: Map<string, Mapping>, limit: number | null) {
const codes = new Map<string, { source: Source; code: string; mic: string; country: string; name: string }>();
for (const source of sources) {
const collection = exchangeFor(source), rules = aliases[collection];
if (!names.has(collection)) continue;
for await (const row of mongo.aggregate(collection, [{ $project: projection(rules) }, ...limitStages(limit)])) {
const fields = identifiers(row, rules), code = upper(fields.exchange);
if (code) codes.set(tupleKey(source, code),
{ source, code, mic: upper(fields.mic), country: countryKey(fields.country), name: fields.name });
}
}
const rows = [...codes.values()];
return Object.fromEntries(sources.map(source => {
const counts = { total: 0, strong: 0, mappedVerified: 0, mappedAuto: 0, mappedOther: 0, weak_only: 0, unmatched: 0 };
for (const row of rows.filter(value => value.source === source)) {
counts.total++;
const mapped = mapping.get(tupleKey(source, row.code));
if (mapped?.master) {
counts.strong++;
if (mapped.verified) counts.mappedVerified++;
else if (mapped.auto) counts.mappedAuto++;
else counts.mappedOther++;
} else if (rows.some(peer => peer.source !== source &&
((row.mic && !/^(X{4}|N\/A|-)$/.test(row.mic) && peer.mic === row.mic) ||
(row.country && peer.country === row.country && similar(row.name, peer.name))))) counts.weak_only++;
else counts.unmatched++;
}
return [source, counts];
}));
}
type Pair = [number, number];
type Case = { bucket: string; key: string; ids: number[] };
const different = (a: string, b: string) => !!a && !!b && a !== b;
function trickySelection({ records, indices }: StockData) {
const cases: Case[] = [];
const idOrder = (a: number, b: number) => cmp(records[a][0], records[b][0]) || cmp(String(records[a][1]), String(records[b][1]));
const pair = (list: number[], test: (a: Stock, b: Stock) => boolean): Pair | undefined => {
if (list.length < 2) return;
const ordered = [...list].sort(idOrder);
for (let i = 0; i < ordered.length; i++) for (let j = i + 1; j < ordered.length; j++) {
const a = ordered[i], b = ordered[j];
if (records[a][0] !== records[b][0] && test(records[a], records[b])) return [a, b];
}
};
const grouped = (bucket: string, index: Index, test: (a: Stock, b: Stock) => boolean) => {
let count = 0;
for (const key of [...index.keys()].sort(cmp)) {
const ids = pair(index.get(key)!, test);
if (!ids) continue;
cases.push({ bucket, key: key.replaceAll('\u0000', ' / '), ids });
if (++count === 5) break;
}
};
grouped('isin_currency_or_country_conflict', indices.isin, (a, b) => different(a[11], b[11]) || different(a[12], b[12]));
grouped('isin_ticker_variation', indices.isin, (a, b) => different(a[2], b[2]));
grouped('share_class_format', indices.tickers, (a, b) =>
/^[A-Z0-9]+\.[A-Z]$/.test(a[3]) && different(a[2], b[2]) && [a[2], b[2]].some(value => /[ /-][A-Z]$/i.test(value)));
grouped('dual_master_exchanges', indices.isin, (a, b) => different(a[5], b[5]));
grouped('ticker_exchange_conflicting_isins', indices.markets, (a, b) => different(a[7], b[7]));
const invalid = records.flatMap((row, id) => row[6] && !row[7] ? [id] : [])
.sort((a, b) => cmp(records[a][6], records[b][6]) || cmp(records[a][2], records[b][2]) || idOrder(a, b));
for (const id of invalid.slice(0, 5)) cases.push({ bucket: 'invalid_isin', key: records[id][6], ids: [id] });
return cases;
}
async function trickyDocuments(mongo: MongoReads, data: StockData) {
const output = [];
for (const { bucket, key, ids } of trickySelection(data)) {
const documents = [];
for (const i of ids) {
const [source, _id, ticker, normalizedTicker, , master] = data.records[i], collection = stocksFor(source);
const [doc] = await mongo.find(collection, { _id }).limit(1);
if (!doc) throw Error('A selected fixture disappeared during the inventory');
documents.push({ collection, _id, ticker, normalizedTicker, resolvedMasterExchangeId: master || null, document: trimmed(doc) });
}
output.push({ bucket, key, documents });
}
return output;
}
async function main() {
const started = performance.now(), generatedAt = new Date().toISOString();
let peakRSS = 0;
const memory = () => { peakRSS = Math.max(peakRSS, process.memoryUsage.rss(), process.resourceUsage().maxRSS * 1024); };
memory();
const args = parseArgs({ options: { 'sample-limit': { type: 'string' } } });
const limit = args.values['sample-limit'] === undefined ? null : Number(args.values['sample-limit']);
if (limit !== null && (!Number.isSafeInteger(limit) || limit < 1)) throw Error('Expected a positive sample limit');
const env = parseEnv(await Bun.file(resolve(import.meta.dir, '../../../../.env')).text());
const rootUri = env.MONGODB_URI;
if (!rootUri) throw Error('Missing MONGODB_URI');
const parsed = safeMongoUri(rootUri), name = env.MONGODB_DATABASE || parsed.pathname.slice(1) || 'stock';
const host = env.POSTGRES_HOST;
if (!host || !['localhost', '127.0.0.1', '::1'].includes(host)) throw Error('Expected a local Postgres host');
const metadata = new MongoClient(rootUri, { readPreference: 'secondaryPreferred', serverSelectionTimeoutMS: 5_000 });
const pg = new Client({
host, port: Number(env.POSTGRES_PORT || 5432), database: env.POSTGRES_DATABASE,
user: env.POSTGRES_USERNAME, password: env.POSTGRES_PASSWORD, connectionTimeoutMillis: 5_000,
});
let reader: MongoClient | undefined;
try {
await metadata.connect();
const users = await mongoUsers(metadata, name);
const readUri = await mongoReadUri(rootUri, name, users, env), active = safeMongoUri(readUri);
let dbClient = metadata;
if (readUri !== rootUri) {
reader = new MongoClient(readUri, { readPreference: 'secondaryPreferred', serverSelectionTimeoutMS: 5_000 });
await reader.connect();
dbClient = reader;
}
const mongo = mongoReads(dbClient.db(name));
const { mapping: rows, ...postgres } = await readPostgres(pg);
const mapping = mappingIndex(rows);
const { collections, groups, examples, fillRates } = await inventory(mongo, limit, memory);
const names = new Set(collections.map(collection => collection.name));
const data = await gatherStocks(mongo, names, mapping, limit, memory);
const stocks = measureStocks(data, memory);
const exchanges = await measureExchanges(mongo, names, mapping, limit);
const trickyCases = await trickyDocuments(mongo, data);
memory();
console.log(JSON.stringify({
generatedAt,
mongo: { uriMasked: active.protocol + '//***:***@' + active.host + '/' + name,
db: name, users, readOnlyUserExists: users.some(readOnly), collectionLogin: readUri === rootUri ? 'configured' : 'read-only' },
collections, sources: { collections: groups, examples }, fillRates, postgres, matching: { stocks, exchanges },
trickyCases, sampleLimit: limit, runtimeMs: Math.round(performance.now() - started), peakRssMb: Math.round(peakRSS / 1048576),
}));
} finally {
await Promise.allSettled([metadata.close(), pg.end(), reader?.close()]);
}
}
await main().catch(error => {
const safeMessages = ['Aggregation stage is forbidden', 'Expected a bounded example query', 'Expected usersInfo',
'Expected a local MongoDB host', 'Expected a local Postgres host', 'Missing MONGODB_URI', 'Expected a positive sample limit',
'A read-only MongoDB user exists but its URI is unavailable; supply PHASE1_MONGO_READ_URI',
'Conflicting master exchange mappings for a normalized provider code', 'A selected fixture disappeared during the inventory'];
console.error('Inventory failed: ' + (safeMessages.includes(error?.message) ? error.message :
String(error?.name || 'Error') + (error?.code ? ' (' + String(error.code) + ')' : '')));
process.exitCode = 1;
});

View file

@ -1,7 +1,6 @@
import { BaseHandler, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers';
import type { IServiceContainer } from '@stock-bot/services';
import { clearPostgreSQLData } from './operations/clear-postgresql-data.operations';
import { getSyncStatus } from './operations/enhanced-sync-status.operations';
import { getExchangeStats } from './operations/exchange-stats.operations';
import { getProviderMappingStats } from './operations/provider-mapping-stats.operations';
import { syncQMExchanges } from './operations/qm-exchanges.operations';
@ -97,15 +96,6 @@ class ExchangesHandler extends BaseHandler {
this.log('info', 'Getting provider mapping statistics...');
return getProviderMappingStats({}, this);
}
/**
* Get enhanced sync status
*/
@Operation('enhanced-sync-status')
async getEnhancedSyncStatus(): Promise<unknown> {
this.log('info', 'Getting enhanced sync status...');
return getSyncStatus({}, this);
}
}
export { ExchangesHandler };

View file

@ -1,29 +0,0 @@
import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload, SyncStatus } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-status');
export async function getSyncStatus(
payload: JobPayload,
container: IServiceContainer
): Promise<SyncStatus[]> {
logger.info('Getting comprehensive sync status...');
try {
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = `
SELECT provider, data_type as "dataType", last_sync_at as "lastSyncAt",
last_sync_count as "lastSyncCount", sync_errors as "syncErrors"
FROM sync_status
ORDER BY provider, data_type
`;
const result = await postgresClient.query<SyncStatus>(query);
logger.info(`Retrieved sync status for ${result.rows.length} entries`);
return result.rows;
} catch (error) {
logger.error('Failed to get sync status', { error });
throw error;
}
}

View file

@ -1,19 +0,0 @@
import { clearPostgreSQLData } from './clear-postgresql-data.operations';
import { getSyncStatus } from './enhanced-sync-status.operations';
import { getExchangeStats } from './exchange-stats.operations';
import { getProviderMappingStats } from './provider-mapping-stats.operations';
import { syncQMExchanges } from './qm-exchanges.operations';
import { syncAllExchanges } from './sync-all-exchanges.operations';
import { syncIBExchanges } from './sync-ib-exchanges.operations';
import { syncQMProviderMappings } from './sync-qm-provider-mappings.operations';
export const exchangeOperations = {
syncAllExchanges,
syncQMExchanges,
syncIBExchanges,
syncQMProviderMappings,
clearPostgreSQLData,
getExchangeStats,
getProviderMappingStats,
'enhanced-sync-status': getSyncStatus,
};

View file

@ -1,9 +0,0 @@
import { syncQMSymbols } from './qm-symbols.operations';
import { getSyncStatus } from './sync-status.operations';
import { syncSymbolsFromProvider } from './sync-symbols-from-provider.operations';
export const symbolOperations = {
syncQMSymbols,
syncSymbolsFromProvider,
getSyncStatus,
};

View file

@ -29,7 +29,7 @@ const app = new ServiceApplication(
serviceName: 'data-pipeline',
hostname: security.hostname,
enableHandlers: true,
enableScheduledJobs: true,
enableScheduledJobs: config.queue?.enableScheduledJobs ?? true,
corsConfig: {
origin: '*',
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],

View file

@ -1,23 +1,9 @@
/**
* Route factory for data pipeline service
* Creates routes with access to the service container
*/
import { Hono } from 'hono';
import type { IServiceContainer } from '@stock-bot/handlers';
import { createEnhancedSyncRoutes } from './enhanced-sync.routes';
import type { IServiceContainer } from '@stock-bot/services';
import { healthRoutes } from './health.routes';
import { createStatsRoutes } from './stats.routes';
import { createSyncRoutes } from './sync.routes';
export function createRoutes(container: IServiceContainer): Hono {
export function createRoutes(_container: IServiceContainer): Hono {
const app = new Hono();
// Mount routes
app.route('/health', healthRoutes);
app.route('/sync', createSyncRoutes(container));
app.route('/sync', createEnhancedSyncRoutes(container));
app.route('/sync/stats', createStatsRoutes(container));
return app;
}

View file

@ -1,161 +0,0 @@
import { Hono } from 'hono';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { parseReferenceDataResetRequest } from '@stock-bot/types';
const logger = getLogger('enhanced-sync-routes');
export function createEnhancedSyncRoutes(container: IServiceContainer) {
const enhancedSync = new Hono();
// Enhanced sync endpoints
enhancedSync.post('/exchanges/all', async c => {
if (c.req.query('clear') && c.req.query('clear') !== 'false') {
return c.json({ error: 'Sync is non-destructive; use the explicit maintenance reset' }, 400);
}
try {
const clearFirst = c.req.query('clear') === 'true';
const queueManager = container.queueManager;
if (!queueManager) {
return c.json({ success: false, error: 'Queue manager not available' }, 503);
}
const exchangesQueue = queueManager.getQueue('exchanges');
const job = await exchangesQueue.add('sync-all-exchanges', {
handler: 'exchanges',
operation: 'sync-all-exchanges',
payload: { clearFirst },
});
return c.json({ success: true, jobId: job.id, message: 'Enhanced exchange sync job queued' });
} catch (error) {
logger.error('Failed to queue enhanced exchange sync job', { error });
return c.json(
{ success: false, error: error instanceof Error ? error.message : 'Unknown error' },
500
);
}
});
enhancedSync.post('/provider-mappings/qm', async c => {
try {
const queueManager = container.queueManager;
if (!queueManager) {
return c.json({ success: false, error: 'Queue manager not available' }, 503);
}
const exchangesQueue = queueManager.getQueue('exchanges');
const job = await exchangesQueue.add('sync-qm-provider-mappings', {
handler: 'exchanges',
operation: 'sync-qm-provider-mappings',
payload: {},
});
return c.json({
success: true,
jobId: job.id,
message: 'QM provider mappings sync job queued',
});
} catch (error) {
logger.error('Failed to queue QM provider mappings sync job', { error });
return c.json(
{ success: false, error: error instanceof Error ? error.message : 'Unknown error' },
500
);
}
});
enhancedSync.post('/provider-mappings/ib', async c => {
try {
const queueManager = container.queueManager;
if (!queueManager) {
return c.json({ success: false, error: 'Queue manager not available' }, 503);
}
const exchangesQueue = queueManager.getQueue('exchanges');
const job = await exchangesQueue.add('sync-ib-exchanges', {
handler: 'exchanges',
operation: 'sync-ib-exchanges',
payload: {},
});
return c.json({
success: true,
jobId: job.id,
message: 'IB exchanges sync job queued',
});
} catch (error) {
logger.error('Failed to queue IB exchanges sync job', { error });
return c.json(
{ success: false, error: error instanceof Error ? error.message : 'Unknown error' },
500
);
}
});
enhancedSync.get('/status', async c => {
try {
const queueManager = container.queueManager;
if (!queueManager) {
return c.json({ success: false, error: 'Queue manager not available' }, 503);
}
const symbolsQueue = queueManager.getQueue('symbols');
const job = await symbolsQueue.add('sync-status', {
handler: 'symbols',
operation: 'sync-status',
payload: {},
});
return c.json({ success: true, jobId: job.id, message: 'Sync status job queued' });
} catch (error) {
logger.error('Failed to queue sync status job', { error });
return c.json(
{ success: false, error: error instanceof Error ? error.message : 'Unknown error' },
500
);
}
});
enhancedSync.post('/clear/postgresql', async c => {
const input: unknown = await c.req.json().catch(() => null);
let payload;
try {
payload = parseReferenceDataResetRequest(input);
} catch (error) {
return c.json({ error: error instanceof Error ? error.message : 'Invalid reset' }, 400);
}
try {
const queueManager = container.queueManager;
if (!queueManager) {
return c.json({ success: false, error: 'Queue manager not available' }, 503);
}
const exchangesQueue = queueManager.getQueue('exchanges');
const job = await exchangesQueue.add('clear-postgresql-data', {
handler: 'exchanges',
operation: 'clear-postgresql-data',
payload,
});
return c.json({
success: true,
jobId: job.id,
message: 'PostgreSQL data clear job queued',
});
} catch (error) {
logger.error('Failed to queue PostgreSQL clear job', { error });
return c.json(
{ success: false, error: error instanceof Error ? error.message : 'Unknown error' },
500
);
}
});
return enhancedSync;
}

View file

@ -1,5 +0,0 @@
// Export all route modules
export { healthRoutes } from './health.routes';
export { createSyncRoutes } from './sync.routes';
export { createEnhancedSyncRoutes } from './enhanced-sync.routes';
export { createStatsRoutes } from './stats.routes';

View file

@ -1,60 +0,0 @@
import { Hono } from 'hono';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
const logger = getLogger('stats-routes');
export function createStatsRoutes(container: IServiceContainer) {
const stats = new Hono();
// Statistics endpoints
stats.get('/exchanges', async c => {
try {
const queueManager = container.queueManager;
if (!queueManager) {
return c.json({ error: 'Queue manager not available' }, 503);
}
const exchangesQueue = queueManager.getQueue('exchanges');
const job = await exchangesQueue.add('get-exchange-stats', {
handler: 'exchanges',
operation: 'get-exchange-stats',
payload: {},
});
// Wait for job to complete and return result
const result = await exchangesQueue.waitForJob(job);
return c.json(result);
} catch (error) {
logger.error('Failed to get exchange stats', { error });
return c.json({ error: error instanceof Error ? error.message : 'Unknown error' }, 500);
}
});
stats.get('/provider-mappings', async c => {
try {
const queueManager = container.queueManager;
if (!queueManager) {
return c.json({ error: 'Queue manager not available' }, 503);
}
const exchangesQueue = queueManager.getQueue('exchanges');
const job = await exchangesQueue.add('get-provider-mapping-stats', {
handler: 'exchanges',
operation: 'get-provider-mapping-stats',
payload: {},
});
// Wait for job to complete and return result
const result = await exchangesQueue.waitForJob(job);
return c.json(result);
} catch (error) {
logger.error('Failed to get provider mapping stats', { error });
return c.json({ error: error instanceof Error ? error.message : 'Unknown error' }, 500);
}
});
return stats;
}

View file

@ -1,92 +0,0 @@
import { Hono } from 'hono';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
const logger = getLogger('sync-routes');
export function createSyncRoutes(container: IServiceContainer) {
const sync = new Hono();
// Manual sync trigger endpoints
sync.post('/symbols', async c => {
try {
const queueManager = container.queueManager;
if (!queueManager) {
return c.json({ success: false, error: 'Queue manager not available' }, 503);
}
const symbolsQueue = queueManager.getQueue('symbols');
const job = await symbolsQueue.add('sync-qm-symbols', {
handler: 'symbols',
operation: 'sync-qm-symbols',
payload: {},
});
return c.json({ success: true, jobId: job.id, message: 'QM symbols sync job queued' });
} catch (error) {
logger.error('Failed to queue symbol sync job', { error });
return c.json(
{ success: false, error: error instanceof Error ? error.message : 'Unknown error' },
500
);
}
});
sync.post('/exchanges', async c => {
try {
const queueManager = container.queueManager;
if (!queueManager) {
return c.json({ success: false, error: 'Queue manager not available' }, 503);
}
const exchangesQueue = queueManager.getQueue('exchanges');
const job = await exchangesQueue.add('sync-qm-exchanges', {
handler: 'exchanges',
operation: 'sync-qm-exchanges',
payload: {},
});
return c.json({ success: true, jobId: job.id, message: 'QM exchanges sync job queued' });
} catch (error) {
logger.error('Failed to queue exchange sync job', { error });
return c.json(
{ success: false, error: error instanceof Error ? error.message : 'Unknown error' },
500
);
}
});
sync.post('/symbols/:provider', async c => {
try {
const provider = c.req.param('provider');
const queueManager = container.queueManager;
if (!queueManager) {
return c.json({ success: false, error: 'Queue manager not available' }, 503);
}
const symbolsQueue = queueManager.getQueue('symbols');
const job = await symbolsQueue.add('sync-symbols-from-provider', {
handler: 'symbols',
operation: 'sync-symbols-from-provider',
payload: { provider },
});
return c.json({
success: true,
jobId: job.id,
message: `${provider} symbols sync job queued`,
});
} catch (error) {
logger.error('Failed to queue provider symbol sync job', { error });
return c.json(
{ success: false, error: error instanceof Error ? error.message : 'Unknown error' },
500
);
}
});
return sync;
}

View file

@ -11,7 +11,6 @@ Current research and paper execution share the authoritative Rust core in [src/f
| Current financial execution | `src/financial/`, `src/api/replay.rs`, `src/api/paper.rs` | Use for canonical research and paper execution. Preserve deterministic ordering, financial invariants and recovery contracts. |
| Indicators and analytical calculations | `src/indicators/`, `src/analytics/`, native risk/orderbook analytics, `libs/calculations/` | Retained capabilities. Reuse reviewed implementations and their fixtures. |
| Legacy native execution and accounting | `TradingEngine`, native `BacktestEngine`, `src/core/`, `src/backtest/`, `src/positions/`, `src/risk/`, `src/strategies/` | Retained for compatibility, regression tests and existing algorithm examples. They are not an alternative execution path for current admitted research jobs. |
| Uncompiled reporting reference | [reference/legacy-reporting](reference/legacy-reporting/README.md) | Original calculation prototypes retained byte-for-byte for inspection. Incomplete and unreviewed; not a runtime API or an oracle for financial results. |
The compiled `src/backtest/simple_results.rs`, `src/strategies/mean_reversion_fixed.rs`, public native constructors, and historical regression fixtures are unchanged by this cleanup. No saved dataset, strategy package, result or checkpoint is migrated or removed.
@ -28,7 +27,7 @@ Evidence baseline: `700ee09c`. Cargo's library target is `src/lib.rs`; its modul
| `events.bak/mod.rs` | Removed undeclared event-bus scaffold. No current event or recovery journal uses it. |
| `modes.bak/{mod,backtest,paper,live}.rs` | Removed undeclared alternate runtime, mock broker and simplistic fill/accounting implementations. These depended on the abandoned event/domain design, not the canonical matcher or any supported broker. |
| `strategies/framework/mod.rs` | Removed undeclared generic strategy trait/context and no-op base strategy. It contained no concrete signal algorithm; all compiled strategies remain. |
| `backtest/metrics_calculator.rs`, `backtest/results.rs` | Moved unchanged to `reference/legacy-reporting/`. They were not declared in `backtest/mod.rs`. Retained because they contain statistical/reporting prototypes and supporting result types worth inspecting before any later reuse. |
| `backtest/metrics_calculator.rs`, `backtest/results.rs` | Removed uncompiled reporting prototypes; canonical metric calculations live in `@stock-bot/calculations`. |
The archived calculator includes return, drawdown, streak and symbol-analysis logic alongside placeholder fields and incomplete methods. Moving it does not make those formulas reviewed or compilable. New calculations should enter the reviewed calculation library with explicit semantics and tests, not reactivate the abandoned financial simulator.

View file

@ -1,17 +0,0 @@
{
"lockfileVersion": 1,
"workspaces": {
"": {
"name": "@stock-bot/engine",
"devDependencies": {
"@napi-rs/cli": "^2.16.3",
"cargo-cp-artifact": "^0.1",
},
},
},
"packages": {
"@napi-rs/cli": ["@napi-rs/cli@2.18.4", "", { "bin": { "napi": "scripts/index.js" } }, "sha512-SgJeA4df9DE2iAEpr3M2H0OKl/yjtg1BnRI5/JyowS71tUWhrfSu2LT0V3vlHET+g1hBVlrO60PmEXwUEKp8Mg=="],
"cargo-cp-artifact": ["cargo-cp-artifact@0.1.9", "", { "bin": { "cargo-cp-artifact": "bin/cargo-cp-artifact.js" } }, "sha512-6F+UYzTaGB+awsTXg0uSJA1/b/B3DDJzpKVRu0UmyI7DmNeaAl2RFHuTGIN6fEgpadRxoXGb7gbC1xo4C3IdyA=="],
}
}

View file

@ -31,13 +31,12 @@
},
"scripts": {
"build": "napi build dist --dts index.d.ts --no-dts-header",
"build:debug": "npm run build --",
"build:release": "npm run build -- --release",
"build:debug": "bun run build",
"build:release": "bun run build --release",
"build:napi": "bun run build --release",
"test": "cargo test"
},
"devDependencies": {
"@napi-rs/cli": "^2.16.3",
"cargo-cp-artifact": "^0.1"
"@napi-rs/cli": "^2.16.3"
}
}

View file

@ -1,7 +0,0 @@
# Uncompiled legacy reporting reference
These two files were moved byte-for-byte from `src/backtest/metrics_calculator.rs` and `src/backtest/results.rs` at baseline `700ee09c`. They were already outside the Rust module graph; this directory is not compiled or exported.
`metrics_calculator.rs` retains return/volatility/risk-ratio, drawdown, streak and symbol-summary prototypes. `results.rs` retains their supporting report structures. They depend on obsolete types and contain unfinished calculations, fabricated placeholder zeros, and financial/statistical assumptions that have not passed the canonical research gates. They are reference material, not supported calculations or expected-result fixtures.
Use the reviewed [calculation library](../../../../../libs/calculations/README.md) and canonical [financial reporting](../../src/financial/reporting.rs) for current work. If a prototype is useful, port only that calculation with explicit units, sampling/alignment/null semantics and independent fixtures. Do not import this directory into the engine or revive its old result model.

View file

@ -1,669 +0,0 @@
use chrono::{DateTime, Utc, Datelike};
use std::collections::HashMap;
use super::results::*;
use super::{BacktestConfig, CompletedTrade};
use super::trade_tracker::CompletedTrade as TrackedTrade;
use crate::{Position, Side};
pub struct MetricsCalculator {
config: BacktestConfig,
equity_curve: Vec<(DateTime<Utc>, f64)>,
trades: Vec<TrackedTrade>,
fills: Vec<CompletedTrade>,
positions: HashMap<String, Position>,
}
impl MetricsCalculator {
pub fn new(
config: BacktestConfig,
equity_curve: Vec<(DateTime<Utc>, f64)>,
trades: Vec<TrackedTrade>,
fills: Vec<CompletedTrade>,
positions: HashMap<String, Position>,
) -> Self {
Self {
config,
equity_curve,
trades,
fills,
positions,
}
}
pub fn calculate_all_metrics(&self) -> BacktestResult {
let start_time = Utc::now();
let backtest_id = format!("rust-{}", start_time.timestamp_millis());
// Calculate comprehensive metrics
let metrics = self.calculate_metrics();
// Convert equity curve
let equity_points: Vec<EquityPoint> = self.equity_curve.iter()
.map(|(dt, value)| EquityPoint {
timestamp: dt.timestamp_millis(),
value: *value,
})
.collect();
// Calculate drawdown curve
let drawdown_curve = self.calculate_drawdown_curve();
// Calculate returns
let daily_returns = self.calculate_daily_returns();
let cumulative_returns = self.calculate_cumulative_returns();
// Convert trades to UI format
let trades = self.convert_fills_to_trades();
let open_trades = self.get_open_trades();
// Period analysis
let monthly_returns = self.calculate_period_returns("monthly");
let yearly_returns = self.calculate_period_returns("yearly");
// Symbol analysis
let symbol_analysis = self.calculate_symbol_analysis();
// Drawdown periods
let drawdown_periods = self.analyze_drawdown_periods();
// Exposure analysis
let exposure_analysis = self.calculate_exposure_analysis();
// Position history
let position_history = self.calculate_position_history();
// Trade signals (extracted from trades)
let trade_signals = self.extract_trade_signals();
BacktestResult {
backtest_id,
status: "completed".to_string(),
started_at: self.config.start_time.to_rfc3339(),
completed_at: Utc::now().to_rfc3339(),
execution_time_ms: (Utc::now() - start_time).num_milliseconds() as u64,
config: self.config.clone(),
metrics,
equity_curve: equity_points,
drawdown_curve,
daily_returns,
cumulative_returns,
trades,
open_trades,
trade_signals,
positions: self.positions.clone(),
position_history,
monthly_returns,
yearly_returns,
symbol_analysis,
drawdown_periods,
exposure_analysis,
ohlc_data: HashMap::new(), // Will be filled by orchestrator
error: None,
warnings: None,
}
}
fn calculate_metrics(&self) -> BacktestMetrics {
let initial_capital = self.config.initial_capital;
let final_capital = self.equity_curve.last().map(|(_, v)| *v).unwrap_or(initial_capital);
// Core performance
let total_return = final_capital - initial_capital;
let total_return_pct = (total_return / initial_capital) * 100.0;
let days = (self.config.end_time - self.config.start_time).num_days() as f64;
let years = days / 365.25;
let annualized_return = if years > 0.0 {
((final_capital / initial_capital).powf(1.0 / years) - 1.0) * 100.0
} else {
0.0
};
// Trade statistics
let total_trades = self.trades.len();
let winning_trades = self.trades.iter().filter(|t| t.pnl > 0.0).count();
let losing_trades = self.trades.iter().filter(|t| t.pnl < 0.0).count();
let breakeven_trades = self.trades.iter().filter(|t| t.pnl == 0.0).count();
let win_rate = if total_trades > 0 {
(winning_trades as f64 / total_trades as f64) * 100.0
} else {
0.0
};
let loss_rate = if total_trades > 0 {
(losing_trades as f64 / total_trades as f64) * 100.0
} else {
0.0
};
// PnL calculations
let total_pnl = self.trades.iter().map(|t| t.pnl).sum::<f64>();
let total_commission = self.trades.iter().map(|t| t.commission).sum::<f64>();
let net_pnl = total_pnl - total_commission;
let wins: Vec<f64> = self.trades.iter().filter(|t| t.pnl > 0.0).map(|t| t.pnl).collect();
let losses: Vec<f64> = self.trades.iter().filter(|t| t.pnl < 0.0).map(|t| t.pnl).collect();
let avg_win = if !wins.is_empty() {
wins.iter().sum::<f64>() / wins.len() as f64
} else {
0.0
};
let avg_loss = if !losses.is_empty() {
losses.iter().sum::<f64>() / losses.len() as f64
} else {
0.0
};
let largest_win = wins.iter().cloned().fold(0.0, f64::max);
let largest_loss = losses.iter().cloned().fold(0.0, f64::min);
let avg_trade_pnl = if total_trades > 0 {
total_pnl / total_trades as f64
} else {
0.0
};
// Risk metrics
let returns = self.calculate_returns_series();
let volatility = self.calculate_volatility(&returns);
let sharpe_ratio = self.calculate_sharpe_ratio(&returns, volatility);
let sortino_ratio = self.calculate_sortino_ratio(&returns);
let (max_drawdown, max_drawdown_pct, max_dd_duration) = self.calculate_max_drawdown();
let calmar_ratio = if max_drawdown_pct != 0.0 {
annualized_return / max_drawdown_pct.abs()
} else {
0.0
};
// Value at Risk
let (var_95, cvar_95) = self.calculate_var_cvar(&returns, 0.95);
// Profit factor
let gross_profit = wins.iter().sum::<f64>();
let gross_loss = losses.iter().map(|l| l.abs()).sum::<f64>();
let profit_factor = if gross_loss > 0.0 {
gross_profit / gross_loss
} else if gross_profit > 0.0 {
f64::INFINITY
} else {
0.0
};
// Expectancy
let expectancy = avg_win * (win_rate / 100.0) - avg_loss.abs() * (loss_rate / 100.0);
let expectancy_ratio = if avg_loss != 0.0 {
expectancy / avg_loss.abs()
} else {
0.0
};
// Position statistics
let avg_trade_duration_hours = if total_trades > 0 {
self.trades.iter()
.map(|t| t.duration_seconds as f64 / 3600.0)
.sum::<f64>() / total_trades as f64
} else {
0.0
};
let total_long_trades = self.trades.iter().filter(|t| matches!(t.side, Side::Buy)).count();
let total_short_trades = self.trades.iter().filter(|t| matches!(t.side, Side::Sell)).count();
let long_wins = self.trades.iter()
.filter(|t| matches!(t.side, Side::Buy) && t.pnl > 0.0)
.count();
let short_wins = self.trades.iter()
.filter(|t| matches!(t.side, Side::Sell) && t.pnl > 0.0)
.count();
let long_win_rate = if total_long_trades > 0 {
(long_wins as f64 / total_long_trades as f64) * 100.0
} else {
0.0
};
let short_win_rate = if total_short_trades > 0 {
(short_wins as f64 / total_short_trades as f64) * 100.0
} else {
0.0
};
// Trading activity
let total_volume_traded = self.trades.iter()
.map(|t| t.quantity * t.entry_price + t.quantity * t.exit_price)
.sum::<f64>();
let commission_pct_of_pnl = if total_pnl != 0.0 {
(total_commission / total_pnl.abs()) * 100.0
} else {
0.0
};
// Calculate additional metrics
let downside_deviation = self.calculate_downside_deviation(&returns);
let win_loss_ratio = if avg_loss != 0.0 {
avg_win / avg_loss.abs()
} else {
0.0
};
let kelly_criterion = if win_loss_ratio > 0.0 {
(win_rate / 100.0) - ((1.0 - win_rate / 100.0) / win_loss_ratio)
} else {
0.0
};
// Streaks
let (max_wins, max_losses, current_streak) = self.calculate_streaks();
BacktestMetrics {
// Core Performance
total_return,
total_return_pct,
annualized_return,
total_pnl,
net_pnl,
// Risk Metrics
sharpe_ratio,
sortino_ratio,
calmar_ratio,
max_drawdown,
max_drawdown_pct,
max_drawdown_duration_days: max_dd_duration,
volatility,
downside_deviation,
var_95,
cvar_95,
// Trade Statistics
total_trades,
winning_trades,
losing_trades,
breakeven_trades,
win_rate,
loss_rate,
avg_win,
avg_loss,
largest_win,
largest_loss,
avg_trade_pnl,
avg_trade_duration_hours,
profit_factor,
expectancy,
expectancy_ratio,
// Position Statistics
avg_position_size: 0.0, // TODO: Calculate from position history
max_position_size: 0.0,
avg_positions_held: 0.0,
max_concurrent_positions: 0,
total_long_trades,
total_short_trades,
long_win_rate,
short_win_rate,
// Trading Activity
total_volume_traded,
total_commission_paid: total_commission,
commission_pct_of_pnl,
avg_daily_trades: 0.0, // TODO: Calculate
max_daily_trades: 0,
trading_days: 0,
exposure_time_pct: 0.0,
// Efficiency Metrics
return_over_max_dd: if max_drawdown != 0.0 {
total_return / max_drawdown.abs()
} else {
0.0
},
win_loss_ratio,
kelly_criterion,
ulcer_index: 0.0, // TODO: Calculate
serenity_ratio: 0.0,
lake_ratio: 0.0,
// Monthly/Period Analysis
best_month_return: 0.0, // TODO: Calculate from monthly returns
worst_month_return: 0.0,
positive_months: 0,
negative_months: 0,
monthly_win_rate: 0.0,
avg_monthly_return: 0.0,
// Streak Analysis
max_consecutive_wins: max_wins,
max_consecutive_losses: max_losses,
current_streak,
avg_winning_streak: 0.0, // TODO: Calculate
avg_losing_streak: 0.0,
}
}
fn calculate_returns_series(&self) -> Vec<f64> {
let mut returns = Vec::new();
for i in 1..self.equity_curve.len() {
let prev_value = self.equity_curve[i - 1].1;
let curr_value = self.equity_curve[i].1;
if prev_value > 0.0 {
returns.push((curr_value - prev_value) / prev_value);
}
}
returns
}
fn calculate_volatility(&self, returns: &[f64]) -> f64 {
if returns.is_empty() {
return 0.0;
}
let mean = returns.iter().sum::<f64>() / returns.len() as f64;
let variance = returns.iter()
.map(|r| (r - mean).powi(2))
.sum::<f64>() / returns.len() as f64;
// Annualize the volatility
variance.sqrt() * (252.0_f64).sqrt()
}
fn calculate_sharpe_ratio(&self, returns: &[f64], volatility: f64) -> f64 {
if volatility == 0.0 || returns.is_empty() {
return 0.0;
}
let mean_return = returns.iter().sum::<f64>() / returns.len() as f64;
let annualized_return = mean_return * 252.0;
let risk_free_rate = 0.02; // 2% annual risk-free rate
(annualized_return - risk_free_rate) / volatility
}
fn calculate_sortino_ratio(&self, returns: &[f64]) -> f64 {
if returns.is_empty() {
return 0.0;
}
let mean_return = returns.iter().sum::<f64>() / returns.len() as f64;
let downside_deviation = self.calculate_downside_deviation(returns);
if downside_deviation == 0.0 {
return 0.0;
}
let annualized_return = mean_return * 252.0;
let risk_free_rate = 0.02;
(annualized_return - risk_free_rate) / downside_deviation
}
fn calculate_downside_deviation(&self, returns: &[f64]) -> f64 {
let negative_returns: Vec<f64> = returns.iter()
.filter(|&&r| r < 0.0)
.cloned()
.collect();
if negative_returns.is_empty() {
return 0.0;
}
let mean = negative_returns.iter().sum::<f64>() / negative_returns.len() as f64;
let variance = negative_returns.iter()
.map(|r| (r - mean).powi(2))
.sum::<f64>() / negative_returns.len() as f64;
variance.sqrt() * (252.0_f64).sqrt()
}
fn calculate_max_drawdown(&self) -> (f64, f64, i64) {
let mut max_drawdown = 0.0;
let mut max_drawdown_pct = 0.0;
let mut max_duration = 0i64;
let mut peak = self.config.initial_capital;
let mut peak_date = self.config.start_time;
for (date, value) in &self.equity_curve {
if *value > peak {
peak = *value;
peak_date = *date;
}
let drawdown = peak - value;
let drawdown_pct = (drawdown / peak) * 100.0;
if drawdown > max_drawdown {
max_drawdown = drawdown;
max_drawdown_pct = drawdown_pct;
}
if drawdown > 0.0 {
let duration = (*date - peak_date).num_days();
if duration > max_duration {
max_duration = duration;
}
}
}
(max_drawdown, max_drawdown_pct, max_duration)
}
fn calculate_var_cvar(&self, returns: &[f64], confidence: f64) -> (f64, f64) {
if returns.is_empty() {
return (0.0, 0.0);
}
let mut sorted_returns = returns.to_vec();
sorted_returns.sort_by(|a, b| a.partial_cmp(b).unwrap());
let index = ((1.0 - confidence) * sorted_returns.len() as f64) as usize;
let var = sorted_returns[index];
let cvar = sorted_returns[..=index].iter().sum::<f64>() / (index + 1) as f64;
(var * 100.0, cvar * 100.0)
}
fn calculate_streaks(&self) -> (usize, usize, i32) {
let mut max_wins = 0;
let mut max_losses = 0;
let mut current_streak = 0;
let mut current_wins = 0;
let mut current_losses = 0;
for trade in &self.trades {
if trade.pnl > 0.0 {
current_wins += 1;
current_losses = 0;
if current_wins > max_wins {
max_wins = current_wins;
}
current_streak = current_wins as i32;
} else if trade.pnl < 0.0 {
current_losses += 1;
current_wins = 0;
if current_losses > max_losses {
max_losses = current_losses;
}
current_streak = -(current_losses as i32);
}
}
(max_wins, max_losses, current_streak)
}
fn calculate_drawdown_curve(&self) -> Vec<EquityPoint> {
let mut drawdown_curve = Vec::new();
let mut peak = self.config.initial_capital;
for (date, value) in &self.equity_curve {
if *value > peak {
peak = *value;
}
let drawdown_pct = ((peak - value) / peak) * 100.0;
drawdown_curve.push(EquityPoint {
timestamp: date.timestamp_millis(),
value: -drawdown_pct, // Negative for visualization
});
}
drawdown_curve
}
fn calculate_daily_returns(&self) -> Vec<DailyReturn> {
let mut daily_returns = Vec::new();
for i in 1..self.equity_curve.len() {
let prev = &self.equity_curve[i - 1];
let curr = &self.equity_curve[i];
// Only include if it's a new day
if prev.0.date() != curr.0.date() {
let return_pct = ((curr.1 - prev.1) / prev.1) * 100.0;
daily_returns.push(DailyReturn {
date: curr.0.format("%Y-%m-%d").to_string(),
value: return_pct,
});
}
}
daily_returns
}
fn calculate_cumulative_returns(&self) -> Vec<EquityPoint> {
let initial = self.config.initial_capital;
self.equity_curve.iter()
.map(|(date, value)| EquityPoint {
timestamp: date.timestamp_millis(),
value: ((value - initial) / initial) * 100.0,
})
.collect()
}
fn convert_fills_to_trades(&self) -> Vec<Trade> {
self.fills.iter()
.enumerate()
.map(|(i, fill)| Trade {
id: format!("trade-{}", i),
timestamp: fill.timestamp,
symbol: fill.symbol.clone(),
side: match fill.side {
Side::Buy => "buy".to_string(),
Side::Sell => "sell".to_string(),
},
quantity: fill.quantity,
price: fill.price,
commission: fill.commission,
pnl: None, // Individual fills don't have PnL
})
.collect()
}
fn get_open_trades(&self) -> Vec<Trade> {
// TODO: Implement based on position tracker
Vec::new()
}
fn calculate_period_returns(&self, period: &str) -> Vec<PeriodReturn> {
// TODO: Implement monthly/yearly return calculations
Vec::new()
}
fn calculate_symbol_analysis(&self) -> HashMap<String, SymbolAnalysis> {
let mut analysis: HashMap<String, SymbolAnalysis> = HashMap::new();
// Group trades by symbol
for trade in &self.trades {
let entry = analysis.entry(trade.symbol.clone()).or_insert(SymbolAnalysis {
symbol: trade.symbol.clone(),
total_trades: 0,
winning_trades: 0,
losing_trades: 0,
total_pnl: 0.0,
win_rate: 0.0,
avg_win: 0.0,
avg_loss: 0.0,
profit_factor: 0.0,
total_volume: 0.0,
avg_position_size: 0.0,
exposure_time_pct: 0.0,
});
entry.total_trades += 1;
entry.total_pnl += trade.pnl;
entry.total_volume += trade.quantity * (trade.entry_price + trade.exit_price);
if trade.pnl > 0.0 {
entry.winning_trades += 1;
} else if trade.pnl < 0.0 {
entry.losing_trades += 1;
}
}
// Calculate derived metrics
for (_, entry) in analysis.iter_mut() {
if entry.total_trades > 0 {
entry.win_rate = (entry.winning_trades as f64 / entry.total_trades as f64) * 100.0;
entry.avg_position_size = entry.total_volume / (entry.total_trades as f64 * 2.0);
}
// Calculate avg win/loss
let wins: Vec<f64> = self.trades.iter()
.filter(|t| t.symbol == entry.symbol && t.pnl > 0.0)
.map(|t| t.pnl)
.collect();
let losses: Vec<f64> = self.trades.iter()
.filter(|t| t.symbol == entry.symbol && t.pnl < 0.0)
.map(|t| t.pnl)
.collect();
if !wins.is_empty() {
entry.avg_win = wins.iter().sum::<f64>() / wins.len() as f64;
}
if !losses.is_empty() {
entry.avg_loss = losses.iter().sum::<f64>() / losses.len() as f64;
}
// Profit factor
let gross_profit = wins.iter().sum::<f64>();
let gross_loss = losses.iter().map(|l| l.abs()).sum::<f64>();
if gross_loss > 0.0 {
entry.profit_factor = gross_profit / gross_loss;
} else if gross_profit > 0.0 {
entry.profit_factor = f64::INFINITY;
}
}
analysis
}
fn analyze_drawdown_periods(&self) -> Vec<DrawdownPeriod> {
// TODO: Implement comprehensive drawdown period analysis
Vec::new()
}
fn calculate_exposure_analysis(&self) -> ExposureAnalysis {
// TODO: Implement exposure analysis
ExposureAnalysis {
avg_gross_exposure: 0.0,
avg_net_exposure: 0.0,
max_gross_exposure: 0.0,
max_net_exposure: 0.0,
time_in_market_pct: 0.0,
long_exposure_pct: 0.0,
short_exposure_pct: 0.0,
}
}
fn calculate_position_history(&self) -> Vec<PositionSnapshot> {
// TODO: Implement position history tracking
Vec::new()
}
fn extract_trade_signals(&self) -> Vec<TradeSignal> {
// TODO: Extract signals from strategy execution
Vec::new()
}
}

View file

@ -1,266 +0,0 @@
use chrono::{DateTime, Utc};
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use crate::Position;
use super::{BacktestConfig, CompletedTrade};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BacktestMetrics {
// Core Performance Metrics
pub total_return: f64,
pub total_return_pct: f64,
pub annualized_return: f64,
pub total_pnl: f64,
pub net_pnl: f64, // After commissions
// Risk Metrics
pub sharpe_ratio: f64,
pub sortino_ratio: f64,
pub calmar_ratio: f64,
pub max_drawdown: f64,
pub max_drawdown_pct: f64,
pub max_drawdown_duration_days: i64,
pub volatility: f64,
pub downside_deviation: f64,
pub var_95: f64, // Value at Risk 95%
pub cvar_95: f64, // Conditional VaR 95%
// Trade Statistics
pub total_trades: usize,
pub winning_trades: usize,
pub losing_trades: usize,
pub breakeven_trades: usize,
pub win_rate: f64,
pub loss_rate: f64,
pub avg_win: f64,
pub avg_loss: f64,
pub largest_win: f64,
pub largest_loss: f64,
pub avg_trade_pnl: f64,
pub avg_trade_duration_hours: f64,
pub profit_factor: f64,
pub expectancy: f64,
pub expectancy_ratio: f64,
// Position Statistics
pub avg_position_size: f64,
pub max_position_size: f64,
pub avg_positions_held: f64,
pub max_concurrent_positions: usize,
pub total_long_trades: usize,
pub total_short_trades: usize,
pub long_win_rate: f64,
pub short_win_rate: f64,
// Trading Activity
pub total_volume_traded: f64,
pub total_commission_paid: f64,
pub commission_pct_of_pnl: f64,
pub avg_daily_trades: f64,
pub max_daily_trades: usize,
pub trading_days: usize,
pub exposure_time_pct: f64,
// Efficiency Metrics
pub return_over_max_dd: f64,
pub win_loss_ratio: f64,
pub kelly_criterion: f64,
pub ulcer_index: f64,
pub serenity_ratio: f64,
pub lake_ratio: f64,
// Monthly/Period Analysis
pub best_month_return: f64,
pub worst_month_return: f64,
pub positive_months: usize,
pub negative_months: usize,
pub monthly_win_rate: f64,
pub avg_monthly_return: f64,
// Streak Analysis
pub max_consecutive_wins: usize,
pub max_consecutive_losses: usize,
pub current_streak: i32, // Positive for wins, negative for losses
pub avg_winning_streak: f64,
pub avg_losing_streak: f64,
}
// Trade structure that matches web app expectations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Trade {
pub id: String,
pub timestamp: DateTime<Utc>,
pub symbol: String,
pub side: String, // "buy" or "sell"
pub quantity: f64,
pub price: f64,
pub commission: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub pnl: Option<f64>,
}
// Equity curve point
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EquityPoint {
pub timestamp: i64, // milliseconds since epoch
pub value: f64,
}
// Daily return data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DailyReturn {
pub date: String,
pub value: f64,
}
// Performance data point for charts
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PerformanceDataPoint {
pub timestamp: String,
pub portfolio_value: f64,
pub pnl: f64,
pub drawdown: f64,
}
// Period returns (monthly, weekly, etc)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PeriodReturn {
pub period: String, // "2024-01", "2024-W01", etc
pub start_date: String,
pub end_date: String,
pub return_pct: f64,
pub pnl: f64,
pub trades: usize,
pub win_rate: f64,
}
// Trade analysis by symbol
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SymbolAnalysis {
pub symbol: String,
pub total_trades: usize,
pub winning_trades: usize,
pub losing_trades: usize,
pub total_pnl: f64,
pub win_rate: f64,
pub avg_win: f64,
pub avg_loss: f64,
pub profit_factor: f64,
pub total_volume: f64,
pub avg_position_size: f64,
pub exposure_time_pct: f64,
}
// Drawdown period information
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DrawdownPeriod {
pub start_date: String,
pub end_date: String,
pub peak_value: f64,
pub trough_value: f64,
pub drawdown_pct: f64,
pub recovery_date: Option<String>,
pub duration_days: i64,
pub recovery_days: Option<i64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BacktestResult {
// Metadata
pub backtest_id: String,
pub status: String,
pub started_at: String,
pub completed_at: String,
pub execution_time_ms: u64,
// Configuration
pub config: BacktestConfig,
// Core Metrics
pub metrics: BacktestMetrics,
// Time Series Data
pub equity_curve: Vec<EquityPoint>,
pub drawdown_curve: Vec<EquityPoint>,
pub daily_returns: Vec<DailyReturn>,
pub cumulative_returns: Vec<EquityPoint>,
// Trade Data
pub trades: Vec<Trade>,
pub open_trades: Vec<Trade>,
pub trade_signals: Vec<TradeSignal>,
// Position Data
pub positions: HashMap<String, Position>,
pub position_history: Vec<PositionSnapshot>,
// Analytics
pub monthly_returns: Vec<PeriodReturn>,
pub yearly_returns: Vec<PeriodReturn>,
pub symbol_analysis: HashMap<String, SymbolAnalysis>,
pub drawdown_periods: Vec<DrawdownPeriod>,
pub exposure_analysis: ExposureAnalysis,
// Market Data
pub ohlc_data: HashMap<String, Vec<serde_json::Value>>,
// Error Handling
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub warnings: Option<Vec<String>>,
}
// Trade signal for visualization
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TradeSignal {
pub timestamp: String,
pub symbol: String,
pub action: String, // "buy", "sell", "hold"
pub strength: f64,
pub reason: String,
}
// Position snapshot for tracking
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PositionSnapshot {
pub timestamp: String,
pub positions: HashMap<String, PositionDetail>,
pub total_value: f64,
pub cash: f64,
pub margin_used: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PositionDetail {
pub symbol: String,
pub quantity: f64,
pub avg_price: f64,
pub current_price: f64,
pub market_value: f64,
pub unrealized_pnl: f64,
pub unrealized_pnl_pct: f64,
}
// Exposure analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExposureAnalysis {
pub avg_gross_exposure: f64,
pub avg_net_exposure: f64,
pub max_gross_exposure: f64,
pub max_net_exposure: f64,
pub time_in_market_pct: f64,
pub long_exposure_pct: f64,
pub short_exposure_pct: f64,
}

View file

@ -1,5 +1,3 @@
pub mod market_impact;
pub mod transaction_costs;
pub use market_impact::{MarketImpactModel, ImpactModelType, MarketImpactEstimate};
pub use transaction_costs::{TransactionCostModel, CostComponents};
pub use market_impact::{ImpactModelType, MarketImpactEstimate, MarketImpactModel};

View file

@ -1,355 +0,0 @@
use crate::{Side, Order, Fill, MarketMicrostructure};
use chrono::{DateTime, Utc};
#[derive(Debug, Clone)]
pub struct CostComponents {
pub spread_cost: f64,
pub market_impact: f64,
pub commission: f64,
pub slippage: f64,
pub opportunity_cost: f64,
pub timing_cost: f64,
pub total_cost: f64,
pub cost_bps: f64,
}
#[derive(Debug, Clone)]
pub struct TransactionCostAnalysis {
pub order_id: String,
pub symbol: String,
pub side: Side,
pub intended_size: f64,
pub filled_size: f64,
pub avg_fill_price: f64,
pub arrival_price: f64,
pub benchmark_price: f64,
pub cost_components: CostComponents,
pub implementation_shortfall: f64,
pub duration_ms: i64,
}
pub struct TransactionCostModel {
commission_rate_bps: f64,
min_commission: f64,
exchange_fees_bps: f64,
regulatory_fees_bps: f64,
benchmark_type: BenchmarkType,
}
#[derive(Debug, Clone, Copy)]
pub enum BenchmarkType {
ArrivalPrice, // Price when order was placed
VWAP, // Volume-weighted average price
TWAP, // Time-weighted average price
Close, // Closing price
MidpointAtArrival, // Mid price at order arrival
}
impl TransactionCostModel {
pub fn new(commission_rate_bps: f64) -> Self {
Self {
commission_rate_bps,
min_commission: 1.0,
exchange_fees_bps: 0.3, // Typical exchange fees
regulatory_fees_bps: 0.1, // SEC fees etc
benchmark_type: BenchmarkType::ArrivalPrice,
}
}
pub fn with_benchmark_type(mut self, benchmark_type: BenchmarkType) -> Self {
self.benchmark_type = benchmark_type;
self
}
pub fn analyze_execution(
&self,
order: &Order,
fills: &[Fill],
arrival_price: f64,
benchmark_prices: &BenchmarkPrices,
microstructure: &MarketMicrostructure,
order_start_time: DateTime<Utc>,
order_end_time: DateTime<Utc>,
) -> TransactionCostAnalysis {
// Calculate filled size and average price
let filled_size = fills.iter().map(|f| f.quantity).sum::<f64>();
let total_value = fills.iter().map(|f| f.price * f.quantity).sum::<f64>();
let avg_fill_price = if filled_size > 0.0 {
total_value / filled_size
} else {
arrival_price
};
// Get benchmark price based on type
let benchmark_price = match self.benchmark_type {
BenchmarkType::ArrivalPrice => arrival_price,
BenchmarkType::VWAP => benchmark_prices.vwap,
BenchmarkType::TWAP => benchmark_prices.twap,
BenchmarkType::Close => benchmark_prices.close,
BenchmarkType::MidpointAtArrival => benchmark_prices.midpoint_at_arrival,
};
// Calculate various cost components
let cost_components = self.calculate_cost_components(
order,
fills,
avg_fill_price,
arrival_price,
benchmark_price,
microstructure,
);
// Calculate implementation shortfall
let side_multiplier = match order.side {
Side::Buy => 1.0,
Side::Sell => -1.0,
};
let implementation_shortfall = side_multiplier * filled_size *
(avg_fill_price - arrival_price) +
side_multiplier * (order.quantity - filled_size) *
(benchmark_price - arrival_price);
// Calculate duration
let duration_ms = (order_end_time - order_start_time).num_milliseconds();
TransactionCostAnalysis {
order_id: order.id.clone(),
symbol: order.symbol.clone(),
side: order.side,
intended_size: order.quantity,
filled_size,
avg_fill_price,
arrival_price,
benchmark_price,
cost_components,
implementation_shortfall,
duration_ms,
}
}
fn calculate_cost_components(
&self,
order: &Order,
fills: &[Fill],
avg_fill_price: f64,
arrival_price: f64,
benchmark_price: f64,
microstructure: &MarketMicrostructure,
) -> CostComponents {
let filled_size = fills.iter().map(|f| f.quantity).sum::<f64>();
let total_value = filled_size * avg_fill_price;
// Spread cost (crossing the spread)
let spread_cost = filled_size * avg_fill_price * microstructure.avg_spread_bps / 10000.0;
// Market impact (price movement due to our order)
let side_multiplier = match order.side {
Side::Buy => 1.0,
Side::Sell => -1.0,
};
let market_impact = side_multiplier * filled_size * (avg_fill_price - arrival_price);
// Commission and fees
let gross_commission = total_value * self.commission_rate_bps / 10000.0;
let commission = gross_commission.max(self.min_commission * fills.len() as f64);
let exchange_fees = total_value * self.exchange_fees_bps / 10000.0;
let regulatory_fees = total_value * self.regulatory_fees_bps / 10000.0;
let total_fees = commission + exchange_fees + regulatory_fees;
// Slippage (difference from benchmark)
let slippage = side_multiplier * filled_size * (avg_fill_price - benchmark_price);
// Opportunity cost (unfilled portion)
let unfilled_size = order.quantity - filled_size;
let opportunity_cost = if unfilled_size > 0.0 {
// Cost of not executing at arrival price
side_multiplier * unfilled_size * (benchmark_price - arrival_price)
} else {
0.0
};
// Timing cost (delay cost)
let timing_cost = side_multiplier * filled_size *
(benchmark_price - arrival_price).max(0.0);
// Total cost
let total_cost = spread_cost + market_impact.abs() + total_fees +
slippage.abs() + opportunity_cost.abs() + timing_cost;
// Cost in basis points
let cost_bps = if total_value > 0.0 {
(total_cost / total_value) * 10000.0
} else {
0.0
};
CostComponents {
spread_cost,
market_impact: market_impact.abs(),
commission: total_fees,
slippage: slippage.abs(),
opportunity_cost: opportunity_cost.abs(),
timing_cost,
total_cost,
cost_bps,
}
}
pub fn calculate_pretrade_cost_estimate(
&self,
order: &Order,
microstructure: &MarketMicrostructure,
current_price: f64,
expected_fill_price: f64,
expected_fill_rate: f64,
) -> CostComponents {
let expected_filled_size = order.quantity * expected_fill_rate;
let total_value = expected_filled_size * expected_fill_price;
// Estimate spread cost
let spread_cost = expected_filled_size * expected_fill_price *
microstructure.avg_spread_bps / 10000.0;
// Estimate market impact
let side_multiplier = match order.side {
Side::Buy => 1.0,
Side::Sell => -1.0,
};
let market_impact = side_multiplier * expected_filled_size *
(expected_fill_price - current_price);
// Calculate commission
let gross_commission = total_value * self.commission_rate_bps / 10000.0;
let commission = gross_commission.max(self.min_commission);
let exchange_fees = total_value * self.exchange_fees_bps / 10000.0;
let regulatory_fees = total_value * self.regulatory_fees_bps / 10000.0;
let total_fees = commission + exchange_fees + regulatory_fees;
// Estimate opportunity cost for unfilled portion
let unfilled_size = order.quantity - expected_filled_size;
let opportunity_cost = if unfilled_size > 0.0 {
// Assume 10bps adverse movement for unfilled portion
unfilled_size * current_price * 0.001
} else {
0.0
};
// No slippage or timing cost for pre-trade estimate
let slippage = 0.0;
let timing_cost = 0.0;
// Total cost
let total_cost = spread_cost + market_impact.abs() + total_fees + opportunity_cost;
// Cost in basis points
let cost_bps = if total_value > 0.0 {
(total_cost / total_value) * 10000.0
} else {
0.0
};
CostComponents {
spread_cost,
market_impact: market_impact.abs(),
commission: total_fees,
slippage,
opportunity_cost,
timing_cost,
total_cost,
cost_bps,
}
}
}
#[derive(Debug, Clone)]
pub struct BenchmarkPrices {
pub vwap: f64,
pub twap: f64,
pub close: f64,
pub midpoint_at_arrival: f64,
}
impl Default for BenchmarkPrices {
fn default() -> Self {
Self {
vwap: 0.0,
twap: 0.0,
close: 0.0,
midpoint_at_arrival: 0.0,
}
}
}
// Helper to track and calculate various price benchmarks
pub struct BenchmarkCalculator {
trades: Vec<(DateTime<Utc>, f64, f64)>, // (time, price, volume)
quotes: Vec<(DateTime<Utc>, f64, f64)>, // (time, bid, ask)
}
impl BenchmarkCalculator {
pub fn new() -> Self {
Self {
trades: Vec::new(),
quotes: Vec::new(),
}
}
pub fn add_trade(&mut self, time: DateTime<Utc>, price: f64, volume: f64) {
self.trades.push((time, price, volume));
}
pub fn add_quote(&mut self, time: DateTime<Utc>, bid: f64, ask: f64) {
self.quotes.push((time, bid, ask));
}
pub fn calculate_benchmarks(
&self,
start_time: DateTime<Utc>,
end_time: DateTime<Utc>,
) -> BenchmarkPrices {
// Filter trades within time window
let window_trades: Vec<_> = self.trades.iter()
.filter(|(t, _, _)| *t >= start_time && *t <= end_time)
.cloned()
.collect();
// Calculate VWAP
let total_volume: f64 = window_trades.iter().map(|(_, _, v)| v).sum();
let vwap = if total_volume > 0.0 {
window_trades.iter()
.map(|(_, p, v)| p * v)
.sum::<f64>() / total_volume
} else {
0.0
};
// Calculate TWAP
let twap = if !window_trades.is_empty() {
window_trades.iter()
.map(|(_, p, _)| p)
.sum::<f64>() / window_trades.len() as f64
} else {
0.0
};
// Get close price (last trade)
let close = window_trades.last()
.map(|(_, p, _)| *p)
.unwrap_or(0.0);
// Get midpoint at arrival
let midpoint_at_arrival = self.quotes.iter()
.filter(|(t, _, _)| *t <= start_time)
.last()
.map(|(_, b, a)| (b + a) / 2.0)
.unwrap_or(0.0);
BenchmarkPrices {
vwap,
twap,
close,
midpoint_at_arrival,
}
}
}

View file

@ -1,210 +0,0 @@
use std::collections::HashMap;
use chrono::{DateTime, Utc};
use serde_json::json;
use crate::{
MarketUpdate, MarketDataType,
backtest::{Strategy, Signal, SignalType},
};
/// Mean Reversion Strategy
///
/// This strategy identifies when a security's price deviates significantly from its
/// moving average and trades on the assumption that it will revert back to the mean.
///
/// Entry Signals:
/// - BUY when price falls below (MA - threshold * std_dev)
/// - SELL when price rises above (MA + threshold * std_dev)
///
/// Exit Signals:
/// - Exit long when price reaches MA
/// - Exit short when price reaches MA
pub struct MeanReversionStrategy {
name: String,
id: String,
lookback_period: usize,
entry_threshold: f64, // Number of standard deviations
exit_threshold: f64, // Typically 0 (at the mean)
position_size: f64,
// State
price_history: HashMap<String, Vec<f64>>,
positions: HashMap<String, f64>,
}
impl MeanReversionStrategy {
pub fn new(
name: String,
id: String,
lookback_period: usize,
entry_threshold: f64,
position_size: f64,
) -> Self {
Self {
name,
id,
lookback_period,
entry_threshold,
exit_threshold: 0.0, // Exit at the mean
position_size,
price_history: HashMap::new(),
positions: HashMap::new(),
}
}
fn calculate_mean(prices: &[f64]) -> f64 {
prices.iter().sum::<f64>() / prices.len() as f64
}
fn calculate_std_dev(prices: &[f64], mean: f64) -> f64 {
let variance = prices.iter()
.map(|p| (p - mean).powi(2))
.sum::<f64>() / prices.len() as f64;
variance.sqrt()
}
}
impl Strategy for MeanReversionStrategy {
fn on_market_data(&mut self, data: &MarketUpdate) -> Vec<Signal> {
let mut signals = Vec::new();
// Only process bar data
if let MarketDataType::Bar(bar) = &data.data {
let symbol = &data.symbol;
let price = bar.close;
// Update price history
let history = self.price_history.entry(symbol.clone()).or_insert_with(Vec::new);
history.push(price);
// Keep only necessary history
if history.len() > self.lookback_period {
history.remove(0);
}
// Need enough data
if history.len() >= self.lookback_period {
// Calculate statistics
let mean = Self::calculate_mean(history);
let std_dev = Self::calculate_std_dev(history, mean);
// Calculate bands
let upper_band = mean + self.entry_threshold * std_dev;
let lower_band = mean - self.entry_threshold * std_dev;
let current_position = self.positions.get(symbol).copied().unwrap_or(0.0);
// Check for entry signals
if current_position == 0.0 {
if price < lower_band {
// Price is oversold, buy
signals.push(Signal {
symbol: symbol.clone(),
signal_type: SignalType::Buy,
strength: 1.0,
quantity: Some(self.position_size),
reason: Some(format!(
"Mean reversion buy: price ${:.2} < lower band ${:.2} (mean: ${:.2}, std: ${:.2})",
price, lower_band, mean, std_dev
)),
metadata: Some(json!({
"mean": mean,
"std_dev": std_dev,
"upper_band": upper_band,
"lower_band": lower_band,
"price": price,
})),
});
self.positions.insert(symbol.clone(), self.position_size);
} else if price > upper_band {
// Price is overbought, sell short
signals.push(Signal {
symbol: symbol.clone(),
signal_type: SignalType::Sell,
strength: 1.0,
quantity: Some(self.position_size),
reason: Some(format!(
"Mean reversion sell: price ${:.2} > upper band ${:.2} (mean: ${:.2}, std: ${:.2})",
price, upper_band, mean, std_dev
)),
metadata: Some(json!({
"mean": mean,
"std_dev": std_dev,
"upper_band": upper_band,
"lower_band": lower_band,
"price": price,
})),
});
self.positions.insert(symbol.clone(), -self.position_size);
}
}
// Check for exit signals
else if current_position > 0.0 {
// We're long, exit when price crosses above mean (not just touches)
// or when we hit stop loss
let stop_loss = lower_band - std_dev; // Stop loss below lower band
if price >= mean * 1.01 || price <= stop_loss {
signals.push(Signal {
symbol: symbol.clone(),
signal_type: SignalType::Sell,
strength: 1.0,
quantity: Some(current_position),
reason: Some(format!(
"Mean reversion exit long: price ${:.2} {} mean ${:.2}",
price, if price >= mean * 1.01 { "crossed above" } else { "hit stop loss below" }, mean
)),
metadata: Some(json!({
"mean": mean,
"price": price,
"exit_type": "mean_reversion",
})),
});
self.positions.remove(symbol);
}
} else if current_position < 0.0 {
// We're short, exit when price crosses below mean
// or when we hit stop loss
let stop_loss = upper_band + std_dev; // Stop loss above upper band
if price <= mean * 0.99 || price >= stop_loss {
signals.push(Signal {
symbol: symbol.clone(),
signal_type: SignalType::Buy,
strength: 1.0,
quantity: Some(current_position.abs()),
reason: Some(format!(
"Mean reversion exit short: price ${:.2} {} mean ${:.2}",
price, if price <= mean * 0.99 { "crossed below" } else { "hit stop loss above" }, mean
)),
metadata: Some(json!({
"mean": mean,
"price": price,
"exit_type": "mean_reversion",
})),
});
self.positions.remove(symbol);
}
}
}
}
signals
}
fn on_fill(&mut self, symbol: &str, quantity: f64, price: f64, side: &str) {
// Position tracking is handled in on_market_data for simplicity
eprintln!("Mean reversion fill: {} {} @ {} - {}", quantity, symbol, price, side);
}
fn get_name(&self) -> &str {
&self.name
}
fn get_parameters(&self) -> serde_json::Value {
json!({
"lookback_period": self.lookback_period,
"entry_threshold": self.entry_threshold,
"exit_threshold": self.exit_threshold,
"position_size": self.position_size,
})
}
}

View file

@ -1,10 +1,8 @@
pub mod mean_reversion;
pub mod mean_reversion_fixed;
pub mod momentum;
pub mod pairs_trading;
pub mod sma_crossover;
pub use mean_reversion::MeanReversionStrategy;
pub use mean_reversion_fixed::MeanReversionFixedStrategy;
pub use momentum::MomentumStrategy;
pub use pairs_trading::PairsTradingStrategy;

View file

@ -1,278 +0,0 @@
/**
* Advanced Risk Management Examples
* Demonstrates orderbook analytics, portfolio risk, and bet sizing
*/
import { OrderbookAnalyzer, RiskAnalyzer, TradingEngine } from '@stock-bot/engine';
import { getLogger } from '@stock-bot/logger';
const _logger = getLogger('AdvancedRiskExample');
// Example 1: Orderbook Analytics
async function orderbookAnalyticsExample() {
console.log('\n=== Orderbook Analytics Example ===');
const engine = new TradingEngine('paper', { startingCapital: 100000 });
const obAnalyzer = new OrderbookAnalyzer();
// Update orderbook with some data
const symbol = 'AAPL';
engine.updateQuote(symbol, 149.95, 150.05, 1000, 1200);
engine.updateQuote(symbol, 149.9, 150.1, 800, 900);
engine.updateQuote(symbol, 149.85, 150.15, 600, 700);
// Get orderbook snapshot
const snapshotJson = engine.getOrderbookSnapshot(symbol, 10);
const _snapshot = JSON.parse(snapshotJson);
// Analyze orderbook
const analyticsJson = obAnalyzer.analyzeOrderbook(snapshotJson);
const analytics = JSON.parse(analyticsJson);
console.log('Orderbook Analytics:');
console.log(` Spread: $${analytics.spread.toFixed(2)} (${analytics.spread_bps.toFixed(1)} bps)`);
console.log(` Mid Price: $${analytics.mid_price.toFixed(2)}`);
console.log(` Micro Price: $${analytics.micro_price.toFixed(2)}`);
console.log(` Imbalance: ${(analytics.imbalance * 100).toFixed(1)}%`);
console.log(` Liquidity Score: ${analytics.liquidity_score.toFixed(2)}`);
// Calculate liquidity profile
const profileJson = obAnalyzer.calculateLiquidityProfile(snapshotJson);
const profile = JSON.parse(profileJson);
console.log('\nLiquidity Profile:');
console.log(` Total Bid Depth: $${profile.total_bid_depth.toFixed(2)}`);
console.log(` Total Ask Depth: $${profile.total_ask_depth.toFixed(2)}`);
// Calculate market impact for a $10,000 buy order
const impactJson = obAnalyzer.calculateMarketImpact(snapshotJson, 10000, true);
const impact = JSON.parse(impactJson);
console.log('\nMarket Impact ($10k buy):');
console.log(` Avg Execution Price: $${impact.avg_execution_price.toFixed(2)}`);
console.log(` Price Impact: ${(impact.price_impact * 100).toFixed(2)}%`);
console.log(` Slippage: $${impact.slippage.toFixed(2)}`);
console.log(` Levels Consumed: ${impact.levels_consumed}`);
}
// Example 2: Portfolio Risk Analysis
async function portfolioRiskExample() {
console.log('\n=== Portfolio Risk Analysis Example ===');
const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252); // $100k, 2% risk, 252 days lookback
// Update historical returns for portfolio symbols
const symbols = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'META'];
// Simulate some returns data (in practice, load from historical data)
for (const symbol of symbols) {
const returns = generateRandomReturns(252);
riskAnalyzer.updateReturns(symbol, returns);
}
// Current positions
const positions = [
{ symbol: 'AAPL', quantity: 100, avgPrice: 150 },
{ symbol: 'GOOGL', quantity: 50, avgPrice: 140 },
{ symbol: 'MSFT', quantity: 75, avgPrice: 380 },
{ symbol: 'AMZN', quantity: 40, avgPrice: 170 },
{ symbol: 'META', quantity: 60, avgPrice: 480 },
];
// Current prices
const prices = {
AAPL: 155,
GOOGL: 145,
MSFT: 390,
AMZN: 175,
META: 490,
};
// Calculate portfolio risk
const riskJson = riskAnalyzer.calculatePortfolioRisk(
JSON.stringify(positions.map(p => [p.symbol, p.quantity, p.avgPrice])),
JSON.stringify(prices)
);
const risk = JSON.parse(riskJson);
console.log('Portfolio Risk Metrics:');
console.log(` VaR (95%): $${risk.total_var_95.toFixed(2)}`);
console.log(` VaR (99%): $${risk.total_var_99.toFixed(2)}`);
console.log(` CVaR (95%): $${risk.total_cvar_95.toFixed(2)}`);
console.log('\nConcentration Metrics:');
console.log(` Herfindahl Index: ${risk.concentration_risk.herfindahl_index.toFixed(3)}`);
console.log(
` Effective Positions: ${risk.concentration_risk.effective_number_of_positions.toFixed(1)}`
);
console.log(
` Top 5 Concentration: ${(risk.concentration_risk.top_5_concentration * 100).toFixed(1)}%`
);
console.log('\nCorrelation Analysis:');
console.log(` Average Correlation: ${risk.correlation_matrix.average_correlation.toFixed(3)}`);
console.log(
` Max Correlation: ${risk.correlation_matrix.max_correlation[0]} vs ${risk.correlation_matrix.max_correlation[1]} = ${risk.correlation_matrix.max_correlation[2].toFixed(3)}`
);
console.log(` Clustering Score: ${risk.correlation_matrix.clustering_score.toFixed(3)}`);
console.log('\nStress Test Results:');
for (const [scenario, loss] of Object.entries(risk.stress_test_results)) {
console.log(` ${scenario}: $${(loss as number).toFixed(2)}`);
}
}
// Example 3: Dynamic Bet Sizing
async function betSizingExample() {
console.log('\n=== Dynamic Bet Sizing Example ===');
const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252);
// Scenario 1: Strong signal in trending market
console.log('\nScenario 1: Strong Signal, Trending Market');
let positionSize = riskAnalyzer.calculatePositionSize(
0.8, // signal_strength
0.9, // signal_confidence
0.015, // volatility (1.5% daily)
0.8, // liquidity_score
0.02, // current_drawdown (2%)
150, // price
145, // stop_loss
'trending'
);
let size = JSON.parse(positionSize);
console.log(` Shares: ${size.shares}`);
console.log(` Notional Value: $${size.notional_value.toFixed(2)}`);
console.log(` % of Capital: ${(size.percent_of_capital * 100).toFixed(2)}%`);
console.log(' Adjustments:');
for (const adj of size.adjustments) {
console.log(` ${adj.reason}: ${adj.factor.toFixed(2)}x`);
}
// Scenario 2: Weak signal in high volatility
console.log('\nScenario 2: Weak Signal, High Volatility');
positionSize = riskAnalyzer.calculatePositionSize(
0.3, // signal_strength
0.5, // signal_confidence
0.03, // volatility (3% daily)
0.6, // liquidity_score
0.15, // current_drawdown (15%)
150, // price
null, // no stop_loss
'high_volatility'
);
size = JSON.parse(positionSize);
console.log(` Shares: ${size.shares}`);
console.log(` Notional Value: $${size.notional_value.toFixed(2)}`);
console.log(` % of Capital: ${(size.percent_of_capital * 100).toFixed(2)}%`);
// Calculate optimal stop loss
const supportLevels = [148, 145, 142, 140];
const optimalStop = riskAnalyzer.calculateOptimalStopLoss(
150, // entry_price
0.015, // volatility
supportLevels,
2.5, // atr
true // is_long
);
console.log(`\nOptimal Stop Loss: $${optimalStop.toFixed(2)}`);
}
// Example 4: Integrated Risk Management in Trading
async function integratedTradingExample() {
console.log('\n=== Integrated Risk Management Example ===');
const engine = new TradingEngine('backtest', {
startTime: Date.now() - 30 * 24 * 60 * 60 * 1000, // 30 days ago
endTime: Date.now(),
speedMultiplier: 1,
});
const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252);
const obAnalyzer = new OrderbookAnalyzer();
// Simulate a trading decision
const symbol = 'AAPL';
// 1. Check orderbook liquidity
engine.updateQuote(symbol, 149.95, 150.05, 5000, 5500);
const snapshot = engine.getOrderbookSnapshot(symbol, 10);
const analytics = JSON.parse(obAnalyzer.analyzeOrderbook(snapshot));
console.log('Pre-trade Analysis:');
console.log(` Liquidity Score: ${analytics.liquidity_score.toFixed(2)}`);
console.log(` Spread: ${analytics.spread_bps.toFixed(1)} bps`);
console.log(` Orderbook Imbalance: ${(analytics.imbalance * 100).toFixed(1)}%`);
// 2. Calculate position size based on current conditions
const positionSizeJson = riskAnalyzer.calculatePositionSize(
0.7, // signal_strength
0.8, // signal_confidence
0.018, // volatility
analytics.liquidity_score, // from orderbook
0.05, // current_drawdown
150, // price
147, // stop_loss
'trending'
);
const positionSize = JSON.parse(positionSizeJson);
console.log(`\nPosition Sizing:`);
console.log(` Recommended Shares: ${positionSize.shares}`);
console.log(` Risk-Adjusted Size: ${(positionSize.risk_adjusted_size * 100).toFixed(2)}%`);
// 3. Check market impact before placing order
const orderValue = positionSize.shares * 150;
const impact = JSON.parse(obAnalyzer.calculateMarketImpact(snapshot, orderValue, true));
console.log(`\nExpected Market Impact:`);
console.log(` Price Impact: ${(impact.price_impact * 100).toFixed(3)}%`);
console.log(` Expected Fill Price: $${impact.avg_execution_price.toFixed(2)}`);
// 4. Risk check
const riskCheck = engine.checkRisk({
id: '123',
symbol: symbol,
side: 'buy',
quantity: positionSize.shares,
orderType: 'market',
timeInForce: 'DAY',
});
const riskResult = JSON.parse(riskCheck);
console.log(`\nRisk Check: ${riskResult.passed ? 'PASSED' : 'FAILED'}`);
if (!riskResult.passed) {
console.log(' Violations:', riskResult.violations);
}
}
// Helper function to generate random returns
function generateRandomReturns(length: number): number[] {
const returns: number[] = [];
for (let i = 0; i < length; i++) {
// Generate returns with mean 0.0005 (0.05%) and std dev 0.02 (2%)
const return_ = (Math.random() - 0.5) * 0.04 + 0.0005;
returns.push(return_);
}
return returns;
}
// Run all examples
async function runExamples() {
try {
await orderbookAnalyticsExample();
await portfolioRiskExample();
await betSizingExample();
await integratedTradingExample();
} catch (error) {
console.error('Error running examples:', error);
}
}
// Execute if running directly
if (require.main === module) {
runExamples();
}

View file

@ -1,6 +1,6 @@
import { parseFinancialDecimal } from '@stock-bot/types';
import type { NativeBacktestWorker } from '../src/backtest/NativeBacktestWorker';
import { replayIdentitySchema } from '../src/contracts/native-replay';
import { replayIdentitySchema } from '@stock-bot/stock-config/canonical-replay';
import {
parseStrategyReplayResult,
strategyReplayRequestSchema,

View file

@ -1,93 +0,0 @@
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { createExampleRuntime } from './example-runtime';
async function debugPositionTracking() {
// Create service container with detailed logging
const {
container,
storageService,
marketDataService: _marketDataService,
modeManager,
strategyManager,
} = await createExampleRuntime();
// Initialize backtest mode with full config
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-06-01T00:00:00Z',
endDate: '2023-09-01T00:00:00Z', // Just 3 months for debugging
speed: 'max',
symbols: ['AAPL.US'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover',
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Listen to strategy events for debugging
strategyManager.on('order', (orderEvent: unknown) => {
console.log('\n📊 STRATEGY ORDER EVENT:', orderEvent);
});
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Position Tracking Debug',
strategy: 'sma-crossover',
symbols: ['AAPL.US'],
startDate: '2023-06-01T00:00:00Z',
endDate: '2023-09-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const,
};
console.log('Starting position tracking debug...\n');
try {
const result = await backtestEngine.runBacktest(config);
console.log('\n=== FINAL RESULTS ===');
console.log(`Total Trades: ${result.metrics.totalTrades}`);
console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`);
console.log('\n=== TRADE DETAILS ===');
let buyCount = 0;
let sellCount = 0;
result.trades.forEach((trade, i) => {
console.log(`\nTrade ${i + 1}:`);
console.log(` Symbol: ${trade.symbol}`);
console.log(` Side: ${trade.side}`);
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
console.log(` Quantity: ${trade.quantity}`);
console.log(` P&L: $${trade.pnl.toFixed(2)}`);
if (trade.side === 'buy') {
buyCount++;
} else if (trade.side === 'sell') {
sellCount++;
}
});
console.log(`\n=== TRADE SIDE SUMMARY ===`);
console.log(`Buy trades: ${buyCount}`);
console.log(`Sell trades: ${sellCount}`);
// Check final positions
console.log('\n=== FINAL POSITIONS ===');
result.positions.forEach(pos => {
console.log(`${pos.symbol}: ${pos.quantity} shares @ avg $${pos.averagePrice.toFixed(2)}`);
});
} catch (error) {
console.error('Debug failed:', error);
}
}
// Run the debug
debugPositionTracking().catch(console.error);

View file

@ -1,130 +0,0 @@
import { TradingEngine } from '@stock-bot/engine';
import type { ClosedTrade } from '../src/backtest/native-result';
async function debugRustShortTrades() {
// Create engine config for backtest mode
const engineConfig = {
startTime: new Date('2023-01-01').getTime(),
endTime: new Date('2023-02-01').getTime(),
speedMultiplier: 0,
};
console.log('=== RUST CORE SHORT TRADE DEBUG ===\n');
console.log('1. Creating TradingEngine in backtest mode...');
const engine = new TradingEngine('backtest', engineConfig);
// Simulate opening a short position
console.log('\n2. Submitting SELL order to open short position...');
const sellOrder = {
id: 'sell-order-001',
symbol: 'TEST',
side: 'sell',
quantity: 100,
orderType: 'market',
timeInForce: 'DAY',
};
const sellOrderId = engine.submitOrder(sellOrder);
console.log(` Sell order ID: ${sellOrderId}`);
// Process the sell fill
console.log('\n3. Processing SELL fill...');
const sellFillResult = engine.processFillWithMetadata(
'TEST', // symbol
50.0, // price
100, // quantity
'sell', // side
0.1, // commission
sellOrderId, // orderId
'debug-strategy' // strategyId
);
console.log(` Fill result: ${sellFillResult}`);
// Check positions
console.log('\n4. Checking positions after SELL...');
const positionsAfterSell = engine.getPosition('TEST');
console.log(' Position:', positionsAfterSell);
// Check open trades
const openTradesAfterSell = JSON.parse(engine.getOpenTrades());
console.log(' Open trades:', openTradesAfterSell.length);
if (openTradesAfterSell.length > 0) {
console.log(' First open trade:', openTradesAfterSell[0]);
}
// Check closed trades
const closedTradesAfterSell = JSON.parse(engine.getClosedTrades());
console.log(' Closed trades:', closedTradesAfterSell.length);
// Now close the short with a buy order
console.log('\n5. Submitting BUY order to close short position...');
const buyOrder = {
id: 'buy-order-001',
symbol: 'TEST',
side: 'buy',
quantity: 100,
orderType: 'market',
timeInForce: 'DAY',
};
const buyOrderId = engine.submitOrder(buyOrder);
console.log(` Buy order ID: ${buyOrderId}`);
// Process the buy fill
console.log('\n6. Processing BUY fill...');
const buyFillResult = engine.processFillWithMetadata(
'TEST', // symbol
48.0, // price (profit on short)
100, // quantity
'buy', // side
0.1, // commission
buyOrderId, // orderId
'debug-strategy' // strategyId
);
console.log(` Fill result: ${buyFillResult}`);
// Check positions after closing
console.log('\n7. Checking positions after BUY...');
const positionsAfterBuy = engine.getPosition('TEST');
console.log(' Position:', positionsAfterBuy);
// Check open trades after closing
const openTradesAfterBuy = JSON.parse(engine.getOpenTrades());
console.log(' Open trades:', openTradesAfterBuy.length);
// Check closed trades after closing - THIS IS WHERE WE SHOULD SEE THE SHORT TRADE
const closedTradesAfterBuy = JSON.parse(engine.getClosedTrades());
console.log(' Closed trades:', closedTradesAfterBuy.length);
if (closedTradesAfterBuy.length > 0) {
console.log('\n8. Closed trade details:');
closedTradesAfterBuy.forEach((trade: ClosedTrade, i: number) => {
console.log(` Trade ${i + 1}:`);
console.log(` ID: ${trade.id}`);
console.log(` Side: ${trade.side}`);
console.log(` Entry: ${trade.entry_price} @ ${trade.entry_time}`);
console.log(` Exit: ${trade.exit_price} @ ${trade.exit_time}`);
console.log(` P&L: ${trade.pnl} (${trade.pnl_percent}%)`);
console.log(` Quantity: ${trade.quantity}`);
});
} else {
console.log('\n❌ ERROR: No closed trades found! Short trade was not recorded.');
}
// Also check trade history
console.log('\n9. Trade history:');
const tradeHistory = JSON.parse(engine.getTradeHistory());
tradeHistory.forEach((trade: ClosedTrade, i: number) => {
console.log(` Trade ${i + 1}: ${trade.side} ${trade.quantity} @ ${trade.price}`);
});
// Check totals
console.log('\n10. Summary:');
console.log(` Total trades: ${engine.getTradeCount()}`);
console.log(` Closed trades: ${engine.getClosedTradeCount()}`);
const [realizedPnl, unrealizedPnl] = engine.getTotalPnl();
console.log(` Realized P&L: ${realizedPnl}`);
console.log(` Unrealized P&L: ${unrealizedPnl}`);
}
// Run the debug
debugRustShortTrades().catch(console.error);

View file

@ -1,70 +0,0 @@
import { ServiceContainerBuilder } from '@stock-bot/di';
import { ModeManager } from '../src/core/ModeManager';
import { ExecutionService } from '../src/services/ExecutionService';
import { MarketDataService } from '../src/services/MarketDataService';
import { StorageService } from '../src/services/StorageService';
import { createBuiltinStrategyRegistry } from '../src/strategies/builtin-strategies';
import { StrategyManager } from '../src/strategies/StrategyManager';
import type { OrchestratorServices } from '../src/types';
/** Legacy algorithm examples only: no queue, HTTP server, durable runs, or paper account. */
export async function createExampleRuntime() {
const di = await new ServiceContainerBuilder()
.withOptions({
enableCache: false,
enableQueue: false,
enableMongoDB: false,
enablePostgres: false,
enableQuestDB: false,
enableBrowser: false,
enableProxy: false,
})
.build();
const container = di.resolve('serviceContainer') as OrchestratorServices;
const storageService = new StorageService(container.logger, null, null, {
allowSyntheticData: true,
syntheticSeed: 42,
});
const marketDataService: MarketDataService = new MarketDataService({
logger: container.logger,
storage: storageService,
drainStrategies: () => strategyManager.drain(),
});
const executionService = new ExecutionService(container, storageService, {
allowedMode: 'backtest',
});
const registry = createBuiltinStrategyRegistry();
const strategyManager: StrategyManager = new StrategyManager({
logger: container.logger,
marketData: marketDataService,
execution: executionService,
createStrategy: config => registry.create(config, { modeManager, execution: executionService }),
});
const modeManager: ModeManager = new ModeManager({
allowedMode: 'backtest',
logger: container.logger,
marketData: marketDataService,
execution: executionService,
strategies: strategyManager,
});
const custom = container.custom ?? {};
if (!container.custom) {
Object.defineProperty(container, 'custom', { value: custom, enumerable: true });
}
Object.assign(custom, {
StorageService: storageService,
MarketDataService: marketDataService,
ExecutionService: executionService,
StrategyManager: strategyManager,
ModeManager: modeManager,
});
strategyManager.setupEventListeners();
return {
container,
storageService,
marketDataService,
executionService,
modeManager,
strategyManager,
};
}

View file

@ -1,138 +0,0 @@
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { createExampleRuntime } from './example-runtime';
// Modify the data generation to ensure we get both golden and death crosses
function generateMockDataWithBothCrosses() {
const data = [];
const startDate = new Date('2023-01-01');
let price = 150;
// Create 365 days of data with clear trends
for (let i = 0; i < 365; i++) {
const date = new Date(startDate);
date.setDate(date.getDate() + i);
// Create alternating trends every ~30 days
const cycleDay = i % 60;
if (cycleDay < 30) {
// Uptrend - will create golden crosses
price += Math.random() * 2 - 0.5; // Bias upward
} else {
// Downtrend - will create death crosses
price -= Math.random() * 2 - 0.5; // Bias downward
}
// Add some volatility
const dayChange = (Math.random() - 0.5) * 4;
price = Math.max(100, Math.min(200, price + dayChange));
data.push({
timestamp: date.toISOString(),
open: price - Math.random() * 2,
high: price + Math.random() * 2,
low: price - Math.random() * 2,
close: price,
volume: Math.floor(Math.random() * 10000000) + 5000000,
});
}
return data;
}
async function forceBothTradeTypes() {
// Create service container with minimal logging
const { container, storageService, marketDataService, modeManager, strategyManager } =
await createExampleRuntime();
// Override the mock data generation
const _originalGenerateMockData = marketDataService.generateMockData;
marketDataService.generateMockData = function (
_symbol: string,
_startDate: string,
_endDate: string
) {
console.log('Generating mock data with forced crossovers...');
return generateMockDataWithBothCrosses();
};
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
speed: 'max',
symbols: ['AAPL.US'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover',
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Force Both Trade Types',
strategy: 'sma-crossover',
symbols: ['AAPL.US'],
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const,
};
console.log('=== TESTING WITH FORCED CROSSOVERS ===\n');
try {
const result = await backtestEngine.runBacktest(config);
console.log('\n=== BACKTEST COMPLETE ===');
console.log(`Total Trades: ${result.metrics.totalTrades}`);
// Analyze trades
let longTrades = 0;
let shortTrades = 0;
result.trades.forEach(trade => {
if (trade.side === 'buy') {
longTrades++;
console.log(`\nLONG trade found:`);
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
console.log(` P&L: $${trade.pnl.toFixed(2)}`);
} else {
shortTrades++;
console.log(`\nSHORT trade found:`);
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
console.log(` P&L: $${trade.pnl.toFixed(2)}`);
}
});
console.log('\n=== FINAL SUMMARY ===');
console.log(`LONG trades: ${longTrades}`);
console.log(`SHORT trades: ${shortTrades}`);
console.log(`Total trades: ${result.metrics.totalTrades}`);
if (longTrades > 0 && shortTrades > 0) {
console.log('\n✅ SUCCESS: Both long and short trades are working!');
} else {
console.log('\n❌ ISSUE: Missing trade types');
if (longTrades === 0) {
console.log(' - No long trades found');
}
if (shortTrades === 0) {
console.log(' - No short trades found');
}
}
} catch (error) {
console.error('Test failed:', error);
}
}
// Run the test
forceBothTradeTypes().catch(console.error);

View file

@ -1,238 +0,0 @@
import { defined } from '@stock-bot/invariants';
/**
* Examples of using the Rust-based Technical Analysis library
*/
import {
IncrementalIndicators,
SignalGenerator,
TechnicalAnalysis,
} from '../src/indicators/TechnicalAnalysis';
// Example 1: Basic indicator calculations
async function basicIndicatorExample() {
console.log('=== Basic Indicator Example ===');
const ta = new TechnicalAnalysis();
// Sample price data
const prices = [
100, 102, 101, 103, 105, 104, 106, 108, 107, 109, 111, 110, 112, 114, 113, 115, 117, 116, 118,
120,
];
// Calculate various indicators
const sma10 = ta.sma(prices, 10);
const ema10 = ta.ema(prices, 10);
const rsi14 = ta.rsi(prices, 14);
console.log(`SMA(10): ${sma10.map(v => v.toFixed(2)).join(', ')}`);
console.log(`EMA(10): ${ema10.map(v => v.toFixed(2)).join(', ')}`);
console.log(`RSI(14): ${rsi14.map(v => v.toFixed(2)).join(', ')}`);
// Latest values
console.log(`\nLatest SMA: ${TechnicalAnalysis.latest(sma10)?.toFixed(2)}`);
console.log(`Latest EMA: ${TechnicalAnalysis.latest(ema10)?.toFixed(2)}`);
console.log(`Latest RSI: ${TechnicalAnalysis.latest(rsi14)?.toFixed(2)}`);
}
// Example 2: Real-time streaming indicators
async function streamingIndicatorExample() {
console.log('\n=== Streaming Indicator Example ===');
const manager = new IncrementalIndicators();
// Create indicators
manager.createSMA('sma_fast', 5);
manager.createSMA('sma_slow', 10);
manager.createEMA('ema', 10);
manager.createRSI('rsi', 14);
// Simulate real-time price updates
console.log('Processing real-time price updates...');
for (let i = 0; i < 20; i++) {
const price = 100 + Math.sin(i * 0.3) * 5 + Math.random() * 2;
const smaFast = manager.update('sma_fast', price);
const smaSlow = manager.update('sma_slow', price);
const ema = manager.update('ema', price);
const rsi = manager.update('rsi', price);
if (i >= 14) {
// Once we have enough data
console.log(
`Price: ${price.toFixed(2)} | SMA5: ${smaFast?.toFixed(2)} | SMA10: ${smaSlow?.toFixed(2)} | EMA: ${ema?.toFixed(2)} | RSI: ${rsi?.toFixed(2)}`
);
}
}
}
// Example 3: Complex indicators (MACD, Bollinger Bands, Stochastic)
async function complexIndicatorExample() {
console.log('\n=== Complex Indicator Example ===');
const ta = new TechnicalAnalysis();
// Generate more realistic price data
const generatePrices = (count: number) => {
const prices: { close: number[]; high: number[]; low: number[]; volume: number[] } = {
close: [],
high: [],
low: [],
volume: [],
};
let basePrice = 100;
for (let i = 0; i < count; i++) {
const change = (Math.random() - 0.5) * 2;
basePrice += change;
const high = basePrice + Math.random() * 1;
const low = basePrice - Math.random() * 1;
const close = low + Math.random() * (high - low);
prices.close.push(close);
prices.high.push(high);
prices.low.push(low);
prices.volume.push(Math.random() * 1000000 + 500000);
}
return prices;
};
const prices = generatePrices(50);
// Calculate MACD
const macd = ta.macd(prices.close);
console.log(`MACD Line: ${TechnicalAnalysis.latest(macd.macd)?.toFixed(3)}`);
console.log(`Signal Line: ${TechnicalAnalysis.latest(macd.signal)?.toFixed(3)}`);
console.log(`Histogram: ${TechnicalAnalysis.latest(macd.histogram)?.toFixed(3)}`);
// Calculate Bollinger Bands
const bb = ta.bollingerBands(prices.close, 20, 2);
const currentPrice = prices.close[prices.close.length - 1];
const bbPercent =
(currentPrice - defined(TechnicalAnalysis.latest(bb.lower))) /
(defined(TechnicalAnalysis.latest(bb.upper)) - defined(TechnicalAnalysis.latest(bb.lower)));
console.log(`\nBollinger Bands:`);
console.log(`Upper: ${TechnicalAnalysis.latest(bb.upper)?.toFixed(2)}`);
console.log(`Middle: ${TechnicalAnalysis.latest(bb.middle)?.toFixed(2)}`);
console.log(`Lower: ${TechnicalAnalysis.latest(bb.lower)?.toFixed(2)}`);
console.log(`%B: ${(bbPercent * 100).toFixed(2)}%`);
// Calculate Stochastic
const stoch = ta.stochastic(prices.high, prices.low, prices.close, 14, 3, 3);
console.log(`\nStochastic:`);
console.log(`%K: ${TechnicalAnalysis.latest(stoch.k)?.toFixed(2)}`);
console.log(`%D: ${TechnicalAnalysis.latest(stoch.d)?.toFixed(2)}`);
// Calculate ATR
const atr = ta.atr(prices.high, prices.low, prices.close, 14);
console.log(`\nATR(14): ${TechnicalAnalysis.latest(atr)?.toFixed(3)}`);
}
// Example 4: Trading signal generation
async function signalGenerationExample() {
console.log('\n=== Signal Generation Example ===');
const generator = new SignalGenerator();
// Generate trending market data
const generateTrendingPrices = (count: number, trend: 'up' | 'down' | 'sideways') => {
const prices: { close: number[]; high: number[]; low: number[]; volume: number[] } = {
close: [],
high: [],
low: [],
volume: [],
};
let basePrice = 100;
for (let i = 0; i < count; i++) {
const trendComponent = trend === 'up' ? 0.1 : trend === 'down' ? -0.1 : 0;
const noise = (Math.random() - 0.5) * 2;
basePrice += trendComponent + noise;
const high = basePrice + Math.random() * 1;
const low = basePrice - Math.random() * 1;
const close = low + Math.random() * (high - low);
prices.close.push(close);
prices.high.push(high);
prices.low.push(low);
prices.volume.push(Math.random() * 1000000 + 500000);
}
return prices;
};
// Test different market conditions
const scenarios = [
{ name: 'Uptrend', data: generateTrendingPrices(50, 'up') },
{ name: 'Downtrend', data: generateTrendingPrices(50, 'down') },
{ name: 'Sideways', data: generateTrendingPrices(50, 'sideways') },
];
for (const scenario of scenarios) {
const signal = generator.generateSignals('TEST', scenario.data, Date.now());
console.log(`\n${scenario.name} Market:`);
console.log(`Signal: ${signal.action} (strength: ${signal.strength.toFixed(2)})`);
console.log(`Reason: ${signal.reason}`);
console.log(
`Indicators: RSI=${signal.indicators.rsi?.toFixed(2)}, MACD=${signal.indicators.macd?.toFixed(3)}`
);
}
}
// Example 5: Crossover detection
async function crossoverExample() {
console.log('\n=== Crossover Detection Example ===');
const ta = new TechnicalAnalysis();
// Generate price data with clear trend changes
const prices: number[] = [];
for (let i = 0; i < 100; i++) {
if (i < 30) {
prices.push(100 + i * 0.3); // Uptrend
} else if (i < 60) {
prices.push(109 - (i - 30) * 0.3); // Downtrend
} else {
prices.push(100 + (i - 60) * 0.2); // Uptrend again
}
}
// Calculate moving averages
const fastMA = ta.sma(prices, 10);
const slowMA = ta.sma(prices, 20);
// Detect crossovers
console.log('Checking for crossovers in the last 10 bars:');
for (let i = Math.max(0, fastMA.length - 10); i < fastMA.length; i++) {
const fast = fastMA.slice(0, i + 1);
const slow = slowMA.slice(0, i + 1);
if (TechnicalAnalysis.crossover(fast, slow)) {
console.log(`Bullish crossover at index ${i + 20}`);
} else if (TechnicalAnalysis.crossunder(fast, slow)) {
console.log(`Bearish crossover at index ${i + 20}`);
}
}
}
// Run all examples
async function runExamples() {
try {
await basicIndicatorExample();
await streamingIndicatorExample();
await complexIndicatorExample();
await signalGenerationExample();
await crossoverExample();
} catch (error) {
console.error('Error running examples:', error);
}
}
// Execute if running directly
if (require.main === module) {
runExamples();
}

View file

@ -1,39 +0,0 @@
import type { BacktestEngine } from '../src/backtest/BacktestEngine';
import { BacktestConfigSchema, type BacktestConfig } from '../src/types';
/**
* Preserved offline prototype for older strategy algorithms; not a production research route.
* Importing this example starts no services, loads no model and submits no work.
* A standalone prototype engine owns this demonstration. It does not create durable research results.
* Production research uses approved retained versions and the canonical runner.
*/
export function runMultiStrategyBacktest(
runner: Pick<BacktestEngine, 'runBacktest'>,
range: Pick<BacktestConfig, 'symbols' | 'startDate' | 'endDate'>
) {
const request = BacktestConfigSchema.parse({
symbols: range.symbols,
startDate: range.startDate,
endDate: range.endDate,
mode: 'backtest',
name: 'SMA and mean-reversion example',
strategy: 'sma-crossover',
initialCapital: 100000,
dataFrequency: '1d',
commission: 0.001,
slippage: 0.0001,
strategies: [
{
name: 'sma-crossover',
enabled: true,
config: { fastPeriod: 5, slowPeriod: 15, positionFraction: 0.1 },
},
{
name: 'mean-reversion',
enabled: true,
config: { lookbackPeriod: 20, entryThreshold: 2, exitZScore: 0.5 },
},
],
});
return runner.runBacktest(request);
}

View file

@ -1,75 +0,0 @@
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { createExampleRuntime } from './example-runtime';
async function showOrderFlow() {
// Create service container
const {
container,
storageService,
marketDataService: _marketDataService,
modeManager,
strategyManager,
} = await createExampleRuntime();
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-07-01T00:00:00Z',
endDate: '2023-08-01T00:00:00Z', // Just 1 month
speed: 'max',
symbols: ['AAPL.US'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover',
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Order Flow Demo',
strategy: 'sma-crossover',
symbols: ['AAPL.US'],
startDate: '2023-07-01T00:00:00Z',
endDate: '2023-08-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const,
};
console.log('\n=== ORDER FLOW DEMONSTRATION ===\n');
console.log('This will show the actual BUY and SELL orders being generated and executed:\n');
try {
const result = await backtestEngine.runBacktest(config);
console.log('\n=== COMPLETED TRADES (Round-trips) ===');
console.log('Note: Each trade below represents a BUY order (entry) + SELL order (exit):\n');
result.trades.forEach((trade, i) => {
console.log(`Trade ${i + 1}:`);
console.log(
` Opened with: BUY order on ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`
);
console.log(
` Closed with: SELL order on ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`
);
console.log(` Trade type: ${trade.side === 'buy' ? 'LONG' : 'SHORT'} position`);
console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)\n`);
});
console.log('Summary:');
console.log(`- Total completed trades: ${result.metrics.totalTrades}`);
console.log(`- Each trade = 1 BUY order + 1 SELL order`);
console.log(`- Total orders executed: ${result.metrics.totalTrades * 2}`);
} catch (error) {
console.error('Failed:', error);
}
}
// Run the demo
showOrderFlow().catch(console.error);

View file

@ -1,92 +0,0 @@
import { getLogger } from '@stock-bot/logger';
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { createExampleRuntime } from './example-runtime';
const _logger = getLogger('BacktestTest');
async function runSimpleBacktest() {
// Create service container
const {
container,
storageService,
marketDataService: _marketDataService,
modeManager,
strategyManager,
} = await createExampleRuntime();
// Initialize backtest mode with full config
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
speed: 'max',
symbols: ['AAPL.US'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover',
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest - shorter period for faster testing
const config = {
mode: 'backtest' as const, // Add mode field
name: 'SMA Crossover Test',
strategy: 'sma-crossover',
symbols: ['AAPL.US'], // Just one symbol for simplicity
startDate: '2023-01-01T00:00:00Z', // ISO datetime format
endDate: '2024-01-01T00:00:00Z', // ISO datetime format
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const,
};
console.log('Starting backtest with configuration:', config);
try {
const result = await backtestEngine.runBacktest(config);
console.log('\n=== BACKTEST RESULTS ===');
console.log(`Total Trades: ${result.metrics.totalTrades}`);
console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`);
console.log(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`);
console.log(`Sharpe Ratio: ${result.metrics.sharpeRatio.toFixed(2)}`);
console.log(`Max Drawdown: ${result.metrics.maxDrawdown.toFixed(2)}%`);
console.log('\n=== TRADE HISTORY ===');
if (result.trades.length === 0) {
console.log('No trades were executed!');
} else {
result.trades.forEach((trade, i) => {
console.log(`\nTrade ${i + 1}:`);
console.log(` Symbol: ${trade.symbol}`);
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`);
});
}
// Show some equity curve data
console.log('\n=== EQUITY CURVE (first and last 5 points) ===');
const equityCurve = result.equity;
if (equityCurve.length > 0) {
equityCurve.slice(0, 5).forEach(point => {
console.log(`${point.date}: $${point.value.toFixed(2)}`);
});
if (equityCurve.length > 10) {
console.log('...');
equityCurve.slice(-5).forEach(point => {
console.log(`${point.date}: $${point.value.toFixed(2)}`);
});
}
}
} catch (error) {
console.error('Backtest failed:', error);
}
}
// Run the test
runSimpleBacktest().catch(console.error);

View file

@ -1,84 +0,0 @@
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { StrategyManager } from '../src/strategies/StrategyManager';
import { StorageService } from '../src/services/StorageService';
import { ModeManager } from '../src/core/ModeManager';
import { MarketDataService } from '../src/services/MarketDataService';
import { ExecutionService } from '../src/services/ExecutionService';
import { IServiceContainer } from '@stock-bot/di';
import { getLogger } from '@stock-bot/logger';
const logger = getLogger('BacktestTest');
async function runBacktestWithDetailedLogging() {
// Create service container
const container: IServiceContainer = {
logger,
custom: {}
};
// Initialize services
const storageService = new StorageService();
const marketDataService = new MarketDataService(container);
const executionService = new ExecutionService(container);
const modeManager = new ModeManager(container);
const strategyManager = new StrategyManager(container);
// Set services in container
container.custom = {
MarketDataService: marketDataService,
ExecutionService: executionService,
ModeManager: modeManager,
StorageService: storageService
};
// Set backtest mode
await modeManager.setMode('backtest', {
startTime: new Date('2020-01-01').getTime(),
endTime: new Date('2025-01-01').getTime(),
speedMultiplier: 1
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
name: 'SMA Crossover Test',
strategy: 'sma-crossover',
symbols: ['AAPL', 'GOOGL', 'MSFT'],
startDate: '2020-01-01',
endDate: '2025-01-01',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d'
};
logger.info('Starting backtest with configuration:', config);
try {
const result = await backtestEngine.runBacktest(config);
logger.info('=== BACKTEST RESULTS ===');
logger.info(`Total Trades: ${result.metrics.totalTrades}`);
logger.info(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`);
logger.info(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`);
logger.info(`Sharpe Ratio: ${result.metrics.sharpeRatio.toFixed(2)}`);
logger.info(`Max Drawdown: ${result.metrics.maxDrawdown.toFixed(2)}%`);
logger.info('\n=== TRADE HISTORY ===');
result.trades.forEach((trade, i) => {
logger.info(`Trade ${i + 1}:`);
logger.info(` Symbol: ${trade.symbol}`);
logger.info(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
logger.info(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
logger.info(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`);
});
} catch (error) {
logger.error('Backtest failed:', error);
}
}
// Run the test
runBacktestWithDetailedLogging().catch(console.error);

View file

@ -1,32 +0,0 @@
#!/usr/bin/env bun
// Test importing the @stock-bot/engine package
import * as engine from '@stock-bot/engine';
console.log('Successfully imported @stock-bot/engine');
console.log('Available exports:', Object.keys(engine));
// Test creating some basic objects if they're available
try {
if (engine.createBacktestEngine) {
console.log('✓ createBacktestEngine is available');
}
if (engine.createIndicator) {
console.log('✓ createIndicator is available');
}
if (engine.createRiskManager) {
console.log('✓ createRiskManager is available');
}
// List all available functions
console.log('\nAll available functions:');
for (const [key, value] of Object.entries(engine)) {
if (typeof value === 'function') {
console.log(` - ${key}()`);
}
}
} catch (error) {
console.error('Error testing engine exports:', error);
}

View file

@ -1,84 +0,0 @@
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { createExampleRuntime } from './example-runtime';
async function testShortTrades() {
// Create service container
const {
container,
storageService,
marketDataService: _marketDataService,
modeManager,
strategyManager,
} = await createExampleRuntime();
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
speed: 'max',
symbols: ['AAPL.US'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover',
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Short Trade Test',
strategy: 'sma-crossover',
symbols: ['AAPL.US'],
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const,
};
console.log('Testing short trade recording...\n');
try {
const result = await backtestEngine.runBacktest(config);
console.log('=== BACKTEST RESULTS ===');
console.log(`Total Trades: ${result.metrics.totalTrades}`);
console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`);
console.log(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`);
// Count long vs short trades
let longTrades = 0;
let shortTrades = 0;
console.log('\n=== TRADE BREAKDOWN ===');
result.trades.forEach((trade, i) => {
const tradeType = trade.side === 'buy' ? 'LONG' : 'SHORT';
if (trade.side === 'buy') {
longTrades++;
} else {
shortTrades++;
}
console.log(`Trade ${i + 1} (${tradeType}):`);
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`);
console.log('');
});
console.log('=== TRADE TYPE SUMMARY ===');
console.log(`Long trades: ${longTrades}`);
console.log(`Short trades: ${shortTrades}`);
console.log(`Total trades: ${result.metrics.totalTrades}`);
} catch (error) {
console.error('Test failed:', error);
}
}
// Run the test
testShortTrades().catch(console.error);

View file

@ -1,139 +0,0 @@
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import type { StrategyFill } from '../src/services/ExecutionService';
import type { OrderRequest } from '../src/types';
import { createExampleRuntime } from './example-runtime';
async function traceShortPositions() {
let orderCount = 0;
let fillCount = 0;
const orderTracker: (OrderRequest & { count: number })[] = [];
const fillTracker: StrategyFill[] = [];
// Create service container with detailed logging
const { container, storageService, modeManager, strategyManager } = await createExampleRuntime();
strategyManager.on('order', (event: { order: OrderRequest }) => {
orderTracker.push({ ...event.order, count: ++orderCount });
});
strategyManager.on('fill', (fill: StrategyFill) => {
fillCount++;
fillTracker.push(fill);
});
// Listen to strategy events
strategyManager.on('signal', (signal: unknown) => {
console.log('\n🎯 STRATEGY SIGNAL:', signal);
});
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-06-01T00:00:00Z',
endDate: '2023-09-01T00:00:00Z', // 3 months
speed: 'max',
symbols: ['AAPL.US'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover',
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Short Position Trace',
strategy: 'sma-crossover',
symbols: ['AAPL.US'],
startDate: '2023-06-01T00:00:00Z',
endDate: '2023-09-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const,
};
console.log('=== TRACING SHORT POSITION FLOW ===\n');
try {
const result = await backtestEngine.runBacktest(config);
console.log('\n=== ORDER/FILL TRACKING SUMMARY ===');
console.log(`Total orders submitted: ${orderCount}`);
console.log(`Total fills executed: ${fillCount}`);
// Analyze order flow
let buyOrders = 0;
let sellOrders = 0;
orderTracker.forEach(order => {
if (order.side === 'buy') {
buyOrders++;
} else {
sellOrders++;
}
});
console.log(`\nOrder breakdown:`);
console.log(`- BUY orders: ${buyOrders}`);
console.log(`- SELL orders: ${sellOrders}`);
// Check for short positions
console.log('\n=== LOOKING FOR SHORT PATTERNS ===');
console.log('(A short position starts with a SELL and closes with a BUY)\n');
let potentialShorts = 0;
for (let i = 0; i < orderTracker.length - 1; i++) {
if (orderTracker[i].side === 'sell') {
// Look for subsequent buy to close
for (let j = i + 1; j < orderTracker.length; j++) {
if (orderTracker[j].side === 'buy' && orderTracker[j].symbol === orderTracker[i].symbol) {
potentialShorts++;
console.log(`Potential short trade found:`);
console.log(` Open: Order #${orderTracker[i].count} (SELL)`);
console.log(` Close: Order #${orderTracker[j].count} (BUY)`);
break;
}
}
}
}
console.log(`\nPotential short trades identified: ${potentialShorts}`);
// Final results
console.log('\n=== BACKTEST RESULTS ===');
console.log(`Total closed trades: ${result.metrics.totalTrades}`);
let longTrades = 0;
let shortTrades = 0;
result.trades.forEach((trade, i) => {
const tradeType = trade.side === 'buy' ? 'LONG' : 'SHORT';
if (trade.side === 'buy') {
longTrades++;
} else {
shortTrades++;
}
console.log(`\nTrade ${i + 1} (${tradeType}):`);
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
console.log(` P&L: $${trade.pnl.toFixed(2)}`);
});
console.log('\n=== FINAL SUMMARY ===');
console.log(`Long trades recorded: ${longTrades}`);
console.log(`Short trades recorded: ${shortTrades}`);
console.log(`Expected short trades (from order flow): ${potentialShorts}`);
if (shortTrades < potentialShorts) {
console.log('\n❌ ISSUE: Not all short trades were recorded in closed trades!');
console.log('This suggests the Rust core trade matching logic may have an issue.');
}
} catch (error) {
console.error('Trace failed:', error);
}
}
// Run the trace
traceShortPositions().catch(console.error);

View file

@ -1,115 +0,0 @@
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { createExampleRuntime } from './example-runtime';
async function verifyBothTradeTypes() {
// Create service container
const {
container,
storageService,
marketDataService: _marketDataService,
modeManager,
strategyManager,
} = await createExampleRuntime();
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
speed: 'max',
symbols: ['AAPL.US'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover',
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Trade Type Verification',
strategy: 'sma-crossover',
symbols: ['AAPL.US'],
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const,
};
console.log('=== VERIFYING BOTH LONG AND SHORT TRADES ===\n');
try {
const result = await backtestEngine.runBacktest(config);
console.log('=== BACKTEST COMPLETE ===');
console.log(`Total Trades: ${result.metrics.totalTrades}`);
console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`);
console.log(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`);
// Analyze trades
let longTrades = 0;
let shortTrades = 0;
let longPnL = 0;
let shortPnL = 0;
console.log('\n=== DETAILED TRADE ANALYSIS ===');
result.trades.forEach((trade, i) => {
const isLong = trade.side === 'buy';
const tradeType = isLong ? 'LONG' : 'SHORT';
if (isLong) {
longTrades++;
longPnL += trade.pnl;
} else {
shortTrades++;
shortPnL += trade.pnl;
}
console.log(`\nTrade ${i + 1}:`);
console.log(` Type: ${tradeType} position`);
console.log(` Opening side: ${trade.side.toUpperCase()}`);
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`);
// Explain the trade flow
if (isLong) {
console.log(` Order flow: BUY ${trade.quantity} shares → SELL ${trade.quantity} shares`);
} else {
console.log(` Order flow: SELL ${trade.quantity} shares → BUY ${trade.quantity} shares`);
}
});
console.log('\n=== SUMMARY BY TRADE TYPE ===');
console.log(`LONG trades: ${longTrades}`);
console.log(` - Total P&L from longs: $${longPnL.toFixed(2)}`);
console.log(
` - Average P&L per long: $${longTrades > 0 ? (longPnL / longTrades).toFixed(2) : '0.00'}`
);
console.log(`\nSHORT trades: ${shortTrades}`);
console.log(` - Total P&L from shorts: $${shortPnL.toFixed(2)}`);
console.log(
` - Average P&L per short: $${shortTrades > 0 ? (shortPnL / shortTrades).toFixed(2) : '0.00'}`
);
console.log(`\nTotal trades: ${result.metrics.totalTrades}`);
if (longTrades === 0) {
console.log('\n⚠️ WARNING: No long trades found!');
}
if (shortTrades === 0) {
console.log('\n⚠️ WARNING: No short trades found!');
}
} catch (error) {
console.error('Test failed:', error);
}
}
// Run the verification
verifyBothTradeTypes().catch(console.error);

View file

@ -1,57 +1,35 @@
{
"name": "@stock-bot/orchestrator",
"version": "0.1.0",
"description": "Trading system orchestrator - coordinates between Rust core, data feeds, and analytics",
"description": "Trading system orchestrator — canonical Rust execution and durable research/paper workers",
"type": "module",
"main": "dist/index.js",
"scripts": {
"dev": "bun --watch src/index.ts",
"build": "bun build src/index.ts src/backtest/native-worker.ts src/paper/paper-host.ts --outdir dist --entry-naming '[name].[ext]' --target node --external @stock-bot/engine --external @tensorflow/tfjs-node --external chromium-bidi --external electron --external playwright --external playwright-core",
"build": "bun build src/index.ts src/backtest/native-worker.ts src/paper/paper-host.ts --outdir dist --entry-naming '[name].[ext]' --target node --external @stock-bot/engine",
"start": "bun dist/index.js",
"test": "bun test",
"test:indicators": "bun test tests/indicators.test.ts",
"example:indicators": "bun run examples/indicator-usage.ts",
"test:engine": "bun run examples/test-engine-import.ts",
"build:rust": "cd ../engine && cargo build --release && napi build --platform --release"
},
"dependencies": {
"@stock-bot/research": "workspace:*",
"@stock-bot/calculations": "workspace:*",
"decimal.js-light": "2.5.1",
"@stock-bot/engine": "*",
"@stock-bot/cache": "*",
"@stock-bot/config": "*",
"@stock-bot/di": "*",
"@stock-bot/logger": "*",
"@stock-bot/questdb": "*",
"@stock-bot/queue": "*",
"@stock-bot/shutdown": "*",
"@stock-bot/stock-config": "*",
"@stock-bot/engine": "workspace:*",
"@stock-bot/di": "workspace:*",
"@stock-bot/logger": "workspace:*",
"@stock-bot/stock-config": "workspace:*",
"hono": "^4.0.0",
"socket.io": "^4.7.2",
"socket.io-client": "^4.7.2",
"zod": "^3.22.0",
"uuid": "^9.0.0",
"axios": "^1.6.0",
"@stock-bot/services": "workspace:*",
"@stock-bot/mongodb": "workspace:*",
"@stock-bot/postgres": "workspace:*",
"@stock-bot/invariants": "workspace:*",
"@stock-bot/types": "workspace:*",
"@stock-bot/handlers": "workspace:*",
"@stock-bot/trading-runtime": "workspace:*"
},
"peerDependencies": {
"@tensorflow/tfjs-node": "^4.0.0"
},
"peerDependenciesMeta": {
"@tensorflow/tfjs-node": {
"optional": true
}
},
"devDependencies": {
"@types/node": "^20.0.0",
"typescript": "^5.0.0",
"@tensorflow/tfjs-node": "^4.0.0"
"typescript": "^5.0.0"
}
}

View file

@ -1,172 +0,0 @@
import {
factorStatistics,
finite,
formatStatistic,
performanceAnalysis,
type EquityPoint,
} from '@stock-bot/calculations/analytics';
export interface Trade {
entryTime: Date;
exitTime: Date;
symbol: string;
side: 'long' | 'short';
entryPrice: number;
exitPrice: number;
quantity: number;
commission: number;
pnl: number;
returnPct: number;
holdingPeriod: number;
mae: number;
mfe: number;
}
type Analysis = ReturnType<typeof performanceAnalysis>;
type CoreMetrics = Analysis['metrics'];
/** Legacy report facade: percentage fields remain percentage points; the pure core uses fractions. */
export type PerformanceMetrics = CoreMetrics;
export type FactorAttribution = ReturnType<typeof factorStatistics>;
export interface DrawdownAnalysis {
maxDrawdown: number;
maxDrawdownDuration: number;
currentDrawdown: number;
drawdownPeriods: {
start: Date;
end: Date;
depth: number;
duration: number;
recovery: number | null;
}[];
underwaterCurve: { date: Date; drawdown: number }[];
}
const percentageFields = [
'totalReturn',
'annualizedReturn',
'cagr',
'volatility',
'downVolatility',
'var95',
'cvar95',
'winRate',
] as const;
/** Compatibility facade over pure, shared math; observations are detached and cache invalidation is explicit. */
export class PerformanceAnalyzer {
private equityCurve: EquityPoint[] = [];
private trades: Trade[] = [];
private benchmarkReturns?: number[];
private analysis?: Analysis;
constructor(private readonly initialCapital = 100000) {
if (finite(initialCapital) <= 0) {
throw new Error('Initial capital must be positive');
}
}
addEquityPoint(date: Date, value: number): void {
const timestamp = finite(date.getTime());
finite(value);
const last = this.equityCurve[this.equityCurve.length - 1];
if (last && timestamp < last.timestamp) {
throw new Error('Equity observations must be ordered');
}
if (last?.timestamp === timestamp) {
last.value = value;
} else {
this.equityCurve.push({ timestamp, value });
}
this.analysis = undefined;
}
addTrade(trade: Trade): void {
finite(trade.pnl);
finite(trade.holdingPeriod);
if (trade.holdingPeriod < 0) {
throw new Error('Holding period must be nonnegative');
}
this.trades.push(structuredClone(trade));
this.analysis = undefined;
}
setBenchmark(returns: number[]): void {
for (const value of returns) {
finite(value);
}
this.benchmarkReturns = [...returns];
this.analysis = undefined;
}
private evaluate(): Analysis {
this.analysis ??= performanceAnalysis(
this.equityCurve,
this.trades,
this.initialCapital,
this.benchmarkReturns
);
return this.analysis;
}
getAnalysis(): Analysis {
return structuredClone(this.evaluate());
}
analyze(): PerformanceMetrics {
const metrics = { ...this.evaluate().metrics };
for (const field of percentageFields) {
const value = metrics[field];
if (value !== null) {
metrics[field] = finite(value * 100);
}
}
return metrics;
}
analyzeDrawdowns(): DrawdownAnalysis {
const equity = this.evaluate().equity;
return {
maxDrawdown: equity.maxDrawdown,
maxDrawdownDuration: equity.maxDrawdownDuration,
currentDrawdown: equity.currentDrawdown,
drawdownPeriods: equity.periods.map(period => ({
...period,
start: new Date(period.start),
end: new Date(period.end),
})),
underwaterCurve: equity.underwater.map(point => ({
date: new Date(point.timestamp),
drawdown: point.value,
})),
};
}
calculateFactorAttribution(benchmark: number[]): FactorAttribution {
return factorStatistics(this.evaluate().equity.dailyReturns, benchmark);
}
exportReport(metrics: PerformanceMetrics = this.analyze()): string {
const number = (value: number | null, scale = 1) => formatStatistic(value, 2, scale);
return [
'# Performance Report',
'',
'## Summary Statistics',
'- Total Return: ' + number(metrics.totalReturn) + '%',
'- Annualized Return: ' +
number(metrics.annualizedReturn) +
(metrics.annualizedReturn === null ? '' : '%'),
'- CAGR: ' + number(metrics.cagr) + (metrics.cagr === null ? '' : '%'),
'- Volatility: ' + number(metrics.volatility) + (metrics.volatility === null ? '' : '%'),
'- Max Drawdown: ' + number(metrics.maxDrawdown, 100) + '%',
'- Sharpe Ratio: ' + number(metrics.sharpeRatio),
'- Sortino Ratio: ' + number(metrics.sortinoRatio),
'',
'## Trade Analysis',
'- Total Trades: ' + metrics.totalTrades,
'- Win Rate: ' + number(metrics.winRate) + '%',
'- Profit Factor: ' + number(metrics.profitFactor),
'- Average Win: $' + number(metrics.avgWin),
'- Average Loss: $' + number(metrics.avgLoss),
'- Expectancy: $' + number(metrics.expectancy),
'',
'## Risk Metrics',
'- VaR (95%): ' + number(metrics.var95) + (metrics.var95 === null ? '' : '%'),
'- CVaR (95%): ' + number(metrics.cvar95) + (metrics.cvar95 === null ? '' : '%'),
'- Downside Volatility: ' +
number(metrics.downVolatility) +
(metrics.downVolatility === null ? '' : '%'),
'- Tail Ratio: ' + number(metrics.tailRatio),
'- Skewness: ' + number(metrics.skewness),
'- Kurtosis: ' + number(metrics.kurtosis),
].join('\n');
}
}

View file

@ -1,67 +0,0 @@
import { Hono } from 'hono';
import { z } from 'zod';
import {
correlationRequestSchema,
dateRangeSchema,
optimizationRequestSchema,
predictionRequestSchema,
} from '../../contracts/analytics';
import { AnalyticsServiceError } from '../../services/analytics-error';
import type { OrchestratorServices } from '../../types';
export function createAnalyticsRoutes(container: OrchestratorServices): Hono {
const app = new Hono();
const service = () => {
const analytics = container.custom?.AnalyticsService;
if (!analytics) {
throw new AnalyticsServiceError('unavailable');
}
return analytics;
};
app.onError((error, c) => {
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid analytics request', details: error.issues }, 400);
}
if (error instanceof SyntaxError) {
return c.json({ error: 'Invalid JSON body' }, 400);
}
if (error instanceof AnalyticsServiceError) {
return c.json({ error: error.message, code: error.code }, error.status);
}
container.logger.error('Analytics request failed', { name: error.name });
return c.json({ error: 'Analytics request failed' }, 500);
});
app.get('/performance/:portfolioId', async c => {
const range = dateRangeSchema.parse({
startDate: c.req.query('start_date'),
endDate: c.req.query('end_date'),
});
return c.json(
await service().getPerformanceMetrics(
c.req.param('portfolioId'),
new Date(range.startDate),
new Date(range.endDate)
)
);
});
app.post('/optimize', async c => {
return c.json(
await service().optimizePortfolio(optimizationRequestSchema.parse(await c.req.json()))
);
});
app.get('/risk/:portfolioId', async c =>
c.json(await service().getRiskMetrics(c.req.param('portfolioId')))
);
app.get('/regime', async c =>
c.json({ regime: await service().detectMarketRegime(), timestamp: new Date().toISOString() })
);
app.post('/correlation', async c => {
const { symbols } = correlationRequestSchema.parse(await c.req.json());
return c.json({ symbols, matrix: await service().calculateCorrelationMatrix(symbols) });
});
app.post('/predict', async c => {
const { modelId, features } = predictionRequestSchema.parse(await c.req.json());
return c.json(await service().predictWithModel(modelId, features));
});
return app;
}

View file

@ -1,140 +0,0 @@
import { Hono } from 'hono';
import { z } from 'zod';
import { ExecutionConflictError } from '../../execution/repository';
import { ExecutionService, UnsupportedExecutionError } from '../../services/ExecutionService';
import type { OrchestratorServices as IServiceContainer } from '../../types';
import { OrderRequestSchema } from '../../types';
const OrderIdSchema = z.object({
orderId: z.string(),
});
export function createOrderRoutes(container: IServiceContainer): Hono {
const app = new Hono();
const executionService = container.custom?.ExecutionService as ExecutionService;
// Submit new order
app.post('/', async c => {
try {
const body = await c.req.json();
const orderRequest = OrderRequestSchema.extend({
clientOrderId: z.string().min(1).max(256),
}).parse(body);
const result = await executionService.submitOrder(orderRequest);
return c.json(result, 201);
} catch (error) {
if (error instanceof ExecutionConflictError) {
return c.json({ error: error.message }, 409);
}
if (error instanceof UnsupportedExecutionError) {
return c.json({ error: error.message }, 503);
}
if (error instanceof z.ZodError) {
return c.json(
{
error: 'Invalid order request',
details: error.errors,
},
400
);
}
container.logger.error('Error submitting order:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to submit order',
},
500
);
}
});
// Cancel order
app.delete('/:orderId', async c => {
try {
const { orderId } = OrderIdSchema.parse(c.req.param());
const success = await executionService.cancelOrder(orderId);
if (success) {
return c.json({ message: 'Order cancelled successfully' });
} else {
return c.json({ error: 'Order not found or already filled' }, 404);
}
} catch (error) {
container.logger.error('Error cancelling order:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to cancel order',
},
500
);
}
});
// Get order status
app.get('/:orderId', async c => {
try {
const { orderId } = OrderIdSchema.parse(c.req.param());
const status = await executionService.getOrderStatus(orderId);
if (status) {
return c.json(status);
} else {
return c.json({ error: 'Order not found' }, 404);
}
} catch (error) {
container.logger.error('Error getting order status:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get order status',
},
500
);
}
});
// Batch order submission
app.post('/batch', async c => {
try {
const body = await c.req.json();
const orders = z
.array(OrderRequestSchema.extend({ clientOrderId: z.string().min(1).max(256) }))
.parse(body);
const results = await Promise.allSettled(
orders.map(order => executionService.submitOrder(order))
);
const response = results.map((result, index) => ({
order: orders[index],
result: result.status === 'fulfilled' ? result.value : { error: result.reason },
}));
return c.json(response, 201);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json(
{
error: 'Invalid batch order request',
details: error.errors,
},
400
);
}
container.logger.error('Error submitting batch orders:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to submit batch orders',
},
500
);
}
});
return app;
}

View file

@ -4,10 +4,10 @@ import {
paperActivationSchema,
paperHaltSchema,
PaperRuntimeError,
} from '../../contracts/paper-runtime';
import { ExecutionConflictError } from '../../execution/repository';
import { PaperDeploymentError } from '../../paper/paper-deployment-custody';
import { paperAllowedOrigins, requirePaperOperator } from '../../paper/paper-operator';
} from '@stock-bot/stock-config/paper-runtime';
import { ExecutionConflictError } from '../../execution/canonical-paper';
import { PaperDeploymentError } from '@stock-bot/trading-runtime/paper-deployment-custody';
import { paperAllowedOrigins, requirePaperOperator } from '@stock-bot/trading-runtime/paper-operator';
import type { PaperDeploymentHost } from '../../paper/PaperDeploymentHost';
export function createPaperDeploymentHostRoutes(

View file

@ -1,6 +1,6 @@
import { Hono } from 'hono';
import { z } from 'zod';
import { getCredentialHttpPrincipal } from '@stock-bot/di';
import { getCredentialHttpPrincipal } from '@stock-bot/di/http-security';
import {
paperActivationSchema,
paperConnectionSchema,
@ -8,10 +8,10 @@ import {
paperHaltSchema,
PaperRuntimeError,
type PaperReadiness,
} from '../../contracts/paper-runtime';
import { ExecutionConflictError } from '../../execution/repository';
import { PaperDeploymentError } from '../../paper/paper-deployment-custody';
import { paperAllowedOrigins, requirePaperOperator } from '../../paper/paper-operator';
} from '@stock-bot/stock-config/paper-runtime';
import { ExecutionConflictError } from '../../execution/canonical-paper';
import { PaperDeploymentError } from '@stock-bot/trading-runtime/paper-deployment-custody';
import { paperAllowedOrigins, requirePaperOperator } from '@stock-bot/trading-runtime/paper-operator';
import type { PaperDeploymentHost } from '../../paper/PaperDeploymentHost';
import type { OrchestratorServices } from '../../types';

View file

@ -1,150 +0,0 @@
import { Hono } from 'hono';
import { z } from 'zod';
import { defined } from '@stock-bot/invariants';
import { ModeManager } from '../../core/ModeManager';
import type { OrchestratorServices as IServiceContainer } from '../../types';
const SymbolSchema = z.object({
symbol: z.string(),
});
export function createPositionRoutes(container: IServiceContainer): Hono {
const app = new Hono();
const execution = defined(container.custom?.ExecutionService);
const positionsFromLedger = async () =>
(await execution.getPositions()).map(p => ({
symbol: p.symbol,
quantity: p.quantity,
average_price: p.averagePrice,
realized_pnl: p.realizedPnl,
unrealized_pnl: p.unrealizedPnl,
}));
const modeManager = container.custom?.ModeManager as ModeManager;
// Get all positions
app.get('/', async c => {
try {
const positions = await positionsFromLedger();
return c.json({
mode: modeManager.getCurrentMode(),
positions,
});
} catch (error) {
container.logger.error('Error getting positions:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get positions',
},
500
);
}
});
// Get open positions only
app.get('/open', async c => {
try {
const positions = (await positionsFromLedger()).filter(p => p.quantity !== 0);
return c.json({
mode: modeManager.getCurrentMode(),
positions,
});
} catch (error) {
container.logger.error('Error getting open positions:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get open positions',
},
500
);
}
});
// Get position for specific symbol
app.get('/:symbol', async c => {
try {
const { symbol } = SymbolSchema.parse(c.req.param());
const position = (await positionsFromLedger()).find(p => p.symbol === symbol);
if (position) {
return c.json({
mode: modeManager.getCurrentMode(),
position,
});
} else {
return c.json(
{
error: 'Position not found',
symbol,
},
404
);
}
} catch (error) {
container.logger.error('Error getting position:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get position',
},
500
);
}
});
// Get P&L summary
app.get('/pnl/summary', async c => {
try {
const account = await execution.getAccount();
const realizedPnl = account.realizedPnl,
unrealizedPnl = account.unrealizedPnl;
return c.json({
mode: modeManager.getCurrentMode(),
pnl: {
realized: realizedPnl,
unrealized: unrealizedPnl,
total: realizedPnl + unrealizedPnl,
},
timestamp: new Date().toISOString(),
});
} catch (error) {
container.logger.error('Error getting P&L:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get P&L',
},
500
);
}
});
// Get risk metrics
app.get('/risk/metrics', async c => {
try {
const account = await execution.getAccount();
const metrics = {
gross_exposure: account.grossExposure,
daily_pnl: account.dailyPnl,
position_count: Object.values(account.positions).filter(p => p.quantity !== 0).length,
limits: account.limits,
};
return c.json({
mode: modeManager.getCurrentMode(),
risk: metrics,
timestamp: new Date().toISOString(),
});
} catch (error) {
container.logger.error('Error getting risk metrics:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get risk metrics',
},
500
);
}
});
return app;
}

View file

@ -1,198 +0,0 @@
import { Socket, Server as SocketIOServer } from 'socket.io';
import { z } from 'zod';
import { defined } from '@stock-bot/invariants';
import { ModeManager } from '../../core/ModeManager';
import { ExecutionService } from '../../services/ExecutionService';
import { MarketDataService } from '../../services/MarketDataService';
import { OrderRequestSchema, type OrchestratorServices as IServiceContainer } from '../../types';
const SubscribeSchema = z.object({
symbols: z.array(z.string()),
dataTypes: z.array(z.enum(['quote', 'trade', 'bar'])).optional(),
});
const UnsubscribeSchema = z.object({
symbols: z.array(z.string()),
});
export function setupWebSocketHandlers(io: SocketIOServer, container: IServiceContainer): void {
const marketDataService = container.custom?.MarketDataService as MarketDataService;
const executionService = container.custom?.ExecutionService as ExecutionService;
const modeManager = container.custom?.ModeManager as ModeManager;
// Track client subscriptions
const clientSubscriptions = new Map<string, Set<string>>();
io.on('connection', (socket: Socket) => {
container.logger.info(`WebSocket client connected: ${socket.id}`);
clientSubscriptions.set(socket.id, new Set());
// Send initial connection info
socket.emit('connected', {
mode: modeManager.getCurrentMode(),
timestamp: new Date().toISOString(),
});
// Handle market data subscriptions
socket.on('subscribe', async (data, callback?: Function) => {
try {
const { symbols, dataTypes: _dataTypes } = SubscribeSchema.parse(data);
const subscriptions = defined(clientSubscriptions.get(socket.id));
for (const symbol of symbols) {
await marketDataService.subscribeToSymbol(symbol);
subscriptions.add(symbol);
}
container.logger.debug(`Client ${socket.id} subscribed to: ${symbols.join(', ')}`);
if (callback) {
callback({ success: true, symbols });
}
} catch (error) {
container.logger.error('Subscription error:', error);
if (callback) {
callback({
success: false,
error: error instanceof Error ? error.message : 'Subscription failed',
});
}
}
});
// Handle unsubscribe
socket.on('unsubscribe', async (data, callback?: Function) => {
try {
const { symbols } = UnsubscribeSchema.parse(data);
const subscriptions = defined(clientSubscriptions.get(socket.id));
for (const symbol of symbols) {
subscriptions.delete(symbol);
// Check if any other clients are subscribed
let othersSubscribed = false;
for (const [clientId, subs] of clientSubscriptions) {
if (clientId !== socket.id && subs.has(symbol)) {
othersSubscribed = true;
break;
}
}
if (!othersSubscribed) {
await marketDataService.unsubscribeFromSymbol(symbol);
}
}
container.logger.debug(`Client ${socket.id} unsubscribed from: ${symbols.join(', ')}`);
if (callback) {
callback({ success: true, symbols });
}
} catch (error) {
container.logger.error('Unsubscribe error:', error);
if (callback) {
callback({
success: false,
error: error instanceof Error ? error.message : 'Unsubscribe failed',
});
}
}
});
// Handle order submission via WebSocket
socket.on('submitOrder', async (order, callback?: Function) => {
try {
const result = await executionService.submitOrder(
OrderRequestSchema.extend({ clientOrderId: z.string().min(1).max(256) }).parse(order)
);
if (callback) {
callback({ success: true, result });
}
} catch (error) {
container.logger.error('Order submission error:', error);
if (callback) {
callback({
success: false,
error: error instanceof Error ? error.message : 'Order submission failed',
});
}
}
});
// Handle position queries
socket.on('getPositions', async (callback?: Function) => {
try {
const positions = await executionService.getPositions();
if (callback) {
callback({ success: true, positions });
}
} catch (error) {
container.logger.error('Error getting positions:', error);
if (callback) {
callback({
success: false,
error: error instanceof Error ? error.message : 'Failed to get positions',
});
}
}
});
// Handle disconnection
socket.on('disconnect', async () => {
container.logger.info(`WebSocket client disconnected: ${socket.id}`);
// Unsubscribe from all symbols for this client
const subscriptions = clientSubscriptions.get(socket.id);
if (subscriptions) {
for (const symbol of subscriptions) {
// Check if any other clients are subscribed
let othersSubscribed = false;
for (const [clientId, subs] of clientSubscriptions) {
if (clientId !== socket.id && subs.has(symbol)) {
othersSubscribed = true;
break;
}
}
if (!othersSubscribed) {
await marketDataService.unsubscribeFromSymbol(symbol);
}
}
}
clientSubscriptions.delete(socket.id);
});
});
// Forward market data to subscribed clients
marketDataService.on('marketDataBatch', batch => {
for (const data of batch) {
for (const [clientId, subscriptions] of clientSubscriptions) {
if (subscriptions.has(data.data.symbol)) {
io.to(clientId).emit('marketData', data);
}
}
}
});
// Forward order updates to all clients
executionService.on('orderUpdate', update => {
io.emit('orderUpdate', update);
});
// Forward fills to all clients
executionService.on('fill', fill => {
io.emit('fill', fill);
});
// Mode change notifications
modeManager.on('modeChanged', config => {
io.emit('modeChanged', {
mode: config.mode,
timestamp: new Date().toISOString(),
});
});
container.logger.info('WebSocket handlers initialized');
}

View file

@ -1,181 +0,0 @@
import { randomUUID } from 'node:crypto';
import { EventEmitter } from 'node:events';
import type { TradingEngine } from '@stock-bot/engine';
import { defined } from '@stock-bot/invariants';
import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import { DataManager } from '../data/DataManager';
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
import { amount, decimal } from '../execution/model';
import type { ExecutionService } from '../services/ExecutionService';
import type { StorageService } from '../services/StorageService';
import type { StrategyManager } from '../strategies/StrategyManager';
import type { BacktestConfig } from '../types';
import { BacktestMarket } from './BacktestMarket';
import { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback';
import { BacktestReport } from './BacktestReport';
import type { LegacyBacktestExecutionEngine } from './execution-engine';
import { closedTradesSchema } from './native-result';
import { backtestStrategies } from './strategy-plan';
import type { BacktestResult } from './typescript-result';
export type { BacktestResult } from './typescript-result';
const speeds = { max: null, realtime: 1, '2x': 2, '5x': 5, '10x': 10 } as const;
/** Composes one run's playback, market projection and report. The runner owns durable lifecycle. */
export class BacktestEngine extends EventEmitter implements LegacyBacktestExecutionEngine {
private playback?: BacktestPlayback;
private active?: Promise<BacktestResult>;
private completedReport?: BacktestReport;
private closing = false;
constructor(
private readonly dependencies: {
logger: Pick<Logger, 'info' | 'error'>;
storage: Pick<StorageService, 'getHistoricalBars'>;
strategies: Pick<StrategyManager, 'initializeStrategies' | 'onMarketData'>;
execution: Pick<ExecutionService, 'getAccount'>;
getTradingEngine: () => TradingEngine;
}
) {
super();
}
async runBacktest(input: unknown, resolver?: DatasetResolver): Promise<BacktestResult> {
if (this.closing || this.active) {
throw new Error(
this.closing ? 'Backtest engine is shutting down' : 'Backtest already running'
);
}
const config = parseBacktestRequest(input);
const playback = new BacktestPlayback(Date.parse(config.startDate), speeds[config.speed]);
this.playback = playback;
this.completedReport = undefined;
const work = this.execute(config, playback, resolver);
this.active = work;
try {
return await work;
} finally {
playback.finish();
this.active = undefined;
}
}
private async execute(
config: BacktestConfig,
playback: BacktestPlayback,
resolver?: DatasetResolver
): Promise<BacktestResult> {
const plan = backtestStrategies(config, 'typescript');
const { logger, storage, strategies: strategyManager, execution } = this.dependencies;
logger.info('Starting TypeScript backtest', { symbols: config.symbols });
const dataset = await playback.read(() =>
resolveDataset(storage, config, resolver, playback.signal)
);
playback.assertRunning();
const dataManager = new DataManager(storage);
dataManager.inspectDataset(dataset);
const strategies = plan.map(({ name, parameters, index }) => ({
id: name + '-' + index,
name,
enabled: true,
parameters,
symbols: config.symbols,
allocation: 1 / plan.length,
}));
await strategyManager.initializeStrategies(strategies);
playback.assertRunning();
const trading = this.dependencies.getTradingEngine();
const market = new BacktestMarket(trading, config.symbols, dataset.manifest.hash);
const report = new BacktestReport(config, config.runId ?? randomUUID());
await playback.process(
dataset.bars,
bar => bar.timestamp,
async bar => {
trading.advanceTime(bar.timestamp);
const data = {
type: 'bar' as const,
data: bar,
eventId: [dataset.manifest.hash, bar.symbol, bar.timestamp].join(':'),
};
market.process(data);
await strategyManager.onMarketData(data);
report.record(bar.timestamp, (await execution.getAccount()).equity);
},
progress => this.publishProgress(progress)
);
playback.assertRunning();
const closedTrades = closedTradesSchema.parse(JSON.parse(trading.getClosedTrades()));
const account = await execution.getAccount();
playback.assertRunning();
const positions = Object.values(account.positions)
.filter(position => position.quantity !== 0)
.map(position => {
const quote = account.quotes[position.symbol];
const currentPrice = quote ? (quote.bid + quote.ask) / 2 : position.averagePrice;
return {
...position,
currentPrice,
unrealizedPnl: amount(
decimal(currentPrice).minus(position.averagePrice).times(position.quantity)
),
};
});
const result = report.complete(
dataset,
closedTrades,
positions,
dataManager.getDataQualityReport()
);
this.completedReport = report;
logger.info('TypeScript backtest completed', { trades: result.trades.length });
return result;
}
private publishProgress(progress: PlaybackProgress): void {
try {
this.emit('progress', progress);
} catch (error) {
this.dependencies.logger.error('Backtest progress observer failed', { error });
}
}
async exportResults(format: 'json' | 'csv' | 'html' = 'json'): Promise<string> {
if (this.active) {
throw new Error('Cannot export an unfinished backtest');
}
return defined(this.completedReport, 'No completed backtest report is available').export(
format
);
}
async pauseBacktest(): Promise<void> {
this.playback?.pause();
}
async resumeBacktest(): Promise<void> {
this.playback?.resume();
}
async stopBacktest(): Promise<void> {
this.playback?.stop();
}
async shutdown(): Promise<void> {
this.closing = true;
await this.stopBacktest();
await this.active?.catch(() => {});
}
setSpeedMultiplier(speed: number | null): void {
if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) {
throw new Error('Backtest speed must be positive or null');
}
this.playback?.setSpeed(speed);
}
getStatus() {
return (
this.playback?.getStatus() ?? {
isRunning: false,
isPaused: false,
progress: 0,
currentTime: 0,
}
);
}
}

View file

@ -1,128 +0,0 @@
import type { TradingEngine } from '@stock-bot/engine';
import { at } from '@stock-bot/invariants';
import type { MarketData, MarketMicrostructure } from '../types';
import { MarketSimulator } from './MarketSimulator';
export type BacktestMarketPort = Pick<
TradingEngine,
'updateQuote' | 'updateTrade' | 'setMicrostructure'
>;
/** Market projection only: orders and financial accounting still go through ExecutionService. */
export class BacktestMarket {
private readonly simulator = new MarketSimulator();
private readonly microstructures = new Map<string, MarketMicrostructure>();
constructor(
private readonly engine: BacktestMarketPort,
symbols: string[],
datasetHash: string
) {
this.simulator.resetWithSeed(Number.parseInt(datasetHash.slice(0, 8), 16));
this.loadMarketMicrostructure(symbols);
}
process(data: MarketData): void {
// Process through market simulator for realistic orderbook
const orderbook = this.simulator.processMarketData(data);
if (orderbook) {
// Update trading engine with simulated orderbook
if (orderbook.bids.length > 0 && orderbook.asks.length > 0) {
this.engine.updateQuote(
orderbook.symbol,
at(orderbook.bids, 0).price,
at(orderbook.asks, 0).price,
at(orderbook.bids, 0).size,
at(orderbook.asks, 0).size
);
}
// Set microstructure in trading core for realistic fills
const microstructure = this.microstructures.get(orderbook.symbol);
if (microstructure && this.engine.setMicrostructure) {
this.engine.setMicrostructure(orderbook.symbol, microstructure);
}
} else {
// Fallback to simple processing
switch (data.type) {
case 'quote':
this.engine.updateQuote(
data.data.symbol,
data.data.bid,
data.data.ask,
data.data.bidSize,
data.data.askSize
);
break;
case 'trade':
this.engine.updateTrade(
data.data.symbol,
data.data.price,
data.data.size,
data.data.side
);
break;
case 'bar': {
const spread = data.data.high - data.data.low;
const spreadBps = (spread / data.data.close) * 10000;
const halfSpread = (data.data.close * Math.min(spreadBps, 10)) / 20000;
this.engine.updateQuote(
data.data.symbol,
data.data.close - halfSpread,
data.data.close + halfSpread,
data.data.volume / 100,
data.data.volume / 100
);
break;
}
}
}
}
private loadMarketMicrostructure(symbols: string[]): void {
// In real implementation, would load from database
// For now, create reasonable defaults based on symbol characteristics
for (const symbol of symbols) {
const microstructure: MarketMicrostructure = {
symbol,
avgSpreadBps: 3,
dailyVolume: 10_000_000,
avgTradeSize: 100,
volatility: 0.2,
tickSize: 0.01,
lotSize: 1,
intradayVolumeProfile: this.generateIntradayProfile(),
};
this.microstructures.set(symbol, microstructure);
this.simulator.setMicrostructure(symbol, microstructure);
}
}
private generateIntradayProfile(): number[] {
// U-shaped intraday volume pattern
const profile = new Array(24).fill(0);
const tradingHours = [9, 10, 11, 12, 13, 14, 15, 16]; // 9:30 AM to 4:00 PM
tradingHours.forEach((hour, idx) => {
if (idx === 0 || idx === tradingHours.length - 1) {
// High volume at open and close
profile[hour] = 0.2;
} else if (idx === 1 || idx === tradingHours.length - 2) {
// Moderate volume
profile[hour] = 0.15;
} else {
// Lower midday volume
profile[hour] = 0.1;
}
});
// Normalize
const sum = profile.reduce((a, b) => a + b, 0);
return profile.map(v => v / sum);
}
}

View file

@ -1,181 +0,0 @@
import { BacktestCancelledError } from './execution-engine';
export interface PlaybackProgress {
processed: number;
total: number;
remaining: number;
currentTime: Date;
currentDate: string;
progress: number;
}
/** One run's cursor and interruptible controls; independent of trading, storage and reporting. */
export class BacktestPlayback {
private readonly controller = new AbortController();
private wake?: () => void;
private running = true;
private paused = false;
private processed = 0;
private total = 0;
private started = false;
constructor(
private currentTime: number,
private speed: number | null
) {
this.validateSpeed(speed);
}
private validateSpeed(speed: number | null): void {
if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) {
throw new Error('Backtest speed must be positive or null');
}
}
assertRunning(): void {
if (!this.running) {
throw new BacktestCancelledError();
}
this.controller.signal.throwIfAborted();
}
get signal(): AbortSignal {
return this.controller.signal;
}
/** Only race side-effect-free reads; late reads must never resume execution. */
async read<T>(load: () => Promise<T>): Promise<T> {
this.assertRunning();
const { signal } = this.controller;
signal.throwIfAborted();
let rejectAbort!: (reason: unknown) => void;
const aborted = new Promise<never>((_resolve, reject) => {
rejectAbort = reject;
});
const onAbort = () => rejectAbort(signal.reason);
signal.addEventListener('abort', onAbort, { once: true });
try {
const work = Promise.resolve().then(() => {
this.assertRunning();
return load();
});
return await Promise.race([work, aborted]);
} finally {
signal.removeEventListener('abort', onAbort);
}
}
private async wait(ms?: number): Promise<void> {
this.assertRunning();
await new Promise<void>(resolve => {
let timer: ReturnType<typeof setTimeout> | undefined;
const done = () => {
if (timer !== undefined) {
clearTimeout(timer);
}
this.wake = undefined;
resolve();
};
this.wake = done;
if (ms !== undefined) {
timer = setTimeout(done, ms);
}
});
this.assertRunning();
}
private async ready(): Promise<void> {
this.assertRunning();
while (this.paused) {
await this.wait();
}
}
async process<T>(
events: readonly T[],
timestamp: (event: T) => number,
consume: (event: T) => Promise<void>,
progress: (value: PlaybackProgress) => void
): Promise<void> {
this.assertRunning();
if (this.started) {
throw new Error('Backtest playback has already started');
}
this.started = true;
this.total = events.length;
// Frozen inputs are already validated and ordered. A cursor avoids copying and shifting history.
for (const event of events) {
await this.ready();
if (this.speed !== null) {
await this.wait(1000 / this.speed);
}
await this.ready();
this.currentTime = timestamp(event);
await consume(event);
this.processed++;
this.assertRunning();
const interval = this.speed === null ? 100 : Math.max(1, Math.floor(10 / this.speed));
if (this.processed < this.total && this.processed % interval === 0) {
progress(this.progress());
}
// Let cancellation, lease heartbeats and other accounts run even at unlimited speed.
if (this.speed === null && this.processed % 100 === 0) {
await this.wait(0);
}
}
this.assertRunning();
progress(this.progress());
this.assertRunning();
}
private progress(): PlaybackProgress {
return {
processed: this.processed,
total: this.total,
remaining: this.total - this.processed,
currentTime: new Date(this.currentTime),
currentDate: new Date(this.currentTime).toISOString(),
progress:
this.total > 0
? this.processed === this.total
? 100
: Math.min(99, Math.round((this.processed / this.total) * 100))
: 0,
};
}
pause(): void {
if (!this.running) {
return;
}
this.paused = true;
this.wake?.();
}
resume(): void {
this.paused = false;
this.wake?.();
}
stop(): void {
this.controller.abort(new BacktestCancelledError());
this.paused = false;
this.wake?.();
}
finish(): void {
this.running = false;
this.paused = false;
this.wake?.();
}
setSpeed(speed: number | null): void {
this.validateSpeed(speed);
this.speed = speed;
this.wake?.();
}
getStatus() {
return {
isRunning: this.running,
isPaused: this.paused,
progress: this.progress().progress,
currentTime: this.currentTime,
};
}
}

View file

@ -1,230 +0,0 @@
import { at, defined } from '@stock-bot/invariants';
import type { HistoricalDataset } from '@stock-bot/types';
import { PerformanceAnalyzer, type PerformanceMetrics } from '../analytics/PerformanceAnalyzer';
import type { BacktestConfig } from '../types';
import type { ClosedTrade } from './native-result';
import { formatReport, type ReportExport } from './report-format';
import type { BacktestResult, OHLCBar } from './typescript-result';
/** Run-local observations and a detached completed report; never reads services or financial state. */
export class BacktestReport {
private readonly equityCurve: { timestamp: number; value: number }[];
private performanceAnalyzer?: PerformanceAnalyzer;
private snapshot?: ReportExport;
private readonly config: BacktestConfig;
constructor(
config: BacktestConfig,
private readonly backtestId: string
) {
this.config = structuredClone(config);
const start = Date.parse(config.startDate);
this.equityCurve = [{ timestamp: start, value: config.initialCapital }];
this.performanceAnalyzer = new PerformanceAnalyzer(config.initialCapital);
this.performanceAnalyzer.addEquityPoint(new Date(start), config.initialCapital);
}
record(timestamp: number, equity: number): void {
if (this.snapshot) {
throw new Error('Backtest report is already finalized');
}
if (!Number.isFinite(timestamp) || !Number.isFinite(equity)) {
throw new Error('Invalid backtest equity observation');
}
const last = defined(this.equityCurve[this.equityCurve.length - 1]);
if (timestamp < last.timestamp) {
throw new Error('Out-of-order backtest equity observation');
}
defined(this.performanceAnalyzer).addEquityPoint(new Date(timestamp), equity);
if (last.timestamp === timestamp) {
last.value = equity;
} else {
this.equityCurve.push({ timestamp, value: equity });
}
}
complete(
dataset: HistoricalDataset,
trades: ClosedTrade[],
finalPositions: BacktestResult['positions'],
dataQuality: unknown,
completedAt = new Date().toISOString()
): BacktestResult {
if (this.snapshot) {
throw new Error('Backtest report is already finalized');
}
const closedTrades = structuredClone(trades);
const performance = this.calculatePerformance(closedTrades);
const analysis = defined(this.performanceAnalyzer).getAnalysis();
const result: BacktestResult = {
// Identification
backtestId: this.backtestId,
status: 'completed' as const,
completedAt,
// Configuration used
config: {
name: this.config.name || 'Backtest',
strategy: this.config.strategy,
symbols: this.config.symbols,
startDate: this.config.startDate,
endDate: this.config.endDate,
initialCapital: this.config.initialCapital,
commission: this.config.commission ?? 0.001,
slippage: this.config.slippage ?? 0.0001,
dataFrequency: this.config.dataFrequency || '1d',
},
// Performance metrics (frontend-ready)
metrics: {
totalReturn: performance.totalReturn,
sharpeRatio: performance.sharpeRatio,
maxDrawdown: performance.maxDrawdown,
winRate: performance.winRate,
totalTrades: performance.totalTrades,
profitFactor: performance.profitFactor,
profitableTrades: Math.round((performance.totalTrades * performance.winRate) / 100),
avgWin: performance.avgWin || 0,
avgLoss: performance.avgLoss || 0,
expectancy: performance.expectancy || 0,
calmarRatio: performance.calmarRatio,
sortinoRatio: performance.sortinoRatio,
annualizedReturn: performance.annualizedReturn,
cagr: performance.cagr,
},
// Chart data (frontend-ready format)
equity: this.equityCurve.map(point => ({
date: new Date(point.timestamp).toISOString(),
value: point.value,
})),
// OHLC data for charts
ohlcData: this.getOHLCData(dataset),
// Trade history (frontend-ready)
trades: closedTrades.map(trade => ({
id: trade.id,
symbol: trade.symbol,
entryDate: trade.entry_time,
exitDate: trade.exit_time,
entryPrice: trade.entry_price,
exitPrice: trade.exit_price,
quantity: trade.quantity,
side: trade.side === 'Buy' ? 'buy' : 'sell',
pnl: trade.pnl,
pnlPercent: trade.pnl_percent,
commission: trade.commission,
duration: trade.duration_ms,
})),
// Final positions
positions: finalPositions.map(pos => ({
symbol: pos.symbol,
quantity: pos.quantity,
averagePrice: pos.averagePrice,
currentPrice: pos.currentPrice || pos.averagePrice,
unrealizedPnl: pos.unrealizedPnl || 0,
realizedPnl: pos.realizedPnl || 0,
})),
// Additional analytics
analytics: {
drawdownSeries: analysis.equity.underwater.map(point => ({
...point,
value: point.value * 100,
})),
dailyReturns: analysis.equity.dailyReturns.map(value => value * 100),
monthlyReturns: Object.fromEntries(
Object.entries(analysis.equity.monthlyReturns).map(([month, value]) => [
month,
value * 100,
])
),
exposureTime: this.calculateExposureTime(closedTrades),
riskMetrics: {
volatility: analysis.risk.volatility,
downsideDeviation: analysis.risk.downsideDeviation,
var95: analysis.risk.var95,
var99: analysis.risk.var99,
cvar95: analysis.risk.cvar95,
maxConsecutiveLosses: analysis.trade.maxConsecutiveLosses,
},
},
};
this.snapshot = structuredClone({
summary: performance,
trades: closedTrades,
equityCurve: this.equityCurve,
drawdowns: result.analytics.drawdownSeries,
dataQuality,
performanceReport: defined(this.performanceAnalyzer).exportReport(performance),
});
// The completed snapshot is sufficient for export; do not retain the analysis input twice.
this.equityCurve.length = 0;
this.performanceAnalyzer = undefined;
return structuredClone(result);
}
export(format: 'json' | 'csv' | 'html' = 'json'): string {
if (!this.snapshot) {
throw new Error('No completed backtest report is available');
}
return formatReport(this.snapshot, format);
}
private calculatePerformance(closedTrades: ClosedTrade[] = []): PerformanceMetrics {
const analyzer = defined(this.performanceAnalyzer);
// Import each closed trade once, when the completed snapshot is built.
closedTrades.forEach(trade => {
analyzer.addTrade({
entryTime: new Date(trade.entry_time),
exitTime: new Date(trade.exit_time),
symbol: trade.symbol,
side: trade.side === 'Buy' ? 'long' : 'short',
entryPrice: trade.entry_price,
exitPrice: trade.exit_price,
quantity: trade.quantity,
commission: trade.commission || 0,
pnl: trade.pnl || 0,
returnPct: trade.pnl_percent || 0,
holdingPeriod: trade.duration_ms / 60000, // Convert to minutes
mae: 0, // Not tracked yet
mfe: 0, // Not tracked yet
});
});
return analyzer.analyze();
}
private calculateExposureTime(closedTrades: ClosedTrade[] = []): number {
if (closedTrades.length === 0) {
return 0;
}
let totalExposureTime = 0;
for (const trade of closedTrades) {
totalExposureTime += trade.duration_ms || 0;
}
// Use equity curve to determine actual trading period
const startTime = this.equityCurve.length > 0 ? at(this.equityCurve, 0).timestamp : 0;
const endTime =
this.equityCurve.length > 0 ? at(this.equityCurve, this.equityCurve.length - 1).timestamp : 0;
const totalTime = endTime - startTime;
return totalTime > 0 ? (totalExposureTime / totalTime) * 100 : 0;
}
private getOHLCData(dataset: HistoricalDataset): Record<string, OHLCBar[]> {
const grouped: Record<string, OHLCBar[]> = Object.fromEntries(
this.config.symbols.map(symbol => [symbol, []])
);
for (const bar of dataset.bars) {
const { timestamp, open, high, low, close, volume } = bar;
defined(grouped[bar.symbol]).push({ timestamp, open, high, low, close, volume });
}
return grouped;
}
}

View file

@ -1,423 +0,0 @@
import { getLogger } from '@stock-bot/logger';
import { at } from '@stock-bot/invariants';
import {
type Bar,
type MarketData,
type OrderBookSnapshot,
type PriceLevel,
type Quote,
type Trade,
} from '../types';
import { type MarketMicrostructure } from '../types/MarketMicrostructure';
const _logger = getLogger('MarketSimulator');
export interface SimulationConfig {
useHistoricalSpreads: boolean;
modelHiddenLiquidity: boolean;
includeDarkPools: boolean;
latencyMs: number;
rebateRate: number;
takeFeeRate: number;
}
export interface LiquidityProfile {
visibleLiquidity: number;
hiddenLiquidity: number;
darkPoolLiquidity: number;
totalLiquidity: number;
}
export class MarketSimulator {
private orderBooks: Map<string, OrderBookSnapshot> = new Map();
private microstructures: Map<string, MarketMicrostructure> = new Map();
private liquidityProfiles: Map<string, LiquidityProfile> = new Map();
private lastTrades: Map<string, Trade> = new Map();
private config: SimulationConfig;
private randomState = 1;
resetWithSeed(seed: number): void {
this.randomState = seed >>> 0;
this.orderBooks.clear();
this.microstructures.clear();
this.liquidityProfiles.clear();
this.lastTrades.clear();
}
private random(): number {
this.randomState = (Math.imul(this.randomState, 1664525) + 1013904223) >>> 0;
return this.randomState / 4294967296;
}
constructor(config: Partial<SimulationConfig> = {}) {
this.config = {
useHistoricalSpreads: true,
modelHiddenLiquidity: true,
includeDarkPools: true,
latencyMs: 1,
rebateRate: -0.0002, // 2 bps rebate for providing liquidity
takeFeeRate: 0.0003, // 3 bps fee for taking liquidity
...config,
};
}
setMicrostructure(symbol: string, microstructure: MarketMicrostructure): void {
this.microstructures.set(symbol, microstructure);
this.updateLiquidityProfile(symbol);
}
processMarketData(data: MarketData): OrderBookSnapshot | null {
const { symbol } = this.getSymbolFromData(data);
switch (data.type) {
case 'quote':
return this.updateFromQuote(symbol, data.data);
case 'trade':
return this.updateFromTrade(symbol, data.data);
case 'bar':
return this.reconstructFromBar(symbol, data.data);
default:
return null;
}
}
private updateFromQuote(symbol: string, quote: Quote): OrderBookSnapshot {
let orderbook = this.orderBooks.get(symbol);
const microstructure = this.microstructures.get(symbol);
if (!orderbook || !microstructure) {
// Create new orderbook
orderbook = this.createOrderBook(symbol, quote, microstructure);
} else {
// Update existing orderbook
orderbook = this.updateOrderBook(orderbook, quote, microstructure);
}
this.orderBooks.set(symbol, orderbook);
return orderbook;
}
private updateFromTrade(symbol: string, trade: Trade): OrderBookSnapshot | null {
const orderbook = this.orderBooks.get(symbol);
if (!orderbook) {
return null;
}
// Update last trade
this.lastTrades.set(symbol, trade);
// Adjust orderbook based on trade
// Large trades likely consumed liquidity
const impactFactor = Math.min(trade.size / 1000, 0.1); // Max 10% impact
if (trade.side === 'buy') {
// Buy trade consumed ask liquidity
orderbook.asks = orderbook.asks.map((level, i) => ({
...level,
size: level.size * (1 - impactFactor * Math.exp(-i * 0.5)),
}));
} else {
// Sell trade consumed bid liquidity
orderbook.bids = orderbook.bids.map((level, i) => ({
...level,
size: level.size * (1 - impactFactor * Math.exp(-i * 0.5)),
}));
}
return orderbook;
}
private reconstructFromBar(symbol: string, bar: Bar): OrderBookSnapshot {
const microstructure =
this.microstructures.get(symbol) || this.createDefaultMicrostructure(symbol);
// Estimate spread from high-low range
const hlSpread = (bar.high - bar.low) / bar.close;
const estimatedSpreadBps = Math.max(
microstructure.avgSpreadBps,
hlSpread * 10000 * 0.1 // 10% of HL range as spread estimate
);
// Create synthetic quote
const midPrice = bar.vwap || (bar.high + bar.low + bar.close) / 3;
const halfSpread = (midPrice * estimatedSpreadBps) / 20000;
const quote: Quote = {
symbol,
timestamp: bar.timestamp,
bid: midPrice - halfSpread,
ask: midPrice + halfSpread,
bidSize: bar.volume / 100, // Rough estimate
askSize: bar.volume / 100,
};
return this.createOrderBook(symbol, quote, microstructure);
}
private createOrderBook(
symbol: string,
topQuote: Quote,
microstructure?: MarketMicrostructure
): OrderBookSnapshot {
const micro = microstructure || this.createDefaultMicrostructure(symbol);
const levels = 10;
const bids: PriceLevel[] = [];
const asks: PriceLevel[] = [];
// Model order book depth
for (let i = 0; i < levels; i++) {
const depthFactor = Math.exp(-i * 0.3); // Exponential decay
const _spreadMultiplier = 1 + i * 0.1; // Wider spread at deeper levels
// Hidden liquidity modeling
const hiddenRatio = this.config.modelHiddenLiquidity
? 1 + this.random() * 2 // 1-3x visible size hidden
: 1;
// Bid levels
const bidPrice = topQuote.bid - i * micro.tickSize;
const bidSize = topQuote.bidSize * depthFactor * (0.8 + this.random() * 0.4);
bids.push({
price: bidPrice,
size: Math.round(bidSize / micro.lotSize) * micro.lotSize,
orderCount: Math.max(1, Math.floor(bidSize / 100)),
hiddenSize: this.config.modelHiddenLiquidity ? bidSize * (hiddenRatio - 1) : undefined,
});
// Ask levels
const askPrice = topQuote.ask + i * micro.tickSize;
const askSize = topQuote.askSize * depthFactor * (0.8 + this.random() * 0.4);
asks.push({
price: askPrice,
size: Math.round(askSize / micro.lotSize) * micro.lotSize,
orderCount: Math.max(1, Math.floor(askSize / 100)),
hiddenSize: this.config.modelHiddenLiquidity ? askSize * (hiddenRatio - 1) : undefined,
});
}
return {
symbol,
timestamp: new Date(),
bids,
asks,
lastTrade: this.lastTrades.get(symbol),
};
}
private updateOrderBook(
current: OrderBookSnapshot,
quote: Quote,
microstructure?: MarketMicrostructure
): OrderBookSnapshot {
const _micro = microstructure || this.createDefaultMicrostructure(current.symbol);
// Update top of book
if (current.bids.length > 0) {
at(current.bids, 0).price = quote.bid;
at(current.bids, 0).size = quote.bidSize;
}
if (current.asks.length > 0) {
at(current.asks, 0).price = quote.ask;
at(current.asks, 0).size = quote.askSize;
}
// Adjust deeper levels based on spread changes
const oldSpread = at(current.asks, 0).price - at(current.bids, 0).price;
const newSpread = quote.ask - quote.bid;
const spreadRatio = newSpread / oldSpread;
// Update deeper levels
for (let i = 1; i < current.bids.length; i++) {
// Adjust sizes based on top of book changes
const sizeRatio = quote.bidSize / (at(current.bids, 0).size || quote.bidSize);
at(current.bids, i).size *= sizeRatio * (0.9 + this.random() * 0.2);
// Adjust prices to maintain relative spacing
const spacing = (at(current.bids, i - 1).price - at(current.bids, i).price) * spreadRatio;
at(current.bids, i).price = at(current.bids, i - 1).price - spacing;
}
for (let i = 1; i < current.asks.length; i++) {
const sizeRatio = quote.askSize / (at(current.asks, 0).size || quote.askSize);
at(current.asks, i).size *= sizeRatio * (0.9 + this.random() * 0.2);
const spacing = (at(current.asks, i).price - at(current.asks, i - 1).price) * spreadRatio;
at(current.asks, i).price = at(current.asks, i - 1).price + spacing;
}
return current;
}
simulateMarketImpact(
symbol: string,
side: 'buy' | 'sell',
orderSize: number,
orderType: 'market' | 'limit',
limitPrice?: number
): {
fills: Array<{ price: number; size: number; venue: string }>;
totalCost: number;
avgPrice: number;
marketImpact: number;
fees: number;
} {
const orderbook = this.orderBooks.get(symbol);
const microstructure = this.microstructures.get(symbol);
const liquidityProfile = this.liquidityProfiles.get(symbol);
if (!orderbook) {
throw new Error(`No orderbook available for ${symbol}`);
}
const fills: Array<{ price: number; size: number; venue: string }> = [];
let remainingSize = orderSize;
let totalCost = 0;
let fees = 0;
// Get relevant price levels
const levels = side === 'buy' ? orderbook.asks : orderbook.bids;
const multiplier = side === 'buy' ? 1 : -1;
// Simulate walking the book
for (const level of levels) {
if (remainingSize <= 0) {
break;
}
// Check limit price constraint
if (limitPrice !== undefined) {
if (side === 'buy' && level.price > limitPrice) {
break;
}
if (side === 'sell' && level.price < limitPrice) {
break;
}
}
// Calculate available liquidity including hidden
let availableSize = level.size;
if (level.hiddenSize && this.config.modelHiddenLiquidity) {
availableSize += level.hiddenSize * this.random(); // Seeded hidden liquidity
}
const fillSize = Math.min(remainingSize, availableSize);
// Simulate latency - price might move
if (this.config.latencyMs > 0 && orderType === 'market') {
const priceMovement = microstructure
? (((this.random() - 0.5) * microstructure.avgSpreadBps) / 10000) * level.price
: 0;
level.price += priceMovement * multiplier;
}
fills.push({
price: level.price,
size: fillSize,
venue: 'primary',
});
totalCost += fillSize * level.price;
remainingSize -= fillSize;
// Calculate fees
if (orderType === 'market') {
fees += fillSize * level.price * this.config.takeFeeRate;
} else {
// Limit orders that provide liquidity get rebate
fees += fillSize * level.price * this.config.rebateRate;
}
}
// Dark pool execution for remaining size
if (remainingSize > 0 && this.config.includeDarkPools && liquidityProfile) {
const darkPoolPct = liquidityProfile.darkPoolLiquidity / liquidityProfile.totalLiquidity;
const darkPoolSize = remainingSize * darkPoolPct * this.random();
if (darkPoolSize > 0) {
const midPrice = (at(orderbook.bids, 0).price + at(orderbook.asks, 0).price) / 2;
fills.push({
price: midPrice,
size: darkPoolSize,
venue: 'dark',
});
totalCost += darkPoolSize * midPrice;
remainingSize -= darkPoolSize;
// Dark pools typically have lower fees
fees += darkPoolSize * midPrice * 0.0001;
}
}
// Calculate results
const filledSize = orderSize - remainingSize;
const avgPrice = filledSize > 0 ? totalCost / filledSize : 0;
// Calculate market impact
const initialMid = (at(orderbook.bids, 0).price + at(orderbook.asks, 0).price) / 2;
const marketImpact =
filledSize > 0
? (Math.abs(avgPrice - initialMid) / initialMid) * 10000 // in bps
: 0;
return {
fills,
totalCost,
avgPrice,
marketImpact,
fees,
};
}
private updateLiquidityProfile(symbol: string): void {
const microstructure = this.microstructures.get(symbol);
if (!microstructure) {
return;
}
// Estimate liquidity distribution
const visiblePct = 0.3; // 30% visible
const hiddenPct = 0.5; // 50% hidden
const darkPct = 0.2; // 20% dark
const totalDailyLiquidity = microstructure.dailyVolume;
this.liquidityProfiles.set(symbol, {
visibleLiquidity: totalDailyLiquidity * visiblePct,
hiddenLiquidity: totalDailyLiquidity * hiddenPct,
darkPoolLiquidity: totalDailyLiquidity * darkPct,
totalLiquidity: totalDailyLiquidity,
});
}
private createDefaultMicrostructure(symbol: string): MarketMicrostructure {
return {
symbol,
avgSpreadBps: 5,
dailyVolume: 1000000,
avgTradeSize: 100,
volatility: 0.02,
tickSize: 0.01,
lotSize: 1,
intradayVolumeProfile: new Array(24).fill(1 / 24),
};
}
private getSymbolFromData(data: MarketData): { symbol: string } {
return { symbol: data.data.symbol };
}
getOrderBook(symbol: string): OrderBookSnapshot | undefined {
return this.orderBooks.get(symbol);
}
getLiquidityProfile(symbol: string): LiquidityProfile | undefined {
return this.liquidityProfiles.get(symbol);
}
reset(): void {
this.orderBooks.clear();
this.lastTrades.clear();
}
}

View file

@ -9,13 +9,13 @@ import {
replayConfigSchema,
replayIdentitySchema,
replayResultFormatSchema,
} from '../contracts/native-replay';
} from '@stock-bot/stock-config/canonical-replay';
import {
parseStrategyReplayResult,
strategyReplayRequestSchema,
} from '../contracts/strategy-replay';
import { removeCandidateContainer } from './candidate-sandbox';
import { canonicalWorkerUrl } from './canonical-build';
import { canonicalWorkerUrl } from '@stock-bot/trading-runtime/canonical-build';
import {
nativeWorkerMessageSchema,
nativeWorkerRequestSchema,

View file

@ -1,5 +1,5 @@
/** This entrypoint runs ONLY inside the restricted image; never the API/native supervisor. */
import { sameIdentity } from '../contracts/native-replay';
import { sameIdentity } from '@stock-bot/stock-config/canonical-replay';
import { importRetainedProgram } from '../strategies/retained-program';
import { StrategyController } from '../strategies/strategy-controller';
import { freeze } from '../strategies/strategy-decision';

View file

@ -6,7 +6,7 @@ import {
retainedProgramSelectionSchema,
} from '@stock-bot/stock-config/candidate-execution';
import { parseFinancialStrategyDecision } from '@stock-bot/types';
import { replayIdentitySchema, stepSchema, submissionSchema } from '../contracts/native-replay';
import { replayIdentitySchema, stepSchema, submissionSchema } from '@stock-bot/stock-config/canonical-replay';
const base = {
version: z.literal(1),

View file

@ -17,7 +17,7 @@ import {
verifyCandidateExecution,
} from '@stock-bot/trading-runtime/candidate-environment';
import { parseFinancialStrategyDecision } from '@stock-bot/types';
import type { ReplaySubmissionOutcome } from '../contracts/native-replay';
import type { ReplaySubmissionOutcome } from '@stock-bot/stock-config/canonical-replay';
import {
candidateResponseSchema,
readCandidateFrames,

View file

@ -1,2 +0,0 @@
/** Shared read-only artifact inspection. */
export * from '@stock-bot/trading-runtime/canonical-build';

View file

@ -1,2 +0,0 @@
/** Compatibility entrypoint for the shared, purely statistical report builder. */
export * from '@stock-bot/research/results';

View file

@ -4,10 +4,6 @@ import type {
CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { HistoricalDatasetV2 } from '@stock-bot/types';
import type { DatasetResolver } from '../data/historical-dataset';
import type { BacktestConfig } from '../types';
import type { NativeBacktestResult } from './native-result';
import type { BacktestResult } from './typescript-result';
/** Capabilities required by the canonical durable runner. No provider loading or playback. */
export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'> {
@ -26,18 +22,6 @@ export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'
shutdown(): Promise<void>;
}
/** Retained algorithm/playback examples only; cannot satisfy the durable runner contract. */
export interface LegacyBacktestExecutionEngine
extends Pick<BacktestExecutionEngine, 'on' | 'off' | 'stopBacktest' | 'getStatus' | 'shutdown'> {
runBacktest(
config: BacktestConfig,
dataset?: DatasetResolver
): Promise<BacktestResult | NativeBacktestResult>;
pauseBacktest(): Promise<void>;
resumeBacktest(): Promise<void>;
setSpeedMultiplier(speed: number | null): void;
}
/** Cancellation has no result when a native worker is forcibly stopped. */
export class BacktestCancelledError extends Error {
constructor() {

View file

@ -32,7 +32,7 @@ import {
type ReplayStep,
type ReplaySubmissionOutcome,
type ReplayTraceRequest,
} from '../contracts/native-replay';
} from '@stock-bot/stock-config/canonical-replay';
import { validateDatasetV2 } from '../data/historical-dataset-v2';
export type {
@ -47,7 +47,7 @@ export type {
DecisionContext,
PublishedObservation,
ReplayTraceRequest,
} from '../contracts/native-replay';
} from '@stock-bot/stock-config/canonical-replay';
/** Expand Number's exact shortest lexical representation, never round toFixed.
* D01 already owns numeric data precision; >8 decimals cannot enter the ledger. */

View file

@ -1,12 +0,0 @@
import type { BacktestConfig } from '../types';
import { backtestStrategies } from './strategy-plan';
/** Resolve and validate before fetching data, and validate again in the isolated worker. */
export function resolveNativeStrategies(config: BacktestConfig) {
return backtestStrategies(config, 'native').map(({ name, kind, parameters, index }) => {
if (!kind) {
throw new Error('Unknown native strategy: ' + name);
}
return { strategy: kind, name, id: 'backtest-strategy-' + index, parameters };
});
}

View file

@ -12,10 +12,10 @@ import {
} from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import type { CanonicalBacktestAnalytics } from '@stock-bot/types';
import { replayTraceSchema } from '../contracts/native-replay';
import type { ReplayReportResult } from '../contracts/native-replay';
import { replayTraceSchema } from '@stock-bot/stock-config/canonical-replay';
import type { ReplayReportResult } from '@stock-bot/stock-config/canonical-replay';
import { strategyReplayRequestSchema } from '../contracts/strategy-replay';
import { buildCanonicalBacktestReport } from './canonical-result';
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
const finite = z.number().finite();
export const retainedStrategyRequestSchema = z

View file

@ -8,8 +8,8 @@ import {
verifyRetainedProgramPackage,
} from '../strategies/retained-program';
import { IsolatedCandidateController } from './candidate-sandbox';
import { verifyCanonicalWorkerBuild } from './canonical-build';
import { buildCanonicalBacktestReport } from './canonical-result';
import { verifyCanonicalWorkerBuild } from '@stock-bot/trading-runtime/canonical-build';
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
import {
executeReplayTrace,
NativeReplaySession,

Some files were not shown because too many files have changed in this diff Show more