Ejemplo n.º 1
0
def available_currencies_as_list():
    """
    This function retrieves a listing with all the available currencies with indexed currency crosses in order to
    get to know which are the available currencies. The currencies listed in this function, so on, can be used to
    search currency crosses and used the retrieved data to get historical data of those currency crosses, so to
    determine which is the value of one base currency in the second currency.

    Returns:
        :obj:`list` - available_currencies:
            The resulting :obj:`list` contains all the available currencies with currency crosses being either the base
            or the second value of the cross, as listed in Investing.com.

            In case the listing was successfully retrieved, the :obj:`list` will look like::

                available_currencies = [
                    'AED', 'AFN', 'ALL', 'AMD', 'ANG', ...
                ]

    Raises:
        IndexError: raised if `currency_crosses.csv` file was unavailable or not found.
    """

    resource_package = 'investpy'
    resource_path = '/'.join(
        ('resources', 'currency_crosses', 'currency_crosses.csv'))
    if pkg_resources.resource_exists(resource_package, resource_path):
        currency_crosses = pd.read_csv(
            pkg_resources.resource_filename(resource_package, resource_path))
    else:
        currency_crosses = retrieve_currency_crosses(test_mode=False)

    if currency_crosses is None:
        raise IOError(
            "ERR#0050: currency_crosses not found or unable to retrieve.")
    else:
        return np.unique(currency_crosses['base'].unique().tolist() +
                         currency_crosses['second'].unique().tolist())
Ejemplo n.º 2
0
def test_currency_crosses_errors():
    """
    This function raises errors on currency cross retrieval functions
    """

    try:
        retrieve_currency_crosses(test_mode=None)
    except:
        pass

    params = [{
        'base': ['error'],
        'second': None
    }, {
        'base': None,
        'second': ['error']
    }, {
        'base': 'error',
        'second': None
    }, {
        'base': 'EUR',
        'second': 'error'
    }, {
        'base': None,
        'second': 'error'
    }, {
        'base': 'EUR',
        'second': 'EUR',
    }]

    for param in params:
        try:
            investpy.get_currency_crosses(base=param['base'],
                                          second=param['second'])
        except:
            pass

        try:
            investpy.get_currency_crosses_list(base=param['base'],
                                               second=param['second'])
        except:
            pass

    params = [
        {
            'base': ['error'],
            'second': None,
            'columns': None,
            'as_json': False
        },
        {
            'base': None,
            'second': ['error'],
            'columns': None,
            'as_json': False
        },
        {
            'base': None,
            'second': None,
            'columns': None,
            'as_json': 'error'
        },
        {
            'base': None,
            'second': None,
            'columns': 'error',
            'as_json': False
        },
        {
            'base': None,
            'second': None,
            'columns': ['error'],
            'as_json': False
        },
        {
            'base': 'error',
            'second': None,
            'columns': None,
            'as_json': False
        },
        {
            'base': 'EUR',
            'second': 'error',
            'columns': None,
            'as_json': False
        },
        {
            'base': None,
            'second': 'error',
            'columns': None,
            'as_json': False
        },
        {
            'base': 'EUR',
            'second': 'Eur',
            'columns': None,
            'as_json': False
        },
    ]

    for param in params:
        try:
            investpy.get_currency_crosses_dict(base=param['base'],
                                               second=param['second'],
                                               columns=param['columns'],
                                               as_json=param['as_json'])
        except:
            pass

    params = [
        {
            'currency_cross': None,
            'as_json': False,
            'order': 'ascending',
            'debug': False
        },
        {
            'currency_cross': ['error'],
            'as_json': False,
            'order': 'ascending',
            'debug': False
        },
        {
            'currency_cross': 'EUR/USD',
            'as_json': 'error',
            'order': 'ascending',
            'debug': False
        },
        {
            'currency_cross': 'EUR/USD',
            'as_json': False,
            'order': 'error',
            'debug': False
        },
        {
            'currency_cross': 'EUR/USD',
            'as_json': False,
            'order': 'ascending',
            'debug': 'error'
        },
        {
            'currency_cross': 'error/error',
            'as_json': False,
            'order': 'ascending',
            'debug': False
        },
        {
            'currency_cross': 'EUR/USD',
            'as_json': False,
            'order': 'ascending',
            'debug': False
        },
    ]

    for param in params:
        try:
            investpy.get_currency_cross_recent_data(
                currency_cross=param['currency_cross'],
                as_json=param['as_json'],
                order=param['order'],
                debug=param['debug'])
        except:
            pass

    params = [
        {
            'currency_cross': None,
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': False
        },
        {
            'currency_cross': ['error'],
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': False
        },
        {
            'currency_cross': 'EUR/USD',
            'from_date': 'error',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': False
        },
        {
            'currency_cross': 'EUR/USD',
            'from_date': '01/01/2018',
            'to_date': 'error',
            'as_json': False,
            'order': 'ascending',
            'debug': False
        },
        {
            'currency_cross': 'EUR/USD',
            'from_date': '01/01/2018',
            'to_date': '01/01/2017',
            'as_json': False,
            'order': 'ascending',
            'debug': False
        },
        {
            'currency_cross': 'EUR/USD',
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': 'error',
            'order': 'ascending',
            'debug': False
        },
        {
            'currency_cross': 'EUR/USD',
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'error',
            'debug': False
        },
        {
            'currency_cross': 'EUR/USD',
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': 'error'
        },
        {
            'currency_cross': 'error/error',
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': False
        },
        {
            'currency_cross': 'EUR/USD',
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': False
        },
    ]

    for param in params:
        try:
            investpy.get_currency_cross_historical_data(
                currency_cross=param['currency_cross'],
                from_date=param['from_date'],
                to_date=param['to_date'],
                as_json=param['as_json'],
                order=param['order'],
                debug=param['debug'])
        except:
            pass

    params = [
        {
            'by': None,
            'value': 'EUR',
        },
        {
            'by': ['error'],
            'value': 'EUR',
        },
        {
            'by': 'error',
            'value': 'EUR',
        },
        {
            'by': 'base',
            'value': None,
        },
        {
            'by': 'base',
            'value': ['error'],
        },
        {
            'by': 'base',
            'value': 'error',
        },
    ]

    for param in params:
        try:
            investpy.search_currency_crosses(by=param['by'],
                                             value=param['value'])
        except:
            pass
