Beispiel #1
0
def wma(close, length=None, asc=None, offset=None, **kwargs):
    """Indicator: Weighted Moving Average (WMA)"""
    # Validate Arguments
    close = verify_series(close)
    length = int(length) if length and length > 0 else 10
    asc = asc if asc else True
    offset = get_offset(offset)

    # Calculate Result
    total_weight = 0.5 * length * (length + 1)
    weights_ = Series(npArange(1, length + 1))
    weights = weights_ if asc else weights_[::-1]

    def linear(w):
        def _compute(x):
            return npDot(x, w) / total_weight

        return _compute

    close_ = close.rolling(length, min_periods=length)
    wma = close_.apply(linear(weights), raw=True)

    # Offset
    if offset != 0:
        wma = wma.shift(offset)

    # Name & Category
    wma.name = f"WMA_{length}"
    wma.category = "overlap"

    return wma
    def _plot(self,
              df,
              mas: bool = True,
              constants: bool = False,
              **kwargs) -> None:

        if constants:
            chart_lines = npAppend(npArange(-5, 6, 1), npArange(-100, 110, 10))
            df.ta.constants(True,
                            chart_lines)  # Adding the constants for the charts
            df.ta.constants(False, npArray(
                [-60, -40, 40,
                 60]))  # Removing some constants from the DataFrame
            if self.verbose: print(f"[i] {df.ticker} constants added.")

        if ta.Imports["matplotlib"]:
            _exchange = kwargs.pop("exchange", "NYSE")
            _time = ta.get_time(_exchange, to_string=True)
            _kind = kwargs.pop("plot_kind", None)
            _figsize = kwargs.pop("figsize", (16, 10))
            _colors = kwargs.pop("figsize",
                                 ["black", "green", "orange", "red", "maroon"])
            _grid = kwargs.pop("grid", True)
            _alpha = kwargs.pop("alpha", 1)
            _last = kwargs.pop("last", 252)
            _title = kwargs.pop("title",
                                f"{df.ticker}   {_time}   [{self.ds_name}]")

            col = kwargs.pop("close", "close")
            if mas:
                # df.ta.strategy(self.strategy, append=True)
                price = df[[col, "SMA_10", "SMA_20", "SMA_50", "SMA_200"]]
            else:
                price = df[col]

            if _kind is None:
                price.tail(_last).plot(figsize=_figsize,
                                       color=_colors,
                                       linewidth=2,
                                       title=_title,
                                       grid=_grid,
                                       alpha=_alpha)
            else:
                print(f"[X] Plot kind not implemented")
                return
Beispiel #3
0
def wma(close, length=None, asc=None, talib=None, offset=None, **kwargs):
    """Indicator: Weighted Moving Average (WMA)"""
    # Validate Arguments
    length = int(length) if length and length > 0 else 10
    asc = asc if asc else True
    close = verify_series(close, length)
    offset = get_offset(offset)
    mode_tal = bool(talib) if isinstance(talib, bool) else True

    if close is None: return

    # Calculate Result
    if Imports["talib"] and mode_tal:
        from talib import WMA
        wma = WMA(close, length)
    else:
        from numpy import arange as npArange
        from numpy import dot as npDot

        total_weight = 0.5 * length * (length + 1)
        weights_ = Series(npArange(1, length + 1))
        weights = weights_ if asc else weights_[::-1]

        def linear(w):
            def _compute(x):
                return npDot(x, w) / total_weight

            return _compute

        close_ = close.rolling(length, min_periods=length)
        wma = close_.apply(linear(weights), raw=True)

    # Offset
    if offset != 0:
        wma = wma.shift(offset)

    # Handle fills
    if "fillna" in kwargs:
        wma.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        wma.fillna(method=kwargs["fill_method"], inplace=True)

    # Name & Category
    wma.name = f"WMA_{length}"
    wma.category = "overlap"

    return wma
Beispiel #4
0
def dibujarFnActivacionNumpy(self, axe=None, axis=[-10.0, 10.0],
                             axline=[0.0, 0.0], mostrar=True):
    if axe is None:
        axe = plt.gca()

    Xaxis = npArange(axis[0], axis[1], 0.01)
    Yaxis = self(Xaxis)
    axe.plot(Xaxis, Yaxis, color='red', linewidth=2.0)
    # lineas horizontales y verticales
    axe.axhline(axline[0], linestyle='-.', color='blue', linewidth=1.5)
    axe.axvline(axline[1], linestyle='-.', color='blue', linewidth=1.5)
    plt.title(self.__str__())
    plt.grid(True)

    plt.show() if mostrar else None

    return axe
Beispiel #5
0
def dibujarFnActivacionTheano(self, axe=None, axis=[-10.0, 10.0],
                              axline=[0.0, 0.0], mostrar=True):

    if axe is None:
        axe = plt.gca()

    Xaxis = npArange(axis[0], axis[1], 0.01)
    Yaxis = self(Xaxis)
    x = Tdvector('x')
    s = Tcast(self(x), dtype=theanoFloat)
    dibujador=Tfunction(inputs=[x], outputs=s)
    axe.plot(Xaxis, dibujador(Xaxis), color='red', linewidth=2.0)
    # lineas horizontales y verticales
    axe.axhline(axline[0], linestyle='-.', color='blue', linewidth=1.5)
    axe.axvline(axline[1], linestyle='-.', color='blue', linewidth=1.5)
    plt.title(self.__str__())
    plt.grid(True)

    plt.show() if mostrar else None

    return axe
Beispiel #6
0
def tos_stdevall(close,
                 length=None,
                 stds=None,
                 ddof=None,
                 offset=None,
                 **kwargs):
    """Indicator: TD Ameritrade's Think or Swim Standard Deviation All"""
    # Validate Arguments
    stds = stds if isinstance(stds, list) and len(stds) > 0 else [1, 2, 3]
    if min(stds) <= 0: return
    if not all(i < j for i, j in zip(stds, stds[1:])):
        stds = stds[::-1]
    ddof = int(ddof) if ddof and ddof >= 0 and ddof < length else 1
    offset = get_offset(offset)

    if length is None:
        length = close.size
        _props = f"STDEVALL"
    else:
        length = int(length) if length and length > 2 else 30
        close = close.iloc[-length:]
        _props = f"STDEVALL_{length}"

    close = verify_series(close, length)

    if close is None: return

    # Calculate Result
    if isinstance(close.index, DatetimeIndex):
        close_ = npArray(close)
        np_index = npArange(length)
        m, b = npPolyfit(np_index, close_, 1)
        lr_ = m * np_index + b
    else:
        m, b = npPolyfit(close.index, close, 1)
        lr_ = m * close.index + b

    lr = Series(lr_, index=close.index)
    stdevall = stdev(Series(close), length=length, ddof=ddof)
    # std = npStd(close, ddof=ddof)

    # Name and Categorize it
    df = DataFrame({f"{_props}_LR": lr}, index=close.index)
    for i in stds:
        df[f"{_props}_L_{i}"] = lr - i * stdevall.iloc[-1]
        df[f"{_props}_U_{i}"] = lr + i * stdevall.iloc[-1]
        df[f"{_props}_L_{i}"].name = df[f"{_props}_U_{i}"].name = f"{_props}"
        df[f"{_props}_L_{i}"].category = df[
            f"{_props}_U_{i}"].category = "statistics"

    # Offset
    if offset != 0:
        df = df.shift(offset)

    # Handle fills
    if "fillna" in kwargs:
        df.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        df.fillna(method=kwargs["fill_method"], inplace=True)

    # Prepare DataFrame to return
    df.name = f"{_props}"
    df.category = "statistics"

    return df