oisigma-drawdown 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- oisigma_drawdown-0.1.0/LICENSE +21 -0
- oisigma_drawdown-0.1.0/PKG-INFO +106 -0
- oisigma_drawdown-0.1.0/README.md +81 -0
- oisigma_drawdown-0.1.0/pyproject.toml +49 -0
- oisigma_drawdown-0.1.0/setup.cfg +4 -0
- oisigma_drawdown-0.1.0/src/oisigma_drawdown/__init__.py +33 -0
- oisigma_drawdown-0.1.0/src/oisigma_drawdown/histogram.py +310 -0
- oisigma_drawdown-0.1.0/src/oisigma_drawdown.egg-info/PKG-INFO +106 -0
- oisigma_drawdown-0.1.0/src/oisigma_drawdown.egg-info/SOURCES.txt +11 -0
- oisigma_drawdown-0.1.0/src/oisigma_drawdown.egg-info/dependency_links.txt +1 -0
- oisigma_drawdown-0.1.0/src/oisigma_drawdown.egg-info/entry_points.txt +2 -0
- oisigma_drawdown-0.1.0/src/oisigma_drawdown.egg-info/top_level.txt +1 -0
- oisigma_drawdown-0.1.0/tests/test_histogram.py +20 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Oisigma (https://oisigma.com)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: oisigma-drawdown
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Descriptive drawdown episode distribution, depth percentiles, time-under-water statistics, and severity histogram (Python companion to Drawdown Severity Histogram [oisigma] on TradingView).
|
|
5
|
+
Author-email: Oisigma <m@oisigma.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: TradingView Indicator, https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/
|
|
8
|
+
Project-URL: Oisigma Homepage, https://oisigma.com
|
|
9
|
+
Project-URL: Empirical Proof, https://oisigma.com/proof
|
|
10
|
+
Project-URL: Working Paper, https://oisigma.com/paper
|
|
11
|
+
Project-URL: Research Blog, https://oisigma.com/blog
|
|
12
|
+
Keywords: drawdown,drawdown-histogram,time-under-water,tradingview,risk-analysis,quantitative-finance,oisigma
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
21
|
+
Requires-Python: >=3.8
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# Drawdown Severity Histogram `[oisigma]` — Python Companion & Episode Distribution Toolkit
|
|
27
|
+
|
|
28
|
+
[](https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/)
|
|
29
|
+
[](https://oisigma.com)
|
|
30
|
+
[](https://opensource.org/licenses/MIT)
|
|
31
|
+
|
|
32
|
+
Most drawdown information on a chart is a single number: how far price is from its peak right now. That number is hard to judge on its own. Is a 7% drawdown a routine dip or a rare event? Historically, how deep do drawdowns on an instrument go, and how long do they take to recover?
|
|
33
|
+
|
|
34
|
+
**`oisigma-drawdown`** is the open-source Python companion to the free public TradingView indicator **[Drawdown Severity Histogram [oisigma]](https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/)** developed by **[Oisigma](https://oisigma.com)**.
|
|
35
|
+
|
|
36
|
+
It scans a price series, identifies every completed drawdown episode, bins those episodes by maximum percentage depth, and computes **depth percentiles** (`median`, `90th`, `95th`, `deepest`) and **time-under-water duration statistics**—while tracking the currently open, unfinished drawdown separately so it does not bias the completed counts.
|
|
37
|
+
|
|
38
|
+
> **Important:** This is a **descriptive tool, not a predictive one**. It measures what has already happened on the loaded history. It does not forecast price, does not generate buy or sell signals, and says nothing about whether a current drawdown will deepen or reverse.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## Live TradingView Indicator (Free Community Script)
|
|
43
|
+
|
|
44
|
+
To plot the histogram and summary table directly on any TradingView chart:
|
|
45
|
+
* **[Drawdown Severity Histogram [oisigma] on TradingView](https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/)**
|
|
46
|
+
|
|
47
|
+
For Oisigma's research on calibrated expected ranges and empirical volatility band audits across 97 years of S&P 500 data and 40 cross-asset instruments:
|
|
48
|
+
* **[Oisigma Home (`oisigma.com`)](https://oisigma.com)**
|
|
49
|
+
* **[Empirical Proof (`oisigma.com/proof`)](https://oisigma.com/proof)**
|
|
50
|
+
* **[Working Paper (`oisigma.com/paper`)](https://oisigma.com/paper)**
|
|
51
|
+
* **[Oisigma Research Blog (`oisigma.com/blog`)](https://oisigma.com/blog)**
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## How It Counts Drawdown Episodes
|
|
56
|
+
|
|
57
|
+
1. **Episode Definition:** An episode begins at a peak, runs through its lowest point, and ends when price sets a new peak. At that moment its maximum depth (%) and its duration in bars (*time under water*) are recorded, and a new episode begins.
|
|
58
|
+
2. **Completed vs. Open Drawdown Separation:** Only completed episodes enter the histogram and the percentile statistics. The drawdown that is still open is tracked separately and highlighted in its provisional depth bin, because it has not finished yet and including it would bias the counts.
|
|
59
|
+
3. **Minimum Depth Floor (`min_depth_pct`, default `1.0%`):** Episodes shallower than 1% are excluded by default so trivial one-bar dips below a peak do not dominate the shallowest bucket and distort the median.
|
|
60
|
+
4. **Close vs. High/Low Consistency:** By default, closing prices are used for both peaks and troughs for an internally consistent series. When High/Low mode is used, on a bar that sets a new peak, the intrabar order of high and low is unknown, so that bar's low is not counted toward the next trough.
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## Installation
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
pip install oisigma-drawdown
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Quickstart in Python
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
import math
|
|
76
|
+
from oisigma_drawdown import analyze_drawdown_episodes
|
|
77
|
+
|
|
78
|
+
# Example price series
|
|
79
|
+
closes = [100.0 * math.exp(0.0015 * i - 0.018 * math.sin(i * 0.15)) for i in range(500)]
|
|
80
|
+
|
|
81
|
+
summary = analyze_drawdown_episodes(
|
|
82
|
+
closes,
|
|
83
|
+
bin_width_pct=5.0, # 5% depth buckets
|
|
84
|
+
min_depth_pct=1.0, # Ignore trivial dips shallower than 1%
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
print(summary.format_report())
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## Limitations to Know Before Using It
|
|
93
|
+
|
|
94
|
+
* **Statistics describe the loaded history only:** A short price series gives unreliable percentiles, so load as much historical data as possible.
|
|
95
|
+
* **Deep drawdowns are rare:** Even with long history, the right-hand tail bins and the 95th percentile rest on a small number of completed episodes.
|
|
96
|
+
* **Open drawdown comparison is provisional:** Compare percentiles with the open drawdown's *deepest point so far*, bearing in mind an unfinished drawdown can still deepen before recovering to a new peak.
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## Related Oisigma Research & Links
|
|
101
|
+
|
|
102
|
+
* **[Drawdown Severity Histogram [oisigma] — TradingView Script](https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/)**
|
|
103
|
+
* **[Oisigma — Calibrated Expected Range Indicator for TradingView](https://oisigma.com)**
|
|
104
|
+
* **[How It Works (`oisigma.com/how-it-works`)](https://oisigma.com/how-it-works)**
|
|
105
|
+
* **[Empirical Proof (`oisigma.com/proof`)](https://oisigma.com/proof)**
|
|
106
|
+
* **[Working Paper (`oisigma.com/paper`)](https://oisigma.com/paper)**
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# Drawdown Severity Histogram `[oisigma]` — Python Companion & Episode Distribution Toolkit
|
|
2
|
+
|
|
3
|
+
[](https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/)
|
|
4
|
+
[](https://oisigma.com)
|
|
5
|
+
[](https://opensource.org/licenses/MIT)
|
|
6
|
+
|
|
7
|
+
Most drawdown information on a chart is a single number: how far price is from its peak right now. That number is hard to judge on its own. Is a 7% drawdown a routine dip or a rare event? Historically, how deep do drawdowns on an instrument go, and how long do they take to recover?
|
|
8
|
+
|
|
9
|
+
**`oisigma-drawdown`** is the open-source Python companion to the free public TradingView indicator **[Drawdown Severity Histogram [oisigma]](https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/)** developed by **[Oisigma](https://oisigma.com)**.
|
|
10
|
+
|
|
11
|
+
It scans a price series, identifies every completed drawdown episode, bins those episodes by maximum percentage depth, and computes **depth percentiles** (`median`, `90th`, `95th`, `deepest`) and **time-under-water duration statistics**—while tracking the currently open, unfinished drawdown separately so it does not bias the completed counts.
|
|
12
|
+
|
|
13
|
+
> **Important:** This is a **descriptive tool, not a predictive one**. It measures what has already happened on the loaded history. It does not forecast price, does not generate buy or sell signals, and says nothing about whether a current drawdown will deepen or reverse.
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Live TradingView Indicator (Free Community Script)
|
|
18
|
+
|
|
19
|
+
To plot the histogram and summary table directly on any TradingView chart:
|
|
20
|
+
* **[Drawdown Severity Histogram [oisigma] on TradingView](https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/)**
|
|
21
|
+
|
|
22
|
+
For Oisigma's research on calibrated expected ranges and empirical volatility band audits across 97 years of S&P 500 data and 40 cross-asset instruments:
|
|
23
|
+
* **[Oisigma Home (`oisigma.com`)](https://oisigma.com)**
|
|
24
|
+
* **[Empirical Proof (`oisigma.com/proof`)](https://oisigma.com/proof)**
|
|
25
|
+
* **[Working Paper (`oisigma.com/paper`)](https://oisigma.com/paper)**
|
|
26
|
+
* **[Oisigma Research Blog (`oisigma.com/blog`)](https://oisigma.com/blog)**
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## How It Counts Drawdown Episodes
|
|
31
|
+
|
|
32
|
+
1. **Episode Definition:** An episode begins at a peak, runs through its lowest point, and ends when price sets a new peak. At that moment its maximum depth (%) and its duration in bars (*time under water*) are recorded, and a new episode begins.
|
|
33
|
+
2. **Completed vs. Open Drawdown Separation:** Only completed episodes enter the histogram and the percentile statistics. The drawdown that is still open is tracked separately and highlighted in its provisional depth bin, because it has not finished yet and including it would bias the counts.
|
|
34
|
+
3. **Minimum Depth Floor (`min_depth_pct`, default `1.0%`):** Episodes shallower than 1% are excluded by default so trivial one-bar dips below a peak do not dominate the shallowest bucket and distort the median.
|
|
35
|
+
4. **Close vs. High/Low Consistency:** By default, closing prices are used for both peaks and troughs for an internally consistent series. When High/Low mode is used, on a bar that sets a new peak, the intrabar order of high and low is unknown, so that bar's low is not counted toward the next trough.
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## Installation
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install oisigma-drawdown
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## Quickstart in Python
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
import math
|
|
51
|
+
from oisigma_drawdown import analyze_drawdown_episodes
|
|
52
|
+
|
|
53
|
+
# Example price series
|
|
54
|
+
closes = [100.0 * math.exp(0.0015 * i - 0.018 * math.sin(i * 0.15)) for i in range(500)]
|
|
55
|
+
|
|
56
|
+
summary = analyze_drawdown_episodes(
|
|
57
|
+
closes,
|
|
58
|
+
bin_width_pct=5.0, # 5% depth buckets
|
|
59
|
+
min_depth_pct=1.0, # Ignore trivial dips shallower than 1%
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
print(summary.format_report())
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Limitations to Know Before Using It
|
|
68
|
+
|
|
69
|
+
* **Statistics describe the loaded history only:** A short price series gives unreliable percentiles, so load as much historical data as possible.
|
|
70
|
+
* **Deep drawdowns are rare:** Even with long history, the right-hand tail bins and the 95th percentile rest on a small number of completed episodes.
|
|
71
|
+
* **Open drawdown comparison is provisional:** Compare percentiles with the open drawdown's *deepest point so far*, bearing in mind an unfinished drawdown can still deepen before recovering to a new peak.
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## Related Oisigma Research & Links
|
|
76
|
+
|
|
77
|
+
* **[Drawdown Severity Histogram [oisigma] — TradingView Script](https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/)**
|
|
78
|
+
* **[Oisigma — Calibrated Expected Range Indicator for TradingView](https://oisigma.com)**
|
|
79
|
+
* **[How It Works (`oisigma.com/how-it-works`)](https://oisigma.com/how-it-works)**
|
|
80
|
+
* **[Empirical Proof (`oisigma.com/proof`)](https://oisigma.com/proof)**
|
|
81
|
+
* **[Working Paper (`oisigma.com/paper`)](https://oisigma.com/paper)**
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "oisigma-drawdown"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Descriptive drawdown episode distribution, depth percentiles, time-under-water statistics, and severity histogram (Python companion to Drawdown Severity Histogram [oisigma] on TradingView)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [
|
|
13
|
+
{name = "Oisigma", email = "m@oisigma.com"}
|
|
14
|
+
]
|
|
15
|
+
keywords = [
|
|
16
|
+
"drawdown",
|
|
17
|
+
"drawdown-histogram",
|
|
18
|
+
"time-under-water",
|
|
19
|
+
"tradingview",
|
|
20
|
+
"risk-analysis",
|
|
21
|
+
"quantitative-finance",
|
|
22
|
+
"oisigma"
|
|
23
|
+
]
|
|
24
|
+
classifiers = [
|
|
25
|
+
"Development Status :: 4 - Beta",
|
|
26
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
27
|
+
"Intended Audience :: Science/Research",
|
|
28
|
+
"License :: OSI Approved :: MIT License",
|
|
29
|
+
"Operating System :: OS Independent",
|
|
30
|
+
"Programming Language :: Python :: 3",
|
|
31
|
+
"Topic :: Office/Business :: Financial :: Investment",
|
|
32
|
+
"Topic :: Scientific/Engineering :: Mathematics"
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[project.urls]
|
|
36
|
+
"TradingView Indicator" = "https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/"
|
|
37
|
+
"Oisigma Homepage" = "https://oisigma.com"
|
|
38
|
+
"Empirical Proof" = "https://oisigma.com/proof"
|
|
39
|
+
"Working Paper" = "https://oisigma.com/paper"
|
|
40
|
+
"Research Blog" = "https://oisigma.com/blog"
|
|
41
|
+
|
|
42
|
+
[project.scripts]
|
|
43
|
+
oisigma-drawdown = "oisigma_drawdown.histogram:main"
|
|
44
|
+
|
|
45
|
+
[tool.setuptools.package-dir]
|
|
46
|
+
"" = "src"
|
|
47
|
+
|
|
48
|
+
[tool.setuptools.packages.find]
|
|
49
|
+
where = ["src"]
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""
|
|
2
|
+
oisigma-drawdown
|
|
3
|
+
================
|
|
4
|
+
|
|
5
|
+
Descriptive drawdown severity histogram, completed episode depth percentiles,
|
|
6
|
+
time-under-water statistics, and open-drawdown tracking.
|
|
7
|
+
|
|
8
|
+
Python companion to the free public TradingView indicator:
|
|
9
|
+
Drawdown Severity Histogram [oisigma]
|
|
10
|
+
https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/
|
|
11
|
+
|
|
12
|
+
Important: This is a descriptive tool, not a predictive one. It measures what has
|
|
13
|
+
already happened on the loaded history. It does not forecast price, does not
|
|
14
|
+
generate buy or sell signals, and says nothing about whether the current drawdown
|
|
15
|
+
will deepen or reverse.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from .histogram import (
|
|
19
|
+
CompletedDrawdownEpisode,
|
|
20
|
+
OpenDrawdownState,
|
|
21
|
+
HistogramBin,
|
|
22
|
+
DrawdownSeveritySummary,
|
|
23
|
+
analyze_drawdown_episodes,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
__version__ = "0.1.0"
|
|
27
|
+
__all__ = [
|
|
28
|
+
"CompletedDrawdownEpisode",
|
|
29
|
+
"OpenDrawdownState",
|
|
30
|
+
"HistogramBin",
|
|
31
|
+
"DrawdownSeveritySummary",
|
|
32
|
+
"analyze_drawdown_episodes",
|
|
33
|
+
]
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Drawdown Severity Histogram [oisigma] - Core Episode & Percentile Engine
|
|
3
|
+
========================================================================
|
|
4
|
+
|
|
5
|
+
Mirrors the methodology of the public TradingView indicator:
|
|
6
|
+
https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/
|
|
7
|
+
|
|
8
|
+
How It Counts:
|
|
9
|
+
- An episode begins at a peak, runs through its lowest point, and ends when price
|
|
10
|
+
sets a new peak. At that moment its maximum depth (%) and its duration in bars
|
|
11
|
+
(time under water) are recorded, and a new episode begins.
|
|
12
|
+
- Only completed episodes enter the histogram and the percentile statistics.
|
|
13
|
+
- The drawdown that is still open is tracked separately so that unfinished episodes
|
|
14
|
+
do not bias the completed counts.
|
|
15
|
+
- Episodes shallower than `min_depth_pct` (default 1.0%) are excluded so trivial dips
|
|
16
|
+
do not dominate the shallowest bucket.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import math
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from typing import List, Optional, Sequence, Tuple
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class CompletedDrawdownEpisode:
|
|
26
|
+
"""A single completed peak-to-trough-to-new-peak drawdown episode."""
|
|
27
|
+
peak_index: int
|
|
28
|
+
trough_index: int
|
|
29
|
+
recovery_index: int
|
|
30
|
+
peak_price: float
|
|
31
|
+
trough_price: float
|
|
32
|
+
max_depth_pct: float
|
|
33
|
+
time_under_water_bars: int
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class OpenDrawdownState:
|
|
38
|
+
"""Tracks the currently open (unfinished) drawdown separately from completed episodes."""
|
|
39
|
+
peak_index: int
|
|
40
|
+
peak_price: float
|
|
41
|
+
current_price: float
|
|
42
|
+
current_distance_pct: float
|
|
43
|
+
deepest_pct_so_far: float
|
|
44
|
+
bars_under_water: int
|
|
45
|
+
provisional_bin_index: Optional[int]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class HistogramBin:
|
|
50
|
+
"""A single percentage depth bin in the drawdown severity histogram."""
|
|
51
|
+
bin_index: int
|
|
52
|
+
depth_low_pct: float
|
|
53
|
+
depth_high_pct: float
|
|
54
|
+
count: int
|
|
55
|
+
cumulative_at_least_count: int
|
|
56
|
+
cumulative_at_least_share_pct: float
|
|
57
|
+
contains_open_drawdown_deepest: bool
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class DrawdownSeveritySummary:
|
|
62
|
+
"""Complete descriptive summary of completed episodes, histogram bins, and open drawdown."""
|
|
63
|
+
completed_count: int
|
|
64
|
+
min_depth_floor_pct: float
|
|
65
|
+
bin_width_pct: float
|
|
66
|
+
median_depth_pct: Optional[float]
|
|
67
|
+
p90_depth_pct: Optional[float]
|
|
68
|
+
p95_depth_pct: Optional[float]
|
|
69
|
+
deepest_episode_pct: Optional[float]
|
|
70
|
+
median_time_under_water_bars: Optional[float]
|
|
71
|
+
p90_time_under_water_bars: Optional[float]
|
|
72
|
+
longest_time_under_water_bars: Optional[int]
|
|
73
|
+
episodes: List[CompletedDrawdownEpisode]
|
|
74
|
+
bins: List[HistogramBin]
|
|
75
|
+
open_drawdown: OpenDrawdownState
|
|
76
|
+
|
|
77
|
+
def format_report(self) -> str:
|
|
78
|
+
lines = [
|
|
79
|
+
"==========================================================================",
|
|
80
|
+
" DRAWDOWN SEVERITY HISTOGRAM [oisigma] - DESCRIPTIVE SUMMARY",
|
|
81
|
+
" TradingView Script: https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/",
|
|
82
|
+
" Homepage : https://oisigma.com",
|
|
83
|
+
"==========================================================================",
|
|
84
|
+
f"Completed Episodes (>= {self.min_depth_floor_pct:.2f}% depth): {self.completed_count}",
|
|
85
|
+
]
|
|
86
|
+
if self.completed_count > 0:
|
|
87
|
+
lines.extend([
|
|
88
|
+
f" - Median Depth : {self.median_depth_pct:.2f}%",
|
|
89
|
+
f" - 90th Percentile Depth : {self.p90_depth_pct:.2f}%",
|
|
90
|
+
f" - 95th Percentile Depth : {self.p95_depth_pct:.2f}%",
|
|
91
|
+
f" - Deepest Episode : {self.deepest_episode_pct:.2f}%",
|
|
92
|
+
f" - Median Time Under Water : {self.median_time_under_water_bars:.1f} bars",
|
|
93
|
+
f" - 90th Pct Time Under Water: {self.p90_time_under_water_bars:.1f} bars",
|
|
94
|
+
f" - Longest Time Under Water : {self.longest_time_under_water_bars} bars",
|
|
95
|
+
])
|
|
96
|
+
od = self.open_drawdown
|
|
97
|
+
lines.extend([
|
|
98
|
+
"--------------------------------------------------------------------------",
|
|
99
|
+
"Open (Unfinished) Drawdown (Tracked Separately):",
|
|
100
|
+
f" - Current Distance from Peak : {od.current_distance_pct:.2f}%",
|
|
101
|
+
f" - Deepest Point So Far : {od.deepest_pct_so_far:.2f}%",
|
|
102
|
+
f" - Bars Under Water So Far : {od.bars_under_water} bars",
|
|
103
|
+
"--------------------------------------------------------------------------",
|
|
104
|
+
"Histogram Bins (Completed Episodes by Maximum Depth):",
|
|
105
|
+
])
|
|
106
|
+
for b in self.bins:
|
|
107
|
+
marker = " <-- [OPEN DRAWDOWN DEEPEST]" if b.contains_open_drawdown_deepest else ""
|
|
108
|
+
lines.append(
|
|
109
|
+
f" [{b.depth_low_pct:5.1f}% to {b.depth_high_pct:5.1f}%] : "
|
|
110
|
+
f"{b.count:4d} episodes (>= {b.depth_low_pct:.1f}%: {b.cumulative_at_least_count} / "
|
|
111
|
+
f"{b.cumulative_at_least_share_pct:5.1f}%){marker}"
|
|
112
|
+
)
|
|
113
|
+
lines.extend([
|
|
114
|
+
"==========================================================================",
|
|
115
|
+
"Important: This is a descriptive tool, not a predictive one. It measures",
|
|
116
|
+
"what has already happened on the loaded history and does not forecast price",
|
|
117
|
+
"or generate buy or sell signals.",
|
|
118
|
+
])
|
|
119
|
+
return "\n".join(lines)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _percentile(sorted_vals: Sequence[float], q: float) -> Optional[float]:
|
|
123
|
+
"""Compute linear-interpolated percentile q in [0, 100] on a sorted sequence."""
|
|
124
|
+
if not sorted_vals:
|
|
125
|
+
return None
|
|
126
|
+
n = len(sorted_vals)
|
|
127
|
+
if n == 1:
|
|
128
|
+
return float(sorted_vals[0])
|
|
129
|
+
pos = (q / 100.0) * (n - 1)
|
|
130
|
+
lo = int(math.floor(pos))
|
|
131
|
+
hi = int(math.ceil(pos))
|
|
132
|
+
if lo == hi:
|
|
133
|
+
return float(sorted_vals[lo])
|
|
134
|
+
weight = pos - lo
|
|
135
|
+
return float(sorted_vals[lo] * (1.0 - weight) + sorted_vals[hi] * weight)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def analyze_drawdown_episodes(
|
|
139
|
+
closes: Sequence[float],
|
|
140
|
+
bin_width_pct: float = 5.0,
|
|
141
|
+
min_depth_pct: float = 1.0,
|
|
142
|
+
highs: Optional[Sequence[float]] = None,
|
|
143
|
+
lows: Optional[Sequence[float]] = None,
|
|
144
|
+
) -> DrawdownSeveritySummary:
|
|
145
|
+
"""
|
|
146
|
+
Scan a price history, identify every completed drawdown episode, bin completed
|
|
147
|
+
episodes by maximum percentage depth, and compute depth and time-under-water
|
|
148
|
+
percentiles while tracking the open drawdown separately.
|
|
149
|
+
|
|
150
|
+
Parameters
|
|
151
|
+
----------
|
|
152
|
+
closes : Sequence[float]
|
|
153
|
+
Closing prices (used for both peaks and troughs unless `highs` and `lows` are provided).
|
|
154
|
+
bin_width_pct : float, default 5.0
|
|
155
|
+
Width of each depth bucket in percentage points (default 5%).
|
|
156
|
+
min_depth_pct : float, default 1.0
|
|
157
|
+
Episodes shallower than this threshold (%) are excluded from counts and statistics.
|
|
158
|
+
highs : Optional[Sequence[float]]
|
|
159
|
+
Optional bar highs for High/Low mode. On a bar that sets a new peak, its low is not
|
|
160
|
+
counted toward the next trough (since intrabar high/low order is unknown).
|
|
161
|
+
lows : Optional[Sequence[float]]
|
|
162
|
+
Optional bar lows for High/Low mode.
|
|
163
|
+
"""
|
|
164
|
+
if len(closes) < 2:
|
|
165
|
+
raise ValueError("closes must contain at least 2 bars.")
|
|
166
|
+
if bin_width_pct <= 0:
|
|
167
|
+
raise ValueError("bin_width_pct must be > 0.")
|
|
168
|
+
if min_depth_pct < 0:
|
|
169
|
+
raise ValueError("min_depth_pct must be >= 0.")
|
|
170
|
+
|
|
171
|
+
use_hl = highs is not None and lows is not None
|
|
172
|
+
if use_hl and (len(highs) != len(closes) or len(lows) != len(closes)):
|
|
173
|
+
raise ValueError("highs and lows must match the length of closes.")
|
|
174
|
+
|
|
175
|
+
peak_price = float(highs[0] if use_hl else closes[0])
|
|
176
|
+
peak_idx = 0
|
|
177
|
+
trough_price = peak_price
|
|
178
|
+
trough_idx = 0
|
|
179
|
+
in_drawdown = False
|
|
180
|
+
|
|
181
|
+
completed: List[CompletedDrawdownEpisode] = []
|
|
182
|
+
|
|
183
|
+
for i in range(1, len(closes)):
|
|
184
|
+
bar_peak_candidate = float(highs[i] if use_hl else closes[i])
|
|
185
|
+
bar_trough_candidate = float(lows[i] if use_hl else closes[i])
|
|
186
|
+
|
|
187
|
+
if bar_peak_candidate >= peak_price:
|
|
188
|
+
# Price set a new peak (or matched prior peak)
|
|
189
|
+
if in_drawdown and trough_price < peak_price:
|
|
190
|
+
max_depth = ((peak_price - trough_price) / peak_price) * 100.0
|
|
191
|
+
duration_bars = i - peak_idx
|
|
192
|
+
if max_depth >= min_depth_pct:
|
|
193
|
+
completed.append(
|
|
194
|
+
CompletedDrawdownEpisode(
|
|
195
|
+
peak_index=peak_idx,
|
|
196
|
+
trough_index=trough_idx,
|
|
197
|
+
recovery_index=i,
|
|
198
|
+
peak_price=peak_price,
|
|
199
|
+
trough_price=trough_price,
|
|
200
|
+
max_depth_pct=max_depth,
|
|
201
|
+
time_under_water_bars=duration_bars,
|
|
202
|
+
)
|
|
203
|
+
)
|
|
204
|
+
# Reset peak; on a new-peak bar in High/Low mode, do not count its low toward the next trough
|
|
205
|
+
peak_price = bar_peak_candidate
|
|
206
|
+
peak_idx = i
|
|
207
|
+
trough_price = peak_price
|
|
208
|
+
trough_idx = i
|
|
209
|
+
in_drawdown = False
|
|
210
|
+
else:
|
|
211
|
+
in_drawdown = True
|
|
212
|
+
if bar_trough_candidate < trough_price:
|
|
213
|
+
trough_price = bar_trough_candidate
|
|
214
|
+
trough_idx = i
|
|
215
|
+
|
|
216
|
+
# Open drawdown state at the final bar
|
|
217
|
+
last_idx = len(closes) - 1
|
|
218
|
+
last_price = float(lows[last_idx] if use_hl else closes[last_idx])
|
|
219
|
+
if in_drawdown and peak_price > 0:
|
|
220
|
+
curr_dist_pct = max(0.0, ((peak_price - last_price) / peak_price) * 100.0)
|
|
221
|
+
deepest_open_pct = max(0.0, ((peak_price - trough_price) / peak_price) * 100.0)
|
|
222
|
+
bars_open = last_idx - peak_idx
|
|
223
|
+
else:
|
|
224
|
+
curr_dist_pct = 0.0
|
|
225
|
+
deepest_open_pct = 0.0
|
|
226
|
+
bars_open = 0
|
|
227
|
+
|
|
228
|
+
open_bin_idx: Optional[int] = None
|
|
229
|
+
if deepest_open_pct >= min_depth_pct:
|
|
230
|
+
open_bin_idx = int(math.floor((deepest_open_pct - min_depth_pct) / bin_width_pct))
|
|
231
|
+
|
|
232
|
+
# Build histogram bins
|
|
233
|
+
depths = sorted(ep.max_depth_pct for ep in completed)
|
|
234
|
+
durations = sorted(float(ep.time_under_water_bars) for ep in completed)
|
|
235
|
+
|
|
236
|
+
max_observed_depth = max(depths[-1] if depths else 0.0, deepest_open_pct)
|
|
237
|
+
if max_observed_depth >= min_depth_pct:
|
|
238
|
+
num_bins = int(math.floor((max_observed_depth - min_depth_pct) / bin_width_pct)) + 1
|
|
239
|
+
else:
|
|
240
|
+
num_bins = 1
|
|
241
|
+
|
|
242
|
+
bin_counts = [0] * num_bins
|
|
243
|
+
for ep in completed:
|
|
244
|
+
b_idx = int(math.floor((ep.max_depth_pct - min_depth_pct) / bin_width_pct))
|
|
245
|
+
if 0 <= b_idx < num_bins:
|
|
246
|
+
bin_counts[b_idx] += 1
|
|
247
|
+
|
|
248
|
+
total_completed = len(completed)
|
|
249
|
+
bins: List[HistogramBin] = []
|
|
250
|
+
running_at_least = total_completed
|
|
251
|
+
|
|
252
|
+
for b_idx in range(num_bins):
|
|
253
|
+
lo_pct = min_depth_pct + b_idx * bin_width_pct
|
|
254
|
+
hi_pct = lo_pct + bin_width_pct
|
|
255
|
+
cnt = bin_counts[b_idx]
|
|
256
|
+
share = (running_at_least / total_completed * 100.0) if total_completed > 0 else 0.0
|
|
257
|
+
bins.append(
|
|
258
|
+
HistogramBin(
|
|
259
|
+
bin_index=b_idx,
|
|
260
|
+
depth_low_pct=lo_pct,
|
|
261
|
+
depth_high_pct=hi_pct,
|
|
262
|
+
count=cnt,
|
|
263
|
+
cumulative_at_least_count=running_at_least,
|
|
264
|
+
cumulative_at_least_share_pct=share,
|
|
265
|
+
contains_open_drawdown_deepest=(open_bin_idx == b_idx),
|
|
266
|
+
)
|
|
267
|
+
)
|
|
268
|
+
running_at_least -= cnt
|
|
269
|
+
|
|
270
|
+
open_state = OpenDrawdownState(
|
|
271
|
+
peak_index=peak_idx,
|
|
272
|
+
peak_price=peak_price,
|
|
273
|
+
current_price=last_price,
|
|
274
|
+
current_distance_pct=curr_dist_pct,
|
|
275
|
+
deepest_pct_so_far=deepest_open_pct,
|
|
276
|
+
bars_under_water=bars_open,
|
|
277
|
+
provisional_bin_index=open_bin_idx,
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
return DrawdownSeveritySummary(
|
|
281
|
+
completed_count=total_completed,
|
|
282
|
+
min_depth_floor_pct=min_depth_pct,
|
|
283
|
+
bin_width_pct=bin_width_pct,
|
|
284
|
+
median_depth_pct=_percentile(depths, 50.0),
|
|
285
|
+
p90_depth_pct=_percentile(depths, 90.0),
|
|
286
|
+
p95_depth_pct=_percentile(depths, 95.0),
|
|
287
|
+
deepest_episode_pct=depths[-1] if depths else None,
|
|
288
|
+
median_time_under_water_bars=_percentile(durations, 50.0),
|
|
289
|
+
p90_time_under_water_bars=_percentile(durations, 90.0),
|
|
290
|
+
longest_time_under_water_bars=int(durations[-1]) if durations else None,
|
|
291
|
+
episodes=completed,
|
|
292
|
+
bins=bins,
|
|
293
|
+
open_drawdown=open_state,
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def main() -> None:
|
|
298
|
+
"""Run a demonstration of the Drawdown Severity Histogram on a sample price series."""
|
|
299
|
+
prices = [100.0]
|
|
300
|
+
for i in range(1, 500):
|
|
301
|
+
# Deterministic series with multiple completed drawdown episodes and an open drawdown
|
|
302
|
+
step = 0.0015 - 0.018 * math.sin(i * 0.15) - (0.012 if i > 465 else 0.0)
|
|
303
|
+
prices.append(prices[-1] * math.exp(step))
|
|
304
|
+
|
|
305
|
+
summary = analyze_drawdown_episodes(prices, bin_width_pct=5.0, min_depth_pct=1.0)
|
|
306
|
+
print(summary.format_report())
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
if __name__ == "__main__":
|
|
310
|
+
main()
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: oisigma-drawdown
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Descriptive drawdown episode distribution, depth percentiles, time-under-water statistics, and severity histogram (Python companion to Drawdown Severity Histogram [oisigma] on TradingView).
|
|
5
|
+
Author-email: Oisigma <m@oisigma.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: TradingView Indicator, https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/
|
|
8
|
+
Project-URL: Oisigma Homepage, https://oisigma.com
|
|
9
|
+
Project-URL: Empirical Proof, https://oisigma.com/proof
|
|
10
|
+
Project-URL: Working Paper, https://oisigma.com/paper
|
|
11
|
+
Project-URL: Research Blog, https://oisigma.com/blog
|
|
12
|
+
Keywords: drawdown,drawdown-histogram,time-under-water,tradingview,risk-analysis,quantitative-finance,oisigma
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
21
|
+
Requires-Python: >=3.8
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# Drawdown Severity Histogram `[oisigma]` — Python Companion & Episode Distribution Toolkit
|
|
27
|
+
|
|
28
|
+
[](https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/)
|
|
29
|
+
[](https://oisigma.com)
|
|
30
|
+
[](https://opensource.org/licenses/MIT)
|
|
31
|
+
|
|
32
|
+
Most drawdown information on a chart is a single number: how far price is from its peak right now. That number is hard to judge on its own. Is a 7% drawdown a routine dip or a rare event? Historically, how deep do drawdowns on an instrument go, and how long do they take to recover?
|
|
33
|
+
|
|
34
|
+
**`oisigma-drawdown`** is the open-source Python companion to the free public TradingView indicator **[Drawdown Severity Histogram [oisigma]](https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/)** developed by **[Oisigma](https://oisigma.com)**.
|
|
35
|
+
|
|
36
|
+
It scans a price series, identifies every completed drawdown episode, bins those episodes by maximum percentage depth, and computes **depth percentiles** (`median`, `90th`, `95th`, `deepest`) and **time-under-water duration statistics**—while tracking the currently open, unfinished drawdown separately so it does not bias the completed counts.
|
|
37
|
+
|
|
38
|
+
> **Important:** This is a **descriptive tool, not a predictive one**. It measures what has already happened on the loaded history. It does not forecast price, does not generate buy or sell signals, and says nothing about whether a current drawdown will deepen or reverse.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## Live TradingView Indicator (Free Community Script)
|
|
43
|
+
|
|
44
|
+
To plot the histogram and summary table directly on any TradingView chart:
|
|
45
|
+
* **[Drawdown Severity Histogram [oisigma] on TradingView](https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/)**
|
|
46
|
+
|
|
47
|
+
For Oisigma's research on calibrated expected ranges and empirical volatility band audits across 97 years of S&P 500 data and 40 cross-asset instruments:
|
|
48
|
+
* **[Oisigma Home (`oisigma.com`)](https://oisigma.com)**
|
|
49
|
+
* **[Empirical Proof (`oisigma.com/proof`)](https://oisigma.com/proof)**
|
|
50
|
+
* **[Working Paper (`oisigma.com/paper`)](https://oisigma.com/paper)**
|
|
51
|
+
* **[Oisigma Research Blog (`oisigma.com/blog`)](https://oisigma.com/blog)**
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## How It Counts Drawdown Episodes
|
|
56
|
+
|
|
57
|
+
1. **Episode Definition:** An episode begins at a peak, runs through its lowest point, and ends when price sets a new peak. At that moment its maximum depth (%) and its duration in bars (*time under water*) are recorded, and a new episode begins.
|
|
58
|
+
2. **Completed vs. Open Drawdown Separation:** Only completed episodes enter the histogram and the percentile statistics. The drawdown that is still open is tracked separately and highlighted in its provisional depth bin, because it has not finished yet and including it would bias the counts.
|
|
59
|
+
3. **Minimum Depth Floor (`min_depth_pct`, default `1.0%`):** Episodes shallower than 1% are excluded by default so trivial one-bar dips below a peak do not dominate the shallowest bucket and distort the median.
|
|
60
|
+
4. **Close vs. High/Low Consistency:** By default, closing prices are used for both peaks and troughs for an internally consistent series. When High/Low mode is used, on a bar that sets a new peak, the intrabar order of high and low is unknown, so that bar's low is not counted toward the next trough.
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## Installation
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
pip install oisigma-drawdown
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Quickstart in Python
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
import math
|
|
76
|
+
from oisigma_drawdown import analyze_drawdown_episodes
|
|
77
|
+
|
|
78
|
+
# Example price series
|
|
79
|
+
closes = [100.0 * math.exp(0.0015 * i - 0.018 * math.sin(i * 0.15)) for i in range(500)]
|
|
80
|
+
|
|
81
|
+
summary = analyze_drawdown_episodes(
|
|
82
|
+
closes,
|
|
83
|
+
bin_width_pct=5.0, # 5% depth buckets
|
|
84
|
+
min_depth_pct=1.0, # Ignore trivial dips shallower than 1%
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
print(summary.format_report())
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## Limitations to Know Before Using It
|
|
93
|
+
|
|
94
|
+
* **Statistics describe the loaded history only:** A short price series gives unreliable percentiles, so load as much historical data as possible.
|
|
95
|
+
* **Deep drawdowns are rare:** Even with long history, the right-hand tail bins and the 95th percentile rest on a small number of completed episodes.
|
|
96
|
+
* **Open drawdown comparison is provisional:** Compare percentiles with the open drawdown's *deepest point so far*, bearing in mind an unfinished drawdown can still deepen before recovering to a new peak.
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## Related Oisigma Research & Links
|
|
101
|
+
|
|
102
|
+
* **[Drawdown Severity Histogram [oisigma] — TradingView Script](https://www.tradingview.com/script/W2UDFbGc-Drawdown-Severity-Histogram-oisigma/)**
|
|
103
|
+
* **[Oisigma — Calibrated Expected Range Indicator for TradingView](https://oisigma.com)**
|
|
104
|
+
* **[How It Works (`oisigma.com/how-it-works`)](https://oisigma.com/how-it-works)**
|
|
105
|
+
* **[Empirical Proof (`oisigma.com/proof`)](https://oisigma.com/proof)**
|
|
106
|
+
* **[Working Paper (`oisigma.com/paper`)](https://oisigma.com/paper)**
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/oisigma_drawdown/__init__.py
|
|
5
|
+
src/oisigma_drawdown/histogram.py
|
|
6
|
+
src/oisigma_drawdown.egg-info/PKG-INFO
|
|
7
|
+
src/oisigma_drawdown.egg-info/SOURCES.txt
|
|
8
|
+
src/oisigma_drawdown.egg-info/dependency_links.txt
|
|
9
|
+
src/oisigma_drawdown.egg-info/entry_points.txt
|
|
10
|
+
src/oisigma_drawdown.egg-info/top_level.txt
|
|
11
|
+
tests/test_histogram.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
oisigma_drawdown
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import unittest
|
|
3
|
+
from oisigma_drawdown import analyze_drawdown_episodes
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class TestDrawdownSeverityHistogram(unittest.TestCase):
|
|
7
|
+
def test_completed_vs_open_drawdown_separation(self):
|
|
8
|
+
# Peak at 100 -> dip to 90 (10% DD) -> new peak at 105 -> dip to 99.75 (5% DD) -> new peak at 110 -> open dip to 93.5 (15% open DD)
|
|
9
|
+
closes = [100.0, 95.0, 90.0, 96.0, 105.0, 99.75, 110.0, 100.0, 93.5]
|
|
10
|
+
summary = analyze_drawdown_episodes(closes, bin_width_pct=5.0, min_depth_pct=1.0)
|
|
11
|
+
|
|
12
|
+
# Only 2 completed episodes (10% and 5%); the 15% open drawdown is tracked separately
|
|
13
|
+
self.assertEqual(summary.completed_count, 2)
|
|
14
|
+
self.assertAlmostEqual(summary.deepest_episode_pct, 10.0, places=2)
|
|
15
|
+
self.assertAlmostEqual(summary.open_drawdown.deepest_pct_so_far, 15.0, places=2)
|
|
16
|
+
self.assertIn("DRAWDOWN SEVERITY HISTOGRAM [oisigma]", summary.format_report())
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
if __name__ == "__main__":
|
|
20
|
+
unittest.main()
|