Skip to content

Martingale42/nautilus-dev / skills/nt-signals

nt-signals

Unverified

Use when working with indicators, signal generation, bar aggregation, custom data types, analysis statistics, or tearsheets in NautilusTrader.

FileKindSize
SKILL.mdskill md7.8 KB
references/api/.gitkeepother0 B
references/api/analysis.mdmarkdown534 B
references/api/book.mdmarkdown160 B
references/api/data.mdmarkdown154 B
references/api/indicators.mdmarkdown1.2 KB
references/api/portfolio.mdmarkdown380 B
references/concepts/.gitkeepother0 B
references/concepts/data.mdmarkdown68.9 KB
references/concepts/portfolio.mdmarkdown6.7 KB
references/concepts/reports.mdmarkdown16.2 KB
references/concepts/visualization.mdmarkdown19.3 KB
references/examples/.gitkeepother0 B
references/examples/bar_aggregation/README.mdmarkdown500 B
references/examples/bar_aggregation/run_example.pyscript3.9 KB
references/examples/bar_aggregation/strategy.pyscript5.1 KB
references/examples/cascaded_indicators/README.mdmarkdown839 B
references/examples/cascaded_indicators/run_example.pyscript4.2 KB
references/examples/cascaded_indicators/strategy.pyscript4.7 KB
references/examples/indicators/README.mdmarkdown632 B
references/examples/indicators/run_example.pyscript3.8 KB
references/examples/indicators/strategy.pyscript5.3 KB
references/guides/.gitkeepother0 B
references/guides/custom_data_patterns.mdmarkdown10.4 KB
references/guides/indicators_guide.mdmarkdown14.6 KB
references/python/analysis/__init__.pyscript5.2 KB
references/python/analysis/analyzer.pyscript16.6 KB
references/python/analysis/config.pyscript6.4 KB
references/python/analysis/reporter.pyscript6.2 KB
references/python/analysis/statistic.pyscript3.8 KB
references/python/analysis/tearsheet.pyscript58.4 KB
references/python/analysis/themes.pyscript6.3 KB
references/rust/analysis/Cargo.tomlmanifest1.1 KB
references/rust/analysis/LICENSEother13 B
references/rust/analysis/README.mdmarkdown2.9 KB
references/rust/analysis/src/analyzer.rsscript31.1 KB
references/rust/analysis/src/lib.rsscript3.2 KB
references/rust/analysis/src/python/analyzer.rsscript13.0 KB
references/rust/analysis/src/python/mod.rsscript2.7 KB
references/rust/analysis/src/python/statistics/cagr.rsscript1.6 KB
references/rust/analysis/src/python/statistics/calmar_ratio.rsscript1.6 KB
references/rust/analysis/src/python/statistics/expectancy.rsscript1.9 KB
references/rust/analysis/src/python/statistics/long_ratio.rsscript2.7 KB
references/rust/analysis/src/python/statistics/loser_avg.rsscript1.9 KB
references/rust/analysis/src/python/statistics/loser_max.rsscript1.9 KB
references/rust/analysis/src/python/statistics/loser_min.rsscript1.9 KB
references/rust/analysis/src/python/statistics/max_drawdown.rsscript1.5 KB
references/rust/analysis/src/python/statistics/mod.rsscript1.6 KB
references/rust/analysis/src/python/statistics/profit_factor.rsscript1.8 KB
references/rust/analysis/src/python/statistics/returns_avg.rsscript1.8 KB
references/rust/analysis/src/python/statistics/returns_avg_loss.rsscript1.8 KB
references/rust/analysis/src/python/statistics/returns_avg_win.rsscript1.8 KB
references/rust/analysis/src/python/statistics/returns_volatility.rsscript1.9 KB
references/rust/analysis/src/python/statistics/risk_return_ratio.rsscript1.8 KB
references/rust/analysis/src/python/statistics/sharpe_ratio.rsscript1.9 KB
references/rust/analysis/src/python/statistics/sortino_ratio.rsscript1.9 KB
references/rust/analysis/src/python/statistics/win_rate.rsscript1.9 KB
references/rust/analysis/src/python/statistics/winner_avg.rsscript1.9 KB
references/rust/analysis/src/python/statistics/winner_max.rsscript1.9 KB
references/rust/analysis/src/python/statistics/winner_min.rsscript1.9 KB
references/rust/analysis/src/statistic.rsscript4.1 KB
references/rust/analysis/src/statistics/cagr.rsscript7.0 KB
references/rust/analysis/src/statistics/calmar_ratio.rsscript5.5 KB
references/rust/analysis/src/statistics/expectancy.rsscript6.8 KB
references/rust/analysis/src/statistics/long_ratio.rsscript8.0 KB
references/rust/analysis/src/statistics/loser_avg.rsscript4.1 KB
references/rust/analysis/src/statistics/loser_max.rsscript4.1 KB
references/rust/analysis/src/statistics/loser_min.rsscript4.2 KB
references/rust/analysis/src/statistics/max_drawdown.rsscript4.8 KB
references/rust/analysis/src/statistics/mod.rsscript1.3 KB
references/rust/analysis/src/statistics/profit_factor.rsscript5.8 KB
references/rust/analysis/src/statistics/returns_avg.rsscript3.9 KB
references/rust/analysis/src/statistics/returns_avg_loss.rsscript4.5 KB
references/rust/analysis/src/statistics/returns_avg_win.rsscript4.0 KB
references/rust/analysis/src/statistics/returns_volatility.rsscript4.9 KB
references/rust/analysis/src/statistics/risk_return_ratio.rsscript4.3 KB
references/rust/analysis/src/statistics/sharpe_ratio.rsscript4.8 KB
references/rust/analysis/src/statistics/sortino_ratio.rsscript5.1 KB
references/rust/analysis/src/statistics/win_rate.rsscript4.1 KB
references/rust/analysis/src/statistics/winner_avg.rsscript3.6 KB
references/rust/analysis/src/statistics/winner_max.rsscript3.6 KB
references/rust/analysis/src/statistics/winner_min.rsscript4.0 KB
templates/.gitkeepother0 B
templates/custom_data.pyscript2.0 KB
templates/indicator.pyscript2.6 KB
templates/portfolio_statistic.pyscript2.3 KB

