class EthPriceFetcher: cg: CoinGeckoAPI cache: dict __instance: EthPriceFetcher = None def __init__(self) -> None: if EthPriceFetcher.__instance is not None: raise Exception("EthPriceFetcher is a singleton") self.cg = CoinGeckoAPI() self.cache = {} EthPriceFetcher.__instance = self @staticmethod def get_instance(): if EthPriceFetcher.__instance is None: EthPriceFetcher() return EthPriceFetcher.__instance def get_eth_usd_price_on_day(self, date: str) -> float: try: if date in self.cache: return self.cache[date] res = self.cg.get_coin_history_by_id("ethereum", date) price = res["market_data"]["current_price"]["usd"] self.cache[date] = price return price except Exception as e: logging.error(e) return 0
def query_coingecko_asset_price(self, asset: str, timestamp: datetime, fiat: str = "usd"): asset = self.get_gecko_token_name(asset) logger.debug("Requesting price of {} at {}".format(asset, timestamp)) if asset == "euro": return self.query_coingecko_asset_price("tether", timestamp, fiat="eur") else: cg = CoinGeckoAPI() data = cg.get_coin_history_by_id( asset, timestamp.strftime("%d-%m-%Y %H:%M:%S"), localization='false') price = data["market_data"]["current_price"][fiat] logger.debug("{} is {} at {}".format(asset, price, timestamp)) return float(price)
return num args = parse_arguments() bitc_price = cg.get_price( ids="bitcoin,litecoin,ethereum", vs_currencies="cad", include_market_cap="true", include_24hr_vol="true", include_24hr_change="true", ) # pprint(bitc_price) # date format is dd-mm-yyyy history = cg.get_coin_history_by_id(id="bitcoin", date="24-09-2020") name = history["name"] symbol = history["symbol"] market_data = history["market_data"] # pprint(market_data) price = market_data["current_price"]["cad"] market_cap = market_data["market_cap"]["cad"] volume = market_data["total_volume"]["cad"] price = sanitize_number(price) market_cap = sanitize_number(market_cap) volume = sanitize_number(volume)
#Giving Choices st.write('''# Choose Date and Amount''') today = datetime.utcnow().date() previous_day = today - timedelta(days=1) HIST_DATE = st.date_input("Date: ", value=previous_day, min_value=datetime(2021, 3, 14), max_value=previous_day) ORG_USD = st.number_input("USD Amount: ", min_value=1, max_value=999999999) #Reformat Historical Date for next function HIST_DATE_REFORMAT = HIST_DATE.strftime("%d-%m-%Y") HIST_DATE_datetime = datetime.strptime(HIST_DATE_REFORMAT, "%d-%m-%Y") sm_historic = cg.get_coin_history_by_id( id='safemoon', vs_currencies='usd', date=HIST_DATE_REFORMAT)['market_data']['current_price']['usd'] sm_historic = round(sm_historic, 9) st.write('''# Results''') st.write('''## Historic Analysis''') st.write("You would have originally bought: ***{:,.2f}*** $SAFEMOON".format( round(ORG_USD / sm_historic), 2)) st.write("At a price of ***{:,.9f}*** per $SAFEMOON".format(sm_historic)) st.write(" ") st.write('''## Present Effects''') total_sm = ORG_USD / sm_historic current_USD = total_sm * sm_current perc_change = (current_USD - ORG_USD) / (ORG_USD) * 100
from pycoingecko import CoinGeckoAPI cg = CoinGeckoAPI() # This gives the historical data of a coin on a particular day # i.e, we want to plot the data of this coin like market_cap or price with other available coins print("Here you can get the coin historical data on a particular day.") id = input("Enter the coin name - ") date = input( "Enter the day on which you want the historical data of this coin in the dd-mm-yyyy format: " ) data = cg.get_coin_history_by_id(id, date) # Example - # if I want to compare bitcoin with all other coins I will enter id as bitcoin # For plotting price this value will be in Y axis and other coins will be on X axis # Their will be bar charts arising from each of these coins # The data is stored in prices and market_cap list prices = data['prices'] market_cap = data['market_cap'] # For each of this you can see first element is coin name and other is conversion price or market_data
token_count = 0 for token, entry_date in data.items(): #token = token.lower() #print(token) if token in token_name: wallet_id.append(wallet) ids = token_id[token_name.index(token)] token_names.append(ids) #ids = token_file.loc[token_file[1]==token,0].item() #ids = token_file[token_file[1]==token][0].apply(lambda x: "'" + str(x) + "'") #ids = "'",ids, "'" print(ids) cg = CoinGeckoAPI() days_50 = 4881600 #56.5 days, just over 8 weeks entry = datetime.utcfromtimestamp(int(entry_date)).strftime('%d-%m-%Y') price_request = cg.get_coin_history_by_id(ids, str(entry)) entry_price = float(price_request.get('market_data')['current_price']['usd']) request = cg.get_coin_market_chart_range_by_id(ids,'usd', int(entry_date) - days_50, int(entry_date) + days_50) content = request.get('prices') token_price_data[ids] = content wk8b = content[0:7] wk7b = content[7:14] wk6b = content[14:21] wk5b = content[21:28] wk4b = content[28:35] wk3b = content[35:42] wk2b = content[42:49] wk1b = content[49:56]
GeckoID = [] for item in Info: GeckoID.append(item['id']) for date in ListOfDays: print('Date:' + date) Name = [] Symbol = [] MarketCap = [] Price = [] Rank = [] for item in CMC_id: if item in GeckoID: Coin = DataMain.get_coin_history_by_id(item, date) if 'market_data' in Coin: MarketCap.append( Coin['market_data']['market_cap'][BaseCurrency.lower()]) Price.append( Coin['market_data']['current_price'][BaseCurrency.lower()]) Symbol.append(Coin['symbol'].upper()) Name.append(Coin['name']) else: MarketCap.append(0.0) Price.append(0.0) Symbol.append(Coin['symbol'].upper()) Name.append(Coin['name']) else: continue
from pycoingecko import CoinGeckoAPI import datetime cg = CoinGeckoAPI() date = [] yesterday = datetime.datetime.now() for i in range(1, 365): nxtDate = yesterday - datetime.timedelta(i) nxtDate = nxtDate.strftime('%d-%m-%Y') date.insert(0, nxtDate) res = cg.get_coin_history_by_id(id = 'tether', date= date[0], localization=False, vs_currencies='usd') prev_buy_price = res['market_data']['current_price']['usd'] startPrice = 3000 amt = startPrice / prev_buy_price money = 0 trades = 0 prev_trades = 0 count = 1 thresh = 0.001 for dt in date: res = cg.get_coin_history_by_id(id = 'tether', date= dt, localization=False, vs_currencies='usd') if 'market_data' not in res.keys(): continue price = res['market_data']['current_price']['usd'] if (prev_buy_price < price - thresh and amt != 0): #sell
# Compute "token weights" for each token # for a rough estimate of capital-weighted # early usage of the Compound protocol # A token's capital weight is taken as the # simple average of its USD price at CompV1deployBlock # and its USD price at COMPlaunchBlock, # the start and end of the early user analysis window. # The following simplifications are adopted to # sidestep limitations in CoinGecko historical data: # --> Stablecoin weights are directly set to 1 # --> Bitcoin data is used for the WBTC price # --> Ethereum data is used for the WETH price CompV1deployBlockDate = '26-09-2018' COMPlaunchBlockDate = '15-06-2020' token_weights = {'sai': 1.0, 'usdc': 1.0, 'dai': 1.0} for token in ['0x', 'basic-attention-token', 'augur', 'ethereum', 'bitcoin']: rawdata = cg.get_coin_history_by_id(token, CompV1deployBlockDate) print(rawdata) StartPrice = rawdata["market_data"]["current_price"]["usd"] print(token + CompV1deployBlockDate + str(StartPrice)) rawdata = cg.get_coin_history_by_id(token, COMPlaunchBlockDate) EndPrice = rawdata["market_data"]["current_price"]["usd"] print(token + CompV1deployBlockDate + str(EndPrice)) token_weights[token] = (0.5 * (StartPrice + EndPrice)) print("token_weights:") print(token_weights)