from vectorbt.indicators import nb from vectorbt.indicators.factory import IndicatorFactory from vectorbt.utils.colors import adjust_opacity from vectorbt.utils.config import merge_dicts from vectorbt.utils.figure import make_figure # ############# MA ############# # MA = IndicatorFactory( class_name='MA', module_name=__name__, short_name='ma', input_names=['close'], param_names=['window', 'ewm'], output_names=['ma'] ).from_apply_func( nb.ma_apply_nb, cache_func=nb.ma_cache_nb, kwargs_to_args=['adjust'], ewm=False, adjust=False ) class _MA(MA): """Moving Average (MA). A moving average is a widely used indicator in technical analysis that helps smooth out price action by filtering out the “noise” from random short-term price fluctuations. See [Moving Average (MA)](https://www.investopedia.com/terms/m/movingaverage.asp)."""
def __init__(self, *args, class_name='CustomSignals', input_names=None, attr_settings=None, exit_only=False, iteratively=False, **kwargs): if input_names is None: input_names = [] if attr_settings is None: attr_settings = {} if iteratively: exit_only = True if exit_only: if len(input_names) > 0: if input_names[0] != 'entries': input_names = ['entries'] + input_names else: input_names = ['entries'] output_names = ['exits'] if iteratively: output_names = ['new_entries'] + output_names attr_settings['new_entries'] = dict(dtype=np.bool) else: output_names = ['entries', 'exits'] attr_settings['entries'] = dict(dtype=np.bool) attr_settings['exits'] = dict(dtype=np.bool) IndicatorFactory.__init__( self, *args, class_name=class_name, input_names=input_names, output_names=output_names, attr_settings=attr_settings, **kwargs ) self.exit_only = exit_only self.iteratively = iteratively def plot(_self, entry_y=None, exit_y=None, entry_types=None, exit_types=None, entry_trace_kwargs=None, exit_trace_kwargs=None, fig=None, **kwargs): # pragma: no cover if _self.wrapper.ndim > 1: raise TypeError("Select a column first. Use indexing.") if entry_trace_kwargs is None: entry_trace_kwargs = {} if exit_trace_kwargs is None: exit_trace_kwargs = {} if entry_types is not None: entry_trace_kwargs = merge_dicts(dict( customdata=entry_types, hovertemplate="(%{x}, %{y})<br>Type: %{customdata}" ), entry_trace_kwargs) if exit_types is not None: exit_trace_kwargs = merge_dicts(dict( customdata=exit_types, hovertemplate="(%{x}, %{y})<br>Type: %{customdata}" ), exit_trace_kwargs) if exit_only and iteratively: entries = _self.new_entries else: entries = _self.entries exits = _self.exits fig = entries.vbt.signals.plot_as_entry_markers( y=entry_y, trace_kwargs=entry_trace_kwargs, fig=fig, **kwargs) fig = exits.vbt.signals.plot_as_exit_markers( y=exit_y, trace_kwargs=exit_trace_kwargs, fig=fig, **kwargs) return fig plot.__doc__ = """Plot `{0}.{1}` and `{0}.exits`. Args: entry_y (array_like): Y-axis values to plot entry markers on. exit_y (array_like): Y-axis values to plot exit markers on. entry_types (array_like): Entry types in string format. exit_types (array_like): Exit types in string format. entry_trace_kwargs (dict): Keyword arguments passed to \ `vectorbt.signals.accessors.SignalsSRAccessor.plot_as_entry_markers` for `{0}.{1}`. exit_trace_kwargs (dict): Keyword arguments passed to \ `vectorbt.signals.accessors.SignalsSRAccessor.plot_as_exit_markers` for `{0}.exits`. fig (plotly.graph_objects.Figure): Figure to add traces to. **kwargs: Keyword arguments passed to `vectorbt.signals.accessors.SignalsSRAccessor.plot_as_markers`. """.format( class_name, 'new_entries' if exit_only and iteratively else 'entries' ) setattr(self.CustomIndicator, 'plot', plot)
"""Basic look-ahead indicators and label generators. You can access all the indicators either by `vbt.*` or `vbt.labels.*`.""" from vectorbt.indicators.factory import IndicatorFactory from vectorbt.indicators.configs import flex_elem_param_config from vectorbt.labels import nb from vectorbt.labels.enums import TrendMode # ############# Look-ahead indicators ############# # FMEAN = IndicatorFactory(class_name='FMEAN', module_name=__name__, input_names=['close'], param_names=['window', 'ewm'], output_names=['fmean']).from_apply_func( nb.future_mean_apply_nb, kwargs_to_args=['wait', 'adjust'], ewm=False, wait=1, adjust=False) FMEAN.__doc__ = """Look-ahead indicator based on `vectorbt.labels.nb.future_mean_apply_nb`.""" FSTD = IndicatorFactory(class_name='FSTD', module_name=__name__, input_names=['close'], param_names=['window', 'ewm'], output_names=['fstd']).from_apply_func( nb.future_std_apply_nb, kwargs_to_args=['wait', 'adjust', 'ddof'], ewm=False,
def __init__(self, *args, mode: tp.Union[str, int] = FactoryMode.Both, input_names: tp.Optional[tp.Sequence[str]] = None, attr_settings: tp.KwargsLike = None, **kwargs) -> None: mode = map_enum_fields(mode, FactoryMode) if input_names is None: input_names = [] else: input_names = list(input_names) if attr_settings is None: attr_settings = {} if 'entries' in input_names: raise ValueError("entries cannot be used in input_names") if 'exits' in input_names: raise ValueError("exits cannot be used in input_names") if mode == FactoryMode.Entries: output_names = ['entries'] elif mode == FactoryMode.Exits: input_names = ['entries'] + input_names output_names = ['exits'] elif mode == FactoryMode.Both: output_names = ['entries', 'exits'] else: input_names = ['entries'] + input_names output_names = ['new_entries', 'exits'] if 'entries' in input_names: attr_settings['entries'] = dict(dtype=np.bool_) for output_name in output_names: attr_settings[output_name] = dict(dtype=np.bool_) IndicatorFactory.__init__(self, *args, input_names=input_names, output_names=output_names, attr_settings=attr_settings, **kwargs) self.mode = mode def plot(_self, entry_y: tp.Optional[tp.ArrayLike] = None, exit_y: tp.Optional[tp.ArrayLike] = None, entry_types: tp.Optional[tp.ArrayLikeSequence] = None, exit_types: tp.Optional[tp.ArrayLikeSequence] = None, entry_trace_kwargs: tp.KwargsLike = None, exit_trace_kwargs: tp.KwargsLike = None, fig: tp.Optional[tp.BaseFigure] = None, **kwargs) -> tp.BaseFigure: # pragma: no cover if _self.wrapper.ndim > 1: raise TypeError("Select a column first. Use indexing.") if entry_trace_kwargs is None: entry_trace_kwargs = {} if exit_trace_kwargs is None: exit_trace_kwargs = {} entry_trace_kwargs = merge_dicts( dict(name="New Entry" if mode == FactoryMode.Chain else "Entry"), entry_trace_kwargs) exit_trace_kwargs = merge_dicts(dict(name="Exit"), exit_trace_kwargs) if entry_types is not None: entry_types = np.asarray(entry_types) entry_trace_kwargs = merge_dicts( dict(customdata=entry_types, hovertemplate="(%{x}, %{y})<br>Type: %{customdata}"), entry_trace_kwargs) if exit_types is not None: exit_types = np.asarray(exit_types) exit_trace_kwargs = merge_dicts( dict(customdata=exit_types, hovertemplate="(%{x}, %{y})<br>Type: %{customdata}"), exit_trace_kwargs) if mode == FactoryMode.Entries: fig = _self.entries.vbt.signals.plot_as_entry_markers( y=entry_y, trace_kwargs=entry_trace_kwargs, fig=fig, **kwargs) elif mode == FactoryMode.Exits: fig = _self.entries.vbt.signals.plot_as_entry_markers( y=entry_y, trace_kwargs=entry_trace_kwargs, fig=fig, **kwargs) fig = _self.exits.vbt.signals.plot_as_exit_markers( y=exit_y, trace_kwargs=exit_trace_kwargs, fig=fig, **kwargs) elif mode == FactoryMode.Both: fig = _self.entries.vbt.signals.plot_as_entry_markers( y=entry_y, trace_kwargs=entry_trace_kwargs, fig=fig, **kwargs) fig = _self.exits.vbt.signals.plot_as_exit_markers( y=exit_y, trace_kwargs=exit_trace_kwargs, fig=fig, **kwargs) else: fig = _self.new_entries.vbt.signals.plot_as_entry_markers( y=entry_y, trace_kwargs=entry_trace_kwargs, fig=fig, **kwargs) fig = _self.exits.vbt.signals.plot_as_exit_markers( y=exit_y, trace_kwargs=exit_trace_kwargs, fig=fig, **kwargs) return fig plot.__doc__ = """Plot `{0}.{1}` and `{0}.exits`. Args: entry_y (array_like): Y-axis values to plot entry markers on. exit_y (array_like): Y-axis values to plot exit markers on. entry_types (array_like): Entry types in string format. exit_types (array_like): Exit types in string format. entry_trace_kwargs (dict): Keyword arguments passed to \ `vectorbt.signals.accessors.SignalsSRAccessor.plot_as_entry_markers` for `{0}.{1}`. exit_trace_kwargs (dict): Keyword arguments passed to \ `vectorbt.signals.accessors.SignalsSRAccessor.plot_as_exit_markers` for `{0}.exits`. fig (Figure or FigureWidget): Figure to add traces to. **kwargs: Keyword arguments passed to `vectorbt.signals.accessors.SignalsSRAccessor.plot_as_markers`. """.format(self.class_name, 'new_entries' if mode == FactoryMode.Chain else 'entries') setattr(self.Indicator, 'plot', plot)
def ta(*args, **kwargs) -> tp.Type[IndicatorBase]: """Shortcut for `vectorbt.indicators.factory.IndicatorFactory.from_ta`.""" return IndicatorFactory.from_ta(*args, **kwargs)
else: ma = timeseries.nb.rolling_mean_nb(ts, windows[i], minp=windows[i]) cache_dict[h] = ma return cache_dict @njit(cache=True) def ma_apply_func_nb(ts, window, ewm, cache_dict): """Numba-compiled apply function for `MA`.""" h = hash((window, ewm)) return cache_dict[h] MA = IndicatorFactory( ts_names=['ts'], param_names=['window', 'ewm'], output_names=['ma'], name='ma' ).from_apply_func(ma_apply_func_nb, caching_func=ma_caching_nb) class MA(MA): """A moving average (MA) is a widely used indicator in technical analysis that helps smooth out price action by filtering out the “noise” from random short-term price fluctuations. See [Moving Average (MA)](https://www.investopedia.com/terms/m/movingaverage.asp). Use `MA.from_params` or `MA.from_combinations` methods to run the indicator.""" @classmethod def from_params(cls, ts, window, ewm=False, **kwargs): """Calculate moving average `MA.ma` from time series `ts` and parameters `window` and `ewm`.
import plotly.graph_objects as go from vectorbt import defaults from vectorbt.utils.config import merge_kwargs from vectorbt.utils.docs import fix_class_for_docs from vectorbt.generic import nb as generic_nb from vectorbt.indicators.factory import IndicatorFactory from vectorbt.indicators import nb # ############# MA ############# # MA = IndicatorFactory(class_name='MA', module_name=__name__, short_name='ma', input_names=['close'], param_names=['window', 'ewm'], param_defaults={ 'ewm': False }, output_names=['ma']).from_apply_func( nb.ma_apply_nb, caching_func=nb.ma_caching_nb) class MA(MA): """A moving average (MA) is a widely used indicator in technical analysis that helps smooth out price action by filtering out the “noise” from random short-term price fluctuations. See [Moving Average (MA)](https://www.investopedia.com/terms/m/movingaverage.asp). Use `MA.run` or `MA.run_combs` to run the indicator.""" def plot(self, close_trace_kwargs={},
from vectorbt import defaults from vectorbt.utils.config import merge_kwargs from vectorbt.utils.docs import fix_class_for_docs from vectorbt.base import reshape_fns from vectorbt.generic import nb as generic_nb from vectorbt.indicators.factory import IndicatorFactory, create_param_product from vectorbt.indicators import nb # ############# MA ############# # MA = IndicatorFactory( class_name='MA', module_name=__name__, ts_names=['ts'], param_names=['window', 'ewm'], output_names=['ma'], name='ma' ).from_apply_func(nb.ma_apply_nb, caching_func=nb.ma_caching_nb) class MA(MA): """A moving average (MA) is a widely used indicator in technical analysis that helps smooth out price action by filtering out the “noise” from random short-term price fluctuations. See [Moving Average (MA)](https://www.investopedia.com/terms/m/movingaverage.asp). Use `MA.from_params` or `MA.from_combs` methods to run the indicator.""" @classmethod def from_params(cls, ts, window, ewm=False, **kwargs):
def ta(*args, **kwargs): """Shortcut for `vectorbt.indicators.factory.IndicatorFactory.from_ta`.""" return IndicatorFactory.from_ta(*args, **kwargs)