maidr 1.2.2__py3-none-any.whl → 1.4.0__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.
maidr/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
- __version__ = "1.2.2"
1
+ __version__ = "1.4.0"
2
2
 
3
3
  from .api import close, render, save_html, show, stacked
4
4
  from .core import Maidr
@@ -15,6 +15,7 @@ from .patch import (
15
15
  scatterplot,
16
16
  regplot,
17
17
  kdeplot,
18
+ mplfinance,
18
19
  )
19
20
 
20
21
  __all__ = [
maidr/core/maidr.py CHANGED
@@ -8,7 +8,7 @@ import os
8
8
  import tempfile
9
9
  import uuid
10
10
  import webbrowser
11
- from typing import Any, Literal
11
+ from typing import Any, Literal, cast
12
12
 
13
13
  import matplotlib.pyplot as plt
14
14
  from htmltools import HTML, HTMLDocument, Tag, tags
@@ -102,14 +102,20 @@ class Maidr:
102
102
  The renderer to use for the HTML preview.
103
103
  """
104
104
  html = self._create_html_tag(use_iframe=True) # Always use iframe for display
105
- _renderer = Environment.get_renderer()
106
- if _renderer == "browser" or (
107
- Environment.is_interactive_shell() and not Environment.is_notebook()
108
- ):
105
+
106
+ # Use the passed renderer parameter, fallback to auto-detection
107
+ if renderer == "auto":
108
+ _renderer = cast(Literal["ipython", "browser"], Environment.get_renderer())
109
+ else:
110
+ _renderer = renderer
111
+
112
+ # Only try browser opening if explicitly requested as browser and not in notebook
113
+ if _renderer == "browser" and not Environment.is_notebook():
109
114
  return self._open_plot_in_browser()
115
+
110
116
  if clear_fig:
111
117
  plt.close()
112
- return html.show(renderer)
118
+ return html.show(_renderer)
113
119
 
114
120
  def clear(self):
115
121
  self._plots = []
@@ -1,11 +1,12 @@
1
1
  import matplotlib.dates as mdates
2
2
  import numpy as np
3
3
  from matplotlib.axes import Axes
4
- from matplotlib.collections import LineCollection, PatchCollection
5
4
  from matplotlib.patches import Rectangle
6
5
 
7
6
  from maidr.core.enum.plot_type import PlotType
8
7
  from maidr.core.plot.maidr_plot import MaidrPlot
8
+ from maidr.core.enum.maidr_key import MaidrKey
9
+ from maidr.util.mplfinance_utils import MplfinanceDataExtractor
9
10
 
10
11
 
11
12
  class CandlestickPlot(MaidrPlot):
@@ -27,213 +28,96 @@ class CandlestickPlot(MaidrPlot):
27
28
  raise ValueError("Axes list cannot be empty.")
28
29
  super().__init__(axes[0], PlotType.CANDLESTICK)
29
30
 
31
+ # Store custom collections passed from mplfinance patch
32
+ self._maidr_wick_collection = kwargs.get("_maidr_wick_collection", None)
33
+ self._maidr_body_collection = kwargs.get("_maidr_body_collection", None)
34
+ self._maidr_date_nums = kwargs.get("_maidr_date_nums", None)
35
+
36
+ # Store the GID for proper selector generation
37
+ self._maidr_gid = None
38
+ if self._maidr_body_collection:
39
+ self._maidr_gid = self._maidr_body_collection.get_gid()
40
+ elif self._maidr_wick_collection:
41
+ self._maidr_gid = self._maidr_wick_collection.get_gid()
42
+
30
43
  def _extract_plot_data(self) -> list[dict]:
31
- """
32
- Extracts candlestick (OHLC) and volume data from the plot axes.
33
-
34
- This method assumes that the candlestick chart is structured with
35
- LineCollection for wicks and PatchCollection of Rectangles for bodies
36
- on the first axis (self.axes[0]). Volume data is expected as a
37
- PatchCollection of Rectangles on the second axis (self.axes[1]), if present.
38
- Open and close prices are inferred from the body rectangle's color.
39
-
40
- Returns
41
- -------
42
- list[dict]
43
- A list of dictionaries, where each dictionary represents a data point
44
- with 'value' (date string YYYY-MM-DD), 'open', 'high', 'low',
45
- 'close', and 'volume'. Fields that cannot be extracted will be None.
46
-
47
- Examples
48
- --------
49
- Assuming a plot has been generated and `plot_instance.axes` is populated:
50
- >>> data = plot_instance._extract_plot_data()
51
- >>> print(data[0])
52
- {
53
- 'value': '2021-01-01',
54
- 'open': 100.0,
55
- 'high': 100.9,
56
- 'low': 99.27,
57
- 'close': 100.75,
58
- 'volume': 171914,
59
- }
60
- """
44
+ """Extract candlestick data from the plot."""
45
+
46
+ # Get the custom collections from kwargs
47
+ body_collection = self._maidr_body_collection
48
+ wick_collection = self._maidr_wick_collection
49
+
50
+ if body_collection and wick_collection:
51
+ # Store the GID from the body collection for highlighting
52
+ self._maidr_gid = body_collection.get_gid()
53
+
54
+ # Use the original collections for highlighting
55
+ self._elements = [body_collection, wick_collection]
56
+
57
+ # Use the utility class to extract data
58
+ return MplfinanceDataExtractor.extract_candlestick_data(
59
+ body_collection, wick_collection, self._maidr_date_nums
60
+ )
61
+
62
+ # Fallback to original detection method
61
63
  if not self.axes:
62
64
  return []
63
65
 
64
- plot_data: list[dict] = []
65
- ax_ohlc: Axes = self.axes[0]
66
-
67
- body_rectangles: list[Rectangle] = []
68
- wick_collection: LineCollection | None = None
69
-
70
- # Find candlestick body Rectangles from the OHLC axis
71
- # Prefer PatchCollection containing Rectangles, fallback to individual Rectangles in ax.patches
72
- for collection in ax_ohlc.collections:
73
- if isinstance(collection, PatchCollection):
74
- # Check if the collection's patches are Rectangles
75
- try:
76
- # Iterating a PatchCollection yields its constituent Patch objects
77
- patches_are_rects = all(
78
- isinstance(p, Rectangle) for p in collection
79
- )
80
- if (
81
- patches_are_rects and len(collection.get_paths()) > 0
82
- ): # Ensure it has paths and they are Rectangles
83
- for (
84
- patch
85
- ) in collection: # Iterate to get actual Rectangle objects
86
- if isinstance(patch, Rectangle):
87
- body_rectangles.append(patch)
88
- if (
89
- body_rectangles
90
- ): # If we found rectangles this way, assume this is the primary body collection
91
- break
92
- except Exception:
93
- # Could fail if collection is not iterable in the expected way or patches are not Rectangles
94
- pass
95
-
96
- if not body_rectangles:
97
- for patch in ax_ohlc.patches:
98
- if isinstance(patch, Rectangle):
99
- body_rectangles.append(patch)
100
-
101
- if not body_rectangles:
102
- pass
103
-
104
- ax_for_wicks: Axes | None = None
105
- if len(self.axes) > 1:
106
- ax_for_wicks = self.axes[1]
107
-
108
- if ax_for_wicks:
109
- # Attempt 1: Find wicks in ax_for_wicks.collections (as a LineCollection)
110
- for collection in ax_for_wicks.collections:
111
- if isinstance(collection, LineCollection):
112
- segments = collection.get_segments()
113
- # Check if the collection contains segments and the first segment looks like a vertical line
114
- if segments is not None and len(segments) > 0:
115
- first_segment = segments[0]
116
- if (
117
- len(first_segment) == 2 # Segment consists of two points
118
- and len(first_segment[0]) == 2 # First point has (x, y)
119
- and len(first_segment[1]) == 2 # Second point has (x, y)
120
- and np.isclose(
121
- first_segment[0][0], first_segment[1][0]
122
- ) # X-coordinates are close (vertical)
123
- ):
124
- wick_collection = collection
125
- break # Found a suitable LineCollection
126
-
127
- # Attempt 2: If no LineCollection found, try to find wicks from individual Line2D objects in ax_for_wicks.get_lines()
128
- if not wick_collection and hasattr(ax_for_wicks, "get_lines"):
129
- potential_wick_segments = []
130
- for line in ax_for_wicks.get_lines(): # Iterate over Line2D objects
131
- x_data, y_data = line.get_data()
132
- # A wick is typically a vertical line defined by two points.
133
- if len(x_data) == 2 and len(y_data) == 2:
134
- if np.isclose(x_data[0], x_data[1]): # Check for verticality
135
- # Create a segment in the format [[x1, y1], [x2, y2]]
136
- segment = [
137
- [x_data[0], y_data[0]],
138
- [x_data[1], y_data[1]],
139
- ]
140
- potential_wick_segments.append(segment)
141
-
142
- if potential_wick_segments:
143
- # If wick segments were found from individual lines,
144
- # create a new LineCollection to hold them.
145
- # This allows the downstream processing logic
146
- # for wicks to remain consistent.
147
- # Basic properties are set; color/linestyle
148
- # are defaults and may not match
149
- # the original plot's styling if that
150
- # were relevant for segment extraction.
151
- wick_collection = LineCollection(
152
- potential_wick_segments,
153
- colors="k", # Default color for the temporary collection
154
- linestyles="solid", # Default linestyle
155
- )
156
-
157
- # Process wicks into a map: x_coordinate -> (low_price, high_price)
158
- wick_segments_map: dict[float, tuple[float, float]] = {}
159
- if wick_collection:
160
- for seg in wick_collection.get_segments():
161
- if len(seg) == 2 and len(seg[0]) == 2 and len(seg[1]) == 2:
162
- # Ensure x-coordinates are (nearly) identical for a vertical wick line
163
- if np.isclose(seg[0][0], seg[1][0]):
164
- x_coord = seg[0][0] # Matplotlib date number
165
- low_price = min(seg[0][1], seg[1][1])
166
- high_price = max(seg[0][1], seg[1][1])
167
- wick_segments_map[x_coord] = (low_price, high_price)
168
-
169
- body_rectangles.sort(key=lambda r: r.get_x())
170
-
171
- for rect in body_rectangles:
172
- x_left = rect.get_x()
173
- width = rect.get_width()
174
- x_center_num = x_left + width / 2.0
175
-
176
- try:
177
- date_dt = mdates.num2date(x_center_num)
178
- date_str = date_dt.strftime("%Y-%m-%d")
179
- except ValueError:
180
- date_str = f"raw_date_{x_center_num:.2f}"
181
-
182
- y_bottom = rect.get_y()
183
- height = rect.get_height()
184
- face_color = rect.get_facecolor() # RGBA tuple
185
-
186
- # Infer open and close prices
187
- # Heuristic: Green component > Red component for an "up" candle (close > open)
188
- # This assumes standard green for up, red for down.
189
- # A more robust method would involve knowing the exact up/down colors used.
190
- is_up_candle = (
191
- face_color[1] > face_color[0]
192
- ) # Compare Green and Red components
193
-
194
- if is_up_candle: # Typically green: price went up
195
- open_price = y_bottom
196
- close_price = y_bottom + height
197
- else: # Typically red: price went down (or other color)
198
- close_price = y_bottom
199
- open_price = y_bottom + height
200
-
201
- matched_wick_data = None
202
- closest_wick_x = None
203
- min_diff = float("inf")
204
-
205
- for wick_x, prices in wick_segments_map.items():
206
- diff = abs(wick_x - x_center_num)
207
- if diff < min_diff:
208
- min_diff = diff
209
- closest_wick_x = wick_x
210
-
211
- # Tolerance for matching wick x-coordinate (e.g., 10% of candle width)
212
- if closest_wick_x is not None and min_diff < (width * 0.1):
213
- matched_wick_data = wick_segments_map[closest_wick_x]
214
-
215
- if matched_wick_data:
216
- low_price, high_price = matched_wick_data
217
- # Ensure high >= max(open,close) and low <= min(open,close)
218
- high_price = max(high_price, open_price, close_price)
219
- low_price = min(low_price, open_price, close_price)
220
- else:
221
- # Fallback if no wick found: high is max(open,close), low is min(open,close)
222
- high_price = max(open_price, close_price)
223
- low_price = min(open_price, close_price)
224
-
225
- plot_data.append(
226
- {
227
- "value": date_str,
228
- "open": open_price,
229
- "high": high_price,
230
- "low": low_price,
231
- "close": close_price,
232
- "volume": 0,
233
- }
66
+ ax_ohlc = self.axes[0]
67
+ candles = []
68
+
69
+ # Look for Rectangle patches (original_flavor candlestick)
70
+ body_rectangles = []
71
+ for patch in ax_ohlc.patches:
72
+ if isinstance(patch, Rectangle):
73
+ body_rectangles.append(patch)
74
+
75
+ if body_rectangles:
76
+ # Set elements for highlighting
77
+ self._elements = body_rectangles
78
+
79
+ # Generate a GID for highlighting if none exists
80
+ if not self._maidr_gid:
81
+ import uuid
82
+
83
+ self._maidr_gid = f"maidr-{uuid.uuid4()}"
84
+ # Set GID on all rectangles
85
+ for rect in body_rectangles:
86
+ rect.set_gid(self._maidr_gid)
87
+
88
+ # Use the utility class to extract data
89
+ return MplfinanceDataExtractor.extract_rectangle_candlestick_data(
90
+ body_rectangles, self._maidr_date_nums
234
91
  )
235
- self._elements.extend(body_rectangles)
236
- return plot_data
92
+
93
+ return []
237
94
 
238
95
  def _extract_axes_data(self) -> dict:
239
96
  return {}
97
+
98
+ def _get_selector(self) -> str:
99
+ """Return the CSS selector for highlighting candlestick elements in the SVG output."""
100
+ # Use the stored GID if available, otherwise fall back to generic selector
101
+ if self._maidr_gid:
102
+ # Use the full GID as the id attribute (since that's what's in the SVG)
103
+ selector = (
104
+ f"g[id='{self._maidr_gid}'] > path, g[id='{self._maidr_gid}'] > rect"
105
+ )
106
+ else:
107
+ selector = "g[maidr='true'] > path, g[maidr='true'] > rect"
108
+ return selector
109
+
110
+ def render(self) -> dict:
111
+ """Initialize the MAIDR schema dictionary with basic plot information."""
112
+ maidr_schema = {
113
+ MaidrKey.TYPE: self.type,
114
+ MaidrKey.TITLE: self.ax.get_title(),
115
+ MaidrKey.AXES: self._extract_axes_data(),
116
+ MaidrKey.DATA: self._extract_plot_data(),
117
+ }
118
+
119
+ # Include selector only if the plot supports highlighting.
120
+ if self._support_highlighting:
121
+ maidr_schema[MaidrKey.SELECTOR] = self._get_selector()
122
+
123
+ return maidr_schema
@@ -42,8 +42,13 @@ class MaidrPlot(ABC):
42
42
  self._support_highlighting = True
43
43
  self._elements = []
44
44
  ss = self.ax.get_subplotspec()
45
- self.row_index = ss.rowspan.start
46
- self.col_index = ss.colspan.start
45
+ # Handle cases where subplotspec is None (dynamically created axes)
46
+ if ss is not None:
47
+ self.row_index = ss.rowspan.start
48
+ self.col_index = ss.colspan.start
49
+ else:
50
+ self.row_index = 0
51
+ self.col_index = 0
47
52
 
48
53
  # MAIDR data
49
54
  self.type = plot_type
@@ -1,7 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from matplotlib.axes import Axes
4
-
5
4
  from maidr.core.enum import PlotType
6
5
  from maidr.core.plot.barplot import BarPlot
7
6
  from maidr.core.plot.boxplot import BoxPlot
@@ -13,6 +12,9 @@ from maidr.core.plot.lineplot import MultiLinePlot
13
12
  from maidr.core.plot.maidr_plot import MaidrPlot
14
13
  from maidr.core.plot.scatterplot import ScatterPlot
15
14
  from maidr.core.plot.regplot import SmoothPlot
15
+ from maidr.core.plot.mplfinance_barplot import MplfinanceBarPlot
16
+ from maidr.core.plot.mplfinance_lineplot import MplfinanceLinePlot
17
+ from maidr.util.plot_detection import PlotDetectionUtils
16
18
 
17
19
 
18
20
  class MaidrPlotFactory:
@@ -38,17 +40,13 @@ class MaidrPlotFactory:
38
40
  single_ax = ax
39
41
 
40
42
  if plot_type == PlotType.CANDLESTICK:
41
- if isinstance(ax, list):
42
- # If ax is a list of lists, flatten it
43
- if ax and isinstance(ax[0], list):
44
- axes = ax[0] # Take the first inner list
45
- else:
46
- axes = ax # Use the list as-is
47
- else:
48
- axes = [ax] # Wrap single axes in list
43
+ axes = PlotDetectionUtils.get_candlestick_axes(ax)
49
44
  return CandlestickPlot(axes, **kwargs)
50
45
  elif PlotType.BAR == plot_type or PlotType.COUNT == plot_type:
51
- return BarPlot(single_ax)
46
+ if PlotDetectionUtils.is_mplfinance_bar_plot(**kwargs):
47
+ return MplfinanceBarPlot(single_ax, **kwargs)
48
+ else:
49
+ return BarPlot(single_ax)
52
50
  elif PlotType.BOX == plot_type:
53
51
  return BoxPlot(single_ax, **kwargs)
54
52
  elif PlotType.HEAT == plot_type:
@@ -56,7 +54,10 @@ class MaidrPlotFactory:
56
54
  elif PlotType.HIST == plot_type:
57
55
  return HistPlot(single_ax)
58
56
  elif PlotType.LINE == plot_type:
59
- return MultiLinePlot(single_ax)
57
+ if PlotDetectionUtils.is_mplfinance_line_plot(single_ax, **kwargs):
58
+ return MplfinanceLinePlot(single_ax, **kwargs)
59
+ else:
60
+ return MultiLinePlot(single_ax, **kwargs)
60
61
  elif PlotType.SCATTER == plot_type:
61
62
  return ScatterPlot(single_ax)
62
63
  elif PlotType.DODGED == plot_type or PlotType.STACKED == plot_type:
@@ -0,0 +1,115 @@
1
+ from __future__ import annotations
2
+
3
+ from matplotlib.axes import Axes
4
+ from matplotlib.patches import Rectangle
5
+
6
+ from maidr.core.enum import PlotType
7
+ from maidr.core.plot import MaidrPlot
8
+ from maidr.exception import ExtractionError
9
+ from maidr.util.mixin import (
10
+ ContainerExtractorMixin,
11
+ DictMergerMixin,
12
+ LevelExtractorMixin,
13
+ )
14
+ from maidr.util.mplfinance_utils import MplfinanceDataExtractor
15
+
16
+
17
+ class MplfinanceBarPlot(
18
+ MaidrPlot, ContainerExtractorMixin, LevelExtractorMixin, DictMergerMixin
19
+ ):
20
+ """
21
+ Specialized bar plot class for mplfinance volume bars.
22
+
23
+ This class handles the extraction and processing of volume data from mplfinance
24
+ plots, including proper date conversion and data validation.
25
+ """
26
+
27
+ def __init__(self, ax: Axes, **kwargs) -> None:
28
+ super().__init__(ax, PlotType.BAR)
29
+ # Store custom patches passed from mplfinance patch
30
+ self._custom_patches = kwargs.get("_maidr_patches", None)
31
+ # Store date numbers for volume bars (from mplfinance)
32
+ self._maidr_date_nums = kwargs.get("_maidr_date_nums", None)
33
+
34
+ def _extract_plot_data(self) -> list:
35
+ """Extract data from mplfinance volume patches."""
36
+ if self._custom_patches:
37
+ return self._extract_volume_patches_data(self._custom_patches)
38
+
39
+ # Fallback to original bar plot logic if no custom patches
40
+ plot = self.extract_container(
41
+ self.ax, ContainerExtractorMixin, include_all=True
42
+ )
43
+ data = self._extract_bar_container_data(plot)
44
+ levels = self.extract_level(self.ax)
45
+ formatted_data = []
46
+ combined_data = list(
47
+ zip(levels, data) if plot[0].orientation == "vertical" else zip(data, levels) # type: ignore
48
+ )
49
+ if combined_data: # type: ignore
50
+ for x, y in combined_data: # type: ignore
51
+ formatted_data.append({"x": x, "y": y})
52
+ return formatted_data
53
+ if len(formatted_data) == 0:
54
+ raise ExtractionError(self.type, plot)
55
+ if data is None:
56
+ raise ExtractionError(self.type, plot)
57
+
58
+ return data
59
+
60
+ def _extract_volume_patches_data(self, volume_patches: list[Rectangle]) -> list:
61
+ """
62
+ Extract data from volume Rectangle patches (used by mplfinance volume bars).
63
+ """
64
+ if not volume_patches:
65
+ return []
66
+
67
+ # Sort patches by x-coordinate to maintain order
68
+ sorted_patches = sorted(volume_patches, key=lambda p: p.get_x())
69
+
70
+ # Set elements for highlighting (use the patches directly)
71
+ self._elements = sorted_patches
72
+
73
+ # Use the utility class to extract data
74
+ return MplfinanceDataExtractor.extract_volume_data(
75
+ sorted_patches, self._maidr_date_nums
76
+ )
77
+
78
+ def _extract_bar_container_data(self, plot: list | None) -> list | None:
79
+ """Fallback method for regular bar containers."""
80
+ if plot is None:
81
+ return None
82
+
83
+ # Since v0.13, Seaborn has transitioned from using `list[Patch]` to
84
+ # `list[BarContainers] for plotting bar plots.
85
+ # So, extract data correspondingly based on the level.
86
+ # Flatten all the `list[BarContainer]` to `list[Patch]`.
87
+ patches = [patch for container in plot for patch in container.patches]
88
+ level = self.extract_level(self.ax)
89
+ if level is None or len(level) == 0: # type: ignore
90
+ level = ["" for _ in range(len(patches))] # type: ignore
91
+
92
+ if len(patches) != len(level):
93
+ return None
94
+
95
+ self._elements.extend(patches)
96
+
97
+ return [float(patch.get_height()) for patch in patches]
98
+
99
+ def _extract_axes_data(self) -> dict:
100
+ """Extract axes data with mplfinance-specific cleaning."""
101
+ ax_data = super()._extract_axes_data()
102
+
103
+ # For mplfinance volume plots, clean up the y-axis label
104
+ if self._custom_patches:
105
+ y_label = ax_data.get("y")
106
+ if y_label:
107
+ ax_data["y"] = MplfinanceDataExtractor.clean_axis_label(y_label)
108
+
109
+ return ax_data
110
+
111
+ def _get_selector(self) -> str:
112
+ """Return the CSS selector for highlighting bar elements in the SVG output."""
113
+ # Use the standard working selector that gets replaced with UUID by Maidr class
114
+ # This works for both original bar plots and mplfinance volume bars
115
+ return "g[maidr='true'] > path"