Esempio n. 1
0
def result_in_wma(data, list_of_wma):
    fast_period = list_of_wma[0]
    middle_period = list_of_wma[1]
    slow_period = list_of_wma[2]
    try:
        fast = talib.WMA(data['close'].values, timeperiod=fast_period)
        middle = talib.WMA(data['close'].values, timeperiod=middle_period)
        slow = talib.WMA(data['close'].values, timeperiod=slow_period)
    except:
        logging.info("could not get wma")
        return 'undefined'

    period = get_period(data)
    if period == "undefined":
        return 'undefined'

    # if (fast[-1] > middle[-1]) and (middle[-1] > slow[-1]) and (data.close[-1] > fast[-1]):
    if (fast[-1] > middle[-1]) and (middle[-1] > slow[-1]):
        for i in range(1, 100):
            # if not ((fast[-i] > middle[-i]) and (middle[-i] > slow[-i]) and (data.close[-1] > fast[-1])):
            if not ((fast[-i] > middle[-i]) and (middle[-i] > slow[-i])):
                    return 'buy during:{} periods of({})'.format(i, period)

    # if (fast[-1] < middle[-1]) and (middle[-1] < slow[-1]) and (data.close[-1] < fast[-1]):
    if (fast[-1] < middle[-1]) and (middle[-1] < slow[-1]):
        for i in range(1, 100):
            # if not ((fast[-i] < middle[-i]) and (middle[-i] < slow[-i]) and (data.close[-1] < fast[-1])):
            if not ((fast[-i] < middle[-i]) and (middle[-i] < slow[-i])):
                return 'sell during:{} periods of({})'.format(i, period)

    return 'undefined'
Esempio n. 2
0
    def get_hma(self, pair, dataframe, index=None, localconfig=None):
        """
        Calculate Hull Moving Average using Weighted Moving Average
        """
        klines = self.make_data_tupple(dataframe.iloc[:index])
        func, timeperiod = localconfig
        close = klines[-1]
        first = talib.WMA(close, int(timeperiod)/2)
        second = talib.WMA(close, int(timeperiod))

        result = talib.WMA((2 * first) - second, round(math.sqrt(int(timeperiod))))[-1]
        trigger = "BUY"
        if result > close[-1]:
            trigger = "SELL"
        else:
            trigger = "BUY"
        scheme = {}

        try:
            scheme["data"] = result
            scheme["symbol"] = pair
            scheme["event"] = func+"_"+str(timeperiod)

            if not index and self.test:
                index = -1
            elif not index and not self.test:
                index = -2
            scheme["close_time"] = str(self.dataframes[pair].iloc[index]["closeTime"])

            self.schemes.append(scheme)

        except KeyError as exc:
            LOGGER.warning("KEY FAILURE in moving averages: %s ", str(exc))

        LOGGER.debug("done getting moving averages")
Esempio n. 3
0
    def process_raw(self, csv_file):
        df = self._file
        df['dt'] = df['Date'].astype(str) + " " + df['Time'].astype(str)
        df['DateTime'] = pd.to_datetime(df['dt'],
                                        format=' % Y % m % d % H: % M: % S',
                                        errors='ignore')
        df = df.set_index(['DateTime'])
        df = df.drop(['General', 'Date', 'Time', 'dt'], axis=1)

        df['EMA10'] = ta.EMA(df['Close'], timeperiod=10)
        df['EMA30'] = ta.EMA(df['Close'], timeperiod=30)
        df['EMA60'] = ta.EMA(df['Close'], timeperiod=60)

        df['SMA10'] = ta.SMA(df['Close'], timeperiod=10)
        df['SMA30'] = ta.SMA(df['Close'], timeperiod=30)
        df['SMA60'] = ta.SMA(df['Close'], timeperiod=60)

        df['WMA10'] = ta.WMA(df['Close'], timeperiod=10)
        df['WMA30'] = ta.WMA(df['Close'], timeperiod=30)
        df['WMA60'] = ta.WMA(df['Close'], timeperiod=60)

        df['RSI10'] = ta.RSI(df['Close'], timeperiod=10)
        df['RSI30'] = ta.RSI(df['Close'], timeperiod=30)
        df['RSI60'] = ta.RSI(df['Close'], timeperiod=60)

        df['MOM10'] = ta.MOM(df['Close'], timeperiod=10)
        df['MOM30'] = ta.MOM(df['Close'], timeperiod=30)
        df['MOM60'] = ta.MOM(df['Close'], timeperiod=60)

        df['ROC10'] = ta.ROC(df['Close'], timeperiod=10)
        df['ROC50'] = ta.ROC(df['Close'], timeperiod=30)
        df['ROC60'] = ta.ROC(df['Close'], timeperiod=60)

        df.to_csv(csv_file)
        return df