Ejemplo n.º 3
0
def test_investpy_currency_crosses():
    """
    This function checks that currency cross data retrieval functions listed in investpy work properly.
    """

    params = [
        {
            'base': None,
            'second': None,
        },
        {
            'base': 'EUR',
            'second': None,
        },
        {
            'base': None,
            'second': 'EUR',
        },
        {
            'base': 'EUR',
            'second': 'USD',
        },
    ]

    for param in params:
        investpy.get_currency_crosses(base=param['base'],
                                      second=param['second'])
        investpy.get_currency_crosses_list(base=param['base'],
                                           second=param['second'])

    params = [
        {
            'base': None,
            'second': None,
            'columns': None,
            'as_json': True
        },
        {
            'base': None,
            'second': None,
            'columns': None,
            'as_json': False
        },
        {
            'base': 'EUR',
            'second': None,
            'columns': None,
            'as_json': True
        },
        {
            'base': 'EUR',
            'second': None,
            'columns': None,
            'as_json': False
        },
        {
            'base': None,
            'second': 'USD',
            'columns': None,
            'as_json': True
        },
        {
            'base': None,
            'second': 'USD',
            'columns': None,
            'as_json': False
        },
        {
            'base': 'EUR',
            'second': 'USD',
            'columns': None,
            'as_json': True
        },
        {
            'base': 'EUR',
            'second': 'USD',
            'columns': None,
            'as_json': False
        },
        {
            'base': 'EUR',
            'second': 'USD',
            'columns': ['name', 'full_name'],
            'as_json': False
        },
    ]

    for param in params:
        investpy.get_currency_crosses_dict(base=param['base'],
                                           second=param['second'],
                                           columns=param['columns'],
                                           as_json=param['as_json'])

    investpy.get_available_currencies()

    params = [
        {
            'currency_cross': 'EUR/USD',
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': True,
            'order': 'ascending',
            'debug': True
        },
        {
            'currency_cross': 'EUR/USD',
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'descending',
            'debug': False
        },
    ]

    for param in params:
        investpy.get_currency_cross_recent_data(
            currency_cross=param['currency_cross'],
            as_json=param['as_json'],
            order=param['order'],
            debug=param['debug'])

        investpy.get_currency_cross_historical_data(
            currency_cross=param['currency_cross'],
            from_date=param['from_date'],
            to_date=param['to_date'],
            as_json=param['as_json'],
            order=param['order'],
            debug=param['debug'])

    investpy.search_currency_crosses(by='base', value='EUR')

    retrieve_currency_crosses(test_mode=True)
    retrieve_currency_cross_continents()
