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/rust/analysis/src/python/analyzer.rs

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.
// -------------------------------------------------------------------------------------------------

use std::{collections::HashMap, sync::Arc};

use nautilus_core::{UnixNanos, python::to_pyvalue_err};
use nautilus_model::{
    identifiers::PositionId,
    position::Position,
    types::{Currency, Money},
};
use pyo3::prelude::*;

use crate::{
    analyzer::PortfolioAnalyzer,
    statistics::{
        expectancy::Expectancy, long_ratio::LongRatio, loser_avg::AvgLoser, loser_max::MaxLoser,
        loser_min::MinLoser, profit_factor::ProfitFactor, returns_avg::ReturnsAverage,
        returns_avg_loss::ReturnsAverageLoss, returns_avg_win::ReturnsAverageWin,
        returns_volatility::ReturnsVolatility, risk_return_ratio::RiskReturnRatio,
        sharpe_ratio::SharpeRatio, sortino_ratio::SortinoRatio, win_rate::WinRate,
        winner_avg::AvgWinner, winner_max::MaxWinner, winner_min::MinWinner,
    },
};

#[pymethods]
impl PortfolioAnalyzer {
    #[new]
    #[must_use]
    pub fn py_new() -> Self {
        Self::new()
    }

    fn __repr__(&self) -> String {
        format!("PortfolioAnalyzer(currencies={})", self.currencies().len())
    }

    #[pyo3(name = "currencies")]
    fn py_currencies(&self) -> Vec<Currency> {
        self.currencies().into_iter().copied().collect()
    }

    #[pyo3(name = "get_performance_stats_returns")]
    fn py_get_performance_stats_returns(&self) -> HashMap<String, f64> {
        self.get_performance_stats_returns().into_iter().collect()
    }

    #[pyo3(name = "get_performance_stats_pnls")]
    fn py_get_performance_stats_pnls(
        &self,
        currency: Option<&Currency>,
        unrealized_pnl: Option<&Money>,
    ) -> PyResult<HashMap<String, f64>> {
        self.get_performance_stats_pnls(currency, unrealized_pnl)
            .map(|m| m.into_iter().collect())
            .map_err(to_pyvalue_err)
    }

    #[pyo3(name = "get_performance_stats_general")]
    fn py_get_performance_stats_general(&self) -> HashMap<String, f64> {
        self.get_performance_stats_general().into_iter().collect()
    }

    #[pyo3(name = "add_return")]
    fn py_add_return(&mut self, timestamp: u64, value: f64) {
        self.add_return(UnixNanos::from(timestamp), value);
    }

    #[pyo3(name = "reset")]
    fn py_reset(&mut self) {
        self.reset();
    }

