mgplot 0.3.4__py3-none-any.whl → 0.3.6__py3-none-any.whl
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.
- mgplot/__init__.py +6 -0
- mgplot/axis_utils.py +300 -10
- mgplot/bar_plot.py +3 -3
- mgplot/fill_between_plot.py +3 -5
- mgplot/finalise_plot.py +18 -4
- mgplot/finalisers.py +23 -0
- mgplot/growth_plot.py +2 -1
- mgplot/line_plot.py +3 -3
- mgplot/multi_plot.py +2 -0
- mgplot/ohlc_plot.py +191 -0
- mgplot/run_plot.py +2 -1
- {mgplot-0.3.4.dist-info → mgplot-0.3.6.dist-info}/METADATA +10 -1
- mgplot-0.3.6.dist-info/RECORD +27 -0
- {mgplot-0.3.4.dist-info → mgplot-0.3.6.dist-info}/WHEEL +1 -1
- mgplot-0.3.4.dist-info/RECORD +0 -26
- {mgplot-0.3.4.dist-info → mgplot-0.3.6.dist-info}/licenses/LICENSE +0 -0
mgplot/__init__.py
CHANGED
|
@@ -27,6 +27,7 @@ from mgplot.finalisers import (
|
|
|
27
27
|
fill_between_plot_finalise,
|
|
28
28
|
growth_plot_finalise,
|
|
29
29
|
line_plot_finalise,
|
|
30
|
+
ohlc_plot_finalise,
|
|
30
31
|
postcovid_plot_finalise,
|
|
31
32
|
revision_plot_finalise,
|
|
32
33
|
run_plot_finalise,
|
|
@@ -44,6 +45,7 @@ from mgplot.growth_plot import (
|
|
|
44
45
|
)
|
|
45
46
|
from mgplot.line_plot import LineKwargs, line_plot
|
|
46
47
|
from mgplot.multi_plot import multi_column, multi_start, plot_then_finalise
|
|
48
|
+
from mgplot.ohlc_plot import OhlcKwargs, ohlc_plot, share_bars
|
|
47
49
|
from mgplot.postcovid_plot import PostcovidKwargs, postcovid_plot
|
|
48
50
|
from mgplot.revision_plot import revision_plot
|
|
49
51
|
from mgplot.run_plot import RunKwargs, run_plot
|
|
@@ -73,6 +75,7 @@ __all__ = (
|
|
|
73
75
|
"FinaliseKwargs",
|
|
74
76
|
"GrowthKwargs",
|
|
75
77
|
"LineKwargs",
|
|
78
|
+
"OhlcKwargs",
|
|
76
79
|
"PostcovidKwargs",
|
|
77
80
|
"RunKwargs",
|
|
78
81
|
"ScatterKwargs",
|
|
@@ -100,6 +103,8 @@ __all__ = (
|
|
|
100
103
|
"line_plot_finalise",
|
|
101
104
|
"multi_column",
|
|
102
105
|
"multi_start",
|
|
106
|
+
"ohlc_plot",
|
|
107
|
+
"ohlc_plot_finalise",
|
|
103
108
|
"plot_then_finalise",
|
|
104
109
|
"postcovid_plot",
|
|
105
110
|
"postcovid_plot_finalise",
|
|
@@ -115,6 +120,7 @@ __all__ = (
|
|
|
115
120
|
"series_growth_plot_finalise",
|
|
116
121
|
"set_chart_dir",
|
|
117
122
|
"set_setting",
|
|
123
|
+
"share_bars",
|
|
118
124
|
"state_abbrs",
|
|
119
125
|
"state_names",
|
|
120
126
|
"summary_plot",
|
mgplot/axis_utils.py
CHANGED
|
@@ -8,13 +8,14 @@ such as days, months, quarters, and years.
|
|
|
8
8
|
"""
|
|
9
9
|
|
|
10
10
|
import calendar
|
|
11
|
+
import itertools
|
|
11
12
|
import math
|
|
12
13
|
from collections.abc import Callable
|
|
13
14
|
from enum import Enum
|
|
14
15
|
from typing import Any, Final
|
|
15
16
|
|
|
16
17
|
from matplotlib.axes import Axes
|
|
17
|
-
from pandas import Index, Period, PeriodIndex, RangeIndex, period_range
|
|
18
|
+
from pandas import Index, Period, PeriodIndex, RangeIndex, Timedelta, Timestamp, date_range, period_range
|
|
18
19
|
from pandas.api.types import is_string_dtype
|
|
19
20
|
|
|
20
21
|
from mgplot.settings import DataT
|
|
@@ -98,11 +99,67 @@ def get_period_axes(axes: Axes) -> tuple[str, int, int] | None:
|
|
|
98
99
|
return getattr(axes, _AXES_PERIOD_ATTR, None)
|
|
99
100
|
|
|
100
101
|
|
|
101
|
-
|
|
102
|
-
|
|
102
|
+
# --- bar axes: an OHLC chart puts its bars at x = 0, 1, 2 ... with no space for closed time
|
|
103
|
+
_AXES_BARS_ATTR: Final[str] = "_mgplot_bars"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def register_bar_axes(axes: Axes, bars: PeriodIndex) -> None:
|
|
107
|
+
"""Record the bars of an OHLC chart on its Axes: the bar at position i is bars[i].
|
|
108
|
+
|
|
109
|
+
Raises ValueError if the axes already holds a chart, as its x-coordinates would mean
|
|
110
|
+
something else.
|
|
111
|
+
"""
|
|
112
|
+
if get_bar_axes(axes) is not None or get_period_axes(axes) is not None:
|
|
113
|
+
raise ValueError("An OHLC chart needs an axes of its own: this axes already holds a chart")
|
|
114
|
+
setattr(axes, _AXES_BARS_ATTR, bars)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def get_bar_axes(axes: Axes) -> PeriodIndex | None:
|
|
118
|
+
"""Return the bars recorded on an OHLC chart's Axes, or None for any other axes."""
|
|
119
|
+
bars = getattr(axes, _AXES_BARS_ATTR, None)
|
|
120
|
+
return bars if isinstance(bars, PeriodIndex) else None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def refuse_bar_axes(axes: object, caller: str) -> None:
|
|
124
|
+
"""Raise ValueError if axes is an OHLC chart, for plots that cannot be placed on its bars."""
|
|
125
|
+
if isinstance(axes, Axes) and get_bar_axes(axes) is not None:
|
|
126
|
+
raise ValueError(f"{caller}() cannot be layered on an OHLC chart")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def bar_positions(bars: PeriodIndex, periods: PeriodIndex, caller: str) -> list[int]:
|
|
130
|
+
"""Return the x-position of each period on an OHLC chart with these bars.
|
|
131
|
+
|
|
132
|
+
Raises ValueError if the frequencies differ or any period is not one of the bars:
|
|
133
|
+
only series built on the chart's own bars (a moving average of the closes, say) can
|
|
134
|
+
be drawn on it.
|
|
135
|
+
"""
|
|
136
|
+
if periods.freqstr != bars.freqstr:
|
|
137
|
+
raise ValueError(
|
|
138
|
+
f"{caller}: data freq {periods.freqstr!r} does not match the OHLC chart's freq {bars.freqstr!r}",
|
|
139
|
+
)
|
|
140
|
+
positions = bars.get_indexer(periods)
|
|
141
|
+
absent = periods[positions < 0]
|
|
142
|
+
if len(absent):
|
|
143
|
+
raise ValueError(
|
|
144
|
+
f"{caller}: {len(absent)} periods are not bars of the OHLC chart (first: {absent[0]})",
|
|
145
|
+
)
|
|
146
|
+
return [int(position) for position in positions]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def map_periodindex(data: DataT, axes: Axes | None = None) -> tuple[DataT, PeriodIndex] | None:
|
|
150
|
+
"""Map a PeriodIndex to an integer index: Period ordinals, or bar positions on an OHLC chart.
|
|
151
|
+
|
|
152
|
+
Raises ValueError for data without a PeriodIndex on an OHLC chart: it has no bars to sit on.
|
|
153
|
+
"""
|
|
154
|
+
bars = get_bar_axes(axes) if axes is not None else None
|
|
103
155
|
if not isinstance(data.index, PeriodIndex):
|
|
156
|
+
if bars is not None:
|
|
157
|
+
raise ValueError("map_periodindex: only data with a PeriodIndex can be drawn on an OHLC chart")
|
|
104
158
|
return None
|
|
105
159
|
og_index = PeriodIndex(data.index.copy()) # mypy
|
|
160
|
+
if bars is not None:
|
|
161
|
+
data.index = Index(bar_positions(bars, og_index, "map_periodindex"))
|
|
162
|
+
return data, og_index
|
|
106
163
|
complete = data.index.max().ordinal - data.index.min().ordinal == len(data.index) - 1
|
|
107
164
|
if complete and (data.index.is_monotonic_decreasing or data.index.is_monotonic_increasing):
|
|
108
165
|
data.index = RangeIndex(
|
|
@@ -126,11 +183,17 @@ class DateLike(Enum):
|
|
|
126
183
|
MONTHS = 3
|
|
127
184
|
DAYS = 4
|
|
128
185
|
BAD = 5
|
|
186
|
+
HOURS = 6
|
|
187
|
+
MINUTES = 7
|
|
188
|
+
WEEKS = 8
|
|
129
189
|
|
|
130
190
|
|
|
131
191
|
frequencies = {
|
|
132
192
|
# freq: [Periods from smaller to larger]
|
|
193
|
+
"min": [DateLike.MINUTES, DateLike.HOURS, DateLike.DAYS, DateLike.MONTHS, DateLike.YEARS],
|
|
194
|
+
"h": [DateLike.HOURS, DateLike.DAYS, DateLike.MONTHS, DateLike.YEARS],
|
|
133
195
|
"D": [DateLike.DAYS, DateLike.MONTHS, DateLike.YEARS],
|
|
196
|
+
"W": [DateLike.WEEKS, DateLike.MONTHS, DateLike.YEARS],
|
|
134
197
|
"M": [DateLike.MONTHS, DateLike.YEARS],
|
|
135
198
|
"Q": [DateLike.QUARTERS, DateLike.YEARS],
|
|
136
199
|
"Y": [DateLike.YEARS],
|
|
@@ -143,8 +206,23 @@ intervals = {
|
|
|
143
206
|
DateLike.QUARTERS: [1, 2],
|
|
144
207
|
DateLike.MONTHS: [1, 2, 3, 4, 6],
|
|
145
208
|
DateLike.DAYS: [1, 2, 3, 4, 7, 14],
|
|
209
|
+
DateLike.WEEKS: [1, 2, 4],
|
|
210
|
+
DateLike.HOURS: [1, 2, 3, 4, 6, 12], # each divides a day, so ticks repeat at the same times
|
|
211
|
+
DateLike.MINUTES: [1, 2, 5, 10, 15, 30], # each divides an hour
|
|
146
212
|
}
|
|
147
213
|
|
|
214
|
+
INTRADAY: Final[tuple[str, ...]] = ("min", "h") # base codes of intraday PeriodIndex frequencies
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def base_freq(p: PeriodIndex) -> str:
|
|
218
|
+
"""Return the base code of a PeriodIndex frequency: "min", "h", or the first letter (D, M, Q, Y ...).
|
|
219
|
+
|
|
220
|
+
Intraday frequencies carry a multiple ("5min", "2h"), so they are read from the rule
|
|
221
|
+
code; the others keep the first letter of freqstr ("Q-DEC" is "Q").
|
|
222
|
+
"""
|
|
223
|
+
code = p.freq.rule_code if p.freq is not None else ""
|
|
224
|
+
return code if code in INTRADAY else p.freqstr[0].upper()
|
|
225
|
+
|
|
148
226
|
|
|
149
227
|
def get_count(p: PeriodIndex, max_ticks: int) -> tuple[int, DateLike, int]:
|
|
150
228
|
"""Work out the label frequency and interval for a date-like PeriodIndex.
|
|
@@ -163,7 +241,7 @@ def get_count(p: PeriodIndex, max_ticks: int) -> tuple[int, DateLike, int]:
|
|
|
163
241
|
error = (0, DateLike.BAD, 0)
|
|
164
242
|
if p.empty:
|
|
165
243
|
return error
|
|
166
|
-
freq: str = p
|
|
244
|
+
freq: str = base_freq(p)
|
|
167
245
|
if freq not in frequencies:
|
|
168
246
|
print(f"Unrecognised date-like PeriodIndex frequency {freq}")
|
|
169
247
|
return error
|
|
@@ -332,6 +410,98 @@ def year_labeller(labels: dict[Period, str]) -> dict[Period, str]:
|
|
|
332
410
|
return labels
|
|
333
411
|
|
|
334
412
|
|
|
413
|
+
def intraday_locator(p: PeriodIndex, date_like: DateLike, interval: int) -> dict[Period, str]:
|
|
414
|
+
"""Select the ticks for an intraday PeriodIndex: round times, as Periods of p's frequency.
|
|
415
|
+
|
|
416
|
+
Tick times are generated directly (every interval minutes or hours from midnight, each
|
|
417
|
+
interval-th day, the first of each interval-th month or year) rather than picked from p,
|
|
418
|
+
because a multi-minute range rebuilt from axis limits need not fall on round minutes.
|
|
419
|
+
"""
|
|
420
|
+
first = Timestamp(p.min().start_time)
|
|
421
|
+
last = Timestamp(p.max().start_time)
|
|
422
|
+
match date_like:
|
|
423
|
+
case DateLike.MINUTES:
|
|
424
|
+
times = date_range(first.ceil(f"{interval}min"), last, freq=f"{interval}min")
|
|
425
|
+
case DateLike.HOURS:
|
|
426
|
+
times = date_range(first.ceil(f"{interval}h"), last, freq=f"{interval}h")
|
|
427
|
+
case DateLike.DAYS:
|
|
428
|
+
times = date_range(first.ceil("D"), last, freq="D")[::interval]
|
|
429
|
+
case DateLike.MONTHS:
|
|
430
|
+
times = date_range(first.ceil("D"), last, freq="MS")
|
|
431
|
+
times = times[(times.month - 1) % interval == 0]
|
|
432
|
+
case _:
|
|
433
|
+
times = date_range(first.ceil("D"), last, freq="YS")
|
|
434
|
+
times = times[times.year % interval == 0]
|
|
435
|
+
return {Period(t, freq=p.freqstr): "" for t in times}
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def intraday_labeller(labels: dict[Period, str]) -> dict[Period, str]:
|
|
439
|
+
"""Label hour or minute ticks with the time, adding the date at each new day.
|
|
440
|
+
|
|
441
|
+
The first tick, and the first of each new year, also carry the year.
|
|
442
|
+
"""
|
|
443
|
+
previous: Period | None = None
|
|
444
|
+
for period in sorted(labels.keys()):
|
|
445
|
+
label = f"{period.hour:02d}:{period.minute:02d}"
|
|
446
|
+
if previous is None or (period.year, period.month, period.day) != (
|
|
447
|
+
previous.year,
|
|
448
|
+
previous.month,
|
|
449
|
+
previous.day,
|
|
450
|
+
):
|
|
451
|
+
label = f"{label}\n{period.day} {calendar.month_abbr[period.month]}"
|
|
452
|
+
if previous is None or period.year != previous.year:
|
|
453
|
+
label = f"{label} {period.year}"
|
|
454
|
+
labels[period] = label
|
|
455
|
+
previous = period
|
|
456
|
+
return labels
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def make_intraday_labels(p: PeriodIndex, date_like: DateLike, interval: int) -> dict[Period, str]:
|
|
460
|
+
"""Select and label the ticks for an intraday PeriodIndex."""
|
|
461
|
+
labels = intraday_locator(p, date_like, interval)
|
|
462
|
+
match date_like:
|
|
463
|
+
case DateLike.MINUTES | DateLike.HOURS:
|
|
464
|
+
return intraday_labeller(labels)
|
|
465
|
+
case DateLike.DAYS:
|
|
466
|
+
return day_labeller(labels)
|
|
467
|
+
case DateLike.MONTHS:
|
|
468
|
+
return month_labeller(labels)
|
|
469
|
+
case _:
|
|
470
|
+
return year_labeller(labels)
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def make_weekly_labels(p: PeriodIndex, date_like: DateLike, interval: int) -> dict[Period, str]:
|
|
474
|
+
"""Select and label the ticks for a complete weekly PeriodIndex, by each week's start date.
|
|
475
|
+
|
|
476
|
+
Week ticks fall every interval weeks; month and year ticks on the first week starting in
|
|
477
|
+
each (interval-th) month or year. A weekly Period's day and month attributes describe its
|
|
478
|
+
last day, so ticks are chosen and labelled from start dates: each chosen week stands in
|
|
479
|
+
as a daily, monthly or yearly Period for the existing labellers.
|
|
480
|
+
"""
|
|
481
|
+
starts = p.start_time
|
|
482
|
+
previous = starts - Timedelta(days=7)
|
|
483
|
+
match date_like:
|
|
484
|
+
case DateLike.WEEKS:
|
|
485
|
+
chosen = list(range(0, len(p), interval))
|
|
486
|
+
proxy_freq, labeller = "D", day_labeller
|
|
487
|
+
case DateLike.MONTHS:
|
|
488
|
+
chosen = [
|
|
489
|
+
i
|
|
490
|
+
for i in range(len(p))
|
|
491
|
+
if starts[i].month != previous[i].month and (starts[i].month - 1) % interval == 0
|
|
492
|
+
]
|
|
493
|
+
proxy_freq, labeller = "M", month_labeller
|
|
494
|
+
case _:
|
|
495
|
+
chosen = [
|
|
496
|
+
i
|
|
497
|
+
for i in range(len(p))
|
|
498
|
+
if starts[i].year != previous[i].year and starts[i].year % interval == 0
|
|
499
|
+
]
|
|
500
|
+
proxy_freq, labeller = "Y", year_labeller
|
|
501
|
+
weeks = {Period(starts[i], freq=proxy_freq): p[i] for i in chosen}
|
|
502
|
+
return {weeks[proxy]: label for proxy, label in labeller(dict.fromkeys(weeks, "")).items()}
|
|
503
|
+
|
|
504
|
+
|
|
335
505
|
def make_labels(p: PeriodIndex, max_ticks: int) -> dict[Period, str]:
|
|
336
506
|
"""Provide a dictionary of labels for the date-like PeriodIndex.
|
|
337
507
|
|
|
@@ -351,6 +521,9 @@ def make_labels(p: PeriodIndex, max_ticks: int) -> dict[Period, str]:
|
|
|
351
521
|
if date_like == DateLike.BAD:
|
|
352
522
|
return labels
|
|
353
523
|
|
|
524
|
+
if base_freq(p) in INTRADAY:
|
|
525
|
+
return make_intraday_labels(p, date_like, interval)
|
|
526
|
+
|
|
354
527
|
target_freq = r_freqs[date_like]
|
|
355
528
|
try:
|
|
356
529
|
complete = period_range(start=p.min(), end=p.max(), freq=p.freqstr)
|
|
@@ -358,6 +531,9 @@ def make_labels(p: PeriodIndex, max_ticks: int) -> dict[Period, str]:
|
|
|
358
531
|
print(f"Error creating period range: {e}")
|
|
359
532
|
return labels
|
|
360
533
|
|
|
534
|
+
if base_freq(p) == "W":
|
|
535
|
+
return make_weekly_labels(complete, date_like, interval)
|
|
536
|
+
|
|
361
537
|
match target_freq:
|
|
362
538
|
case "D":
|
|
363
539
|
second_interval: Final[int] = 2
|
|
@@ -410,6 +586,110 @@ def make_ilabels(
|
|
|
410
586
|
return ticks, ticklabels
|
|
411
587
|
|
|
412
588
|
|
|
589
|
+
MINUTES_PER_HOUR: Final[int] = 60
|
|
590
|
+
MIN_BAR_TICKS: Final[int] = 4 # fewer ticks than this on an OHLC chart, and a finer unit is used
|
|
591
|
+
MIN_SPACED_TICKS: Final[int] = 2 # an OHLC chart with more ticks than this is checked for crowding
|
|
592
|
+
CROWDED_SHARE: Final[float] = 0.5 # a tick nearer its successor than this share of the usual spacing goes
|
|
593
|
+
BAR_EDGE: Final[float] = 0.5 # half a bar slot: a tick between two bars sits this far left of the later
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def bar_tick_positions(bars: PeriodIndex, date_like: DateLike, interval: int) -> list[int]:
|
|
597
|
+
"""Select the bars to tick on an OHLC chart, for one tick unit and interval.
|
|
598
|
+
|
|
599
|
+
Minute and hour ticks fall on bars at round times of day. Coarser ticks fall on the first
|
|
600
|
+
bar of each interval-th day, week, month, quarter or year; the first bar's own month,
|
|
601
|
+
quarter or year is skipped there, as the chart may start part-way through it.
|
|
602
|
+
"""
|
|
603
|
+
starts = bars.start_time
|
|
604
|
+
match date_like:
|
|
605
|
+
case DateLike.MINUTES:
|
|
606
|
+
minutes = starts.hour * MINUTES_PER_HOUR + starts.minute
|
|
607
|
+
return [i for i in range(len(bars)) if minutes[i] % interval == 0]
|
|
608
|
+
case DateLike.HOURS:
|
|
609
|
+
return [i for i in range(len(bars)) if starts[i].minute == 0 and starts[i].hour % interval == 0]
|
|
610
|
+
case DateLike.DAYS:
|
|
611
|
+
keys: list[object] = list(starts.normalize())
|
|
612
|
+
case DateLike.WEEKS:
|
|
613
|
+
keys = list(range(len(bars))) # weekly bars: each bar is its own week
|
|
614
|
+
case DateLike.MONTHS:
|
|
615
|
+
keys = list(zip(starts.year, starts.month, strict=True))
|
|
616
|
+
case DateLike.QUARTERS:
|
|
617
|
+
keys = list(zip(starts.year, starts.quarter, strict=True))
|
|
618
|
+
case _:
|
|
619
|
+
keys = list(starts.year)
|
|
620
|
+
firsts = [i for i in range(len(bars)) if i == 0 or keys[i] != keys[i - 1]]
|
|
621
|
+
if date_like in (DateLike.DAYS, DateLike.WEEKS):
|
|
622
|
+
return firsts[::interval]
|
|
623
|
+
numbers = {DateLike.MONTHS: starts.month - 1, DateLike.QUARTERS: starts.quarter - 1}.get(
|
|
624
|
+
date_like,
|
|
625
|
+
starts.year,
|
|
626
|
+
)
|
|
627
|
+
return [i for i in firsts if i > 0 and numbers[i] % interval == 0]
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def bar_tick_labels(bars: PeriodIndex, positions: list[int], date_like: DateLike) -> list[str]:
|
|
631
|
+
"""Label the ticked bars of an OHLC chart with the existing contextual labellers.
|
|
632
|
+
|
|
633
|
+
Each ticked bar stands in as a Period of the tick unit (a minute, day, month ...), so the
|
|
634
|
+
labellers add the month and year where they change, as on other mgplot date axes.
|
|
635
|
+
"""
|
|
636
|
+
proxy_freq, labeller = {
|
|
637
|
+
DateLike.MINUTES: ("min", intraday_labeller),
|
|
638
|
+
DateLike.HOURS: ("min", intraday_labeller),
|
|
639
|
+
DateLike.DAYS: ("D", day_labeller),
|
|
640
|
+
DateLike.WEEKS: ("D", day_labeller),
|
|
641
|
+
DateLike.MONTHS: ("M", month_labeller),
|
|
642
|
+
DateLike.QUARTERS: ("Q", qtr_labeller),
|
|
643
|
+
}.get(date_like, ("Y", year_labeller))
|
|
644
|
+
proxies = [Period(bars[i].start_time, freq=proxy_freq) for i in positions]
|
|
645
|
+
labels = labeller(dict.fromkeys(proxies, ""))
|
|
646
|
+
return [labels[proxy] for proxy in proxies]
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def make_bar_ilabels(
|
|
650
|
+
bars: PeriodIndex,
|
|
651
|
+
max_ticks: int,
|
|
652
|
+
tick_relabel: Callable[[str], str] | None = None,
|
|
653
|
+
) -> tuple[list[float], list[str]]:
|
|
654
|
+
"""Create the x-ticks and tick labels for an OHLC chart, from its bars.
|
|
655
|
+
|
|
656
|
+
The coarsest unit giving MIN_BAR_TICKS to max_ticks ticks wins, at its smallest such
|
|
657
|
+
interval (a week of hourly bars gets day ticks, one day of minute bars hour ticks); failing
|
|
658
|
+
that, the finest unit and interval giving no more than max_ticks. Ticks of the bars' own
|
|
659
|
+
unit (and minute or hour ticks) sit on their bar; coarser ticks sit on the edge before
|
|
660
|
+
the first bar of their day, month or year, where a session-boundary line usually falls.
|
|
661
|
+
A tick crowding the next one (a session's last hour against the next session's first) is
|
|
662
|
+
dropped, keeping the later.
|
|
663
|
+
"""
|
|
664
|
+
if bars.empty:
|
|
665
|
+
return [], []
|
|
666
|
+
units = frequencies.get(base_freq(bars), frequencies["D"])
|
|
667
|
+
candidates = [(unit, interval) for unit in units for interval in intervals[unit]]
|
|
668
|
+
counts = {candidate: len(bar_tick_positions(bars, *candidate)) for candidate in candidates}
|
|
669
|
+
fitting = [candidate for candidate in candidates if counts[candidate] <= max_ticks]
|
|
670
|
+
enough = [candidate for candidate in fitting if counts[candidate] >= MIN_BAR_TICKS]
|
|
671
|
+
if enough:
|
|
672
|
+
coarsest = max(units.index(unit) for unit, _ in enough)
|
|
673
|
+
date_like, interval = next(c for c in enough if units.index(c[0]) == coarsest)
|
|
674
|
+
else:
|
|
675
|
+
date_like, interval = fitting[0] if fitting else candidates[-1]
|
|
676
|
+
positions = bar_tick_positions(bars, date_like, interval)
|
|
677
|
+
if len(positions) > MIN_SPACED_TICKS:
|
|
678
|
+
# closed time takes no space, so a session's last tick can crowd the next session's
|
|
679
|
+
# first: drop a tick closer than CROWDED_SHARE of the usual spacing to the next tick
|
|
680
|
+
spacings = sorted(b - a for a, b in itertools.pairwise(positions))
|
|
681
|
+
crowded = CROWDED_SHARE * spacings[len(spacings) // 2]
|
|
682
|
+
positions = [
|
|
683
|
+
a for a, b in zip(positions, [*positions[1:], None], strict=True) if b is None or b - a >= crowded
|
|
684
|
+
]
|
|
685
|
+
labels = bar_tick_labels(bars, positions, date_like)
|
|
686
|
+
on_bar = date_like in (DateLike.MINUTES, DateLike.HOURS, units[0])
|
|
687
|
+
ticks = [float(i) if on_bar else i - BAR_EDGE for i in positions]
|
|
688
|
+
if tick_relabel is not None:
|
|
689
|
+
labels = [tick_relabel(label) for label in labels]
|
|
690
|
+
return ticks, labels
|
|
691
|
+
|
|
692
|
+
|
|
413
693
|
def refresh_period_labels(axes: Axes, max_ticks: int | None = None) -> None:
|
|
414
694
|
"""Regenerate x-axis tick labels from the stashed period range and current xlim.
|
|
415
695
|
|
|
@@ -420,15 +700,23 @@ def refresh_period_labels(axes: Axes, max_ticks: int | None = None) -> None:
|
|
|
420
700
|
Label options (max_ticks, rotation, tick_relabel) stashed by set_labels()
|
|
421
701
|
are honoured, so a refresh reproduces what the plot function originally
|
|
422
702
|
built. An explicit max_ticks argument overrides the stashed value.
|
|
703
|
+
|
|
704
|
+
An OHLC chart's labels come from its bars instead (see make_bar_ilabels()).
|
|
423
705
|
"""
|
|
424
|
-
stash = get_period_axes(axes)
|
|
425
|
-
if stash is None:
|
|
426
|
-
return
|
|
427
|
-
freq, stash_min, stash_max = stash
|
|
428
706
|
options = get_label_options(axes)
|
|
429
707
|
if max_ticks is None:
|
|
430
708
|
stashed = options.get("max_ticks", DEFAULT_REFRESH_TICKS)
|
|
431
709
|
max_ticks = stashed if isinstance(stashed, int) else DEFAULT_REFRESH_TICKS
|
|
710
|
+
bars = get_bar_axes(axes)
|
|
711
|
+
if bars is not None:
|
|
712
|
+
bar_ticks, bar_labels = make_bar_ilabels(bars, max_ticks, options.get("tick_relabel"))
|
|
713
|
+
axes.set_xticks(bar_ticks)
|
|
714
|
+
axes.set_xticklabels(bar_labels, rotation=options.get("rotation", 0), ha="center")
|
|
715
|
+
return
|
|
716
|
+
stash = get_period_axes(axes)
|
|
717
|
+
if stash is None:
|
|
718
|
+
return
|
|
719
|
+
freq, stash_min, stash_max = stash
|
|
432
720
|
xlim = axes.get_xlim()
|
|
433
721
|
# round inwards: only periods inside the view get a label. A bar chart's limits sit
|
|
434
722
|
# half a bar beyond its end bars, and truncating them named the neighbouring period,
|
|
@@ -460,7 +748,8 @@ def set_labels(
|
|
|
460
748
|
Registers the PeriodIndex on the axes (see register_period_axes()). When
|
|
461
749
|
multiple series are plotted on the same axes, the stashed ordinal range is
|
|
462
750
|
the union of everything plotted so far, so ticks always span the full
|
|
463
|
-
extent of all plotted data.
|
|
751
|
+
extent of all plotted data. On an OHLC chart nothing is registered: its
|
|
752
|
+
labels come from its bars.
|
|
464
753
|
|
|
465
754
|
The label options are stashed on the axes so that later refreshes
|
|
466
755
|
(including the one in finalise_plot()) reproduce them.
|
|
@@ -475,6 +764,7 @@ def set_labels(
|
|
|
475
764
|
digits).
|
|
476
765
|
|
|
477
766
|
"""
|
|
478
|
-
|
|
767
|
+
if get_bar_axes(axes) is None: # an OHLC chart is labelled from its bars, not p
|
|
768
|
+
register_period_axes(axes, p)
|
|
479
769
|
register_label_options(axes, max_ticks=max_ticks, rotation=rotation, tick_relabel=tick_relabel)
|
|
480
770
|
refresh_period_labels(axes)
|
mgplot/bar_plot.py
CHANGED
|
@@ -276,6 +276,7 @@ def bar_plot(data: DataT, **kwargs: Unpack[BarKwargs]) -> Axes:
|
|
|
276
276
|
df = DataFrame(data) # really we are only plotting DataFrames
|
|
277
277
|
df, kwargs_d = constrain_data(df, **kwargs)
|
|
278
278
|
item_count = len(df.columns)
|
|
279
|
+
axes, kwargs_d = get_axes(**kwargs_d) # before mapping: an OHLC chart maps to its bars
|
|
279
280
|
|
|
280
281
|
# --- deal with string indices
|
|
281
282
|
saved_strings = map_stringindex(df)
|
|
@@ -283,7 +284,7 @@ def bar_plot(data: DataT, **kwargs: Unpack[BarKwargs]) -> Axes:
|
|
|
283
284
|
df = saved_strings[0]
|
|
284
285
|
|
|
285
286
|
# --- deal with complete PeriodIndex indices
|
|
286
|
-
saved_pi = map_periodindex(df)
|
|
287
|
+
saved_pi = map_periodindex(df, axes)
|
|
287
288
|
if saved_pi is not None:
|
|
288
289
|
df = saved_pi[0] # extract the reindexed DataFrame from the PeriodIndex
|
|
289
290
|
|
|
@@ -329,10 +330,9 @@ def bar_plot(data: DataT, **kwargs: Unpack[BarKwargs]) -> Axes:
|
|
|
329
330
|
"color": kwargs_d.get("annotate_color", "black" if above else "white"),
|
|
330
331
|
"above": above,
|
|
331
332
|
}
|
|
332
|
-
bar_args,
|
|
333
|
+
bar_args, _ = apply_defaults(item_count, bar_defaults, kwargs_d)
|
|
333
334
|
|
|
334
335
|
# --- plot the data
|
|
335
|
-
axes, remaining_kwargs = get_axes(**dict(remaining_kwargs))
|
|
336
336
|
if chart_args["stacked"]:
|
|
337
337
|
stacked(axes, df, anno_args, horizontal=horizontal, **bar_args)
|
|
338
338
|
else:
|
mgplot/fill_between_plot.py
CHANGED
|
@@ -63,14 +63,12 @@ def fill_between_plot(data: DataFrame, **kwargs: Unpack[FillBetweenKwargs]) -> A
|
|
|
63
63
|
data = check_clean_timeseries(data, ME)
|
|
64
64
|
data, kwargs_d = constrain_data(data, **kwargs)
|
|
65
65
|
|
|
66
|
-
# --- handle PeriodIndex conversion
|
|
67
|
-
|
|
66
|
+
# --- get axes, then handle PeriodIndex conversion for it
|
|
67
|
+
axes, kwargs_d = get_axes(**kwargs_d)
|
|
68
|
+
saved_pi = map_periodindex(data, axes)
|
|
68
69
|
if saved_pi is not None:
|
|
69
70
|
data = saved_pi[0]
|
|
70
71
|
|
|
71
|
-
# --- get axes
|
|
72
|
-
axes, kwargs_d = get_axes(**kwargs_d)
|
|
73
|
-
|
|
74
72
|
if data.empty or data.isna().all().all():
|
|
75
73
|
print(f"Warning: No data to plot in {ME}().")
|
|
76
74
|
return axes
|
mgplot/finalise_plot.py
CHANGED
|
@@ -16,7 +16,13 @@ from matplotlib.transforms import blended_transform_factory
|
|
|
16
16
|
from pandas import Period, PeriodIndex
|
|
17
17
|
|
|
18
18
|
from mgplot.annotation_utils import resolve_annotation_collisions
|
|
19
|
-
from mgplot.axis_utils import
|
|
19
|
+
from mgplot.axis_utils import (
|
|
20
|
+
bar_positions,
|
|
21
|
+
get_bar_axes,
|
|
22
|
+
get_period_axes,
|
|
23
|
+
refresh_period_labels,
|
|
24
|
+
register_period_axes,
|
|
25
|
+
)
|
|
20
26
|
from mgplot.keyword_checking import BaseKwargs, report_kwargs, validate_kwargs
|
|
21
27
|
from mgplot.settings import get_setting
|
|
22
28
|
|
|
@@ -226,16 +232,20 @@ def _convert_period_coords(axes: Axes, method_name: str, item: dict[str, Any]) -
|
|
|
226
232
|
If the axes was period-mapped by mgplot, the Period's freq must match the
|
|
227
233
|
axes' stashed freq — otherwise the ordinals live in different spaces.
|
|
228
234
|
On an axes with no stash we trust the programmer and just take .ordinal.
|
|
235
|
+
On an OHLC chart a Period becomes the position of its bar.
|
|
229
236
|
"""
|
|
230
237
|
keys = _PERIOD_COORD_KEYS.get(method_name)
|
|
231
238
|
if not keys:
|
|
232
239
|
return item
|
|
233
240
|
stash = get_period_axes(axes)
|
|
234
241
|
stashed_freq = stash[0] if stash is not None else None
|
|
242
|
+
bars = get_bar_axes(axes)
|
|
235
243
|
converted = dict(item)
|
|
236
244
|
for key in keys:
|
|
237
245
|
val = converted.get(key)
|
|
238
|
-
if isinstance(val, Period):
|
|
246
|
+
if isinstance(val, Period) and bars is not None:
|
|
247
|
+
converted[key] = bar_positions(bars, PeriodIndex([val]), method_name)[0]
|
|
248
|
+
elif isinstance(val, Period):
|
|
239
249
|
if stashed_freq is not None and val.freqstr != stashed_freq:
|
|
240
250
|
raise ValueError(
|
|
241
251
|
f"{method_name} Period freq {val.freqstr!r} does not match axes freq {stashed_freq!r}",
|
|
@@ -259,15 +269,19 @@ def _convert_period_value(axes: Axes, setting: str, value: object) -> object:
|
|
|
259
269
|
xlim is a 2-tuple and xticks a list; either may contain Periods when the
|
|
260
270
|
caller describes the axis in calendar terms. On a period-mapped axes the
|
|
261
271
|
Period freq must match the axes' stashed freq (see register_period_axes).
|
|
262
|
-
Non-x settings, None, and non-Period entries pass through unchanged.
|
|
272
|
+
Non-x settings, None, and non-Period entries pass through unchanged. On an
|
|
273
|
+
OHLC chart a Period becomes the position of its bar.
|
|
263
274
|
"""
|
|
264
275
|
if setting not in _PERIOD_X_VALUE_KWARGS or not isinstance(value, (tuple, list)):
|
|
265
276
|
return value
|
|
266
277
|
stash = get_period_axes(axes)
|
|
267
278
|
stashed_freq = stash[0] if stash is not None else None
|
|
279
|
+
bars = get_bar_axes(axes)
|
|
268
280
|
converted: list[object] = []
|
|
269
281
|
for val in value:
|
|
270
|
-
if isinstance(val, Period):
|
|
282
|
+
if isinstance(val, Period) and bars is not None:
|
|
283
|
+
converted.append(bar_positions(bars, PeriodIndex([val]), setting)[0])
|
|
284
|
+
elif isinstance(val, Period):
|
|
271
285
|
if stashed_freq is not None and val.freqstr != stashed_freq:
|
|
272
286
|
raise ValueError(
|
|
273
287
|
f"{setting} Period freq {val.freqstr!r} does not match axes freq {stashed_freq!r}",
|
mgplot/finalisers.py
CHANGED
|
@@ -35,6 +35,7 @@ from mgplot.growth_plot import (
|
|
|
35
35
|
from mgplot.keyword_checking import validate_kwargs
|
|
36
36
|
from mgplot.line_plot import LineKwargs, line_plot
|
|
37
37
|
from mgplot.multi_plot import plot_then_finalise
|
|
38
|
+
from mgplot.ohlc_plot import OhlcKwargs, ohlc_plot
|
|
38
39
|
from mgplot.postcovid_plot import PostcovidKwargs, postcovid_plot
|
|
39
40
|
from mgplot.revision_plot import revision_plot
|
|
40
41
|
from mgplot.run_plot import RunKwargs, run_plot
|
|
@@ -67,6 +68,10 @@ class LPFKwargs(LineKwargs, FinaliseKwargs):
|
|
|
67
68
|
"""Combined kwargs for line_plot_finalise()."""
|
|
68
69
|
|
|
69
70
|
|
|
71
|
+
class OhlcPFKwargs(OhlcKwargs, FinaliseKwargs):
|
|
72
|
+
"""Combined kwargs for ohlc_plot_finalise()."""
|
|
73
|
+
|
|
74
|
+
|
|
70
75
|
class PCFKwargs(PostcovidKwargs, FinaliseKwargs):
|
|
71
76
|
"""Combined kwargs for postcovid_plot_finalise()."""
|
|
72
77
|
|
|
@@ -211,6 +216,24 @@ def line_plot_finalise(
|
|
|
211
216
|
plot_then_finalise(data, function=line_plot, **kwargs)
|
|
212
217
|
|
|
213
218
|
|
|
219
|
+
def ohlc_plot_finalise(
|
|
220
|
+
data: DataFrame,
|
|
221
|
+
**kwargs: Unpack[OhlcPFKwargs],
|
|
222
|
+
) -> None:
|
|
223
|
+
"""Call ohlc_plot() then finalise_plot().
|
|
224
|
+
|
|
225
|
+
No legend is imposed: the candles explain themselves, and the frame's four price
|
|
226
|
+
columns are not separate series.
|
|
227
|
+
|
|
228
|
+
Args:
|
|
229
|
+
data: DataFrame with Open, High, Low and Close columns on a PeriodIndex.
|
|
230
|
+
kwargs: Combined ohlc plot and finalise plot keyword arguments.
|
|
231
|
+
|
|
232
|
+
"""
|
|
233
|
+
validate_kwargs(schema=OhlcPFKwargs, caller="ohlc_plot_finalise", **kwargs)
|
|
234
|
+
plot_then_finalise(data, function=ohlc_plot, **kwargs)
|
|
235
|
+
|
|
236
|
+
|
|
214
237
|
def postcovid_plot_finalise(
|
|
215
238
|
data: DataT,
|
|
216
239
|
**kwargs: Unpack[PCFKwargs],
|
mgplot/growth_plot.py
CHANGED
|
@@ -13,7 +13,7 @@ from matplotlib.axes import Axes
|
|
|
13
13
|
from numpy import nan
|
|
14
14
|
from pandas import DataFrame, Period, PeriodIndex, Series, period_range
|
|
15
15
|
|
|
16
|
-
from mgplot.axis_utils import map_periodindex, set_labels
|
|
16
|
+
from mgplot.axis_utils import map_periodindex, refuse_bar_axes, set_labels
|
|
17
17
|
from mgplot.bar_plot import bar_plot
|
|
18
18
|
from mgplot.keyword_checking import (
|
|
19
19
|
BaseKwargs,
|
|
@@ -185,6 +185,7 @@ def growth_plot(
|
|
|
185
185
|
me = "growth_plot"
|
|
186
186
|
report_kwargs(caller=me, **kwargs)
|
|
187
187
|
validate_kwargs(GrowthKwargs, caller=me, **kwargs)
|
|
188
|
+
refuse_bar_axes(kwargs.get("ax"), me)
|
|
188
189
|
|
|
189
190
|
# --- data checks
|
|
190
191
|
data = check_clean_timeseries(data, me)
|
mgplot/line_plot.py
CHANGED
|
@@ -200,8 +200,9 @@ def line_plot(data: DataT, **kwargs: Unpack[LineKwargs]) -> Axes:
|
|
|
200
200
|
df = DataFrame(data) # we are only plotting DataFrames
|
|
201
201
|
df, kwargs_d = constrain_data(df, **kwargs)
|
|
202
202
|
|
|
203
|
-
# --- convert PeriodIndex to Integer Index
|
|
204
|
-
|
|
203
|
+
# --- get the axes to plot on, then convert PeriodIndex to Integer Index for it
|
|
204
|
+
axes, kwargs_d = get_axes(**kwargs_d)
|
|
205
|
+
saved_pi = map_periodindex(df, axes)
|
|
205
206
|
if saved_pi is not None:
|
|
206
207
|
df = saved_pi[0]
|
|
207
208
|
|
|
@@ -209,7 +210,6 @@ def line_plot(data: DataT, **kwargs: Unpack[LineKwargs]) -> Axes:
|
|
|
209
210
|
print("Internal error: data is still a PeriodIndex - come back here and fix it")
|
|
210
211
|
|
|
211
212
|
# --- Let's plot
|
|
212
|
-
axes, kwargs_d = get_axes(**kwargs_d) # get the axes to plot on
|
|
213
213
|
if df.empty or df.isna().all().all():
|
|
214
214
|
# Note: finalise plot should ignore an empty axes object
|
|
215
215
|
print(f"Warning: No data to plot in {ME}().")
|
mgplot/multi_plot.py
CHANGED
|
@@ -59,6 +59,7 @@ from mgplot.keyword_checking import (
|
|
|
59
59
|
validate_kwargs,
|
|
60
60
|
)
|
|
61
61
|
from mgplot.line_plot import LineKwargs, line_plot
|
|
62
|
+
from mgplot.ohlc_plot import OhlcKwargs, ohlc_plot
|
|
62
63
|
from mgplot.postcovid_plot import PostcovidKwargs, postcovid_plot
|
|
63
64
|
from mgplot.revision_plot import revision_plot
|
|
64
65
|
from mgplot.run_plot import RunKwargs, run_plot
|
|
@@ -72,6 +73,7 @@ EXPECTED_CALLABLES: dict[Callable, type[Any]] = {
|
|
|
72
73
|
line_plot: LineKwargs,
|
|
73
74
|
bar_plot: BarKwargs,
|
|
74
75
|
fill_between_plot: FillBetweenKwargs,
|
|
76
|
+
ohlc_plot: OhlcKwargs,
|
|
75
77
|
seastrend_plot: LineKwargs,
|
|
76
78
|
postcovid_plot: PostcovidKwargs,
|
|
77
79
|
revision_plot: LineKwargs,
|
mgplot/ohlc_plot.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Plot open-high-low-close candles, with no space for closed hours, weekends or holidays.
|
|
2
|
+
|
|
3
|
+
Each bar takes one slot on the x-axis (bar i at x = i), so only traded time is shown. A light
|
|
4
|
+
grey line marks each session boundary: wherever the time from one bar to the next is longer
|
|
5
|
+
than a bar (overnight and weekends for intraday bars, weekends and holidays for daily bars,
|
|
6
|
+
and gaps in the data). There are no x-gridlines, so every vertical line is a boundary. A
|
|
7
|
+
chart with more than max_boundaries boundaries (default 50: years of daily bars) gets none.
|
|
8
|
+
|
|
9
|
+
A series built on the chart's own bars (a moving average of the closes, say) can be layered
|
|
10
|
+
on with line_plot(), bar_plot() or fill_between_plot() and ax=; they place each point on its
|
|
11
|
+
bar. Data with any period that is not one of the bars raises a ValueError rather than being
|
|
12
|
+
drawn in the wrong place. share_bars() makes a second axes a panel on the same bars, for an
|
|
13
|
+
indicator drawn under the candles (MACD, volume).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from collections.abc import Callable, Mapping
|
|
17
|
+
from typing import Any, Final, NotRequired, Unpack
|
|
18
|
+
|
|
19
|
+
from matplotlib.axes import Axes
|
|
20
|
+
from pandas import DataFrame, PeriodIndex
|
|
21
|
+
|
|
22
|
+
from mgplot.axis_utils import get_bar_axes, register_bar_axes, set_labels
|
|
23
|
+
from mgplot.keyword_checking import BaseKwargs, report_kwargs, validate_kwargs
|
|
24
|
+
from mgplot.settings import get_setting
|
|
25
|
+
from mgplot.utilities import constrain_data, get_axes
|
|
26
|
+
|
|
27
|
+
# --- constants
|
|
28
|
+
ME: Final[str] = "ohlc_plot"
|
|
29
|
+
OHLC_COLUMNS: Final[tuple[str, ...]] = ("Open", "High", "Low", "Close")
|
|
30
|
+
DEFAULT_UP_COLOR: Final[str] = "#2ca02c" # green: closed at or above the open
|
|
31
|
+
DEFAULT_DOWN_COLOR: Final[str] = "#d62728" # red: closed below the open
|
|
32
|
+
DEFAULT_BODY_WIDTH: Final[float] = 0.6 # share of a bar's slot
|
|
33
|
+
DEFAULT_WICK_WIDTH: Final[float] = 0.75 # points
|
|
34
|
+
BODY_EDGE_WIDTH: Final[float] = 0.5 # points: keeps a bar that closed at its open visible
|
|
35
|
+
DEFAULT_BOUNDARY_COLOR: Final[str] = "lightgrey"
|
|
36
|
+
DEFAULT_BOUNDARY_WIDTH: Final[float] = 0.75 # points
|
|
37
|
+
BOUNDARY_OFFSET: Final[float] = 0.5 # a boundary line sits midway between two bars
|
|
38
|
+
BOUNDARY_ZORDER: Final[float] = 1.0 # above the y-grid, below the candles
|
|
39
|
+
DEFAULT_MAX_BOUNDARIES: Final[int] = 50 # more boundaries than this, and none are drawn
|
|
40
|
+
CANDLE_ZORDER: Final[float] = 2.0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class BoundaryKwargs(BaseKwargs):
|
|
44
|
+
"""Keyword arguments for the session boundaries of an OHLC chart or a panel sharing its bars."""
|
|
45
|
+
|
|
46
|
+
boundaries: NotRequired[bool]
|
|
47
|
+
boundary_color: NotRequired[str]
|
|
48
|
+
boundary_width: NotRequired[float]
|
|
49
|
+
max_boundaries: NotRequired[int]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class OhlcKwargs(BoundaryKwargs):
|
|
53
|
+
"""Keyword arguments for the ohlc_plot function."""
|
|
54
|
+
|
|
55
|
+
ax: NotRequired[Axes | None]
|
|
56
|
+
up_color: NotRequired[str]
|
|
57
|
+
down_color: NotRequired[str]
|
|
58
|
+
body_width: NotRequired[float]
|
|
59
|
+
wick_width: NotRequired[float]
|
|
60
|
+
plot_from: NotRequired[int | None]
|
|
61
|
+
max_ticks: NotRequired[int]
|
|
62
|
+
tick_relabel: NotRequired[Callable[[str], str]]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _prepare_bar_axes(axes: Axes, bars: PeriodIndex, kwargs_d: Mapping[str, Any]) -> None:
|
|
66
|
+
"""Record the bars on the axes, turn off its x-gridlines and draw its session boundaries.
|
|
67
|
+
|
|
68
|
+
A boundary falls where the next bar starts later than this bar ends. On a long chart (years
|
|
69
|
+
of daily bars, a line every weekend) they would hide the candles, so above max_boundaries
|
|
70
|
+
none are drawn.
|
|
71
|
+
"""
|
|
72
|
+
register_bar_axes(axes, bars)
|
|
73
|
+
axes.grid(visible=False, axis="x") # the only vertical lines are the session boundaries
|
|
74
|
+
starts = bars.start_time
|
|
75
|
+
follows = (bars + 1).start_time # when the next bar would start with no gap
|
|
76
|
+
gaps = [i for i in range(1, len(bars)) if starts[i] > follows[i - 1]]
|
|
77
|
+
max_boundaries = kwargs_d.get("max_boundaries", DEFAULT_MAX_BOUNDARIES)
|
|
78
|
+
if kwargs_d.get("boundaries", True) and len(gaps) <= max_boundaries:
|
|
79
|
+
for i in gaps:
|
|
80
|
+
axes.axvline(
|
|
81
|
+
i - BOUNDARY_OFFSET,
|
|
82
|
+
color=kwargs_d.get("boundary_color", DEFAULT_BOUNDARY_COLOR),
|
|
83
|
+
linewidth=kwargs_d.get("boundary_width", DEFAULT_BOUNDARY_WIDTH),
|
|
84
|
+
zorder=BOUNDARY_ZORDER,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def share_bars(axes: Axes, ohlc_axes: Axes, **kwargs: Unpack[BoundaryKwargs]) -> Axes:
|
|
89
|
+
"""Make axes a panel on an OHLC chart's bars, such as an indicator under the candles.
|
|
90
|
+
|
|
91
|
+
The panel gets the chart's bars (so line_plot(), bar_plot() and fill_between_plot() with
|
|
92
|
+
ax= place each point on its bar, and refuse data that is not on the bars), the same session
|
|
93
|
+
boundaries, and no x-gridlines. Create the two axes with a shared x-axis (for example
|
|
94
|
+
plt.subplots(2, 1, sharex=True)) so the panels scroll and label together.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
axes: Axes - the panel, which must not already hold a chart.
|
|
98
|
+
ohlc_axes: Axes - an axes drawn by ohlc_plot().
|
|
99
|
+
kwargs: BoundaryKwargs - how the panel's session boundaries are drawn.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
Axes - the panel.
|
|
103
|
+
|
|
104
|
+
Raises:
|
|
105
|
+
ValueError: If ohlc_axes holds no OHLC chart, or axes already holds a chart.
|
|
106
|
+
|
|
107
|
+
"""
|
|
108
|
+
validate_kwargs(schema=BoundaryKwargs, caller="share_bars", **kwargs)
|
|
109
|
+
bars = get_bar_axes(ohlc_axes)
|
|
110
|
+
if bars is None:
|
|
111
|
+
raise ValueError("share_bars: ohlc_axes holds no OHLC chart")
|
|
112
|
+
_prepare_bar_axes(axes, bars, kwargs)
|
|
113
|
+
return axes
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def ohlc_plot(data: DataFrame, **kwargs: Unpack[OhlcKwargs]) -> Axes:
|
|
117
|
+
"""Plot candles from Open, High, Low and Close columns on a PeriodIndex.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
data: DataFrame - Open, High, Low and Close columns (others are ignored) on a unique,
|
|
121
|
+
increasing PeriodIndex of any frequency. Rows missing any of the four are dropped.
|
|
122
|
+
kwargs: OhlcKwargs - keyword arguments for the plot.
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
Axes - the matplotlib Axes, which must not already hold a chart.
|
|
126
|
+
|
|
127
|
+
Raises:
|
|
128
|
+
TypeError: If data is not a DataFrame on a PeriodIndex.
|
|
129
|
+
ValueError: If a column is missing, the index is not unique and increasing, no row is
|
|
130
|
+
complete, or the axes already holds a chart.
|
|
131
|
+
|
|
132
|
+
"""
|
|
133
|
+
# --- validate inputs
|
|
134
|
+
report_kwargs(caller=ME, **kwargs)
|
|
135
|
+
validate_kwargs(schema=OhlcKwargs, caller=ME, **kwargs)
|
|
136
|
+
if not isinstance(data, DataFrame):
|
|
137
|
+
raise TypeError(f"data must be a DataFrame for {ME}()")
|
|
138
|
+
missing = [column for column in OHLC_COLUMNS if column not in data.columns]
|
|
139
|
+
if missing:
|
|
140
|
+
raise ValueError(f"data for {ME}() lacks the column(s) {', '.join(missing)}")
|
|
141
|
+
if not isinstance(data.index, PeriodIndex):
|
|
142
|
+
raise TypeError(f"data for {ME}() must have a PeriodIndex")
|
|
143
|
+
if not data.index.is_unique or not data.index.is_monotonic_increasing:
|
|
144
|
+
raise ValueError(f"the index of data for {ME}() must be unique and increasing")
|
|
145
|
+
|
|
146
|
+
# --- the bars: complete rows only, as a candle needs all four prices
|
|
147
|
+
ohlc = data[list(OHLC_COLUMNS)].dropna()
|
|
148
|
+
ohlc, kwargs_d = constrain_data(ohlc, **kwargs)
|
|
149
|
+
if ohlc.empty:
|
|
150
|
+
raise ValueError(f"no complete open-high-low-close rows to plot in {ME}()")
|
|
151
|
+
bars = PeriodIndex(ohlc.index)
|
|
152
|
+
axes, kwargs_d = get_axes(**kwargs_d)
|
|
153
|
+
_prepare_bar_axes(axes, bars, kwargs_d)
|
|
154
|
+
x = list(range(len(bars)))
|
|
155
|
+
|
|
156
|
+
# --- candles: a wick from low to high, a body from open to close
|
|
157
|
+
up = ohlc["Close"] >= ohlc["Open"]
|
|
158
|
+
colors = [
|
|
159
|
+
kwargs_d.get("up_color", DEFAULT_UP_COLOR) if rose else kwargs_d.get("down_color", DEFAULT_DOWN_COLOR)
|
|
160
|
+
for rose in up
|
|
161
|
+
]
|
|
162
|
+
axes.vlines(
|
|
163
|
+
x,
|
|
164
|
+
ohlc["Low"],
|
|
165
|
+
ohlc["High"],
|
|
166
|
+
colors=colors,
|
|
167
|
+
linewidth=kwargs_d.get("wick_width", DEFAULT_WICK_WIDTH),
|
|
168
|
+
zorder=CANDLE_ZORDER,
|
|
169
|
+
)
|
|
170
|
+
bodies = axes.bar(
|
|
171
|
+
x,
|
|
172
|
+
(ohlc["Close"] - ohlc["Open"]).abs(),
|
|
173
|
+
bottom=ohlc[["Open", "Close"]].min(axis=1),
|
|
174
|
+
width=kwargs_d.get("body_width", DEFAULT_BODY_WIDTH),
|
|
175
|
+
color=colors,
|
|
176
|
+
edgecolor=colors,
|
|
177
|
+
linewidth=BODY_EDGE_WIDTH,
|
|
178
|
+
zorder=CANDLE_ZORDER,
|
|
179
|
+
label="_candles",
|
|
180
|
+
)
|
|
181
|
+
for body in bodies: # a bar's base is sticky, and would stop the y-margin at a low close
|
|
182
|
+
body.sticky_edges.y.clear()
|
|
183
|
+
|
|
184
|
+
# --- tick labels from the bars
|
|
185
|
+
set_labels(
|
|
186
|
+
axes,
|
|
187
|
+
bars,
|
|
188
|
+
kwargs_d.get("max_ticks", get_setting("max_ticks")),
|
|
189
|
+
tick_relabel=kwargs_d.get("tick_relabel"),
|
|
190
|
+
)
|
|
191
|
+
return axes
|
mgplot/run_plot.py
CHANGED
|
@@ -7,7 +7,7 @@ from matplotlib import patheffects as pe
|
|
|
7
7
|
from matplotlib.axes import Axes
|
|
8
8
|
from pandas import Series, concat
|
|
9
9
|
|
|
10
|
-
from mgplot.axis_utils import map_periodindex, set_labels
|
|
10
|
+
from mgplot.axis_utils import map_periodindex, refuse_bar_axes, set_labels
|
|
11
11
|
from mgplot.keyword_checking import (
|
|
12
12
|
limit_kwargs,
|
|
13
13
|
report_kwargs,
|
|
@@ -172,6 +172,7 @@ def run_plot(data: DataT, **kwargs: Unpack[RunKwargs]) -> Axes:
|
|
|
172
172
|
# --- validate inputs
|
|
173
173
|
report_kwargs(caller=ME, **kwargs)
|
|
174
174
|
validate_kwargs(schema=RunKwargs, caller=ME, **kwargs)
|
|
175
|
+
refuse_bar_axes(kwargs.get("ax"), ME)
|
|
175
176
|
|
|
176
177
|
series = check_clean_timeseries(data, ME)
|
|
177
178
|
if not isinstance(series, Series):
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: mgplot
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.6
|
|
4
4
|
Summary: mgplot is a time-series/PeriodIndex frontend for matplotlib
|
|
5
5
|
Project-URL: Repository, https://github.com/bpalmer4/mgplot
|
|
6
6
|
Project-URL: Homepage, https://github.com/bpalmer4/mgplot
|
|
@@ -121,6 +121,15 @@ the tick density is chosen to fit within `max_ticks`, and labels show
|
|
|
121
121
|
the period with years marked at transitions (e.g. a monthly axis shows
|
|
122
122
|
`Feb Mar ... 2024 ... Feb`, a quarterly axis shows `Q2 Q3 2025 Q2`).
|
|
123
123
|
|
|
124
|
+
Contextual labels cover yearly, quarterly, monthly, weekly, daily and
|
|
125
|
+
intraday (minute, multi-minute such as `5min`, and hourly) frequencies.
|
|
126
|
+
Weekly ticks are labelled by each week's start day, or fall on the first
|
|
127
|
+
week of a month or year for longer spans. Intraday axes show times with
|
|
128
|
+
the date at each new day (`12:00` / `19 Nov 2026`, `15:00`, ... `00:00` /
|
|
129
|
+
`20 Nov`), or days, months or years for longer spans. Points sit at their
|
|
130
|
+
period ordinals, so gaps in the data (closed market hours, weekends) take
|
|
131
|
+
their real width on the axis.
|
|
132
|
+
|
|
124
133
|
Three keyword arguments control the labels on the period-indexed plot
|
|
125
134
|
functions (`line_plot`, `bar_plot`, `growth_plot`, `fill_between_plot`,
|
|
126
135
|
`run_plot`, and their `*_finalise` variants):
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
mgplot/__init__.py,sha256=H-U3paNXZY-j5GVwCHxyPNrc5ugArIid2tXSMQcGYy0,3471
|
|
2
|
+
mgplot/annotation_utils.py,sha256=p0iju88_QGsfzttK3sn53DwF4hD3ZXiCJVkE6RENovw,20972
|
|
3
|
+
mgplot/axis_utils.py,sha256=hUM0q8H4r2OyvBAi2WUj7d9T27vGCTNPtZnbr9EypZ4,30111
|
|
4
|
+
mgplot/bar_plot.py,sha256=XFehJCZG0jwMg58Xbhk2_fQKogHmE-lzfqfUJZq798o,12532
|
|
5
|
+
mgplot/colors.py,sha256=f5q4z7kORUu66uAxNeK9KAZ64gv_7h_x2qH53BvzwPw,4848
|
|
6
|
+
mgplot/fill_between_plot.py,sha256=sOBTsY0dc391Ft0Fr4cKazVzBxewxkgJS8UMLKIGuFY,3369
|
|
7
|
+
mgplot/finalise_plot.py,sha256=kTRLTNDDUEEV9qH8xIk6mYiVXkRqvQVG_OeteOZi6XE,24981
|
|
8
|
+
mgplot/finalisers.py,sha256=DJcJcuKj23TUOTofPmhuqGtHynoRYadRv0Fgo5BBChY,11984
|
|
9
|
+
mgplot/growth_plot.py,sha256=7rSHbRnXyRbC5A1qnEP3---xiITshIErenDtBCGAyzo,8811
|
|
10
|
+
mgplot/keyword_checking.py,sha256=-XXYlrfJOTQkWxA8L_FPxCfRJvKMGR9wKUQprb9O1Hs,11657
|
|
11
|
+
mgplot/line_plot.py,sha256=WtlHbbQZqJGN9VXo2sZ0mXZCSLwdrS2pCmnRfdi5fLg,10177
|
|
12
|
+
mgplot/lint-all.sh,sha256=O7ns09v0cQNQ6POWtXtYn6VdtYURHTjy06vntR8tr_U,465
|
|
13
|
+
mgplot/multi_plot.py,sha256=uJzoz1qupHjQQ_hG28iXGB3S-yAZHax6kGaLwkHMv5M,10808
|
|
14
|
+
mgplot/ohlc_plot.py,sha256=OgMtzhvdg-lxM7C0Rm7pNAUZcsaGclgFEZs_3ZCNBVU,8246
|
|
15
|
+
mgplot/postcovid_plot.py,sha256=FIuJnANOoPIwqddS2MP1_8QjReszmjJEcN5zBanafKQ,8792
|
|
16
|
+
mgplot/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
17
|
+
mgplot/revision_plot.py,sha256=GC4h-7VKBkA0wdvbzsRtOdexdjJBrqZ6cDtGaq-65LE,2238
|
|
18
|
+
mgplot/run_plot.py,sha256=LtpsHT_cYGM64LUPxWWJi4CKEBwwck6Nyo5IbE72rsQ,7497
|
|
19
|
+
mgplot/scatter_plot.py,sha256=WVPPof_W1j8sT7hUA1WeTOkCESGK--ulmME6ZSq2jPA,8188
|
|
20
|
+
mgplot/seastrend_plot.py,sha256=hi9t0cY0bHdIOU5abLMX7qvAp_hlVLlJFyEKNBzg6Ts,2000
|
|
21
|
+
mgplot/settings.py,sha256=GxIR-CvVmUwHBhD_H0MDcG1Fxc7-bUndPn4tA5MGzn4,5581
|
|
22
|
+
mgplot/summary_plot.py,sha256=Kg7VD8KFIls4KlD4jeaaXnDw51BZ3p_wMAUpjG49zGQ,11102
|
|
23
|
+
mgplot/utilities.py,sha256=269tGaEt4sMqPKSr1sUXfBjN7RLvCugLwN6EjTS2uE0,8536
|
|
24
|
+
mgplot-0.3.6.dist-info/METADATA,sha256=MsVnaI2I7gY81dSRG-41gTqCFJ5nBFBiWiPoVtGNKfw,8490
|
|
25
|
+
mgplot-0.3.6.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
26
|
+
mgplot-0.3.6.dist-info/licenses/LICENSE,sha256=6ZyruOwF8J7mY25-vZHdOibtY8cSNLz0vWeH59TLhtw,1082
|
|
27
|
+
mgplot-0.3.6.dist-info/RECORD,,
|
mgplot-0.3.4.dist-info/RECORD
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
mgplot/__init__.py,sha256=9AXauCKo2XlPP-yfDQRnEXr3X9OI2A7kCe0zDcbLRn8,3305
|
|
2
|
-
mgplot/annotation_utils.py,sha256=p0iju88_QGsfzttK3sn53DwF4hD3ZXiCJVkE6RENovw,20972
|
|
3
|
-
mgplot/axis_utils.py,sha256=oolTlkMzsBMkfpfSR1BeCunjM4nnthBJ2sDuRD1INGg,16302
|
|
4
|
-
mgplot/bar_plot.py,sha256=FobAsadYSEf-U0RZFgZutTzse4Rgr0TDFyWUMM68JVs,12513
|
|
5
|
-
mgplot/colors.py,sha256=f5q4z7kORUu66uAxNeK9KAZ64gv_7h_x2qH53BvzwPw,4848
|
|
6
|
-
mgplot/fill_between_plot.py,sha256=XJvtkBeOkohHyayQnu84jURapB5RsMAR-3SaskHkHfM,3361
|
|
7
|
-
mgplot/finalise_plot.py,sha256=8NGi2SFAABrP1vjKpHcug8OS6jWWpHErwq1mif6qCCg,24456
|
|
8
|
-
mgplot/finalisers.py,sha256=-3gSpGa4-z4JyhnrKyFyexKmYcY3u9IlHRDgsv4HqL8,11256
|
|
9
|
-
mgplot/growth_plot.py,sha256=ahGvOB2hr981KvgoqeoWb7jRg6Uag91JrD6-aKMojXM,8752
|
|
10
|
-
mgplot/keyword_checking.py,sha256=-XXYlrfJOTQkWxA8L_FPxCfRJvKMGR9wKUQprb9O1Hs,11657
|
|
11
|
-
mgplot/line_plot.py,sha256=9_peu41ivxx3VovDJ-lzM40ld7BQQwRF7BoiZBqBJ9s,10161
|
|
12
|
-
mgplot/lint-all.sh,sha256=O7ns09v0cQNQ6POWtXtYn6VdtYURHTjy06vntR8tr_U,465
|
|
13
|
-
mgplot/multi_plot.py,sha256=ONEY16Lql3a7iFzLcWSVcSnoLF0RnACsAo7_yQHJINY,10730
|
|
14
|
-
mgplot/postcovid_plot.py,sha256=FIuJnANOoPIwqddS2MP1_8QjReszmjJEcN5zBanafKQ,8792
|
|
15
|
-
mgplot/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
16
|
-
mgplot/revision_plot.py,sha256=GC4h-7VKBkA0wdvbzsRtOdexdjJBrqZ6cDtGaq-65LE,2238
|
|
17
|
-
mgplot/run_plot.py,sha256=JYNaUh_ghCa5YFE4q2qiRgXcwI9Z73OZiKbg-9fnK9o,7438
|
|
18
|
-
mgplot/scatter_plot.py,sha256=WVPPof_W1j8sT7hUA1WeTOkCESGK--ulmME6ZSq2jPA,8188
|
|
19
|
-
mgplot/seastrend_plot.py,sha256=hi9t0cY0bHdIOU5abLMX7qvAp_hlVLlJFyEKNBzg6Ts,2000
|
|
20
|
-
mgplot/settings.py,sha256=GxIR-CvVmUwHBhD_H0MDcG1Fxc7-bUndPn4tA5MGzn4,5581
|
|
21
|
-
mgplot/summary_plot.py,sha256=Kg7VD8KFIls4KlD4jeaaXnDw51BZ3p_wMAUpjG49zGQ,11102
|
|
22
|
-
mgplot/utilities.py,sha256=269tGaEt4sMqPKSr1sUXfBjN7RLvCugLwN6EjTS2uE0,8536
|
|
23
|
-
mgplot-0.3.4.dist-info/METADATA,sha256=CnV_ALt9EbHX8GyXqX1t746jMqCYMlF7xts7HMs4AHc,7950
|
|
24
|
-
mgplot-0.3.4.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
25
|
-
mgplot-0.3.4.dist-info/licenses/LICENSE,sha256=6ZyruOwF8J7mY25-vZHdOibtY8cSNLz0vWeH59TLhtw,1082
|
|
26
|
-
mgplot-0.3.4.dist-info/RECORD,,
|
|
File without changes
|