def digital_currency(message): try: text = message.text if text =="Назад": markup = types.ReplyKeyboardMarkup() markup.row('Информация о боте', 'Котировки', 'Форекс', 'Портфель') bot.send_message(message.chat.id, "Выберите действие:", reply_markup=markup) else: markup = types.ReplyKeyboardMarkup() markup.row("Получить новости", "Назад") global slov slov = message.text String = str(slov) string1 = String[0:3] string2 = String[4:7] cc = ForeignExchange(key='ZBRM5PCHPIYQV8BY', output_format='pandas') # There is no metadata in this call data, meta_data = cc.get_currency_exchange_daily(from_symbol=string1, to_symbol=string2, outputsize='full') now = pd.DataFrame(data.tail(1)) now1 = now['1. open'] nw = str(now1) nw2 = nw[19:25] nw3 = float(nw2) openn = pd.DataFrame(data.tail(1)) openn1 = openn['4. close'] op = str(openn1) op2 = op[19:25] op3 = float(op2) if op3 >= nw3: proc = round(100 - ((op3 / nw3) * 100), 2) proc1 = str(proc) bot.send_message(message.chat.id, slov + " - $" + op2 + ' +' + proc1 + '%') elif op3 < nw3: proc2 = round(100 - ((nw3 / op3) * 100), 2) proc2 = str(proc2) bot.send_message(message.chat.id, slov + " - $" + op2 + ' -' + proc2 + '%') da, meta_data = cc.get_currency_exchange_daily(from_symbol=string1, to_symbol=string2, outputsize='full') da['4. close'].plot() plt.title('Intraday Times Series (1 min) within 10 days') plt.savefig('graph.png') plt.close() photo = open("graph.png", 'rb') bot.send_photo(message.chat.id, photo) msg = bot.send_message(message.chat.id, "Получить новости?", reply_markup=markup) bot.register_next_step_handler(msg, new) except Exception as e: m = types.ReplyKeyboardMarkup() m.row('Информация о боте', 'Котировки', 'Форекс', 'Портфель') bot.send_message(message.chat.id, 'Что-то пошло не так...', reply_markup=m)
def get_daily_currency_data(outdir, filename, key=key, curr1='EUR', curr2='USD', values='all', num_days=100): fe = ForeignExchange(key, output_format='pandas') data, meta = fe.get_currency_exchange_daily(from_symbol=curr1, to_symbol=curr2, outputsize='full') filepath = Path(outdir, filename + '.csv') if values == 'all': data = pd.DataFrame.head(data, n=num_days) pd.DataFrame.to_csv(data, filepath, header=True) return options = ['open', 'high', 'low', 'close'] for i in range(len(options)): if values == options[i]: data = pd.DataFrame.head(data[data.columns[i]], n=num_days) pd.DataFrame.to_csv(data, filepath, header=True) return else: print( "Error: values must be \'all\', \'open\', \'high\', \'low\', or \'close\'" ) return
def get_fx_data(): fx_pairs = FX.objects.all() count = 0 for fx in fx_pairs: latest = FXPriceData.objects.filter( currency_pair=fx).order_by('-timestamp').first() if latest and latest.timestamp == datetime.datetime.today(): print('Latest data for {} already stored'.format(fx)) else: try: # Check if I have hit alphas api limit, if so wait 1 min count += 1 if count == 6: time.sleep(75) count = 0 exchange = ForeignExchange(key='3GVY8HKU0D7L550R', output_format='pandas') data, meta_data = exchange.get_currency_exchange_daily( from_symbol=fx.from_currency.code, to_symbol=fx.to_currency.code, outputsize='full') # Format the dataframe and save the data in the db df = format_df(data, fx) df_to_sql(df) except ValueError as e: print('{} - Pair: {}'.format(e, fx))
def create_data_frame(self): fe = ForeignExchange(key=self.api_key) data, _ = fe.get_currency_exchange_daily(from_symbol=EXCHANGE_RATE_SYMBOLS['from_symbol'], to_symbol=EXCHANGE_RATE_SYMBOLS['to_symbol'], outputsize='full') data_df = pd.DataFrame(data) data_df = data_df.T data_df.columns = ['open', 'high', 'low', 'close'] data_df.index = pd.DatetimeIndex(data_df.index) self.df = data_df
def get_exchange_rate(cur): cc = ForeignExchange(key=ALPHA_VANTAGE_KEY, output_format='pandas', indexing_type='date') # There is no metadata in this call data, _ = cc.get_currency_exchange_daily(from_symbol=cur, to_symbol='CNY') data.reset_index(inplace=True) exRate = data.loc[:, ('date', '4. close')] exRate.rename(columns={'date': 'Date', '4. close': 'Close'}, inplace=True) exRate.insert(1, 'SymbolCode', cur) exRate['Date'] = exRate.apply(lambda x: x['Date'].strftime('%Y-%m-%d'), axis=1) return exRate
def get_forex_daily(self, from_currency, to_currency, num_days): self._check_api_rate_limit() cc = ForeignExchange(key=self._api_key, output_format='pandas') output_size = 'compact' if num_days > 100: output_size = 'full' cc_data, _ = cc.get_currency_exchange_daily( from_symbol=from_currency, to_symbol=to_currency, outputsize=output_size, ) self._rename_columns(cc_data) return cc_data.iloc[-num_days:]
def forex(API_key, fromCurr, toCurr): from alpha_vantage.foreignexchange import ForeignExchange import matplotlib.pyplot as plt fe=ForeignExchange(key=API_key,output_format='pandas') option=input('1. Exchange Rates\n2. Intraday\n3. Daily\n4. Weekly\n5. Monthly\n').lower() if option=='exchange rates' or option=='1': data=fe.get_currency_exchange_rate(from_currency=fromCurr, to_currency=toCurr)[0] return data elif option=='intraday' or option=='2': interval=int(input("Enter 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=fe.get_currency_exchange_intraday(from_symbol=fromCurr, to_symbol=toCurr,interval=intervalList[interval])[0] data.plot() plt.title(f'Forex Intraday for the {fromCurr}-{toCurr} stock ({intervalList[interval]})') plt.tight_layout() plt.grid() plt.show() return data elif option=='daily' or option=='3': data=fe.get_currency_exchange_daily(from_symbol=fromCurr, to_symbol=toCurr)[0] data.plot() plt.title(f'Forex Daily for the {fromCurr}-{toCurr} stock') plt.tight_layout() plt.grid() plt.show() return data elif option=='weekly' or option=='4': data=fe.get_currency_exchange_weekly(from_symbol=fromCurr, to_symbol=toCurr)[0] data.plot() plt.title(f'Forex Weekly for the {fromCurr}-{toCurr} stock') plt.tight_layout() plt.grid() plt.show() return data elif option=='monthly' or option=='5': data=fe.get_currency_exchange_monthly(from_symbol=fromCurr, to_symbol=toCurr)[0] data.plot() plt.title(f'Forex Monthly for the {fromCurr}-{toCurr} stock') plt.tight_layout() plt.grid() plt.show() return data else: print("DATA NOT AVAILABLE")
def forex(API_key='Z6P4MY41TAIKFAXW', fromCurr='INR', toCurr='USD'): print("########PROCESSING#########") from alpha_vantage.foreignexchange import ForeignExchange import matplotlib.pyplot as plt import mplfinance as mpf fe=ForeignExchange(key=API_key,output_format='pandas') data=fe.get_currency_exchange_daily(from_symbol=fromCurr, to_symbol=toCurr)[0] data.columns = ['Open', 'High', 'Low', 'Close'] data.index.name = "Date" mpf.plot(data, type='candle', title=f'Daily FOREX for the {fromCurr} against {toCurr} currency', mav=(20), tight_layout=True, style='yahoo') return data
def omen(key, from_symbol, to_symbol, interval=False): """Takes Alpha Vantage API key, currency pair and optional interval, and returns the predicted next value.""" #set constants FIELD = "4. close" #fetch data api = ForeignExchange(key=key) if interval: data, _ = api.get_currency_exchange_intraday(from_symbol=from_symbol, to_symbol=to_symbol, outputsize="full", interval=interval) else: data, _ = api.get_currency_exchange_daily(from_symbol=from_symbol, to_symbol=to_symbol, outputsize="full") #extract required data time_series = [] for date in data: time_series.append((date, float(data[date][FIELD]))) time_series.sort(key=lambda tup: tup[0]) dates = [] prices = [] for date, price in time_series: dates.append(date) prices.append(price) #build data structures df = pd.DataFrame(data=prices, index=dates, columns=["price"]) df["prediction"] = df[["price"]].shift(-1) x = np.array(df.drop(["prediction"], 1)) x = preprocessing.scale(x) x_forecast = x[-1:] x = x[:-1] y = np.array(df["prediction"]) y = y[:-1] x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) #run linear regression reg = LinearRegression() reg.fit(x_train, y_train) future = reg.predict(x_forecast) return prices[-1], future[0]
def add_forex(self, from_currency, to_currency, primary_df): """ Adds FOREX rates to the dataset. Currently only incorporates a couple of years ############ Recommend against using until improved ########################## Parameters ---------- from_currency : str Currency being compared to another currency to_currency : str Second currency being compared to the first. primary_df : pandas dataframe pandas dataframe to be appended. Calculation ----------- forex_value = (from_currency / to_currency) """ # API Object cc = ForeignExchange(key=config('ALPHA_VANTAGE'), output_format='pandas') # API Call data = cc.get_currency_exchange_daily(from_symbol=from_currency, to_symbol=to_currency, outputsize=self.outputsize) data = data.rename(columns={ '1. open' : from_currency+'_to_'+to_currency+'_open', '2. high' : from_currency+'_to_'+to_currency+'_high', '3. low' : from_currency+'_to_'+to_currency+'_low', '4. close' : from_currency+'_to_'+to_currency+'_close', } ) final_df = primary_df.merge(data, how='inner', on='date') return final_df
def add_forex(self, from_currency, to_currency, primary_df): cc = ForeignExchange(key=config('ALPHA_VANTAGE'), output_format='pandas') data, meta_data = cc.get_currency_exchange_daily( from_symbol=from_currency, to_symbol=to_currency, outputsize=self.outputsize) print(meta_data) data = data.rename( columns={ '1. open': from_currency + '_to_' + to_currency + '_open', '2. high': from_currency + '_to_' + to_currency + '_high', '3. low': from_currency + '_to_' + to_currency + '_low', '4. close': from_currency + '_to_' + to_currency + '_close', }) final_df = primary_df.merge(data, how='inner', on='date') return final_df
dfm, meta_data = cc.get_currency_exchange_monthly(from_symbol='EUR', to_symbol='USD', outputsize='full') clean_Columns(dfm) dfm = dfm.tail(12) if dfw.empty: dfw, meta_data = cc.get_currency_exchange_weekly(from_symbol='EUR', to_symbol='USD', outputsize='full') clean_Columns(dfw) dfw = dfw.tail(24) if dfd.empty: dfd, meta_data = cc.get_currency_exchange_daily(from_symbol='EUR', to_symbol='USD', outputsize='full') clean_Columns(dfd) dfd = dfd.tail(90) #How to create a random array #df = pd.DataFrame(np.random.randint(0,20,size=(20, 2)), columns=list('AB')) cols = ['Date', 'Time', 'Open', 'High', 'Low', 'Last'] df = pd.read_csv('data/4hMFE.csv', skipinitialspace=True, usecols=cols) df = df.tail(78) df.reset_index(drop=False, inplace=True) #%% end of cell begining of new # data x = df.index y = df['High']
if __name__ == '__main__': try: foreign = sys.argv[1].upper() except IndexError: sys.exit('No foreign currency symbol entered.') try: domestic = sys.argv[2].upper() except IndexError: sys.exit('No domestic currency symbol entered.') checkArgs(foreign, domestic) forex = ForeignExchange(AV_API_KEY, output_format='pandas') print('Fetching data for ' + foreign + '/' + domestic + ':') try: data = forex.get_currency_exchange_daily(from_symbol=foreign, to_symbol=domestic, outputsize='full')[0] except ValueError: sys.exit( 'Invalid currency symbol entered. Please look at symbols used.') data = formatData(data) c = data['close'] #o = data['open'] #h = data['high'] #l = data['low'] print('Generating Charts:') plt.figure(0) plt.title(foreign + '/' + domestic + ' Daily Exchange Rate Close') plt.xlabel('Date') plt.ylabel('Rate') plt.grid()
import pandas as pd from alpha_vantage.timeseries import TimeSeries from alpha_vantage.foreignexchange import ForeignExchange #import matplotlib.pyplot as plt keys='8C0B4ERLNTL4KOMW' df = ForeignExchange (key=keys, output_format='pandas') data, meta_data =df.get_currency_exchange_daily(from_symbol='USD', to_symbol='CAD',outputsize='compact') print ('USDCAD') print (data) #still working out this section so its all commented out ''' data['close'].plot() plt.title('My First Observation') plt.show() '''
ti=TechIndicators(key=free_api_key, output_format='pandas') sma=ti.get_sma('MSFT',interval='daily',time_period=50)[0] bbands=ti.get_bbands('MSFT',interval='daily',time_period=50)[0] # add close price to bollinger bands df (want to adadjusted!!) bbands['close']=close.iloc[:,0] macd=ti.get_macd('MSFT',interval='daily')[0] # currencies # supports 150 currencies fx=ForeignExchange(key=free_api_key, output_format='pandas') eurusd=fx.get_currency_exchange_daily('EUR','USD',outputsize='full')[0] #intraday fx.get_currency_exchange_intraday('EUR','USD', interval='1min', outputsize='full')[0] # cryptocurrencies more than 500 supported cc=CryptoCurrencies(key=free_api_key, output_format='pandas') VTC= cc.get_digital_currency_daily(symbol='BTC',market='USD') BTC[1] BTC[0
#print (data.head()) #data.columns=['open','high','low','close','volume'] #data['close'].plot() #data['date']=data.index.date #data['time']=data.index.time #data.index.names=['datetime'] #print(data.head()) #market = data.between_time('09:00:00', '16:00:00').copy() #market.sort_index(inplace=True) #print(market.head()) #market_mean=market.groupby('date').mean() #print(market_mean.head()) #high_low=market.groupby('date').agg({'low':min, 'high':max}) #print (high_low.head()) #myapi trial #from alpha_vantage.fundamentaldata import FundamentalData #fd=FundamentalData(key,output_format='pandas') #data=fd.get_cash_flow_annual('TSLA') #print (data) #Import API data from alpha_vantage website import pandas as pd from alpha_vantage.foreignexchange import ForeignExchange fx = ForeignExchange(key, output_format='pandas') fxdata = fx.get_currency_exchange_daily('EUR', 'USD', outputsize='compact') EUR_USD_Daily = pd.DataFrame(fxdata[0]) print(EUR_USD_Daily) EUR_USD_Daily.plot(title='EUR to USD Daily Rate')
# Validate quantile q_ = getattr(args, "quantile") assert 0 < q_ and q_ < 0.5, "Quantile sample must be in the range 0 < QUANTILE < 0.5 to function." # --------- USE THE OUP STRATEGY TO MAKE A BUY/SELL DECISION --------- # Process of retrieving can take a few seconds, inform the user print("\tRetrieving past price values, please wait...\n") # Retrieve the price history (past 100 days) for the given currency pair # DISCLAIMER: Alpha Vantage API puts a limit on calls to 5 per minute and 500 per day # Ideally, the API key would also be unique per user, but is included for demonstration purposes try: cc = ForeignExchange(key='UH8X7NHOQEPGPWUV', output_format='pandas') data, meta_data = cc.get_currency_exchange_daily(from_symbol=from_, to_symbol=to_) # Execute the strategy with the given parameters bought, last_buy_point = trade_OUP(data['4. close'].tolist(), trading_time=time_, ma_period=period_, ma_t=ma_t_, T=t_, quantile=q_) pair = str(from_) + "/" + str(to_) # Provide command line feedback if bought: print("\tOUP strategy would purchase " + pair + ". Buy order set " + str(last_buy_point) + " day(s) ago.") else:
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
class AlphaVantageFOREXClient: def __init__(self, api_key=None): if api_key is None: default_api_key = utils.get_api_key('AlphaVantage') if default_api_key is None: raise ValueError('No AlphaVantage API Key found.') else: self.ts = ForeignExchange(key=default_api_key, output_format='pandas') else: self.ts = ForeignExchange(key=api_key, output_format='pandas') def get_data(self, from_currency, to_currency, freq='daily', interval='15min', outputsize='full'): """ Return time series in pandas formet. Keyword Arguments: from_currency: The currency you would like to get the exchange rate for. It can either be a physical currency or digital/crypto currency. to_currency: The destination currency for the exchange rate. It can either be a physical currency or digital/crypto currency. freq: frequency of data, supported values are 'daily', 'weekly', 'monthly' (default 'daily'). Currently not support for 'intraday' interval: time interval between two conscutive values, used when freq is intraday supported values are '1min', '5min', '15min', '30min', '60min' (default '15min') outputsize: The size of the call, supported values are 'compact' and 'full; the first returns the last 100 points in the data series, and 'full' returns the full-length intraday times series, commonly above 1MB (default 'compact') """ # if freq == 'intraday': # data, _ = self.ts.get_currency_exchange_intraday(from_symbol=from_currency, to_symbol=to_currency, interval=interval, outputsize=outputsize) if freq == 'daily': data, _ = self.ts.get_currency_exchange_daily( from_symbol=from_currency, to_symbol=to_currency, outputsize=outputsize) elif freq == 'weekly': data, _ = self.ts.get_currency_exchange_weekly( from_symbol=from_currency, to_symbol=to_currency, outputsize=outputsize) elif freq == 'monthly': data, _ = self.ts.get_currency_exchange_monthly( from_symbol=from_currency, to_symbol=to_currency, outputsize=outputsize) else: raise Warning('Freq: {} is not valid. Default to Daily.') data, _ = self.ts.get_currency_exchange_daily( from_symbol=from_currency, to_symbol=to_currency, outputsize=outputsize) data.columns = ['Open', 'High', 'Low', 'Close'] data = data.rename(index={'date': 'Date'}) return data.sort_index(ascending=True) def get_latest_data(self, from_currency, to_currency): """ Return the latest price and volume information for a exchange of your choice Keyword Arguments: from_currency: The currency you would like to get the exchange rate for. It can either be a physical currency or digital/crypto currency. to_currency: The destination currency for the exchange rate. It can either be a physical currency or digital/crypto currency. """ data, _ = self.ts.get_currency_exchange_rate( from_currency=from_currency, to_currency=to_currency) data = data.iloc[:, [0, 2, 4, 5, 7, 8]] columns_name = ['From', 'To', 'Rate', 'Date', 'Bid', 'Ask'] data.columns = columns_name data = data.set_index(['Date']) return data