Ejemplo n.º 4
0
def currency_crosses_as_df(base=None, second=None):
    """
    This function retrieves all the available currency crosses from Investing.com and returns them as a
    :obj:`pandas.DataFrame`, which contains not just the currency crosses names, but all the fields contained on
    the currency_crosses file. Note that the filtering params are both base and second, which mean the base and the
    second currency of the currency cross, for example, in the currency cross `EUR/USD` the base currency is EUR and
    the second currency is USD. These are optional parameters, so specifying one of them means that all the currency
    crosses where the introduced currency is either base or second will be returned; if both are specified,
    just the introduced currency cross will be returned if it exists. All the available currency crosses can be found
    at: https://es.investing.com/currencies/

    Args:
        base (:obj:`str`, optional):
            symbol of the base currency of the currency cross, this will return a :obj:`pandas.DataFrame` containing
            all the currency crosses where the base currency matches the introduced one.
        second (:obj:`str`):
            symbol of the second currency of the currency cross, this will return a :obj:`pandas.DataFrame` containing
            all the currency crosses where the second currency matches the introduced one.

    Returns:
        :obj:`pandas.DataFrame` - currency_crosses_df:
            The resulting :obj:`pandas.DataFrame` contains all the currency crosses basic information retrieved from
            Investing.com, some of which is not useful for the user, but for the inner package functions, such as the
            `tag` or `id` fields.

            In case the information was successfully retrieved, the resulting :obj:`pandas.DataFrame` will look like::

                name | full_name | tag | id | base | second | base_name | second_name
                -----|-----------|-----|----|------|--------|-----------|-------------
                xxxx | xxxxxxxxx | xxx | xx | xxxx | xxxxxx | xxxxxxxxx | xxxxxxxxxxx

            Just like `investpy.currency_crosses.retrieve_currencies()`, the output of this function is a
            :obj:`pandas.DataFrame` containing all the currency crosses as indexed in Investing.com, but instead of
            scraping the web in order to retrieve them and then generating the CSV file, this function just reads it
            and loads it into a :obj:`pandas.DataFrame`.

    Raises:
        IOError: raised if currency_crosses retrieval failed, both for missing file or empty file.
    """

    if base is not None and not isinstance(base, str):
        raise ValueError(
            "ERR#0049: specified base currency value is not valid.")

    if second is not None and not isinstance(second, str):
        raise ValueError(
            "ERR#0051: specified second currency value is not valid.")

    resource_package = 'investpy'
    resource_path = '/'.join(
        ('resources', 'currency_crosses', 'currency_crosses.csv'))
    if pkg_resources.resource_exists(resource_package, resource_path):
        currency_crosses = pd.read_csv(
            pkg_resources.resource_filename(resource_package, resource_path))
    else:
        currency_crosses = retrieve_currency_crosses(test_mode=False)

    if currency_crosses is None:
        raise IOError(
            "ERR#0050: currency_crosses not found or unable to retrieve.")

    available_currencies = available_currencies_as_list()

    if base is None and second is None:
        currency_crosses.reset_index(drop=True, inplace=True)

        return currency_crosses
    elif base is not None:
        if unidecode.unidecode(base.upper()) in available_currencies:
            if second is not None:
                if unidecode.unidecode(second.upper()) in available_currencies:
                    currency_crosses = currency_crosses[
                        (currency_crosses['base'] == unidecode.unidecode(
                            base.upper()))
                        & (currency_crosses['second'] == unidecode.unidecode(
                            second.upper()))]
                    currency_crosses.reset_index(drop=True, inplace=True)

                    if len(currency_crosses) > 0:
                        return currency_crosses
                    else:
                        raise ValueError(
                            "ERR#0054: the introduced currency cross " +
                            str(base) + "/" + str(second) +
                            " does not exists.")
                else:
                    raise ValueError("ERR#0053: the introduced currency " +
                                     str(second) + " does not exists.")
            else:
                currency_crosses = currency_crosses[currency_crosses['base'] ==
                                                    unidecode.unidecode(
                                                        base.upper())]
                currency_crosses.reset_index(drop=True, inplace=True)

                return currency_crosses
        else:
            raise ValueError("ERR#0053: the introduced currency " + str(base) +
                             " does not exists.")
    elif second is not None:
        if unidecode.unidecode(second.upper()) in available_currencies:
            currency_crosses = currency_crosses[currency_crosses['second'] ==
                                                unidecode.unidecode(
                                                    second.upper())]
            currency_crosses.reset_index(drop=True, inplace=True)

            return currency_crosses
        else:
            raise ValueError("ERR#0053: the introduced currency " +
                             str(second) + " does not exists.")
