コード例 #1
0
def roc(close, length=None, scalar=None, offset=None, **kwargs):
    """Indicator: Rate of Change (ROC)"""
    # Validate Arguments
    length = int(length) if length and length > 0 else 10
    scalar = float(scalar) if scalar and scalar > 0 else 100
    close = verify_series(close, length)
    offset = get_offset(offset)

    if close is None: return

    # Calculate Result
    if Imports["talib"]:
        from talib import ROC
        roc = ROC(close, length)
    else:
        roc = scalar * mom(close=close, length=length) / close.shift(length)

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

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

    # Name and Categorize it
    roc.name = f"ROC_{length}"
    roc.category = "momentum"

    return roc
コード例 #2
0
ファイル: cstock01.py プロジェクト: lqwangxg/python
    def refresh(self, df):
        df = df[-(MAX_ROWS + 1):-1]
        open = df.open.astype("f8").values
        high = df.high.astype("f8").values
        low = df.low.astype("f8").values
        close = df.close.astype("f8").values
        volume = df.volume.astype("f8").values

        df["price"] = WCLPRICE(high, low, close)  #Weighted Close Price
        df["obv"] = OBV(close, volume)
        df["ad"] = AD(high, low, close, volume)
        df["macd"], df["signal"], df["histogram"] = MACD(close)
        df["rsi"] = RSI(close)  #relative strong index
        #df["willr"] = WILLR(high, low, close) + 100 #will index
        df["roc"] = ROC(close)

        #統計
        df["beta"] = BETA(high, low)
        df["linearR"] = LINEARREG(close)  #線形回帰
        df["linearA"] = LINEARREG_ANGLE(close)  ##線形回帰 角度
        df["linearI"] = LINEARREG_INTERCEPT(close)  #線形回帰 JIEJU
        df["linearS"] = LINEARREG_SLOPE(close)  #線形回帰 坂
        df["stddev"] = STDDEV(close)  #標準偏差
        df["tsf"] = TSF(close)  #Time Series Forecast
        df["var"] = VAR(close)  #方差

        df["wramount"] = 0
        df["amount"] = 0
        df["memo"] = 0
コード例 #3
0
    def binaryClassificationInThirtyMinutes(self, df):
        '''
        Predict the price of bitcoin in the next 30 minutes by a given df (dataframe)

        Example: 
            binaryClassificationInThirtyMinutes(df) = 0

        Parameters:
            df: a dataframe with df.columns = ['open', 'high', 'low', 'close', 'volume']
        Returns:
            prediction: int = a prediction by the model, 0 for down, 1 for same or up
        '''

        # if len(df) != 34:
        #    # due to wma
        #    raise Exception("Dataframe must have 34 rows")

        data = df.copy()

        rsi = RSI(data['close'])
        k, d = STOCH(data['high'], data['low'], data['close'])
        macd, macdsignal, macdhist = MACD(data['close'],
                                          fastperiod=12,
                                          slowperiod=26,
                                          signalperiod=9)
        williams_r = WILLR(data['high'], data['low'], data['close'])
        rate_of_change = ROC(data['close'])
        on_balance_volume = OBV(data['close'], data['volume'])
        weighted_moving_average = WMA(data['close'])
        normalized_average_true_range = NATR(data['high'], data['low'],
                                             data['close'])

        data['rsi'] = rsi
        data['k'] = k
        data['d'] = d
        data['macd'] = macd
        data['williams_r'] = williams_r
        data['rate_of_change'] = rate_of_change
        data['on_balance_volume'] = on_balance_volume
        data['weighted_moving_average'] = weighted_moving_average
        data['normalized_average_true_range'] = normalized_average_true_range

        data = data.dropna(axis=0)

        data = self.normalizeDataframe(data)

        with open(
                pathlib.Path(__file__).resolve().parent /
                "random_forest_params", "rb") as file:
            model = pickle.load(file)

        features = data.values
        prediction = model.predict(features)
        return prediction[0]