Esempio n. 4
0
def create_features(df):
    period = 14
    bid_df = df[['bid']]
    ask_df = df[['ask']]

    bid_df['dema_bid'] = talib.DEMA(df.bid.values, timeperiod=period)
    ask_df['dema_ask'] = talib.DEMA(df.ask.values, timeperiod=period)

    bid_df['ema_bid'] = talib.EMA(df.bid.values, timeperiod=period)
    ask_df['ema_ask'] = talib.EMA(df.ask.values, timeperiod=period)

    bid_df['ht_trendline_bid'] = talib.HT_TRENDLINE(df.bid.values)
    ask_df['ht_trendline_ask'] = talib.HT_TRENDLINE(df.ask.values)

    bid_df['ma_bid'] = talib.MA(df.bid.values, timeperiod=period, matype=0)
    ask_df['ma_ask'] = talib.MA(df.ask.values, timeperiod=period, matype=0)

    bid_df['sma_bid'] = talib.SMA(df.bid.values, timeperiod=period)
    ask_df['sma_ask'] = talib.SMA(df.ask.values, timeperiod=period)

    bid_df['tema_bid'] = talib.TEMA(df.bid.values, timeperiod=period)
    ask_df['tema_ask'] = talib.TEMA(df.ask.values, timeperiod=period)

    bid_df['wma_bid'] = talib.WMA(df.bid.values, timeperiod=period)
    ask_df['wma_ask'] = talib.WMA(df.ask.values, timeperiod=period)

    bid_df['kama_bid'] = talib.KAMA(df.bid.values, timeperiod=period)
    ask_df['kama_ask'] = talib.KAMA(df.ask.values, timeperiod=period)

    bid_df = bid_df.fillna(method='bfill')
    ask_df = ask_df.fillna(method='bfill')

    return bid_df, ask_df
Esempio n. 5
0
def cal_signal(df,strat_time,end_time,cs0,ix_zong=100):
    a = time.process_time()
     # ===指标数据
    # da, zhong, xiao, stop_n, max_stop_win = cs0
    df['ma_da'] = talib.MA(df['close'],cs0[0])
    df['ma_z'] = talib.MA(df['close'],cs0[1])
    df['ma_xiao'] = talib.MA(df['close'],cs0[2])
    N = int(cs0[0])
    X = 2 * talib.WMA(df['close'], int(N / 2)) - talib.WMA(df['close'], N)
    df['hma'] = talib.WMA(X, int(N ** 0.5))
    df['止损价'] = np.nan
    df['止盈价'] = np.nan
    df['日内最低价'] = 100000
    df['日内最高价'] = 0
    pass
    # ===转化成np.array
    df0cols = ['candle_begin_time', 'open', 'high', 'low', 'close', 'volume','days', 'huors', 'minutes']
    df0 = df[df0cols].values
    df1cols = ['candle_begin_time', 'signal', 'pos', 'opne_price', 'per_lr', 'sl']
    df1 = df[df1cols].values
    df2cols = ['candle_begin_time', 'ma_da', 'ma_z', 'ma_xiao', '止损价', '止盈价', '日内最低价', '日内最高价','hma']
    df2 = df[df2cols].values
    df0, df1, df2, res = cal_signal_(df0, df1, df2, strat_time, end_time, cs0)
    print('runingtime:', time.process_time() - a, f's ,已经完成 ==:{round(ix_zong,2)}%')
    # print(df0.shape, df1.shape, df2.shape,[df0cols,df1cols,df2cols], res)

    # res=[0]
    return df0, df1, df2,[df0cols,df1cols,df2cols], res
