Skip to main content

pyvsmc

Python Version License: MIT PyPI version Tests Type Checked Ruff

Ultra-fast, fully vectorized market structure & Smart Money Concepts (SMC) for Python.

pyvsmc provides pure NumPy + Polars implementations of the most widely used SMC / ICT concepts — Fair Value Gaps, fractal swings, Break of Structure (BOS), Change of Character (CHOCH), and Order Blocks — with zero Python for-loops over time-series, strict typing, and a clean Polars plugin.


Features

Module Concept Key Function
fvg Fair Value Gap / Imbalance detect_fvg()
swings Fractal Swing Highs & Lows detect_swings()
structure BOS & CHOCH Engine detect_structure()
order_blocks Order Block Zones detect_order_blocks()
polars_ext Polars .smc namespace df.smc.add_all()
  • Performance: 100% vectorized (NumPy / Polars vector expressions). No .iterrows(), .apply(), or Python loops over bars. Handles 100k+ candles in milliseconds.
  • Type Safety: Strict mypy — all public APIs are fully typed with Google-style docstrings.
  • Polars Native: Optional pl.DataFrame.smc.* namespace + add_smc_columns() helper.
  • Tested: Comprehensive pytest suite covering normal, edge (empty, flat, NaN, length < 3), and benchmark cases.

Installation

pip install pyvsmc

With Polars (recommended):

pip install "pyvsmc[dev]"   # includes polars, pytest, ruff, mypy
# or
pip install pyvsmc polars

From source:

git clone https://github.com/Khaymat/pyvsmc
cd pyvsmc
pip install -e ".[dev]"

Requirements: Python >= 3.10, numpy>=1.24.0, polars>=0.20.0 (optional but recommended).


Quickstart

NumPy API

import numpy as np
import pyvsmc as smc

# OHLC arrays (float)
high  = np.array([10.0, 11.2, 10.8, 12.5, 11.0, 13.0])
low   = np.array([ 9.5,  9.8, 10.0, 11.8, 10.5, 12.2])
close = np.array([10.0, 10.5, 10.2, 12.2, 11.1, 12.8])
open_ = np.array([ 9.8, 10.0, 10.4, 11.0, 11.5, 12.0])

# 1. Fair Value Gaps (with mitigation tracking)
fvg = smc.detect_fvg(high, low, min_gap_size=0.3, compute_mitigation=True)
print(fvg.bullish)          # boolean mask
print(fvg.bullish_upper)    # upper boundary (Low[i])
print(fvg.mitigated)        # has price revisited the gap?

# 2. Fractal Swings
swings = smc.detect_swings(high, low, window_size=2)
print(swings.swing_high)       # True where High[i] == max(window)
print(swings.swing_high_price)

# 3. Market Structure — BOS & CHOCH
structure = smc.detect_structure(high, low, close, window_size=2)
print(structure.bos_bullish)    # continuation breaks
print(structure.choch_bearish)  # reversal breaks
print(structure.trend)          # 1=bull, -1=bear, 0=neutral

# 4. Order Blocks
obs = smc.detect_order_blocks(open_, high, low, close, lookback=5)
print(obs.bullish_ob)  # True at the bearish candle before a bullish impulse
print(obs.ob_high, obs.ob_low)

Polars API

import polars as pl
import pyvsmc  # registers .smc namespace

df = pl.DataFrame({
    "open":  open_,
    "high":  high,
    "low":   low,
    "close": close,
    "volume": [100, 120, 80, 200, 150, 180],
})

# Functional helper — adds all SMC columns at once
from pyvsmc.polars_ext import add_smc_columns
df = add_smc_columns(df, window_size=2, fvg_mitigation=True)

# Or via the .smc namespace (more granular)
df = pl.DataFrame({"open": open_, "high": high, "low": low, "close": close})
df = df.smc.add_all(window_size=2, ob_lookback=10)
df = df.smc.fvg(min_gap_size=0.5)
df = df.smc.swings(window_size=2)
df = df.smc.structure(window_size=2)
df = df.smc.order_blocks(lookback=5)

print(df)

Re-using Swings in Structure

from pyvsmc.swings import detect_swings
from pyvsmc.structure import detect_structure

swings = detect_swings(high, low, window_size=3)
structure = detect_structure(
    high, low, close,
    swing_high=swings.swing_high,
    swing_low=swings.swing_low,
)

API Reference

detect_fvg(high, low, min_gap_size=None, min_gap_size_pct=None, *, compute_mitigation=False)

Detects 3-candle Fair Value Gaps.

  • Bullish FVG: Low[i] > High[i-2] — gap zone [High[i-2], Low[i]]
  • Bearish FVG: High[i] < Low[i-2] — gap zone [High[i], Low[i-2]]

Returns FVGResult with bullish, bearish, bullish_upper/lower, bearish_upper/lower, gap_size, gap_size_pct, mitigated, mitigated_index.

detect_swings(high, low, window_size=2)

Fractal swing detection. High[i] == max(High[i-N:i+N+1]), Low[i] == min(Low[i-N:i+N+1]). Returns SwingResult.

