def load( coin: str, source: str, ) -> Tuple[Union[Optional[str], pycoingecko_model.Coin], Any]: """Load cryptocurrency from given source. Available sources are: CoinGecko, CoinPaprika, Coinbase and Binance. Loading coin from Binance and CoinPaprika means validation if given coins exists in chosen source, if yes then id of the coin is returned as a string. In case of CoinGecko load will return Coin object, if provided coin exists. Coin object has access to different coin information. Parameters ---------- coin: str Coin symbol or id which is checked if exists in chosen data source. source : str Source of the loaded data. CoinGecko, CoinPaprika, or Binance Returns ------- Tuple[Union[str, pycoingecko_model.Coin], Any] - str or Coin object for provided coin - str with source of the loaded data. CoinGecko, CoinPaprika, or Binance """ current_coin = "" # type: Optional[Any] if source == "cg": current_coin = pycoingecko_model.Coin(coin) return current_coin, source if source == "bin": parsed_coin = coin.upper() current_coin, pairs = show_available_pairs_for_given_symbol( parsed_coin) if len(pairs) > 0: print(f"Coin found : {current_coin}\n") else: print(f"Couldn't find coin with symbol {current_coin}\n") return current_coin, source if source == "cp": paprika_coins = get_list_of_coins() paprika_coins_dict = dict(zip(paprika_coins.id, paprika_coins.symbol)) current_coin, _ = coinpaprika_model.validate_coin( coin, paprika_coins_dict) return current_coin, source if source == "cb": coinbase_coin = coin.upper() current_coin, pairs = coinbase_model.show_available_pairs_for_given_symbol( coinbase_coin) if len(pairs) > 0: print(f"Coin found : {current_coin}\n") else: print(f"Couldn't find coin with symbol {current_coin}\n") return current_coin, source return current_coin, None
def prepare_all_coins_df() -> pd.DataFrame: """Helper method which loads coins from all sources: CoinGecko, CoinPaprika, Binance and merge those coins on keys: CoinGecko - > name < - CoinPaprika CoinGecko - > id <- Binance Returns ------- pd.DataFrame CoinGecko - id for coin in CoinGecko API: uniswap CoinPaprika - id for coin in CoinPaprika API: uni-uniswap Binance - symbol (baseAsset) for coin in Binance API: UNI Coinbase - symbol for coin in Coinbase Pro API e.g UNI Symbol: uni """ gecko_coins_df = get_coin_list() paprika_coins_df = get_list_of_coins() # TODO: Think about scheduled job, that once a day will update data binance_coins_df = load_binance_map().rename(columns={"symbol": "Binance"}) coinbase_coins_df = load_coinbase_map().rename( columns={"symbol": "Coinbase"}) gecko_paprika_coins_df = pd.merge(gecko_coins_df, paprika_coins_df, on="name", how="left") df_merged = pd.merge( left=gecko_paprika_coins_df, right=binance_coins_df, left_on="id_x", right_on="id", how="left", ) df_merged.rename( columns={ "id_x": "CoinGecko", "symbol_x": "Symbol", "id_y": "CoinPaprika", }, inplace=True, ) df_merged = pd.merge( left=df_merged, right=coinbase_coins_df, left_on="CoinGecko", right_on="id", how="left", ) return df_merged[[ "CoinGecko", "CoinPaprika", "Binance", "Coinbase", "Symbol" ]]
def load(other_args: List[str]): """Select coin from CoinPaprika Parameters ---------- other_args: List[str] Argparse arguments Returns ------- coin: str Coin that is defined on binance df_coin : pd.DataFrame Dataframe of prices for selected coin """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="load", description="Define the coin to be used from CoinPaprika and get data", ) parser.add_argument( "-c", "--coin", help="Coin to get", dest="coin", type=str, required="-h" not in other_args, ) try: if other_args: if not other_args[0][0] == "-": other_args.insert(0, "-c") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return COINS = get_list_of_coins() COINS_DCT = dict(zip(COINS.id, COINS.symbol)) coin_id, _ = paprika.validate_coin(ns_parser.coin, COINS_DCT) if coin_id: return coin_id except SystemExit: print("") except Exception as e: print(e, "\n")
def display_all_coins(source: str, coin: str, top: int, skip: int, show_all: bool, export: str) -> None: """Find similar coin by coin name,symbol or id. If you don't remember exact name or id of the Coin at CoinGecko, CoinPaprika, Coinbase, Binance you can use this command to display coins with similar name, symbol or id to your search query. Example of usage: coin name is something like "polka". So I can try: find -c polka -k name -t 25 It will search for coin that has similar name to polka and display top 25 matches. -c, --coin stands for coin - you provide here your search query -t, --top it displays top N number of records. Parameters ---------- top: int Number of records to display coin: str Cryptocurrency source: str Data source of coins. CoinGecko (cg) or CoinPaprika (cp) or Binance (bin), Coinbase (cb) skip: int Skip N number of records show_all: bool Flag to show all sources of data export : str Export dataframe data to csv,json,xlsx file """ sources = ["cg", "cp", "bin", "cb"] limit, cutoff = 30, 0.75 coins_func_map = { "cg": get_coin_list, "cp": get_list_of_coins, "bin": load_binance_map, "cb": load_coinbase_map, } if show_all: coins_func = coins_func_map.get(source) if coins_func: df = coins_func() else: df = prepare_all_coins_df() elif not source or source not in sources: df = prepare_all_coins_df() cg_coins_list = df["CoinGecko"].to_list() sim = difflib.get_close_matches(coin.lower(), cg_coins_list, limit, cutoff) df_matched = pd.Series(sim).to_frame().reset_index() df_matched.columns = ["index", "CoinGecko"] df = df.merge(df_matched, on="CoinGecko") df.drop("index", axis=1, inplace=True) else: if source == "cg": coins_df = get_coin_list().drop("index", axis=1) df = _create_closest_match_df(coin.lower(), coins_df, limit, cutoff) df = df[["index", "id", "name"]] elif source == "cp": coins_df = get_list_of_coins() df = _create_closest_match_df(coin.lower(), coins_df, limit, cutoff) df = df[["index", "id", "name"]] elif source == "bin": coins_df_gecko = get_coin_list() coins_df_bin = load_binance_map() coins_df_bin.columns = ["symbol", "id"] coins_df = pd.merge(coins_df_bin, coins_df_gecko[["id", "name"]], how="left", on="id") df = _create_closest_match_df(coin.lower(), coins_df, limit, cutoff) df = df[["index", "symbol", "name"]] df.columns = ["index", "id", "name"] elif source == "cb": coins_df_gecko = get_coin_list() coins_df_cb = load_coinbase_map() coins_df_cb.columns = ["symbol", "id"] coins_df = pd.merge(coins_df_cb, coins_df_gecko[["id", "name"]], how="left", on="id") df = _create_closest_match_df(coin.lower(), coins_df, limit, cutoff) df = df[["index", "symbol", "name"]] df.columns = ["index", "id", "name"] else: df = pd.DataFrame(columns=["index", "id", "symbol"]) print("Couldn't find any coins") print("") try: df = df[skip:skip + top] except Exception as e: print(e) if gtff.USE_TABULATE_DF: print( tabulate( df, headers=df.columns, floatfmt=".1f", showindex=False, tablefmt="fancy_grid", )) else: print(df.to_string, "\n") export_data( export, os.path.dirname(os.path.abspath(__file__)), "coins", df, )
def find(source: str, coin: str, key: str, top: int, export: str) -> None: """Find similar coin by coin name,symbol or id. If you don't remember exact name or id of the Coin at CoinGecko CoinPaprika, Binance or Coinbase you can use this command to display coins with similar name, symbol or id to your search query. Example of usage: coin name is something like "polka". So I can try: find -c polka -k name -t 25 It will search for coin that has similar name to polka and display top 25 matches. -c, --coin stands for coin - you provide here your search query -k, --key it's a searching key. You can search by symbol, id or name of coin -t, --top it displays top N number of records. Parameters ---------- top: int Number of records to display coin: str Cryptocurrency key: str Searching key (symbol, id, name) source: str Data source of coins. CoinGecko (cg) or CoinPaprika (cp) or Binance (bin), Coinbase (cb) export : str Export dataframe data to csv,json,xlsx file """ if source == "cg": coins_df = get_coin_list() coins_list = coins_df[key].to_list() if key in ["symbol", "id"]: coin = coin.lower() sim = difflib.get_close_matches(coin, coins_list, top) df = pd.Series(sim).to_frame().reset_index() df.columns = ["index", key] coins_df.drop("index", axis=1, inplace=True) df = df.merge(coins_df, on=key) elif source == "cp": coins_df = get_list_of_coins() coins_list = coins_df[key].to_list() keys = {"name": "title", "symbol": "upper", "id": "lower"} func_key = keys[key] coin = getattr(coin, str(func_key))() sim = difflib.get_close_matches(coin, coins_list, top) df = pd.Series(sim).to_frame().reset_index() df.columns = ["index", key] df = df.merge(coins_df, on=key) elif source == "bin": # TODO: Fix it in future. Determine if user looks for symbol like ETH or ethereum if len(coin) > 5: key = "id" coins_df_gecko = get_coin_list() coins_df_bin = load_binance_map() coins = pd.merge(coins_df_bin, coins_df_gecko[["id", "name"]], how="left", on="id") coins_list = coins[key].to_list() sim = difflib.get_close_matches(coin, coins_list, top) df = pd.Series(sim).to_frame().reset_index() df.columns = ["index", key] df = df.merge(coins, on=key) elif source == "cb": if len(coin) > 5: key = "id" coins_df_gecko = get_coin_list() coins_df_bin = load_coinbase_map() coins = pd.merge(coins_df_bin, coins_df_gecko[["id", "name"]], how="left", on="id") coins_list = coins[key].to_list() sim = difflib.get_close_matches(coin, coins_list, top) df = pd.Series(sim).to_frame().reset_index() df.columns = ["index", key] df = df.merge(coins, on=key) else: print( "Couldn't execute find methods for CoinPaprika, Binance, Coinbase or CoinGecko\n" ) df = pd.DataFrame() if gtff.USE_TABULATE_DF: print( tabulate( df, headers=df.columns, floatfmt=".1f", showindex=False, tablefmt="fancy_grid", ), "\n", ) else: print(df.to_string, "\n") export_data( export, os.path.dirname(os.path.abspath(__file__)), "find", df, )
def load( coin: str, source: str = "cp", days: int = 60, vs: str = "usd", interval: str = "1day", should_load_ta_data: bool = False, ): """Load cryptocurrency from given source. Available sources are: CoinGecko, CoinPaprika, Coinbase, Binance and Yahoo Finance Loading coin from Binance and CoinPaprika means validation if given coins exists in chosen source, if yes then id of the coin is returned as a string. In case of CoinGecko load will return Coin object, if provided coin exists. Coin object has access to different coin information. Parameters ---------- coin: str Coin symbol or id which is checked if exists in chosen data source. source : str Source of the loaded data. CoinGecko, CoinPaprika, Yahoo Finance or Binance Returns ------- Tuple[Union[str, pycoingecko_model.Coin], str, str] - str or Coin object for provided coin - str with source of the loaded data. CoinGecko, CoinPaprika, Yahoo Finance or Binance - str with symbol - Dataframe with coin map to different sources """ if source in ("cg", "cp"): if vs not in ("USD", "BTC", "usd", "btc"): console.print( "You can only compare with usd or btc (e.g., --vs usd)\n") return None, None, None, None, None, None if interval != "1day": console.print( "Only daily data is supported for coingecko and coinpaprika (e.g., -i 1day)\n" ) return None, None, None, None, None, None current_coin = "" # type: Optional[Any] coins_map_df = prepare_all_coins_df().set_index("Symbol").dropna(thresh=2) if source == "cg": coingecko = pycoingecko_model.Coin(coin.lower(), True) if not coingecko.symbol: return None, None, None, None, None, None coin_map_df = coins_map_df.loc[coingecko.symbol] coin_map_df = ( coin_map_df.iloc[0] if isinstance(coin_map_df, pd.DataFrame) else coin_map_df ) # TODO: improve to choose the row that matches better; # if it is dataframe, it means that found more than 1 coin if should_load_ta_data: df_prices, currency = load_ta_data( coin_map_df=coin_map_df, source=source, currency=vs, days=days, limit=0, interval=interval, ) return ( str(coingecko), source, coingecko.symbol, coin_map_df, df_prices, currency, ) return ( str(coingecko), source, coingecko.symbol, coin_map_df, None, None, ) if source == "cp": paprika_coins = get_list_of_coins() paprika_coins_dict = dict(zip(paprika_coins.id, paprika_coins.symbol)) current_coin, symbol = coinpaprika_model.validate_coin( coin, paprika_coins_dict) if not symbol: return None, None, None, None, None, None coin_map_df = coins_map_df.loc[symbol.lower( ) if symbol is not None else symbol] coin_map_df = (coin_map_df.iloc[0] if isinstance( coin_map_df, pd.DataFrame) else coin_map_df) if should_load_ta_data: df_prices, currency = load_ta_data( coin_map_df=coin_map_df, source=source, currency=vs, days=days, limit=0, interval=interval, ) return (current_coin, source, symbol, coin_map_df, df_prices, currency) return (current_coin, source, symbol, coin_map_df, None, None) if source == "bin": if vs == "usd": vs = "USDT" if interval not in SOURCES_INTERVALS["bin"]: console.print( "Interval not available on binance. Run command again with one supported (e.g., -i 1day):\n", SOURCES_INTERVALS["bin"], ) return None, None, None, None, None, None # TODO: convert bitcoin to btc before searching pairs parsed_coin = coin.upper() current_coin, pairs = show_available_pairs_for_given_symbol( parsed_coin) if len(pairs) > 0: if vs not in pairs: console.print( "vs specified not supported by binance. Run command again with one supported (e.g., --vs USDT):\n", pairs, ) return None, None, None, None, None, None coin_map_df = coins_map_df.loc[parsed_coin.lower()] coin_map_df = (coin_map_df.iloc[0] if isinstance( coin_map_df, pd.DataFrame) else coin_map_df) # console.print(f"Coin found : {current_coin}\n") if should_load_ta_data: df_prices, currency = load_ta_data( coin_map_df=coin_map_df, source=source, currency=vs, days=0, limit=days, interval=interval, ) return ( current_coin, source, parsed_coin, coin_map_df, df_prices, currency, ) return (current_coin, source, parsed_coin, coin_map_df, None, None) return None, None, None, None, None, None if source == "cb": if vs == "usd": vs = "USDT" if interval not in SOURCES_INTERVALS["cb"]: console.print( "Interval not available on coinbase. Run command again with one supported (e.g., -i 1day):\n", SOURCES_INTERVALS["cb"], ) return None, None, None, None, None, None # TODO: convert bitcoin to btc before searching pairs coinbase_coin = coin.upper() current_coin, pairs = coinbase_model.show_available_pairs_for_given_symbol( coinbase_coin) if vs not in pairs: console.print( "vs specified not supported by coinbase. Run command again with one supported (e.g., --vs USDT):\n", pairs, ) return None, None, None, None, None, None if len(pairs) > 0: # console.print(f"Coin found : {current_coin}\n") coin_map_df = coins_map_df.loc[coin] coin_map_df = (coin_map_df.iloc[0] if isinstance( coin_map_df, pd.DataFrame) else coin_map_df) if should_load_ta_data: df_prices, currency = load_ta_data( coin_map_df=coin_map_df, source=source, currency=vs, days=0, limit=days, interval=interval, ) return (current_coin, source, coin, coin_map_df, df_prices, currency) return (current_coin, source, coin, coin_map_df, None, None) console.print(f"Couldn't find coin with symbol {current_coin}\n") return None, None, None, None, None, None if source == "yf": if vs.upper() not in YF_CURRENCY: console.print( "vs specified not supported by Yahoo Finance. Run command again with one supported (e.g., --vs USD):\n", YF_CURRENCY, ) return None, None, None, None, None, None if interval not in SOURCES_INTERVALS["yf"]: console.print( "Interval not available on YahooFinance. Run command again with one supported (e.g., -i 1day):\n", SOURCES_INTERVALS["yf"], ) return None, None, None, None, None, None # Search coin using crypto symbol coin_map_df_1 = coins_map_df.loc[coins_map_df.index == coin] # Search coin using yfinance id coin_map_df_2 = coins_map_df.loc[coins_map_df.YahooFinance == f"{coin.upper()}-{vs.upper()}"] # Search coin using crypto full name coin_map_df_3 = coins_map_df.loc[coins_map_df.CoinGecko == coin] for _df in [coin_map_df_1, coin_map_df_2, coin_map_df_3]: if not _df.empty: coin_map_df = _df break if coin_map_df.empty: console.print( f"Cannot find {coin} against {vs} on Yahoo finance. Try another source or currency.\n" ) return None, None, None, None, None, None if (coin_map_df["YahooFinance"]).isna().all(): console.print( f"Cannot find {coin} Yahoo finance. Try another source.\n") return None, None, None, None, None, None # Filter for the currency coin_map_df = coin_map_df[ coin_map_df["YahooFinance"].str.upper().str.contains(vs.upper())] coin_map_df = (coin_map_df.iloc[0] if isinstance( coin_map_df, pd.DataFrame) else coin_map_df) if should_load_ta_data: df_prices, currency = load_ta_data( coin_map_df=coin_map_df, source=source, currency=vs, days=days, limit=0, interval=interval, ) return ( coin_map_df["YahooFinance"], source, coin, coin_map_df, df_prices, currency, ) return ( coin_map_df["YahooFinance"], source, coin, coin_map_df, None, None, ) return None, None, None, None, None, None
def coins(other_args: List[str]): """Shows list of all available coins on CoinPaprika Parameters ---------- other_args: List[str] Arguments to pass to argparse """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="coins", description="""Shows list of all available coins on CoinPaprika. You can display top N number of coins with --top N flag, You can search by starting letters with -l/--letter flag like `coins -l M` And you can also specify by which column you are searching for coin with --key Displays columns like: rank, id, name, type""", ) parser.add_argument( "-s", "--skip", default=0, dest="skip", help="Skip n of records", type=check_positive, ) parser.add_argument( "-t", "--top", default=30, dest="top", help="Limit of records", type=check_positive, ) parser.add_argument("-l", "--letter", dest="letter", help="First letters", type=str) parser.add_argument( "-k", "--key", dest="key", help="Search in column symbol, name, id", type=str, choices=["id", "symbol", "name"], default="symbol", ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return df = get_list_of_coins() letter = ns_parser.letter if letter and isinstance(letter, str): df = df[df[ns_parser.key].str.match( f"^({letter.lower()}|{letter.upper()})")] try: df = df[ns_parser.skip:ns_parser.skip + ns_parser.top] except Exception as e: print(e) print( tabulate( df, headers=df.columns, floatfmt=".1f", showindex=False, tablefmt="fancy_grid", ), "\n", ) except Exception as e: print(e, "\n")
def find(other_args: List[str]): parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="find", description=""" Find similar coin by coin name,symbol or id. If you don't remember exact name or id of the Coin at CoinPaprika, you can use this command to display coins with similar name, symbol or id to your search query. Example of usage: coin name is something like "kusama". So : find -c kusama -k name -t 25 It will search for coin that has similar name to kusama and display top 25 matches. -c, --coin stands for coin - you provide here your search query -k, --key it's a searching key. You can search by symbol, id or name of coin -t, --top it displays top N number of records. """, ) parser.add_argument( "-c", "--coin", help="Coin name or id, or symbol", dest="coin", required="-h" not in other_args, type=str, ) parser.add_argument( "-k", "--key", dest="key", help= "Specify by which column you would like to search: symbol, name, id", type=str, choices=["id", "symbol", "name"], default="name", ) parser.add_argument( "-t", "--top", default=10, dest="top", help="Limit of records", type=check_positive, ) try: if other_args: if not other_args[0][0] == "-": other_args.insert(0, "-c") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return if not ns_parser.coin or ns_parser.coin is None: print( "You didn't provide coin. Please use param -c/--coin <coin name>", "\n") return coins_df = get_list_of_coins() coins_list = coins_df[ns_parser.key].to_list() keys = {"name": "title", "symbol": "upper", "id": "lower"} key = keys.get(ns_parser.key) coin = getattr(ns_parser.coin, str(key))() sim = difflib.get_close_matches(coin, coins_list, ns_parser.top) df = pd.Series(sim).to_frame().reset_index() df.columns = ["index", ns_parser.key] df = df.merge(coins_df, on=ns_parser.key) print( tabulate( df, headers=df.columns, floatfmt=".1f", showindex=False, tablefmt="fancy_grid", ), "\n", ) except Exception as e: print(e, "\n")
def all_coins(other_args: List[str]): """Find similar coin by coin name,symbol or id. If you don't remember exact name or id of the Coin at CoinGecko or CoinPaprika you can use this command to display coins with similar name, symbol or id to your search query. Example of usage: coin name is something like "polka". So I can try: find -c polka -k name -t 25 It will search for coin that has similar name to polka and display top 25 matches. -c, --coin stands for coin - you provide here your search query -t, --top it displays top N number of records. Parameters ---------- other_args: List[str] Arguments to pass to argparse """ parser = argparse.ArgumentParser( prog="coins", add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, description= """Shows list of coins available on CoinGecko, CoinPaprika and Binance. If you provide name of coin then in result you will see ids of coins with best match for all mentioned services. If you provide ALL keyword in your search query, then all coins will be displayed. To move over the coins you can use pagination mechanism with skip, top params. E.g. coins ALL --skip 100 --limit 30 then all coins from 100 to 130 will be displayed. By default skip = 0, limit = 10. If you won't provide source of the data everything will be displayed (CoinGecko, CoinPaprika, Binance). If you want to search only in given source then use --source flag. E.g. if you want to find coin with name uniswap on CoinPaprika then use: coins uniswap --source cp --limit 10 """, ) parser.add_argument( "-c", "--coin", help="Coin you search for", dest="coin", required="-h" not in other_args, type=str, ) parser.add_argument( "-s", "--skip", default=0, dest="skip", help="Skip n of records", type=check_positive, ) parser.add_argument( "-l", "--limit", default=10, dest="top", help="Limit of records", type=check_positive, ) parser.add_argument( "--source", dest="source", required=False, help="Source of data.", type=str, ) limit, cutoff = 30, 0.75 coins_func_map = { "cg": get_coin_list, "cp": get_list_of_coins, "bin": load_binance_map, } try: if other_args: if not other_args[0][0] == "-": other_args.insert(0, "-c") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return if "ALL" in other_args: coins_func = coins_func_map.get(ns_parser.source) if coins_func: df = coins_func() else: df = prepare_all_coins_df() elif not ns_parser.source or ns_parser.source not in [ "cg", "cp", "bin" ]: df = prepare_all_coins_df() cg_coins_list = df["CoinGecko"].to_list() sim = difflib.get_close_matches(ns_parser.coin.lower(), cg_coins_list, limit, cutoff) df_matched = pd.Series(sim).to_frame().reset_index() df_matched.columns = ["index", "CoinGecko"] df = df.merge(df_matched, on="CoinGecko") df.drop("index", axis=1, inplace=True) else: if ns_parser.source == "cg": coins_df = get_coin_list().drop("index", axis=1) df = _create_closest_match_df(ns_parser.coin.lower(), coins_df, limit, cutoff) df = df[["index", "id", "name"]] elif ns_parser.source == "cp": coins_df = get_list_of_coins() df = _create_closest_match_df(ns_parser.coin.lower(), coins_df, limit, cutoff) df = df[["index", "id", "name"]] elif ns_parser.source == "bin": coins_df_gecko = get_coin_list() coins_df_bin = load_binance_map() coins_df_bin.columns = ["symbol", "id"] coins_df = pd.merge(coins_df_bin, coins_df_gecko[["id", "name"]], how="left", on="id") df = _create_closest_match_df(ns_parser.coin.lower(), coins_df, limit, cutoff) df = df[["index", "symbol", "name"]] df.columns = ["index", "id", "name"] else: df = pd.DataFrame(columns=["index", "id", "symbol"]) print("Couldn't find any coins") print("") try: df = df[ns_parser.skip:ns_parser.skip + ns_parser.top] except Exception as e: print(e) print( tabulate( df, headers=df.columns, floatfmt=".1f", showindex=False, tablefmt="fancy_grid", )) except Exception as e: print(e, "\n")
def find(other_args: List[str]): """Find similar coin by coin name,symbol or id. If you don't remember exact name or id of the Coin at CoinGecko or CoinPaprika you can use this command to display coins with similar name, symbol or id to your search query. Example of usage: coin name is something like "polka". So I can try: find -c polka -k name -t 25 It will search for coin that has similar name to polka and display top 25 matches. -c, --coin stands for coin - you provide here your search query -k, --key it's a searching key. You can search by symbol, id or name of coin -t, --top it displays top N number of records. Parameters ---------- other_args: List[str] Arguments to pass to argparse """ parser = argparse.ArgumentParser( prog="find", add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=""" Find similar coin by coin name,symbol or id. If you don't remember exact name or id of the Coin at CoinGecko, Binance or CoinPaprika you can use this command to display coins with similar name, symbol or id to your search query. Example of usage: coin name is something like "polka". So I can try: find -c polka -k name -t 25 It will search for coin that has similar name to polka and display top 25 matches. -c, --coin stands for coin - you provide here your search query -k, --key it's a searching key. You can search by symbol, id or name of coin -t, --top it displays top N number of records.""", ) parser.add_argument( "-c", "--coin", help="Symbol Name or Id of Coin", dest="coin", required="-h" not in other_args, type=str, ) parser.add_argument( "-k", "--key", dest="key", help= "Specify by which column you would like to search: symbol, name, id", type=str, choices=["id", "symbol", "name"], default="symbol", ) parser.add_argument( "-t", "--top", default=10, dest="top", help="Limit of records", type=check_positive, ) parser.add_argument( "--source", dest="source", choices=["cp", "cg", "bin"], default="cg", help="Source of data.", type=str, ) try: if other_args: if not other_args[0][0] == "-": other_args.insert(0, "-c") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return if ns_parser.source == "cg": coins_df = get_coin_list() coins_list = coins_df[ns_parser.key].to_list() sim = difflib.get_close_matches(ns_parser.coin, coins_list, ns_parser.top) df = pd.Series(sim).to_frame().reset_index() df.columns = ["index", ns_parser.key] coins_df.drop("index", axis=1, inplace=True) df = df.merge(coins_df, on=ns_parser.key) print( tabulate( df, headers=df.columns, floatfmt=".1f", showindex=False, tablefmt="fancy_grid", )) elif ns_parser.source == "cp": coins_df = get_list_of_coins() coins_list = coins_df[ns_parser.key].to_list() keys = {"name": "title", "symbol": "upper", "id": "lower"} key = keys.get(ns_parser.key) coin = getattr(ns_parser.coin, str(key))() sim = difflib.get_close_matches(coin, coins_list, ns_parser.top) df = pd.Series(sim).to_frame().reset_index() df.columns = ["index", ns_parser.key] df = df.merge(coins_df, on=ns_parser.key) print( tabulate( df, headers=df.columns, floatfmt=".1f", showindex=False, tablefmt="fancy_grid", )) elif ns_parser.source == "bin": # TODO: Fix it in future. Determine if user looks for symbol like ETH or ethereum if len(ns_parser.coin) > 4: ns_parser.key = "id" coins_df_gecko = get_coin_list() coins_bin = create_mapping_matrix_for_binance() coins_df_bin = pd.Series(coins_bin).reset_index() coins_df_bin.columns = ["symbol", "id"] coins = pd.merge(coins_df_bin, coins_df_gecko[["id", "name"]], how="left", on="id") coins_list = coins[ns_parser.key].to_list() sim = difflib.get_close_matches(ns_parser.coin, coins_list, ns_parser.top) df = pd.Series(sim).to_frame().reset_index() df.columns = ["index", ns_parser.key] df = df.merge(coins, on=ns_parser.key) print( tabulate( df, headers=df.columns, floatfmt=".1f", showindex=False, tablefmt="fancy_grid", )) else: print( "Couldn't execute find methods for CoinPaprika, Binance or CoinGecko" ) print("") except Exception as e: print(e, "\n")