Esempio n. 6
0
 def extreme(self):
     WMA_PERIOD = 5
     prices = self.prices["close"]
     prev_close = prices[-2]
     date = prices[4]
     bbup, bbmid, bblow = talib.BBANDS(prices, 20)
     lma5 = talib.WMA(prices_arr[2], timeperiod=WMA_PERIOD)
     hma5 = talib.WMA(prices_arr[1], timeperiod=WMA_PERIOD)
     # check prev candle is EXTREME
     if self.ext is None:
         if hma5[-2] > bbup[-2]:
             self.ext = {
                 "action": "sell",
                 "ep": "{}-{}".format(prices_arr[1][-2]),
                 "ma_ep": True
             }
         elif lma5[-2] > bblow[-2]:
             self.ext = {
                 "action": "buy",
                 "ep": "{}-{}".format(),
                 "ma_ep": True,
                 "date": date[-2]
             }
     else:
         #check out previous extreme is invalid.New candle close out of bb(faild)
         if (prev_close > self.ext
                 and prev_close > bbup[-2]) or (prev_close < self.ext
                                                and prev_close < bblow[-2]):
             self.ext = None
             #self.ext_dt =
     return
Esempio n. 7
0
    def on_bar(self, bars):
        close = self.source_preference + '_close'

        wma_1 = talib.WMA(bars[close].values, self.period / 2)
        wma_2 = talib.WMA(bars[close].values, self.period)

        bars['value'] = talib.WMA((2 * wma_1) - wma_2, math.sqrt(self.period))
        return bars
Esempio n. 8
0
def wma(df, time_id, slk = 3, llk = 24):
    Log(LOG_INFO) << "Computing wma with %d, %d" % (slk, llk)
    prices = df[OPEN_KEY].values
    kma_s = talib.WMA(prices, slk)
    kma_l = talib.WMA(prices, llk)
    dif_s = prices[time_id] - kma_s[time_id]
    dif_l = prices[time_id] - kma_l[time_id]
    dwma = kma_s[time_id] - kma_l[time_id]
    return np.hstack((dif_s.reshape(-1, 1), dif_l.reshape(-1,1),dwma.reshape(-1, 1)))
Esempio n. 9
0
def TA_HMA(close, period):
    """
    赫尔移动平均线(HMA) 
    Hull Moving Average.
    Formula:
    HMA = WMA(2*WMA(n/2) - WMA(n)), sqrt(n)
    """
    hma = talib.WMA(2 * talib.WMA(close, int(period / 2)) - talib.WMA(close, period), int(np.sqrt(period)))
    return hma
def wma(df, target_list):

    for target in target_list:

        df['WMA_SHORT_' + target] = talib.WMA(df[target], 20)
        df['WMA_LONG_' + target] = talib.WMA(df[target], 50)
        df['CROSS_WMA_' + target] = np.where(
            df['WMA_LONG_' + target] >= df['WMA_LONG_' + target], 1, 0)

    return df
Esempio n. 11
0
def _hma(close, timeperiod):
    """Hull Moving Average (HMA)

    Fidelity:   https://bit.ly/2Jhuvge
    InstaForex: https://bit.ly/2Hi4Su0
    """
    n = timeperiod
    n1 = np.ceil(timeperiod / 2)
    n2 = np.ceil(np.sqrt(timeperiod))
    hma = ta.WMA(2 * ta.WMA(close, n1) - ta.WMA(close, n), n2)
    return pd.Series(hma, name=f'HMA({timeperiod})')
