Beispiel #1
0
def test_investpy_stocks():
    """
    This function checks that stock data retrieval functions listed in investpy work properly.
    """

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

    for param in params:
        investpy.get_stocks(country=param['country'])
        investpy.get_stocks_list(country=param['country'])

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

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

    investpy.get_stock_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_stock_recent_data(stock='BBVA',
                                       country='spain',
                                       as_json=param['as_json'],
                                       order=param['order'],
                                       debug=param['debug'])

        investpy.get_stock_historical_data(stock='BBVA',
                                           country='spain',
                                           from_date='01/01/1990',
                                           to_date='01/01/2019',
                                           as_json=param['as_json'],
                                           order=param['order'],
                                           debug=param['debug'])

    for value in ['spanish', 'english']:
        investpy.get_stock_company_profile(stock='BBVA',
                                           country='spain',
                                           language=value)

    investpy.get_stock_dividends(stock='BBVA', country='spain')

    investpy.search_stocks(by='name', value='BBVA')
Beispiel #2
0
def test_investpy_stocks():
    """
    This function checks that stock data retrieval functions listed in investpy work properly.
    """

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

    for param in params:
        investpy.get_stocks(country=param['country'])
        investpy.get_stocks_list(country=param['country'])

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

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

    investpy.get_stock_countries()

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

    for param in params:
        investpy.get_stock_recent_data(stock='BBVA',
                                       country='spain',
                                       as_json=param['as_json'],
                                       order=param['order'],
                                       interval='Daily')

        investpy.get_stock_historical_data(stock='BBVA',
                                           country='spain',
                                           from_date='01/01/1990',
                                           to_date='01/01/2019',
                                           as_json=param['as_json'],
                                           order=param['order'],
                                           interval='Daily')

    for value in ['spanish', 'english']:
        investpy.get_stock_company_profile(stock='BBVA',
                                           country='spain',
                                           language=value)

    params = [
        {
            'stock': 'bbva',
            'country': 'spain',
            'as_json': False
        },
        {
            'stock': 'bbva',
            'country': 'spain',
            'as_json': True
        },
        {
            'stock': 'HSBK',
            'country': 'kazakhstan',
            'as_json': False
        }
    ]

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

    params = [
        {
            'country': 'spain',
            'as_json': True,
            'n_results': 50
        },
        {
            'country': 'united states',
            'as_json': False,
            'n_results': 50
        },
        {
            'country': 'bosnia',
            'as_json': False,
            'n_results': 50
        },
        {
            'country': 'palestine',
            'as_json': False,
            'n_results': 50
        },
        {
            'country': 'dubai',
            'as_json': False,
            'n_results': 50
        },
        {
            'country': 'ivory coast',
            'as_json': False,
            'n_results': 50
        }
    ]

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

    params = [
        {
            'stock': 'bbva',
            'country': 'spain'
        },
        {
            'stock': 'entel',
            'country': 'chile'
        }
    ]

    for param in params:
        investpy.get_stock_dividends(stock=param['stock'], country=param['country'])

    params = [
        {
            'stock': 'bbva',
            'country': 'spain',
            'summary_type': 'balance_sheet',
            'period': 'annual'
        },
        {
            'stock': 'aapl',
            'country': 'united states',
            'summary_type': 'income_statement',
            'period': 'quarterly'
        },
        {
            'stock': 'barc',
            'country': 'united kingdom',
            'summary_type': 'cash_flow_statement',
            'period': 'annual'
        }
    ]

    for param in params:
        investpy.get_stock_financial_summary(stock=param['stock'],
                                             country=param['country'], 
                                             summary_type=param['summary_type'],
                                             period=param['period'])

    investpy.search_stocks(by='name', value='BBVA')
Beispiel #3
0
Datei: test.py Projekt: jklen/fin
df_aapl = investpy.get_stock_historical_data(stock='AAPL',
                                             country='United States',
                                             from_date='01/01/2010',
                                             to_date='01/01/2020')

df_fund = investpy.get_fund_historical_data(
    fund='bbva plan multiactivo moderado pp',
    country='spain',
    from_date='01/01/2010',
    to_date='01/01/2019')

