def obv(close, volume, talib=None, offset=None, **kwargs): """Indicator: On Balance Volume (OBV)""" # Validate arguments close = verify_series(close) volume = verify_series(volume) offset = get_offset(offset) mode_tal = bool(talib) if isinstance(talib, bool) else True # Calculate Result if Imports["talib"] and mode_tal: from talib import OBV obv = OBV(close, volume) else: signed_volume = signed_series(close, initial=1) * volume obv = signed_volume.cumsum() # Offset if offset != 0: obv = obv.shift(offset) # Handle fills if "fillna" in kwargs: obv.fillna(kwargs["fillna"], inplace=True) if "fill_method" in kwargs: obv.fillna(method=kwargs["fill_method"], inplace=True) # Name and Categorize it obv.name = f"OBV" obv.category = "volume" return obv
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
def getOBV(price, volume): date = 1 OBV_ = [] obv = OBV(price, volume) for ele in obv: OBV_.append([date, ele]) date = date + 1 return OBV_
def volumeTechnicalIndicators(price, volume, tot_lags, prefix): data_result = priceTechnicalIndicator(volume, tot_lags, prefix) # OBV lags = tot_lags obv = OBV(price, volume) for lag in lags: tmp = obv.diff(lag) # diff, otherwise the scale would change if accumulates tmp.name = 'OBV_DIFF_%dD' % lag data_result = data_result.join(tmp) # VOLUME RATIO lag = 5 tmp = volume.rolling(window=lag).mean() volume_ratio = volume / tmp volume_ratio.name = 'VOLUME_RATIO' data_result = data_result.join(volume_ratio) return data_result
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]
def amountTechnicalIndicators(price, amount, tot_lags, prefix): data_result = priceTechnicalIndicator(amount, tot_lags, prefix) # OBV lags = tot_lags amt_obv = OBV(price, amount) for lag in lags: tmp = amt_obv.diff(lag) # diff, otherwise the scale would change if accumulates tmp.name = 'AMT_OBV_DIFF_%dD' % lag data_result = data_result.join(tmp) # AMOUNT RATIO lags = np.array(tot_lags) lags = lags[lags >= 2] for lag in lags: tmp = amount.rolling(window=lag).mean() amt_ratio = amount / tmp amt_ratio.name = 'AMOUNT_RATIO_%dD' % lag data_result = data_result.join(amt_ratio) return data_result
def create_features(ts): from talib import SMA, RSI, OBV target = 'future_close_ret' features = ['current_close_ret', 'current_volume_ret'] for n in [14, 25, 50, 100]: ts['sma_' + str(n)] = SMA(ts['close'].values, timeperiod=n) / ts['close'] ts['rsi_' + str(n)] = RSI(ts['close'].values, timeperiod=n) ts['obv'] = OBV(ts['close'].values, ts['volume'].values.astype('float64')) ts.drop( ['close', 'volume', 'close_ret', 'volume_ret', 'future_volume_ret'], axis='columns', inplace=True) ts.dropna(inplace=True) return ts.corr()
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
def calcOBV(self, dates, price, volume): obv = OBV(price, volume) OBV_, isExist = self.createDateFrame(dates, obv, ['timestamp', 'OBV']) return OBV_, isExist
def setvolume(open, high, low, close, volume): #volume df["obv"] = OBV(close, volume) #df["ad"] = AD(high, low, close, volume) df["ad"] = ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10)
slowperiod=26, signalperiod=9) # print('-----------------------------------MACD-----------------------------------') # print(macd[34:37]) # print(macdsignal[34:37]) # print(macdhist[34:37]) # rsi = RSI(fechamento, timeperiod=14) # print('-----------------------------------RSI-----------------------------------') # print(rsi[34:37]) # Momentum Indicators # Volume Indicators mfi = MFI(maximo, minimo, fechamento, volume, timeperiod=14) # print('-----------------------------------MFI-----------------------------------') # print(mfi[34:37]) #Volume Indicators ad = AD(maximo, minimo, fechamento, volume) adosc = ADOSC(maximo, minimo, fechamento, volume, fastperiod=3, slowperiod=10) obv = OBV(fechamento, volume) # dataFrameConcatened = pd.concat(fechamento, rsi) dataFrameConcatened = np.concatenate((abertura, rsi), axis=0) print(dataFrameConcatened) ax = plt.gca() # brsr6CSV.plot(kind='line',x='DATA',y='ABERTURA',ax=ax) brsr6CSV.plot(kind='line', x='DATA', y='FECHAMENTO', color='red', ax=ax) plt.plot(upBR, label='BB UP') plt.plot(lowBR, label='BB Low') plt.show()
def fetch(self, symbol: str, interval: Interval = Interval.DAY, window: Window = Window.YEAR, indicators: Indicators = [], verbose=False) -> pd.DataFrame: """ Fetch symbol stock OHLCV from Yahoo Finance API Args: symbol (str): Symbol to fetch interval (Interval, optional): Interval (hour, day, week, ...) of data. Defaults to Interval.DAY. window (Window, optional): Length (day, week, month, year) of interval. Defaults to Window.YEAR. indicators (Indicators, optional): Array of indicators to include in the result. Defaults to empty array. Returns: pd.DataFrame: OHLCV pandas DataFrame with interval on window length and indicators if specified """ try: if verbose: print( f"Fetching OHLCV {symbol} stock data on {interval.name} interval and {window.name} window" ) # Generic url to fetch url = f"https://query1.finance.yahoo.com/v8/finance/chart/{symbol}?region=FR&lang=fr-FR&includePrePost=false&interval={interval.value}&range={window.value}&corsDomain=fr.finance.yahoo.com&.tsrc=finance" req = requests.get(url) # Testing request status code if req.status_code == 200: # Extracting data as json data = req.json() # Creating new DataFrame df = pd.DataFrame() # Extract date from object if interval in [ Interval.MINUTE, Interval.TWO_MINUTE, Interval.FIVE_MINUTE, Interval.FIFTEEN_MINUTE, Interval.THIRTY_MINUTE, Interval.HOUR ]: dateFromUnix = [ datetime.utcfromtimestamp(dt).strftime( "%Y-%m-%d %H:%M:%S") for dt in data["chart"]["result"][0]["timestamp"] ] else: dateFromUnix = [ datetime.utcfromtimestamp(dt).strftime("%Y-%m-%d") for dt in data["chart"]["result"][0]["timestamp"] ] # Date & OHLCV to DataFrame df["date"] = pd.to_datetime(dateFromUnix) df["open"] = data["chart"]["result"][0]["indicators"]["quote"][ 0]["open"] df["high"] = data["chart"]["result"][0]["indicators"]["quote"][ 0]["high"] df["low"] = data["chart"]["result"][0]["indicators"]["quote"][ 0]["low"] df["close"] = data["chart"]["result"][0]["indicators"][ "quote"][0]["close"] df["volume"] = data["chart"]["result"][0]["indicators"][ "quote"][0]["volume"] # Drop NaN on close col df.dropna(subset=["close"], inplace=True) # Divide volume column by a 1 000 df["volume"] = df["volume"].div(1000) # Set date column as index df.set_index("date", inplace=True) for indicator in indicators: # ADX if indicator == Indicators.ADX: df[indicator.value] = ADX(df["high"], df["low"], df["close"]) # BBANDS elif indicator == Indicators.BBANDS: df[Indicators.BBANDS.value[0]], df[ Indicators.BBANDS.value[1]], df[ Indicators.BBANDS.value[2]] = BBANDS( df["close"]) df["p_band"] = 100 - \ (df["l_band"] / df["u_band"] * 100) df["p_band_ma_5"] = MA(df["p_band"], timeperiod=5) # EMA elif indicator == Indicators.EMA: for ema in Indicators.EMA.value: df[ema] = EMA(df["close"], timeperiod=int(ema.split("_")[1])) # MA elif indicator == Indicators.MA: for ma in Indicators.MA.value: df[ma] = MA(df["close"], timeperiod=int(ma.split("_")[1])) # OBV elif indicator == Indicators.OBV: df[indicator.value] = OBV(df["close"], df["volume"]) df[indicator.value] = df[indicator.value].div(1000) # PSAR elif indicator == Indicators.PSAR: df[indicator.value] = SAR(df["high"], df["low"]) # PERCENT CHANGE elif indicator == Indicators.P_CHANGE: for p_change in Indicators.P_CHANGE.value: df[p_change] = df["close"].pct_change( int(p_change.split(" ")[1])) * 100 # RSI elif indicator == Indicators.RSI: df[indicator.value] = RSI(df["close"]) return df.round(decimals=2) except Exception as e: print(e)