Esempio n. 12
0
def my_hma(ohlc, period, mode='close'):
    if mode == 'close':
        price = ohlc.loc[:, 'close']
    else:
        pass
    fast_wma = talib.WMA(price, int(period / 2))
    slow_wma = talib.WMA(price, period)
    diff = 2 * fast_wma - slow_wma
    hma = talib.WMA(diff, int(math.sqrt(period)))
    # print(hma)
    return hma
Esempio n. 13
0
def preprocess_and_Separation_data_for_model(series, test_date):
    data = series.copy()
    # Add feature to data for supervised model
    data = data.drop([
        '<TICKER>', '<VOL>', '<OPENINT>', '<PER>', '<FIRST>', '<LAST>',
        '<VALUE>'
    ],
                     axis=1)
    data = data.iloc[::-1].reset_index(drop=True)
    data['<RSI>'] = talib.RSI(data['<CLOSE>'], timeperiod=14)
    data['SMA_5'] = talib.SMA(data['<CLOSE>'], timeperiod=5)
    data['WMA_5'] = talib.WMA(data['<CLOSE>'], timeperiod=5)
    data['WMA_10'] = talib.WMA(data['<CLOSE>'], timeperiod=10)
    data['MOM_10'] = talib.MOM(data['<CLOSE>'], timeperiod=10)
    data.drop(data.head(15).index, inplace=True)
    #   end
    # Add Next Day label
    next_day_label = np.sign(data['<CLOSE>'].diff(1).shift(-1).values)
    next_day_label[np.where(next_day_label == 0)] = 1
    data['next_day_label'] = next_day_label
    #   end
    # Build a complete array of all dates
    data['<DTYYYYMMDD>'] = pd.to_datetime(data['<DTYYYYMMDD>'],
                                          format='%Y%m%d')
    data = data.sort_values(by=['<DTYYYYMMDD>'], ascending=True)
    data = data.set_index('<DTYYYYMMDD>', drop=True)
    #   end
    # Separation of train, validation and test data for the supervised model
    end_train_date = '2019-09-22'
    start_test_date = '2020-02-22'
    train_data_for_supervised_model = data[data.index <= end_train_date]
    train_data_for_supervised_model = train_data_for_supervised_model.dropna(
        axis=0)
    # -----------------------------------------------------------------
    validation_data_for_supervised_model = data[data.index > end_train_date]
    validation_data_for_supervised_model = validation_data_for_supervised_model[
        validation_data_for_supervised_model.index < test_date]
    validation_data_for_supervised_model = validation_data_for_supervised_model.dropna(
        axis=0)
    # -----------------------------------------------------------------
    test_data_for_supervised_model = data[data.index > start_test_date]
    test_data_for_supervised_model = test_data_for_supervised_model.dropna(
        axis=0)
    # -----------------------------------------------------------------
    if test_date in test_data_for_supervised_model.index:
        return train_data_for_supervised_model, validation_data_for_supervised_model, \
               test_data_for_supervised_model.loc[test_date], 1
    else:
        return train_data_for_supervised_model, -1, -1, -1
Esempio n. 14
0
def wma(prices, signal):
    """
    Weighted Moving Average
    """

    window = signal['params']['window']
    signal['data'] = talib.WMA(prices['close'], window).to_numpy()[:, None]
