Skill: tangweigang-jpg/cuemacro-finmarket (version 0.3.3)

--- name: cuemacro-finmarket description: |- 金融市场回测框架，支持FX G10货币对技术指标策略回测、ArcticDB高频tick数据本地与S3云端存储、Quandl等数据源的市场数据获取与缓存。 license: Proprietary. See LICENSE.txt in project root. compatibility: Designed for Doramagic-host ecosystem (Claude Code / openclaw / Cursor). Requires Python 3.12+ with uv package manager. metadata: version: "v6.1" blueprint_id: "finance-bp-108" compiled_at: "2026-04-22T13:00:51.768652+00:00" capability_markets: "multi-market" capability_activities: "portfolio-analytics" sop_version: "crystal-compilation-v6.1" --- # Cuemacro 市场工具 (cuemacro-finmarket) > 金融市场回测框架，支持FX G10货币对技术指标策略回测、ArcticDB高频tick数据本地与S3云端存储、Quandl等数据源的市场数据获取与缓存。 ## Pipeline `data_collection -> data_storage -> factor_computation -> target_selection -> trading_execution -> visualization` ## Top Use Cases (4 total) ### ArcticDB Tick Data Storage (`UC-101`) Provides persistent storage for high-frequency tick market data using ArcticDB, supporting both local LMDB and S3 cloud storage backends for efficient **Triggers**: arcticdb, tick data storage, time series database ### Market Data Fetching from Vendors (`UC-103`) Fetches economic and financial market data from external vendors like Quandl, demonstrating how to request and cache market data with specific fields **Triggers**: market data, quandl, fetch data ### S3 Cloud Storage for Tick Data (`UC-104`) Demonstrates writing and reading tick market data to/from AWS S3 cloud storage using Parquet format for efficient compression and retrieval of histori **Triggers**: s3 storage, aws, parquet For all **4** use cases, see [references/USE_CASES.md](references/USE_CASES.md). **Execute trigger**: `When user intent matches intent_router.uc_entries[].positive_terms AND user uses action verb (run/execute/跑/执行/backtest/fetch/collect)` ## What I'll Ask You - Target market: A-share (default), HK, or crypto? (US stocks in ZVT are half-baked — stockus_nasdaq_AAPL exists but coverage is thin) - Data source / provider: eastmoney (free, no account), joinquant (account+paid), baostock (free, good history), akshare, or qmt (broker)? - Strategy type: MACD golden-cross, MA crossover, volume breakout, fundamental screen, or custom factor? - Time range: start_timestamp and end_timestamp for backtest period - Target entity IDs: specific stocks (stock_sh_600000) or index components (SZ1000)? ## Semantic Locks (Fatal) | ID | Rule | On Violation | |---|---|---| | `SL-01` | Execute sell orders before buy orders in every trading cycle | halt | | `SL-02` | Trading signals MUST use next-bar execution (no look-ahead) | halt | | `SL-03` | Entity IDs MUST follow format entity_type_exchange_code | halt | | `SL-04` | DataFrame index MUST be MultiIndex (entity_id, timestamp) | halt | | `SL-05` | TradingSignal MUST have EXACTLY ONE of: position_pct, order_money, order_amount | halt | | `SL-06` | filter_result column semantics: True=BUY, False=SELL, None/NaN=NO ACTION | halt | | `SL-07` | Transformer MUST run BEFORE Accumulator in factor pipeline | halt | | `SL-08` | MACD parameters locked: fast=12, slow=26, signal=9 | halt | Full lock definitions: [references/LOCKS.md](references/LOCKS.md) ## Top Anti-Patterns (14 total) - **`AP-PORTFOLIO-ANALYTICS-001`**: Division by zero in price ratio calculations corrupts rebalancing - **`AP-PORTFOLIO-ANALYTICS-002`**: Look-ahead bias from unshifted signal generation and position calculations - **`AP-PORTFOLIO-ANALYTICS-003`**: Non-positive-semidefinite covariance matrix breaks CVXPY optimization All 14 anti-patterns: [references/ANTI_PATTERNS.md](references/ANTI_PATTERNS.md) ## Evidence Quality Notice > [QUALITY NOTICE] This crystal was compiled from blueprint finance-bp-108. Evidence verify ratio = 32.0% and audit fail total = 18. Generated results may have uncaptured requirement gaps. Verify critical decisions against source files (LATEST.yaml / LATEST.jsonl). ## Reference Files | File | Contents | When to Load | |---|---|---| | [references/seed.yaml](references/seed.yaml) | V6+ 全量权威 (source-of-truth) | 有行为/决策争议时必读 | | [references/ANTI_PATTERNS.md](references/ANTI_PATTERNS.md) | 14 条跨项目反模式 | 开始实现前 | | [references/WISDOM.md](references/WISDOM.md) | 跨项目精华借鉴 | 架构决策时 | | [references/CONSTRAINTS.md](references/CONSTRAINTS.md) | domain + fatal 约束 | 规则冲突时 | | [references/USE_CASES.md](references/USE_CASES.md) | 全量 KUC-* 业务场景 | 需要完整示例时 | | [references/LOCKS.md](references/LOCKS.md) | SL-* + preconditions + hints | 生成回测/交易代码前 | | [references/COMPONENTS.md](references/COMPONENTS.md) | AST 组件地图（按 module 拆分）| 查 API 时 | --- *Compiled by Doramagic crystal-compilation-v6.1 from `finance-bp-108` blueprint at 2026-04-22T13:00:51.768652+00:00.* *See [human_summary.md](human_summary.md) for non-technical overview.*

