def create_lots_of_rsis(prices): rsis = np.reshape(RSI(prices, timeperiod=6), (len(prices), 1)) for i in range(7, 21): rsi_i = np.reshape(RSI(prices, timeperiod=i), (len(prices), 1)) rsis = np.hstack((rsis, rsi_i)) return rsis
def CalculateIndices(df): MACD_FAST = 10 MACD_SLOW = 21 MACD_SIGNAL = 7 macd, macdSignal, macdHist = MACD(df['c'], MACD_FAST, MACD_SLOW, MACD_SIGNAL) rsi10 = RSI(df['c'], 10) rsi14 = RSI(df['c'], 14) return macd, macdSignal, macdHist, rsi10, rsi14
def biases(df: DataFrame) -> (List, List, DataFrame): """A function to populate the main df with signals bool values""" df['rsi_2'] = RSI(df['close'], 2) df['rsi_14'] = RSI(df['close'], 14) signal_names = [ 'buysharpe', 'ma_50', 'ma_100', 'Mvwap', 'Wvwap', 'rsi_2', 'rsi_14' ] for signal in signal_names: df[f'signal_{str(signal)}'] = False # calc sharpe of buy and hold buysharpe = calc_metrics(df, 'buy&hold') df['signal_buysharpe'] = True # calc sharpe of close above vwap and show True df_Wvwap = df[df['close'].shift(1) > df['W_vwap'].shift(1)] df.loc[df['close'].shift(1) > df['W_vwap'].shift(1), 'signal_Wvwap'] = True Wvwap = calc_metrics(df_Wvwap, '>Wvwap') df_Mvwap = df[df['close'].shift(1) > df['M_vwap'].shift(1)] df.loc[df['close'].shift(1) > df['M_vwap'].shift(1), 'signal_Mvwap'] = True Mvwap = calc_metrics(df_Mvwap, '>Mvwap') # calc metrics of price closing above 50ma, 100ma and show True df_50ma = df[df['close'].shift(1) > df['50d_ma'].shift(1)] df.loc[df['close'].shift(1) > df['50d_ma'].shift(1), 'signal_ma_50'] = True ma_50 = calc_metrics(df_50ma, '>50d_ma') df_100ma = df[df['close'].shift(1) > df['100d_ma'].shift(1)] df.loc[df['close'].shift(1) > df['50d_ma'].shift(1), 'signal_ma_100'] = True ma_100 = calc_metrics(df_100ma, '>100d_ma') # calc metrics of rsi_2 > 90 and show True df_rsi_2 = df[df['rsi_2'].shift(1) > 90] df.loc[df['rsi_2'].shift(1) > 90, 'signal_rsi_2'] = True rsi_2 = calc_metrics(df_rsi_2, 'RSI_2>90') df_rsi_14 = df[df['rsi_14'].shift(1) > 70] df.loc[df['rsi_14'].shift(1) > 70, 'signal_rsi_14'] = True rsi_14 = calc_metrics(df_rsi_14, 'RSI_14>70') greens = df[df['colour'] == 'gr'] reds = df[df['colour'] == 'r'] # list of lists containing metrics of all active signals signals = [buysharpe, ma_50, ma_100, Mvwap, Wvwap, rsi_2, rsi_14] return signal_names, signals, df
def rsi_strategy_001(dfsource, length=14, overbought=80, oversold=20): """ Simple RSI strategy: [1] Buy: RSI(t-1) < Oversold(t-1) and RSI(t) > Oversold(t) [-1]Sell: RSI(t-1) > Overbought(t-1) and RSI(t) < Overbought(t) [0] Hold: Otherwise input: series returns: A list of results [{0,-1,1},..., n] """ rsi = RSI(dfsource, length) results = [] for i in range(len(rsi)): if rsi[i] == None: results.append(0) continue # Buy condition elif rsi[i - 1] < oversold and rsi[i] > oversold: results.append(1) # Sell Condition elif rsi[i - 1] > overbought and rsi[i] < overbought: results.append(-1) # Hold Condition else: results.append(0) return results
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 get_rsi_score(self, product_df): rsi = RSI(product_df.close).iloc[-1] if rsi >= RSI_UPPER: return -1 elif rsi <= RSI_LOWER: return 1 return 0
def getRSI(price): date = 1 RSI_ = [] rsi = RSI(price, timeperiod=14) for ele in rsi: RSI_.append([date, ele]) date = date + 1 return RSI_
def run(self): minKlines = max(200, self._calcMinKlines()) for i in range(minKlines, len(self.ohlcvs[self.timeFrames[0]])): tempDf = self.ohlcvs[self.timeFrames[0]].iloc[i-minKlines:i+1].copy() rsi = RSI(tempDf['close'], self.params['rsi']) if rsi[-2] < 50: # Long condition 1 tempDf.loc[tempDf.index[-1], 'close'] = tempDf['high'][-1] rsi = RSI(tempDf['close'], self.params['rsi']) if rsi[-1] > 50: # Long condition 2 for i in np.arange(tempDf['open'][-1], tempDf['high'][-1] + self.ohlcvs['pip'], self.ohlcvs['pip']): openPrice = round(i, self.ohlcvs['precision']) tempDf.loc[tempDf.index[-1], 'close'] = openPrice # Indicators rsi = RSI(tempDf['close'], self.params['rsi']) if rsi[-1] > 50: # Long condition 2 if len(self.openTradesL) > 0: self.closeTrade(time=tempDf.index[-1], tradeType='market', closePrice=openPrice) self.openTrade(time=tempDf.index[-1], side='long', tradeType='market', leverage=self.params['leverage'], amount=self.capital, openPrice=openPrice) break elif rsi[-2] > 50: # Short condition 1 tempDf.loc[tempDf.index[-1], 'close'] = tempDf['low'][-1] rsi = RSI(tempDf['close'], self.params['rsi']) if rsi[-1] < 50: # Short condition 2 for i in np.arange(tempDf['open'][-1], tempDf['low'][-1] - self.ohlcvs['pip'], self.ohlcvs['pip'] * -1): openPrice = round(i, self.ohlcvs['precision']) tempDf.loc[tempDf.index[-1], 'close'] = openPrice # Indicators rsi = RSI(tempDf['close'], self.params['rsi']) if rsi[-1] < 50: # Short condition 2 if len(self.openTradesL) > 0: self.closeTrade(time=tempDf.index[-1], tradeType='market', closePrice=openPrice) self.openTrade(time=tempDf.index[-1], side='short', tradeType='market', leverage=self.params['leverage'], amount=self.capital, openPrice=openPrice) break
def add_technicals(price, close): price["RSI"] = RSI(close, timeperiod=14) price["BBP"] = bbp(price) price["BB_up"], price["BB_mid"], price["BB_low"] = BBANDS(close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0) return price
def get_stock_rsi_daily(time_series_df, ticker): """ compute rolling RSI of stock prices using talib """ close = get_time_series_adjusted_close(time_series_df, ticker) rsi = RSI(close, timeperiod=20) rsi_series = pd.Series(rsi) tmpDf = pd.DataFrame(data=rsi_series, columns=['RSI']) time_series_df.loc[ticker, 'RSI'] = tmpDf['RSI'].values return time_series_df
def execute(self, env, df): ''' Execute a single iteration of algorithmic trading ''' last_row_idx = len(df) - 1 for product_id in env.product_id_list: product_df = df[product_id] rsi = RSI(product_df.close) macd, macd_signal, macd_hist = MACD( product_df.close, fastperiod=self.fast_period, slowperiod=self.slow_period, signalperiod=self.signal_period) if self.states.get(product_id) is None: self.states[product_id] = NO_POSITION next_state = self.next_state(product_id, rsi[last_row_idx], macd[last_row_idx]) if self.states[product_id] != next_state: if next_state == BUY: # buy if len(env.positions) == 0: quantity = env.balance / product_df.close[last_row_idx] ts = product_df.timestamp[last_row_idx] price = product_df.close[last_row_idx] buy_order = BuyMarketOrder(product_id, ts, funds=env.balance) env.process_buy_order(buy_order) else: print("already holding trade") self.states[product_id] = POSITION_HELD elif next_state == SELL: # sell if len(env.positions): for position in env.find_positions( lambda x: x.product_id == product_id): ts = product_df.timestamp[last_row_idx] sell_order = SellMarketOrder( product_id, ts, quantity=position.quantity, ) env.process_sell_order(sell_order) else: print("did not have active trade") self.states[product_id] = NO_POSITION else: self.states[product_id] = next_state
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 checkRSI(apikey, from_email, data_window_length, rsi_window_length):#window length for data and window length for moving average are passed through try: #create start and end dates start = (datetime.now() - timedelta(days=data_window_length)).strftime('%Y-%m-%d') end = datetime.now().strftime('%Y-%m-%d') #get closing price data symbol = 'BITSTAMP/USD' btc = web.DataReader(symbol, 'quandl', start, end)['Last'] #make into numpy array close = btc.values #use TA-lib to calculate rsi array = RSI(close, timeperiod=rsi_window_length) #graph last 2 years #plt.figure() #plt.plot(array) #plt.show() #get last month #lastmonth = array[-31:] #graph last month #plt.figure() #plt.plot(lastmonth) #plt.show() #get todays rsi rsitoday = round( array[-1], 2) #interpret rsi meaning if rsitoday >= 70: rsimeaning = "is overbought" elif 70 > rsitoday > 50: rsimeaning = "is trending towards being overbought" elif rsitoday == 50: rsimeaning = "shows no trend" elif 50 < rsitoday < 30: rsimeaning = "is trending towards being overbought" elif rsitoday <= 30: rsimeaning = "is oversold" print("----------The RSI is ", rsitoday, " which indicates that bitcoin ", sep="") print("---------------", rsimeaning, sep="") #send rsi notification emails rsiMailer(apikey, from_email, rsitoday, rsimeaning) except Exception as e: print(e)
def duration_of_trend (ticker, prices): streak = 0 streaks = [] for index in reversed(range(0, len(prices) - 1)) : if (prices[index] > prices[index+1]) : if (streak < 0) : streak = 0 streak += 1 elif (prices[index] < prices[index+1]) : if (streak > 0) : streak = 0 streak -= 1 else : streak = 0 streaks.append(float(streak)) rsi = RSI(np.asarray(streaks), timeperiod=2).tolist() rsi.reverse() return rsi.pop(0)
def rsi_increasing_all_timeframes(self, period=20): def is_increasing(series): midpoint = int(len(series) / 2) return series[:midpoint].mean() < series[midpoint:].mean() results = [] for i in list(self.tf.keys()): rsi_timeframe = RSI(self.tf[i].close.as_matrix())[-period:] results.append(is_increasing(rsi_timeframe)) return all(results)
def add_rsi(historical_data): prices = historical_data['Adj Close'].as_matrix() rsis = dict() for i in range(6, 21): rsi_i = RSI(prices, timeperiod=i) rsis['rsi' + str(i)] = rsi_i rsis_dataframe = pd.DataFrame(rsis) return historical_data.join(rsis_dataframe)
def MASync(stock, interval): currentTicks = stock.currentTicks.getTicksWithInterval(interval) totalTicks = stock.totalTicks.getTicksWithInterval(interval) stockNum = stock.stockNum if totalTicks.getNum() == 0 or currentTicks.getNum() == 0: return [] # MA60 = SMA(array(totalTicks.closes, dtype=double), 60) # MA20 = SMA(array(totalTicks.closes, dtype=double), 20) # MA10 = SMA(array(totalTicks.closes, dtype=double), 10) RSI_PERIOD = 9 if len( totalTicks.closes ) < RSI_PERIOD * 2 + 1 or INVALID_PRICE in totalTicks.closes[-RSI_PERIOD * 2 - 1:]: return [] RSICloses = [] for idx in range(len(totalTicks.closes) - 1, -1, -1): if totalTicks.closes[idx] != -1: RSICloses.append(totalTicks.closes[idx]) else: lastClose = RSICloses[-1] for i in range(20): RSICloses.append(lastClose + (i % 2 == 1)) break RSICloses = RSICloses[::-1] rsi = RSI(array(RSICloses, dtype=double), timeperiod=RSI_PERIOD) signal = [] MA60Direction = MADirection(totalTicks.closes, 60) MA20Direction = MADirection(totalTicks.closes, 20) MA10Direction = MADirection(totalTicks.closes, 10) if MA60Direction == "Up" and MA20Direction == "Up" and MA10Direction == "Up" and rsi[ -2] < 50 and rsi[-1] > 50: timestamp = currentTicks.times[-1].strip() s = "【均線多頭排列】 股票代號 : %s %s" % (stockNum, timestamp) signal.append(s) if MA60Direction == "Down" and MA20Direction == "Down" and MA10Direction == "Down" and rsi[ -2] > 50 and rsi[-1] < 50: timestamp = currentTicks.times[-1].strip() s = "【均線空頭排列】 股票代號 : %s %s" % (stockNum, timestamp) signal.append(s) return signal
def CodeBuy(code, index): aim = code + ".TW" aimTW = code target = '' try: target = data.get_data_yahoo(aim, start=TF, end=today) except: time.sleep(5) try: target = data.get_data_yahoo(aim, start=TF, end=today) except: target = data.get_data_yahoo(aim + "O", start=TF, end=today) if target['Volume'][-1] == 0 or twseresp["data9"][index][8] == '--': return False #股價收盤 price = float((twseresp["data9"][index][8]).replace(',', '')) #100日平均成交股數 Volume = target['Volume'][(len(target['Volume']) - 101):] AV = 0 for DV in Volume: AV += (DV / 100) AV = round(AV, 2) #股價200日均線 SMA_200 = float(SMA(round(target.Close, 2), timeperiod=200)[-1]) SMA_200 = round(SMA_200, 2) SMA_60 = float(SMA(round(target.Close, 2), timeperiod=60)[-1]) SMA_60 = round(SMA_60, 2) #取rsi(2) rsi2 = float(RSI(round(target.Close, 2), 2)[-1]) rsi2 = round(rsi2, 2) #目標價格 aimprice = price #股價高於200日均線和60日均線, RSI2小於10, 成交股數高於500k, 買入 if price > SMA_200 and price > SMA_60 and rsi2 < 10 and AV > 500000: vs.buy(aimTW, 1, aimprice) writer1.writerow([aim, '買入', aimprice, SMA_200, SMA_60, rsi2, AV]) return True #股價低於200日均線和60日均線, RSI2大於90, 成交股數高於500k, 放空 elif price < SMA_200 and price < SMA_60 and rsi2 > 90 and AV > 500000: vs.Margin_Sell(aimTW, 1, aimprice) writer1.writerow([aim, '放空', aimprice, SMA_200, SMA_60, rsi2, AV]) return True else: return False
def get_RSI(day, tickers, dl=22): d = timedelta(days=dl) window = timedelta(days=100) start_date = datetime.strftime(day - d, "%Y-%m-%d") start_date_window = datetime.strftime(day - window, "%Y-%m-%d") end_date = datetime.strftime(day, "%Y-%m-%d") after_start_date = df["Date"] >= start_date_window before_end_date = df["Date"] <= end_date between_two_dates = after_start_date & before_end_date filtered_dates = df.loc[between_two_dates] res = [] for ticker in tickers: fin = filtered_dates[filtered_dates['Short_Ticker'] == ticker] fin = fin.copy() real = RSI(fin['Adj Close'], timeperiod=14) real = real.tolist() fin["RSI"] = real start_date_idx = fin["Date"] >= start_date fin = fin.loc[start_date_idx] #print(fin) res.append(fin) #print("RSI") #print(pd.concat(res)) return pd.concat(res)
def get_technical_analysis(stock_data: pd.DataFrame, stock_name: str) -> pd.DataFrame: data = stock_data.query(f'stock_name=="{stock_name}"') close_prices = data['Adj Close'].values up, mid, low = BBANDS(close_prices, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0) rsi = RSI(close_prices, timeperiod=14) bbp = (data['Adj Close'] - low) / (up - low) data['lower_bound'] = low data['upper_bound'] = up data['RSI'] = rsi data['BBP'] = bbp return data
def execute(dates, price): rsi = RSI(price, timeperiod=14) indicator = { 'series': rsi, 'go_up': rsi < 25, 'go_down': rsi > 75 } all_orders = stragegy_helper_single_indicator.get_orders(dates, price, indicator) statistics = trade_helper.compute_statistics_from_orders(all_orders) new_stats = copy.deepcopy(statistics) new_stats['name'] = 'rsi' return new_stats
def priceTechnicalIndicatorOHLCV(open_price, high_price, low_price, close_price, volume): data_result = pd.DataFrame([]) lags = [7, 14, 21, 28] # ****** 待修改,技术指标的参数只用最常用的一套 # accumlation/distribution ad = AD(high_price, low_price, close_price, volume) for lag in lags: # n day diff of AD tmp = ad.diff(lag) tmp.name = 'AD_DIFF_%dD' % lag data_result = pd.concat([data_result, tmp], axis=1) #Average Directional Movement Index tmp = ADX(high_price, low_price, close_price, lag) tmp.name = 'ADX_%dD' % lag data_result = data_result.join(tmp) # Commodity Channel Index tmp = CCI(high_price, low_price, close_price, lag) tmp.name = 'CCI_%dD' % lag data_result = data_result.join(tmp) # RSI tmp = RSI(close_price, lag) tmp.name = 'RSI_%dD' % lag data_result = data_result.join(tmp) # Stochastic tmp_k, tmp_d = STOCH(high_price, low_price, close_price, fastk_period=lag, slowk_period=3, slowd_period=3) tmp_k.name = 'STOCH_K_%dD' % lag tmp_d.name = 'STOCH_D_%dD' % lag data_result = data_result.join(tmp_k) data_result =data_result.join(tmp_d) # WILLR - Williams' %R tmp = WILLR(high_price, low_price, close_price, lag) tmp.name = 'WILLER_%dD' % lag data_result =data_result.join(tmp) # volatility ratio tmp = VR(high_price, low_price, close_price, lag) tmp.name = 'VR_%dD' % lag data_result = data_result.join(tmp) 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 calculateIndex(filePath): File = open(filePath, "r") text = File.read() text = text.rstrip() File.close() OHLCV = json.loads(text) timePeriod = np.array(OHLCV['t']) nClose = np.array(OHLCV['c']) rsi = RSI(nClose, timeperiod=RSI_T) macd, macdSignal, macdHist = MACD(nClose, MACD_FAST, MACD_SLOW, MACD_SIGNAL) emaSlow = EMA(nClose, EMA_SLOW) emaMedium = EMA(nClose, EMA_MEDIUM) emaFast = EMA(nClose, EMA_FAST) #print("RSI (first 10 elements)\n", rsi[10:20]) return timePeriod, rsi, macd, macdSignal, macdHist, emaSlow, emaMedium, emaFast
def _calc_indicator(self, OHLCV_input): """ Calculates the Relative Strength Index 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(RSI(close, self.__timeperiod)) output.columns = ['RSI%d' % self.__timeperiod] return output
def calculateIndex(filePath): File = open(filePath, "r") text = File.read() text = text.rstrip() File.close() OHLCV = json.loads(text) timePeriod = OHLCV['t'] if timePeriod: nClose = np.array(OHLCV['c']) rsi = RSI(nClose, timeperiod=RSI_T) macd, macdSignal, macdHist = MACD(nClose, MACD_FAST, MACD_SLOW, MACD_SIGNAL) #print("RSI (first 10 elements)\n", rsi[-1]) return rsi, macd, macdSignal, macdHist else: return 100, 0, 0, 0
def get_new_data( self, now ): new_row = {} self.is_trading_locked = False new_row[ 'timestamp' ] = now.strftime( "%Y-%m-%d %H:%M" ) # Calculate moving averages and RSI values for a_kraken_ticker, a_robinhood_ticker in config[ 'ticker_list' ].items(): if ( not config[ 'debug_enabled' ] ): try: result = get_json( 'https://api.kraken.com/0/public/Ticker?pair=' + str( a_kraken_ticker ) ).json() if ( len( result[ 'error' ] ) == 0 ): new_row[ a_robinhood_ticker ] = round( float( result[ 'result' ][ a_kraken_ticker ][ 'a' ][ 0 ] ), 3 ) except: print( 'An exception occurred retrieving prices.' ) self.is_trading_locked = True return self.data else: new_row[ a_robinhood_ticker ] = round( float( randint( 10, 100 ) ), 3 ) self.data = self.data.append( new_row, ignore_index = True ) # If the Kraken API is overloaded, they freeze the values it returns if ( ( self.data.tail( 4 )[ a_robinhood_ticker ].to_numpy()[ -1 ] == self.data.tail( 4 )[ a_robinhood_ticker ].to_numpy() ).all() ): print( 'Repeating values detected for ' + str( a_robinhood_ticker ) + '. Ignoring data point.' ) self.data = self.data[:-1] elif ( self.data.shape[ 0 ] > 0 ): self.data[ a_robinhood_ticker + '_SMA_F' ] = self.data[ a_robinhood_ticker ].shift( 1 ).rolling( window = config[ 'moving_average_periods' ][ 'sma_fast' ] ).mean() self.data[ a_robinhood_ticker + '_SMA_S' ] = self.data[ a_robinhood_ticker ].shift( 1 ).rolling( window = config[ 'moving_average_periods' ][ 'sma_slow' ] ).mean() self.data[ a_robinhood_ticker + '_RSI' ] = RSI( self.data[ a_robinhood_ticker ].values, timeperiod = config[ 'rsi_period' ] ) self.data[ a_robinhood_ticker + '_MACD' ], self.data[ a_robinhood_ticker + '_MACD_S' ], macd_hist = MACD( self.data[ a_robinhood_ticker ].values, fastperiod = config[ 'moving_average_periods' ][ 'macd_fast' ], slowperiod = config[ 'moving_average_periods' ][ 'macd_slow' ], signalperiod = config[ 'moving_average_periods' ][ 'macd_signal' ] ) if ( config[ 'save_charts' ] == True ): slice = self.data[ [ a_robinhood_ticker, str( a_robinhood_ticker ) + '_SMA_F', str( a_robinhood_ticker ) + '_SMA_S' ] ] fig = slice.plot.line().get_figure() fig.savefig( 'chart-' + str( a_robinhood_ticker ).lower() + '-sma.png', dpi = 300 ) plt.close( fig ) return self.data
def init_data( self ): print( 'Starting with a fresh dataset.' ) # Download historical data from Kraken column_names = [ 'timestamp' ] for a_robinhood_ticker in config[ 'ticker_list' ].values(): column_names.append( a_robinhood_ticker ) self.data = pd.DataFrame( columns = column_names ) for a_kraken_ticker, a_robinhood_ticker in config[ 'ticker_list' ].items(): try: result = get_json( 'https://api.kraken.com/0/public/OHLC?interval=' + str( config[ 'bot' ][ 'minutes_between_updates' ] ) + '&pair=' + a_kraken_ticker ).json() historical_data = pd.DataFrame( result[ 'result' ][ a_kraken_ticker ] ) historical_data = historical_data[ [ 0, 1 ] ] self.api_error_counter = 0 # Be nice to the Kraken API sleep( 3 ) except: print( 'An exception occurred retrieving historical data from Kraken.' ) self.api_error_counter = self.api_error_counter + 1 return False # Convert timestamps self.data[ 'timestamp' ] = [ pd.Timestamp( datetime.fromtimestamp( x ).strftime( "%Y-%m-%d %H:%M" ) ) for x in historical_data[ 0 ] ] # Copy the data self.data[ a_robinhood_ticker ] = [ round( float( x ), 3 ) for x in historical_data[ 1 ] ] # Calculate the indicators self.data[ a_robinhood_ticker + '_SMA_F' ] = self.data[ a_robinhood_ticker ].shift( 1 ).rolling( window = config[ 'ta' ][ 'moving_average_periods' ][ 'sma_fast' ] ).mean() self.data[ a_robinhood_ticker + '_SMA_S' ] = self.data[ a_robinhood_ticker ].shift( 1 ).rolling( window = config[ 'ta' ][ 'moving_average_periods' ][ 'sma_slow' ] ).mean() self.data[ a_robinhood_ticker + '_EMA_F' ] = self.data[ a_robinhood_ticker ].ewm( span = config[ 'ta' ][ 'moving_average_periods' ][ 'ema_fast' ], adjust = False, min_periods = config[ 'ta' ][ 'moving_average_periods' ][ 'ema_fast' ]).mean() self.data[ a_robinhood_ticker + '_EMA_S' ] = self.data[ a_robinhood_ticker ].ewm( span = config[ 'ta' ][ 'moving_average_periods' ][ 'ema_slow' ], adjust = False, min_periods = config[ 'ta' ][ 'moving_average_periods' ][ 'ema_slow' ]).mean() self.data[ a_robinhood_ticker + '_RSI' ] = RSI( self.data[ a_robinhood_ticker ].values, timeperiod = config[ 'ta' ][ 'rsi_period' ] ) self.data[ a_robinhood_ticker + '_MACD' ], self.data[ a_robinhood_ticker + '_MACD_S' ], macd_hist = MACD( self.data[ a_robinhood_ticker ].values, fastperiod = config[ 'ta' ][ 'moving_average_periods' ][ 'macd_fast' ], slowperiod = config[ 'ta' ][ 'moving_average_periods' ][ 'macd_slow' ], signalperiod = config[ 'ta' ][ 'moving_average_periods' ][ 'macd_signal' ] )
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
def main(): file_content = file_io_service.load_historical_data('PETR4.SA') file_content = file_content.dropna() close = file_content['Adj Close'].values date = np.array( list( map(lambda x: date_helper.parse_date_to_datetime(x), file_content['Date']))) rsi = RSI(close, timeperiod=14) macd, macdsignal, macdhist = MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) up, mid, low = BBANDS(close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0) fig, (ax0, ax1, ax2) = plt.subplots(3, 1, sharex=True, figsize=(12, 8)) ax0.plot(date, close, label='Close') ax0.set_xlabel('Date') ax0.set_ylabel('Close') ax0.grid() ax1.plot(date, rsi, label='Close', linewidth=.5) ax1.set_xlabel('Date') ax1.set_ylabel('Close') ax1.grid() ax2.plot(date, up, label='BB_up', color='BLUE', linewidth=.5) ax2.plot(date, close, label='AdjClose', color='BLACK', linewidth=.5) ax2.plot(date, low, label='BB_low', color='RED', linewidth=.5) ax2.fill_between(date, y1=low, y2=up, color='#adccff', alpha='0.3') ax2.set_xlabel('Date') ax2.set_ylabel('Bollinger Bands') ax2.grid() fig.tight_layout() plt.show()