references/concepts/portfolio.md

View on GitHub
# Portfolio

The Portfolio is the central hub for managing and tracking all positions across active strategies for the trading node or backtest.
It consolidates position data from multiple instruments, providing a unified view of your holdings, risk exposure, and overall performance.
Explore this section to understand how NautilusTrader aggregates and updates portfolio state to support effective trading and risk management.

## Currency conversion

The Portfolio supports automatic currency conversion for PnL and exposure calculations,
allowing you to view results in your preferred currency. This is particularly useful when
trading across multiple instruments with different settlement currencies or managing multiple
accounts with different base currencies.

### Supported conversions

Currency conversion is available for the following portfolio queries:

- `realized_pnl()` / `realized_pnls()` - Convert realized PnL to target currency.
- `unrealized_pnl()` / `unrealized_pnls()` - Convert unrealized PnL to target currency.
- `total_pnl()` / `total_pnls()` - Convert total PnL to target currency.
- `net_exposure()` / `net_exposures()` - Convert net exposure to target currency.

All methods accept an optional `target_currency` parameter to specify the desired output
currency.

### Single account behavior

When querying a single account without specifying `target_currency`, the Portfolio
automatically converts values to that account's base currency:

```python
# Returns exposure in the account's base currency (e.g., USD)
exposure = portfolio.net_exposures(venue=BINANCE, account_id=account_id)
```

### Multi-account behavior

When querying multiple accounts simultaneously, behavior depends on whether you query
all instruments (`net_exposures()`) or a single instrument (`net_exposure()`):

**For `net_exposures()` (all instruments):**

- **Same base currency**: Automatically converts to the common base currency.
- **Different base currencies**: Returns a dict with multiple currencies, each converted
  to its account's base currency. Provide `target_currency` for single-currency results.

**For `net_exposure()` (single instrument across accounts):**

- **Different base currencies**: Returns `None` unless you provide `target_currency`.

