Skip to main content

NumPy-based Technical Analysis library with focus on performance

Project description

numta

A pure Python implementation of TA-Lib (Technical Analysis Library) with a focus on performance and compatibility.

Overview

numta (NumPy Technical Analysis) provides the same functionality as the popular TA-Lib library but implemented entirely in Python using NumPy and Numba for performance. This eliminates the need for complex C library dependencies while maintaining high performance through optimized NumPy operations and JIT compilation.

Disclaimer: This is an independent implementation inspired by TA-Lib. It is not affiliated with, endorsed by, or connected to the original TA-Lib project. The technical analysis algorithms implemented here are based on publicly available mathematical formulas and are compatible with TA-Lib's function signatures for ease of migration.

Features

  • Pure Python implementation (no C dependencies)
  • TA-Lib compatible function signatures
  • Multiple performance backends:
    • Default NumPy implementation
    • Optimized cumsum algorithm (3x faster, no dependencies)
    • Numba JIT compilation (5-10x faster)
  • Automatic backend selection for optimal performance
  • Easy installation via pip
  • Comprehensive test suite comparing outputs with original TA-Lib
  • Built-in performance benchmarking tools

Installation

Basic Installation

# From PyPI (when published)
pip install numta

# From source
git clone https://github.com/houseofai/numta.git
cd numta
pip install -e .

Performance Optimizations (Recommended)

# Install with Numba for 5-10x speedup
pip install "numta[numba]"

# Install development dependencies
pip install "numta[dev]"

Quick Start

import numpy as np
from numta import SMA

# Create sample price data
close_prices = np.random.uniform(100, 200, 100)

# Calculate Simple Moving Average with default period (30)
sma = SMA(close_prices)

# Calculate SMA with custom period
sma_20 = SMA(close_prices, timeperiod=20)

print(f"SMA values: {sma[-5:]}")  # Last 5 values

Performance Optimization ๐Ÿš€

numta can match or exceed TA-Lib's performance using optional optimization backends:

from numta import SMA_auto

# Automatic backend selection (recommended)
sma = SMA_auto(close_prices, timeperiod=30, backend='auto')

# Or choose specific backend
from numta import SMA_cumsum, SMA_numba

sma_fast = SMA_cumsum(close_prices, timeperiod=30)    # 3x faster, no deps
sma_faster = SMA_numba(close_prices, timeperiod=30)   # 5-10x faster

Performance Comparison

Implementation Speed vs Original Requirements
numpy (default) 1.0x (baseline) None
cumsum 3.14x faster None
numba 5-10x faster pip install numba

Benchmark Results (10,000 points):

  • Original (numpy): 0.154ms
  • Cumsum: 0.049ms (3.14x faster)
  • Numba: 0.028ms (5.52x faster) โญ

Implemented Indicators

This library implements a comprehensive set of technical analysis indicators across multiple categories:

Overlap Studies

SMA, EMA, DEMA, TEMA, TRIMA, WMA, KAMA, MAMA, T3, BBANDS, MA, SAR, SAREXT

Momentum Indicators

RSI, MACD, MACDEXT, MACDFIX, STOCH, STOCHF, STOCHRSI, ADX, ADXR, APO, AROON, AROONOSC, ATR, BOP, CCI, CMO, DX, MFI, MINUS_DI, MINUS_DM, MOM, PLUS_DI, PLUS_DM, PPO, ROC, ROCP, ROCR, ROCR100, TRIX, ULTOSC, WILLR

Volume Indicators

AD, ADOSC, OBV

Volatility Indicators

NATR, TRANGE

Cycle Indicators

HT_DCPERIOD, HT_DCPHASE, HT_PHASOR, HT_SINE, HT_TRENDLINE, HT_TRENDMODE

Statistical Functions

BETA, CORREL, LINEARREG, LINEARREG_ANGLE, LINEARREG_INTERCEPT, LINEARREG_SLOPE, STDDEV, TSF, VAR

Math Operators

MAX, MAXINDEX, MIN, MININDEX, MINMAX, MINMAXINDEX, SUM

Price Transform

MEDPRICE, MIDPOINT, MIDPRICE, TYPPRICE, WCLPRICE

Pattern Recognition

60+ candlestick patterns including: Doji, Hammer, Engulfing, Morning Star, Evening Star, Three White Soldiers, and many more.

See FUNCTION_IMPLEMENTATIONS.md for detailed implementation status.

Usage Examples

Basic Usage

import numpy as np
from numta import SMA

# Generate sample data
close = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=np.float64)

# Calculate 3-period SMA
result = SMA(close, timeperiod=3)

# Output: [nan nan  2.  3.  4.  5.  6.  7.  8.  9.]
# First (timeperiod-1) values are NaN due to lookback period