Esempio n. 15
0
 def calculations(self):
     '''calculations'''
     self.df['rsi'] = ta.RSI(self.df['close'], timeperiod=5)
     self.df['apo'] = ta.APO(self.df['close'],
                             fastperiod=10,
                             slowperiod=5,
                             matype=0)
     self.df['upperband'], self.df['middleband'], self.df[
         'lowerband'] = ta.BBANDS(self.df['close'],
                                  timeperiod=5,
                                  nbdevup=2,
                                  nbdevdn=2,
                                  matype=0)
     self.df['ema'] = ta.EMA(self.df['close'], timeperiod=5)
     self.df['ma'] = ta.MA(self.df['close'], timeperiod=5, matype=0)
     self.df['sma'] = ta.MA(self.df['close'], timeperiod=5)
     self.df['t3'] = ta.T3(self.df['close'], timeperiod=5, vfactor=0)
     self.df['wma'] = ta.WMA(self.df['close'], timeperiod=5)
     self.df['aroonosc'] = ta.AROONOSC(self.df['high'],
                                       self.df['low'],
                                       timeperiod=5)
     self.df['cci'] = ta.CCI(self.df['high'],
                             self.df['low'],
                             self.df['close'],
                             timeperiod=5)
     self.df['cmo'] = ta.CMO(self.df['close'], timeperiod=14)
     self.df['macd'], self.df['macdsignal'], self.df[
         'macdhist'] = ta.MACDEXT(self.df['close'],
                                  fastperiod=12,
                                  fastmatype=0,
                                  slowperiod=26,
                                  slowmatype=0,
                                  signalperiod=9,
                                  signalmatype=0)
     self.df['slowk'], self.df['slowd'] = ta.STOCH(self.df['high'],
                                                   self.df['low'],
                                                   self.df['close'],
                                                   fastk_period=5,
                                                   slowk_period=3,
                                                   slowk_matype=0,
                                                   slowd_period=3,
                                                   slowd_matype=0)
     self.df['fastk'], self.df['fastd'] = ta.STOCHRSI(self.df['close'],
                                                      timeperiod=5,
                                                      fastk_period=5,
                                                      fastd_period=3,
                                                      fastd_matype=0)
     self.df['ultosc'] = ta.ULTOSC(self.df['high'],
                                   self.df['low'],
                                   self.df['close'],
                                   timeperiod1=7,
                                   timeperiod2=14,
                                   timeperiod3=28)
     self.df['adosc'] = ta.ADOSC(self.df['high'],
                                 self.df['low'],
                                 self.df['close'],
                                 self.df['volume'],
                                 fastperiod=3,
                                 slowperiod=10)
     return self.df
def rebalance(context, data):
    history = data.history(context.asset, ['close'], 40, '1d')
    close = history['close'].values
    date = history.index.values[-1]
    current_position = context.portfolio.positions[context.asset].amount
    print("当前持仓==>%d" % current_position)
    price = data[context.asset].price
    record(price=price)

    # 计算指标
    sma_data = talib.SMA(close)[-1]
    wma_data = talib.WMA(close)[-1]
    mom_data = talib.MOM(close)[-1]

    # 添加今日的特征
    features = []
    x = []
    features.append(sma_data)
    features.append(wma_data)
    features.append(mom_data)
    x.append(features)
    flag = context.svm_module.predict(x)  # 预测的涨跌结果

    if bool(flag) and current_position == 0:
        order_target_percent(context.asset, 0.5)
        print(str(date) + "==>买入信号")
    elif bool(flag) is False and current_position > 0:
        order_target_percent(context.asset, 0.0)
        print(str(date) + "==>卖出信号")
    else:
        print(str(date) + "==>无交易信号")
Esempio n. 17
0
def get_tis(df, dropnan=True, drop_vol=True):
    """ calculate technical indicators with ta-lib
    requires a df with a column named "Close" """
    # to delete rows which have 0 volume / delete weekends
    print("dropping rows with zero volume from dataFrame {}".format(df.shape))
    if drop_vol:
        df = df[(df[['Volume']] != 0).all(axis=1)]

    print("creating technical indicators")
    df['RSI'] = ta.RSI(df.Close.values, timeperiod=14)
    df['ROC'] = ta.ROC(df.Close.values, timeperiod=10)
    df['SMA'] = ta.SMA(df.Close.values, timeperiod=30)
    df['EMA'] = ta.EMA(df.Close.values, timeperiod=30)
    df['WMA'] = ta.WMA(df.Close.values, timeperiod=30)
    df['MACD'], df['macdSignal'], df['macdHist'] = ta.MACD(df.Close.values,
                                                           fastperiod=12,
                                                           slowperiod=26,
                                                           signalperiod=9)
    print("done {}".format(df.shape))

    print("dropping NaN values")
    if dropnan:
        df.dropna(inplace=True)
    print("returning dataFrame: {}  from get_tis func".format(df.shape))

    return df
