def updateETH(): conn = sqlite3.connect("data/crypto.db") cur = conn.cursor() cur.execute("select max(Date) from eth") results = cur.fetchone() # print(results[0]) cc = CryptoCurrencies(key=akey, output_format='pandas') data, meta_data = cc.get_digital_currency_daily(symbol='ETH', market='EUR') data['Currency'] = 'ETH' data.reset_index(inplace=True) data.drop(['1a. open (EUR)', '2a. high (EUR)', '3a. low (EUR)','4a. close (EUR)'], axis=1, inplace=True) # print(data.columns.values.tolist()) data.columns = ['Date','Open','High','Low','Close','Volume','MarketCap','Coin'] data['Date']= pd.to_datetime(data['Date']) data.set_index('Date', inplace=True) data['200_MA'] = data['Close'].rolling('200D').mean() data['150_MA'] = data['Close'].rolling('150D').mean() data['50_MA'] = data['Close'].rolling('50D').mean() data['52W_High'] = data['Close'].rolling('365D').max() data['52W_Low'] = data['Close'].rolling('365D').min() data['Volatility']=(data['High']-data['Low'])/data['Open'] data['Pct_Chg'] = (data['Close'] - data['Open'])/data['Open'] data.drop('Coin', axis=1, inplace=True) eth_csv = data eth_csv.reset_index(inplace=True) eth_csv.to_csv('static/updated_csv/eth_current.csv', index=False) # print(data.head()) selected = data.loc[:results[0]] #selected.reset_index(inplace=True) # print(selected.head()) selected.to_sql('eth', conn, if_exists='append', index=False) con.close()
def find_crypto_daily(ctx): """ Finds all data on cryptocurrency of choice and displays data for that day. """ # Check output format if (ctx.obj['GRAPH']): out = 'pandas' else: out = 'json' # Get data from API cc = CryptoCurrencies(key=apiKey, output_format=out) # Get object with the crypto data and another with the call's metadata data, meta_data = cc.get_digital_currency_daily(symbol=crypto_symbol, market=market) # Show data depending on output format # if(ctx.obj['GRAPH']): # data['4b. close (USD)'].plot() # plt.tight_layout() # plt.title('Daily close value for bitcoin (BTC)') # plt.grid() # plt.show() # else: pprint(data)
def getValues(symbol, currency='Stock'): ''' get the full time series from a given stock or cryptocurrency :param symbol: symbol of desired stock or crypto :param currency: 'stock' or 'crypto' :return: (x,y) x is the dates, and y is the stock value ''' if currency == 'Stock': ts = TimeSeries(key=api_key, output_format='pandas') try: data, meta_data = ts.get_weekly(symbol) except KeyError: return None, None x = data.index.values # get index values (dates) y = data.iloc[:, 3].values # get third column which is closing price return x, y elif currency == 'Cryptocurrency': cc = CryptoCurrencies(key=api_key, output_format='pandas') try: data, meta_data = cc.get_digital_currency_weekly(symbol, market='USD') except KeyError: return None, None x = data.index.values # get index values (dates) y = data.iloc[:, 3].values # get third column which is closing price return x, y
def getCurrentPrice(symbol, currency='Stock'): ''' get current price for a given stock or cryptocurrency :param symbol: string of the desired stock or cryptocurrency :param currency: 'stock' or 'crypto' :return: (x,y) x is string with date and time, and y is stock value ''' if currency == 'Stock': ts = TimeSeries(key=api_key, output_format='pandas') try: data, meta_data = ts.get_intraday(symbol, interval='1min', outputsize='compact') except KeyError: return None, None x = data.index.values[-1] # get index values (dates) y = data.iloc[-1, 3] # get third column which is closing price return x, y elif currency == 'Cryptocurrency': cc = CryptoCurrencies(key=api_key, output_format='pandas') try: data, meta_data = cc.get_digital_currency_daily(symbol, market='USD') except KeyError: return None, None x = data.index.values[-1] # get index values (dates) y = data.iloc[-1, 3] # get third column which is closing price return x, y
def save_digital_dataset(symbol, market): cc = CryptoCurrencies(key=api_key, output_format='pandas') data, meta_data = cc.get_digital_currency_daily(symbol, market) data.to_csv(f'./Crypto Data/{symbol}_daily')
def Init_Crypto_Currency_API_Alpha_Vantage(self , API_Key, Crypto_Currency , Market): cc = CryptoCurrencies(key=API_Key,output_format='pandas') self.Data, self.MetaData = cc.get_digital_currency_daily(Crypto_Currency,Market) self.Base = self.data['4a. close (USD)'] self.DataSet = None
def getData(self, params): ticker = params['ticker'] key = '' #insertkeyhere-for.ex-6CGJ8IWIR2UQ361H cc = CryptoCurrencies(key,output_format='pandas') df, meta = cc.get_digital_currency_daily(symbol=ticker,market='USD') #df= pd.read_csv('physical_currency_list.csv') return df
def __init__(self, api_key): self._api_key = get_alpha_vantage_credentials(api_key) self._session = requests.Session() self._timeseries = TimeSeries(key=self._api_key) self._cryptocurrencies = CryptoCurrencies(key=self._api_key) self._foreignexchange = ForeignExchange(key=self._api_key) self._sectorperformance = SectorPerformances(key=self._api_key) self._techindicators = TechIndicators(key=self._api_key)
def step_impl(context): digital_currency = context.vars['digital_currency'] crypto_currencies = CryptoCurrencies(key=context.apy_key) response = crypto_currencies.get_digital_currency_weekly( symbol=digital_currency['currency'], market=digital_currency['market']) context.response = response
def __init__(self, args): self.args = args #self.ts = TimeSeries(key=self.args.api_key, output_format='pandas') self.cc = CryptoCurrencies(key=self.args.api_key, output_format='pandas') self.daily_data, self.meta_data = self.cc.get_digital_currency_daily( symbol='ETC', market='USD') print('reached here')
async def crypto_current_price(ctx, symbol: str, market: str): cc = CryptoCurrencies(key=os.environ['ALPHA_VANTAGE_API_KEY']) data = cc.get_digital_currency_intraday(symbol=symbol, market=market) current_time = max(data[0].keys()) most_recent_entry = data[0][current_time] output_header = "{} ({})".format(symbol, market) output = get_nice_output(output_header, current_time, most_recent_entry) print(output) await bot.say(output)
def get_crypto_data(crypto_symbol, market): cc = CryptoCurrencies(key=apiKey, output_format='json') # Get json object with the crypto data and another with the call's metadata data, meta_data = cc.get_digital_currency_daily(symbol=crypto_symbol, market=market) return data, meta_data
def __init__(self): self.root = Tk() self.root.title("Crypto Graph") self.root.geometry("1070x800") self.root.configure(background="light green") self.used_symbolsC = pickle.load(open("symbolsC", "rb")) self.usedsymbolsM = pickle.load(open("markets", "rb")) self.cc = CryptoCurrencies(key='YOUR_API_KEY', output_format='pandas') self.actv = False self.fig = Figure() self.ax1 = self.fig.add_subplot(111) self.ax1.grid() self.canvas = FigureCanvasTkAgg(self.fig, master=self.root) self.canvas.draw() self.toolbar = NavigationToolbar2Tk(self.canvas, self.root) self.toolbar.update() self.canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=1) self.labelSym = Label(self.root, text="Symbol:", bg="light green", width=8, height=2) self.labelSym.pack(side=LEFT) self.entry = ttk.Combobox(self.root, width=8) self.entry["values"] = self.used_symbolsC self.entry.pack(side=LEFT) self.labelMarket = Label(self.root, text="Market:", bg="light green", width=8, height=2) self.labelMarket.pack(side=LEFT) self.entryMarket = ttk.Combobox(self.root, width=8) self.entryMarket["values"] = self.usedsymbolsM self.entryMarket.pack(side=LEFT) self.btnTable = Button(self.root, text="SHOW TABLE", height=1) self.btnTable.pack(side=RIGHT) self.btnGraph = Button(self.root, text="SHOW GRAPH", height=1, command=self.activate) self.btnGraph.pack(side=RIGHT) ani = animation.FuncAnimation(self.fig, self.representation, interval=1000) self.root.mainloop()
def crypto_currencies(key, symbol, market="CNY"): from alpha_vantage.cryptocurrencies import CryptoCurrencies import matplotlib.pyplot as plt cc = CryptoCurrencies(key=key, output_format="pandas") data, meta_data = cc.get_digital_currency_daily(symbol=symbol, market=market) data["4b. close (USD)"].plot() plt.tight_layout() plt.title("Daily close value for bitcoin (BTC)") plt.grid() plt.show()
def generate_report(stock): logger.info(f"Generating report for {stock}") if stock.replace("$", "") in const.CRYPTO_CURRENCIES: crypto = CryptoCurrencies(key=environ["ALPHA_VANTAGE_API_KEY"]) data, _ = crypto.get_digital_crypto_rating(stock) else: fd = FundamentalData(key=environ["ALPHA_VANTAGE_API_KEY"]) data, _ = fd.get_company_overview(stock) for (key, val) in list(data.items()): if val.isnumeric(): data[key] = "${:,.2f}".format(float(val)) if key not in const.REPORT_FIELDS: data.pop(key) save_report_to_image(data)
def cryptocurrency(API_key='Z6P4MY41TAIKFAXW', currency="BTC"): print("########PROCESSING#########") from alpha_vantage.cryptocurrencies import CryptoCurrencies import matplotlib.pyplot as plt import mplfinance as mpf cc=CryptoCurrencies(key=API_key,output_format='pandas') data=cc.get_digital_currency_daily(symbol=currency, market='INR')[0] data.columns = ['Open','_Open','High','_High','Low','_Low','Close','_Close','Volume','Market Cap'] data.index.name = "Date" mpf.plot(data, type='candle', title=f'Daily Time series for the {currency} cryptocurrency', mav=(20), volume=True, tight_layout=True, style='yahoo') return data
def load_cryptocurrency_data(api_key,params): for k, v in Cryptocurrencies["From_Currency"].items(): conn = None try: conn = psycopg2.connect(**params) cur = conn.cursor() cr = CryptoCurrencies(key=api_key) data, meta_data = cr.get_digital_currency_daily(symbol=v, market=Cryptocurrencies["To_Currency"]["Indian Rupee"]) for key, value in data.items(): Last_Refreshed = key, Time_Zone = meta_data['7. Time Zone'], Digital_Currency_Code = v, Digital_Currency_Name = k, Market_Code = Cryptocurrencies["To_Currency"]["Indian Rupee"], Market_Name = "Indian Rupee", Open_INR = value['1a. open (INR)'] Open_USD = value['1b. open (USD)'] High_INR = value['2a. high (INR)'] High_USD = value['2b. high (USD)'] Low_INR = value['3a. low (INR)'] Low_USD = value['3b. low (USD)'] Close_INR = value['4a. close (INR)'] Close_USD = value['4b. close (USD)'] Volume = value['5. volume'] Market_CAP = value['6. market cap (USD)'] cur.execute( "Insert into Cryptocurrency_Data_Daily values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", (Last_Refreshed, Time_Zone, Digital_Currency_Code, Digital_Currency_Name, Market_Code, Market_Name, Open_INR, Open_USD, High_INR, High_USD, Low_INR, Low_USD, Close_INR, Close_USD, Volume, Market_CAP ) ) conn.commit() except ValueError: print( "Calling Cryptocurrency Data but execeeded number of calls per min,\nSo will call rest of the symbols after 60 seconds\n") time.sleep(60) finally: if conn is not None: conn.close()
def download_data(self, criptocoin='BTC', currency='EUR'): # Alpha Vantage API api_key = "J41D51QYZT0JLZ99" # This API outputs a dataframe with the open, low, high and close values in the "market" currency # daily for the whole historical record. Also gives same values for USD and the volume and market capitalization # in USD. cc = CryptoCurrencies(key=api_key, output_format='pandas') data, _ = cc.get_digital_currency_daily(symbol=criptocoin, market=currency) data = data.rename( columns={ "3a. low (EUR)": "low", "2a. high (EUR)": "high", "1a. open (EUR)": "open", "4a. close (EUR)": "close", "5. volume": "volume" }) # Keep only the "close" and "volume" columns self.data = data[["close", "volume"]]
def GetCrypto(coin): ''' :return: A pandas dataframe of the information from AlphaVantage ''' # Using AlphaVantage https://alpha-vantage.readthedocs.io/en/latest/ cc = CryptoCurrencies(key=ALPHA_API, output_format='pandas') data, meta_data = cc.get_digital_currency_daily(symbol=coin, market='USD') meta = None historical = read_latest(coin, parse_dates=True, errors='ignore') #set_trace() if historical is None: data, meta_data = cc.get_digital_currency_daily(symbol=coin, market='USD') data.rename(columns={'1a. open (USD)':OPEN_PRICE, '2a. high (USD)':DAY_HIGH, '3a. low (USD)':DAY_LOW, '4a. close (USD)':DAY_CLOSE, '5. volume':DAY_VOLUME, '6. market cap (USD)':MARKET_CAP} ,inplace=True) data = data[[OPEN_PRICE, DAY_HIGH, DAY_LOW, DAY_CLOSE, DAY_VOLUME, MARKET_CAP]] write_data(data, coin) ticker_data=data else: #set_trace() # If we have old data, then we'll go back to the source and get new data print(relativedelta(pd.to_datetime(historical.index[-1]), TODAY).days) if relativedelta(pd.to_datetime(historical.index[-1]), TODAY).days != 0: last_100, meta = cc.get_digital_currency_daily(symbol=coin, market='USD') last_100.rename(columns={'1a. open (USD)':OPEN_PRICE, '2a. high (USD)':DAY_HIGH, '3a. low (USD)':DAY_LOW, '4a. close (USD)':DAY_CLOSE, '5. volume':DAY_VOLUME, '6. market cap (USD)':MARKET_CAP} ,inplace=True) last_100 = last_100[[OPEN_PRICE, DAY_HIGH, DAY_LOW, DAY_CLOSE, DAY_VOLUME, MARKET_CAP]] ticker_data = historical.append(last_100) ticker_data.drop_duplicates(inplace=True) write_data(ticker_data, coin) else: ticker_data = historical return ticker_data
def __init__(self, interval=None, interval_length=None, symbol='BTC', market='USD'): self.cc = CryptoCurrencies(key=ALPHA_VANTAGE_API_KEY) self.fe = ForeignExchange(key=ALPHA_VANTAGE_API_KEY) self.symbol = symbol self.market = market super(BtcData, self).__init__(interval or 'daily', interval_length or 7, key_name='4a. close ({})'.format(self.market))
def get_bitcoin(): cc = CryptoCurrencies(key='YOUR_API_KEY', output_format='pandas') data_btc, meta_data = cc.get_digital_currency_daily(symbol='BTC', market='CNY') data_btc = data_btc.reset_index() data_btc = data_btc.drop(data_btc.index[100:1000], 0) data_btc_x = data_btc.drop(labels=[ "1a. open (CNY)", "1b. open (USD)", "2a. high (CNY)", "2b. high (USD)", "3a. low (CNY)", "3b. low (USD)", "4a. close (CNY)", "4b. close (USD)", "5. volume", "6. market cap (USD)" ], axis=1) data_btc_x = pd.to_datetime(data_btc_x["date"].unique()).tolist() data_btc_y = data_btc.drop(labels=[ "date", "1a. open (CNY)", "1b. open (USD)", "2a. high (CNY)", "2b. high (USD)", "3a. low (CNY)", "3b. low (USD)", "4a. close (CNY)", "5. volume", "6. market cap (USD)" ], axis=1) data_btc_y = data_btc_y.rename(columns={"4b. close (USD)": "Close"}) data_btc_y = data_btc_y["Close"].values.tolist() return data_btc_x, data_btc_y
class CheckingStockPrice: def __init__(self, args): self.args = args #self.ts = TimeSeries(key=self.args.api_key, output_format='pandas') self.cc = CryptoCurrencies(key=self.args.api_key, output_format='pandas') self.daily_data, self.meta_data = self.cc.get_digital_currency_daily( symbol='ETC', market='USD') print('reached here') # pass def get_excel_sheet(self): i = 1 while i is 1: self.data.to_excel('/Users/christianalcala/desktop/microsoft.xlsx') time.sleep(60)
def cryptocurrency(API_key, currency): from alpha_vantage.cryptocurrencies import CryptoCurrencies import matplotlib.pyplot as plt cc=CryptoCurrencies(key=API_key,output_format='pandas') option=input('1. Exchange Rates\n2. Health Index\n3. Daily\n4. Weekly\n5. Monthly\n').lower() if option=='exchange rates' or option=='1': data=cc.get_currency_exchange_rate(from_currency=currency, to_currency='USD')[0] return data elif option=='health index' or option=='2': data=cc.get_crypto_rating(symbol=currency)[0] return data elif option=='daily' or option=='3': data=cc.get_digital_currency_daily(symbol=currency, market='CNY')[0] data.plot() plt.title(f'Crypto Daily for the {currency} stock') plt.tight_layout() plt.grid() plt.show() return data elif option=='weekly' or option=='4': data=cc.get_digital_currency_weekly(symbol=currency, market='CNY')[0] data.plot() plt.title(f'Crypto Weekly for the {currency} stock') plt.tight_layout() plt.grid() plt.show() return data elif option=='monthly' or option=='5': data=cc.get_digital_currency_monthly(symbol=currency, market='CNY')[0] data.plot() plt.title(f'Crypto Monthly for the {currency} stock') plt.tight_layout() plt.grid() plt.show() return data else: print("DATA NOT AVAILABLE")
def setup_request_object(request, symbol, interval): if CHARTDOMAIN == 'stock': try: ts = TimeSeries(API_KEY, output_format='pandas', indexing_type='date') except: print("Error occurred/ Number of API calls exhausted") return [False, False] if request == 'intraday': return ['intraday', ts] if request == 'daily': return ['daily', ts] if request == 'weekly': return ['weekly', ts] if request == 'monthly': return ['monthly', ts] return [False, False] if CHARTDOMAIN == 'cryptocurrency': try: cc = CryptoCurrencies(key=API_KEY, output_format='pandas') except: print("Error occurred/ Number of API calls exhausted") return [False, False] if CRYPTOINTERVAL == 'daily': return ['daily', cc] if CRYPTOINTERVAL == 'weekly': return ['weekly', cc] if CRYPTOINTERVAL == 'monthly': return ['monthly', cc] return [False, False]
def create_line_chart(user_doc): """ This function creates a line chart for the user's wallet performance. It querries the user's wallet and calls the API Alpha Vantage in order to get historical data of those specific cryptocurrencies. The values are filtered to only those after the coins have been purchased for the first time. For simplicity purposes, it assumes A CONSTANT TICKER DURING THE WHOLE TIME PERIOD. """ # Alpha Vantage Alpha_Vantage_Key = os.getenv("ALPHAVANTAGE_API_KEY") cc = CryptoCurrencies(Alpha_Vantage_Key) # Fetching historical data for specific coins in user's wallet user_wallet = user_doc['wallet'] wallet_coins = user_wallet['coins'] coins_obj = {} for coin, obj in wallet_coins.items(): symbol = coin.replace('USDT', '') coins_obj[coin] = {} ticker = obj['total_ticker'] coins_obj[coin]['ticker'] = ticker start_date = pd.to_datetime(obj['transactions'][0]['date']) coins_obj[coin]['coin_name'] = obj['transactions'][0]['name'] coins_obj[coin]['start_date'] = start_date #API Call for every coin in wallet, market is set to United States US$ cc_data, meta_data = cc.get_digital_currency_daily(symbol=symbol, market='USD') filter_data = {} for date, data in cc_data.items(): date = pd.to_datetime(date) # Filter only relevant values by date and calculate total value if date >= start_date: filter_data[date] = float(data['4b. close (USD)']) * ticker coins_obj[coin]['historical_data'] = filter_data # Plotly line chart initiation figure = go.Figure() # Add data to figure for coin, info in coins_obj.items(): historical_data = info['historical_data'] coin_name = info['coin_name'] labels = [] values = [] for time, value in historical_data.items(): labels.append(time) values.append(value) trace = go.Scatter(x=labels, y=values, mode='lines', name=coin_name) figure.add_trace(trace) # Edit the layout figure.update_layout(title='My CryptoWallet Performance', xaxis_title='Month', yaxis_title='Total value (US$)') # Json the data to be parsed later onto the html template. graphJSON = json.dumps(figure, cls=plotly.utils.PlotlyJSONEncoder) return graphJSON
# ------------------------------ # 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() plt.show() # --------------------------- # Part Four: Cryptocurrencies # --------------------------- ticker = 'BTC' cc = CryptoCurrencies(key='YOUR_API_KEY', output_format='pandas') data, metadata = cc.get_digital_currency_intraday(symbol=ticker, market='CNY') data['1b. price (USD)'].plot() plt.tight_layout() plt.title('Intraday value for bitcoin (BTC)') plt.grid() plt.show() # -------------------------------- # Part Five: Foreign Exchange (FX) # -------------------------------- fe = ForeignExchange(key='YOUR_API_KEY') # No metadata here data, _ = fe.get_currency_exchange_rate(from_currency='BTC', to_currency='USD') pprint(data)
def fetch(self, ticker): if self.exchange == 'poloniex': #ticker in format 'BTC_OMG' #period in format '5m', '1h' etc #downloads all data for a given exchange directory = self.directory + '/Raw_data/' + self.exchange + '/' + self.period + '/' + tickDir( ticker) + '.pickle' if (not os.path.isfile(directory)) or self.newdata == True: data = self.exchangeObject.fetch_ohlcv(ticker, timeframe=self.period) df = pd.DataFrame(data) df.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume'] df['Date'] = pd.to_datetime(df['Date'], unit='ms') df.set_index('Date', inplace=True) if not os.path.exists(self.directory + '/Raw_data/' + self.exchange + '/' + self.period): os.makedirs(self.directory + '/Raw_data/' + self.exchange + '/' + self.period) pickler(directory, df) return df elif os.path.isfile(directory): return dePickler(directory) if self.exchange == 'snp500': directory = self.directory + '/Raw_data/' + self.exchange + '/1d/' + ticker + '.pickle' if not os.path.isfile(directory): df = web.DataReader(ticker, 'google') if not os.path.exists(self.directory + self.exchange + '/1d'): os.makedirs(self.directory + self.exchange + '/1d') pickler(directory, df) elif os.path.isfile(directory): return dePickler(directory) if self.exchange == 'alphavantage': directory = self.directory + 'Raw_data/' + self.exchange + '/' + self.period + '/' + ticker + '.pickle' if (not os.path.isfile(directory)) or self.newdata == True: if self.asset_type == 'eft' and self.period == '1d': ts = TimeSeries(key='YOUR_API_KEY', output_format='pandas') data, meta_data = ts.get_daily(symbol=ticker, outputsize='full') data.columns = ['Open', 'High', 'Low', 'Close', 'Volume'] elif self.asset_type == 'crypto' and self.period == '1d': ts = CryptoCurrencies(key='YOUR_API_KEY', output_format='pandas') data, meta_data = ts.get_digital_currency_daily( symbol=ticker, market='USD') data.drop([ '1b. open (USD)', '2b. high (USD)', '3b. low (USD)', '4b. close (USD)', '6. market cap (USD)' ], axis=1, inplace=True) data.columns = ['Open', 'High', 'Low', 'Close', 'Volume'] elif self.asset_type == 'crypto' and self.period == '5m': ts = CryptoCurrencies(key='YOUR_API_KEY', output_format='pandas') data, meta_data = ts.get_digital_currency_intraday( symbol=ticker, market='USD') data.drop(['1b. price (USD)', '3. market cap (USD)'], axis=1, inplace=True) data.columns = ['Close', 'Volume'] print(data) time.sleep(50) else: print( 'incompatible asset type and period (see getdata module)' ) sys.exit(2) else: data = dePickler(directory) if not os.path.exists(self.directory + '/Raw_data/' + self.exchange + '/' + self.period): os.makedirs(self.directory + '/Raw_data/' + self.exchange + '/' + self.period) pickler(directory, data) return data
import streamlit as st import pandas as pd import numpy as np import os import requests import plotly.express as px from datetime import datetime, timedelta from alpha_vantage.timeseries import TimeSeries from alpha_vantage.cryptocurrencies import CryptoCurrencies from PIL import Image ALPHAVANTAGE_API_KEY = 'H983JJABQU6EEV35' ts = TimeSeries(key=ALPHAVANTAGE_API_KEY, output_format='pandas') cc = CryptoCurrencies(key=ALPHAVANTAGE_API_KEY, output_format='pandas') resp = requests.get('https://www.alphavantage.co/query', params={ 'function': 'TIME_SERIES_DAILY_ADJUSTED', 'symbol': 'ITSA4.SA', 'market': 'BRL', 'apikey': ALPHAVANTAGE_API_KEY, 'datatype': 'json', 'outputsize': "full" }) doc = resp.json() df = pd.DataFrame.from_dict(doc['Time Series (Daily)'], orient='index', dtype=np.float) df.reset_index(inplace=True) df = df.rename(columns={ 'index': 'Data',
class REST(object): def __init__(self, api_key): self._api_key = get_alpha_vantage_credentials(api_key) self._session = requests.Session() self._timeseries = TimeSeries(key=self._api_key) self._cryptocurrencies = CryptoCurrencies(key=self._api_key) self._foreignexchange = ForeignExchange(key=self._api_key) self._sectorperformance = SectorPerformances(key=self._api_key) self._techindicators = TechIndicators(key=self._api_key) def _request(self, method, params=None): url = 'https://www.alphavantage.co/query?' params = params or {} params['apikey'] = self._api_key resp = self._session.request(method, url, params=params) resp.raise_for_status() return resp.json() def get(self, params=None): ''' Customizable endpoint, where you can pass all keywords/paramters from the documentation: https://www.alphavantage.co/documentation/# Returns: pandas, csv, or json ''' return self._request('GET', params=params) def historic_quotes(self, symbol, adjusted=False, outputsize='full', cadence='daily', output_format=None): ''' Returns the one of the TIME_SERIES_* endpoints of the Alpha Vantage API. Params: symbol: The ticker to return adjusted: Return the adjusted prices cadence: Choose between ['daily', 'weekly', 'monthly'], to return the cadence output_format: Choose between['json', 'csv', 'pandas'] Returns: pandas, csv, or json ''' if output_format: self._timeseries.output_format = output_format if cadence == 'daily': data, _ = self._timeseries.get_daily_adjusted( symbol=symbol, outputsize=outputsize) if adjusted else self._timeseries.get_daily(symbol=symbol, outputsize=outputsize) if cadence == 'weekly': data, _ = self._timeseries.get_weekly_adjusted( symbol=symbol) if adjusted else self._timeseries.get_weekly(symbol=symbol) if cadence == 'monthly': data, _ = self._timeseries.get_monthly_adjusted( symbol=symbol) if adjusted else self._timeseries.get_monthly(symbol=symbol) return data def intraday_quotes(self, symbol, interval='5min', outputsize='full', output_format=None): ''' Returns the TIME_SERIES_INTRADAY endpoint of the Alpha Vantage API. Params: symbol: The ticker to return interval: Choose between['1min', '5min', '15min', '30min', '60min'] output_format: Choose between['json', 'csv', 'pandas'] Returns: pandas, csv, or json ''' if output_format: self._timeseries.output_format = output_format data, _ = self._timeseries.get_intraday( symbol=symbol, interval=interval, outputsize=outputsize) return data def current_quote(self, symbol): ''' Returns the GLOBAL_QUOTE endpoint of the Alpha Vantage API. Params: symbol: The ticker to return output_format: Choose between['json', 'csv', 'pandas'] Returns: pandas, csv, or json ''' data, _ = self._timeseries.get_quote_endpoint(symbol=symbol) return data def last_quote(self, symbol): return self.current_quote(symbol) def company(self, symbol, datatype='json'): return self.search_endpoint(symbol, datatype=datatype) def search_endpoint(self, keywords, datatype='json'): '''Search endpoint returns a list of possible companies that correspond to keywords Params: datatype: csv, json, or pandas keywords: ex. keywords=microsoft Returns: pandas, csv, or json ''' params = {'function': 'SYMBOL_SEARCH', 'keywords': keywords, 'datatype': datatype} return self.get(params) def historic_fx_quotes(self, from_symbol, to_symbol, outputsize='full', cadence='daily', output_format=None): ''' Returns the one of the FX_* endpoints of the Alpha Vantage API. Params: from_currency: The symbol to convert to_currency: The symbol to convert to cadence: Choose between ['daily', 'weekly', 'monthly'], to return the cadence output_format: Choose between['json', 'csv', 'pandas'] Returns: pandas, csv, or json ''' if output_format: self._foreignexchange.output_format = output_format if cadence == 'daily': data, _ = self._foreignexchange.get_currency_exchange_daily( from_symbol=from_symbol, to_symbol=to_symbol, outputsize=outputsize) if cadence == 'weekly': data, _ = self._foreignexchange.get_currency_exchange_weekly( from_symbol=from_symbol, to_symbol=to_symbol, outputsize=outputsize) if cadence == 'monthly': data, _ = self._foreignexchange.get_currency_exchange_monthly( from_symbol=from_symbol, to_symbol=to_symbol, utputsize=outputsize) return data def intraday_fx_quotes(self, from_symbol, to_symbol, interval='5min', outputsize='full', output_format=None): ''' Returns the FX_INTRADAY endpoint of the Alpha Vantage API. Params: from_currency: The symbol to convert to_currency: The symbol to convert to interval: Choose between['1min', '5min', '15min', '30min', '60min'] output_format: Choose between['json', 'csv', 'pandas'] Returns: pandas, csv, or json ''' if output_format: self._foreignexchange.output_format = output_format data, _ = self._foreignexchange.get_currency_exchange_intraday( from_symbol=from_symbol, to_symbol=to_symbol, interval=interval, outputsize=outputsize) return data def exchange_rate(self, from_currency, to_currency): ''' Returns the exchange rate of two currencies, digital or physical. CURRENCY_EXCHANGE_RATE endpoint of the Alpha Vantage API Params: from_currency: The symbol to convert to_currency: The symbol to convert to Returns: json ''' params = {'function': "CURRENCY_EXCHANGE_RATE", 'from_currency': from_currency, 'to_currency': to_currency} data = self.get(params) return data def historic_cryptocurrency_quotes(self, symbol, market, cadence='daily', output_format=None): ''' Returns the one of the DIGITAL_CURRENCY_* endpoints of the Alpha Vantage API. Params: symbol: The cryptocurrency to return market: The market it's being sold on cadence: Choose between ['daily', 'weekly', 'monthly'], to return the cadence output_format: Choose between['json', 'csv', 'pandas'] Returns: pandas, csv, or json ''' if output_format: self._cryptocurrencies.output_format = output_format if cadence == 'daily': data, _ = self._cryptocurrencies.get_digital_currency_daily( symbol=symbol, market=market) if cadence == 'weekly': data, _ = self._cryptocurrencies.get_digital_currency_weekly( symbol=symbol, market=market) if cadence == 'monthly': data, _ = self._cryptocurrencies.get_digital_currency_monthly( symbol=symbol, market=market) return data def techindicators(self, techindicator='SMA', output_format='json', **kwargs): ''' Returns the one of the technical indicator endpoints of the Alpha Vantage API. Params: techindicator: The technical indicator of choice params: Each technical indicator has additional optional parameters Returns: pandas, csv, or json ''' if output_format: self._techindicators.output_format = output_format params = {'function': techindicator} for key, value in kwargs.items(): params[key] = value data = self.get(params) return data def sector(self): ''' Returns the sector performances Returns: pandas, csv, or json ''' data, _ = self._sectorperformance.get_sector() return data
ti = TechIndicators(key=mykey, output_format='pandas') data, meta_data = ti.get_bbands(symbol=myticker, time_period=20) data.tail(252).plot() # Plot last year only. plt.title('BBbands indicator for ' + myticker) plt.show() # Sector performance. sp = SectorPerformances(key=mykey, output_format='pandas') data, meta_data = sp.get_sector() data['Rank G: Year Performance'].plot(kind='bar') plt.title('Sector Performance (Year)') plt.tight_layout() plt.grid() plt.show() # Crypto currencies. cc = CryptoCurrencies(key=mykey, output_format='pandas') data, meta_data = cc.get_digital_currency_daily(symbol='BTC', market='CNY') data['4b. close (USD)'].plot(logy=True) plt.tight_layout() plt.title('Daily Value for Bitcoin (BTC)') plt.grid() plt.show() # Foreign exchange data is only available as JSON format (not in CSV # or Pandas format). There's also no metadata in this call (so we just # use a placeholder `_`). cc = ForeignExchange(key=mykey) data, _ = cc.get_currency_exchange_rate(from_currency='EUR', to_currency='USD') pprint(data)