Exemplo n.º 1
0
def indices_as_df(country=None):
    """
    This function retrieves all the available `indices` from Investing.com as previously listed in investpy, and
    returns them as a :obj:`pandas.DataFrame` with all the information of every available index. If the country
    filtering is applied, just the indices from the introduced country are going to be returned.
    All the available indices can be found at: https://es.investing.com/indices/world-indices and at
    https://es.investing.com/indices/world-indices, since both world and global indices are retrieved.

    Args:
        country (:obj:`str`, optional): name of the country to retrieve all its available indices from.

    Returns:
        :obj:`pandas.DataFrame` - indices_df:
            The resulting :obj:`pandas.DataFrame` contains all the indices information retrieved from Investing.com,
            as previously listed by investpy.

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

                country | name | full_name | symbol | currency | class | market
                --------|------|-----------|--------|----------|-------|--------
                xxxxxxx | xxxx | xxxxxxxxx | xxxxxx | xxxxxxxx | xxxxx | xxxxxx

    Raises:
        ValueError: raised if any of the introduced parameters is missing or errored.
        IOError: raised if the indices file from `investpy` is missing or errored.
    """

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

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

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

    indices.drop(columns=['tag', 'id'], inplace=True)

    if country is None:
        indices.reset_index(drop=True, inplace=True)
        return indices
    elif unidecode.unidecode(country.lower()) in index_countries_as_list():
        indices = indices[indices['country'] == unidecode.unidecode(
            country.lower())]
        indices.reset_index(drop=True, inplace=True)
        return indices
Exemplo n.º 2
0
def indices_as_list(country=None):
    """
    This function retrieves all the available `indices` from Investing.com as previously listed in investpy, and
    returns them as a :obj:`list` with the names of every available index. If the country filtering is applied, just
    the indices from the introduced country are going to be returned.
    All the available indices can be found at: https://es.investing.com/indices/world-indices and at
    https://es.investing.com/indices/world-indices, since both world and global indices are retrieved.

    Args:
        country (:obj:`str`, optional): name of the country to retrieve all its available indices from.

    Returns:
        :obj:`list` - indices_list:
            The resulting :obj:`list` contains the retrieved data, which corresponds to the index names of
            every index listed in Investing.com.

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

                indices = ['S&P Merval', 'S&P Merval Argentina', 'S&P/BYMA Argentina General', ...]

    Raises:
        ValueError: raised when the introduced arguments are not correct.
        IOError: raised if the indices file from `investpy` is missing or errored.
    """

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

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

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

    indices.drop(columns=['tag', 'id'], inplace=True)

    if country is None:
        return indices['name'].tolist()
    elif unidecode.unidecode(country.lower()) in index_countries_as_list():
        return indices[indices['country'] == unidecode.unidecode(
            country.lower())]['name'].tolist()
Exemplo n.º 3
0
def test_indices_errors():
    """
    This function raises errors on index retrieval functions
    """

    try:
        retrieve_indices(test_mode=None)
    except:
        pass

    try:
        retrieve_index_countries(test_mode=None)
    except:
        pass

    try:
        retrieve_global_indices_countries(test_mode=None)
    except:
        pass

    params = [
        {
            'country': ['error']
        },
        {
            'country': 'error'
        },
    ]

    for param in params:
        try:
            investpy.get_indices(country=param['country'])
        except:
            pass

        try:
            investpy.get_indices_list(country=param['country'])
        except:
            pass

    params = [
        {
            'country': ['error'],
            'columns': None,
            'as_json': False
        },
        {
            'country': 'spain',
            'columns': None,
            'as_json': 'error'
        },
        {
            'country': 'spain',
            'columns': 0,
            'as_json': True
        },
        {
            'country': 'spain',
            'columns': ['error'],
            'as_json': False
        },
    ]

    for param in params:
        try:
            investpy.get_indices_dict(country=param['country'],
                                      columns=param['columns'],
                                      as_json=param['as_json'])
        except:
            pass

    params = [
        {
            'index': None,
            'country': 'spain',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': ['error'],
            'country': 'spain',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': None,
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'error',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'netherlands',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': ['error'],
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'spain',
            'as_json': 'error',
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'spain',
            'as_json': True,
            'order': 'error',
            'debug': True
        },
        {
            'index': 'error',
            'country': 'spain',
            'as_json': True,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': ['error'],
            'country': 'spain',
            'as_json': True,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'spain',
            'as_json': True,
            'order': 'ascending',
            'debug': 'error'
        },
    ]

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

    params = [
        {
            'index': None,
            'country': 'spain',
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'error',
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'netherlands',
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': None,
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': ['error'],
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'spain',
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': 'error',
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'spain',
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'error',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'spain',
            'from_date': 'error',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'spain',
            'from_date': '01/01/2019',
            'to_date': 'error',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'error',
            'country': 'spain',
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': ['error'],
            'country': 'spain',
            'from_date': '01/01/2018',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'spain',
            'from_date': '01/01/1998',
            'to_date': '01/01/2019',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'spain',
            'from_date': '01/01/2019',
            'to_date': '01/01/1998',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'spain',
            'from_date': '01/01/1900',
            'to_date': '01/01/1950',
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'index': 'ibex 35',
            'country': 'spain',
            'from_date': '01/01/2019',
            'to_date': '01/03/2019',
            'as_json': True,
            'order': 'ascending',
            'debug': 'error'
        },
    ]

    for param in params:
        try:
            investpy.get_index_historical_data(index=param['index'],
                                               country=param['country'],
                                               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': 'ibex',
        },
        {
            'by': ['error'],
            'value': 'ibex',
        },
        {
            'by': 'error',
            'value': 'ibex',
        },
        {
            'by': 'name',
            'value': None,
        },
        {
            'by': 'name',
            'value': ['error'],
        },
        {
            'by': 'name',
            'value': 'error',
        },
    ]

    for param in params:
        try:
            investpy.search_indices(by=param['by'], value=param['value'])
        except:
            pass