Ejemplo n.º 5
0
def currency_crosses_as_dict(base=None,
                             second=None,
                             columns=None,
                             as_json=False):
    """
    This function retrieves all the available currency crosses from Investing.com and returns them as a
    :obj:`dict`, which contains not just the currency crosses names, but all the fields contained on
    the currency_crosses file is columns is None, otherwise, just the specified column values will be returned. Note
    that the filtering params are both base and second, which mean the base and the second currency of the currency
    cross, for example, in the currency cross `EUR/USD` the base currency is EUR and the second currency is USD. These
    are optional parameters, so specifying one of them means that all the currency crosses where the introduced
    currency is either base or second will be returned; if both are specified, just the introduced currency cross will
    be returned if it exists. All the available currency crosses can be found at: https://es.investing.com/currencies/

    Args:
        base (:obj:`str`, optional):
            symbol of the base currency of the currency cross, this will return a :obj:`pandas.DataFrame` containing
            all the currency crosses where the base currency matches the introduced one.
        second (:obj:`str`):
            symbol of the second currency of the currency cross, this will return a :obj:`pandas.DataFrame` containing
            all the currency crosses where the second currency matches the introduced one.
        columns (:obj:`list`, optional):
            names of the columns of the equity data to retrieve <name, full_name, tag, id, base, base_name,
            second, second_name>
        as_json (:obj:`bool`, optional):
            value to determine the format of the output data which can either be a :obj:`dict` or a :obj:`json`.

    Returns:
        :obj:`dict` or :obj:`json` - currency_crosses_dict:
            The resulting :obj:`dict` contains the retrieved data if found, if not, the corresponding
            fields are filled with `None` values.

            In case the information was successfully retrieved, the :obj:`dict` will look like::

                {
                    'name': name,
                    'full_name': full_name,
                    'tag': tag,
                    'id': id,
                    'base': base,
                    'base_name': base_name,
                    'second': second,
                    'second_name': second_name
                }

    Raises:
        ValueError: raised when any of the input arguments is not valid.
       IOError: raised if currency_crosses retrieval failed, both for missing file or empty file.
    """

    if base is not None and not isinstance(base, str):
        raise ValueError(
            "ERR#0049: specified base currency value is not valid.")

    if second is not None and not isinstance(second, str):
        raise ValueError(
            "ERR#0051: specified second currency value is not valid.")

    if not isinstance(as_json, bool):
        raise ValueError(
            "ERR#0002: as_json argument can just be True or False, bool type.")

    resource_package = 'investpy'
    resource_path = '/'.join(
        ('resources', 'currency_crosses', 'currency_crosses.csv'))
    if pkg_resources.resource_exists(resource_package, resource_path):
        currency_crosses = pd.read_csv(
            pkg_resources.resource_filename(resource_package, resource_path))
    else:
        currency_crosses = retrieve_currency_crosses(test_mode=False)

    if currency_crosses is None:
        raise IOError(
            "ERR#0050: currency_crosses not found or unable to retrieve.")

    available_currencies = available_currencies_as_list()

    if columns is None:
        columns = currency_crosses.columns.tolist()
    else:
        if not isinstance(columns, list):
            raise ValueError(
                "ERR#0020: specified columns argument is not a list, it can just be list type."
            )

    if not all(column in currency_crosses.columns.tolist()
               for column in columns):
        raise ValueError(
            "ERR#0021: specified columns does not exist, available columns are "
            "<name, full_name, tag, id, base, base_name, second, second_name>")

    if base is None and second is None:
        currency_crosses.reset_index(drop=True, inplace=True)

        if as_json:
            return json.dumps(
                currency_crosses[columns].to_dict(orient='records'))
        else:
            return currency_crosses[columns].to_dict(orient='records')
    elif base is not None:
        if unidecode.unidecode(base.upper()) in available_currencies:
            if second is not None:
                if unidecode.unidecode(second.upper()) in available_currencies:
                    currency_crosses = currency_crosses[
                        (currency_crosses['base'] == unidecode.unidecode(
                            base.upper()))
                        & (currency_crosses['second'] == unidecode.unidecode(
                            second.upper()))]
                    currency_crosses.reset_index(drop=True, inplace=True)

                    if len(currency_crosses) > 0:
                        if as_json:
                            return json.dumps(
                                currency_crosses[columns].to_dict(
                                    orient='records'))
                        else:
                            return currency_crosses[columns].to_dict(
                                orient='records')
                    else:
                        raise ValueError(
                            "ERR#0054: the introduced currency cross " +
                            str(base) + "/" + str(second) +
                            " does not exists.")
                else:
                    raise ValueError("ERR#0053: the introduced currency " +
                                     str(second) + " does not exists.")
            else:
                currency_crosses = currency_crosses[currency_crosses['base'] ==
                                                    unidecode.unidecode(
                                                        base.upper())]
                currency_crosses.reset_index(drop=True, inplace=True)

                if as_json:
                    return json.dumps(
                        currency_crosses[columns].to_dict(orient='records'))
                else:
                    return currency_crosses[columns].to_dict(orient='records')
        else:
            raise ValueError("ERR#0053: the introduced currency " + str(base) +
                             " does not exists.")
    elif second is not None:
        if unidecode.unidecode(second.upper()) in available_currencies:
            currency_crosses = currency_crosses[currency_crosses['second'] ==
                                                unidecode.unidecode(
                                                    second.upper())]
            currency_crosses.reset_index(drop=True, inplace=True)

            if as_json:
                return json.dumps(
                    currency_crosses[columns].to_dict(orient='records'))
            else:
                return currency_crosses[columns].to_dict(orient='records')
        else:
            raise ValueError("ERR#0053: the introduced currency " +
                             str(second) + " does not exists.")