コード例 #4
0
    def _calc_indicator(self, OHLCV_input):
        """
        Calculates the Percentage Price Oscillator technical indicator using a wrapper for the TA-lib

        Args:
            :param OHLCV_input:  the dataframe with the Open, High, Low, Close and Volume values
            :type OHLCV_input: pandas DataFrame

        Returns:
            DataFrame with the indicators values.
        """
        try:
            close = OHLCV_input['close'].values[:, 0]
        except IndexError:
            close = OHLCV_input['close'].values

        output = DataFrame(ROC(close, self.__timeperiod))
        output.columns = ['ROC%d' % self.__timeperiod]
        return output
コード例 #5
0
ファイル: cstocklib.py プロジェクト: lqwangxg/python
def refresh(df, days=MAX_DAYS):
    df = df[-(days + 1):-1]
    open = df.open.astype("f8").values
    high = df.high.astype("f8").values
    low = df.low.astype("f8").values
    df["h2"] = 0
    df["l2"] = 0
    close = df.close.astype("f8").values
    volume = df.volume.astype("f8").values

    #df["wma"] = WMA(close)
    #df["price"] = WCLPRICE(high, low, close) #Weighted Close Price
    #df["obv"] = OBV(close,volume)
    #df["ad"] = AD(high, low, close, volume)
    #df["macd"],df["signal"],df["histogram"] = MACD(close)
    df["rsi"] = RSI(close)  #relative strong index
    #df["willr"] = WILLR(high, low, close) + 100 #will index
    df["roc"] = ROC(close)
    k, d = STOCH(high, low, close)
    df["K"] = k
    df["D"] = d
    df["J"] = k * 3 - d * 2

    #統計
    #df["beta"] = BETA(high,low)
    #df["linearR"] = LINEARREG(close)#線形回帰
    #df["linearA"] = LINEARREG_ANGLE(close)##線形回帰 角度
    #df["linearI"] = LINEARREG_INTERCEPT(close)#線形回帰 JIEJU
    #df["linearS"] = LINEARREG_SLOPE(close)#線形回帰 坂
    #df["stddev"] = STDDEV(close)#標準偏差
    #df["tsf"] = TSF(close)#Time Series Forecast
    #df["var"] = VAR(close) #方差
    df["saleprice"] = 0
    df["buyprice"] = 0
    df["balance1"] = 0
    df["balance2"] = 0
    df["balance3"] = 0
    return df
コード例 #6
0
def getTechnicalInd(data, window=10):
    close = data['Close']
    high = data['High']
    low = data['Low']
    volume = data['Volume']
    #madev = roc = willr=rsi=apo=atr=obv=adosc=slowk=fastk=slowd=fastd=vpos=vneg={}
    window = 10
    for i in range(0, window):

        # momentum indicators
        # rate of change: (price/prevPrice - 1)*100
        data["roc{0}".format(i)] = ROC(close.shift(i), timeperiod=10)
        # williams oscillator
        data["willr{0}".format(i)] = WILLR(high.shift(i),
                                           low.shift(i),
                                           close.shift(i),
                                           timeperiod=14)

        # relative strength index
        data["rsi{0}".format(i)] = RSI(close.shift(i), timeperiod=14)

        # absolute price oscillator: slowMA(price) - fastMA(price)
        data["apo{0}".format(i)] = APO(close.shift(i),
                                       fastperiod=12,
                                       slowperiod=26,
                                       matype=0)
        # volatility indicator

        data["atr{0}".format(i)] = ATR(high.shift(i),
                                       low.shift(i),
                                       close.shift(i),
                                       timeperiod=14)  # average true range
        # Volume indicator
        # on balance volume
        data["obv{0}".format(i)] = OBV(close.shift(i), volume.shift(i))
        # chaikin A/D oscillator
        data["adosc{0}".format(i)] = ADOSC(high.shift(i),
                                           low.shift(i),
                                           close.shift(i),
                                           volume.shift(i),
                                           fastperiod=3,
                                           slowperiod=10)

        # Stochastic Oscillator Slow %k: (C-L)/(H-L)*100
        data["slowk{0}".format(i)], data["slowd{0}".format(i)] = STOCH(
            high.shift(i),
            low.shift(i),
            close.shift(i),
            fastk_period=5,
            slowk_period=3,
            slowk_matype=0,
            slowd_period=3,
            slowd_matype=0)

        # STOCHF - Stochastic Fast
        data["fastk{0}".format(i)], data["fastd{0}".format(i)] = STOCHF(
            high.shift(i),
            low.shift(i),
            close.shift(i),
            fastk_period=5,
            fastd_period=3,
            fastd_matype=0)

        #vortex
        data["vortex_indicator_pos{0}".format(i)] = vortex_indicator_pos(
            high.shift(i), low.shift(i), close.shift(i), n=14, fillna=False)
        data["vortex_indicator_neg{0}".format(i)] = vortex_indicator_neg(
            high.shift(i), low.shift(i), close.shift(i), n=14, fillna=False)

        # returns
    for i in range(1, window):
        # overlap studies
        data["madev{0}".format(i)] = close - close.shift(1).rolling(
            window=i).mean()
        data["return{0}".format(i)] = close - close.shift(i)
    # std
    for i in range(2, window):
        data["std{0}".format(i)] = close.rolling(
            i).std()  #Standard deviation for a period of 5 days

    return data  #madev, roc,willr,rsi,apo,atr,obv,adosc,slowk,slowd,fastk,fastd,vpos, vneg, returns, stds