    #[pyo3(name = "register_statistic")]
    fn py_register_statistic(&mut self, py: Python, statistic: Py<PyAny>) -> PyResult<()> {
        let type_name = statistic
            .getattr(py, "__class__")?
            .getattr(py, "__name__")?
            .extract::<String>(py)?;

        match type_name.as_str() {
            "MaxWinner" => {
                let stat = statistic.extract::<MaxWinner>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "MinWinner" => {
                let stat = statistic.extract::<MinWinner>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "AvgWinner" => {
                let stat = statistic.extract::<AvgWinner>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "MaxLoser" => {
                let stat = statistic.extract::<MaxLoser>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "MinLoser" => {
                let stat = statistic.extract::<MinLoser>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "AvgLoser" => {
                let stat = statistic.extract::<AvgLoser>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "Expectancy" => {
                let stat = statistic.extract::<Expectancy>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "WinRate" => {
                let stat = statistic.extract::<WinRate>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "ReturnsVolatility" => {
                let stat = statistic.extract::<ReturnsVolatility>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "ReturnsAverage" => {
                let stat = statistic.extract::<ReturnsAverage>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "ReturnsAverageLoss" => {
                let stat = statistic.extract::<ReturnsAverageLoss>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "ReturnsAverageWin" => {
                let stat = statistic.extract::<ReturnsAverageWin>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "SharpeRatio" => {
                let stat = statistic.extract::<SharpeRatio>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "SortinoRatio" => {
                let stat = statistic.extract::<SortinoRatio>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "ProfitFactor" => {
                let stat = statistic.extract::<ProfitFactor>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "RiskReturnRatio" => {
                let stat = statistic.extract::<RiskReturnRatio>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            "LongRatio" => {
                let stat = statistic.extract::<LongRatio>(py)?;
                self.register_statistic(Arc::new(stat));
            }
            _ => {
                return Err(to_pyvalue_err(format!(
                    "Unknown statistic type: {type_name}"
                )));
            }
        }

        Ok(())
    }

    #[pyo3(name = "deregister_statistic")]
    fn py_deregister_statistic(&mut self, py: Python, statistic: Py<PyAny>) -> PyResult<()> {
        let type_name = statistic
            .getattr(py, "__class__")?
            .getattr(py, "__name__")?
            .extract::<String>(py)?;

        match type_name.as_str() {
            "MaxWinner" => {
                let stat = statistic.extract::<MaxWinner>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "MinWinner" => {
                let stat = statistic.extract::<MinWinner>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "AvgWinner" => {
                let stat = statistic.extract::<AvgWinner>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "MaxLoser" => {
                let stat = statistic.extract::<MaxLoser>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "MinLoser" => {
                let stat = statistic.extract::<MinLoser>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "AvgLoser" => {
                let stat = statistic.extract::<AvgLoser>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "Expectancy" => {
                let stat = statistic.extract::<Expectancy>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "WinRate" => {
                let stat = statistic.extract::<WinRate>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "ReturnsVolatility" => {
                let stat = statistic.extract::<ReturnsVolatility>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "ReturnsAverage" => {
                let stat = statistic.extract::<ReturnsAverage>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "ReturnsAverageLoss" => {
                let stat = statistic.extract::<ReturnsAverageLoss>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "ReturnsAverageWin" => {
                let stat = statistic.extract::<ReturnsAverageWin>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "SharpeRatio" => {
                let stat = statistic.extract::<SharpeRatio>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "SortinoRatio" => {
                let stat = statistic.extract::<SortinoRatio>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "ProfitFactor" => {
                let stat = statistic.extract::<ProfitFactor>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "RiskReturnRatio" => {
                let stat = statistic.extract::<RiskReturnRatio>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            "LongRatio" => {
                let stat = statistic.extract::<LongRatio>(py)?;
                self.deregister_statistic(Arc::new(stat));
            }
            _ => {
                return Err(to_pyvalue_err(format!(
                    "Unknown statistic type: {type_name}"
                )));
            }
        }

        Ok(())
    }

    #[pyo3(name = "deregister_statistics")]
    fn py_deregister_statistics(&mut self) {
        self.deregister_statistics();
    }

    #[pyo3(name = "add_positions")]
    fn py_add_positions(&mut self, py: Python, positions: Vec<Py<PyAny>>) -> PyResult<()> {
        // Extract Position objects from Cython wrappers
        let positions: Vec<Position> = positions
            .iter()
            .map(|p| {
                // Try to get the underlying Rust Position
                // For now, we'll need to handle Cython Position by accessing its _mem field
                p.getattr(py, "_mem")?
                    .extract::<Position>(py)
                    .map_err(Into::into)
            })
            .collect::<PyResult<Vec<Position>>>()?;

        self.add_positions(&positions);
        Ok(())
    }

    #[pyo3(name = "add_trade")]
    fn py_add_trade(&mut self, position_id: &PositionId, realized_pnl: &Money) {
        self.add_trade(position_id, realized_pnl);
    }

    // Note: calculate_statistics is not exposed to Python because it requires
    // complex conversions of Account and dict types. Use the Python analyzer.py wrapper instead.

    #[pyo3(name = "statistic")]
    fn py_statistic(&self, name: &str) -> Option<String> {
        self.statistic(name).map(|s| s.name())
    }

    #[pyo3(name = "returns")]
    fn py_returns(&self, py: Python) -> PyResult<Py<PyAny>> {
        // Convert BTreeMap<UnixNanos, f64> to Python dict
        let dict = pyo3::types::PyDict::new(py);
        for (timestamp, value) in self.returns() {
            dict.set_item(timestamp.as_u64(), value)?;
        }
        Ok(dict.into())
    }

    #[pyo3(name = "realized_pnls")]
    fn py_realized_pnls(&self, py: Python, currency: Option<&Currency>) -> PyResult<Py<PyAny>> {
        match self.realized_pnls(currency) {
            Some(pnls) => {
                // Convert Vec<(PositionId, f64)> to Python list of tuples or dict
                let dict = pyo3::types::PyDict::new(py);
                for (position_id, pnl) in pnls {
                    dict.set_item(position_id.to_string(), pnl)?;
                }
                Ok(dict.into())
            }
            None => Ok(py.None()),
        }
    }

    #[pyo3(name = "total_pnl")]
    fn py_total_pnl(
        &self,
        currency: Option<&Currency>,
        unrealized_pnl: Option<&Money>,
    ) -> PyResult<f64> {
        self.total_pnl(currency, unrealized_pnl)
            .map_err(to_pyvalue_err)
    }

    #[pyo3(name = "total_pnl_percentage")]
    fn py_total_pnl_percentage(
        &self,
        currency: Option<&Currency>,
        unrealized_pnl: Option<&Money>,
    ) -> PyResult<f64> {
        self.total_pnl_percentage(currency, unrealized_pnl)
            .map_err(to_pyvalue_err)
    }

    #[pyo3(name = "get_stats_pnls_formatted")]
    fn py_get_stats_pnls_formatted(
        &self,
        currency: Option<&Currency>,
        unrealized_pnl: Option<&Money>,
    ) -> PyResult<Vec<String>> {
        self.get_stats_pnls_formatted(currency, unrealized_pnl)
            .map_err(to_pyvalue_err)
    }

    #[pyo3(name = "get_stats_returns_formatted")]
    fn py_get_stats_returns_formatted(&self) -> Vec<String> {
        self.get_stats_returns_formatted()
    }

    #[pyo3(name = "get_stats_general_formatted")]
    fn py_get_stats_general_formatted(&self) -> Vec<String> {
        self.get_stats_general_formatted()
    }
}
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