def show_scatter_and_return_corr(name: str, country: str, start_date: str, end_date: str): BTC = investpy.get_crypto_historical_data(crypto='bitcoin', from_date=start_date, to_date=end_date) try: security = investpy.indices.get_index_historical_data( index=name, country=country, from_date=start_date, to_date=end_date, as_json=False, order='ascending', interval='Daily') except: security = investpy.get_stock_historical_data(stock=name, country=country, from_date=start_date, to_date=end_date) security = security.reindex(BTC.index) security.fillna(value={'Volume': 0}, inplace=True) security.fillna(method='ffill', inplace=True) security.dropna(how='any', inplace=True) BTC = BTC.reindex(security.index) plt.scatter(x=BTC.Close, y=security.Close) plt.show() return security, np.round(np.corrcoef(BTC.Close, security.Close)[0, 1], 2)
def get_Cryptro(assetname): asset = investpy.get_crypto_historical_data(crypto=assetname, from_date='01/01/2010', to_date='01/01/2021') filename = assetname.replace(".", "") filename = filename.replace("/", "") filename = filename.replace(" ", "") filename = filename.replace("&", "") asset.to_csv(wd+'\\toto_data\\'+'crypto-'+filename+'.csv')
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 load_early_data(): ed = investpy.get_crypto_historical_data(crypto='bitcoin', from_date='01/01/2010', to_date=f'31/12/{last_year}') ed = ed.drop(columns=unused_columns) ed.to_csv(csv_early_filename) # This is so that the Date index becomes a column. ed = ed.reset_index(level=0) ed.Date = ed.Date.dt.strftime('%Y-%m-%d') return ed
def get_currency_price(ticker): if ticker in ["EUR", "USD"]: return investpy.get_currency_cross_recent_data( currency_cross='{}/ISK'.format(ticker))['Close'][-1] elif ticker in ["BTC"]: from_date = datetime.datetime.now().strftime("%d/%m/%Y") to_date = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%d/%m/%Y") btc_usd_rate = investpy.get_crypto_historical_data( crypto='bitcoin', from_date=from_date, to_date=to_date)['Close'][-1] return get_currency_price("USD") * btc_usd_rate
def loadData(self): print('Loading ', self.name) try: self.df = investpy.get_crypto_historical_data( crypto=self.name, 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 dataHistoricalCripto(crypto, from_date, to_date): df = investpy.get_crypto_historical_data(crypto=crypto, as_json=True, from_date=from_date, to_date=to_date) result_json = df result_decoded_json = json.loads(result_json)['historical'] resultado = json.dumps(result_decoded_json) out_file = open("consulta_historica_archivo.json", "w") out_file.writelines(str(resultado)) out_file.close() df = pd.read_json(r'consulta_historica_archivo.json') # export_csv = df.to_csv(r'historico_' + crypto + '.csv', index=None, header=True) salida = df return salida
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 get_currency_info(ticker): price_now = get_currency_price(ticker) now = datetime.datetime.now() if ticker in ["EUR", "USD"]: price_year_ago = investpy.get_currency_cross_historical_data( currency_cross="{}/ISK".format(ticker), from_date=(now - datetime.timedelta(days=365)).strftime('%d/%m/%Y'), to_date=(now - datetime.timedelta(days=350) ).strftime('%d/%m/%Y'))['Close'][-1] else: price_year_ago = investpy.get_crypto_historical_data( crypto="bitcoin", 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 get_df_crypto(crypto, age='2Y'): # function to get crypto OLHC prices from name # by default 2 years back in time if 'Y' in age: age = float(age.strip('Y')) date_since = dt.date.today() - dt.timedelta(days=age*365.25) elif 'M' in age: date_since = dt.date.today() - dt.timedelta(days=age*31) date_since = date_since.strftime('%d/%m/%Y') date_to = dt.date.today().strftime('%d/%m/%Y') try: df = investpy.get_crypto_historical_data(crypto=crypto, from_date=date_since, to_date=date_to, as_json=False, order='ascending') df.reset_index(inplace=True) df.columns = [i.lower() for i in df.columns] except: # couldn't retrieve data!! raise Exception(f"Couldn\'t get data for {crypto}") df = pd.DataFrame([]) return df
investpy.get_commodities_list() # Gold Futures (ZGJ2) investpy_Gold = investpy.get_commodity_historical_data(commodity="Gold", from_date="30/01/1900", to_date=DD_END_DATE, country=None, as_json=False, order='ascending', interval='Daily') investpy_Gold.to_pickle('./Market_Watch_Data/investpy_Gold.pkl') ######################################################################################################################## # Bitcoin investpy_bitcoin = investpy.get_crypto_historical_data(crypto='bitcoin', from_date="30/01/1900", to_date=DD_END_DATE, interval='Daily') investpy_bitcoin.to_pickle('./Market_Watch_Data/investpy_bitcoin.pkl') investpy_Ethereum = investpy.get_crypto_historical_data(crypto='Ethereum', from_date="30/01/1900", to_date=DD_END_DATE, interval='Daily') investpy_Ethereum.to_pickle('./Market_Watch_Data/investpy_Ethereum.pkl') investpy_Ripple = investpy.get_crypto_historical_data(crypto='XRP', from_date="30/01/1900", to_date=DD_END_DATE, interval='Daily') investpy_Ripple.to_pickle('./Market_Watch_Data/investpy_Ripple.pkl')
import investpy from datetime import datetime import pandas as pd from prompt_toolkit import prompt import csv import os import seaborn as sns import matplotlib.pyplot as plt from IPython.display import display from PIL import Image from_date = input('Start date (DD/MM/YYYY): ') to_date = input('End date (DD/MM/YYYY): ') btc = investpy.get_crypto_historical_data(crypto='bitcoin', from_date=from_date, to_date=to_date) btc.reset_index(inplace = True) close_px = btc['Close'] btc['50d'] = close_px.rolling(window=50).mean() btc['200d'] = close_px.rolling(window=200).mean() csvPath = 'data/stocks' csvName = input("Save csv as: ") + '.csv' csvFileName = os.path.join(csvPath, csvName) btc.to_csv(csvFileName) fig, ax = plt.subplots() ax.plot(btc['Date'], btc[['Close', '50d', '200d']]) ax.set_ylabel('Price')
'NRG': 'Energi', 'HC': 'HyperCash', 'STEEM': 'Steem', 'ZIL': 'Zilliqa', 'QNT': 'Quant', 'SLV': 'Silverway', 'BTS': 'BitShares', 'FXC': 'Flexacoin', 'ARDR': 'Ardor', 'AE': 'Aeternity', 'XET': 'ETERNAL TOKEN' } for key, val in top_100_coin_dict.items(): data = investpy.get_crypto_historical_data(crypto=val, from_date='14/07/2020', to_date='16/07/2020', as_json=False) print("\n" + key) print(data) # write all top 100 coin name coin_column = 1 for key, val in top_100_coin_dict.items(): print(key, val) sheet_two.write(0, 0, "Symbol") sheet_two.write(0, 1, "Name") sheet_two.write(coin_column, 0, key) sheet_two.write(coin_column, 1, val)
def get_crypto(crypto_name, start, end): crypto = investpy.get_crypto_historical_data(crypto_name, from_date=start, to_date=end) return crypto
from_date='01/01/2012', to_date='12/01/2030') eur_df = eur_df.drop(['High', 'Low', 'Currency'], axis=1) # print(eur_df.tail()) # Gold/Usd gold_df = pdr.DataReader('GOLDAMGBD228NLBM', data_source, starttime, endtime) # print(gold_df.tail()) # Silver/Usd silver_df = pdr.DataReader('SLVPRUSD', data_source, starttime, endtime) # print(silver_df.tail()) # Bitcoin/Usd and BTC_Volume bitcoin_df = investpy.get_crypto_historical_data(crypto='bitcoin', from_date='01/01/2012', to_date='12/01/2030') bitcoin_df = bitcoin_df.drop(['Open', 'High', 'Low', 'Currency'], axis=1) # print(bitcoin_df.tail()) lite_df = investpy.get_crypto_historical_data(crypto='litecoin', from_date='01/01/2012', to_date='12/01/2030') lite_df = lite_df.drop(['Open', 'High', 'Low', 'Currency'], axis=1) lite_df.columns = ['lite', 'Volume'] lite_df['lite_mean'] = lite_df['lite'].rolling(21).mean() lite_df['lite_std'] = lite_df['lite'].rolling(21).std() lite_df['lite_low'] = lite_df['lite_mean'] - lite_df['lite_std'] * 2
if os.path.isfile(csv_early_filename): early_data = pd.read_csv(csv_early_filename) most_recent_year = int(max(early_data.Date).split('-')[0]) if most_recent_year < last_year: early_data = load_early_data() else: early_data = load_early_data() today_str = today.strftime('%d/%m/%Y') jan1_this_year = f'01/01/{today.year}' # Get data for this year data = investpy.get_crypto_historical_data(crypto='bitcoin', from_date=jan1_this_year, to_date=today_str) data = data.drop(columns=unused_columns) data = data.reset_index(level=0) data.Date = data.Date.dt.strftime('%Y-%m-%d') data = pd.concat([early_data, data], ignore_index=True) with open('data/btcusd_annotated.csv', 'w') as f1: annotated = csv.writer(f1) annotated.writerow(['Date', 'Close', 'News', 'url']) news = {} urls = {}
def fetchData(self): df = investpy.get_crypto_historical_data( self.crypto, from_date=self.start_date.strftime("%d/%m/%Y"), to_date=self.end_date.strftime("%d/%m/%Y")) return df
def test_investpy_cryptos(): """ This function checks that crypto currencies data retrieval functions listed in investpy work properly. """ investpy.get_cryptos() investpy.get_cryptos_list() params = [ { 'columns': None, 'as_json': False }, { 'columns': ['name', 'symbol', 'currency'], 'as_json': False }, { 'columns': None, 'as_json': True }, ] for param in params: investpy.get_cryptos_dict(columns=param['columns'], as_json=param['as_json']) 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_crypto_recent_data(crypto='bitcoin', as_json=param['as_json'], order=param['order'], interval='Daily') investpy.get_crypto_historical_data(crypto='bitcoin', from_date='01/01/1990', to_date='01/01/2019', as_json=param['as_json'], order=param['order'], interval='Daily') params = [ { 'crypto': 'bitcoin', 'as_json': False }, { 'crypto': 'bitcoin', 'as_json': True } ] for param in params: investpy.get_crypto_information(crypto=param['crypto'], as_json=param['as_json']) params = [ { 'as_json': False, 'n_results': 10 }, { 'as_json': True, 'n_results': 10 }, { 'as_json': False, 'n_results': 110 }, { 'as_json': True, 'n_results': 110 }, { 'as_json': False, 'n_results': None }, { 'as_json': True, 'n_results': None }, ] for param in params: investpy.get_cryptos_overview(as_json=param['as_json'], n_results=param['n_results']) investpy.search_cryptos(by='name', value='bitcoin')
import investpy df = investpy.get_stock_historical_data(stock='blue', country='United States', from_date='01/02/2021', to_date='23/02/2021') crypto = investpy.get_crypto_historical_data('ethereum', from_date='28/01/2021', to_date='23/02/2021') test = investpy.get_stock_financial_summary(stock='aapl', country='United States', summary_type='income_statement', period='annual') print(test.head())