df_bbva_etf = investpy.get_etf_recent_data(etf='bbva accion dj eurostoxx 50',
                                           country='spain')
etfs_ger = investpy.get_etfs_list(country='germany')

investpy.get_stock_countries()

#%% get finax tickers
from_date = '01/01/1990'
to_date = '21/03/2021'

search = investpy.search_quotes('FRCK')
df_frck = search[0].retrieve_historical_data(from_date=from_date,
                                             to_date=to_date)
#df_frck.columns = 'frck_' + df_frck.columns

search = investpy.search_quotes('XXSC')
df_xxsc = search[0].retrieve_historical_data(from_date=from_date,
                                             to_date=to_date)  # etf - xetra
#df_xxsc.columns = 'xxsc_' + df_xxsc.columns
def main():
    """
    Despliega un menú de opciones en la consola del terminal
    """
    ot1 = 0
    ValorGrafico = Valor()

    while ot1 == 0:
        # Primer while principal para la identificación del código y el país del valor
        global num_exis
        num_exis = 0
        a = -1

        while a != 1 and a != 2 and a != 3:
            # Bucle que repite la opción de la elección de lista
            print(
                "\n\nEste programa realiza recomendaciones de compra o venta de un valor según un análisis técnico con los datos obtenidos de Investing.com\n"
            )
            print("(1)          Ver lista de países                         ")
            print("(2)          Ver lista de valores de todos los países    ")
            print("(3)          Ver lista de valores según el país          ")
            a = int(input("\n¿Qué desea hacer?\n"))
        if a == 1:
            # Se imprimen todos los países que están registrados en el mercado de valores
            for i in investpy.get_stock_countries():
                print("País {}: {}".format(
                    investpy.get_stock_countries().index(i) + 1, i))

        elif a == 2:
            # Se imprime un panda.DataFrame de todos los valores sin importar el país
            print(investpy.get_stocks(country=None))

        elif a == 3:
            # Se imprime un panda.DataFrame de todos los valores según el país indicado
            otra = 1
            while otra != 0:
                try:
                    b = input("Escribe el país de donde quieres buscar:\n")
                    print(investpy.get_stocks(country=b))
                    otra = 0

                except ValueError:
                    # Evita que se ejecute el error ValueError cuando la palabra insertada no se encuentra entre los países de la lista
                    print("Escribe un pais existente\n")

        ott = 1
        while ott != 0:
            # Permite la opción de salida del primer bucle while principal
            ot = str(input("¿Desea ver otra lista? Sí(S) o No (N):\n"))
            if ot == 'S' or ot == 's':
                ot1 = 0
                ott = 0
            elif ot == 'N' or ot == 'n':
                ot1 = 1
                ott = 0
            else:
                ott = 1

    ot2 = 0
    while ot2 == 0:
        # Segundo while principal para ingresar el país y el valor, o salir del programa
        a1 = -1
        while a1 != 1 and a1 != 2:
            # Bucle que repite la opción de la elección de continuar con el análisis o salir del programa
            print(
                "\nElija si desea realizar un análisis técnico de un valor en el mercado de valores\n"
            )
            print("(1)          Analizar un valor                           ")
            print("(2)          Salir                                       ")
            a1 = int(input("\n¿Qué desea hacer?\n"))
        if a1 == 1:
            # Se ingresa el país y el valor para su análisis técnico
            otr = 1
            while otr != 0:
                try:
                    print("¿Qué valor deseas ver?\n")
                    pais = input(
                        "Ingresa el país                 (Segunda columna en la lista de valores)\n"
                    )
                    stock_valor = input(
                        "Ingresa el código del valor     (Séptima columna en la lista de valores)\n"
                    ).upper()
                    p = 0
                    while p == 0:
                        # Permite la opción de especificar un rango de tiempo
                        p1 = str(
                            input(
                                "¿Desea establecer un rango de tiempo? Sí(S) o No (N):\n"
                            ))
                        if p1 == 'S' or p1 == 's':
                            print(
                                "Escriba el rango de tiempo con el formato (dd/mm/aaaa)"
                            )
                            pi = str(input("Escriba el día de inicio :     "))
                            pf = str(input("Escriba el día de término:     "))
                            df = extraer(1, stock_valor, pais, pi, pf)
                            print(df)
                            mpf.plot(
                                df,
                                axtitle=f'Gráfica del valor (De {pi} a {pf})',
                                style='yahoo',
                                xrotation=15,
                                type='candle')
                            mpf.show()

                            p = 1
                        elif p1 == 'N' or p1 == 'n':
                            df = extraer(2, stock_valor, pais)
                            print(df)
                            mpf.plot(
                                df,
                                axtitle='Gráfica del valor (últimos 30 días)',
                                style='yahoo',
                                xrotation=15,
                                type='candle')
                            mpf.show()

                            p = 1
                        else:
                            p = 0

                    otr = 0
                except ValueError:
                    print("Escribe un país existente\n")

        elif a1 == 2:
            # Sale del programa
            break

        otq = 0
        while otq == 0:
            z = -1
            while z != 1 and z != 2 and z != 3:
                # Bucle que repite la opción de la elección de indicador
                print("\n¿Cuál indicador deseas ver?\n")
                print(
                    "(1)          RSI (Relative Strength Index)                        "
                )
                print(
                    "(2)          SMA (Simple Moving Average)                          "
                )
                print(
                    "(3)          Ambos                                                "
                )

                z = int(input("\n¿Qué desea hacer?\n"))
            indic1 = Indicador_tecnico(df)
            if z == 1:
                indic1.RSI()
                t = "RSI"

            elif z == 2:
                indic1.SMA()
                t = "SMA"

            elif z == 3:
                indic1.All()

            Grafico(indic1, indic1._RSI, indic1._SMA)
            señ1 = señal(z, stock_valor, pais)
            if z != 3:

                print(
                    f"\n\nEl indicador {t} en el valor búrsatil '{señ1[0]}' es de {señ1[1]}, e indica que se recomienda {señ1[2]}.\n\n"
                )
            else:
                print(
                    f"\n\nCon el valor búrsatil '{señ1[0]}', con el indicador RSI, el cual es de {señ1[1]}, recomienda {señ1[2]}; mientras que el indicador SMA, el cual es de {señ1[3]}, recomienda {señ1[4]}.\n\n"
                )

            ott2 = 1
            while ott2 != 0:
                # Permite la opción de salida del bucle while
                otp = str(input(
                    "¿Desea ver otro indicador? Sí(S) o No (N):\n")).upper()
                if otp == 'S':
                    otq = 0
                    ott2 = 0
                elif otp == 'N':
                    otq = 1
                    ott2 = 0
                else:
                    ott2 = 1

        ValorGrafico.agregar_valor(stock_valor, indic1)

        otw = 0
        while otw == 0:
            ddd = 1
            while ddd != 0:
                # Permite la opción de salida del bucle while
                otp5 = str(
                    input(
                        "¿Desea ver algún valor registrado? Sí(S) o No (N):\n")
                ).upper()
                if otp5 == 'S':
                    otw = 0
                    ddd = 0
                elif otp5 == 'N':
                    otw = 1
                    ddd = 0
                    break
                else:
                    ddd = 1
            if otp5 == 'S':
                valReg = str(
                    input(
                        "Escriba el símbolo del valor registrado que quiere buscar:    "
                    )).upper()
                VR = ValorGrafico.mostrar_valor(valReg)
            elif otp5 == 'N':
                break

            Grafico(VR[0], VR[1], VR[2])

            if VR[1] == 1 and VR[2] == 0:
                t1 = "RSI"
                z1 = 1
            elif VR[1] == 0 and VR[2] == 1:
                t1 = "SMA"
                z1 = 2
            elif VR[1] == 1 and VR[2] == 1:
                z1 = 3
            señ2 = señal(z1, valReg, pais)
            if z1 != 3:

                print(
                    f"\n\nEl indicador {t1} en el valor búrsatil '{señ2[0]}' es de {señ2[1]}, e indica que se recomienda {señ2[2]}.\n\n"
                )
            else:
                print(
                    f"\n\nCon el valor búrsatil '{señ2[0]}', con el indicador RSI, el cual es de {señ2[1]}, recomienda {señ2[2]}; mientras que el indicador SMA, el cual es de {señ2[3]}, recomienda {señ2[4]}.\n\n"
                )
            ott2 = 1
            while ott2 != 0:
                # Permite la opción de salida del bucle while
                otp7 = str(
                    input(
                        "¿Desea ver otro valor registrado? Sí(S) o No (N):\n"))
                if otp7 == 'S' or otp7 == 's':
                    otw = 0
                    ott2 = 0
                elif otp7 == 'N' or otp7 == 'n':
                    otw = 1
                    ott2 = 0
                    break
                else:
                    ott2 = 1

                valReg = str(
                    input(
                        "Escriba el símbolo del valor registrado que quiere buscar:    "
                    )).upper()
                ValorGrafico.mostrar_valor(valReg)
                VR1 = ValorGrafico.mostrar_valor(valReg)
                Grafico(VR1[0], VR1[1], VR1[2])

                if VR1[1] == 1 and VR1[2] == 0:
                    t2 = "RSI"
                    z2 = 1
                elif VR1[1] == 0 and VR1[2] == 1:
                    t2 = "SMA"
                    z2 = 2
                elif VR1[1] == 1 and VR1[2] == 1:
                    z2 = 3
                    señ3 = señal(z2, valReg, pais)
                if z2 != 3:

                    print(
                        f"\n\nEl indicador {t2} en el valor búrsatil '{señ3[0]}' es de {señ3[1]}, e indica que se recomienda {señ3[2]}.\n\n"
                    )
                else:
                    print(
                        f"\n\nCon el valor búrsatil '{señ3[0]}', con el indicador RSI, el cual es de {señ3[1]}, recomienda {señ3[2]}; mientras que el indicador SMA, el cual es de {señ3[3]}, recomienda {señ3[4]}.\n\n"
                    )

        ott3 = 1
        while ott3 != 0:
            # Permite la opción de salida del segundo bucle while principal
            otp3 = str(input("¿Desea ver otro valor? Sí(S) o No (N):\n"))
            if otp3 == 'S' or otp3 == 's':
                ot2 = 0
                ott3 = 0
            elif otp3 == 'N' or otp3 == 'n':
                ot2 = 1
                ott3 = 0
            else:
                ott3 = 1