```python
# Scenario 1: Multiple accounts, all with USD base currency
exposures = portfolio.net_exposures(venue=BINANCE)
# Returns {USD: Money(...)}

# Scenario 2: Multiple accounts with different base currencies (USD and EUR)
exposures = portfolio.net_exposures(venue=BINANCE)
# Returns {USD: Money(...), EUR: Money(...)}

# Force single currency across accounts
exposures = portfolio.net_exposures(venue=BINANCE, target_currency=USD)
# Returns {USD: Money(...)}
```

### Conversion failures

When `target_currency` is provided and currency conversion fails, behavior depends on
the method type:

- **Single-value methods** (`realized_pnl`, `unrealized_pnl`, `total_pnl`, `net_exposure`):
  Return `None` and log an error to prevent incorrect values.
- **Dict-returning methods** (`realized_pnls`, `unrealized_pnls`, `total_pnls`, `net_exposures`):
  Omit instruments that fail conversion but return results for successful conversions.

:::warning
Ensure exchange rate data is available when using `target_currency` for cross-currency
aggregation.
:::

### Conversion price types

When converting exposures to a target currency, the Portfolio uses different price types
depending on the position composition:

- **All long positions**: Uses `BID` prices (conservative for long exposure).
- **All short positions**: Uses `ASK` prices (conservative for short exposure).
- **Mixed positions**: Uses `MID` prices (neutral when both long and short exist).

This ensures conversions reflect realistic market conditions where you would liquidate
long positions at bid and cover short positions at ask. For mixed positions, mid-pricing
provides a neutral valuation.

If `use_mark_xrates` is enabled in the portfolio configuration, `MARK` prices replace
`MID` prices for mixed positions and general conversions.

## Portfolio statistics

There are a variety of [built-in portfolio statistics](https://github.com/nautechsystems/nautilus_trader/tree/develop/crates/analysis/src/statistics)
which are used to analyse a trading portfolios performance for both backtests and live trading.

The statistics are generally categorized as follows.

- PnLs based statistics (per currency)
- Returns based statistics
- Positions based statistics
- Orders based statistics

It's also possible to call a traders `PortfolioAnalyzer` and calculate statistics at any arbitrary
time, including *during* a backtest, or live trading session.

## Custom statistics

Custom portfolio statistics can be defined by inheriting from the `PortfolioStatistic`
base class, and implementing any of the `calculate_` methods.

For example, the following is the implementation for the built-in `WinRate` statistic:

```python
import pandas as pd
from typing import Any
from nautilus_trader.analysis.statistic import PortfolioStatistic


class WinRate(PortfolioStatistic):
    """
    Calculates the win rate from a realized PnLs series.
    """

    def calculate_from_realized_pnls(self, realized_pnls: pd.Series) -> Any | None:
        # Preconditions
        if realized_pnls is None or realized_pnls.empty:
            return 0.0

        # Calculate statistic
        winners = [x for x in realized_pnls if x > 0.0]
        losers = [x for x in realized_pnls if x <= 0.0]

        return len(winners) / float(max(1, (len(winners) + len(losers))))
```

These statistics can then be registered with a traders `PortfolioAnalyzer`.

```python
stat = WinRate()

# Register with the portfolio analyzer
engine.portfolio.analyzer.register_statistic(stat)
```

See the [`PortfolioAnalyzer` API Reference](../api_reference/analysis.md#class-portfolioanalyzer) for all available methods.

:::tip
Ensure your statistic is robust to degenerate inputs such as `None`, empty series, or insufficient data.
Return `None` for unknown/incalculable values, or a reasonable default like `0.0` when semantically appropriate (e.g., win rate with no trades).
:::

## Backtest analysis

Following a backtest run, a performance analysis will be carried out by passing realized PnLs, returns, positions and orders data to each registered
statistic in turn. Any output is then displayed in the tear sheet under the `Portfolio Performance` heading, grouped as:

- Realized PnL statistics (per currency)
- Returns statistics (for the entire portfolio)
- General statistics derived from position and order data (for the entire portfolio)

## Related guides

- [Positions](positions.md) - Position tracking within portfolios.
- [Reports](reports.md) - Generate portfolio analysis reports.
- [Visualization](visualization.md) - Visualize portfolio performance.
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall