Beispiel #1
0
    def __init__(self, index, columns, ndim, freq=None, column_only_select=None,
                 group_select=None, grouped_ndim=None, **kwargs):
        config = dict(
            index=index,
            columns=columns,
            ndim=ndim,
            freq=freq,
            column_only_select=column_only_select,
            group_select=group_select,
            grouped_ndim=grouped_ndim,
        )

        checks.assert_not_none(index)
        checks.assert_not_none(columns)
        checks.assert_not_none(ndim)
        if not isinstance(index, pd.Index):
            index = pd.Index(index)
        if not isinstance(columns, pd.Index):
            columns = pd.Index(columns)

        self._index = index
        self._columns = columns
        self._ndim = ndim
        self._freq = freq
        self._column_only_select = column_only_select
        self._group_select = group_select
        self._grouper = ColumnGrouper(columns, **kwargs)
        self._grouped_ndim = grouped_ndim

        PandasIndexer.__init__(self)
        Configured.__init__(self, **merge_dicts(config, self._grouper._config))
Beispiel #2
0
    def __init__(self, wrapper, mapped_arr, col_arr, idx_arr=None):
        Configured.__init__(
            self,
            wrapper=wrapper,
            mapped_arr=mapped_arr,
            col_arr=col_arr,
            idx_arr=idx_arr
        )
        checks.assert_type(wrapper, ArrayWrapper)
        if not isinstance(mapped_arr, np.ndarray):
            mapped_arr = np.asarray(mapped_arr)
        if not isinstance(col_arr, np.ndarray):
            col_arr = np.asarray(col_arr)
        checks.assert_shape_equal(mapped_arr, col_arr, axis=0)
        if idx_arr is not None:
            if not isinstance(idx_arr, np.ndarray):
                idx_arr = np.asarray(idx_arr)
            checks.assert_shape_equal(mapped_arr, idx_arr, axis=0)

        self._wrapper = wrapper
        self._mapped_arr = mapped_arr
        self._col_arr = col_arr
        self._idx_arr = idx_arr

        PandasIndexer.__init__(self, _mapped_array_indexing_func)
Beispiel #3
0
    def __init__(self, wrapper: ArrayWrapper, **kwargs) -> None:
        checks.assert_instance_of(wrapper, ArrayWrapper)
        self._wrapper = wrapper

        Configured.__init__(self, wrapper=wrapper, **kwargs)
        PandasIndexer.__init__(self)
        AttrResolver.__init__(self)
Beispiel #4
0
 def __init__(self, data, schedule_manager=None, **kwargs):
     Configured.__init__(self,
                         data=data,
                         schedule_manager=schedule_manager,
                         **kwargs)
     self._data = data
     if schedule_manager is None:
         schedule_manager = ScheduleManager()
     self._schedule_manager = schedule_manager
Beispiel #5
0
    def __init__(self, giphy_kwargs: tp.KwargsLike = None, **kwargs) -> None:
        from vectorbt._settings import settings
        telegram_cfg = settings['messaging']['telegram']
        giphy_cfg = settings['messaging']['giphy']

        Configured.__init__(self, giphy_kwargs=giphy_kwargs, **kwargs)

        # Resolve kwargs
        giphy_kwargs = merge_dicts(giphy_cfg, giphy_kwargs)
        self.giphy_kwargs = giphy_kwargs
        default_kwargs = dict()
        passed_kwargs = dict()
        for k in get_func_kwargs(Updater):
            if k in telegram_cfg:
                default_kwargs[k] = telegram_cfg[k]
            if k in kwargs:
                passed_kwargs[k] = kwargs.pop(k)
        updater_kwargs = merge_dicts(default_kwargs, passed_kwargs)
        persistence = updater_kwargs.pop('persistence', None)
        if isinstance(persistence, str):
            persistence = PicklePersistence(persistence)
        defaults = updater_kwargs.pop('defaults', None)
        if isinstance(defaults, dict):
            defaults = Defaults(**defaults)

        # Create the (persistent) Updater and pass it your bot's token.
        logger.info("Initializing bot")
        self._updater = Updater(persistence=persistence,
                                defaults=defaults,
                                **updater_kwargs)

        # Get the dispatcher to register handlers
        self._dispatcher = self.updater.dispatcher

        # Register handlers
        self.dispatcher.add_handler(self.log_handler)
        self.dispatcher.add_handler(
            CommandHandler('start', self.start_callback))
        self.dispatcher.add_handler(CommandHandler("help", self.help_callback))
        for handler in self.custom_handlers:
            self.dispatcher.add_handler(handler)
        self.dispatcher.add_handler(
            MessageHandler(Filters.status_update.migrate,
                           self.chat_migration_callback))
        self.dispatcher.add_handler(
            MessageHandler(Filters.command, self.unknown_callback))
        self.dispatcher.add_error_handler(
            self_decorator(self, self.__class__.error_callback))

        # Set up data
        if 'chat_ids' not in self.dispatcher.bot_data:
            self.dispatcher.bot_data['chat_ids'] = []
        else:
            logger.info("Loaded chat ids %s",
                        str(self.dispatcher.bot_data['chat_ids']))
Beispiel #6
0
 def __init__(self,
              data: Data,
              schedule_manager: tp.Optional[ScheduleManager] = None,
              **kwargs) -> None:
     Configured.__init__(self,
                         data=data,
                         schedule_manager=schedule_manager,
                         **kwargs)
     self._data = data
     if schedule_manager is None:
         schedule_manager = ScheduleManager()
     self._schedule_manager = schedule_manager
Beispiel #7
0
    def __init__(self,
                 returns_accessor: ReturnsAccessor,
                 defaults: tp.KwargsLike = None,
                 **kwargs) -> None:
        checks.assert_instance_of(returns_accessor, ReturnsAccessor)

        Configured.__init__(self,
                            returns_accessor=returns_accessor,
                            defaults=defaults,
                            **kwargs)

        self._returns_accessor = returns_accessor
        self._defaults = defaults
Beispiel #8
0
    def __init__(self,
                 index,
                 columns,
                 ndim,
                 freq=None,
                 column_only_select=None,
                 group_select=None,
                 grouped_ndim=None,
                 group_by=None,
                 allow_enable=True,
                 allow_disable=True,
                 allow_modify=True):
        Configured.__init__(self,
                            index=index,
                            columns=columns,
                            ndim=ndim,
                            freq=freq,
                            column_only_select=column_only_select,
                            group_select=group_select,
                            grouped_ndim=grouped_ndim,
                            group_by=group_by,
                            allow_enable=allow_enable,
                            allow_disable=allow_disable,
                            allow_modify=allow_modify)

        checks.assert_not_none(index)
        checks.assert_not_none(columns)
        checks.assert_not_none(ndim)
        if not isinstance(index, pd.Index):
            index = pd.Index(index)
        if not isinstance(columns, pd.Index):
            columns = pd.Index(columns)

        self._index = index
        self._columns = columns
        self._ndim = ndim
        self._freq = freq
        self._column_only_select = column_only_select
        self._group_select = group_select
        self._grouper = ColumnGrouper(columns,
                                      group_by=group_by,
                                      allow_enable=allow_enable,
                                      allow_disable=allow_disable,
                                      allow_modify=allow_modify)
        self._grouped_ndim = grouped_ndim

        PandasIndexer.__init__(self,
                               _indexing_func,
                               column_only_select=column_only_select,
                               group_select=group_select)
Beispiel #9
0
    def __init__(self, wrapper, records_arr, ts, idx_field='end_idx'):
        Records.__init__(self, wrapper, records_arr, idx_field=idx_field)
        Configured.__init__(self,
                            wrapper=wrapper,
                            records_arr=records_arr,
                            ts=ts,
                            idx_field=idx_field)
        self._ts = ts

        if not all(field in records_arr.dtype.names
                   for field in drawdown_dt.names):
            raise ValueError(
                "Records array must have all fields defined in drawdown_dt")

        PandasIndexer.__init__(self, _indexing_func)
Beispiel #10
0
    def __init__(self, wrapper, records_arr, close, idx_field='exit_idx'):
        Records.__init__(self, wrapper, records_arr, idx_field=idx_field)
        Configured.__init__(self,
                            wrapper=wrapper,
                            records_arr=records_arr,
                            close=close,
                            idx_field=idx_field)
        self.close = close

        if not all(field in records_arr.dtype.names
                   for field in event_dt.names):
            raise ValueError(
                "Records array must have all fields defined in event_dt")

        PandasIndexer.__init__(self, _indexing_func)
Beispiel #11
0
    def replace(self: MappedArrayT, **kwargs) -> MappedArrayT:
        """See `vectorbt.utils.config.Configured.replace`.

        Also, makes sure that `MappedArray.col_mapper` is not passed to the new instance."""
        if self.config.get('col_mapper', None) is not None:
            if 'wrapper' in kwargs:
                if self.wrapper is not kwargs.get('wrapper'):
                    kwargs['col_mapper'] = None
            if 'col_arr' in kwargs:
                if self.col_arr is not kwargs.get('col_arr'):
                    kwargs['col_mapper'] = None
        return Configured.replace(self, **kwargs)
Beispiel #12
0
    def __init__(self, wrapper, records_arr, idx_field=None):
        Configured.__init__(self,
                            wrapper=wrapper,
                            records_arr=records_arr,
                            idx_field=idx_field)
        checks.assert_type(wrapper, ArrayWrapper)
        if not isinstance(records_arr, np.ndarray):
            records_arr = np.asarray(records_arr)
        checks.assert_not_none(records_arr.dtype.fields)
        checks.assert_in('col', records_arr.dtype.names)
        if idx_field is not None:
            checks.assert_in(idx_field, records_arr.dtype.names)
        else:
            if 'idx' in records_arr.dtype.names:
                idx_field = 'idx'

        self._wrapper = wrapper
        self._records_arr = records_arr
        self._idx_field = idx_field

        PandasIndexer.__init__(self, _records_indexing_func)
Beispiel #13
0
    def __init__(self, columns, group_by=None, allow_enable=True, allow_disable=True, allow_modify=True):
        Configured.__init__(
            self,
            columns=columns,
            group_by=group_by,
            allow_enable=allow_enable,
            allow_disable=allow_disable,
            allow_modify=allow_modify
        )

        checks.assert_not_none(columns)
        self._columns = columns
        if group_by is None or isinstance(group_by, bool):
            self._group_by = None
        else:
            self._group_by = group_by_to_index(columns, group_by)

        # Everything is allowed by default
        self._allow_enable = allow_enable
        self._allow_disable = allow_disable
        self._allow_modify = allow_modify
Beispiel #14
0
    def __init__(self, columns: tp.Index, group_by: tp.GroupByLike = None, allow_enable: bool = True,
                 allow_disable: bool = True, allow_modify: bool = True) -> None:
        Configured.__init__(
            self,
            columns=columns,
            group_by=group_by,
            allow_enable=allow_enable,
            allow_disable=allow_disable,
            allow_modify=allow_modify
        )

        checks.assert_type(columns, pd.Index)
        self._columns = columns
        if group_by is None or group_by is False:
            self._group_by = None
        else:
            self._group_by = group_by_to_index(columns, group_by)

        # Everything is allowed by default
        self._allow_enable = allow_enable
        self._allow_disable = allow_disable
        self._allow_modify = allow_modify
Beispiel #15
0
    def __init__(self,
                 index: tp.IndexLike,
                 columns: tp.IndexLike,
                 ndim: int,
                 freq: tp.Optional[tp.FrequencyLike] = None,
                 column_only_select: tp.Optional[bool] = None,
                 group_select: tp.Optional[bool] = None,
                 grouped_ndim: tp.Optional[int] = None,
                 **kwargs) -> None:
        config = dict(
            index=index,
            columns=columns,
            ndim=ndim,
            freq=freq,
            column_only_select=column_only_select,
            group_select=group_select,
            grouped_ndim=grouped_ndim,
        )

        checks.assert_not_none(index)
        checks.assert_not_none(columns)
        checks.assert_not_none(ndim)
        if not isinstance(index, pd.Index):
            index = pd.Index(index)
        if not isinstance(columns, pd.Index):
            columns = pd.Index(columns)

        self._index = index
        self._columns = columns
        self._ndim = ndim
        self._freq = freq
        self._column_only_select = column_only_select
        self._group_select = group_select
        self._grouper = ColumnGrouper(columns, **kwargs)
        self._grouped_ndim = grouped_ndim

        PandasIndexer.__init__(self)
        Configured.__init__(self, **merge_dicts(config, self._grouper._config))
Beispiel #16
0
    def __init__(self,
                 data=None,
                 x_labels=None,
                 y_labels=None,
                 z_labels=False,
                 trace_kwargs=None,
                 add_trace_kwargs=None,
                 scene_name='scene',
                 fig=None,
                 **layout_kwargs):
        """Create a volume plot.

        Args:
            data (array_like): Data in any format that can be converted to NumPy.

                Must be a 3-dim array.
            x_labels (array_like): X-axis labels.
            y_labels (array_like): Y-axis labels.
            z_labels (array_like): Z-axis labels.
            trace_kwargs (dict): Keyword arguments passed to `plotly.graph_objects.Volume`.
            add_trace_kwargs (dict): Keyword arguments passed to `add_trace`.
            scene_name (str): Reference to the 3D scene.
            fig (plotly.graph_objects.Figure): Figure to add traces to.
            **layout_kwargs: Keyword arguments for layout.

        !!! note
            Figure widgets have currently problems displaying NaNs.
            Use `.show()` method for rendering.

        ## Example

        ```python-repl
        >>> import vectorbt as vbt
        >>> import numpy as np

        >>> volume = vbt.plotting.Volume(
        ...     data=np.random.randint(1, 10, size=(3, 3, 3)),
        ...     x_labels=['a', 'b', 'c'],
        ...     y_labels=['d', 'e', 'f'],
        ...     z_labels=['g', 'h', 'i']
        ... )
        >>> volume.fig
        ```

        ![](/vectorbt/docs/img/Volume.png)
        """
        Configured.__init__(self,
                            data=data,
                            x_labels=x_labels,
                            y_labels=y_labels,
                            z_labels=z_labels,
                            trace_kwargs=trace_kwargs,
                            add_trace_kwargs=add_trace_kwargs,
                            scene_name=scene_name,
                            fig=fig,
                            **layout_kwargs)

        from vectorbt.settings import layout

        if trace_kwargs is None:
            trace_kwargs = {}
        if add_trace_kwargs is None:
            add_trace_kwargs = {}
        if data is None:
            if x_labels is None or y_labels is None or z_labels is None:
                raise ValueError(
                    "At least x_labels, y_labels and z_labels must be passed")
            x_len = len(x_labels)
            y_len = len(y_labels)
            z_len = len(z_labels)
        else:
            checks.assert_ndim(data, 3)
            data = np.asarray(data)
            x_len, y_len, z_len = data.shape
        if x_labels is None:
            x_labels = np.arange(x_len)
        else:
            x_labels = clean_labels(x_labels)
        if y_labels is None:
            y_labels = np.arange(y_len)
        else:
            y_labels = clean_labels(y_labels)
        if z_labels is None:
            z_labels = np.arange(z_len)
        else:
            z_labels = clean_labels(z_labels)
        x_labels = np.asarray(x_labels)
        y_labels = np.asarray(y_labels)
        z_labels = np.asarray(z_labels)

        if fig is None:
            fig = FigureWidget()
            if 'width' in layout:
                # Calculate nice width and height
                fig.update_layout(width=layout['width'],
                                  height=0.7 * layout['width'])

        # Non-numeric data types are not supported by go.Volume, so use ticktext
        # Note: Currently plotly displays the entire tick array, in future versions it will be more sensible
        more_layout = dict()
        if not np.issubdtype(x_labels.dtype, np.number):
            x_ticktext = x_labels
            x_labels = np.arange(x_len)
            more_layout[scene_name] = dict(xaxis=dict(
                ticktext=x_ticktext, tickvals=x_labels, tickmode='array'))
        if not np.issubdtype(y_labels.dtype, np.number):
            y_ticktext = y_labels
            y_labels = np.arange(y_len)
            more_layout[scene_name] = dict(yaxis=dict(
                ticktext=y_ticktext, tickvals=y_labels, tickmode='array'))
        if not np.issubdtype(z_labels.dtype, np.number):
            z_ticktext = z_labels
            z_labels = np.arange(z_len)
            more_layout[scene_name] = dict(zaxis=dict(
                ticktext=z_ticktext, tickvals=z_labels, tickmode='array'))
        fig.update_layout(**more_layout)
        fig.update_layout(**layout_kwargs)

        # Arrays must have the same length as the flattened data array
        x = np.repeat(x_labels, len(y_labels) * len(z_labels))
        y = np.tile(np.repeat(y_labels, len(z_labels)), len(x_labels))
        z = np.tile(z_labels, len(x_labels) * len(y_labels))

        volume = go.Volume(
            x=x,
            y=y,
            z=z,
            opacity=0.2,
            surface_count=15,  # keep low for big data
            colorscale='Plasma')
        volume.update(**trace_kwargs)
        fig.add_trace(volume, **add_trace_kwargs)

        TraceUpdater.__init__(self, fig, [fig.data[-1]])

        if data is not None:
            self.update(data)
Beispiel #17
0
    def __init__(self,
                 data=None,
                 x_labels=None,
                 y_labels=None,
                 trace_kwargs=None,
                 add_trace_kwargs=None,
                 fig=None,
                 **layout_kwargs):
        """Create a heatmap plot.

        Args:
            data (array_like): Data in any format that can be converted to NumPy.

                Must be of shape (`y_labels`, `x_labels`).
            x_labels (array_like): X-axis labels, corresponding to columns in pandas.
            y_labels (array_like): Y-axis labels, corresponding to index in pandas.
            trace_kwargs (dict): Keyword arguments passed to `plotly.graph_objects.Heatmap`.
            add_trace_kwargs (dict): Keyword arguments passed to `add_trace`.
            fig (plotly.graph_objects.Figure): Figure to add traces to.
            **layout_kwargs: Keyword arguments for layout.

        ## Example

        ```python-repl
        >>> import vectorbt as vbt

        >>> heatmap = vbt.plotting.Heatmap(
        ...     data=[[1, 2], [3, 4]],
        ...     x_labels=['a', 'b'],
        ...     y_labels=['x', 'y']
        ... )
        >>> heatmap.fig
        ```
        ![](/vectorbt/docs/img/Heatmap.png)
        """
        Configured.__init__(self,
                            data=data,
                            x_labels=x_labels,
                            y_labels=y_labels,
                            trace_kwargs=trace_kwargs,
                            add_trace_kwargs=add_trace_kwargs,
                            fig=fig,
                            **layout_kwargs)

        from vectorbt.settings import layout

        if trace_kwargs is None:
            trace_kwargs = {}
        if add_trace_kwargs is None:
            add_trace_kwargs = {}
        if data is None:
            if x_labels is None or y_labels is None:
                raise ValueError(
                    "At least x_labels and y_labels must be passed")
        else:
            data = reshape_fns.to_2d(np.array(data))
        if x_labels is not None:
            x_labels = clean_labels(x_labels)
        if y_labels is not None:
            y_labels = clean_labels(y_labels)

        if fig is None:
            fig = FigureWidget()
            if 'width' in layout:
                # Calculate nice width and height
                max_width = layout['width']
                if data is not None:
                    x_len = data.shape[1]
                    y_len = data.shape[0]
                else:
                    x_len = len(x_labels)
                    y_len = len(y_labels)
                width = math.ceil(
                    renormalize(x_len / (x_len + y_len), [0, 1],
                                [0.3 * max_width, max_width]))
                width = min(width + 150, max_width)  # account for colorbar
                height = math.ceil(
                    renormalize(y_len / (x_len + y_len), [0, 1],
                                [0.3 * max_width, max_width]))
                height = min(height, max_width * 0.7)  # limit height
                fig.update_layout(width=width, height=height)

        fig.update_layout(**layout_kwargs)

        heatmap = go.Heatmap(hoverongaps=False,
                             colorscale='Plasma',
                             x=x_labels,
                             y=y_labels)
        heatmap.update(**trace_kwargs)
        fig.add_trace(heatmap, **add_trace_kwargs)

        TraceUpdater.__init__(self, fig, [fig.data[-1]])

        if data is not None:
            self.update(data)
Beispiel #18
0
    def __init__(self,
                 value=None,
                 label=None,
                 value_range=None,
                 cmap_name='Spectral',
                 trace_kwargs=None,
                 add_trace_kwargs=None,
                 fig=None,
                 **layout_kwargs):
        """Create an indicator plot.

        Args:
            value (int or float): The value to be displayed.
            label (str): The label to be displayed.
            value_range (list or tuple of 2 values): The value range of the gauge.
            cmap_name (str): A matplotlib-compatible colormap name.

                See the [list of available colormaps](https://matplotlib.org/tutorials/colors/colormaps.html).
            trace_kwargs (dict): Keyword arguments passed to the `plotly.graph_objects.Indicator`.
            add_trace_kwargs (dict): Keyword arguments passed to `add_trace`.
            fig (plotly.graph_objects.Figure): Figure to add traces to.
            **layout_kwargs: Keyword arguments for layout.

        ## Example

        ```python-repl
        >>> import vectorbt as vbt

        >>> indicator = vbt.plotting.Indicator(
        ...     value=2,
        ...     value_range=(1, 3),
        ...     label='My Indicator'
        ... )
        >>> indicator.fig
        ```
        ![](/vectorbt/docs/img/Indicator.png)
        """
        Configured.__init__(self,
                            value=value,
                            label=label,
                            value_range=value_range,
                            cmap_name=cmap_name,
                            trace_kwargs=trace_kwargs,
                            add_trace_kwargs=add_trace_kwargs,
                            fig=fig,
                            **layout_kwargs)

        from vectorbt.settings import layout

        if trace_kwargs is None:
            trace_kwargs = {}
        if add_trace_kwargs is None:
            add_trace_kwargs = {}

        if fig is None:
            fig = FigureWidget()
            if 'width' in layout:
                # Calculate nice width and height
                fig.update_layout(width=layout['width'] * 0.7,
                                  height=layout['width'] * 0.5,
                                  margin=dict(t=80))
        fig.update_layout(**layout_kwargs)

        indicator = go.Indicator(domain=dict(x=[0, 1], y=[0, 1]),
                                 mode="gauge+number+delta",
                                 title=dict(text=label))
        indicator.update(**trace_kwargs)
        fig.add_trace(indicator, **add_trace_kwargs)

        TraceUpdater.__init__(self, fig, [fig.data[-1]])
        self.value_range = value_range
        self.cmap_name = cmap_name

        if value is not None:
            self.update(value)
Beispiel #19
0
    def __init__(self,
                 data=None,
                 trace_names=None,
                 horizontal=False,
                 remove_nan=True,
                 from_quantile=None,
                 to_quantile=None,
                 trace_kwargs=None,
                 add_trace_kwargs=None,
                 fig=None,
                 **layout_kwargs):
        """Create a box plot.

        For keyword arguments, see `Histogram`.

        ## Example

        ```python-repl
        >>> import vectorbt as vbt

        >>> box = vbt.plotting.Box(
        ...     data=[[1, 2], [3, 4], [2, 1]],
        ...     trace_names=['a', 'b']
        ... )
        >>> box.fig
        ```
        ![](/vectorbt/docs/img/Box.png)
        """
        Configured.__init__(self,
                            data=data,
                            trace_names=trace_names,
                            horizontal=horizontal,
                            remove_nan=remove_nan,
                            from_quantile=from_quantile,
                            to_quantile=to_quantile,
                            trace_kwargs=trace_kwargs,
                            add_trace_kwargs=add_trace_kwargs,
                            fig=fig,
                            **layout_kwargs)

        if trace_kwargs is None:
            trace_kwargs = {}
        if add_trace_kwargs is None:
            add_trace_kwargs = {}
        if data is None:
            if trace_names is None:
                raise ValueError("At least trace_names must be passed")
        if trace_names is None:
            data = reshape_fns.to_2d(data)
            trace_names = [None] * data.shape[1]
        if isinstance(trace_names, str):
            trace_names = [trace_names]

        if fig is None:
            fig = FigureWidget()
        fig.update_layout(**layout_kwargs)

        for i, trace_name in enumerate(trace_names):
            _trace_kwargs = trace_kwargs[i] if isinstance(
                trace_kwargs, (list, tuple)) else trace_kwargs
            trace_name = _trace_kwargs.pop('name', trace_name)
            if trace_name is not None:
                trace_name = str(trace_name)
            box = go.Box(name=trace_name, showlegend=trace_name is not None)
            box.update(**_trace_kwargs)
            fig.add_trace(box, **add_trace_kwargs)

        TraceUpdater.__init__(self, fig, fig.data[-len(trace_names):])
        self.horizontal = horizontal
        self.remove_nan = remove_nan
        self.from_quantile = from_quantile
        self.to_quantile = to_quantile

        if data is not None:
            self.update(data)
Beispiel #20
0
    def __init__(self,
                 data=None,
                 trace_names=None,
                 horizontal=False,
                 remove_nan=True,
                 from_quantile=None,
                 to_quantile=None,
                 trace_kwargs=None,
                 add_trace_kwargs=None,
                 fig=None,
                 **layout_kwargs):
        """Create a histogram plot.

        Args:
            data (array_like): Data in any format that can be converted to NumPy.

                Must be of shape (any, `trace_names`).
            trace_names (str or list of str): Trace names, corresponding to columns in pandas.
            horizontal (bool): Plot horizontally.
            remove_nan (bool): Whether to remove NaN values.
            from_quantile (float): Filter out data points before this quantile.

                Should be in range `[0, 1]`.
            to_quantile (float): Filter out data points after this quantile.

                Should be in range `[0, 1]`.
            trace_kwargs (dict): Keyword arguments passed to `plotly.graph_objects.Histogram`.
            add_trace_kwargs (dict): Keyword arguments passed to `add_trace`.
            fig (plotly.graph_objects.Figure): Figure to add traces to.
            **layout_kwargs: Keyword arguments for layout.

        ## Example

        ```python-repl
        >>> import vectorbt as vbt

        >>> hist = vbt.plotting.Histogram(
        ...     data=[[1, 2], [3, 4], [2, 1]],
        ...     trace_names=['a', 'b']
        ... )
        >>> hist.fig
        ```
        ![](/vectorbt/docs/img/Histogram.png)
        """
        Configured.__init__(self,
                            data=data,
                            trace_names=trace_names,
                            horizontal=horizontal,
                            remove_nan=remove_nan,
                            from_quantile=from_quantile,
                            to_quantile=to_quantile,
                            trace_kwargs=trace_kwargs,
                            add_trace_kwargs=add_trace_kwargs,
                            fig=fig,
                            **layout_kwargs)

        if trace_kwargs is None:
            trace_kwargs = {}
        if add_trace_kwargs is None:
            add_trace_kwargs = {}
        if data is None:
            if trace_names is None:
                raise ValueError("At least trace_names must be passed")
        if trace_names is None:
            data = reshape_fns.to_2d(data)
            trace_names = [None] * data.shape[1]
        if isinstance(trace_names, str):
            trace_names = [trace_names]

        if fig is None:
            fig = FigureWidget()
            fig.update_layout(barmode='overlay')
        fig.update_layout(**layout_kwargs)

        for i, trace_name in enumerate(trace_names):
            _trace_kwargs = trace_kwargs[i] if isinstance(
                trace_kwargs, (list, tuple)) else trace_kwargs
            trace_name = _trace_kwargs.pop('name', trace_name)
            if trace_name is not None:
                trace_name = str(trace_name)
            hist = go.Histogram(opacity=0.75 if len(trace_names) > 1 else 1,
                                name=trace_name,
                                showlegend=trace_name is not None)
            hist.update(**_trace_kwargs)
            fig.add_trace(hist, **add_trace_kwargs)

        TraceUpdater.__init__(self, fig, fig.data[-len(trace_names):])
        self.horizontal = horizontal
        self.remove_nan = remove_nan
        self.from_quantile = from_quantile
        self.to_quantile = to_quantile

        if data is not None:
            self.update(data)
Beispiel #21
0
    def __init__(self,
                 data=None,
                 trace_names=None,
                 x_labels=None,
                 trace_kwargs=None,
                 add_trace_kwargs=None,
                 fig=None,
                 **layout_kwargs):
        """Create a scatter plot.

        Args:
            data (array_like): Data in any format that can be converted to NumPy.

                Must be of shape (`x_labels`, `trace_names`).
            trace_names (str or list of str): Trace names, corresponding to columns in pandas.
            x_labels (array_like): X-axis labels, corresponding to index in pandas.
            trace_kwargs (dict): Keyword arguments passed to `plotly.graph_objects.Scatter`.
            add_trace_kwargs (dict): Keyword arguments passed to `add_trace`.
            fig (plotly.graph_objects.Figure): Figure to add traces to.
            **layout_kwargs: Keyword arguments for layout.

        ## Example

        ```python-repl
        >>> import vectorbt as vbt

        >>> scatter = vbt.plotting.Scatter(
        ...     data=[[1, 2], [3, 4]],
        ...     trace_names=['a', 'b'],
        ...     x_labels=['x', 'y']
        ... )
        >>> scatter.fig
        ```
        ![](/vectorbt/docs/img/Scatter.png)
        """
        Configured.__init__(self,
                            data=data,
                            trace_names=trace_names,
                            x_labels=x_labels,
                            trace_kwargs=trace_kwargs,
                            add_trace_kwargs=add_trace_kwargs,
                            fig=fig,
                            **layout_kwargs)

        if trace_kwargs is None:
            trace_kwargs = {}
        if add_trace_kwargs is None:
            add_trace_kwargs = {}
        if data is None:
            if trace_names is None:
                raise ValueError("At least trace_names must be passed")
        if trace_names is None:
            data = reshape_fns.to_2d(data)
            trace_names = [None] * data.shape[1]
        if isinstance(trace_names, str):
            trace_names = [trace_names]
        if x_labels is not None:
            x_labels = clean_labels(x_labels)

        if fig is None:
            fig = FigureWidget()
        fig.update_layout(**layout_kwargs)

        for i, trace_name in enumerate(trace_names):
            _trace_kwargs = trace_kwargs[i] if isinstance(
                trace_kwargs, (list, tuple)) else trace_kwargs
            trace_name = _trace_kwargs.pop('name', trace_name)
            if trace_name is not None:
                trace_name = str(trace_name)
            scatter = go.Scatter(x=x_labels,
                                 name=trace_name,
                                 showlegend=trace_name is not None)
            scatter.update(**_trace_kwargs)
            fig.add_trace(scatter, **add_trace_kwargs)

        TraceUpdater.__init__(self, fig, fig.data[-len(trace_names):])

        if data is not None:
            self.update(data)
Beispiel #22
0
    def __init__(self, wrapper, **kwargs):
        checks.assert_type(wrapper, ArrayWrapper)
        self._wrapper = wrapper

        Configured.__init__(self, wrapper=wrapper, **kwargs)
        PandasIndexer.__init__(self)
Beispiel #23
0
    def __init__(self,
                 data: tp.Optional[tp.ArrayLike] = None,
                 trace_names: tp.TraceNames = None,
                 horizontal: bool = False,
                 remove_nan: bool = True,
                 from_quantile: tp.Optional[float] = None,
                 to_quantile: tp.Optional[float] = None,
                 trace_kwargs: tp.KwargsLikeSequence = None,
                 add_trace_kwargs: tp.KwargsLike = None,
                 fig: tp.Optional[tp.BaseFigure] = None,
                 **layout_kwargs) -> None:
        """Create a histogram plot.

        Args:
            data (array_like): Data in any format that can be converted to NumPy.

                Must be of shape (any, `trace_names`).
            trace_names (str or list of str): Trace names, corresponding to columns in pandas.
            horizontal (bool): Whether to plot horizontally.
            remove_nan (bool): Whether to remove NaN values.
            from_quantile (float): Filter out data points before this quantile.

                Should be in range `[0, 1]`.
            to_quantile (float): Filter out data points after this quantile.

                Should be in range `[0, 1]`.
            trace_kwargs (dict or list of dict): Keyword arguments passed to `plotly.graph_objects.Histogram`.

                Can be specified per trace as a sequence of dicts.
            add_trace_kwargs (dict): Keyword arguments passed to `add_trace`.
            fig (Figure or FigureWidget): Figure to add traces to.
            **layout_kwargs: Keyword arguments for layout.

        Usage:
            ```pycon
            >>> import vectorbt as vbt

            >>> hist = vbt.plotting.Histogram(
            ...     data=[[1, 2], [3, 4], [2, 1]],
            ...     trace_names=['a', 'b']
            ... )
            >>> hist.fig
            ```

            ![](/assets/images/Histogram.svg)
        """
        Configured.__init__(self,
                            data=data,
                            trace_names=trace_names,
                            horizontal=horizontal,
                            remove_nan=remove_nan,
                            from_quantile=from_quantile,
                            to_quantile=to_quantile,
                            trace_kwargs=trace_kwargs,
                            add_trace_kwargs=add_trace_kwargs,
                            fig=fig,
                            **layout_kwargs)

        if trace_kwargs is None:
            trace_kwargs = {}
        if add_trace_kwargs is None:
            add_trace_kwargs = {}
        if data is not None:
            data = reshape_fns.to_2d_array(data)
            if trace_names is not None:
                checks.assert_shape_equal(data, trace_names, (1, 0))
        else:
            if trace_names is None:
                raise ValueError("At least data or trace_names must be passed")
        if trace_names is None:
            trace_names = [None] * data.shape[1]
        if isinstance(trace_names, str):
            trace_names = [trace_names]

        if fig is None:
            fig = make_figure()
            fig.update_layout(barmode='overlay')
        fig.update_layout(**layout_kwargs)

        for i, trace_name in enumerate(trace_names):
            _trace_kwargs = resolve_dict(trace_kwargs, i=i)
            trace_name = _trace_kwargs.pop('name', trace_name)
            if trace_name is not None:
                trace_name = str(trace_name)
            hist = go.Histogram(opacity=0.75 if len(trace_names) > 1 else 1,
                                name=trace_name,
                                showlegend=trace_name is not None)
            hist.update(**_trace_kwargs)
            fig.add_trace(hist, **add_trace_kwargs)

        TraceUpdater.__init__(self, fig, fig.data[-len(trace_names):])
        self._horizontal = horizontal
        self._remove_nan = remove_nan
        self._from_quantile = from_quantile
        self._to_quantile = to_quantile

        if data is not None:
            self.update(data)