Beispiel #5
0
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

import plotly.graph_objects as go
import datetime as dt
import pandas as pd
import numpy as np
import investpy


# get a list of all available countries
countries_list = investpy.get_stock_countries()
countries_list.sort()


def get_tickers(country):
    # function to get a dictionary of all tickers/stocks available
    # in a specific country
    try:
        tickers_df = investpy.get_stocks(country=country.lower())
    except:
        tickers_df = pd.DataFrame(data=dict(name=['No results'], symbol=['No results']) )
    # extract names and symbols
    tickers_df.loc[:, 'name'] = tickers_df.loc[:, 'name'].apply(lambda x: x.strip('u200b') )
    
    labels= [', '.join(i) for i in tickers_df.loc[:, ['name','symbol']].values]
    values = tickers_df.loc[:, ['symbol']].values.T[0]
    tickers_dict = [{'label':i, 'value':j} for i,j in zip(labels, values)]
Beispiel #6
0
fund_sheet = 'funds'
index_sheet = 'indices'
stock_sheet = 'stocks'
bond_sheet = 'bonds'
etf_sheet = 'etfs'
crypto_sheet = 'cryptos'

req_fund_countries = investpy.get_fund_countries()
df_fund_countries = pd.DataFrame(req_fund_countries)

req_bond_countries = investpy.get_bond_countries()
df_bond_countries = pd.DataFrame(req_bond_countries)

