def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Alpha Vantage sensor.""" from alpha_vantage.timeseries import TimeSeries from alpha_vantage.foreignexchange import ForeignExchange api_key = config.get(CONF_API_KEY) symbols = config.get(CONF_SYMBOLS) timeseries = TimeSeries(key=api_key) dev = [] for symbol in symbols: try: timeseries.get_intraday(symbol[CONF_SYMBOL]) except ValueError: _LOGGER.error( "API Key is not valid or symbol '%s' not known", symbol) dev.append(AlphaVantageSensor(timeseries, symbol)) forex = ForeignExchange(key=api_key) for conversion in config.get(CONF_FOREIGN_EXCHANGE): from_cur = conversion.get(CONF_FROM) to_cur = conversion.get(CONF_TO) try: forex.get_currency_exchange_rate( from_currency=from_cur, to_currency=to_cur) except ValueError as error: _LOGGER.error( "API Key is not valid or currencies '%s'/'%s' not known", from_cur, to_cur) _LOGGER.debug(str(error)) dev.append(AlphaVantageForeignExchange(forex, conversion)) add_devices(dev, True)
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Alpha Vantage sensor.""" from alpha_vantage.timeseries import TimeSeries from alpha_vantage.foreignexchange import ForeignExchange api_key = config.get(CONF_API_KEY) symbols = config.get(CONF_SYMBOLS, []) conversions = config.get(CONF_FOREIGN_EXCHANGE, []) if not symbols and not conversions: msg = 'Warning: No symbols or currencies configured.' hass.components.persistent_notification.create( msg, 'Sensor alpha_vantage') _LOGGER.warning(msg) return timeseries = TimeSeries(key=api_key) dev = [] for symbol in symbols: try: _LOGGER.debug("Configuring timeseries for symbols: %s", symbol[CONF_SYMBOL]) timeseries.get_intraday(symbol[CONF_SYMBOL]) except ValueError: _LOGGER.error( "API Key is not valid or symbol '%s' not known", symbol) dev.append(AlphaVantageSensor(timeseries, symbol)) forex = ForeignExchange(key=api_key) for conversion in conversions: from_cur = conversion.get(CONF_FROM) to_cur = conversion.get(CONF_TO) try: _LOGGER.debug("Configuring forex %s - %s", from_cur, to_cur) forex.get_currency_exchange_rate( from_currency=from_cur, to_currency=to_cur) except ValueError as error: _LOGGER.error( "API Key is not valid or currencies '%s'/'%s' not known", from_cur, to_cur) _LOGGER.debug(str(error)) dev.append(AlphaVantageForeignExchange(forex, conversion)) add_devices(dev, True) _LOGGER.debug("Setup completed")
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Alpha Vantage sensor.""" from alpha_vantage.timeseries import TimeSeries api_key = config.get(CONF_API_KEY) symbols = config.get(CONF_SYMBOLS) timeseries = TimeSeries(key=api_key) dev = [] for symbol in symbols: try: timeseries.get_intraday(symbol) except ValueError: _LOGGER.error( "API Key is not valid or symbol '%s' not known", symbol) return dev.append(AlphaVantageSensor(timeseries, symbol)) add_devices(dev, True)
def get_data(comp_name, start, end): #Load the data api_key = '2ZQ7F65CN9W34EV1' ts = TimeSeries(key=api_key, output_format='pandas') df, meta_data = ts.get_intraday(symbol=comp_name, outputsize='full') #print(df) # if symbol.upper() == 'AXIS': # df = pd.read_csv("E:/learning/various technololgy learned/computer simulation project/edited_csv file/AXIS_BANK.csv") # elif symbol.upper() == 'ICICI': # df = pd.read_csv("E:/learning/various technololgy learned/computer simulation project/edited_csv file/ICICI_BANK.csv") # elif symbol.upper() == 'KOTAK': # df = pd.read_csv("E:/learning/various technololgy learned/computer simulation project/edited_csv file/KOTAK_BANK.csv") # else: # df = pd.DataFrame(columns=['Date', 'Close', 'Open', 'Prev Close', 'High', 'Low']) #get the date range start = pd.to_datetime(start) end = pd.to_datetime(end) print(start) print(pd.to_datetime(df['date'][0])) #set the start and end index rows both to 0 start_row = 0 end_row = 0 #Start the date from the top of the data set and go down to see if the users start date is less than or equal to the date in the dataset. for i in range(0, len(df)): if start <= pd.to_datetime(df['Date'][i]): start_row = i break #Start from the bottom of the dataset and go up to see if the users end date is greater than or equal to the date in the dataset. for j in range(0, len(df)): if end >= pd.to_datetime(df['Date'][len(df) - 1 - j]): end_row = len(df) - 1 - j break #set the index to be the date df = df.set_index(pd.DatetimeIndex(df['Date'].values)) return df.iloc[start_row:end_row + 1, :]
def getGraph(bot, update, args): try: # The args contain the company name stockName = " ".join(args).upper() # Call the constructor of the Alphavantage API wrapper ts = TimeSeries(key=alphaVantage_apiKey, output_format='pandas') # Calls the method to fetch intraday prices # The .NS is to let the API know we want the prices from NSE data, meta_data = ts.get_intraday(stockName + ".NS", interval='1min', outputsize='compact') # Find the documentation of the Alphavantage API at https://github.com/RomelTorres/alpha_vantage data['datetime'] = data.index indianTimeZone = pytz.timezone('Asia/Kolkata') data['datetime'] = pd.to_datetime(data['datetime']).dt.tz_localize( pytz.utc).dt.tz_convert(indianTimeZone) #Plotting the close values data['4. close'].plot() plt.grid() #Setting the Graph title plotTitle = 'Intraday price for {} (1 min)'.format(stockName) plt.title(plotTitle) # Using a Python Util called Temporary file in order to convert the graph into a file object #tmpfile = tempfile.TemporaryFile(suffix=".png") tmpfile = BytesIO() plt.savefig(tmpfile, format="png") tmpfile.seek(0) img = tmpfile update.message.reply_photo(img) plt.close() except Exception as e: # Catches the exception and prints the stack trace logging.exception("message") message = '''You probably used the incorrect format for the command.\nUse /graph <pre>'companyName' </pre> \nFor more info, please check /help''' # If any exception, send the message showing the frequent cause of exception update.message.reply_html(message)
def patternStorage(self, label_magnitude, position_holding_len, wait_len): ts = TimeSeries(key='5891QG9FRTQ9TNS', output_format='pandas') data, meta_data = ts.get_intraday(symbol=self.stock, interval=self.frenquency, outputsize='full') short_ave = data['close'].rolling(12).mean() long_ave = data['close'].rolling(26).mean() diff = short_ave - long_ave dea = diff.rolling(9).mean() macd = diff - dea data['MACD'] = macd data.dropna(axis=0, inplace=True) label = [] bar = 0 x = len(data) - position_holding_len - wait_len pattern = data.loc[:len(data) - position_holding_len - wait_len, ['close', 'MACD']] while bar < x: maxim = max(data['close'][bar + position_holding_len:bar + position_holding_len + wait_len]) currentP = data['close'][bar] highmag = currentP * (1 + label_magnitude) lowmag = currentP * (1 - label_magnitude) minim = min(data['close'][bar + position_holding_len:bar + position_holding_len + wait_len]) if maxim > highmag and minim > currentP: label.append(2) bar += 1 elif maxim > highmag and minim < currentP: label.append(1) bar += 1 elif maxim > currentP and minim < lowmag: label.append(-1) bar += 1 elif maxim < currentP and minim < lowmag: label.append(-2) bar += 1 else: label.append(0) bar += 1 return pattern, label
def get_dataset(symbol, time_window): api_key = os.environ["API_KEY"] print(symbol, time_window) ts = TimeSeries(key=api_key, output_format='pandas') if time_window == 'intraday': data, meta_data = ts.get_intraday(symbol="{symbol}", interval='1min', outputsize='full') elif time_window == 'daily': data, meta_data = ts.get_daily(symbol, outputsize='full') elif time_window == 'daily_adj': data, meta_data = ts.get_daily_adjusted(symbol, outputsize='full') os.makedirs(f"./files/data/{symbol}", exist_ok=True) data['date'] = data.index #data.to_csv(f'./files/data/{symbol}/{symbol}_{time_window}.csv') return data
def fetch_data_for_one(key, symbol, interval, output_format): ts = TimeSeries(key, output_format=output_format) data, metadata = ts.get_intraday('NSE:' + symbol, interval, outputsize='full') data = data.rename( columns={ '1. open': 'Open', '2. high': 'High', '3. low': 'Low', '4. close': 'Close', '5. volume': 'Volume' }) print('data for ' + metadata['2. Symbol']) print(data.head() + '\n') plt.plot(data['Open']) plt.show() return data, metadata
def get_intraday_history(ticker, time_frame): """ get intraday historical prices https://www.alphavantage.co/documentation/ :param ticker: string. "AAPL", "AMZN" ... :param time_frame: string. "1min","15min" :return: pandas dataframe """ api_key = '' # API key from https://www.alphavantage.co ts = TimeSeries(key=api_key, output_format='pandas') data, meta_data = ts.get_intraday(symbol=ticker, interval=time_frame, outputsize='full') return data
def stockchart(): print "inside stockchart" symbol = request.form.get("symbol") print symbol ts = TimeSeries(key='your_key', output_format='pandas') data, meta_data = ts.get_intraday(symbol=symbol, interval='1day', outputsize='full') data['close'].plot() plt.title('1 day performance of {} stock').format(symbol) plt.show() print data print meta_datae symbol = input("Pick a Tech Stock of Your interest:") stockchart(symbol) return "selected Symbol" + symbol
def fetch_stock_data(stocks): """ Fetches stock data (per min) for last 14 days. INPUT: List of stocks OUTPUT: CSV files generated in data folder for all the stocks """ cnt=0 for stock in stocks: time=TimeSeries(key="Enter alphavantage key",output_format='pandas') data=time.get_intraday(symbol=stock,interval='1min',outputsize="full") stock_df=data[0] stock_df.to_csv("../data/Historical_Data/"+stock+".csv") ## API can only fetch data for 5 stocks in a minute cnt+=1 if cnt==4: cnt=0 sleep(60)
def TimeSeries(self, plot=False): ts = TimeSeries(key=self.api_key, output_format='pandas') self.df, meta_data = ts.get_intraday(symbol='MSFT', interval='1min', outputsize='full') print('dataframe created') self.clean_data() self.indicator() self.df = self.df.drop([ '2. high', '3. low', '5. volume', '6. pv total', '7. volume total' ], axis=1) print(self.df) self.df.plot() plt.title('Intraday Time Series (1 min)') plt.grid() plt.show()
def save_dataset(symbol, time_window): with open('av_creds.json', 'r') as creds: credentials = json.load(creds) api_key = credentials['av_api_key'] print(symbol, time_window) ts = TimeSeries(key=api_key, output_format='pandas') if time_window == 'intraday': data, meta_data = ts.get_intraday(symbol=symbol, interval='1min', outputsize='full') elif time_window == 'daily': data, meta_data = ts.get_daily(symbol, outputsize='full') elif time_window == 'daily_adj': data, meta_data = ts.get_daily_adjusted(symbol, outputsize='full') pprint(data.head(10)) data.to_csv(f'./{symbol}_{time_window}.csv')
def save_dataset(symbol, time_window): #credentials = json.load(open('creds.json', 'r')) #api_key = credentials['av_api_key'] api_key = 'ULG711DCFEJJ7I41' print(symbol, time_window) ts = TimeSeries(key=api_key, output_format='pandas') if time_window == 'intraday': data, meta_data = ts.get_intraday(symbol='MSFT', interval='1min', outputsize='full') elif time_window == 'daily': data, meta_data = ts.get_daily(symbol, outputsize='full') elif time_window == 'daily_adj': data, meta_data = ts.get_daily_adjusted(symbol, outputsize='full') pprint(data.head(10)) data.to_csv(f'./{symbol}_{time_window}.csv')
def get_data(ticker, truncate_data=False): ts = TimeSeries() data, metadata = ts.get_intraday(ticker) # The data has the following structure (shown by example): # { # '2020-09-14 19:00:00': { # '1. open': '1511.0500', # '2. high': '1512.3800', # '3. low': '1511.0500', # '4. close': '1512.3800', # '5. volume': '1486', # }, # ... # } if truncate_data: two_keys = list(sorted(data.keys()))[:2] data = {k: data[k] for k in two_keys} return data
def alpha_vantage_timeseries(ticker): ts = TimeSeries(key="4RKAADTMMAZ4U000", output_format='pandas') #retreiving the stock with appropriate tickers data, meta_data = ts.get_intraday(symbol='NASDAQ:' + ticker, interval='5min', outputsize='full') data = data.rename( columns={ "1. open": "open", "2. high": "high", "3. low": "low", "4. close": "close", "5. volume": "volume" }) #testing/manipulating pandas section return data
def candlestick2(stock): ts = TimeSeries(key='QBGZM8IV1P2X2VJQ', output_format='pandas') data, meta_data = ts.get_intraday(symbol=stock, interval='60min', outputsize='compact') df = web.get_data_yahoo('GOOGL') trace = go.Candlestick(x=df.index, open=df.Open, high=df.High, low=df.Low, close=df.Close, increasing=dict(line=dict(color='#17BECF')), decreasing=dict(line=dict(color='#7F7F7F'))) data = [trace] plotly.offline.plot(data, filename='file.html') return None1
def get_data_intraday(symbol, interval, outputsize, savingtoCsv=False): # gets data over a period of a day # loading necessary modules from alpha_vantage.timeseries import TimeSeries # getting the right api key API_KEY, waiting_times = api_key_finder() # setting the reading data ts = TimeSeries(key=API_KEY, output_format='pandas', indexing_type='integer') # getting the final data data, meta_data = ts.get_intraday(symbol=symbol, interval=interval, outputsize=outputsize) # writing data to database and csv write_to_database(data, 'IntraDay', symbol, interval, savingtoCsv) return data, meta_data
def get_alphavantage(self, symbol, start, end, resolution=Resolution.one_day): from alpha_vantage.timeseries import TimeSeries INTERVAL = {} INTERVAL[Resolution.one_min] = '1min' INTERVAL[Resolution.five_min] = '5min' INTERVAL[Resolution.fifteen_min] = '15min' INTERVAL[Resolution.thirty_min] = '30min' INTERVAL[Resolution.one_hour] = '60min' ts = TimeSeries(key=self.alpha_vantage_token, retries=5, output_format='pandas', indexing_type='date') if resolution == Resolution.one_day: data_d, meta_data_d = ts.get_daily_adjusted(symbol=symbol, outputsize='full') data_d.rename(columns={'5. adjusted close': 'close'}, inplace=True) data_d.rename(columns={'1. open': 'open'}, inplace=True) data_d.rename(columns={'2. high': 'high'}, inplace=True) data_d.rename(columns={'3. low': 'low'}, inplace=True) data_d.rename(columns={'6. volume': 'volume'}, inplace=True) data_d.reset_index(inplace=True) data_d.rename(columns={'date': 'index'}, inplace=True) data_d.set_index('index', inplace=True) data_d.index = pd.to_datetime(data_d.index) else: # intervals='1min', '5min', '15min', '30min', '60min' data_d, meta_data_d = ts.get_intraday(symbol=symbol, interval=INTERVAL[resolution], outputsize='full') data_d.rename(columns={'5. volume': 'volume'}, inplace=True) data_d.rename(columns={'1. open': 'open'}, inplace=True) data_d.rename(columns={'2. high': 'high'}, inplace=True) data_d.rename(columns={'3. low': 'low'}, inplace=True) data_d.rename(columns={'4. close': 'close'}, inplace=True) data_d.reset_index(inplace=True) data_d.rename(columns={'date': 'index'}, inplace=True) data_d.set_index('index', inplace=True) data_d.index = pd.to_datetime(data_d.index) output = data_d[['close', 'open', 'high', 'low', 'volume']] output['symbol'] = symbol if output.index[0] < start: output = output[["symbol", "open", "high", "low", "close", "volume"]][start:] if output.index[-1] > end: output = output[["symbol", "open", "high", "low", "close", "volume"]][:end] return output
def doOneSecurity(self, security): logging.basicConfig(filename='example.log', level=logging.DEBUG) logging.basicConfig( format='%(asctime)-15s %(clientip)s %(user)-8s %(message)s') str_price = "" cpt_retry = 10 while cpt_retry > 0: cpt_retry = cpt_retry - 1 logging.info( "One try to pull data ... {} remaining\n".format(cpt_retry)) try: ts = TimeSeries(key=config.mAlphaVantageAPIKey, output_format='pandas') data, meta_data = ts.get_daily(symbol=security, outputsize='compact') str_price = data['4. close'][0] cpt_retry = 0 except: logging.warning( "ts.get_daily did not worked, trying ts.get_intraday\n") try: ts = TimeSeries(key=config.mAlphaVantageAPIKey, output_format='pandas') data, meta_data = ts.get_intraday(symbol=security, outputsize='compact') str_price = data['4. close'][0] cpt_retry = 0 except ValueError as error: logging.error( "Because of the 5 / minute API called limit ?\n") except: logging.error( "ts.get_intraday failed Is it because of the 5 / minute API called limit ?\n" ) finally: # Probably exceeded the API limit of 5 calls per minutes try again, recursively str_price = "0.00" time.sleep(60) return str_price
def getData(symbol, timeSeries, chartType, startDate, endDate): ts = TimeSeries(key=API_KEY, output_format='pandas') if timeSeries == '1': data, meta_data = ts.get_intraday(symbol=symbol, interval='60min', outputsize='full') f = 'H' if timeSeries == '2': data, meta_data = ts.get_daily(symbol=symbol, outputsize='compact') f = 'D' if timeSeries == '3': data, meta_data = ts.get_weekly(symbol=symbol) f = 'W' if timeSeries == '4': data, meta_data = ts.get_monthly(symbol=symbol) f = 'M' data_date_changed = data[endDate:startDate] if chartType == "1": line_chart = pygal.Bar(x_label_rotation=20, width=1000, height=400) line_chart.title = 'Stock Data for {}: {} to {}'.format( symbol, startDate, endDate) labels = data_date_changed.index.to_list() line_chart.x_labels = reversed(labels) line_chart.add("Open", data_date_changed['1. open']) line_chart.add("High", data_date_changed['2. high']) line_chart.add("Low", data_date_changed['3. low']) line_chart.add("Close", data_date_changed['4. close']) line_chart.render_in_browser() if chartType == "2": line_chart = pygal.Line(x_label_rotation=20, spacing=80) line_chart.title = 'Stock Data for {}: {} to {}'.format( symbol, startDate, endDate) labels = data_date_changed.index.to_list() line_chart.x_labels = reversed(labels) line_chart.add("Open", data_date_changed['1. open']) line_chart.add("High", data_date_changed['2. high']) line_chart.add("Low", data_date_changed['3. low']) line_chart.add("Close", data_date_changed['4. close']) line_chart.render_in_browser()
class AlphaVantageManager(object): """description of class""" PandasTimeSeries: TimeSeries column_names: List[str] = ["open", "high", "low", "close", "volume"] min_s: str = "min" def __init__(self, a_key: str, y_ticker: YahooTicker): self.__alphaK: str = a_key self.PandasTimeSeries = TimeSeries(key=open(a_key, 'r').read(), output_format='pandas') self.__ticker = y_ticker def GetIntraDayMinuteSparse(self, a_int: int): s_int = str(a_int) + self.min_s a_df = self.PandasTimeSeries.get_intraday( symbol=self.__ticker.TickerName, interval=s_int, outputsize='full')[0] a_df.columns = self.column_names return a_df
def pull_tickers(self, tickers, freq='15min'): """ freq: '1min','5min','15min','30min','60min' """ ts = TimeSeries(key=self.key, output_format='pandas') try: frames = [] for tick in tickers: self.tracker.wait() df, meta_data = ts.get_intraday(symbol=tick, interval=freq, outputsize='full') df = df.reset_index() df['ticker'] = tick frames.append(df) self.tracker.update(1) except ValueError as e: logger.warning(repr(e)) return pd.concat(frames)
def save_dataset(symbol, time_window, api_key: str = API_KEY): # credentials = json.load(open('creds.json', 'r')) # api_key = credentials['av_api_key'] print(symbol, time_window) ts = TimeSeries(key=api_key, output_format='pandas') if time_window == 'intraday': data, meta_data = ts.get_intraday(symbol='MSFT', interval='1min', outputsize='full') elif time_window == 'daily': data, meta_data = ts.get_daily(symbol, outputsize='full') elif time_window == 'daily_adj': data, meta_data = ts.get_daily_adjusted(symbol, outputsize='full') pprint(data.head(10)) path = f'/media/dorel/DATA/work/stock-trading-ml/data/{symbol}_{time_window}.csv' data.to_csv(path)
def get_price(): print('Enter the stocks ticker') ticker = input() ts = TimeSeries(key=api_key, output_format='pandas') data, meta_data = ts.get_intraday(symbol=ticker, interval='1min', outputsize='compact') close_data = data['4. close'] last_change = close_data[-1] #print(data) print('$', last_change) repeat = input('Would you like to enter another ticker? ').lower() if repeat == 'yes': get_price() else: print('Thanks for using the app ')
def addAlphaTickerData(ticker, interval='5'): try: ts = TimeSeries(key=constants.ALPHAADVANTAGEKEY, output_format='csv') logging.info( "Getting intraday {} data from Alpha Vantage".format(ticker)) data, _ = ts.get_intraday(symbol=ticker, interval=interval + 'min', outputsize='full') logging.info("Generating {}.csv".format(ticker)) with open('out/' + ticker + ".csv", 'w') as write_csvfile: writer = csv.writer(write_csvfile, dialect='excel') for row in data: writer.writerow(row) logging.info("Generation successful!") except KeyboardInterrupt(): pass except Exception as e: logging.error(e)
class TimeSeriesAPI(BaseAPI): """ This TimeSeries API is for demo use only. """ def __init__(self): super(TimeSeriesAPI, self).__init__() self.ts = TimeSeries(key=self.api, output_format=self.output_format) def get_intraday(self, symbol, interval="15min", outputsize="full"): return self.ts.get_intraday(symbol, interval=interval, outputsize=outputsize) def plot(self, **kwargs): symbol = kwargs.get('symbol') data, meta_data = self.get_intraday(symbol) data['4. close'].plot() plt.title('Intraday Times Series for the AAPL stock (15 min)') plt.show()
def get_aa_timesereis(key, symbol, time_val): ts = TimeSeries(key, output_format='pandas', indexing_type='date') if time_val == 'd': data, meta_data = ts.get_daily(symbol=symbol, outputsize='full') else: data, meta_data = ts.get_intraday(symbol=symbol, interval='1min', outputsize='full') data.reset_index(inplace=True) data.rename(columns={ 'date': 'Date', '1. open': 'Open', '2. high': 'High', '3. low': 'Low', '4. close': 'Close', '5. volume': 'Volume' }, inplace=True) return data
def rsi_dataframe(stock=stock): period = 60 ts = TimeSeries(key=api_key, output_format='pandas') data_ts = ts.get_intraday(stock.upper(), interval='1min', outputsize='full') ti = TechIndicators(key=stock.upper(), output_format='pandas') #RSI determines if a stock is overbought or oversold data_ti, meta_data_ti = ti.get_rsi(symbol=stock.upper(), interval='1min', time_period=period, series_type='close') df_ti = data_ti #SMA data_sma, meta_data_sma = ti.get_sma(symbol=stock.upper(), interval='1min', time_period=period, series_type='close') df_sma = data_sma.iloc[1::] # since sma start with one before #ensure indexes are the same df_ti.index = df_sma.index fig, ax1 = plt.subplots() ax1.plot(df_ti, 'b-') ax2 = ax1.twinx() #plots along same x value ax2.plot(df_sma, 'r-') plt.title("SMA & RSI Graph") plt.show() # df = data_ts[0][period::] # # df.index = pd.Index(map(lambda x: str(x)[:-3], df.index)) # df2 = data_ti # total_df = pd.merge(df, df2, on="date") # print(total_df) return
def load_data_history(ticker='SPY', freq='15min', start='2014', end='2016'): """ Loads data from Yahoo. After loading it renames columns to shorter format, which is what Backtest expects. Set `adjust close` to True to correct all fields with with divident info provided by Yahoo via Adj Close field. Defaults are in place for convenience. """ if isinstance(ticker, list): return pd.Panel({ t: load_data_history(ticker=t, start=start, adjust_close=adjust_close) for t in ticker }) ts = TimeSeries(key='8YLDYU6Z9IAZNIS4') if freq == 'daily': data, meta_data = ts.get_daily(ticker, outputsize='full') elif freq == 'weekly': data, meta_data = ts.get_weekly(ticker, outputsize='full') elif freq == 'monthly': data, meta_data = ts.get_monthly(ticker, outputsize='full') else: data, meta_data = ts.get_intraday( ticker, interval=freq, outputsize='full') #supported 1min, 15min, 30min, 60min #r = data['Close'] ohlc_cols = ['Open', 'High', 'Low', 'Close'] #data[ohlc_cols] = data[ohlc_cols].mul(r, axis=0) data = data.rename( columns={ 'Open': 'O', 'High': 'H', 'Low': 'L', 'Close': 'C', 'Adj Close': 'AC', 'Volume': 'V' }) return data
def getIntraDay(ticker: str, interval="1min", full=False): """ Gets intra day data. :param ticker: e.g. TSLA :param interval: 1min, 5min, 15min, 30min, 60min :return: Pandas Dataframe """ ts = TimeSeries(key=api_key, output_format='pandas') data, meta_data = ts.get_intraday(symbol=ticker, interval=interval, outputsize='full') data = data.rename( columns={ "1. open": "Open", "2. high": "High", "3. low": "Low", "4. close": "Close", "5. volume": "Volume" }) return data
def candlestick2(stock): ts = TimeSeries(key='QBGZM8IV1P2X2VJQ', output_format='pandas') data, meta_data = ts.get_intraday(symbol=stock, interval='60min', outputsize='compact') import pandas_datareader as pdr df = web.get_data_yahoo('AAPL') trace = go.Candlestick(x=df.index, open=df.Open, high=df.High, low=df.Low, close=df.Close) data = [trace] layout = go.Layout(title='Candlestick Plot Testing', width=800, height=640) fig = go.Figure(data=data, layout=layout) py.image.save_as(fig, filename='candle_testing.png') return None1
def candlestick1(stock): ts = TimeSeries(key='QBGZM8IV1P2X2VJQ', output_format='pandas') data, meta_data = ts.get_intraday(symbol=stock, interval='60min', outputsize='compact') fig, ax1 = plt.subplots() ax1.plot(data, 'b') ax1.set_xlabel('Time(s)') ax1.set_ylabel(stock.upper(), color='b') plt.title('Stock Value of ' + stock.upper()) for tick in ax1.get_xticklabels(): tick.set_rotation(45) canvas = FigureCanvas(fig) output = io.BytesIO() fig.tight_layout() canvas.print_png(output) response = base64.b64encode(output.getvalue()).decode('ascii') return response
# https://github.com/RomelTorres/alpha_vantage from alpha_vantage.timeseries import TimeSeries from pprint import pprint ts = TimeSeries(key='Y3086XYRBVO5KMFD', output_format='pandas') data, meta_data = ts.get_intraday('AAPL', interval='1min', outputsize='full') pprint(data.head(5))