Esempio n. 18
0
 def compWMA(self):
     wma = talib.WMA(self.close,timeperiod=self.lookback)
     self.removeNullID(wma)
     self.rawFeatures['WMA'] = wma 
     
     FEATURE_SIZE_DICT['WMA'] = 1
     return
Esempio n. 19
0
def getData(code,start,end):
    data = pandasData.DataReader(code,'yahoo',start,end)
    # print len(data)
    f_ema = ta.EMA(data['Close'].values, timeperiod=30).tolist()
    # print f_ema
    f_ma = ta.MA(data['Close'].values, timeperiod=30, matype=0).tolist()
    f_wma = ta.WMA(data['Close'].values, timeperiod=30).tolist()
    f_momentum = ta.MOM(data['Close'].values, timeperiod=10).tolist()
    f_roc = ta.ROC(data['Close'].values, timeperiod=10).tolist()
    # f_cycle = ta.HT_DCPERIOD(data['Close'].values).tolist()
    f_price = ta.WCLPRICE(data['High'].values, data['Low'].values, data['Close'].values).tolist()
    f_natr = ta.NATR(data['High'].values, data['Low'].values, data['Close'].values, timeperiod=14).tolist()
    f_stddev = ta.STDDEV(data['Close'].values, timeperiod=5, nbdev=1).tolist()
    X = pd.DataFrame(
        pd.np.array([f_ema, f_ma, f_wma, f_momentum, f_roc, f_price, f_natr, f_stddev]).T[32:]
        ,columns=['f_ema','f_ma','f_wma','f_momentum','f_roc','f_price','f_natr','f_stddev'])
    # print X['f_ema'].size
    # print X
    data = data['Close'].tolist()
    finaldata = [[] for i in range(2)]
    for i in range(0, len(data) - 1):
        temp = (data[i + 1] - data[i]) / data[i]
        finaldata[0].append(temp)
        if (temp > 0):
            finaldata[1].append(1)
        else:
            finaldata[1].append(0)
    # print len(data)
    data = data[31:len(data) - 1]
    # print data
    Y = pd.DataFrame(pd.np.array(finaldata).T, columns=['change', 'label'])
    X = X.join(Y)
    return X
Esempio n. 20
0
 def idx_signal(self):
     l_wma13 = talib.WMA(self.l_close, 21)
     l_sma89 = talib.SMA(self.l_close, 89)
     l_k, l_d = talib.STOCH(self.df['high'], self.df['low'],
                            self.df['close'])
     self.l_signal = (l_k < l_d)
     return self
def SVM_train(context):
    print("开始训练")
    first_day = pd.Timestamp(train_start_day, tz='utc')
    last_day = pd.Timestamp(train_end_day, tz='utc')
    cal = get_calendar(calendar_name)
    days = cal.sessions_in_range(first_day, last_day)

    x_train = []  # 特征
    y_train = []  # 标记

    for day in days:
        close = get_window_price(day)
        # 计算指标
        sma_data = talib.SMA(close)[-1]
        wma_data = talib.WMA(close)[-1]
        mom_data = talib.MOM(close)[-1]

        features = []
        features.append(sma_data)
        features.append(wma_data)
        features.append(mom_data)

        label = False  # 标记为跌(False)
        if close[-1] > close[-2]:  # 如果今天的收盘价超过了昨天,那么标记为涨(True)
            label = True
        x_train.append(features)
        y_train.append(label)

    context.svm_module = svm.SVC()
    context.svm_module.fit(x_train, y_train)  # 训练分类器
    print("训练结束")