Working with Real Market Data

import numpy as np
from numta import SMA

# Example with stock prices
close_prices = np.array([
    150.0, 151.5, 149.0, 153.0, 155.0,
    154.0, 156.5, 158.0, 157.0, 159.5
])

# Calculate 5-period SMA
sma_5 = SMA(close_prices, timeperiod=5)

for i, (price, sma) in enumerate(zip(close_prices, sma_5)):
    if not np.isnan(sma):
        print(f"Day {i+1}: Price={price:.2f}, SMA(5)={sma:.2f}")

Performance Benchmarking

numta includes a powerful benchmarking class to compare performance with the original TA-Lib:

import numpy as np
from numta import SMA as SMA_numta
from numta.benchmark import PerformanceMeasurement
import talib

# Create test data
data = np.random.uniform(100, 200, 10000)

# Setup benchmark
bench = PerformanceMeasurement()
bench.add_function("numta SMA", SMA_numta, data, timeperiod=30)
bench.add_function("TA-Lib SMA", talib.SMA, data, timeperiod=30)

# Run benchmark
results = bench.run(iterations=1000)
bench.print_results(results)

Running the Benchmark Script

python examples/benchmark_sma.py

Benchmark Features

The PerformanceMeasurement class provides:

  • Measure execution time with configurable iterations and warmup
  • Compare multiple functions side-by-side
  • Calculate speedup ratios
  • Test across different data sizes
  • Statistical analysis (mean, median, std dev, min, max)

Testing

The library includes comprehensive tests that compare outputs with the original TA-Lib:

# Install test dependencies
pip install -e ".[dev]"

# Run all tests
pytest

# Optional: Install TA-Lib for comparison tests (requires TA-Lib C library)
pip install -e ".[comparison]"

# Run specific test file
pytest tests/test_sma.py

# Run with verbose output
pytest -v

# Run benchmark tests
pytest tests/test_benchmark.py

Test Coverage

  • Comparison Tests: Verify that outputs match TA-Lib exactly
  • Edge Cases: Handle empty arrays, insufficient data, etc.
  • Input Validation: Test error handling for invalid inputs
  • Data Types: Support for both numpy arrays and Python lists

API Compatibility

numta maintains full API compatibility with TA-Lib:

Feature TA-Lib numta
Function signatures โœ“ โœ“
Return values โœ“ โœ“
NaN handling โœ“ โœ“
NumPy array support โœ“ โœ“
List support โœ“ โœ“
Default parameters โœ“ โœ“

Development

Project Structure

numta/
โ”œโ”€โ”€ src/
โ”‚   โ””โ”€โ”€ numta/
โ”‚       โ”œโ”€โ”€ __init__.py           # Main package exports
โ”‚       โ”œโ”€โ”€ backend.py            # Backend selection logic
โ”‚       โ”œโ”€โ”€ benchmark.py          # Performance measurement tools
โ”‚       โ”œโ”€โ”€ optimized.py          # Optimized implementations
โ”‚       โ”œโ”€โ”€ api/                  # Public API layer
โ”‚       โ”‚   โ”œโ”€โ”€ overlap.py        # Overlap studies (SMA, EMA, etc.)
โ”‚       โ”‚   โ”œโ”€โ”€ momentum_indicators.py
โ”‚       โ”‚   โ”œโ”€โ”€ volume_indicators.py
โ”‚       โ”‚   โ””โ”€โ”€ ...
โ”‚       โ””โ”€โ”€ cpu/                  # CPU/Numba implementations
โ”‚           โ”œโ”€โ”€ overlap.py        # Numba-optimized overlap studies
โ”‚           โ”œโ”€โ”€ math_operators.py
โ”‚           โ””โ”€โ”€ ...
โ”œโ”€โ”€ tests/                        # Comprehensive test suite
โ”‚   โ”œโ”€โ”€ test_sma.py
โ”‚   โ”œโ”€โ”€ test_ema.py
โ”‚   โ””โ”€โ”€ test_benchmark.py
โ”œโ”€โ”€ examples/                     # Usage examples
โ”‚   โ”œโ”€โ”€ benchmark_sma.py
โ”‚   โ””โ”€โ”€ benchmark_optimized.py
โ”œโ”€โ”€ development/                  # Development tools
โ”‚   โ”œโ”€โ”€ accuracy_*.py             # Accuracy comparison scripts
โ”‚   โ”œโ”€โ”€ benchmark_*.py            # Benchmark scripts
โ”‚   โ””โ”€โ”€ ACCURACY.md               # Accuracy test results
โ”œโ”€โ”€ PERFORMANCE.md                # Performance analysis
โ”œโ”€โ”€ FUNCTION_IMPLEMENTATIONS.md   # Implementation details
โ”œโ”€โ”€ pyproject.toml
โ”œโ”€โ”€ LICENSE
โ””โ”€โ”€ README.md

