def get_historical(from1, to1, timeframe): cc = ForeignExchange(key='N6A6QT6IBFJOPJ70', output_format='pandas') data, meta_data = cc.get_currency_exchange_intraday( from_symbol=from1.strip(), to_symbol=to1.strip(), interval=timeframe.strip(), outputsize='full') df = pd.DataFrame(data) #df= pd.date_range(pd.to_datetime('today'), periods=10, freq='15min') df = df.rename( columns={ 'date': 'Date', '1. open': 'Open', '2. high': 'High', '3. low': 'Low', '4. close': 'Close' }) df.index.names = ['Date'] st.write(df) #df['Close'].plot() #plt.tight_layout() #plt.title('15 mins EUR/USD') #df = df.to_csv(quote + ".csv") #plt.show() #print() #print("##############################################################################") #print("Today's price") #today_stock = df.iloc[1:2] #print(today_stock) #print("##############################################################################") #print() return df
def load_forex_data_intraday(api_key,params): for k, v in Forex_List.items(): conn = None try: conn = psycopg2.connect(**params) cur = conn.cursor() fx = ForeignExchange(key=api_key) data, meta_data = fx.get_currency_exchange_intraday(from_symbol=v, to_symbol="INR", interval=Interval[0]) for key, value in data.items(): Last_Refreshed = key Time_Zone = meta_data['7. Time Zone'] open_price = value['1. open'] high_price = value['2. high'] low_price = value['3. low'] close_price = value['4. close'] cur.execute("Insert into Currency_Exchange_Rate_Intraday values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", (Last_Refreshed, Time_Zone, v, k, "INR", "Indian Rupee", open_price, high_price, low_price, close_price) ) conn.commit() except ValueError: print( "Calling Forex 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 get_intraday_currency_data(outdir, filename, key=key, curr1='EUR', curr2='USD', values='all', num_obs=100, interval='15min'): fe = ForeignExchange(key, output_format='pandas') data, meta = fe.get_currency_exchange_intraday(from_symbol=curr1, to_symbol=curr2, interval=interval, outputsize='full') filepath = Path(outdir, filename + '.csv') if values == 'all': data = pd.DataFrame.head(data, n=num_obs) 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_obs) pd.DataFrame.to_csv(data, filepath, header=True) return else: print( "Error: values must be \'all\', \'open\', \'high\', \'low\', or \'close\'" ) return # Example: get_intraday_currency_data(outdir="C:/Users/RBP7855/Desktop", filename="EUR_to_USD_intraday", curr1='EUR', curr2='USD', values='open', num_obs=500, interval='30min')
class ForeignExchangeAPI(BaseAPI): """ API for ForeignExchange Data """ def __init__(self): super(ForeignExchangeAPI, self).__init__() self.fe = ForeignExchange(key=self.api, output_format=self.output_format) def get_intraday(self, from_symbol, to_symbol, interval='15min', outputsize='compact'): return self.fe.get_currency_exchange_intraday(from_symbol, to_symbol, interval=interval, outputsize=outputsize) def get_exchange_rate(self, from_currency, to_currency): return self.fe.get_currency_exchange_rate(from_currency, to_currency) def plot(self, **kwargs): from_symbol = kwargs.get('from_symbol') to_symbol = kwargs.get('to_symbol') data, meta_data = self.get_intraday(from_symbol, to_symbol) data['4. close'].plot() plt.show()
def grap_api_data(): api_key = '1456af4c4704e5e6bd4b60c30094b56b-32c375f91dc677c9fce0916d50811d4f' cc = ForeignExchange(key=api_key) global data data, _ = cc.get_currency_exchange_intraday(from_symbol='EUR', to_symbol='USD', interval="1min", outputsize='compact')
def fetch_forex_data(from_symbol, to_symbol): cc = ForeignExchange(key=ALPHA_VANTAGE_API_KEY, output_format="pandas") data, meta_data = cc.get_currency_exchange_intraday( from_symbol=from_symbol, to_symbol=to_symbol, interval="1min", outputsize="full") return data
def getfxdata(alphaVantageKey, our, their, interval): data = None while data is None: try: fx = ForeignExchange(key=alphaVantageKey, output_format='pandas') data, meta_data = fx.get_currency_exchange_intraday( our, their, interval=interval, outputsize='full') except: pass return data['4. close']
def api_info(): api_key = "1456af4c4704e5e6bd4b60c30094b56b-32c375f91dc677c9fce0916d50811d4f" api_name = ForeignExchange(key=api_key) global data data, _ = api_name.get_currency_exchange_intraday(from_symbol="EUR", to_symbol="USD", interval="1min", outputsize="compact") global json json = str(data)
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 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 alpha_collect_fx(): cc = ForeignExchange(key=Config.keys.alphaVantageApi) data, meta_data = cc.get_currency_exchange_intraday(from_currency='BTC', to_currency='USD')
def sql_grabber_and_trendline_generator(): connection = pymysql.connect(host="localhost", user="******", password="******", db="forextrade") b = 1 print("Enter a start point for the bottom trend line") userchoice = float( input('Type start point here for the bottom trend line--> ')) global newuser newuser = userchoice - 1.6000 print(newuser) print("Enter a start point for the top trend line") userchoice2 = float( input('Type start point here for the top trend line--> ')) global newuser2 newuser2 = userchoice2 print(newuser2) while b == 1: for i in range(30): api_key = '1456af4c4704e5e6bd4b60c30094b56b-32c375f91dc677c9fce0916d50811d4f' cc = ForeignExchange(key=api_key) global data data, _ = cc.get_currency_exchange_intraday(from_symbol='EUR', to_symbol='USD', interval="1min", outputsize='compact') converteddata = str(data) global cursor connection = pymysql.connect(host="localhost", user="******", password="******", db="forextrade") cursor = connection.cursor() sql3 = "insert into testtoptrendline(testtoptrendlinedata) values (%s)" sql4 = "insert into testbottomtrendline(testbottomtrendlinedata) values (%s)" sql5 = "insert into testtimeprice(testimedata) values (substring(%s from 10794 for 19))" sql6 = "insert into testcloseprice(testclosedata) values (substring(%s from 10892 for 6))" sql7 = "insert into testopenprice(testopendata) values (substring(%s from 10829 for 6))" sql8 = "select testclosedata from testcloseprice order by id desc limit 1" sql12 = "select testtoptrendlinedata from testtoptrendline order by id desc limit 1" sql13 = "insert into testtriggerz(testanswer) values (%s)" sql10 = "select testopendata from testopenprice order by id desc limit 1" newuser = newuser + 0.0264 newuser2 = newuser2 cursor.execute(sql4, newuser) cursor.execute(sql3, newuser2) cursor.execute(sql5, converteddata) cursor.execute(sql6, converteddata) cursor.execute(sql7, converteddata) print("insert successful") connection.commit() cursor.execute(sql8) cursor.execute(sql10) cursor.execute(sql12) cursor.execute(sql13) cursor.execute() if cursor.execute(sql8) >= cursor.execute(sql3): print("closing price is above top trend line") elif cursor.execute(sql8) <= cursor.execute(sql3): AAAAAAAAAAAAAAAAAAAA print("1 cycle done") time.sleep(600) continue
def get_HKD_data(): fx = ForeignExchange(key=api_key, output_format='pandas') hkd_data, meta_data = fx.get_currency_exchange_intraday( 'HKD', 'CNY', '1min', outputsize='compact') return hkd_data
def sql_grabber_and_trendline_generator(runtime): _runtime = runtime global connection b = 1 print("Enter a start point for the bottom trend line") userchoice = float( input('Type start point here for the bottom trend line--> ')) global newuser newuser = userchoice print(newuser) print("Enter a start point for the top trend line") userchoice2 = float( input('Type start point here for the top trend line--> ')) global newuser2 newuser2 = userchoice2 print(newuser2) belowTrendline = False aboveTrendline = False while b == 1: for i in range(_runtime): api_key = '1456af4c4704e5e6bd4b60c30094b56b-32c375f91dc677c9fce0916d50811d4f' cc = ForeignExchange(key=api_key) global data data, _ = cc.get_currency_exchange_intraday(from_symbol='EUR', to_symbol='USD', interval="1min", outputsize='compact') global converteddata converteddata = str(data) print(converteddata) global connection global cursor connection = pymysql.connect(host="localhost", user="******", password="******", db="tyler_trade2") cursor = connection.cursor() sql3 = "insert into usd_eur_toptrendline(toptrendlinedata) values (%s)" sql4 = "insert into usd_eur_bottomtrendline(bottomtrendlinedata) values (%s)" sql5 = "insert into usd_eur_timestamp(timestampdata) values (substring(%s from 10794 for 19))" sql6 = "insert into usd_eur_closingprice(closepricedata) values (substring(%s from 10892 for 6))" sql7 = "insert into usd_eur_openingprice(openpricedata) values (substring(%s from 10829 for 6))" print("insert successful") newuser = newuser + 0.00001 newuser2 = newuser2 + 0.00001 cursor.execute(sql4, newuser) connection.commit() cursor.execute(sql3, newuser2) connection.commit() cursor.execute(sql5, converteddata) connection.commit() cursor.execute(sql6, converteddata) connection.commit() cursor.execute(sql7, converteddata) connection.commit() belowTrendline = emailNotifBottomTrendline(sql6, sql7, sql4, belowTrendline) aboveTrendline = emailNotifTopTrendline(sql6, sql7, sql3, aboveTrendline) time.sleep(60) print("1 cycle done") time.sleep(600) continue
from alpha_vantage.foreignexchange import ForeignExchange import time import pymysql import smtplib api_key = '1456af4c4704e5e6bd4b60c30094b56b-32c375f91dc677c9fce0916d50811d4f' cc = ForeignExchange(key=api_key) global data data, _ = cc.get_currency_exchange_intraday(from_symbol='EUR', to_symbol='USD', interval="1min", outputsize='compact') global converteddata converteddata = str(data) print(converteddata) def sql_grabber_and_trendline_generator(runtime): _runtime = runtime global connection b = 1 print("Enter a start point for the bottom trend line") userchoice = float( input('Type start point here for the bottom trend line--> ')) global newuser newuser = userchoice print(newuser)
dfm = pd.DataFrame() dfw = pd.DataFrame() dfd = pd.DataFrame() if dfm.empty: dfm, meta_data = cc.get_currency_exchange_monthly(from_symbol='EUR',to_symbol='USD', outputsize='full') if dfw.empty: dfw, meta_data = cc.get_currency_exchange_weekly(from_symbol='EUR',to_symbol='USD', outputsize='full') if dfd.empty: dfd, meta_data = cc.get_currency_exchange_daily(from_symbol='EUR',to_symbol='USD', outputsize='full') df60, meta_data = cc.get_currency_exchange_intraday(from_symbol='EUR',to_symbol='USD',interval='60min', outputsize='full') def clean_Columns(df): if 'errorslope' not in df.columns: df.reset_index(inplace=True) #reset index to get timestamp out df.columns = ['date','open','high','low','close'] #Make sure column names are legit df['index'] = np.arange(len(df)) #create an index df['hilow_median'] = df[['high', 'low']].median(axis=1) return df #%% end of cell begining of new #Cleanup columns clean_Columns(dfm) clean_Columns(dfw) clean_Columns(dfd) #clean_Columns(df60)
from alpha_vantage.timeseries import TimeSeries from alpha_vantage import foreignexchange from alpha_vantage.foreignexchange import ForeignExchange from pandas import DataFrame as df #ts = TimeSeries(key='G8L62BYFX5JJH9QX', retries=10, output_format='pandas', indexing_type='date') # Get json object with the intraday data and another with the call's metadata #foreign = ForeignExchange(function='CURRENCY_EXCHANGE_RATE', from_currency='BTC', to_currency='USD', key='G8L62BYFX5JJH9QX' ) foreign2 = ForeignExchange(key='G8L62BYFX5JJH9QX', retries=10, output_format='pandas') foreign_data, meta_data = foreign2.get_currency_exchange_intraday( from_symbol='CAN', to_symbol='USD') #data, meta_data = ts.get_intraday(symbol='DJI',interval='1min', outputsize='full') print(foreign_data[0][99:])
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
plt.style.use('fivethirtyeight') from datetime import datetime date=str(datetime.now().strftime('%d-%m-%Y')) time = str (datetime.now().strftime('%H:%M:%S')) year = int(datetime.now().strftime('%Y')) month = int(datetime.now().strftime('%m')) day = int(datetime.now().strftime('%d')) #Get the stock quote from alpha_vantage.foreignexchange import ForeignExchange import matplotlib.pyplot as plt cur1 = 'EUR' cur2 = 'USD' fx = ForeignExchange(key="ALPHAVANTAGE_API_KEY", output_format='pandas') df, meta_data = fx.get_currency_exchange_intraday(cur1, cur2, '60min', 'full') df=df.iloc[::-1] #Create new dataframe with only the 'Close column' data = df.filter(['4. close']) #Convert the dataframe to a numpy array dataset = data.values #Get the number of rows to train the model on training_data_len = math.ceil(len(dataset)* .8) training_data_len #Scale the data scaler = MinMaxScaler(feature_range=(0,1)) scaled_data = scaler.fit_transform(dataset)
import pandas as pd import matplotlib.pyplot as plt from alpha_vantage.foreignexchange import ForeignExchange #APIs to use - Key & URL - Only need 1 usually api_key = 'M83XDO2TK8UTLUDB' API_URL = "https://www.alphavantage.co/query" #Retrieving data cc = ForeignExchange(key=api_key, output_format='pandas') data, meta_data = cc.get_currency_exchange_intraday(from_symbol='EUR', to_symbol='GBP') #Save data to CSV file data.to_csv('EUR-GBP.csv') #Give the console something to display print(data) #Plotting data to graph data['4. close'].plot() plt.title('Intraday EUR/GBP') plt.show() #Very cool, can dump to JSON file, works fine, cannot convert to pandas # i = 1 # while i == 1: # data = { # "function": "FX_INTRADAY", # "from_symbol": "EUR", # "to_symbol": "GBP", # "interval": "5min",
from alpha_vantage.foreignexchange import ForeignExchange import pandas as pd from alpha_vantage.techindicators import TechIndicators import matplotlib.pyplot as plt from pprint import pprint import time import pymysql import numpy as np import matplotlib.dates as mdates from itertools import count from matplotlib.animation import FuncAnimation plt.style.use("fivethirtyeight") api_key = '1456af4c4704e5e6bd4b60c30094b56b-32c375f91dc677c9fce0916d50811d4f' cc = ForeignExchange(key=api_key) data, _ = cc.get_currency_exchange_intraday(from_symbol='EUR', to_symbol='USD', interval="1min", outputsize='compact') converteddata = str(data) connection = pymysql.connect(host="localhost", user="******", password="******", db="forextrade") cursor = connection.cursor() # sql5 = "insert into timeprice(timedata) values (substring(%s from 10794 for 19))" # sql6 = "insert into closeprice(closedata) values (substring(%s from 10892 for 6))" # sql7 = "insert into openprice(opendata) values (substring(%s from 10829 for 6))" sql8 = "select closedata from closeprice" sql9 = "select timedata from timeprice" sql10 = "select opendata from openprice"
import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates from functools import reduce # takes function as argument from alpha_vantage.foreignexchange import ForeignExchange import time alpha_key = 'VSCB9AMAH2RJVBV1' fx = ForeignExchange(key=alpha_key, output_format='pandas') df, meta_data = fx.get_currency_exchange_intraday('EUR', 'USD', '1min', 'full') print(df['4. close']) avg_price = df['4. close'] pattern_arr = [] #array of patterns created from points (see path_store) perf_arr = [] #array of future outcomes of patterns in pattern_arr pattern_for_rec_arr = [] #current pattern preds = [] #predictions for current pattern def per_change(start, curr): try: x = ((float(curr) - start) / abs(start)) * 100 if (x == 0.0): return 0.000000001 else: return x except Exception as e: print(str(e)) return 0.0001
from alpha_vantage.foreignexchange import ForeignExchange app = ForeignExchange(output_format='pandas') eurusd = app.get_currency_exchange_intraday('EUR', 'USD') print(eurusd[0]) print(eurusd[0]['2020-04-03']) #Narrow output to specific date
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