detect_structure(high, low, close, window_size=2, *, swing_high=None, swing_low=None)

BOS (continuation) vs CHOCH (reversal) classification with trend tracking. Returns StructureResult with bos_bullish/bearish, choch_bullish/bearish, bos_level, choch_level, trend.

detect_order_blocks(open_, high, low, close, *, lookback=10, ...)

Finds last opposing candle before FVG/BOS impulses. Returns OrderBlockResult with bullish_ob/bearish_ob, ob_high/low, validated_index, impulse_type.

All functions also have *_polars(df, ...) variants and are available via df.smc.*.


Testing

pip install -e ".[dev]"
pytest -v
pytest --cov=pyvsmc --cov-report=term-missing

Run type checks and lint:

mypy src/pyvsmc
ruff check src/pyvsmc tests

Project Structure

pyvsmc/
├── pyproject.toml
├── README.md
├── src/pyvsmc/
│   ├── __init__.py
│   ├── py.typed
│   ├── fvg.py
│   ├── swings.py
│   ├── structure.py
│   ├── order_blocks.py
│   └── polars_ext.py
└── tests/
    ├── test_fvg.py
    ├── test_swings.py
    ├── test_structure.py
    ├── test_order_blocks.py
    └── test_polars_ext.py

Performance Notes

  • All indicators use numpy.lib.stride_tricks.sliding_window_view, np.maximum.accumulate, broadcasting, and chunked evaluation — no Python loops over bars.
  • The single exception is the BOS/CHOCH trend tracker, which requires sequential state. It is JIT-compiled with numba when available and falls back to a single O(n) scan otherwise.
  • Benchmark: ~100k candles — FVG < 10ms, swings < 20ms, structure < 30ms (CPython 3.11, NumPy 1.26).

Financial & Legal Disclaimer

IMPORTANT — PLEASE READ CAREFULLY

pyvsmc is an open-source analytics and research library. It is provided solely for educational, informational, and research purposes.

  • Not Financial Advice. Nothing in this library, its documentation, examples, or outputs constitutes financial, investment, trading, or other professional advice. No recommendation to buy, sell, or hold any financial instrument is made or implied.
  • No Warranty of Accuracy or Fitness. Market structure and Smart Money Concepts are interpretive frameworks; their definitions vary across practitioners. The library implements one set of rules that may not match your trading methodology. Outputs may be incorrect, incomplete, or inappropriate for your use case.
  • Use at Your Own Risk. Trading and investing involve substantial risk of loss, including loss of principal. Past simulated or historical performance is not indicative of future results. You are solely responsible for your own trading decisions, risk management, and compliance with applicable laws and regulations.
  • No Liability. To the fullest extent permitted by law, the authors, contributors, and distributors of pyvsmc disclaim all liability for any loss, damage, cost, or expense arising directly or indirectly from use of this software.
  • Do Your Own Research (DYOR). Always validate any signal or analysis with independent research, additional data sources, and, where appropriate, advice from a qualified professional.

By using this software you acknowledge that you have read, understood, and agree to this disclaimer.


License

MIT License — see LICENSE for details.

Copyright (c) 2026 pyvsmc contributors.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Contributing

Issues and pull requests are welcome. Please run ruff, mypy, and pytest before submitting.

Acknowledgements

Built with NumPy and Polars. SMC concepts as described by the broader ICT / Smart Money community.

Download files

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

Source Distribution

pyvsmc-0.3.0.tar.gz (45.8 kB view details)

Uploaded Source

Built Distribution

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

pyvsmc-0.3.0-py3-none-any.whl (38.0 kB view details)

Uploaded Python 3

File details

Details for the file pyvsmc-0.3.0.tar.gz.

File metadata

  • Download URL: pyvsmc-0.3.0.tar.gz
  • Upload date:
  • Size: 45.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.11.5

File hashes

Hashes for pyvsmc-0.3.0.tar.gz
Algorithm Hash digest
SHA256 0d4c2072707bc254c125b3d2f1d97205310c2a11c8def77bee6ac799f92688a1
MD5 4524caf5a434471248bb9f7403dacead
BLAKE2b-256 1e72db43fa5d06fbd460c4caced131a0ea01e2a6f763cfecc842b7caaa3046a0

See more details on using hashes here.

File details

Details for the file pyvsmc-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: pyvsmc-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 38.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.11.5

File hashes

Hashes for pyvsmc-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 58611107f631c80a6d6da07df7363d770a0dde038fecf50788e11855bbc68a37
MD5 4f5449fe3e1d5cf13643afbba9bc06ee
BLAKE2b-256 486a2b00a0316f7458b11ad6272fd9a6b15bd3cf8077c73cb1703eaef561081e

See more details on using hashes here.

Release history Release notifications | RSS feed

0.3.7

2 files

0.3.6

2 files

0.3.5

2 files

0.3.4

2 files

0.3.3

2 files

0.3.2

2 files

0.3.1

2 files

This release

0.3.0 This release

2 files

0.2.0

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page