Exemplo n.º 4
0
def test_investpy_indices():
    """
    This function checks that index data retrieval functions listed in investpy work properly.
    """

    params = [
        {
            'country': 'spain',
        },
        {
            'country': None,
        },
    ]

    for param in params:
        investpy.get_indices(country=param['country'])
        investpy.get_indices_list(country=param['country'])

    params = [
        {
            'country': None,
            'columns': ['name', 'currency'],
            'as_json': True
        },
        {
            'country': None,
            'columns': ['name', 'currency'],
            'as_json': False
        },
        {
            'country': 'spain',
            'columns': ['name', 'currency'],
            'as_json': True
        },
        {
            'country': 'spain',
            'columns': ['name', 'currency'],
            'as_json': False
        },
        {
            'country': 'spain',
            'columns': None,
            'as_json': False
        },
    ]

    for param in params:
        investpy.get_indices_dict(country=param['country'],
                                  columns=param['columns'],
                                  as_json=param['as_json'])

    investpy.get_index_countries()

    params = [
        {
            'as_json': True,
            'order': 'ascending',
            'debug': False
        },
        {
            'as_json': False,
            'order': 'ascending',
            'debug': True
        },
        {
            'as_json': True,
            'order': 'descending',
            'debug': False
        },
        {
            'as_json': False,
            'order': 'descending',
            'debug': False
        },
    ]

    for param in params:
        investpy.get_index_recent_data(index='ibex 35',
                                       country='spain',
                                       as_json=param['as_json'],
                                       order=param['order'],
                                       debug=param['debug'])

        investpy.get_index_historical_data(index='ibex 35',
                                           country='spain',
                                           from_date='01/01/2018',
                                           to_date='01/01/2019',
                                           as_json=param['as_json'],
                                           order=param['order'],
                                           debug=param['debug'])

    investpy.search_indices(by='name', value='ibex')

    retrieve_indices(test_mode=True)
    retrieve_index_countries(test_mode=True)
    retrieve_global_indices_countries(test_mode=True)
Exemplo n.º 5
0
def indices_as_dict(country=None, columns=None, as_json=False):
    """
    This function retrieves all the available `indices` from Investing.com as previously listed in investpy, and
    returns them as a :obj:`dict` with all the information of every available index. If the country
    filtering is applied, just the indices from the introduced country are going to be returned. Additionally, the
    columns to retrieve data from can be specified as a parameter formatted as a :obj:`list`.
    All the available indices can be found at: https://es.investing.com/indices/world-indices and at
    https://es.investing.com/indices/world-indices, since both world and global indices are retrieved.

    Args:
        country (:obj:`str`, optional): name of the country to retrieve all its available indices from.
        columns (:obj:`list` of :obj:`str`, optional): description
            a :obj:`list` containing the column names from which the data is going to be retrieved.
        as_json (:obj:`bool`, optional): description
            value to determine the format of the output data (:obj:`dict` or :obj:`json`).

    Returns:
        :obj:`dict` or :obj:`json` - indices_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::

                {
                    'country': country,
                    'name': name,
                    'full_name': full_name,
                    'symbol': symbol,
                    'tag': tag,
                    'id': id,
                    'currency': currency
                }

    Raises:
        ValueError: raised when the introduced arguments are not correct.
        IOError: raised if the indices file from `investpy` is missing or errored.
    """

    if country is not None and not isinstance(country, str):
        raise ValueError("ERR#0025: specified country value 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', 'indices', 'indices.csv'))
    if pkg_resources.resource_exists(resource_package, resource_path):
        indices = pd.read_csv(
            pkg_resources.resource_filename(resource_package, resource_path))
    else:
        indices = retrieve_indices(test_mode=False)

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

    indices.drop(columns=['tag', 'id'], inplace=True)

    if columns is None:
        columns = indices.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 indices.columns.tolist() for column in columns):
        raise ValueError(
            "ERR#0023: specified columns does not exist, available columns are "
            "<country, name, full_name, symbol, currency, class, market>")

    if country is None:
        if as_json:
            return json.dumps(indices[columns].to_dict(orient='records'))
        else:
            return indices[columns].to_dict(orient='records')
    elif country in index_countries_as_list():
        if as_json:
            return json.dumps(
                indices[indices['country'] == unidecode.unidecode(
                    country.lower())][columns].to_dict(orient='records'))
        else:
            return indices[indices['country'] == unidecode.unidecode(
                country.lower())][columns].to_dict(orient='records')