Adding New Indicators

To add a new indicator:

  1. Implement the function in the appropriate API module (e.g., api/overlap.py for overlap studies)
  2. Optionally add optimized Numba implementation in the corresponding cpu/ module
  3. Ensure the signature matches TA-Lib exactly
  4. Add comparison tests in tests/
  5. Export the function in __init__.py
  6. Add documentation and examples

Example:

def EMA(close: Union[np.ndarray, list], timeperiod: int = 30) -> np.ndarray:
    """
    Exponential Moving Average

    Parameters
    ----------
    close : array-like
        Close prices
    timeperiod : int, optional
        Period for EMA (default: 30)

    Returns
    -------
    np.ndarray
        EMA values
    """
    # Implementation here
    pass

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Implement your changes with tests
  4. Ensure all tests pass
  5. Submit a pull request

Performance

numta uses NumPy's optimized functions and Numba JIT compilation to achieve performance competitive with the C-based TA-Lib. Benchmark results:

  • SMA: Comparable performance to TA-Lib for large datasets
  • Lookback handling: Efficient NaN placement
  • Memory usage: Optimized array operations

Run python examples/benchmark_sma.py to see detailed benchmarks on your system.

Requirements

  • Python >= 3.8
  • NumPy >= 1.20.0

Optional Dependencies

  • Testing: pytest >= 7.0.0, pytest-benchmark >= 4.0.0
  • Performance: numba >= 0.56.0 (for JIT compilation, 5-10x speedup)
  • Comparison: TA-Lib >= 0.4.0 (only for development/comparison scripts, requires C library)

License

MIT License - see LICENSE file for details

Acknowledgments

This project implements technical analysis algorithms that are publicly available mathematical formulas. We acknowledge and credit:

numta is an independent clean-room implementation and is not derived from TA-Lib's source code. All code in this repository is original work licensed under the MIT License (see LICENSE file).

Roadmap

Completed โœ…

  • Core overlap studies (SMA, EMA, DEMA, TEMA, WMA, KAMA, etc.)
  • Momentum indicators (RSI, MACD, STOCH, ADX, etc.)
  • Volume indicators (OBV, AD, ADOSC)
  • Volatility indicators (NATR, TRANGE)
  • Pattern recognition (60+ candlestick patterns)
  • Cycle indicators (Hilbert Transform functions)
  • Statistical functions
  • Math operators
  • Price transforms
  • Comprehensive test framework
  • Performance benchmarking tools
  • Multiple backend support (NumPy, Numba)

In Progress ๐Ÿšง

  • Additional performance optimizations
  • Extended documentation and examples
  • More comprehensive benchmarks

Future Plans ๐Ÿ“‹

  • Real-time streaming data support
  • Integration with popular data providers
  • Interactive visualization tools
  • Additional optimization backends

Support

For issues, questions, or contributions, please visit: https://github.com/houseofai/numta/issues

Citation

If you use this library in your research or project, please cite:

@software{numta,
  title={numta: NumPy-based Technical Analysis Library},
  author={numta contributors},
  url={https://github.com/houseofai/numta},
  year={2025}
}

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

numta-0.1.1.tar.gz (145.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

numta-0.1.1-py3-none-any.whl (114.7 kB view details)

Uploaded Python 3

File details

Details for the file numta-0.1.1.tar.gz.

File metadata

  • Download URL: numta-0.1.1.tar.gz
  • Upload date:
  • Size: 145.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for numta-0.1.1.tar.gz
Algorithm Hash digest
SHA256 3c411ad2e9d2e4aac9b1be934369834393d61c86b0cc13fbf55fec88d9d347e8
MD5 a6c2c8ceefdc389f81ceb93a6bbc527b
BLAKE2b-256 a95b01e5a8eeb691e8b54f21e9ccceb8fb9fe9e5aee0f43cdca428ff36be934d

See more details on using hashes here.

Provenance

The following attestation bundles were made for numta-0.1.1.tar.gz:

Publisher: publish-to-pypi.yml on houseofai/numta

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file numta-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: numta-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 114.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for numta-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 0da4403317633327e623df90ce5e8de421956608cef8e5d8ab67c97176e92ebb
MD5 53de1af81e92ed7c22abb072b7cff690
BLAKE2b-256 8da57932495f7b0b734fd32cf0aea7977fda369c5da26b9ccf5590fbe352f339

See more details on using hashes here.

Provenance

The following attestation bundles were made for numta-0.1.1-py3-none-any.whl:

Publisher: publish-to-pypi.yml on houseofai/numta

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page