def test_fund_errors(): params = [ {'columns': None, 'as_json': 'error'}, {'columns': 0, 'as_json': True}, {'columns': ['error'], 'as_json': False}, ] for param in params: try: investpy.get_funds_dict(columns=param['columns'], as_json=param['as_json']) except: pass params = [ {'fund': 'quality inversion conservadora fi', 'as_json': 'error', 'order': 'ascending'}, {'fund': 'quality inversion conservadora fi', 'as_json': True, 'order': 'error'}, {'fund': 'error', 'as_json': True, 'order': 'ascending'}, ] for param in params: try: investpy.get_fund_recent_data(fund=param['fund'], as_json=param['as_json'], order=param['order']) except: pass params = [ {'fund': 'quality inversion conservadora fi', 'start': '01/01/2019', 'end': '01/01/2019', 'as_json': 'error', 'order': 'ascending'}, {'fund': 'quality inversion conservadora fi', 'start': '01/01/2019', 'end': '01/01/2019', 'as_json': False, 'order': 'error'}, {'fund': 'quality inversion conservadora fi', 'start': 'error', 'end': '01/01/2019', 'as_json': False, 'order': 'ascending'}, {'fund': 'quality inversion conservadora fi', 'start': '01/01/2019', 'end': 'error', 'as_json': False, 'order': 'ascending'}, {'fund': 'error', 'start': '01/01/2019', 'end': '01/01/2019', 'as_json': False, 'order': 'ascending'}, {'fund': 'quality inversion conservadora fi', 'start': '01/01/1998', 'end': '01/01/2019', 'as_json': False, 'order': 'ascending'}, ] for param in params: try: print(param) investpy.get_fund_historical_data(fund=param['fund'], start=param['start'], end=param['end'], as_json=param['as_json'], order=param['order']) except: pass params = [ {'fund': 'quality inversion conservadora fi', 'as_json': 'error'}, {'fund': 'error', 'as_json': True}, ] for param in params: try: print('hola') investpy.get_fund_information(fund=param['fund'], as_json=param['as_json']) except: pass
def get_asset_data(asset_list: list, from_date: str, to_date: str, asset_type: str, asset_df: pd.DataFrame) -> Tuple[list, pd.DataFrame]: # commodity, bond, currency # etfs and funds need country if asset_type == "Bonds": func = lambda a, s, e: investpy.get_bond_historical_data(a, s, e) elif asset_type == "Currencies": func = lambda a, s, e: investpy.get_currency_cross_historical_data( a, s, e) elif asset_type == "ETFs": func = lambda a, s, e, c: investpy.get_etf_historical_data(a, c, s, e) elif asset_type == "Funds": func = lambda a, s, e, c: investpy.get_fund_historical_data(a, c, s, e) elif asset_type == "Commodities": func = lambda a, s, e: investpy.get_commodity_historical_data(a, s, e) elif asset_type == "Indices": func = lambda a, s, e, c: investpy.get_index_historical_data( a, c, s, e) elif asset_type == "Crypto": func = lambda a, s, e: investpy.get_crypto_historical_data(a, s, e) df_list = [] for asset in asset_list: if asset_type != "ETFs" and asset_type != "Funds" and asset_type != "Indices": df = func(asset, from_date, to_date) df_list.append(df) else: country = get_attribute_investing(asset_df, asset, 'country') df = func(asset, from_date, to_date, country) df_list.append(df) close_list = [df.Close for df in df_list] # print(close_list) close_df = pd.concat(close_list, axis=1) close_df.columns = asset_list return df_list, close_df
def get_investiments_returns(pct_change_window=1): stocks_name = get_assets_env_var('STOCKS') funds_name = get_assets_env_var('FUNDS') today = date.today() today = today.strftime("%d/%m/%Y") close_prices = [] for stock in stocks_name: prices = inv.get_stock_historical_data(stock=stock, country='brazil', from_date='01/01/2015', to_date=today) close_prices.append(prices.Close) for fund in funds_name: prices = inv.get_fund_historical_data(fund, country='brazil', from_date='01/01/2015', to_date=today) close_prices.append(prices.Close) prices = pd.concat(close_prices, axis=1) prices = prices.dropna() columns_name = [] for column_name in (stocks_name + funds_name): columns_name.append(column_name[:10]) prices.columns = columns_name returns = prices.pct_change(pct_change_window).dropna() return returns
def ApiGetAllByIsin(self, isin, tipologia_strumento, periodicita, start): #restituisce il nome di corrispondenza all'isin inserito country_iniziali = isin[:2] country = GLOBE.country_isin.get(country_iniziali) endus = datetime.now() endeu = endus.strftime("%d/%m/%Y") # print(inv.stocks.get_stock_countries()) if tipologia_strumento == GLOBE.mappa_strumenti.get("stock"): stock = inv.stocks.get_stocks(country = country) info_gen = stock.loc[stock["isin"] == isin] df = inv.get_stock_historical_data(stock = info_gen["symbol"].values[0], country = country, from_date = start, to_date = endeu, as_json=False, order='ascending', interval = GLOBE.mappa_periodicita[periodicita]) elif tipologia_strumento == GLOBE.mappa_strumenti.get("etf"): etf = inv.etfs.get_etfs(country = country) info_gen = etf.loc[etf["isin"] == isin] df = inv.get_etf_historical_data(etf = info_gen["name"].values[0], country = country, from_date = start, to_date = endeu, as_json=False, order='ascending', interval = GLOBE.mappa_periodicita[periodicita]) elif tipologia_strumento == GLOBE.mappa_strumenti.get("fund"): fund = inv.funds.get_funds(country = country) info_gen = fund.loc[fund["isin"] == isin] df = inv.get_fund_historical_data(fund = info_gen["name"].values[0], country = country, from_date = start, to_date = endeu, as_json=False, order='ascending', interval = GLOBE.mappa_periodicita[periodicita]) all_info = { #dict con tutte le informazioni "datafetch" : df, "info_gen" : info_gen, "tipo_strumento" : tipologia_strumento } return all_info
def get_fund_info(ticker): price_now = get_fund_price(ticker) now = datetime.datetime.now() price_year_ago = investpy.get_fund_historical_data( fund=get_fund_from_ticker(ticker), country='united states', from_date=(now - datetime.timedelta(days=365)).strftime('%d/%m/%Y'), to_date=(now - datetime.timedelta(days=350)).strftime( '%d/%m/%Y'))['Close'][-1] * get_currency_price('USD') return price_now, price_year_ago
def loadData(self): print('Loading ', self.name) try: self.df = investpy.get_fund_historical_data( fund=self.name, country=self.country, from_date=self.sampling_from_str, to_date=self.end_date_str) self.parseDF() except ConnectionError: print('Internet connection Error') except ValueError: print('No data found')
def evolucion_fondo(isin): import pandas as pd import investpy from datetime import date isin = isin nombre = investpy.search_funds(by='isin', value=isin).loc[0, 'name'] pais = investpy.search_funds(by='isin', value=isin).loc[0, 'country'] df = investpy.get_fund_historical_data( fund=nombre, from_date="01/01/2000", to_date=date.today().strftime("%d/%m/%Y"), country=pais) df = df.drop(['Open', 'High', 'Low'], axis=1) df['returns'] = df['Close'].pct_change() df = df.dropna() return df
def _download_data(self, asset_type, symbol, name, country, from_date, max_date): if asset_type == "BOND": # name == symbol df = ip.get_bond_historical_data(symbol, from_date=from_date, to_date=max_date) elif asset_type == "CERT": df = ip.get_certificate_historical_data(name, country=country, from_date=from_date, to_date=max_date) elif asset_type == "CRYPTO": df = ip.get_crypto_historical_data(name, from_date=from_date, to_date=max_date) elif asset_type == "COMM": df = ip.get_commodity_historical_data(symbol, from_date=from_date, to_date=max_date) elif asset_type == "ETF": df = ip.get_etf_historical_data(name, country=country, from_date=from_date, to_date=max_date) elif asset_type == "FUND": df = ip.get_fund_historical_data(name, country=country, from_date=from_date, to_date=max_date) elif asset_type == "FX": df = ip.get_currency_cross_historical_data(symbol, from_date=from_date, to_date=max_date) elif asset_type == "INDEX": df = ip.get_index_historical_data(name, country=country, from_date=from_date, to_date=max_date) elif asset_type == "STOCK": df = ip.get_stock_historical_data(symbol, country=country, from_date=from_date, to_date=max_date) return df
def ApiGetAllByIsinPortafoglio(self, isin, tipologia_strumento): years_obs = timedelta(days=365.24) * 5 endus = datetime.now() endeu = endus.strftime("%d/%m/%Y") #conversioni date US a EU startus = endus - years_obs starteu = startus.strftime("%d/%m/%Y") country_iniziali = isin[:2] #convertitore ISIN to country country = GLOBE.country_isin.get(country_iniziali) df = 0 info_gen = 0 info_tech = 0 if tipologia_strumento == GLOBE.mappa_strumenti.get("stock"): stock = inv.stocks.get_stocks(country = country) info_gen = stock.loc[stock["isin"] == isin] info_tech = inv.stocks.get_stock_information(info_gen["symbol"].values[0], country, as_json=False) df = inv.get_stock_historical_data(stock = info_gen["symbol"].values[0], country = country, from_date = starteu, to_date = endeu, as_json=False, order='ascending', interval = GLOBE.mappa_periodicita.get("Monthly")) elif tipologia_strumento == GLOBE.mappa_strumenti.get("etf"): etf = inv.etfs.get_etfs(country = country) info_gen = etf.loc[etf["isin"] == isin] info_tech = inv.etfs.get_etf_information(info_gen["name"].values[0], country, as_json=False) df = inv.get_etf_historical_data(etf = info_gen["name"].values[0], country = country, from_date = starteu, to_date = endeu, as_json=False, order='ascending', interval = GLOBE.mappa_periodicita.get("Monthly")) elif tipologia_strumento == GLOBE.mappa_strumenti.get("fund"): fund = inv.funds.get_funds(country = country) info_gen = fund.loc[fund["isin"] == isin] info_tech = inv.funds.get_fund_information(info_gen["name"].values[0], country, as_json=False) df = inv.get_fund_historical_data(fund = info_gen["name"].values[0], country = country, from_date = starteu, to_date = endeu, as_json=False, order='ascending', interval = GLOBE.mappa_periodicita.get("Monthly")) all_info_portafoglio = { #dict con tutte le informazioni "datafetch" : df, "info_gen" : info_gen, "info_tech" : info_tech, "tipo_strumento" : tipologia_strumento } return all_info_portafoglio
def import_funds(successfulPulls): # imports funds in the US search_results = investpy.search_funds(by='country', value='united states') list_of_fund_names = search_results["name"] firstIndex = datetime.datetime.strptime(_configKeys.STARTPULL, '%d/%m/%Y') lastIndex = datetime.datetime.strptime(_configKeys.ENDPULL, '%d/%m/%Y') for name in list_of_fund_names[:2500]: try: # Have an if statement in place in case if we don't want to pull every fund because there are a lot of funds # Program takes a long time to run if we have to webscrape every fund each time we run fundData = [] fundData = investpy.get_fund_historical_data( fund=name, country='united states', from_date=_configKeys.STARTPULL, to_date=_configKeys.ENDPULL) newIndex = [] for index in fundData.index: newIndex.append( datetime.datetime.strptime( datetime.datetime.strftime((index + timedelta(days=1)), '%Y-%m-%d'), '%Y-%m-%d')) fundData['Date'] = newIndex fundData.set_index('Date', inplace=True) # If there's something that's been loaded into stockData, then the length is no longer 0 # if the differences is under 2~3 days, then it is ok to take this data since there is still enough data in the week to be usable # this timedelta fixes the problem of trying to pull during a long weekend name = str(name) + "Fund" if fundData.empty == False and fundData.index[ 0] - firstIndex <= timedelta( days=2 ) and lastIndex - fundData.index[-1] <= timedelta(days=3): successfulPulls["Symbol"].append(name.replace("/", "")) successfulPulls["Type"].append("Fund") fundData.to_csv( os.path.join(Path(_configKeys.DATA_FOLDER), name.replace("/", "") + '.csv')) except: print("Something went wrong when importing: " + name)
def get_fund_data(isin: str, start_date: np.datetime64, end_date: np.datetime64) -> pd.DataFrame: """ Gets price data for fund for specified period Args: ticker (str): String ticker with ISIN start_date (np.datetime64): Start date to get price data end_date (np.datetime64): End date to get price data Returns: pd.DataFrame: Dataframe containing close, split, dividend data for ticker from start_date to end_date """ try: fund_search = investpy.search_funds(by='isin', value=isin) name = fund_search.at[0, 'name'] country = fund_search.at[0, 'country'] df = investpy.get_fund_historical_data( fund=name, country=country, from_date=start_date.strftime('%d/%m/%Y'), to_date=end_date.strftime('%d/%m/%Y')) df.drop('Currency', axis=1, inplace=True) df.reset_index(inplace=True) except RuntimeError: # if not in investpy database, check if there is a custom funds module, import and execute custom fund function try: from utils.custom_funds import get_custom_fund_data df = get_custom_fund_data(isin, start_date, end_date) except ImportError: print('No custom funds module available') df = None except ValueError: df = None if isinstance(df, pd.DataFrame): df['Stock Splits'] = 0 df['Dividends'] = 0 df.set_index(['Date'], inplace=True, drop=True) return df
def test_investpy_funds(): """ This function checks that fund data retrieval functions listed in investpy work properly. """ 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': 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_funds_dict(country=param['country'], columns=param['columns'], as_json=param['as_json']) investpy.get_fund_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_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']) 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']) investpy.search_funds(by='name', value='bbva') retrieve_funds(test_mode=True) retrieve_fund_countries(test_mode=True)
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 fetch_prices(): consecutive_trades = '' # Variable for checking consecutive trades (i.e. where two different purchases were sold together) consecutive_trades_I = '' # Another variable for checking consecutive trades (but in second part of code) for equity in enumerate(equities_DF.index): # Add fund/share as dict key, and add sub-dict with key as 'Investpy fund name' / 'ISIN' / 'Ticker' and search name as value. if equity[1] not in prices: prices[equity[1]] = equities_DF.iloc[equity[0], 7:10].dropna().to_dict() consecutive_trades = equity[1] elif equity[ 1] == consecutive_trades: # If a consecutive buy exists, add the date of that buy. prices[equity[1]]['Additional buy'] = equities_DF.iloc[equity[0], 1] consecutive_trades = equity[1] # Set default search country as UK, unless 'USD' found. country = 'United Kingdom' if 'USD' in equity[1]: country = 'United States' elif 'CAD' in equity[1]: country = 'Canada' # Retrieve historic fund/share prices # First check what type of search we need to do: using Fund Name, ISIN, or ticker if equity[ 1] == consecutive_trades_I: # Skip the additional buys if they are part of same sell transaction. print(f'{equity[0]}. Additional buy for {equity[1]} - skipped.') continue elif 'InvestPy Fund Name' in prices[equity[1]]: search_name = prices[equity[1]][ 'InvestPy Fund Name'] # Get value that we use to search InvestPy or Yahoo. try: # Add a df of historical price data to 'Price History' key prices[equity[1]][ 'Price History'] = investpy.get_fund_historical_data( fund=search_name, country= country, # Below converts datetime to string format for searching from_date=equities_DF.iloc[equity[0], -4].strftime('%d/%m/%Y'), to_date=equities_DF.iloc[equity[0], -3].strftime('%d/%m/%Y'), interval='Daily') print( f'{equity[0]}. Retrieved fund price data for {equity[1]}.') except RuntimeError: print( RuntimeError, f'CHECK! InvestPy did not find price data for {equity[1]}') elif 'Stock Ticker' in prices[equity[1]]: search_name = prices[equity[1]]['Stock Ticker'] try: prices[equity[1]][ 'Price History'] = investpy.get_stock_historical_data( stock=search_name, country=country, from_date=equities_DF.iloc[equity[0], -4].strftime('%d/%m/%Y'), to_date=equities_DF.iloc[equity[0], -3].strftime('%d/%m/%Y'), interval='Daily') print( f'{equity[0]}. Retrieved stock price data for {equity[1]}.' ) except RuntimeError: # If InvestPy fails, try Yahoo Finance. prices[equity[1]]['Price History'] = pd.read_csv( f'https://query1.finance.yahoo.com/v7/finance/download/{search_name}?period1={equities_DF.iloc[equity[0], -2]}&period2={equities_DF.iloc[equity[0], -1]}&interval=1d&events=history', index_col='Date') # Yahoo Finance data not downloaded as datetime objects - convert these: prices[equity[1]]['Price History'].index = pd.to_datetime( prices[equity[1]]['Price History'].index, format='%Y-%m-%d') print( f'{equity[0]}. Retrieved stock price data for {equity[1]} from YF.' ) sleep(1) # Ensures we don't overload Yahoo with requests. except HTTPError: print('CHECK! Yahoo Finance request failed for', equity[1]) elif 'ISIN for Yahoo Finance' in prices[equity[1]]: search_name = prices[equity[1]]['ISIN for Yahoo Finance'] try: prices[equity[1]]['Price History'] = pd.read_csv( f'https://query1.finance.yahoo.com/v7/finance/download/{search_name}?period1={equities_DF.iloc[equity[0], -2]}&period2={equities_DF.iloc[equity[0], -1]}&interval=1d&events=history', index_col='Date') prices[equity[1]]['Price History'].index = pd.to_datetime( prices[equity[1]]['Price History'].index, format='%Y-%m-%d') # Convert index to datetime print( f'{equity[0]}. Retrieved fund price data for {equity[1]} using ISIN.' ) sleep(1) except HTTPError: try: # Some ISIN numbers require a '.L' on the end to be found on Yahoo for some reason. prices[equity[1]]['Price History'] = pd.read_csv( f'https://query1.finance.yahoo.com/v7/finance/download/{search_name}.L?period1={equities_DF.iloc[equity[0], -2]}&period2={equities_DF.iloc[equity[0], -1]}&interval=1d&events=history', index_col='Date') prices[equity[1]]['Price History'].index = pd.to_datetime( prices[equity[1]]['Price History'].index, format='%Y-%m-%d') # Convert index to datetime print( f'{equity[0]}. Retrieved fund price data for {equity[1]} using ISIN.' ) sleep(1) except HTTPError: print('CHECK! Yahoo Finance request failed for', equity[1]) except Exception as UnknownError: print('Unknown error for', equity[1], UnknownError) else: # I couldn't find this equity on Investing.com or Yahoo Finance so we just skip it. print(f'{equity[0]}. No price data for this equity - skipped.') consecutive_trades_I = equity[ 1] # Overwrite this var to check for consecutives. # Now correct price data which is in £ not pennies: Some funds randomly change from £s to pennies midway through dataset. try: # Correct values which are < max value divided by 100. prices[equity[1]]['Price History'].loc[ prices[equity[1]]['Price History']['Close'] < prices[equity[1]]['Price History']['Close'].max() / 100, ['Open', 'High', 'Low', 'Close']] *= 100 except KeyError: print(KeyError, 'This equity had no price data')
def my_fund_historical_data(fund, country, from_date, to_date): return investpy.get_fund_historical_data(fund=fund, country=country, from_date=from_date, to_date=to_date)
print(fundo) # In[77]: # pega os dados recentes do fundo nome_fundo = 'Fundo De Investimento Caixa Master Personalizado 50 Renda Fixa Longo Prazo' investpy.get_fund_recent_data(fund=nome_fundo, country='brazil') # In[78]: # Retrieves historical data of 'Bankia Cauto Pp', which is a fund from 'Spain', on the specified date range as a pandas.DataFrame investpy.get_fund_historical_data(fund=nome_fundo, country='brazil', from_date='01/01/2018', to_date='25/09/2020') # In[91]: # LBMA - Quandl url = 'https://www.quandl.com/api/v3/datasets/LBMA/GOLD.json?api_key=x1dVtsgtRJvLJ1tyNh8S' df = pd.read_json(url) df = pd.DataFrame(df['dataset']['data'], columns=df['dataset']['column_names']) df # In[ ]:
def test_investpy_funds(): """ This function checks that fund data retrieval functions listed in investpy work properly. """ 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': ['name'], 'as_json': True }, { 'country': None, 'columns': ['name'], 'as_json': False }, { 'country': 'spain', 'columns': ['name'], 'as_json': True }, { 'country': 'spain', 'columns': ['name'], 'as_json': False }, { 'country': 'spain', 'columns': None, 'as_json': False }, ] for param in params: investpy.get_funds_dict(country=param['country'], columns=param['columns'], as_json=param['as_json']) investpy.get_fund_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_fund_recent_data(fund='bbva multiactivo conservador pp', country='spain', as_json=param['as_json'], order=param['order'], interval='Daily') 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'], interval='Daily') 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 = [ { 'country': 'andorra', 'as_json': True, 'n_results': 2 }, { 'country': 'andorra', 'as_json': False, 'n_results': 2 }, { 'country': 'united states', 'as_json': False, 'n_results': 2 }, { 'country': 'united kingdom', 'as_json': False, 'n_results': 2 } ] for param in params: investpy.get_funds_overview(country=param['country'], as_json=param['as_json'], n_results=param['n_results']) investpy.search_funds(by='name', value='bbva')
as_json=False, order='ascending') # Retrieve the company profile of the introduced stock on english profile = investpy.get_stock_company_profile(stock='bbva', country='spain', language='english') 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,
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 funds(request): price = 0.0 m = money.objects.get(pk=1) amount = m.mymoney amount = round(amount, 2) rem = 1000000 - amount rem = round(rem, 2) close = [] close1 = [] close2 = [] no = [] no1 = [] no2 = [] n = "Funds name" for i in range(len(close)): no.append(i + 1) for i in range(len(close1)): no1.append(i + 1) for i in range(len(close2)): no2.append(i + 1) s = "" labels = [] datap = [] DataFrame3 = "Table for Particular Stock" indianfunds = [ 'Icici Prudential Life - Balancer Fund', 'Hdfc Standard Life - Balanced Managed Investment Pension' ] #fetch recent 10 investments query_results = investmentsinfunds.objects.all().order_by('-id')[:10] last_stock = 0 v1 = 0 if request.method == 'POST': #for buy stock,available assets,investments and pushing purcahses into investment table if ('stockname' in request.POST): n = request.POST['stockname'] #api_key = 'BJQZ9I2H012Q7FDD' #code for profit loss returns none if no query found so used if condition last_stock = investmentsinfunds.objects.filter(name=n).values( 'id', 'price').last() #ts = TimeSeries(key=api_key, output_format='json') #data, meta_data = ts.get_quote_endpoint(n) #get price real-time if (n in indianfunds): v1 = investpy.funds.get_fund_recent_data( fund=n, country='india', as_json=False, order='descending', interval='Daily').iloc[0, :]['Close'] v1 = float(v1) c = CurrencyRates() inrtousd = c.get_rate('INR', 'USD') v1 = v1 * inrtousd price = round(v1, 2) else: v1 = float( investpy.funds.get_fund_recent_data( fund=n, country='united states', as_json=False, order='descending', interval='Daily').iloc[0, :]['Close']) price = round(v1, 2) if (last_stock != None): last_stock = float(last_stock['price']) last_stock = round(last_stock, 2) else: #assigned price because profit or loss=0 if we are adding it to table first time(assumption) last_stock = price if (price != 0.0): if (amount > price): amount = amount - price amount = round(amount, 2) m.mymoney = amount m.save() t = time.localtime() current_time = str(time.strftime("%H:%M:%S", t)) last_stock = price - last_stock last_stock = round(last_stock, 2) a = investmentsinfunds(name=n.upper(), price=price, date_created=str(date.today()), current_time=current_time, gain_loss=last_stock) a.save() rem = 1000000 - amount rem = round(rem, 2) #for table start to end elif ('sn' in request.POST): a11 = request.POST['sdate1'] import datetime darevy = str(datetime.datetime.strptime(a11, "%Y-%m-%d").year) darevd = str(datetime.datetime.strptime(a11, "%Y-%m-%d").day) darevm = str(datetime.datetime.strptime(a11, "%Y-%m-%d").month) a11 = request.POST['edate1'] edarevy = str(datetime.datetime.strptime(a11, "%Y-%m-%d").year) edarevd = str(datetime.datetime.strptime(a11, "%Y-%m-%d").day) edarevm = str(datetime.datetime.strptime(a11, "%Y-%m-%d").month) if (request.POST['sn'] in indianfunds): DataFrame3 = investpy.get_fund_historical_data( fund=request.POST['sn'], country='india', from_date=darevd + '/' + darevm + '/' + darevy, to_date=edarevd + '/' + edarevm + '/' + edarevy) else: DataFrame3 = investpy.get_fund_historical_data( fund=request.POST['sn'], country='united states', from_date=darevd + '/' + darevm + '/' + darevy, to_date=edarevd + '/' + edarevm + '/' + edarevy) DataFrame3 = DataFrame3.to_html() #for graphs start to end else: a11 = request.POST['sdate'] import datetime darevy = str(datetime.datetime.strptime(a11, "%Y-%m-%d").year) darevd = str(datetime.datetime.strptime(a11, "%Y-%m-%d").day) darevm = str(datetime.datetime.strptime(a11, "%Y-%m-%d").month) a11 = request.POST['edate'] edarevy = str(datetime.datetime.strptime(a11, "%Y-%m-%d").year) edarevd = str(datetime.datetime.strptime(a11, "%Y-%m-%d").day) edarevm = str(datetime.datetime.strptime(a11, "%Y-%m-%d").month) if (request.POST['s'] in indianfunds): DataFrame = investpy.get_fund_historical_data( fund=request.POST['s'], country='india', from_date=darevd + '/' + darevm + '/' + darevy, to_date=edarevd + '/' + edarevm + '/' + edarevy) else: DataFrame = investpy.get_fund_historical_data( fund=request.POST['s'], country='united states', from_date=darevd + '/' + darevm + '/' + darevy, to_date=edarevd + '/' + edarevm + '/' + edarevy) #DataFrame = yf.download(request.POST['s'],request.POST['sdate'],request.POST['edate']) close = DataFrame['Close'].tolist() s = str(request.POST['s']) sdate2 = date(int(darevy), int(darevm), int(darevd)) edate2 = date(int(edarevy), int(edarevm), int(edarevd)) delta2 = edate2 - sdate2 for i in range(delta2.days + 1): day = sdate2 + timedelta(days=i) no.append(str(day)) diff = len(no) - len(close) for i in range(1, diff + 1): no.remove(no[i]) d = dict() #for pie chart getting all investemnts summing up the stock by their labels queryset = investmentsinfunds.objects.order_by('name') for stock in queryset: labels.append(stock.name) datap.append(stock.price) for i in range(len(labels)): if (labels[i] in d.keys()): d[labels[i]] += datap[i] else: d[labels[i]] = datap[i] labels = list(d.keys()) datap = list(d.values()) #returning all the calculates values to html return render( request, 'portfolio/funds.html', { 'n': n, 'labels': labels, 'datap': datap, 'price': price, 'amount': amount, 'query_results': query_results, 'rem': rem, 'close': close, 'no': no, 's': s, 'close1': close1, 'close2': close2, 'no1': no1, 'no2': no2, 'DataFrame3': DataFrame3 })
def test_funds_errors(): """ This function raises errors on fund retrieval functions """ try: retrieve_funds(test_mode=None) except: pass try: retrieve_fund_countries(test_mode=None) except: pass params = [ { 'country': ['error'], }, ] for param in params: try: investpy.get_funds(country=param['country']) except: pass try: investpy.get_funds_list(country=param['country']) except: pass params = [ { 'country': ['error'], 'columns': None, 'as_json': False }, { 'country': None, 'columns': None, 'as_json': 'error' }, { 'country': None, 'columns': 0, 'as_json': True }, { 'country': None, 'columns': ['error'], 'as_json': False }, ] for param in params: try: investpy.get_funds_dict(country=param['country'], columns=param['columns'], as_json=param['as_json']) except: pass params = [ { 'fund': None, 'country': 'spain', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'fund': 'quality inversion conservadora fi', 'country': None, 'as_json': False, 'order': 'ascending', 'debug': False }, { 'fund': 'quality inversion conservadora fi', 'country': ['error'], 'as_json': False, 'order': 'ascending', 'debug': False }, { 'fund': 'quality inversion conservadora fi', 'country': 'error', 'as_json': False, 'order': 'ascending', 'debug': False }, { 'fund': 'quality inversion conservadora fi', 'country': 'germany', 'as_json': False, 'order': 'ascending', 'debug': False }, { 'fund': 'quality inversion conservadora fi', 'country': 'spain', 'as_json': 'error', 'order': 'ascending', 'debug': True }, { 'fund': 'quality inversion conservadora fi', 'country': 'spain', 'as_json': True, 'order': 'error', 'debug': True }, { 'fund': 'error', 'country': 'spain', 'as_json': True, 'order': 'ascending', 'debug': True }, { 'fund': ['error'], 'country': 'spain', 'as_json': True, 'order': 'ascending', 'debug': True }, { 'fund': 'quality inversion conservadora fi', 'country': 'spain', 'as_json': True, 'order': 'ascending', 'debug': 'error' }, ] for param in params: try: investpy.get_fund_recent_data(fund=param['fund'], country=param['country'], as_json=param['as_json'], order=param['order'], debug=param['debug']) except: pass params = [ { 'fund': None, 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'fund': 'quality inversion conservadora fi', 'country': None, 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': False }, { 'fund': 'quality inversion conservadora fi', 'country': ['error'], 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': False }, { 'fund': 'quality inversion conservadora fi', 'country': 'error', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': False }, { 'fund': 'quality inversion conservadora fi', 'country': 'germany', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': False }, { 'fund': 'quality inversion conservadora fi', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': 'error', 'order': 'ascending', 'debug': True }, { 'fund': 'quality inversion conservadora fi', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': 'error', 'order': 'ascending', 'debug': True }, { 'fund': 'quality inversion conservadora fi', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'error', 'debug': True }, { 'fund': 'quality inversion conservadora fi', 'country': 'spain', 'from_date': 'error', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'fund': 'quality inversion conservadora fi', 'country': 'spain', 'from_date': '01/01/2019', 'to_date': 'error', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'fund': 'error', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'fund': ['error'], 'country': 'spain', 'from_date': '01/01/1998', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'fund': 'quality inversion conservadora fi', 'country': 'spain', 'from_date': '01/01/1998', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'fund': 'quality inversion conservadora fi', 'country': 'spain', 'from_date': '01/01/2019', 'to_date': '01/01/1998', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'fund': 'quality inversion conservadora fi', 'country': 'spain', 'from_date': '01/01/1900', 'to_date': '01/01/1950', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'fund': 'quality inversion conservadora fi', '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_fund_historical_data(fund=param['fund'], 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 = [ { 'fund': None, 'country': 'spain', 'as_json': False }, { 'fund': 'quality inversion conservadora fi', 'country': None, 'as_json': False }, { 'fund': 'quality inversion conservadora fi', 'country': ['error'], 'as_json': False }, { 'fund': 'quality inversion conservadora fi', 'country': 'error', 'as_json': False }, { 'fund': 'quality inversion conservadora fi', 'country': 'germany', 'as_json': False }, { 'fund': 'quality inversion conservadora fi', 'country': 'spain', 'as_json': 'error' }, { 'fund': 'error', 'country': 'spain', 'as_json': True }, { 'fund': ['error'], 'country': 'spain', 'as_json': True }, ] for param in params: try: investpy.get_fund_information(fund=param['fund'], country=param['country'], as_json=param['as_json']) 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_funds(by=param['by'], value=param['value']) except: pass
stock_from_date = xw.sheets[home_sheet].range('H5').value stock_from_date = stock_from_date.strftime("%d/%m/%Y") stock_to_date = xw.sheets[home_sheet].range('I5').value stock_to_date = stock_to_date.strftime("%d/%m/%Y") bond_from_date = xw.sheets[home_sheet].range('H6').value bond_from_date = bond_from_date.strftime("%d/%m/%Y") bond_to_date = xw.sheets[home_sheet].range('I6').value bond_to_date = bond_to_date.strftime("%d/%m/%Y") if fund and fund_country and fund_from_date and fund_to_date != "": fund_data_historical = investpy.get_fund_historical_data( fund=fund, country=fund_country, from_date=fund_from_date, to_date=fund_to_date) if index and index_country and index_from_date and index_to_date != "": index_data_historical = investpy.get_index_historical_data( index=index, country=index_country, from_date=index_from_date, to_date=index_to_date) if stock and stock_country and stock_from_date and stock_to_date != "": stock_data_historical = investpy.get_stock_historical_data( stock=stock, country=stock_country, from_date=stock_from_date,