req_index_countries = investpy.get_index_countries()
df_index_countries = pd.DataFrame(req_index_countries)

req_stock_countries = investpy.get_stock_countries()
df_stock_countries = pd.DataFrame(req_stock_countries)

req_etf_countries = investpy.get_etf_countries()
df_etf_countries = pd.DataFrame(req_etf_countries)


def GetCountries():
    wb = xw.Book.caller()
    wb.sheets[fund_sheet].range('A1').value = df_fund_countries
    wb.sheets[index_sheet].range('A1').value = df_index_countries
    wb.sheets[stock_sheet].range('A1').value = df_stock_countries
    wb.sheets[bond_sheet].range('A1').value = df_bond_countries
    wb.sheets[etf_sheet].range('A1').value = df_etf_countries
Beispiel #7
0
    def validate(self):
        """ Method used to validate that the introduced Stock is valid before adding it to the StockPortfolio.

        This method is the one in charge of the validation of the introduced Stock via checking the introduced data
        with the one indexed in investpy, so to check if the data match. Also, the introduced parameters are checked in
        order to determine if the type is correct of those values is correct, if not, an exception will be raised. The
        result of this function is just setting either True or False to the self.valid value if the Stock is valid or
        not, respectively.

        """
        if not isinstance(self.stock_symbol, str):
            raise ValueError(
                "ERROR [0005]: The introduced stock_symbol is mandatory and should be a str."
            )

        if not isinstance(self.stock_country, str):
            raise ValueError(
                "ERROR [0006]: The introduced stock_country is mandatory and should be a str."
            )

        try:
            datetime.datetime.strptime(self.purchase_date, '%d/%m/%Y')
        except ValueError:
            raise ValueError(
                "ERROR [0007]: The introduced purchase_date is not properly formatted (dd/mm/yyyy)."
            )

        purchase_date_ = datetime.datetime.strptime(self.purchase_date,
                                                    '%d/%m/%Y')
        if purchase_date_ > datetime.datetime.now():
            raise ValueError(
                "ERROR [0008]: The introduced purchase_date is not valid since it should be earlier than "
                "the current date.")

        if not isinstance(self.num_of_shares, int):
            raise ValueError(
                "ERROR [0009]: The introduced num_of_shares is mandatory and should be an int higher "
                "than 0.")
        else:
            if self.num_of_shares <= 0:
                raise ValueError(
                    "ERROR [0009]: The introduced num_of_shares is mandatory and should be an int higher "
                    "than 0.")

        if not isinstance(self.cost_per_share, float):
            raise ValueError(
                "ERROR [0010]: The introduced cost_per_share is mandatory and should be a float higher "
                "than 0.")
        else:
            if self.cost_per_share <= 0:
                raise ValueError(
                    "ERROR [0010]: The introduced Stock is not valid.")

        stock_countries = investpy.get_stock_countries()

        if self.stock_country.lower() in stock_countries:
            stocks = investpy.get_stocks(country=self.stock_country)

            search_results = stocks[stocks['symbol'].str.lower() ==
                                    self.stock_symbol.lower()]

            if len(search_results) > 0:
                data = investpy.get_stock_historical_data(
                    stock=self.stock_symbol,
                    country=self.stock_country,
                    from_date=self.purchase_date,
                    to_date=datetime.date.today().strftime("%d/%m/%Y"))

                try:
                    purchase_date_ = purchase_date_.strftime("%Y-%m-%d")
                    min_value = data.loc[purchase_date_]['Low']
                    max_value = data.loc[purchase_date_]['High']
                except KeyError:
                    raise KeyError(
                        "ERROR [0004]: The introduced purchase_date is not valid since the market was "
                        "closed.")

                if min_value <= self.cost_per_share <= max_value:
                    self.valid = True
                else:
                    raise ValueError(
                        "ERROR [0011]: The introduced value is not possible, because the range stock "
                        "values of the purchase data were between " +
                        str(min_value) + " and " + str(max_value))
            else:
                raise ValueError(
                    "ERROR [0003]: No results were found for the introduced stock_symbol in the specified "
                    "stock_country.")
        else:
            raise ValueError(
                "ERROR [0002]: The introduced stock_country is not valid or does not have any indexed "
                "stock.")