コード例 #7
0
def myalgo(cache, key, ohlc_data_df, algo=None, state='SCANNING', quick=False): 
    pdebug7('myalgo {}'.format(key))

    if quick == False:
        ohlc_data_temp = ohlc_data_df.tail(51).head(50) #to reduce calculation load, remove last candle
    else:
        ohlc_data_temp = ohlc_data_df

    OPEN = ohlc_data_temp['open']
    CLOSE = ohlc_data_temp['close']
    HIGH = ohlc_data_temp['high']
    LOW = ohlc_data_temp['low']
    #VOLUME = ohlc_data_temp['volume']
    
    (haOPEN, haHIGH, haLOW, haCLOSE) = HAIKINASI(ohlc_data_temp)
 
    TIME = ohlc_data_temp.index.minute+ohlc_data_temp.index.hour*60
    
    REF = lambda df, i: df.shift(i)
    TREND_UP = lambda a,b=3: ROC(a, b) > 0.1
    TREND_DOWN = lambda a,b=3: ROC(a, b) < -0.1
    CROSSOVER = lambda a, b: (REF(a,1)<=REF(b,1)) & (a > b)
    sell = pd.DataFrame()
    buy = pd.DataFrame()
    
    BUY = lambda qty=-1, sl=-1, tp=-1, x2 = -1:order_details(cache, key, 'BUY', x2, qty, sl, tp)
    SELL = lambda qty=-1, sl=-1, tp=-1, x2 = -1:order_details(cache, key, 'SELL', x2, qty, sl, tp)
    WAIT = lambda : order_details(cache, key, 'WAIT')
    def update_decision(buy, sell):
        #pinfo(buy.index)
        cache.set('buy_df',buy.to_json(orient='index'))
        cache.set('sell_df',sell.to_json(orient='index'))
        #buy1 = buy.copy(deep=True)
        #sell1 = sell.copy(deep=True)
        try:
            if buy[-1] == True:
                BUY()
            elif sell[-1] == True:
                SELL()
            else:
                WAIT()
        except:
            WAIT()

    decision = 'WAIT'
    cache.set('decision'+cache_type,decision)
   
    try:
        if algo != '' and algo is not None:

            postfix = "update_decision(buy, sell)"
            code = algo + '\n'+ postfix

            exec(code)
            
        else:
            sell = (REF(haOPEN, 0) > REF(haCLOSE,0)) & (REF(haOPEN, 1) < REF(haCLOSE,1))
            buy = (REF(haOPEN, 0) < REF(haCLOSE,0)) & (REF(haOPEN, 1) > REF(haCLOSE,1))
            update_decision(buy, sell)
        
        decision = cache.get('decision'+cache_type)
    except:
        perror("Error in executing algorithm")

    if quick == False:
        #pinfo(decision)
        return decision #"BUY"|"SELL"
    else:
        buy = pd.read_json(cache.get('buy_df'), orient='index')
        sell = pd.read_json(cache.get('sell_df'), orient='index')
        #pinfo(buy)
        return buy[0].values, sell[0].values