def get_data(symbol): print 'Getting data' # Technical Indicators ti = TechIndicators(key='4BTFICZGTPWZRRQS', output_format='pandas') sma, _ = ti.get_sma(symbol=symbol, interval='daily') wma, _ = ti.get_wma(symbol='SPX', interval='daily') ema, _ = ti.get_ema(symbol=symbol, interval='daily') macd, _ = ti.get_macd(symbol=symbol, interval='daily') stoch, _ = ti.get_stoch(symbol=symbol, interval='daily') rsi, _ = ti.get_rsi(symbol=symbol, interval='daily') adx, _ = ti.get_adx(symbol=symbol, interval='daily') cci, _ = ti.get_cci(symbol=symbol, interval='daily') aroon, _ = ti.get_aroon(symbol=symbol, interval='daily') bbands, _ = ti.get_bbands(symbol='SPX', interval='daily') ad, _ = ti.get_ad(symbol='SPX', interval='daily') obv, _ = ti.get_obv(symbol='SPX', interval='daily') mom, _ = ti.get_mom(symbol='SPX', interval='daily') willr, _ = ti.get_willr(symbol='SPX', interval='daily') tech_ind = pd.concat([sma, ema, macd, stoch, rsi, adx, cci, aroon, bbands, ad, obv, wma, mom, willr], axis=1) print 'Getting time series' ts = TimeSeries(key='4BTFICZGTPWZRRQS', output_format='pandas') close = ts.get_daily(symbol=symbol, outputsize='full')[0].rename(columns={'4. close': 'close'})['close'] direction = (close > close.shift()).astype(int) target = direction.shift(-1).fillna(0).astype(int) target.name = 'target' data = pd.concat([tech_ind, close, target], axis=1) return data
def get_daily_technical(stock, indicator, API_key, period=-1): ti = TechIndicators(key=API_key, output_format='pandas') if indicator == "bband": if (period <= 0): period = 20 data, meta_data = ti.get_bbands(symbol=stock, interval='daily', time_period=period) elif indicator == "macd": data, meta_data = ti.get_macd(symbol=stock, interval='daily') elif indicator == "rsi": if (period <= 0): period = 14 data, meta_data = ti.get_rsi(symbol=stock, interval='daily', time_period=period) elif indicator == "cci": if (period <= 0): period = 20 data, meta_data = ti.get_cci(symbol=stock, interval='daily', time_period=period) elif indicator == "aroon": if (period <= 0): period = 14 data, meta_data = ti.get_aroon(symbol=stock, interval='daily', time_period=period) elif indicator == "ad": data, meta_data = ti.get_ad(symbol=stock, interval='daily') elif indicator == "adx": if (period <= 0): period = 20 data, meta_data = ti.get_adx(symbol=stock, interval='daily', time_period=period) elif indicator == "sma": if (period <= 0): period = 40 data, meta_data = ti.get_sma(symbol=stock, interval='daily', time_period=period) else: sys.exit('Failed to input a valid indicator') return data, meta_data
def techIndicator_get_bbands(self, timePeriod, format): #outputting data in JSON format in the below line ti = TechIndicators(key=settings.API_KEY, output_format=format) data, meta_data = ti.get_bbands(symbol=self.symbol, interval='daily', time_period=timePeriod) return data, meta_data
def getData(equity, MY_API_KEY): """ parse data for a given stock symbol. :param equity (panda series): TimeSeries data and TechIndicators pandaframe. """ # Pandaframe for TimeSeries ts = TimeSeries(key=f"{MY_API_KEY}", output_format='pandas', indexing_type='date') tsdata, tsmeta_data = ts.get_intraday(symbol=equity, interval='60min', outputsize='full') TS = tsdata.head(1000) path = "data/TimeSeries/" path += equity + ".csv" tsdata.to_csv(path_or_buf=path) # Pandaframe for TechIndicators ti = TechIndicators(key=f"{MY_API_KEY}", output_format='pandas', indexing_type='data') tidata, timeta_data = ti.get_bbands(symbol=equity, interval='60min', time_period=60) TI = tidata.head(1000) path = "data/TechIndicators/" path += equity + ".csv" tidata.to_csv(path_or_buf=path)
def get_raw_input_data(stock="DJI"): ts = TimeSeries(key=AV_API_KEY, output_format='pandas') d, md = ts.get_daily(symbol=stock, outputsize='compact') d = d.loc['2020-01-01':'2020-03-27'] d[CLOSE] = d[CLOSE].pct_change() d = d[d[CLOSE] <= 100] d = d.dropna(axis=0) TI = TechIndicators(key=AV_API_KEY, output_format='pandas') rsi_data, meta_data = TI.get_rsi(symbol=stock, interval="daily", time_period=14) macd_data, meta_data = TI.get_macd(symbol=stock, interval="daily") sma_data, meta_data = TI.get_sma(symbol=stock, time_period=30) bbands_data, meta_data = TI.get_bbands(symbol=stock) input_data = pd.DataFrame(columns=["Volume", "Price_Change"], index=d.index) input_data["Volume"] = d[VOLUME] input_data["Price_Change"] = d[CLOSE] input_data = input_data.merge(rsi_data, left_index=True, right_index=True) input_data = input_data.merge(sma_data, left_index=True, right_index=True) input_data = input_data.merge(macd_data, left_index=True, right_index=True) input_data = input_data.merge(bbands_data, left_index=True, right_index=True) input_data = input_data.merge(load_covid(), left_index=True, right_index=True) input_data = input_data.merge(gen_sentiment_df(stock), left_index=True, right_index=True) return input_data
def get_data(symbol): # Technical Indicators ti = TechIndicators(key='YOUR_API_KEY', output_format='pandas') sma, _ = ti.get_sma(symbol=symbol, interval='daily') wma, _ = ti.get_wma(symbol=symbol, interval='daily') ema, _ = ti.get_ema(symbol=symbol, interval='daily') macd, _ = ti.get_macd(symbol=symbol, interval='daily') stoch, _ = ti.get_stoch(symbol=symbol, interval='daily') rsi, _ = ti.get_rsi(symbol=symbol, interval='daily') adx, _ = ti.get_adx(symbol=symbol, interval='daily') cci, _ = ti.get_cci(symbol=symbol, interval='daily') aroon, _ = ti.get_aroon(symbol=symbol, interval='daily') bbands, _ = ti.get_bbands(symbol=symbol, interval='daily') ad, _ = ti.get_ad(symbol=symbol, interval='daily') obv, _ = ti.get_obv(symbol=symbol, interval='daily') mom, _ = ti.get_mom(symbol=symbol, interval='daily') willr, _ = ti.get_willr(symbol=symbol, interval='daily') tech_ind = pd.concat([sma, ema, macd, stoch, rsi, adx, cci, aroon, bbands, ad, obv, wma, mom, willr], axis=1) ts = TimeSeries(key='YOUR_API_KEY', output_format='pandas') close = ts.get_daily(symbol=symbol, outputsize='full')[0]['close'] # compact/full direction = (close > close.shift()).astype(int) target = direction.shift(-1).fillna(0).astype(int) target.name = 'target' data = pd.concat([tech_ind, close, target], axis=1) return data
def get_company_techindicators(company_symbol, interval): ts = TechIndicators(key=apiKey, output_format='json') # Get json object with the techindicator data and another with the call's metadata data, meta_data = ts.get_bbands(symbol=company_symbol, interval=interval) return data, meta_data
def checkSymbol(symbol, interval, msgInterval, mustCandleBullish = False): bullish = False rate = 0 gMsg = '#'+symbol + ' '+msgInterval ts = TimeSeries(key=cfg.APIKey, output_format=cfg.format) if interval == cfg.intervalDaily: #daily dataTS, meta_data = ts.get_daily(symbol=symbol) else: dataTS, meta_data = ts.get_intraday(symbol=symbol,interval=interval) sample = [dict() for x in range(3)] for i in range(1,4): sample[i-1] = {'close':dataTS['close'][-i],'high':dataTS['high'][-i],'low':dataTS['low'][-i],'open':dataTS['open'][-i]} csp = CandleStickPattern(sample[2],sample[1],sample[0]) if csp.bullishPattern(): bullish = True rate += 1 gMsg += '\nCandle Bull' else: if mustCandleBullish: return False, gMsg, rate ti = TechIndicators(key=cfg.APIKey, output_format=cfg.format) ##### bband data, meta_data = ti.get_bbands(symbol=symbol, interval=interval) # data.plot() bbLower = data['Real Lower Band'][-1] if sample[0]['low'] < bbLower: bullish = True rate += 1 gMsg += '\nBB lower band tested' ##### MACD data, meta_data = ti.get_macd(symbol=symbol, interval=interval, fastperiod=12, slowperiod = 26, signalperiod = 9) #print data.keys() if data['MACD_Hist'][-1] > 0: for i in range(2,6): if data['MACD_Hist'][-i] < 0: gMsg += '\nMACD cross' bullish = True rate += 1 break if bullish: data, meta_data = ti.get_rsi(symbol=symbol, interval = interval) if data['RSI'][-1] < 50: rate += 1 gMsg += '\nRSI ' + round(data['RSI'][-1]).__str__() gMsg += '\nVol ' + printInK(dataTS['volume'][-1]) +" "+ printInK(dataTS['volume'][-2]) +" "+ printInK(dataTS['volume'][-3]) return bullish, gMsg, rate
def technical_indicators(): if request.method == 'POST': ticker = request.form['ticker'] ti = TechIndicators(key='SS66OZ9EH3PLN7HS', output_format='pandas') data, meta_data = ti.get_bbands(symbol=ticker, interval='60min', time_period=60) plt.title('BBbands indicator') plt.savefig("static\\images\\technical_indicators\\" + ticker) filename = 'images/technical_indicators/'+ ticker + '.png' print(filename) return render_template('technical_indicators.html', technical_indicator_image = filename)
def bollinger_bands(key, symbol): from alpha_vantage.techindicators import TechIndicators import matplotlib.pyplot as plt ti = TechIndicators(key=key, output_format="pandas") data, meta_data = ti.get_bbands(symbol=symbol, interval="60min", time_period=60) data.plot() plt.title("BBbands indicator for MSFT stock (60 min)") plt.show()
def bands(self): try: ti = TechIndicators(key='MY_API_KEY', output_format='pandas') self.BBdata, meta_data = ti.get_bbands(symbol=self.entry.get(), interval='60min', time_period=60) self.table_head = 'BBbands indicator for {} stock (60 min)'.format( self.entry.get()) self.more_info.configure(state='normal') self.BBdata.plot() plt.title(self.table_head) self.display_content = self.BBdata plt.show() except: messagebox.showwarning("ERROR", "Información no disponible")
def filterPriceThree(self): ti = TechIndicators(key='XP9KDY0X1E13B4HN',output_format='pandas') self.ctrtwo = 0 for i in range(0, len(self.symbols)-(self.ctrtwo),1): if i > len(self.symbols): break try: print(self.symbols[i]) data, meta_data = ti.get_bbands(symbol= self.symbols[i], interval='60min',time_period= 5) except ValueError: self.symbols.pop(i) self.price.pop(i) self.ctrtwo += 1 print(self.symbols)
def pull(self): # Load Indicator ti = TechIndicators(key='XP9KDY0X1E13B4HN',output_format='pandas') # Pulls Bollinger Bands - symbol = current symbol, interval = Time between data points, time_period = number of data points data, meta_data = ti.get_bbands(symbol= self.stocks[self.temp], interval='daily',time_period= 60) # Not used atm ################# self.middle.append(data['Real Middle Band'].tolist()) ################## # Appends data points of current stock to self.upper.append(data['Real Upper Band'].tolist()) self.lower.append(data['Real Lower Band'].tolist())
def bands(): global table_head, display_content try: ti = TechIndicators(key='MY_API_KEY', output_format='pandas') print(ti) BBdata, meta_data = ti.get_bbands(symbol=entry.get(), interval='60min', time_period=60) print(type(BBdata)) table_head = 'BBbands indicator for {} stock (60 min)'.format(entry.get()) more_info.configure(state='normal') BBdata.plot() plt.title(table_head) plt.grid() display_content = BBdata plt.show() except Exception as e: print(str(e)) messagebox.showwarning("ERROR","Información no disponible.")
def bbands(update, context): ti = TechIndicators(key=keys, output_format='pandas') word = str(umt) word_refined = word.replace('/indicator ', '') data_ti, meta_data_ti = ti.get_bbands(symbol=str(word_refined), interval='60min', time_period=60) # pylint: disable=W0632, W0612 data_refined = pandas.DataFrame(data_ti) query = update.callback_query query.answer() data_refined.plot() plt.title('Bollinger Bands indicator for ' + word_refined + ' stock (60min)') plt.savefig('indicator.png') context.bot.send_photo(chat_id=update.effective_chat.id, photo=open('indicator.png', 'rb')) plt.close()
def bbands(symbol, interval): # Parameters: stock symbol and time interval # Calculates three Bollinger Bands for the given stock # Returns the lower, upper, middle band, and standard deviation data points ti = TechIndicators(key=api_key, output_format="pandas") data_ti, meta_data_ti = ti.get_bbands(symbol=symbol, interval=interval, time_period=20, series_type="close") bbands = data_ti bbands.reset_index(inplace=True) bbands["date"] = bbands["date"].map(mdates.date2num) lower_band = bbands["Real Lower Band"] middle_band = bbands["Real Middle Band"] upper_band = bbands["Real Upper Band"] sd = middle_band - lower_band return lower_band, middle_band, upper_band, sd
def get_data(symbol): # API KEY: 51N1JMO66W56AYA3 ti = TechIndicators(key='51N1JMO66W56AYA3', output_format='pandas') sma, _ = ti.get_sma(symbol=symbol, interval='daily') wma, _ = ti.get_wma(symbol=symbol, interval='daily') ema, _ = ti.get_ema(symbol=symbol, interval='daily') macd, _ = ti.get_macd(symbol=symbol, interval='daily') stoch, _ = ti.get_stoch(symbol=symbol, interval='daily') # Alpha Vantage Times out for more than 5 request time.sleep(65) rsi, _ = ti.get_rsi(symbol=symbol, interval='daily') adx, _ = ti.get_adx(symbol=symbol, interval='daily') cci, _ = ti.get_cci(symbol=symbol, interval='daily') aroon, _ = ti.get_aroon(symbol=symbol, interval='daily') bbands, _ = ti.get_bbands(symbol=symbol, interval='daily') time.sleep(65) ad, _ = ti.get_ad(symbol=symbol, interval='daily') obv, _ = ti.get_obv(symbol=symbol, interval='daily') mom, _ = ti.get_mom(symbol=symbol, interval='daily') willr, _ = ti.get_willr(symbol=symbol, interval='daily') time.sleep(65) tech_ind = pd.concat([ sma, ema, macd, rsi, adx, cci, aroon, bbands, ad, obv, wma, mom, willr, stoch ], axis=1) ts = TimeSeries(key='51N1JMO66W56AYA3', output_format='pandas') close2 = ts.get_daily(symbol=symbol, outputsize='full') close = ts.get_daily(symbol=symbol, outputsize='full')[0]['4. close'] direction = (close > close.shift()).astype(int) target = direction.shift(-1).fillna(0).astype(int) target.name = 'target' data = pd.concat([tech_ind, close, target], axis=1) return data
def check_bb(self): # get bollinger band data ti = TechIndicators(key='YOUR_API_KEY', output_format='pandas') bbdata, meta_data = ti.get_bbands(symbol='MSFT', interval='60min', time_period=60) bbdata.reset_index(inplace=True) bbdata['date'] = pd.to_datetime(bbdata['date'], utc=True) bbdata = bbdata.resample('D', on='date').mean().sort_values(by='date', ascending=False) bb2days_middle = bbdata.iloc[2, 0] bb2days_upper = bbdata.iloc[2, 1] bb2days_lower = bbdata.iloc[2, 2] df = pd.read_csv(self.csv_dir) df = df.sort_values(by='Datetime', ascending=False) df['Datetime'] = pd.to_datetime(df['Datetime'], utc=True) df_day = df.resample('D', on='Datetime').mean().sort_values( by='Datetime', ascending=False).head() # get price day from 2 days and 1 day ago price2days = df_day.iloc[2, 3] price1day = df_day.iloc[1, 3] currentprice = df_day.iloc[0, 3] # if price2days > bb2days_upper # if price2days > price1day AND price1day > current, SELL # if price2days < price1day AND price1day < current, BUY if price2days > bb2days_upper or price2days < bb2days_lower or price2days == bb2days_middle: if price2days > price1day and price1day > currentprice: self.bb_condition_sell = True if price2days < price1day and price1day < currentprice: self.bb_condition_buy = True
def technicalIndicators(API_key,ticker): from alpha_vantage.techindicators import TechIndicators import matplotlib.pyplot as plt import mplfinance as mpf ti=TechIndicators(key=API_key, output_format='pandas') option=input('1. SMA\n2. EMA\n3. VWAP\n4. MACD\n5. STOCH\n6. RSI\n7. ADX\n8. CCI\n9. AROON\n10. BBANDS\n11. AD\n12. OBV\n').lower() if option=='sma' or option=='1': interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n")) intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly'] timeperiod=int(input('Enter Time Period\n')) ser=int(input('Enter the series:\n\t1. close\n\t2. open\n\t3. low\n\t4. high\n')) series=['','close','open','low','high'] data=ti.get_sma(symbol=ticker, interval=intervalList[interval], time_period=timeperiod, series_type=series[ser])[0] data.columns = ['SMA'] data.index.name ="Date" mpf.plot(data, type='candle', title=f'SMA for the {ticker} stock', mav=(20), volume=True, tight_layout=True, style='yahoo') mpf.plot(data,type='line', volume=True) return data elif option=='ema' or option=='2': interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n")) intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly'] timeperiod=int(input('Enter Time Period\n')) ser=int(input('Enter the series:\n\t1. close\n\t2. open\n\t3. low\n\t4. high\n')) series=['','close','open','low','high'] data=ti.get_ema(symbol=ticker, interval=intervalList[interval], time_period=timeperiod, series_type=series[ser])[0] data.plot() plt.title(f'EMA for the {ticker} stock') plt.tight_layout() plt.grid() plt.show() return data elif option=='vwap' or option=='3': interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n")) intervalList=['','1min','5min','15min','30min','60min'] data=ti.get_vwap(symbol=ticker, interval=intervalList[interval])[0] data.plot() plt.title(f'VWAP for the {ticker} stock') plt.tight_layout() plt.grid() plt.show() return data elif option=='macd' or option=='4': interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n")) intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly'] ser=int(input('Enter the series:\n\t1. close\n\t2. open\n\t3. low\n\t4. high\n')) series=['','close','open','low','high'] data=ti.get_macd(symbol=ticker, interval=intervalList[interval], series_type=series[ser])[0] data.plot() plt.title(f'MACD for the {ticker} stock') plt.tight_layout() plt.grid() plt.show() return data elif option=='stoch' or option=='5': interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n")) intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly'] data=ti.get_stoch(symbol=ticker, interval=intervalList[interval])[0] data.plot() plt.title(f'STOCH for the {ticker} stock') plt.tight_layout() plt.grid() plt.show() return data elif option=='rsi' or option=='6': interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n")) intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly'] timeperiod=int(input('Enter Time Period\n')) ser=int(input('Enter the series:\n\t1. close\n\t2. open\n\t3. low\n\t4. high\n')) series=['','close','open','low','high'] data=ti.get_rsi(symbol=ticker, interval=intervalList[interval], time_period=timeperiod, series_type=series[ser])[0] data.plot() plt.title(f'RSI for the {ticker} stock') plt.tight_layout() plt.grid() plt.show() return data elif option=='adx' or option=='7': interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n")) intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly'] timeperiod=int(input('Enter Time Period\n')) data=ti.get_adx(symbol=ticker, interval=intervalList[interval], time_period=timeperiod)[0] data.plot() plt.title(f'ADX for the {ticker} stock') plt.tight_layout() plt.grid() plt.show() return data elif option=='cci' or option=='8': interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n")) intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly'] timeperiod=int(input('Enter Time Period\n')) data=ti.get_cci(symbol=ticker, interval=intervalList[interval], time_period=timeperiod)[0] data.plot() plt.title(f'CCI for the {ticker} stock') plt.tight_layout() plt.grid() plt.show() return data elif option=='aroon' or option=='9': interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n")) intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly'] timeperiod=int(input('Enter Time Period')) data=ti.get_aroon(symbol=ticker, interval=intervalList[interval], time_period=timeperiod)[0] data.plot() plt.title(f'AROON for the {ticker} stock') plt.tight_layout() plt.grid() plt.show() return data elif option=='bbands' or option=='10': interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n")) intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly'] timeperiod=int(input('Enter Time Period\n')) ser=int(input('Enter the series:\n\t1. close\n\t2. open\n\t3. low\n\t4. high\n')) series=['','close','open','low','high'] data=ti.get_bbands(symbol=ticker, interval=intervalList[interval], time_period=timeperiod, series_type=series[ser])[0] data.plot() plt.title(f'BBANDS for the {ticker} stock') plt.tight_layout() plt.grid() plt.show() return data elif option=='ad' or option=='11': interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n")) intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly'] data=ti.get_ad(symbol=ticker, interval=intervalList[interval])[0] data.plot() plt.title(f'AD for the {ticker} stock') plt.tight_layout() plt.grid() plt.show() return data elif option=='obv' or option=='12': interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n")) intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly'] data=ti.get_obv(symbol=ticker, interval=intervalList[interval])[0] data.plot() plt.title(f'OBV for the {ticker} stock') plt.tight_layout() plt.grid() plt.show() return data else: print("CANNOT RECOGNIZE")
def stockIndicators(self): ti = TechIndicators(key=self.apiKey, output_format='pandas') if (self.stockIndi == "sma"): ts = TimeSeries(key=self.apiKey, output_format='pandas') data, meta_data = ts.get_monthly(symbol=self.stockName) dataIndi, meta_dataIndi = ti.get_sma(symbol=self.stockName, time_period=30) elif (self.stockIndi == "ema"): ts = TimeSeries(key=self.apiKey, output_format='pandas') data, meta_data = ts.get_monthly(symbol=self.stockName) dataIndi, meta_dataIndi = ti.get_ema(symbol=self.stockName, time_period=30) elif (self.stockIndi == "vwap"): ts = TimeSeries(key=self.apiKey, output_format='pandas') data, meta_data = ts.get_monthly(symbol=self.stockName) dataIndi, meta_dataIndi = ti.get_vwap(symbol=self.stockName, time_period=30) elif (self.stockIndi == "macd"): ts = TimeSeries(key=self.apiKey, output_format='pandas') data, meta_data = ts.get_monthly(symbol=self.stockName) dataIndi, meta_dataIndi = ti.get_macd(symbol=self.stockName, time_period=30) elif (self.stockIndi == "obv"): ts = TimeSeries(key=self.apiKey, output_format='pandas') data, meta_data = ts.get_monthly(symbol=self.stockName) dataIndi, meta_dataIndi = ti.get_obv(symbol=self.stockName, time_period=30) elif (self.stockIndi == "ad"): ts = TimeSeries(key=self.apiKey, output_format='pandas') data, meta_data = ts.get_monthly(symbol=self.stockName) dataIndi, meta_dataIndi = ti.get_ad(symbol=self.stockName, time_period=30) elif (self.stockIndi == "bbands"): ts = TimeSeries(key=self.apiKey, output_format='pandas') data, meta_data = ts.get_monthly(symbol=self.stockName) dataIndi, meta_dataIndi = ti.get_bbands(symbol=self.stockName, time_period=30) elif (self.stockIndi == "aroon"): ts = TimeSeries(key=self.apiKey, output_format='pandas') data, meta_data = ts.get_monthly(symbol=self.stockName) dataIndi, meta_dataIndi = ti.get_aroon(symbol=self.stockName, time_period=30) elif (self.stockIndi == "cci"): ts = TimeSeries(key=self.apiKey, output_format='pandas') data, meta_data = ts.get_monthly(symbol=self.stockName) dataIndi, meta_dataIndi = ti.get_cci(symbol=self.stockName, time_period=30) elif (self.stockIndi == "adx"): ts = TimeSeries(key=self.apiKey, output_format='pandas') data, meta_data = ts.get_monthly(symbol=self.stockName) dataIndi, meta_dataIndi = ti.get_adx(symbol=self.stockName, time_period=30) elif (self.stockIndi == "rsi"): ts = TimeSeries(key=self.apiKey, output_format='pandas') data, meta_data = ts.get_monthly(symbol=self.stockName) dataIndi, meta_dataIndi = ti.get_rsi(symbol=self.stockName, time_period=30) elif (self.stockIndi == "stoch"): ts = TimeSeries(key=self.apiKey, output_format='pandas') data, meta_data = ts.get_monthly(symbol=self.stockName) dataIndi, meta_dataIndi = ti.get_stoch(symbol=self.stockName, time_period=30) return data, dataIndi
plt.show() # Plot Volume Data data1['5. volume'].plot() plt.title('Intraday Time Series for %s stock at (%s) intervals' % (ticker, interval)) plt.show() # ------------------------------ # Part Two: Technical Indicators # ------------------------------ ti = TechIndicators(key='API_KEY', output_format='pandas') interval = '60min' data, metadata = ti.get_bbands(symbol=ticker, interval=interval, time_period=60) data.plot() plt.title('BBands indicator for %s stock, at %s interval' % (ticker, interval)) plt.show() # ------------------------------ # Part Three: Sector Performance # ------------------------------ sp = SectorPerformances(key='API_KEY', output_format='pandas') data, metadata = sp.get_sector() data['Rank A: Real-Time Performance'].plot(kind='bar') plt.title('Real Time Performance (%) per Sector') plt.tight_layout() plt.grid()
def get_daily_history(token_1, symbol, amount_of_entries=1000): ts_1 = TimeSeries(key=token_1, output_format='pandas') ti_1 = TechIndicators(key=token_1, output_format='pandas') print('get_daily_history') interval = 'daily' series_type = 'open' # Fetch dataset from api # OHLC series #1 time_series, meta_time_series = ts_1.get_daily(symbol=symbol, outputsize='full') # Bollinger Bands #2 bbands, meta = ti_1.get_bbands(symbol=symbol, interval=interval, time_period=60, series_type=series_type) bbands = bbands.sort_index(ascending=False) # SMA10 or MA10 #3 sma_10, meta = ti_1.get_sma(symbol=symbol, interval=interval, time_period=10, series_type=series_type) sma_10 = sma_10.sort_index(ascending=False) # SMA5 or MA5 #4 sma_5, meta = ti_1.get_sma(symbol=symbol, interval=interval, time_period=5, series_type=series_type) sma_5 = sma_5.sort_index(ascending=False) # ROC #5 roc_20, meta = ti_1.get_roc(symbol=symbol, interval=interval, time_period=20, series_type=series_type) roc_20 = roc_20.sort_index(ascending=False) # Wait 70 seconds print('waiting 70 seconds'); sleep(70) # MACD #1 macd, meta = ti_1.get_macd(symbol=symbol, interval=interval, series_type=series_type) macd = macd.sort_index(ascending=False) # CCI #2 cci_20, meta = ti_1.get_cci(symbol=symbol, interval=interval, time_period=20) cci_20 = cci_20.sort_index(ascending=False) # ATR #3 atr_20, meta = ti_1.get_atr(symbol=symbol, interval=interval, time_period=20) atr_20 = atr_20.sort_index(ascending=False) # EMA20 #4 ema_20, meta = ti_1.get_ema(symbol=symbol, interval=interval, time_period=20, series_type=series_type) ema_20 = ema_20.sort_index(ascending=False) # MTM6 #5 mtm_6, meta = ti_1.get_mom(symbol=symbol, interval=interval, time_period=180, series_type=series_type) mtm_6 = mtm_6.sort_index(ascending=False) # Wait 70 seconds print('waiting 70 seconds'); sleep(70) # MTM12 #1 mtm_12, meta = ti_1.get_mom(symbol=symbol, interval=interval, time_period=360, series_type=series_type) mtm_12 = mtm_12.sort_index(ascending=False) # Get last n data points in the dataset and set your respective column name d1 = time_series[:amount_of_entries]; d1.columns = ['open', 'high', 'low', 'close', 'volume'] d2 = sma_10[:amount_of_entries] d2.columns = ['sma10'] d3 = sma_5[:amount_of_entries] d3.columns = ['sma5'] d4 = pd.DataFrame(bbands['Real Middle Band'][:amount_of_entries]) d4.columns = ['bbands'] d5 = roc_20[:amount_of_entries] d5.columns = ['roc'] d6 = pd.DataFrame(macd['MACD'][:amount_of_entries]) d6.columns = ['macd'] d7 = cci_20[:amount_of_entries] d7.columns = ['cci'] d8 = atr_20[:amount_of_entries] d8.columns = ['atr'] d9 = ema_20[:amount_of_entries] d9.columns = ['ema20'] d10 = mtm_6[:amount_of_entries] d10.columns = ['mtm6'] d11 = mtm_12[:amount_of_entries] d11.columns = ['mtm12'] # Merge elements merged = d1.merge(d2, left_index=True, right_index=True) merged = merged.merge(d3, left_index=True, right_index=True) merged = merged.merge(d4, left_index=True, right_index=True) merged = merged.merge(d5, left_index=True, right_index=True) merged = merged.merge(d6, left_index=True, right_index=True) merged = merged.merge(d7, left_index=True, right_index=True) merged = merged.merge(d8, left_index=True, right_index=True) merged = merged.merge(d9, left_index=True, right_index=True) merged = merged.merge(d10, left_index=True, right_index=True) merged = merged.merge(d11, left_index=True, right_index=True) sep = os.path.sep filename = 'datasets'+sep+'history_'+symbol+'.csv' merged.to_csv(filename, index=True) return merged, meta_time_series
def main_job(): global data_EMA_10, data_EMA_20, data_MACD, data_BBands, data_Price API_key = '5LDF8BV8UHC3F4Y7' TI = TechIndicators(key=API_key, output_format='json') TS = TimeSeries(key=API_key, output_format='json') Stop_1 = True while Stop_1: try: symbol = 'USDCHF' interval = '5min' slowperiod = '26' signalperiod = '9' fastperiod = '12' series_type = 'close' time_period = '20' outputsize = "compact" data_Price, meta_data_Price = TS.get_intraday( symbol=symbol, interval=interval, outputsize=outputsize) data_BBands, meta_data_BBands = TI.get_bbands( symbol=symbol, interval=interval, time_period=time_period, series_type=series_type) time_period = '10' data_EMA_10, meta_data_EMA_50 = TI.get_ema(symbol=symbol, interval=interval, time_period=time_period, series_type=series_type) time_period = '20' data_EMA_20, meta_data_EMA_200 = TI.get_ema( symbol=symbol, interval=interval, time_period=time_period, series_type=series_type) data_MACD, meta_data_MACD = TI.get_macd(symbol=symbol, interval=interval, series_type=series_type, fastperiod=fastperiod, slowperiod=slowperiod, signalperiod=signalperiod) Stop_1 = False except (UnboundLocalError, ValueError, MaxRetryError, ConnectionError, SSLError) as e: print(e) time.sleep(60) pass # print(data_EMA_10) # print(data_EMA_20) # Retrieve EMA 10 and EMA 20 data """EMA 10""" EMA_10 = list(data_EMA_10.values()) """Current ema 10""" level = EMA_10[0].values() current_ema_10 = (float([x for x in level][0])) """Previous ema 10""" level = EMA_10[1].values() previous_ema_10 = (float([x for x in level][0])) """EMA 20""" EMA_20 = list(data_EMA_20.values()) """Current ema 20""" level = EMA_20[0].values() current_ema_20 = (float([x for x in level][0])) """Previous ema 20""" level = EMA_20[1].values() previous_ema_20 = (float([x for x in level][0])) # Check for crossover between EMA 10 and EMA 20 current_diff = current_ema_10 - current_ema_20 prev_diff = previous_ema_10 - previous_ema_20 file_name = 'Crossing_Flags_EMA.json' with open(file_name) as f_obj: data = f_obj.read() retrieve = json.loads(data) Prev_Cross_Up = retrieve['Cross_Up'] Prev_Cross_Down = retrieve['Cross_Down'] Crossing_Flag = {} if current_diff >= 0 > prev_diff: Crossing_Flag['Cross_Up'] = Prev_Cross_Up Crossing_Flag['Cross_Down'] = True elif current_diff <= 0 < prev_diff: Crossing_Flag['Cross_Up'] = True Crossing_Flag['Cross_Down'] = Prev_Cross_Down else: Crossing_Flag['Cross_Up'] = Prev_Cross_Up Crossing_Flag['Cross_Down'] = Prev_Cross_Down # Update the Crossing flag folder file_name = "Crossing_Flags_EMA.json" with open(file_name, "w") as f_obj: json.dump(Crossing_Flag, f_obj) # Retrieve MACD data """MACD""" MACD = list(data_MACD.values()) current_Hist = float(MACD[0]['MACD_Hist']) prev_Hist = float(MACD[1]['MACD_Hist']) file_name = 'Crossing_Flags_MACD.json' with open(file_name) as f_obj: data = f_obj.read() retrieve = json.loads(data) Prev_Cross_Up = retrieve['Cross_Up'] Prev_Cross_Down = retrieve['Cross_Down'] Crossing_Flag = {} if "-" not in str(prev_Hist) and "-" in str(current_Hist): Crossing_Flag['Cross_Up'] = Prev_Cross_Up Crossing_Flag['Cross_Down'] = True elif "-" in str(prev_Hist) and "-" not in str(current_Hist): Crossing_Flag['Cross_Up'] = True Crossing_Flag['Cross_Down'] = Prev_Cross_Down else: Crossing_Flag['Cross_Up'] = Prev_Cross_Up Crossing_Flag['Cross_Down'] = Prev_Cross_Down file_name = "Crossing_Flags_MACD.json" with open(file_name, "w") as f_obj: json.dump(Crossing_Flag, f_obj) # Retrieve crossing data for EMA and MACD file_name = 'Crossing_Flags_MACD.json' with open(file_name) as f_obj: data = f_obj.read() retrieve = json.loads(data) MACD_Up = retrieve['Cross_Up'] MACD_Down = retrieve['Cross_Down'] file_name = 'Crossing_Flags_EMA.json' with open(file_name) as f_obj: data = f_obj.read() retrieve = json.loads(data) EMA_Up = retrieve['Cross_Up'] EMA_Down = retrieve['Cross_Down'] # Retrieve price and bollinger band data BBands = list(data_BBands.values()) middle_band = float(BBands[0]['Real Middle Band']) Price = list(data_Price.values()) Price = float(Price[0]['4. close']) Trigger_Flags = {} if MACD_Up and EMA_Up: if Price < middle_band: Buy_flag = True Sell_flag = False else: Buy_flag = False Sell_flag = False elif MACD_Down and EMA_Down: if Price > middle_band: Buy_flag = False Sell_flag = True else: Buy_flag = False Sell_flag = False else: Buy_flag = False Sell_flag = False Trigger_Flags["Buy_flag"] = Buy_flag Trigger_Flags["Sell_flag"] = Sell_flag file_name = "Trigger_Flags.json" with open(file_name, "w") as f_obj: json.dump(Trigger_Flags, f_obj)
from click._compat import raw_input from alpha_vantage.timeseries import TimeSeries import pandas as pd key = 'PH2SVH5EIR56RTXD' ti = TechIndicators(key, output_format='pandas') ts = TimeSeries(key, output_format='pandas') AAPL_MACD, meta_data = ti.get_macd(symbol='AAPL', interval='daily', series_type="close") AAPL_RSI, meta_data = ti.get_rsi(symbol='AAPL', interval='daily', series_type="close") AAPL_BBANDS, meta_data = ti.get_bbands(symbol="AAPL", interval='daily', series_type="close") AAPL_PRICE, meta_data = ts.get_daily(symbol="AAPL", outputsize='full') AAPL = AAPL_MACD.join(AAPL_RSI["RSI"]) AAPL = AAPL.join(AAPL_BBANDS["Real Lower Band"]) AAPL = AAPL.join(AAPL_BBANDS['Real Middle Band']) AAPL = AAPL.join(AAPL_BBANDS['Real Upper Band']) AAPL = AAPL.join(AAPL_PRICE['4. close']) AAPL.to_csv('C:/Users/akeats97/Desktop/AAPL.csv') ''' #print(AAPL_MACD)
data, meta_data = ts.get_intraday(symbol=stock,interval=t_period) #print data.shape #print data.columns.values # datetime have differrent format for idx, el in enumerate(data.index._data): data.index._data[idx] = el[:-3] data["trend"] = data["4. close"].subtract(data["1. open"], fill_value=0) del data["4. close"] del data["1. open"] print data.shape ti = TechIndicators(key=apikey, output_format='pandas') #1 bbands, meta_data_bbands = ti.get_bbands(symbol=stock, interval=t_period, series_type=series_type) print bbands.shape #2 ema, meta_data_ema = ti.get_ema(symbol=stock, interval=t_period, series_type= series_type) print ema.shape #3 wma, meta_data_wma = ti.get_wma(symbol=stock, interval=t_period, series_type= series_type) print wma.shape #4 sma, meta_data_sma = ti.get_sma(symbol=stock, interval=t_period, series_type= series_type) print sma.shape #5 rsi, meta_data_rsi = ti.get_rsi(symbol=stock, interval=t_period, series_type= series_type) print rsi.shape #6 macd, meta_data_macd = ti.get_macd(symbol=stock,interval=t_period, series_type= series_type)
def bbands(self): c = TechIndicators(key=self.api_key, output_format='pandas') data, meta_data = c.get_bbands(symbol=self.stock_name) return data
) ti = TechIndicators(key, output_format='pandas') if tech_indi == 'SMA': state = ti.get_sma(symbol, interval=interval, time_period=time, series_type='close')[0] elif tech_indi == 'EMA': state = ti.get_ema(symbol, interval=interval, time_period=time, series_type='close')[0] elif tech_indi == 'VWAP': state = ti.get_vwap(symbol, interval=interval)[0] elif tech_indi == 'MACD': state = ti.get_macd(symbol, interval=interval, series_type='close')[0] elif tech_indi == 'Stochastic Oscillator': state = ti.get_stoch(symbol, interval=interval)[0] elif tech_indi == 'RSI': state = ti.get_rsi(symbol, interval=interval, time_period=time, series_type='close')[0] elif tech_indi == 'Bollinger bands': state = ti.get_bbands(symbol, interval=interval, time_period=time, series_type='close')[0] else: print('Wrong Entry') print(state)
def data_to_csv(ticker, dire): # Your key here - keep it - not an issue, free key = '6LGG0QGAGBROB2M6' # make the directory if it doesn't exist if os.path.isdir(dire) == False: os.mkdir(ticker) os.mkdir(dire) ts = TimeSeries(key=key, output_format='pandas') ti = TechIndicators(key=key, output_format='pandas') ### PRICE ############################################################### intra, meta = ts.get_intraday(symbol=ticker, interval='1min', outputsize='full') intra.to_csv(dire + ticker + "_prices.csv") ### SMA ################################################################# sma8, meta = ti.get_sma(symbol=ticker, interval='1min', time_period=8) sma8.to_csv(dire + ticker + "_sma8.csv") ### EMA ################################################################# ema8, meta = ti.get_ema(symbol=ticker, interval='1min', time_period=8) ema8.to_csv(dire + ticker + "_ema8.csv") ### VWAP ################################################################ vwap, meta = ti.get_vwap(symbol=ticker, interval='1min') vwap.to_csv(dire + ticker + "_vwap.csv") ### MACD ################################################################ macd, meta = ti.get_macd(symbol=ticker, interval='1min') macd.to_csv(dire + ticker + "_macd.csv") # they limit user to 5 calls per minute and 500 per day for free access # print("waiting so we don't overload API (60 seconds...)") time.sleep(60) ### STOCH ############################################################### stoch, meta = ti.get_stoch(symbol=ticker, interval='1min') stoch.to_csv(dire + ticker + "_stoch.csv") ### RSI ################################################################# rsi, meta = ti.get_rsi(symbol=ticker, interval='1min', time_period=60) rsi.to_csv(dire + ticker + "_rsi.csv") ### ADX ################################################################# adx, meta = ti.get_adx(symbol=ticker, interval='1min', time_period=60) adx.to_csv(dire + ticker + "_adx.csv") ### CCI ################################################################# cci, meta = ti.get_cci(symbol=ticker, interval='1min', time_period=60) cci.to_csv(dire + ticker + "_cci.csv") # TODO: These are tricky, several lines, parse differently, separate indices really ### AROON ############################################################### aroon, meta = ti.get_aroon(symbol=ticker, interval='1min', time_period=60) aroon.to_csv(dire + ticker + "_aroon.csv") # they limit user to 5 calls per minute and 500 per day for free access # print("waiting so we don't overload API (60 seconds...)") time.sleep(60) ### BBANDS ############################################################### bbands, meta = ti.get_bbands(symbol=ticker, interval='1min', time_period=60) bbands.to_csv(dire + ticker + "_bbands.csv") '''
import os from alpha_vantage.timeseries import TimeSeries, TimeSeriesDaily from alpha_vantage.techindicators import TechIndicators key = os.environ.get('ALPHAVANTAGE_KEY') print(key) ts = TimeSeries(key=key) import matplotlib.pyplot as plt symbol = 'MSFT' symbol = 'NSE:RELIANCE' ti = TechIndicators(key=key, output_format='pandas') data, meta_data = ti.get_bbands(symbol=symbol, interval='60min', time_period=60) data.plot() plt.title('BBbands indicator for MSFT stock (60 min)') plt.show() print(meta_data)
def get_technical(symbol, is_save=False): """ Esta función es para descargar todos los indicadores técnicos. Si usamos una API_KEY gratuita de ALPHA VANTAGE tenemos que descomentar los time.sleep() de la función para que no de un problema de peticiones; en el caso de una API_KEY premium no haría falta descomentarlo. Parámetros: ---------- symbol str: Nombre de la acción en bolsa. is_save bool: Booleano para decidir si guardar o no los datos descargados. Por defecto False no guarda los datos descargados """ try: # Comprueba si ya existe o no el archivo y en el caso de que # si exista guarda solo los días que no estén descargados if os.path.isfile(f"{c.PATH_SAVE_TECH}{symbol}.csv"): df = pd.read_csv(f"{c.PATH_SAVE_TECH}{symbol}.csv", names=c.COLUMNS) df = df[df['symbol'] == symbol] df['date'] = pd.to_datetime(df['date']) ld = df['date'].tail(1) last = datetime(ld.dt.year, ld.dt.month, ld.dt.day) else: last = None techindc = list() # Descarga los datos de indicadores técnicos. ti = TechIndicators(key=c.ALPHA_VAN_KEY, output_format='pandas') init = time.time() macd = ti.get_macd(symbol, interval='daily')[0] techindc.append(macd) stoch = ti.get_stoch(symbol, interval='daily')[0] techindc.append(stoch) ad = ti.get_ad(symbol, interval='daily')[0] techindc.append(ad) obv = ti.get_obv(symbol, interval='daily')[0] techindc.append(obv) # time.sleep(60) sma = ti.get_sma(symbol, interval='daily', time_period=50)[0] sma.columns = [f"{c}50" for c in sma.columns] techindc.append(sma) bbands = ti.get_bbands(symbol, interval='daily', time_period=28)[0] bbands.columns = [f"{c}28" for c in bbands.columns] techindc.append(bbands) for tp in c.TIME_PERIOD: rsi = ti.get_rsi(symbol, interval='daily', time_period=tp)[0] rsi.columns = [f"{c}{tp}" for c in rsi.columns] techindc.append(rsi) adx = ti.get_adx(symbol, interval='daily', time_period=tp)[0] adx.columns = [f"{c}{tp}" for c in adx.columns] techindc.append(adx) # time.sleep(60) cci = ti.get_cci(symbol, interval='daily', time_period=tp)[0] cci.columns = [f"{c}{tp}" for c in cci.columns] techindc.append(cci) aroon = ti.get_aroon(symbol, interval='daily', time_period=tp)[0] aroon.columns = [f"{c}{tp}" for c in aroon.columns] techindc.append(aroon) df_techindc = pd.concat(techindc, axis=1, join='inner') df_techindc.reset_index(inplace=True) df_techindc['symbol'] = symbol if last is not None: df_techindc = df_techindc[df_techindc['date'] > last] # Guardar los datos if is_save: df_techindc[c.COLUMNS_TECH].to_csv( f"{c.PATH_SAVE_TECH}{symbol}.csv", mode='a', index=False, header=False) except: LOGGER.warning(f"Ticker {symbol} ha fallado.")