Beispiel #24
0
    def __init__(self,
                 value: tp.Optional[float] = None,
                 label: tp.Optional[str] = None,
                 value_range: tp.Optional[tp.Tuple[float, float]] = None,
                 cmap_name: str = 'Spectral',
                 trace_kwargs: tp.KwargsLike = None,
                 add_trace_kwargs: tp.KwargsLike = None,
                 fig: tp.Optional[tp.BaseFigure] = None,
                 **layout_kwargs) -> None:
        """Create a gauge plot.

        Args:
            value (float): The value to be displayed.
            label (str): The label to be displayed.
            value_range (tuple of float): The value range of the gauge.
            cmap_name (str): A matplotlib-compatible colormap name.

                See the [list of available colormaps](https://matplotlib.org/tutorials/colors/colormaps.html).
            trace_kwargs (dict): Keyword arguments passed to the `plotly.graph_objects.Indicator`.
            add_trace_kwargs (dict): Keyword arguments passed to `add_trace`.
            fig (Figure or FigureWidget): Figure to add traces to.
            **layout_kwargs: Keyword arguments for layout.

        ## Example

        ```python-repl
        >>> import vectorbt as vbt

        >>> gauge = vbt.plotting.Gauge(
        ...     value=2,
        ...     value_range=(1, 3),
        ...     label='My Gauge'
        ... )
        >>> gauge.fig
        ```
        ![](/vectorbt/docs/img/Gauge.svg)
        """
        Configured.__init__(self,
                            value=value,
                            label=label,
                            value_range=value_range,
                            cmap_name=cmap_name,
                            trace_kwargs=trace_kwargs,
                            add_trace_kwargs=add_trace_kwargs,
                            fig=fig,
                            **layout_kwargs)

        from vectorbt._settings import settings
        layout_cfg = settings['plotting']['layout']

        if trace_kwargs is None:
            trace_kwargs = {}
        if add_trace_kwargs is None:
            add_trace_kwargs = {}

        if fig is None:
            fig = make_figure()
            if 'width' in layout_cfg:
                # Calculate nice width and height
                fig.update_layout(width=layout_cfg['width'] * 0.7,
                                  height=layout_cfg['width'] * 0.5,
                                  margin=dict(t=80))
        fig.update_layout(**layout_kwargs)

        indicator = go.Indicator(domain=dict(x=[0, 1], y=[0, 1]),
                                 mode="gauge+number+delta",
                                 title=dict(text=label))
        indicator.update(**trace_kwargs)
        fig.add_trace(indicator, **add_trace_kwargs)

        TraceUpdater.__init__(self, fig, (fig.data[-1], ))
        self.value_range = value_range
        self.cmap_name = cmap_name

        if value is not None:
            self.update(value)
Beispiel #25
0
    def __init__(self,
                 data: tp.Optional[tp.ArrayLike] = None,
                 x_labels: tp.Optional[tp.Labels] = None,
                 y_labels: tp.Optional[tp.Labels] = None,
                 is_x_category: bool = False,
                 is_y_category: bool = False,
                 trace_kwargs: tp.KwargsLike = None,
                 add_trace_kwargs: tp.KwargsLike = None,
                 fig: tp.Optional[tp.BaseFigure] = None,
                 **layout_kwargs) -> None:
        """Create a heatmap plot.

        Args:
            data (array_like): Data in any format that can be converted to NumPy.

                Must be of shape (`y_labels`, `x_labels`).
            x_labels (array_like): X-axis labels, corresponding to columns in pandas.
            y_labels (array_like): Y-axis labels, corresponding to index in pandas.
            is_x_category (bool): Whether X-axis is a categorical axis.
            is_y_category (bool): Whether Y-axis is a categorical axis.
            trace_kwargs (dict): Keyword arguments passed to `plotly.graph_objects.Heatmap`.
            add_trace_kwargs (dict): Keyword arguments passed to `add_trace`.
            fig (Figure or FigureWidget): Figure to add traces to.
            **layout_kwargs: Keyword arguments for layout.

        ## Example

        ```python-repl
        >>> import vectorbt as vbt

        >>> heatmap = vbt.plotting.Heatmap(
        ...     data=[[1, 2], [3, 4]],
        ...     x_labels=['a', 'b'],
        ...     y_labels=['x', 'y']
        ... )
        >>> heatmap.fig
        ```
        ![](/vectorbt/docs/img/Heatmap.svg)
        """
        Configured.__init__(self,
                            data=data,
                            x_labels=x_labels,
                            y_labels=y_labels,
                            trace_kwargs=trace_kwargs,
                            add_trace_kwargs=add_trace_kwargs,
                            fig=fig,
                            **layout_kwargs)

        from vectorbt._settings import settings
        layout_cfg = settings['plotting']['layout']

        if trace_kwargs is None:
            trace_kwargs = {}
        if add_trace_kwargs is None:
            add_trace_kwargs = {}
        if data is None:
            if x_labels is None or y_labels is None:
                raise ValueError(
                    "At least x_labels and y_labels must be passed")
        else:
            data = reshape_fns.to_2d(np.asarray(data))
        if x_labels is not None:
            x_labels = clean_labels(x_labels)
        if y_labels is not None:
            y_labels = clean_labels(y_labels)

        if fig is None:
            fig = make_figure()
            if 'width' in layout_cfg:
                # Calculate nice width and height
                max_width = layout_cfg['width']
                if data is not None:
                    x_len = data.shape[1]
                    y_len = data.shape[0]
                else:
                    x_len = len(x_labels)
                    y_len = len(y_labels)
                width = math.ceil(
                    renormalize(x_len / (x_len + y_len), (0, 1),
                                (0.3 * max_width, max_width)))
                width = min(width + 150, max_width)  # account for colorbar
                height = math.ceil(
                    renormalize(y_len / (x_len + y_len), (0, 1),
                                (0.3 * max_width, max_width)))
                height = min(height, max_width * 0.7)  # limit height
                fig.update_layout(width=width, height=height)

        heatmap = go.Heatmap(hoverongaps=False,
                             colorscale='Plasma',
                             x=x_labels,
                             y=y_labels)
        heatmap.update(**trace_kwargs)
        fig.add_trace(heatmap, **add_trace_kwargs)

        axis_kwargs = dict()
        if is_x_category:
            if fig.data[-1]['xaxis'] is not None:
                axis_kwargs['xaxis' +
                            fig.data[-1]['xaxis'][1:]] = dict(type='category')
            else:
                axis_kwargs['xaxis'] = dict(type='category')
        if is_y_category:
            if fig.data[-1]['yaxis'] is not None:
                axis_kwargs['yaxis' +
                            fig.data[-1]['yaxis'][1:]] = dict(type='category')
            else:
                axis_kwargs['yaxis'] = dict(type='category')
        fig.update_layout(**axis_kwargs)
        fig.update_layout(**layout_kwargs)

        TraceUpdater.__init__(self, fig, (fig.data[-1], ))

        if data is not None:
            self.update(data)