Ejemplo n.º 6
0
def currency_crosses_as_list(base=None, second=None):
    """
    This function retrieves all the available currency crosses from Investing.com and returns them as a
    :obj:`dict`, which contains not just the currency crosses names, but all the fields contained on
    the currency_crosses file is columns is None, otherwise, just the specified column values will be returned. Note
    that the filtering params are both base and second, which mean the base and the second currency of the currency
    cross, for example, in the currency cross `EUR/USD` the base currency is EUR and the second currency is USD. These
    are optional parameters, so specifying one of them means that all the currency crosses where the introduced
    currency is either base or second will be returned; if both are specified, just the introduced currency cross will
    be returned if it exists. All the available currency crosses can be found at: https://es.investing.com/currencies/

    Args:
        base (:obj:`str`, optional):
            symbol of the base currency of the currency cross, this will return a :obj:`pandas.DataFrame` containing
            all the currency crosses where the base currency matches the introduced one.
        second (:obj:`str`):
            symbol of the second currency of the currency cross, this will return a :obj:`pandas.DataFrame` containing
            all the currency crosses where the second currency matches the introduced one.

    Returns:
        :obj:`list` - currency_crosses_list:
            The resulting :obj:`list` contains the retrieved data from the `currency_crosses.csv` file, which is
            a listing of the names of the currency crosses listed in Investing.com, which is the input for data
            retrieval functions as the name of the currency cross to retrieve data from needs to be specified.

            In case the listing was successfully retrieved, the :obj:`list` will look like::

                currency_crosses_list = [
                    'USD/BRLT', 'CAD/CHF', 'CHF/CAD', 'CAD/PLN', 'PLN/CAD', ...
                ]

    Raises:
        IOError: raised if currency_crosses retrieval failed, both for missing file or empty file.
    """

    if base is not None and not isinstance(base, str):
        raise ValueError(
            "ERR#0049: specified base currency value is not valid.")

    if second is not None and not isinstance(second, str):
        raise ValueError(
            "ERR#0051: specified second currency value is not valid.")

    resource_package = 'investpy'
    resource_path = '/'.join(
        ('resources', 'currency_crosses', 'currency_crosses.csv'))
    if pkg_resources.resource_exists(resource_package, resource_path):
        currency_crosses = pd.read_csv(
            pkg_resources.resource_filename(resource_package, resource_path))
    else:
        currency_crosses = retrieve_currency_crosses(test_mode=False)

    if currency_crosses is None:
        raise IOError(
            "ERR#0050: currency_crosses not found or unable to retrieve.")

    available_currencies = available_currencies_as_list()

    if base is None and second is None:
        currency_crosses.reset_index(drop=True, inplace=True)

        return currency_crosses['name'].tolist()
    elif base is not None:
        if unidecode.unidecode(base.upper()) in available_currencies:
            if second is not None:
                if unidecode.unidecode(second.upper()) in available_currencies:
                    currency_crosses = currency_crosses[
                        (currency_crosses['base'] == unidecode.unidecode(
                            base.upper()))
                        & (currency_crosses['second'] == unidecode.unidecode(
                            second.upper()))]
                    currency_crosses.reset_index(drop=True, inplace=True)

                    if len(currency_crosses) > 0:
                        return currency_crosses['name'].tolist()
                    else:
                        raise ValueError(
                            "ERR#0054: the introduced currency cross " +
                            str(base) + "/" + str(second) +
                            " does not exists.")
                else:
                    raise ValueError("ERR#0053: the introduced currency " +
                                     str(second) + " does not exists.")
            else:
                currency_crosses = currency_crosses[currency_crosses['base'] ==
                                                    unidecode.unidecode(
                                                        base.upper())]
                currency_crosses.reset_index(drop=True, inplace=True)

                return currency_crosses['name'].tolist()
        else:
            raise ValueError("ERR#0053: the introduced currency " + str(base) +
                             " does not exists.")
    elif second is not None:
        if unidecode.unidecode(second.upper()) in available_currencies:
            currency_crosses = currency_crosses[currency_crosses['second'] ==
                                                unidecode.unidecode(
                                                    second.upper())]
            currency_crosses.reset_index(drop=True, inplace=True)

            return currency_crosses['name'].tolist()
        else:
            raise ValueError("ERR#0053: the introduced currency " +
                             str(second) + " does not exists.")