示例#1
0
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")
示例#2
0
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
示例#3
0
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
示例#4
0
文件: test_V1.py 项目: grantxx/Spyder
dfd = pd.DataFrame()


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


if dfm.empty:
    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')