Beispiel #26
0
    def __init__(self,
                 data: tp.Optional[tp.ArrayLike] = None,
                 trace_names: tp.TraceNames = None,
                 x_labels: tp.Optional[tp.Labels] = None,
                 trace_kwargs: tp.KwargsLikeSequence = None,
                 add_trace_kwargs: tp.KwargsLike = None,
                 fig: tp.Optional[tp.BaseFigure] = None,
                 **layout_kwargs) -> None:
        """Create a bar plot.

        Args:
            data (array_like): Data in any format that can be converted to NumPy.

                Must be of shape (`x_labels`, `trace_names`).
            trace_names (str or list of str): Trace names, corresponding to columns in pandas.
            x_labels (array_like): X-axis labels, corresponding to index in pandas.
            trace_kwargs (dict or list of dict): Keyword arguments passed to `plotly.graph_objects.Bar`.

                Can be specified per trace as a sequence of dicts.
            add_trace_kwargs (dict): Keyword arguments passed to `add_trace`.
            fig (Figure or FigureWidget): Figure to add traces to.
            **layout_kwargs: Keyword arguments for layout.

        ## Example

        ```python-repl
        >>> import vectorbt as vbt

        >>> bar = vbt.plotting.Bar(
        ...     data=[[1, 2], [3, 4]],
        ...     trace_names=['a', 'b'],
        ...     x_labels=['x', 'y']
        ... )
        >>> bar.fig
        ```
        ![](/vectorbt/docs/img/Bar.svg)
        """
        Configured.__init__(self,
                            data=data,
                            trace_names=trace_names,
                            x_labels=x_labels,
                            trace_kwargs=trace_kwargs,
                            add_trace_kwargs=add_trace_kwargs,
                            fig=fig,
                            **layout_kwargs)

        if trace_kwargs is None:
            trace_kwargs = {}
        if add_trace_kwargs is None:
            add_trace_kwargs = {}
        if data is None:
            if trace_names is None:
                raise ValueError("At least trace_names must be passed")
        if trace_names is None:
            data = reshape_fns.to_2d(np.asarray(data))
            trace_names = [None] * data.shape[1]
        if isinstance(trace_names, str):
            trace_names = [trace_names]
        if x_labels is not None:
            x_labels = clean_labels(x_labels)

        if fig is None:
            fig = make_figure()
        fig.update_layout(**layout_kwargs)

        for i, trace_name in enumerate(trace_names):
            _trace_kwargs = resolve_dict(trace_kwargs, i=i)
            trace_name = _trace_kwargs.pop('name', trace_name)
            if trace_name is not None:
                trace_name = str(trace_name)
            bar = go.Bar(x=x_labels,
                         name=trace_name,
                         showlegend=trace_name is not None)
            bar.update(**_trace_kwargs)
            fig.add_trace(bar, **add_trace_kwargs)

        TraceUpdater.__init__(self, fig, fig.data[-len(trace_names):])

        if data is not None:
            self.update(data)
Beispiel #27
0
    def __init__(self,
                 data: tp.Optional[tp.ArrayLike] = None,
                 trace_names: tp.TraceNames = None,
                 horizontal: bool = False,
                 remove_nan: bool = True,
                 from_quantile: tp.Optional[float] = None,
                 to_quantile: tp.Optional[float] = None,
                 trace_kwargs: tp.KwargsLikeSequence = None,
                 add_trace_kwargs: tp.KwargsLike = None,
                 fig: tp.Optional[tp.BaseFigure] = None,
                 **layout_kwargs) -> None:
        """Create a box plot.

        For keyword arguments, see `Histogram`.

        ## Example

        ```python-repl
        >>> import vectorbt as vbt

        >>> box = vbt.plotting.Box(
        ...     data=[[1, 2], [3, 4], [2, 1]],
        ...     trace_names=['a', 'b']
        ... )
        >>> box.fig
        ```
        ![](/docs/img/Box.svg)
        """
        Configured.__init__(
            self,
            data=data,
            trace_names=trace_names,
            horizontal=horizontal,
            remove_nan=remove_nan,
            from_quantile=from_quantile,
            to_quantile=to_quantile,
            trace_kwargs=trace_kwargs,
            add_trace_kwargs=add_trace_kwargs,
            fig=fig,
            **layout_kwargs
        )

        if trace_kwargs is None:
            trace_kwargs = {}
        if add_trace_kwargs is None:
            add_trace_kwargs = {}
        if data is not None:
            data = reshape_fns.to_2d_array(data)
            if trace_names is not None:
                checks.assert_shape_equal(data, trace_names, (1, 0))
        else:
            if trace_names is None:
                raise ValueError("At least data or trace_names must be passed")
        if trace_names is None:
            trace_names = [None] * data.shape[1]
        if isinstance(trace_names, str):
            trace_names = [trace_names]

        if fig is None:
            fig = make_figure()
        fig.update_layout(**layout_kwargs)

        for i, trace_name in enumerate(trace_names):
            _trace_kwargs = resolve_dict(trace_kwargs, i=i)
            trace_name = _trace_kwargs.pop('name', trace_name)
            if trace_name is not None:
                trace_name = str(trace_name)
            box = go.Box(
                name=trace_name,
                showlegend=trace_name is not None
            )
            box.update(**_trace_kwargs)
            fig.add_trace(box, **add_trace_kwargs)

        TraceUpdater.__init__(self, fig, fig.data[-len(trace_names):])
        self._horizontal = horizontal
        self._remove_nan = remove_nan
        self._from_quantile = from_quantile
        self._to_quantile = to_quantile

        if data is not None:
            self.update(data)