path: human_summary.md
content: # Human Summary

> I help you build quant strategies on A-share with ZVT — from data fetch to backtest, one flow. Just tell me what you want; I'll write the code, you don't have to dig docs. (Heads up: ZVT natively supports A-share, HK, and crypto. US stocks — stockus_nasdaq_AAPL — are half-baked; don't bother for serious work.)

## What I Can Do

- **tagline**: I help you build quant strategies on A-share with ZVT — from data fetch to backtest, one flow. Just tell me what you want; I'll write the code, you don't have to dig docs. (Heads up: ZVT natively supports A-share, HK, and crypto. US stocks — stockus_nasdaq_AAPL — are half-baked; don't bother for serious work.)
- **use_cases**: ['Market Data Fetching from Vendors', 'FX G10 Cross Backtesting', 'ArcticDB Tick Data Storage', 'A-share MACD daily golden-cross backtest with hfq price adjustment from eastmoney', 'End-to-end ZVT pipeline: FinanceRecorder + GoodCompanyFactor + StockTrader', 'Multi-factor strategy with TargetSelector (AND mode) combining MACD + volume breakout', 'Index composition data collection (SZ1000, SZ2000) with EM recorder']

## What I Ask You

- Target market: A-share (default), HK, or crypto? (US stocks in ZVT are half-baked — stockus_nasdaq_AAPL exists but coverage is thin)
- Data source / provider: eastmoney (free, no account), joinquant (account+paid), baostock (free, good history), akshare, or qmt (broker)?
- Strategy type: MACD golden-cross, MA crossover, volume breakout, fundamental screen, or custom factor?
- Time range: start_timestamp and end_timestamp for backtest period
- Target entity IDs: specific stocks (stock_sh_600000) or index components (SZ1000)?


path: references/ANTI_PATTERNS.md
content: # Anti-Patterns (Cross-Project)

Total: **14**

## finance-bp-066--wealthbot (2)

### `AP-PORTFOLIO-ANALYTICS-001` — Division by zero in price ratio calculations corrupts rebalancing <sub>(high)</sub>

When calculating price_diff using current_price divided by old_price without validating old_price is non-zero, the result is NaN or INF. This corrupts portfolio rebalancing calculations in wealthbot, causing incorrect buy/sell decisions based on invalid prices_diff values. The same issue appears in getPricesDiff() where divide-by-zero when old_price equals zero produces NaN/infinity that propagates to all subsequent trade decisions.

### `AP-PORTFOLIO-ANALYTICS-004` — Incorrect portfolio value tracking destroys time-series integrity <sub>(high)</sub>

Updating existing ClientPortfolioValue records instead of creating new ones destroys the time-series integrity needed for billing calculations and historical reconciliation. This creates data corruption where billing calculations and historical reporting against custodian records will fail to match. Portfolio value records must be linked to parent ClientPortfolio via proper relationships to avoid orphaned records.

## finance-bp-068--xalpha (1)

### `AP-PORTFOLIO-ANALYTICS-006` — FIFO sell order violation corrupts cost basis and XIRR <sub>(high)</sub>

Processing positions out of chronological order in FIFO sell operations causes incorrect cost basis assignment, leading to inaccurate realized gains/losses and wrong XIRR calculation. Chinese funds have tiered redemption fees based on holding periods, so FIFO violations result in incorrect holding period calculation and wrong redemption fee being applied, causing direct financial loss.

## finance-bp-068--xalpha, finance-bp-093--PyPortfolioOpt, finance-bp-117--Riskfolio-Lib (1)

### `AP-PORTFOLIO-ANALYTICS-010` — Missing DataFrame schema validation causes KeyError propagation <sub>(medium)</sub>

Passing non-DataFrame objects (numpy arrays, lists) where DataFrame is expected causes NameError, AttributeError, or TypeError in downstream pandas operations. xalpha's fundinfo.price requires specific columns (date, netvalue, totvalue, comment), PyPortfolioOpt and Riskfolio-Lib require index alignment between expected returns and covariance matrix. Missing columns cause backtest calculations to fail with NaN values or KeyError.

## finance-bp-082--stock-screener (1)

### `AP-PORTFOLIO-ANALYTICS-007` — Score validation bypass allows invalid composite calculations <sub>(medium)</sub>

Accepting scores outside the 0-100 range in screener results corrupts ranking and rating logic, causing unpredictable screening results that violate the fundamental score contract. When combined with division-by-zero guards that return 0.0 for empty screener lists, this creates unpredictable behavior where invalid scores produce wrong composite calculations and incorrect Strong Buy/Buy/Watch/Pass ratings.

## finance-bp-093--PyPortfolioOpt (1)

### `AP-PORTFOLIO-ANALYTICS-008` — Convex optimization constraints violate DCP rules <sub>(high)</sub>

Using non-convex objectives or DCP-violating expressions in CVXPY optimization causes DCPError, completely preventing portfolio optimization from running. Similarly, providing non-callable constraints or invalid bounds formats (not matching n_assets length) causes TypeError. Feasibility violations like setting target_volatility below global minimum or target_return above maximum achievable return make problems infeasible.

## finance-bp-093--PyPortfolioOpt, finance-bp-117--Riskfolio-Lib (1)

### `AP-PORTFOLIO-ANALYTICS-003` — Non-positive-semidefinite covariance matrix breaks CVXPY optimization <sub>(high)</sub>

Passing a non-positive-semidefinite covariance matrix to CVXPY optimization with assume_PSD=True produces incorrect results because the solver assumes validity without verification. This causes Cholesky decomposition to fail or produce garbage weights, preventing portfolio optimization from running entirely. Riskfolio-Lib and PyPortfolioOpt both require explicit PSD validation before optimization.

## finance-bp-106--pyfolio-reloaded (2)

### `AP-PORTFOLIO-ANALYTICS-005` — Allocation denominator excludes cash, corrupting portfolio composition <sub>(medium)</sub>

When computing allocation percentages excluding cash from the denominator, portfolio allocation percentages will not sum to 100%, misrepresenting the portfolio's actual composition. Additionally, concentration metrics become artificially skewed when including cash (a non-position asset), producing misleading diversification assessments that could lead to inappropriate risk management decisions.

### `AP-PORTFOLIO-ANALYTICS-009` — Transaction data corruption from missing columns and invalid dates <sub>(medium)</sub>

Extracting round trips from transactions DataFrame without validating required columns (amount, price, symbol) causes KeyError exceptions. When open_dt is not strictly less than close_dt, negative or zero duration values indicate data corruption causing incorrect holding period statistics. Similarly, non-normalized transaction timestamps cause intra-day trades to be incorrectly split across days.

## finance-bp-107--empyrical-reloaded (1)

### `AP-PORTFOLIO-ANALYTICS-011` — Wrong annualization factors distort cross-frequency metric comparison <sub>(high)</sub>

Applying incorrect annualization factors (wrong values for daily, weekly, monthly, quarterly, yearly frequencies) produces non-comparable metrics across different return frequencies, causing invalid strategy comparisons and misallocated capital. The Sharpe ratio formula must use correct annualization with sample standard deviation (ddof=1), otherwise producing misleading risk-adjusted return estimates.

## finance-bp-107--empyrical-reloaded, finance-bp-118--FinanceToolkit (1)

### `AP-PORTFOLIO-ANALYTICS-012` — Misaligned time series in alpha/beta calculation produces invalid factor analysis <sub>(high)</sub>

Passing returns and factor_returns to alpha_beta functions without verifying data alignment on index labels (pd.Series) or length equality (np.ndarray) produces incorrect alpha/beta values due to correlation computed between mismatched periods. Including benchmark ticker in the asset ticker list causes circular correlation producing meaningless beta values of approximately 1.0.

## finance-bp-108--finmarketpy (1)

### `AP-PORTFOLIO-ANALYTICS-013` — Forward-filling spot prices creates look-ahead bias in TRI construction <sub>(high)</sub>

Forward-filling spot prices creates look-ahead bias where future prices are used to calculate historical returns, invalidating all TRI-based backtest results. The total return index construction requires multiplicative cumulation using cumprod (not cumsum) with base value 100, as additive cumulation allows negative cumulative returns to break the index chain.

## finance-bp-108--finmarketpy, finance-bp-106--pyfolio-reloaded (1)

### `AP-PORTFOLIO-ANALYTICS-002` — Look-ahead bias from unshifted signal generation and position calculations <sub>(high)</sub>

Generating trading signals from current-period technical indicators (RSI, moving averages) without proper shift(-1) creates look-ahead bias, causing live trading returns to fall far below backtested results. Similarly, when estimating intraday positions from transactions without applying shift(1) to EOD positions, day-start positions are contaminated with end-of-day values, making results unrepresentative of actual trading.

## finance-bp-117--Riskfolio-Lib, finance-bp-093--PyPortfolioOpt (1)

### `AP-PORTFOLIO-ANALYTICS-014` — Unsupported solver selection breaks advanced risk calculations <sub>(medium)</sub>

Using solvers that don't support required cone programming (power cone, exponential cone) causes CVXPY to fail with SolverError, returning None and breaking risk calculations. CLARABEL, SCS, ECOS support power cone for RLVaR/RLDaR calculations, while CLARABEL/MOSEK/SCS/ECOS support exponential cone for EVaR calculations. Riskfolio-Lib and PyPortfolioOpt both require careful solver selection.


path: references/COMPONENTS.md
content: # Component Capability Map

**Project**: finance-bp-108--finmarketpy
**Scan date**: 2026-04-22
**Stats**: {'total_files': 6, 'total_classes': 33, 'total_functions': 0, 'total_stages': 6}

## Modules (6)

- [market_data_collection](components/market_data_collection.md): 4 classes
- [technical_indicator_&_signal_generation](components/technical_indicator_-_signal_generation.md): 5 classes
- [total_return_index_construction](components/total_return_index_construction.md): 6 classes
- [fx_volatility_surface_&_pricing](components/fx_volatility_surface_-_pricing.md): 6 classes
- [strategy_backtesting_engine](components/strategy_backtesting_engine.md): 7 classes
- [trade_analysis_&_reporting](components/trade_analysis_-_reporting.md): 5 classes


path: references/CONSTRAINTS.md
content: # Constraints

## preservation_manifest

```yaml
required_objects:
  business_decisions_count: 82
  fatal_constraints_count: 18
  non_fatal_constraints_count: 132
  use_cases_count: 4
  semantic_locks_count: 12
  preconditions_count: 4
  evidence_quality_rules_count: 2
  traceback_scenarios_count: 5

```


path: references/LOCKS.md
content: # Semantic Locks + Preconditions

## Semantic Locks (12)

### `SL-01` <sub>(on_violation: fatal)</sub>
Execute sell orders before buy orders in every trading cycle

### `SL-02` <sub>(on_violation: fatal)</sub>
Trading signals MUST use next-bar execution (no look-ahead)

### `SL-03` <sub>(on_violation: fatal)</sub>
Entity IDs MUST follow format entity_type_exchange_code

### `SL-04` <sub>(on_violation: fatal)</sub>
DataFrame index MUST be MultiIndex (entity_id, timestamp)

### `SL-05` <sub>(on_violation: fatal)</sub>
TradingSignal MUST have EXACTLY ONE of: position_pct, order_money, order_amount

### `SL-06` <sub>(on_violation: fatal)</sub>
filter_result column semantics: True=BUY, False=SELL, None/NaN=NO ACTION

### `SL-07` <sub>(on_violation: fatal)</sub>
Transformer MUST run BEFORE Accumulator in factor pipeline

### `SL-08` <sub>(on_violation: fatal)</sub>
MACD parameters locked: fast=12, slow=26, signal=9

### `SL-09` <sub>(on_violation: warning)</sub>
Default transaction costs: buy_cost=0.001, sell_cost=0.001, slippage=0.001

### `SL-10` <sub>(on_violation: fatal)</sub>
A-share equity trading is T+1 (no same-day close of buy positions)

### `SL-11` <sub>(on_violation: fatal)</sub>
Recorder subclass MUST define provider AND data_schema class attributes

### `SL-12` <sub>(on_violation: fatal)</sub>
Factor result_df MUST contain either 'filter_result' OR 'score_result' column

## Preconditions (4)

- **`PC-01`**: `python3 -c 'import zvt; print(zvt.__version__)'` → on_fail: Run: python3 -m pip install zvt then re-run: python3 -m zvt.init_dirs to initialize data directories
- **`PC-02`**: `python3 -c "from zvt.api.kdata import get_kdata; df = get_kdata(entity_ids=['stock_sh_600000'], limit=1); assert df is not None and len(df) > 0, 'No kdata found'"` → on_fail: Run recorder first: python3 -m zvt.recorders.em.em_stock_kdata_recorder --entity_ids stock_sh_600000 (replace with your target entity IDs)
- **`PC-03`**: `python3 -c "import os; from pathlib import Path; zvt_home = Path(os.environ.get('ZVT_HOME', Path.home() / '.zvt')); assert zvt_home.exists(), f'ZVT home not found: {zvt_home}'"` → on_fail: Run: python3 -m zvt.init_dirs
- **`PC-04`**: `python3 -c "import os, tempfile; from pathlib import Path; zvt_home = Path(os.environ.get('ZVT_HOME', Path.home() / '.zvt')); test_f = zvt_home / '.write_test'; test_f.touch(); test_f.unlink()"` → on_fail: Check directory permissions: chmod u+w ~/.zvt or set ZVT_HOME environment variable to a writable location


path: references/USE_CASES.md
content: # Known Use Cases (KUC)

Total: **4**

## `KUC-101`
**Source**: `finmarketpy_examples/finmarketpy_notebooks/arcticdb_example.ipynb`

Provides persistent storage for high-frequency tick market data using ArcticDB, supporting both local LMDB and S3 cloud storage backends for efficient time series data management.

## `KUC-102`
**Source**: `finmarketpy_examples/finmarketpy_notebooks/backtest_example.ipynb`

Enables historical backtesting of FX trading strategies using G10 currency pairs with technical indicator-based signal generation to evaluate strategy performance.

## `KUC-103`
**Source**: `finmarketpy_examples/finmarketpy_notebooks/market_data_example.ipynb`

Fetches economic and financial market data from external vendors like Quandl, demonstrating how to request and cache market data with specific fields and date ranges.

## `KUC-104`
**Source**: `finmarketpy_examples/finmarketpy_notebooks/s3_bucket_example.ipynb`

Demonstrates writing and reading tick market data to/from AWS S3 cloud storage using Parquet format for efficient compression and retrieval of historical FX tick data.


path: references/WISDOM.md
content: # Cross-Project Wisdom

Total: **10**

## `CW-PORTFOLIO-ANALYTICS-001` — Defensive zero-division guards with explicit handling
**From**: finance-bp-066--wealthbot, finance-bp-082--stock-screener, finance-bp-093--PyPortfolioOpt · **Applicable to**: portfolio-analytics

Always guard division operations with explicit zero-value checks before executing. In price ratio calculations, filter out securities where old_price is zero before calling getPricesDiff. In composite score calculations, guard against total_weight of zero and return 0.0 for empty input lists. This prevents NaN/infinity propagation that corrupts downstream calculations and crashes pipelines.

## `CW-PORTFOLIO-ANALYTICS-002` — Covariance matrix positive-semidefiniteness verification
**From**: finance-bp-093--PyPortfolioOpt, finance-bp-117--Riskfolio-Lib · **Applicable to**: portfolio-analytics

Always verify covariance matrix is positive-semidefinite before passing to CVXPY optimization. Apply eigenvalue clipping if violated, as non-PSD matrices cause Cholesky decomposition failures. Both PyPortfolioOpt and Riskfolio-Lib enforce this constraint to prevent optimizer from finding mathematically invalid solutions or crashing entirely.

## `CW-PORTFOLIO-ANALYTICS-003` — Geometric compounding for cumulative returns
**From**: finance-bp-068--xalpha, finance-bp-106--pyfolio-reloaded, finance-bp-107--empyrical-reloaded · **Applicable to**: portfolio-analytics

Compute cumulative returns using geometric compounding via cumprod(1 + returns), never arithmetic cumulation via cumsum. Arithmetic cumulative sum overstates gains and understates losses, causing cumulative returns to diverge significantly from actual portfolio performance over volatile periods. This principle applies to total return index construction and any cumulative performance calculation.

## `CW-PORTFOLIO-ANALYTICS-004` — Temporal shift enforcement to prevent look-ahead bias
**From**: finance-bp-108--finmarketpy, finance-bp-106--pyfolio-reloaded · **Applicable to**: portfolio-analytics

Enforce proper temporal shifting in signal generation and position calculations. Use shift(-1) for exit signals to prevent look-ahead bias, and shift(1) when estimating intraday positions from EOD data. Forward-fill carry data and backward-fill only old data gaps, never forward-fill spot prices. Violations cause live trading returns to diverge from backtested results.

## `CW-PORTFOLIO-ANALYTICS-005` — DCP-compliant convex optimization construction
**From**: finance-bp-093--PyPortfolioOpt, finance-bp-117--Riskfolio-Lib · **Applicable to**: portfolio-analytics

Use only DCP-compliant convex objectives and constraints in CVXPY. Provide constraints as callable functions accepting weight variables, use valid bounds formats matching n_assets length, and verify target parameters (volatility, return) are within feasible ranges. Non-convex or infeasible problems fail with DCPError or OptimizationError, preventing optimization entirely.

## `CW-PORTFOLIO-ANALYTICS-006` — Correct Sharpe ratio formula with risk-free rate subtraction
**From**: finance-bp-107--empyrical-reloaded, finance-bp-118--FinanceToolkit · **Applicable to**: portfolio-analytics

Calculate Sharpe ratio using (mean returns - risk_free) / std(returns) * sqrt(annualization) with sample standard deviation (ddof=1). Subtract risk-free rate from asset returns before dividing by volatility. Incorrect Sharpe ratio calculation produces misleading risk-adjusted return estimates, causing poor investment decisions based on faulty performance attribution.

## `CW-PORTFOLIO-ANALYTICS-007` — Immutable FIFO position tracking with chronological ordering
**From**: finance-bp-068--xalpha, finance-bp-066--wealthbot · **Applicable to**: portfolio-analytics

Maintain FIFO position tracking with strictly increasing date order for position entries. Use copy() function to create independent copies before mutating remtable to avoid side effects. Enforce chronological ordering in sell operations to ensure correct cost basis and holding period calculation, particularly important for funds with tiered fees by holding period.

## `CW-PORTFOLIO-ANALYTICS-008` — Validation at system boundaries with descriptive errors
**From**: finance-bp-082--stock-screener, finance-bp-093--PyPortfolioOpt, finance-bp-117--Riskfolio-Lib · **Applicable to**: portfolio-analytics

Enforce validation at system boundaries with descriptive error messages. Validate expected returns matches covariance matrix dimensions, score values are within [0, 100], confidence values within [0, 1], and required DataFrame columns are present. Invalid inputs should raise ValueError with descriptive messages listing valid options to prevent silent failures or corrupted calculations.

## `CW-PORTFOLIO-ANALYTICS-009` — Decimal rounding for monetary calculations
**From**: finance-bp-068--xalpha, finance-bp-107--empyrical-reloaded · **Applicable to**: portfolio-analytics

Use Decimal with explicit rounding (myround) for each monetary calculation to avoid floating-point errors that cause share miscalculation and incorrect cost basis. This prevents rounding errors from propagating to XIRR and portfolio valuation calculations. Direct floating-point operations in financial calculations accumulate errors that become material over many transactions.

## `CW-PORTFOLIO-ANALYTICS-010` — Cash flow sign convention enforcement
**From**: finance-bp-106--pyfolio-reloaded, finance-bp-068--xalpha · **Applicable to**: portfolio-analytics

Mark cash outflows as negative and cash inflows as positive in cftable. Incorrect cash flow signs cause NPV calculation to invert, producing negative returns for profitable trades and vice versa. Verify sum of round trip PnLs equals total realized transaction dollars to catch sign convention errors before they corrupt performance attribution.


path: references/components/fx_volatility_surface_-_pricing.md
content: # fx_volatility_surface_&_pricing (6 classes)

## `FXVolSurface.build_vol_surface`
`fx_volatility_surface_&_pricing/fxvolsurface-build-vol-surface.py:0`

## `FXOptionsPricer.price_option`
`fx_volatility_surface_&_pricing/fxoptionspricer-price-option.py:0`

## `FXForwardsPricer.price_odd_date`
`fx_volatility_surface_&_pricing/fxforwardspricer-price-odd-date.py:0`

## `VolStats.calculate`
`fx_volatility_surface_&_pricing/volstats-calculate.py:0`

## `vol_function_type`
`fx_volatility_surface_&_pricing/vol-function-type.py:0`

## `pricing_engine`
`fx_volatility_surface_&_pricing/pricing-engine.py:0`


path: references/components/market_data_collection.md
content: # market_data_collection (4 classes)

## `MarketDataRequest.__init__`
`market_data_collection/marketdatarequest-init.py:0`

## `Market.fetch_market_data`
`market_data_collection/market-fetch-market-data.py:0`

## `SpeedCache.generate_key`
`market_data_collection/speedcache-generate-key.py:0`

## `data_source`
`market_data_collection/data-source.py:0`


path: references/components/strategy_backtesting_engine.md
content: # strategy_backtesting_engine (7 classes)

## `Backtest.calculate_trading_PnL`
`strategy_backtesting_engine/backtest-calculate-trading-pnl.py:0`

## `TradingModel.construct_strategy`
`strategy_backtesting_engine/tradingmodel-construct-strategy.py:0`

## `PortfolioWeightConstruction.optimize_portfolio_weights`
`strategy_backtesting_engine/portfolioweightconstruction-optimize-por.py:0`

## `RiskEngine.calculate_leverage_factor`
`strategy_backtesting_engine/riskengine-calculate-leverage-factor.py:0`

## `portfolio_combination`
`strategy_backtesting_engine/portfolio-combination.py:0`

## `signal_delay`
`strategy_backtesting_engine/signal-delay.py:0`

## `portfolio_vol_adjust`
`strategy_backtesting_engine/portfolio-vol-adjust.py:0`


path: references/components/technical_indicator_-_signal_generation.md
content: # technical_indicator_&_signal_generation (5 classes)

## `TechIndicator.create_tech_ind`
`technical_indicator_&_signal_generation/techindicator-create-tech-ind.py:0`

## `TechParams.__init__`
`technical_indicator_&_signal_generation/techparams-init.py:0`

## `EventsFactory.create_event_signal`
`technical_indicator_&_signal_generation/eventsfactory-create-event-signal.py:0`

## `indicator_type`
`technical_indicator_&_signal_generation/indicator-type.py:0`

## `signal_direction_filter`
`technical_indicator_&_signal_generation/signal-direction-filter.py:0`


path: references/components/total_return_index_construction.md
content: # total_return_index_construction (6 classes)

## `FXSpotCurve.construct_total_returns_index`
`total_return_index_construction/fxspotcurve-construct-total-returns-inde.py:0`

## `FXForwardsCurve.roll_contracts`
`total_return_index_construction/fxforwardscurve-roll-contracts.py:0`

## `FXOptionsCurve.construct_tri`
`total_return_index_construction/fxoptionscurve-construct-tri.py:0`

## `AbstractCurve.generate_key`
`total_return_index_construction/abstractcurve-generate-key.py:0`

## `roll_event`
`total_return_index_construction/roll-event.py:0`

## `construct_via_currency`
`total_return_index_construction/construct-via-currency.py:0`


path: references/components/trade_analysis_-_reporting.md
content: # trade_analysis_&_reporting (5 classes)

## `TradeAnalysis.analyse_strategy`
`trade_analysis_&_reporting/tradeanalysis-analyse-strategy.py:0`

## `BacktestComparison.compare`
`trade_analysis_&_reporting/backtestcomparison-compare.py:0`

## `Report.generate`
`trade_analysis_&_reporting/report-generate.py:0`

## `Seasonality.detect`
`trade_analysis_&_reporting/seasonality-detect.py:0`

## `analysis_engine`
`trade_analysis_&_reporting/analysis-engine.py:0`


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)