Esempio n. 22
0
File: cc.py Progetto: t3ch9/jesse
def cc(candles: np.ndarray,
       wma_period: int = 10,
       roc_short_period: int = 11,
       roc_long_period: int = 14,
       source_type: str = "close",
       sequential: bool = False) -> Union[float, np.ndarray]:
    """
    CC - Coppock Curve

    :param candles: np.ndarray
    :param wma_period: int - default: 10
    :param roc_short_period: int - default: 11
    :param roc_long_period: int - default: 14
    :param source_type: str - default: "close"
    :param sequential: bool - default=False

    :return: float | np.ndarray
    """
    if not sequential and len(candles) > 240:
        candles = candles[-240:]

    source = get_candle_source(candles, source_type=source_type)
    res = talib.WMA(talib.ROC(source, timeperiod=roc_long_period) +
                    talib.ROC(source, timeperiod=roc_short_period),
                    timeperiod=wma_period)

    return res if sequential else res[-1]
Esempio n. 23
0
def wma(close_ts, timeperiod=30):
    import talib
    close_np = close_ts.cpu().detach().numpy()
    close_df = pd.DataFrame(close_np)
    wma = close_df.apply(lambda x: talib.WMA(x, timeperiod=30))
    wma_ts = torch.tensor(wma.values, dtype=close_ts.dtype, device=close_ts.device)
    return wma_ts
Esempio n. 24
0
    def preprocessIndicators(self, forecastLen):
        close_columns = [
            col for col in list(self.data.columns.values) if 'Close' in col
        ]
        open_columns = [
            col for col in list(self.data.columns.values) if 'Open' in col
        ]
        high_columns = [
            col for col in list(self.data.columns.values) if 'High' in col
        ]
        low_columns = [
            col for col in list(self.data.columns.values) if 'Low' in col
        ]

        #features dependent only on the closing price
        sma_lengths = [16, 64, 256]
        for currency in close_columns:
            #no length dependence #add HT_TRENDLINE - Hilbert transform whatever the f**k that is
            self.data[currency + '_HT_TRENDLINE_'] = talib.HT_TRENDLINE(
                self.data[currency])

            for length in sma_lengths:
                #add SMA column
                self.data[currency + '_SMA_' + str(length)] = talib.SMA(
                    self.data[currency], timeperiod=length)
                #add WMA - weighted moving average
                self.data[currency + '_WMA_' + str(length)] = talib.WMA(
                    self.data[currency], timeperiod=length)
                #add TRIMA - triangilar moving average
                self.data[currency + '_TRIMA_' + str(length)] = talib.TRIMA(
                    self.data[currency], timeperiod=length)
                #add TEMA -  triple exponential moving average
                self.data[currency + '_TEMA_' + str(length)] = talib.TEMA(
                    self.data[currency], timeperiod=length)
                #add DEMA - double exp ma
                self.data[currency + '_DEMA_' + str(length)] = talib.DEMA(
                    self.data[currency], timeperiod=length)
                #add bollinger bands
                upperband, middleband, lowerband = talib.BBANDS(
                    self.data[currency],
                    timeperiod=length,
                    nbdevup=2,
                    nbdevdn=2,
                    matype=0)
                self.data[currency + '_BOLLINGER_UPPER_' +
                          str(length)] = upperband
                self.data[currency + '_BOLLINGER_MIDDLE_' +
                          str(length)] = middleband
                self.data[currency + '_BOLLINGER_LOWER_' +
                          str(length)] = lowerband

            #we also want to add a 'forecast column', which has the column value for a specific row 'forecastLen' units in the future.
            self.data[currency + '_FORECAST_' +
                      str(forecastLen)] = self.data[currency].shift(
                          -forecastLen)
            self.data[currency + '_pipDiff_' + str(forecastLen)] = list(
                map(self.classify, self.data[currency],
                    self.data[currency + '_FORECAST_' + str(forecastLen)]))

        return self.data
Esempio n. 25
0
def ift_rsi(candles: np.ndarray,
            rsi_period: int = 5,
            wma_period: int = 9,
            source_type: str = "close",
            sequential: bool = False) -> Union[float, np.ndarray]:
    """
    Modified Inverse Fisher Transform applied on RSI

    :param candles: np.ndarray
    :param rsi_period: int - default: 5
    :param wma_period: int - default: 9
    :param source_type: str - default: "close"
    :param sequential: bool - default: False

    :return: float | np.ndarray
    """

    candles = slice_candles(candles, sequential)
    source = get_candle_source(candles, source_type=source_type)

    v1 = 0.1 * (talib.RSI(source, rsi_period) - 50)

    v2 = talib.WMA(v1, wma_period)

    res = (((2 * v2)**2 - 1) / ((2 * v2)**2 + 1))

    return same_length(candles, res) if sequential else res[-1]
