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/python/analysis/analyzer.py

View on GitHub
# -------------------------------------------------------------------------------------------------
#  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
#  https://nautechsystems.io
#
#  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
#  You may not use this file except in compliance with the License.
#  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
# -------------------------------------------------------------------------------------------------

from datetime import datetime
from decimal import Decimal
from typing import Any

import pandas as pd
from numpy import float64

from nautilus_trader.accounting.accounts.base import Account
from nautilus_trader.analysis.statistic import PortfolioStatistic
from nautilus_trader.core.correctness import PyCondition
from nautilus_trader.core.datetime import unix_nanos_to_dt
from nautilus_trader.model.identifiers import PositionId
from nautilus_trader.model.objects import Currency
from nautilus_trader.model.objects import Money
from nautilus_trader.model.position import Position


class PortfolioAnalyzer:
    """
    Provides a portfolio performance analyzer for tracking and generating performance
    metrics and statistics.
    """

    def __init__(self) -> None:
        self._statistics: dict[str, PortfolioStatistic] = {}

        # Data
        self._account_balances_starting: dict[Currency, Money] = {}
        self._account_balances: dict[Currency, Money] = {}
        self._positions: list[Position] = []
        self._realized_pnls: dict[Currency, pd.Series] = {}
        self._returns: pd.Series = pd.Series(dtype=float64)

    def register_statistic(self, statistic: PortfolioStatistic) -> None:
        """
        Register the given statistic with the analyzer.

        Parameters
        ----------
        statistic : PortfolioStatistic
            The statistic to register.

        """
        PyCondition.not_none(statistic, "statistic")

        self._statistics[statistic.name] = statistic

    def deregister_statistic(self, statistic: PortfolioStatistic) -> None:
        """
        Deregister a statistic from the analyzer.
        """
        self._statistics.pop(statistic.name, None)

    def deregister_statistics(self) -> None:
        """
        Deregister all statistics from the analyzer.
        """
        self._statistics.clear()

    def reset(self) -> None:
        """
        Reset the analyzer.

        All stateful fields are reset to their initial value.

        """
        self._account_balances_starting = {}
        self._account_balances = {}
        self._positions = []
        self._realized_pnls = {}
        self._returns = pd.Series(dtype=float64)

    def _get_max_length_name(self) -> int:
        max_length = 0
        for stat_name in self._statistics:
            max_length = max(max_length, len(stat_name))

        return max_length

    @property
    def currencies(self) -> list[Currency]:
        """
        Return the analyzed currencies.

        Returns
        -------
        list[Currency]

        """
        return list(self._account_balances.keys())

    def statistic(self, name: str) -> PortfolioStatistic | None:
        """
        Return the statistic with the given name (if found).

        Returns
        -------
        PortfolioStatistic or ``None``

        """
        return self._statistics.get(name)

    def returns(self) -> pd.Series:
        """
        Return raw the returns data.

        Returns
        -------
        pd.Series

        """
        return self._returns

    def calculate_statistics(self, account: Account, positions: list[Position]) -> None:
        """
        Calculate performance metrics from the given data.

        Parameters
        ----------
        account : Account
            The account for the calculations.
        positions : list[Position]
            The positions for the calculations.

        """
        self._account_balances_starting = account.starting_balances()
        self._account_balances = account.balances_total()
        self._positions = []
        self._realized_pnls = {}
        self._returns = pd.Series(dtype=float64)

        self.add_positions(positions)
        self._returns = self._returns.sort_index()

    def add_positions(self, positions: list[Position]) -> None:
        """
        Add positions data to the analyzer.

        Parameters
        ----------
        positions : list[Position]
            The positions for analysis.

        """
        self._positions += positions

        for position in positions:
            if position.realized_pnl is None:
                continue  # Skip empty shell positions

            self.add_trade(position.id, position.realized_pnl)

            if position.ts_closed > 0:
                self.add_return(unix_nanos_to_dt(position.ts_closed), position.realized_return)

    def add_trade(self, position_id: PositionId, realized_pnl: Money) -> None:
        """
        Add trade data to the analyzer.

        Parameters
        ----------
        position_id : PositionId
            The position ID for the trade.
        realized_pnl : Money
            The realized PnL for the trade.

        """
        currency = realized_pnl.currency
        realized_pnls = self._realized_pnls.get(currency, pd.Series(dtype=float64))
        realized_pnls.loc[position_id.value] = realized_pnl.as_double()
        self._realized_pnls[currency] = realized_pnls

    def add_return(self, timestamp: datetime, value: float) -> None:
        """
        Add return data to the analyzer.

        Parameters
        ----------
        timestamp : datetime
            The timestamp for the returns entry.
        value : double
            The return value to add.

        """
        if timestamp not in self._returns:
            self._returns.loc[timestamp] = 0.0
        self._returns.loc[timestamp] += float(value)

    def realized_pnls(self, currency: Currency | None = None) -> pd.Series | None:
        """
        Return the realized PnL for the portfolio.

        For multi-currency portfolios, specify the currency for the result.

        Parameters
        ----------
        currency : Currency, optional
            The currency for the result.

        Returns
        -------
        pd.Series or ``None``

        Raises
        ------
        ValueError
            If `currency` is ``None`` when analyzing multi-currency portfolios.

        """
        if not self._realized_pnls:
            return None
        if currency is None:
            if len(self._account_balances) > 1:
                raise ValueError("`currency` was `None` for multi-currency portfolio")
            currency = next(iter(self._account_balances.keys()))

        return self._realized_pnls.get(currency)

    def total_pnl(
        self,
        currency: Currency | None = None,
        unrealized_pnl: Money | None = None,
    ) -> float:
        """
        Return the total PnL for the portfolio.

        For multi-currency portfolios, specify the currency for the result.

        Parameters
        ----------
        currency : Currency, optional
            The currency for the result.
        unrealized_pnl : Money, optional
            The unrealized PnL for the given currency.

        Returns
        -------
        float

        Raises
        ------
        ValueError
            If `currency` is ``None`` when analyzing multi-currency portfolios.
        ValueError
            If `currency` is not contained in the tracked account balances.
        ValueError
            If `unrealized_pnl` is not ``None`` and currency is not equal to the given currency.

        """
        if not self._account_balances:
            return 0.0

        if currency is None:
            if len(self._account_balances) > 1:
                raise ValueError("`currency` was `None` for multi-currency portfolio")
            currency = next(iter(self._account_balances.keys()))

        if unrealized_pnl is not None and unrealized_pnl.currency != currency:
            raise ValueError(f"unrealized PnL currency is not {currency}")

        account_balance = self._account_balances.get(currency)
        account_balance_starting = self._account_balances_starting.get(currency, Money(0, currency))

        if account_balance is None:
            return 0.0

        unrealized_pnl_f64 = 0.0 if unrealized_pnl is None else unrealized_pnl.as_double()
        return float(account_balance - account_balance_starting) + unrealized_pnl_f64

    def total_pnl_percentage(
        self,
        currency: Currency | None = None,
        unrealized_pnl: Money | None = None,
    ) -> float:
        """
        Return the percentage change of the total PnL for the portfolio.

        For multi-currency accounts, specify the currency for the result.

        Parameters
        ----------
        currency : Currency, optional
            The currency for the result.
        unrealized_pnl : Money, optional
            The unrealized PnL for the given currency.

        Returns
        -------
        float

        Raises
        ------
        ValueError
            If `currency` is ``None`` when analyzing multi-currency portfolios.
        ValueError
            If `currency` is not contained in the tracked account balances.
        ValueError
            If `unrealized_pnl` is not ``None`` and currency is not equal to the given currency.

        """
        if not self._account_balances:
            return 0.0

        if currency is None:
            if len(self._account_balances) != 1:
                raise ValueError("currency was None for multi-currency portfolio")
            currency = next(iter(self._account_balances.keys()))

        if unrealized_pnl is not None and unrealized_pnl.currency != currency:
            raise ValueError(f"unrealized PnL currency is not {currency}")

        account_balance = self._account_balances.get(currency)
        account_balance_starting = self._account_balances_starting.get(currency, Money(0, currency))

        if account_balance is None:
            return 0.0

        if account_balance_starting.as_decimal() == 0:
            # Protect divide by zero
            return 0.0

        unrealized_pnl_f64 = 0.0 if unrealized_pnl is None else unrealized_pnl.as_double()

        # Calculate percentage
        current = account_balance + unrealized_pnl_f64
        starting = account_balance_starting
        difference = current - starting

        return float((difference / starting) * 100)

    def get_performance_stats_pnls(
        self,
        currency: Currency | None = None,
        unrealized_pnl: Money | None = None,
    ) -> dict[str, float]:
        """
        Return the 'PnL' (profit and loss) performance statistics, optionally includes
        the unrealized PnL.

        Money objects are converted to floats.

        Parameters
        ----------
        currency : Currency
            The currency for the performance.
        unrealized_pnl : Money, optional
            The unrealized PnL for the performance.

        Returns
        -------
        dict[str, Any]

        """
        realized_pnls = self.realized_pnls(currency)

        output: dict[str, Any] = {
            "PnL (total)": self.total_pnl(currency, unrealized_pnl),
            "PnL% (total)": self.total_pnl_percentage(currency, unrealized_pnl),
        }

        for name, stat in self._statistics.items():
            # Check if this is a Rust statistic (requires list) or Python statistic (expects Series)
            is_rust_stat = type(stat).__module__.startswith("nautilus_trader.core.nautilus_pyo3")

            if is_rust_stat:
                # Convert pandas Series to list for Rust statistics
                pnls_list = realized_pnls.tolist() if realized_pnls is not None else []
                value = stat.calculate_from_realized_pnls(pnls_list)
            else:
                # Pass Series directly for Python statistics (backward compatibility)
                value = stat.calculate_from_realized_pnls(realized_pnls)

            if value is None:
                continue  # Not implemented
            if not isinstance(value, int | float | str | bool):
                value = str(value)
            output[name] = value

        return output

    def get_performance_stats_returns(self) -> dict[str, Any]:
        """
        Return the `return` performance statistics values.

        Returns
        -------
        dict[str, Any]

        """
        output = {}

        for name, stat in self._statistics.items():
            # Check if this is a Rust statistic (requires dict) or Python statistic (expects Series)
            is_rust_stat = type(stat).__module__.startswith("nautilus_trader.core.nautilus_pyo3")

            if is_rust_stat:
                # Convert pandas Series with datetime index to dict with unix timestamps for Rust statistics
                returns_dict = {}
                if not self._returns.empty:
                    for timestamp, value in self._returns.items():
                        # Convert datetime to unix nanoseconds (use .value to avoid float precision loss)
                        unix_nanos = timestamp.value
                        returns_dict[unix_nanos] = float(value)
                value = stat.calculate_from_returns(returns_dict)
            else:
                # Pass Series directly for Python statistics (backward compatibility)
                value = stat.calculate_from_returns(self._returns)

            if value is None:
                continue  # Not implemented
            if not isinstance(value, int | float | str | bool):
                value = str(value)
            output[name] = value

        return output

    def get_performance_stats_general(self) -> dict[str, Any]:
        """
        Return the `general` performance statistics.

        Returns
        -------
        dict[str, Any]

        """
        output = {}

        for name, stat in self._statistics.items():
            # Positions are passed as-is to both Rust and Python statistics
            # (list[Position] works for both)
            value = stat.calculate_from_positions(self._positions)
            if value is None:
                continue  # Not implemented
            if not isinstance(value, int | float | str | bool):
                value = str(value)
            output[name] = value

        return output

    def get_stats_pnls_formatted(
        self,
        currency: Currency | None = None,
        unrealized_pnl: Money | None = None,
    ) -> list[str]:
        """
        Return the performance statistics from the last backtest run formatted for
        printing in the backtest run footer.

        Parameters
        ----------
        currency : Currency
            The currency for the performance.
        unrealized_pnl : Money, optional
            The unrealized PnL for the performance.

        Returns
        -------
        list[str]

        """
        max_length: int = self._get_max_length_name()
        stats = self.get_performance_stats_pnls(currency, unrealized_pnl)

        output = []
        for k, v in stats.items():
            padding = max_length - len(k) + 1
            output.append(f"{k}: {' ' * padding}{v:_}")

        return output

    def get_stats_returns_formatted(self) -> list[str]:
        """
        Return the performance statistics for returns from the last backtest run
        formatted for printing in the backtest run footer.

        Returns
        -------
        list[str]

        """
        max_length: int = self._get_max_length_name()
        stats = self.get_performance_stats_returns()

        output = []
        for k, v in stats.items():
            padding = max_length - len(k) + 1
            output.append(f"{k}: {' ' * padding}{v:_}")

        return output

    def get_stats_general_formatted(self) -> list[str]:
        """
        Return the performance statistics for returns from the last backtest run
        formatted for printing in the backtest run footer.

        Returns
        -------
        list[str]

        """
        max_length: int = self._get_max_length_name()
        stats = self.get_performance_stats_general()

        output = []
        for k, v in stats.items():
            padding = max_length - len(k) + 1
            v_formatted = f"{v:_}" if isinstance(v, int | float | Decimal) else str(v)
            output.append(f"{k}: {' ' * padding}{v_formatted}")

        return output
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