def test_equity_errors(): params = [ {'equity': 'bbva', 'as_json': 'error', 'order': 'ascending'}, {'equity': 'bbva', 'as_json': True, 'order': 'error'}, {'equity': 'error', 'as_json': True, 'order': 'ascending'}, ] for param in params: try: investpy.get_recent_data(equity=param['equity'], as_json=param['as_json'], order=param['order']) except: pass params = [ {'equity': 'bbva', 'start': '01/01/2019', 'end': '01/01/2019', 'as_json': 'error', 'order': 'ascending'}, {'equity': 'bbva', 'start': '01/01/2019', 'end': '01/01/2019', 'as_json': False, 'order': 'error'}, {'equity': 'bbva', 'start': 'error', 'end': '01/01/2019', 'as_json': False, 'order': 'ascending'}, {'equity': 'bbva', 'start': '01/01/2019', 'end': 'error', 'as_json': False, 'order': 'ascending'}, {'equity': 'error', 'start': '01/01/2019', 'end': '01/01/2019', 'as_json': False, 'order': 'ascending'}, {'equity': 'bbva', 'start': '01/01/1998', 'end': '01/01/2019', 'as_json': False, 'order': 'ascending'}, ] for param in params: try: investpy.get_historical_data(equity=param['equity'], start=param['start'], end=param['end'], as_json=param['as_json'], order=param['order']) except: pass params = [ {'equity': None, 'language': 'spanish'}, {'equity': 'bbva', 'language': 'error'}, {'equity': 'error', 'language': 'spanish'}, ] for param in params: try: investpy.get_equity_company_profile(equity=param['equity'], language=param['language']) except: pass
def add_stock(self, stock_name, stock_country, purchase_date, num_of_shares, cost_per_share): """ Method to add a stock to the portfolio. This method adds a stock to the custom portfolio data. Some parameters need to be specified for the introduced stock such as the purchase date of the shares, the number of shares bought and the price payed (cost) per every share. From this data, the portfolio will be created and the specified calculations will be done, so to give the user an overview of his/her own portfolio. Args: stock_name (:obj:`str`): name of the Stock that is going to be added to the StockPortfolio. stock_country (:obj:`str`): country from where the specified stock_name is, so to validate it. purchase_date (:obj:`str`): date when the shares of the introduced stock were bought, formatted as dd/mm/yyyy. num_of_shares (:obj:`int`): amount of shares bought of the specified Stock in the specified date. cost_per_share (:obj:`float`): price of every share of the Stock in the specified date. """ stock = Stock(stock_name, stock_country, purchase_date, num_of_shares, cost_per_share) stock.validate() if stock.valid is True: data = investpy.get_historical_data(equity=stock_name, country=stock_country, from_date=purchase_date, to_date=date.today().strftime("%d/%m/%Y")) curr_price = self.current_price(data=data) obj = { 'stock_name': stock_name, 'stock_country': stock_country, 'purchase_date': purchase_date, 'num_of_shares': num_of_shares, 'cost_per_share': cost_per_share, 'current_price': curr_price, 'gross_current_value': self.gross_current_value(current_price=curr_price, num_of_shares=num_of_shares), } self.stocks.append(obj) self.data = pd.DataFrame(self.stocks) else: raise ValueError("ERROR [0001]: The introduced Stock is not valid.")
def test_equities_errors(): """ This function raises errors on equity retrieval functions """ try: retrieve_equities(test_mode=None) except: pass try: retrieve_equity_countries(test_mode=None) except: pass params = [ { 'country': ['error'] }, { 'country': 'error' }, ] for param in params: try: investpy.get_equities(country=param['country']) except: pass try: investpy.get_equities_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_equities_dict(country=param['country'], columns=param['columns'], as_json=param['as_json']) except: pass params = [ { 'equity': 'Euripo Properties Socimi', 'country': 'spain', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': None, 'country': 'spain', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': None, 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': ['error'], 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': 'greece', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': 'spain', 'as_json': 'error', 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': 'spain', 'as_json': True, 'order': 'error', 'debug': True }, { 'equity': 'error', 'country': 'spain', 'as_json': True, 'order': 'ascending', 'debug': True }, { 'equity': ['error'], 'country': 'spain', 'as_json': True, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': 'spain', 'as_json': True, 'order': 'ascending', 'debug': 'error' }, ] for param in params: try: investpy.get_recent_data(equity=param['equity'], country=param['country'], as_json=param['as_json'], order=param['order'], debug=param['debug']) except: pass params = [ { 'equity': 'Euripo Properties Socimi', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': None, 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': None, 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': ['error'], 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': 'greece', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': 'error', 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'error', 'debug': True }, { 'equity': 'bbva', 'country': 'spain', 'from_date': 'error', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2019', 'to_date': 'error', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'error', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': ['error'], 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/1999', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/1900', 'to_date': '01/01/1950', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/1950', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2019', 'to_date': '01/01/1999', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2019', 'to_date': '01/03/2019', 'as_json': False, 'order': 'ascending', 'debug': 'error' }, ] for param in params: try: investpy.get_historical_data(equity=param['equity'], 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 = [ { 'equity': None, 'country': 'spain', 'language': 'spanish' }, { 'equity': 'bbva', 'country': None, 'language': 'spanish' }, { 'equity': 'bbva', 'country': 'greece', 'language': 'spanish' }, { 'equity': 'bbva', 'country': 'spain', 'language': 'error' }, { 'equity': 'error', 'country': 'spain', 'language': 'spanish' }, { 'equity': ['error'], 'country': 'spain', 'language': 'spanish' }, ] for param in params: try: investpy.get_equity_company_profile(equity=param['equity'], country=param['country'], language=param['language']) except: pass params = [ { 'by': None, 'value': 'bbva', }, { 'by': ['error'], 'value': 'bbva', }, { 'by': 'error', 'value': 'bbva', }, { 'by': 'name', 'value': None, }, { 'by': 'name', 'value': ['error'], }, { 'by': 'isin', 'value': 'error', }, ] for param in params: try: investpy.search_equities(by=param['by'], value=param['value']) except: pass
def test_investpy(): """ This function checks that main functions of investpy work properly. """ print(investpy.__author__, investpy.__version__) for value in ['spain', None]: investpy.get_equities(country=value) investpy.get_equities_list(country=value) params = [ { 'country': None, 'columns': ['id', 'name'], 'as_json': True }, { 'country': 'spain', 'columns': ['id', 'name'], 'as_json': True }, { 'country': None, 'columns': ['id', 'name'], 'as_json': False }, { 'country': 'spain', 'columns': None, 'as_json': False }, { 'country': 'spain', 'columns': ['id', 'name'], 'as_json': False }, ] for param in params: investpy.get_equities_dict(country=param['country'], columns=param['columns'], as_json=param['as_json']) investpy.get_equity_countries() params = [ { 'as_json': False, 'order': 'ascending', 'debug': True }, { 'as_json': True, 'order': 'descending', 'debug': False }, { 'as_json': True, 'order': 'ascending', 'debug': False }, { 'as_json': False, 'order': 'descending', 'debug': False }, ] for param in params: investpy.get_recent_data(equity='enagás', country='spain', as_json=param['as_json'], order=param['order'], debug=param['debug']) investpy.get_historical_data(equity='enagás', 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_equity_company_profile(equity='enagás', country='spain', language=value) retrieve_equities(test_mode=True) retrieve_equity_countries(test_mode=True) params = [ { 'country': 'spain', }, { 'country': None, }, ] for param in params: investpy.get_funds(country=param['country']) investpy.get_funds_list(country=param['country']) params = [ { 'country': None, 'columns': ['id', 'name'], 'as_json': True }, { 'country': 'spain', 'columns': ['id', 'name'], 'as_json': True }, { 'country': None, 'columns': ['id', 'name'], 'as_json': False }, { 'country': 'spain', 'columns': None, 'as_json': False }, { 'country': 'spain', 'columns': ['id', 'name'], 'as_json': False }, ] for param in params: investpy.get_funds_dict(country=param['country'], columns=param['columns'], as_json=param['as_json']) params = [ { 'fund': 'bbva multiactivo conservador pp', 'country': 'spain', 'as_json': True, }, { 'fund': 'bbva multiactivo conservador pp', 'country': 'spain', 'as_json': False, }, ] for param in params: investpy.get_fund_information(fund=param['fund'], country=param['country'], as_json=param['as_json']) params = [ { 'as_json': False, 'order': 'ascending', 'debug': True }, { 'as_json': True, 'order': 'descending', 'debug': False }, { 'as_json': True, 'order': 'ascending', 'debug': False }, { 'as_json': False, 'order': 'descending', 'debug': False }, ] for param in params: investpy.get_fund_recent_data(fund='bbva multiactivo conservador pp', country='spain', as_json=param['as_json'], order=param['order'], debug=param['debug']) investpy.get_fund_historical_data( fund='bbva multiactivo conservador pp', country='spain', from_date='01/01/2010', to_date='01/01/2019', as_json=param['as_json'], order=param['order'], debug=param['debug']) investpy.get_fund_countries() investpy.get_funds() retrieve_funds(test_mode=True) retrieve_fund_countries(test_mode=True) investpy.get_etf_countries() for value in ['spain', None]: investpy.get_etfs(country=value) investpy.get_etfs_list(country=value) params = [ { 'country': None, 'columns': ['id', 'name'], 'as_json': True }, { 'country': 'spain', 'columns': ['id', 'name'], 'as_json': True }, { 'country': None, 'columns': ['id', 'name'], 'as_json': False }, { 'country': 'spain', 'columns': None, 'as_json': False }, { 'country': 'spain', 'columns': ['id', 'name'], 'as_json': False }, ] for param in params: investpy.get_etfs_dict(country=param['country'], columns=param['columns'], as_json=param['as_json']) params = [ { 'as_json': False, 'order': 'ascending', 'debug': True }, { 'as_json': True, 'order': 'descending', 'debug': False }, { 'as_json': True, 'order': 'ascending', 'debug': False }, { 'as_json': False, 'order': 'descending', 'debug': False }, ] for param in params: investpy.get_etf_recent_data(etf='bbva accion dj eurostoxx 50', country='spain', as_json=param['as_json'], order=param['order'], debug=param['debug']) investpy.get_etf_historical_data(etf='bbva accion dj eurostoxx 50', country='spain', from_date='01/01/2010', to_date='01/01/2019', as_json=param['as_json'], order=param['order'], debug=param['debug']) params = [ { 'country': 'france', 'as_json': True, }, { 'country': 'usa', 'as_json': False, }, ] for param in params: investpy.get_etfs_overview(country=param['country'], as_json=param['as_json']) retrieve_etfs(test_mode=True)
def test_investpy_equities(): """ This function checks that equity data retrieval functions listed in investpy work properly. """ params = [ { 'country': 'spain', }, { 'country': None, }, ] for param in params: investpy.get_equities(country=param['country']) investpy.get_equities_list(country=param['country']) params = [ { 'country': None, 'columns': ['id', 'name'], 'as_json': True }, { 'country': None, 'columns': ['id', 'name'], 'as_json': False }, { 'country': 'spain', 'columns': ['id', 'name'], 'as_json': True }, { 'country': 'spain', 'columns': ['id', 'name'], 'as_json': False }, { 'country': 'spain', 'columns': None, 'as_json': False }, ] for param in params: investpy.get_equities_dict(country=param['country'], columns=param['columns'], as_json=param['as_json']) investpy.get_equity_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_recent_data(equity='enagás', country='spain', as_json=param['as_json'], order=param['order'], debug=param['debug']) investpy.get_historical_data(equity='enagás', 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_equity_company_profile(equity='enagás', country='spain', language=value) investpy.search_equities(by='name', value='bbva') retrieve_equities(test_mode=True) retrieve_equity_countries(test_mode=True)
def test_errors(): """ This function raises trendet errors to improve coverage """ params = [ { 'equity': ['error'], 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 3, 'labels': None, 'identify': 'both', }, { 'equity': None, 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 3, 'labels': None, 'identify': 'both', }, { 'equity': 'error', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 3, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': None, 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 3, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': 'error', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 3, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': ['error'], 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 3, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': None, 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 3, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': None, 'window_size': 5, 'trend_limit': 3, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2019', 'to_date': '01/01/2018', 'window_size': 5, 'trend_limit': 3, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01-2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 3, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '_01*01/2019', 'window_size': 5, 'trend_limit': 3, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 0, 'trend_limit': 3, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': -1, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': None, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': None, 'trend_limit': 1, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 'error', 'trend_limit': 1, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 1, 'trend_limit': 'error', 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 2, 'trend_limit': 5, 'labels': None, 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 3, 'labels': ['a', 'b'], 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 3, 'labels': 'error', 'identify': 'both', }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 3, 'labels': None, 'identify': ['error'], }, { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 3, 'labels': None, 'identify': 'error', }, ] for param in params: try: trendet.identify_trends(equity=param['equity'], country=param['country'], from_date=param['from_date'], to_date=param['to_date'], window_size=param['window_size'], trend_limit=param['trend_limit'], labels=param['labels'], identify=param['identify']) except: pass try: trendet.identify_all_trends(equity=param['equity'], country=param['country'], from_date=param['from_date'], to_date=param['to_date'], window_size=param['window_size'], identify=param['identify']) except: pass df = investpy.get_historical_data(equity='repsol', country='spain', from_date='01/01/2018', to_date='01/01/2019') df['str'] = 'error' params = [ { 'df': None, 'column': 'Close', 'window_size': 5, 'identify': 'both' }, { 'df': ['error'], 'column': 'Close', 'window_size': 5, 'identify': 'both' }, { 'df': df, 'column': None, 'window_size': 5, 'identify': 'both' }, { 'df': df, 'column': ['error'], 'window_size': 5, 'identify': 'both' }, { 'df': df, 'column': 'error', 'window_size': 5, 'identify': 'both' }, { 'df': df, 'column': 'str', 'window_size': 5, 'identify': 'both' }, { 'df': df, 'column': 'Close', 'window_size': None, 'identify': 'both' }, { 'df': df, 'column': 'Close', 'window_size': 1, 'identify': 'both' }, { 'df': df, 'column': 'Close', 'window_size': 5, 'identify': ['error'] }, { 'df': df, 'column': 'Close', 'window_size': 5, 'identify': 'error' }, ] for param in params: try: trendet.identify_df_trends(df=param['df'], column=param['column'], window_size=param['window_size'], identify=param['identify']) except: pass
def test_investpy(): """ This function checks that main functions of investpy work properly. """ investpy.get_equities() investpy.get_equities_list() params = [ {'as_json': False, 'order': 'ascending'}, {'as_json': True, 'order': 'descending'}, {'as_json': True, 'order': 'ascending'}, {'as_json': False, 'order': 'descending'}, ] for param in params: investpy.get_recent_data(equity='enagás', as_json=param['as_json'], order=param['order']) investpy.get_historical_data(equity='enagás', start='01/01/1990', end='01/01/2019', as_json=param['as_json'], order=param['order']) for value in ['spanish', 'english']: investpy.get_equity_company_profile(equity='enagás', language=value) get_equity_names() investpy.get_funds() investpy.get_funds_list() for value in [True, False]: investpy.get_funds_dict(columns=['id', 'name'], as_json=value) investpy.get_fund_information(fund='bbva multiactivo conservador pp', as_json=value) params = [ {'as_json': False, 'order': 'ascending'}, {'as_json': True, 'order': 'descending'}, {'as_json': True, 'order': 'ascending'}, {'as_json': False, 'order': 'descending'}, ] for param in params: investpy.get_fund_recent_data(fund='bbva multiactivo conservador pp', as_json=param['as_json'], order=param['order']) investpy.get_fund_historical_data(fund='bbva multiactivo conservador pp', start='01/01/2010', end='01/01/2019', as_json=param['as_json'], order=param['order']) get_fund_names() # investpy.get_etfs() # # investpy.get_etfs_list() # # # # for value in [True, False]: # # investpy.get_etfs_dict(columns=['id', 'name'], as_json=value) params = [ {'as_json': False, 'order': 'ascending'}, {'as_json': True, 'order': 'descending'}, {'as_json': True, 'order': 'ascending'}, {'as_json': False, 'order': 'descending'}, ] for param in params: investpy.get_etf_recent_data(etf='bbva accion dj eurostoxx 50', as_json=param['as_json'], order=param['order']) investpy.get_etf_historical_data(etf='bbva accion dj eurostoxx 50', start='01/01/2010', end='01/01/2019', as_json=param['as_json'], order=param['order']) get_etfs()
def identify_all_trends(equity, country, from_date, to_date, window_size=5, identify='both'): """ This function retrieves historical data from the introduced `equity` between two dates from Investing via investpy; and that data is later going to be analysed in order to detect/identify trends over a certain date range. A trend is considered so based on the window_size, which specifies the number of consecutive days which lead the algorithm to identify the market behaviour as a trend. So on, this function will identify both up and down trends and will remove the ones that overlap, keeping just the longer trend and discarding the nested trend. Args: equity (:obj:`str`): name of the equity to retrieve historical data from. country (:obj:`str`): name of the country from where the equity is. from_date (:obj:`str`): date as `str` formatted as `dd/mm/yyyy`, from where data is going to be retrieved. to_date (:obj:`str`): date as `str` formatted as `dd/mm/yyyy`, until where data is going to be retrieved. window_size (:obj:`window`, optional): number of days from where market behaviour is considered a trend. identify (:obj:`str`, optional): which trends does the user wants to be identified, it can either be 'both', 'up' or 'down'. Returns: :obj:`pandas.DataFrame`: The function returns a :obj:`pandas.DataFrame` which contains the retrieved historical data from Investing using `investpy`, with a new column which identifies every trend found on the market between two dates identifying when did the trend started and when did it end. So the additional column contains labeled date ranges, representing both bullish (up) and bearish (down) trends. Raises: ValueError: raised if any of the introduced arguments errored. """ if equity and not isinstance(equity, str): raise ValueError("equity argument needs to be a `str`.") if not equity: raise ValueError( "equity parameter is mandatory and must be a valid equity name.") if not country: raise ValueError( "country parameter is mandatory and must be a valid country name as listed in " "`investpy.get_equity_countries()`.") if country and not isinstance(country, str): raise ValueError( "country argument is mandatory and needs to be a `str`.") if isinstance(country, str) and country not in get_equity_countries(): raise ValueError( "introduced country is not a valid one, check valid equity countries in " "`investpy.get_equity_countries()`.") try: datetime.datetime.strptime(from_date, '%d/%m/%Y') except ValueError: raise ValueError( "incorrect from_date date format, it should be 'dd/mm/yyyy'.") try: datetime.datetime.strptime(to_date, '%d/%m/%Y') except ValueError: raise ValueError( "incorrect to_date format, it should be 'dd/mm/yyyy'.") start_date = datetime.datetime.strptime(from_date, '%d/%m/%Y') end_date = datetime.datetime.strptime(to_date, '%d/%m/%Y') if start_date >= end_date: raise ValueError( "to_date should be greater than from_date, both formatted as 'dd/mm/yyyy'." ) if not isinstance(window_size, int): raise ValueError('window_size must be an `int`') if isinstance(window_size, int) and window_size < 3: raise ValueError( 'window_size must be an `int` equal or higher than 3!') if not isinstance(identify, str): raise ValueError( 'identify should be a `str` contained in [both, up, down]!') if isinstance(identify, str) and identify not in ['both', 'up', 'down']: raise ValueError( 'identify should be a `str` contained in [both, up, down]!') try: df = get_historical_data(equity=str(equity), country=str(country), from_date=from_date, to_date=to_date, as_json=False, order='ascending', debug=False) except: raise RuntimeError('investpy function call failed!') objs = list() up_trend = {'name': 'Up Trend', 'element': np.negative(df['Close'])} down_trend = {'name': 'Down Trend', 'element': df['Close']} if identify == 'both': objs.append(up_trend) objs.append(down_trend) elif identify == 'up': objs.append(up_trend) elif identify == 'down': objs.append(down_trend) results = dict() for obj in objs: limit = None values = list() trends = list() for index, value in enumerate(obj['element'], 0): if limit and limit > value: values.append(value) limit = mean(values) elif limit and limit < value: if len(values) > window_size: min_value = min(values) for counter, item in enumerate(values, 0): if item == min_value: break to_trend = from_trend + counter trend = { 'from': df.index.tolist()[from_trend], 'to': df.index.tolist()[to_trend], } trends.append(trend) limit = None values = list() else: from_trend = index values.append(value) limit = mean(values) results[obj['name']] = trends if identify == 'both': up_trends = list() for up in results['Up Trend']: flag = True for down in results['Down Trend']: if down['from'] < up['from'] < down['to'] or down['from'] < up[ 'to'] < down['to']: if (up['to'] - up['from']).days > (down['to'] - down['from']).days: flag = True else: flag = False else: flag = True if flag is True: up_trends.append(up) labels = [letter for letter in string.ascii_uppercase[:len(up_trends)]] for up_trend, label in zip(up_trends, labels): for index, row in df[up_trend['from']:up_trend['to']].iterrows(): df.loc[index, 'Up Trend'] = label down_trends = list() for down in results['Down Trend']: flag = True for up in results['Up Trend']: if up['from'] < down['from'] < up['to'] or up['from'] < down[ 'to'] < up['to']: if (up['to'] - up['from']).days < (down['to'] - down['from']).days: flag = True else: flag = False else: flag = True if flag is True: down_trends.append(down) labels = [ letter for letter in string.ascii_uppercase[:len(down_trends)] ] for down_trend, label in zip(down_trends, labels): for index, row in df[down_trend['from']:down_trend['to']].iterrows( ): df.loc[index, 'Down Trend'] = label return df elif identify == 'up': up_trends = results['Up Trend'] up_labels = [ letter for letter in string.ascii_uppercase[:len(up_trends)] ] for up_trend, up_label in zip(up_trends, up_labels): for index, row in df[up_trend['from']:up_trend['to']].iterrows(): df.loc[index, 'Up Trend'] = up_label return df elif identify == 'down': down_trends = results['Down Trend'] down_labels = [ letter for letter in string.ascii_uppercase[:len(down_trends)] ] for down_trend, down_label in zip(down_trends, down_labels): for index, row in df[down_trend['from']:down_trend['to']].iterrows( ): df.loc[index, 'Down Trend'] = down_label return df
def test_trendet(): """ This function checks that main functions of trendet work properly. """ author = trendet.__author__ print(author) version = trendet.__version__ print(version) equities = investpy.get_equities(country='spain') equities = equities['name'].tolist() params = list() for equity in equities[:25]: obj = { 'equity': equity, 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 5, 'labels': None, 'identify': 'both', } params.append(obj) obj = { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 2, 'labels': ['A', 'B'], 'identify': 'both' } params.append(obj) obj = { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 2, 'labels': None, 'identify': 'up', } params.append(obj) obj = { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 2, 'labels': ['A', 'B'], 'identify': 'up', } params.append(obj) obj = { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 2, 'labels': None, 'identify': 'down', } params.append(obj) obj = { 'equity': 'bbva', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'window_size': 5, 'trend_limit': 2, 'labels': ['A', 'B'], 'identify': 'down', } params.append(obj) for param in params: trendet.identify_trends(equity=param['equity'], country=param['country'], from_date=param['from_date'], to_date=param['to_date'], window_size=param['window_size'], trend_limit=param['trend_limit'], labels=param['labels'], identify=param['identify']) trendet.identify_all_trends(equity=param['equity'], country=param['country'], from_date=param['from_date'], to_date=param['to_date'], window_size=param['window_size'], identify=param['identify']) df = investpy.get_historical_data(equity='repsol', country='spain', from_date='01/01/2018', to_date='01/01/2019') params = [ { 'df': df, 'column': 'Close', 'window_size': 5, 'identify': 'both' }, { 'df': df, 'column': 'Close', 'window_size': 5, 'identify': 'up' }, { 'df': df, 'column': 'Close', 'window_size': 5, 'identify': 'down' }, ] for param in params: trendet.identify_df_trends(df=param['df'], column=param['column'], window_size=param['window_size'], identify=param['identify'])
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_name, str): raise ValueError("ERROR [0005]: The introduced stock_name 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_equity_countries() if self.stock_country.lower() in stock_countries: stocks = investpy.get_equities(country=self.stock_country) search_results = stocks[stocks['name'].str.lower() == self.stock_name.lower()] if len(search_results) > 0: data = investpy.get_historical_data(equity=self.stock_name, 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") open_value = data.loc[purchase_date_]['Open'] close_value = data.loc[purchase_date_]['Close'] except KeyError: raise KeyError("ERROR [0004]: The introduced purchase_date is not valid since the market was " "closed.") if open_value <= self.cost_per_share <= close_value: self.valid = True else: raise ValueError("ERROR [0003]: No results were found for the introduced stock_name in the specified " "stock_country.") else: raise ValueError("ERROR [0002]: The introduced stock_country is not valid or does not have any indexed " "stock.")