Esempio n. 26
0
File: E_15_2.py Progetto: nwf5d/note
def SMAWMA(df, count, acmroi, winnum, winfact):
    close = np.array(df['close'], dtype=float)
    SMA = talib.SMA(close, 5)  #close 代進SMA方法做計算
    WMA = talib.WMA(close, 5)  #close 代進WMA方法做計算
    df['SMA'] = SMA
    df['WMA'] = WMA
    #    print(df)
    #設定初始值
    df['XBuy'] = np.nan
    df['YBuy'] = np.nan
    df['XSell'] = np.nan
    df['YSell'] = np.nan
    row = len(df)
    flag = False
    change = 0
    buyprice = []
    sellprice = []
    win = 0
    loss = 0
    roi = 0
    for i in range(row):
        change = df['WMA'].iloc[i] / df['SMA'].iloc[i]
        if (flag == False) & (df['WMA'].iloc[i] >
                              df['SMA'].iloc[i]) & (change >= 1.02):
            df['XBuy'].iloc[i] = df['dates'].iloc[i]
            df['YBuy'].iloc[i] = df['close'].iloc[i]
            buyprice = df['close'].iloc[i]
            flag = True
        if (flag == True) & (df['WMA'].iloc[i] <=
                             df['SMA'].iloc[i]) & (change <= 0.98):
            df.XSell[i] = df['dates'].iloc[i]
            df.YSell[i] = df['close'].iloc[i]
            sellprice = df['close'].iloc[i]
            count += 1
            flag = False
            [roi, winnum] = roical(buyprice, sellprice, winnum)
            acmroi += roi
            [loss, win] = winfactor(buyprice, sellprice, loss, win)
        if (flag == True & i == (row - 1)):
            df.XSell[i] = df['dates'].iloc[i]
            df.YSell[i] = df['close'].iloc[i]
            sellprice = df['close'].iloc[i]
            count += 1
            [roi, winnum] = roical(buyprice, sellprice, winnum)
            acmroi += roi
    if (loss == 0):
        loss = 1
    winvar = win / loss
    print(' win = ', win)
    print('loss = ', loss)
    print('winvar = ', winvar)
    if (count == 0):
        count = 0.01
    str1 = 'SMAWMA策略: ' + '交易次數 = ' + str(count) + ' 次; ' + '累計報酬率 = ' + str(
        round(acmroi * 100, 2)) + '%;' + '勝率 = ' + str(
            round((winnum / count) * 100, 2)) + '%' + '; 獲利因子 = ' + str(
                round(winvar, 2))
    print(str1)
    return (count, acmroi, winnum, winvar)
Esempio n. 27
0
 def wma(self, n: int, array: bool = False) -> Union[float, np.ndarray]:
     """
     WMA.
     """
     result = talib.WMA(self.close, n)
     if array:
         return result
     return result[-1]
Esempio n. 28
0
 def test_lwma(self):
     """
     Test linear weighted moving average.
     """
     periods = 200
     lwma = qufilab.lwma(self.close, periods)
     lwma_talib = talib.WMA(self.close, periods)
     np.testing.assert_allclose(lwma, lwma_talib, rtol=self.tolerance)
Esempio n. 29
0
 def wma(self, n, array=False):
     """
     WMA.
     """
     result = talib.WMA(self.close, n)
     if array:
         return result
     return result[-1]
Esempio n. 30
0
    def wma_close(self, sym, frequency, period=30):
        if not self.kbars_ready(sym, frequency):
            return []

        closes = self.close(sym, frequency)
        ma = ta.WMA(closes, timeperiod=period)

        return ma