def display_info(symbol: str, export: str) -> None: """Shows basic information about loaded coin. [Source: CoinGecko] Parameters ---------- symbol : str Cryptocurrency export : str Export dataframe data to csv,json,xlsx file """ coin = gecko.Coin(symbol) df = wrap_text_in_df(coin.get_base_info, w=80) print_rich_table(df, headers=list(df.columns), show_index=False, title="Basic Coin Information") console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "info", df, )
def display_web(symbol: str, export: str) -> None: """Shows found websites corresponding to loaded coin. [Source: CoinGecko] Parameters ---------- symbol : str Cryptocurrency export : str Export dataframe data to csv,json,xlsx file """ coin = gecko.Coin(symbol) df = coin.get_websites print_rich_table(df, headers=list(df.columns), show_index=False, title="Websites for Loaded Coin") console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "web", df, )
def display_bc(symbol: str, export: str) -> None: """Shows urls to blockchain explorers. [Source: CoinGecko] Parameters ---------- symbol : str Cryptocurrency export : str Export dataframe data to csv,json,xlsx file """ coin = gecko.Coin(symbol) df = coin.get_blockchain_explorers print_rich_table(df, headers=list(df.columns), show_index=False, title="Blockchain URLs") console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "bc", df, )
def display_market(symbol: str, export: str) -> None: """Shows market data for loaded coin. [Source: CoinGecko] Parameters ---------- symbol : str Cryptocurrency export : str Export dataframe data to csv,json,xlsx file """ coin = gecko.Coin(symbol) df = coin.get_market_data print_rich_table(df, headers=list(df.columns), show_index=False, title="Market Data") console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "market", df, )
def display_score(symbol: str, export: str) -> None: """Shows different kind of scores for loaded coin. [Source: CoinGecko] Parameters ---------- symbol : str Cryptocurrency export : str Export dataframe data to csv,json,xlsx file """ coin = gecko.Coin(symbol) df = coin.get_scores print_rich_table( df, headers=list(df.columns), show_index=False, title="Different Scores for Loaded Coin", ) console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "score", df, )
def display_atl(symbol: str, currency: str, export: str) -> None: """Shows all time low data for loaded coin. [Source: CoinGecko] Parameters ---------- symbol : str Cryptocurrency currency: str currency vs which coin ath will be displayed: usd or btc export : str Export dataframe data to csv,json,xlsx file """ coin = gecko.Coin(symbol) df = coin.get_all_time_low(currency=currency) print_rich_table(df, headers=list(df.columns), show_index=False, title="Coin Lows") console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "atl", df, )
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 load(other_args: List[str]): """Load selected Cryptocurrency. You can pass either symbol of id of the coin Parameters ---------- other_args : List[str] argparse arguments """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="load", description="""Load cryptocurrency, from CoinGecko. You will have access to a lot of statistics on that coin like price data, coin development stats, social media and many others. Loading coin also will open access to technical analysis menu.""", ) parser.add_argument( "-c", "--coin", required="-h" not in other_args, type=str, dest="coin", help= "Coin to load data for (symbol or coin id). You can use either symbol of the coin or coinId" "You can find all coins using command `coins` or visit https://www.coingecko.com/en. " "To use load a coin use command load -c [symbol or coinId]", ) try: if other_args: if "-" not in other_args[0]: other_args.insert(0, "-c") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return coin = gecko.Coin(ns_parser.coin) print("") return coin except KeyError: print(f"Could not find coin with the id: {ns_parser.coin}", "\n") return None except SystemExit: print("") return None except Exception as e: print(e, "\n") return None
def plot_chart(coin_map_df: pd.DataFrame, source: str, currency: str, **kwargs: Any) -> None: """Load data for Technical Analysis Parameters ---------- coin_map_df: pd.DataFrame Cryptocurrency source: str Source of data: CoinGecko, Binance, CoinPaprika currency: str Quotes currency kwargs: days: int Days limit for coingecko, coinpaprika limit: int Limit for binance quotes interval: str Time interval for Binance Returns ---------- Tuple[pd.DataFrame, str] dataframe with prices quoted currency """ limit = kwargs.get("limit", 100) interval = kwargs.get("interval", "1day") days = kwargs.get("days", 30) if source == "bin": client = Client(cfg.API_BINANCE_KEY, cfg.API_BINANCE_SECRET) interval_map = { "1day": client.KLINE_INTERVAL_1DAY, "3day": client.KLINE_INTERVAL_3DAY, "1hour": client.KLINE_INTERVAL_1HOUR, "2hour": client.KLINE_INTERVAL_2HOUR, "4hour": client.KLINE_INTERVAL_4HOUR, "6hour": client.KLINE_INTERVAL_6HOUR, "8hour": client.KLINE_INTERVAL_8HOUR, "12hour": client.KLINE_INTERVAL_12HOUR, "1week": client.KLINE_INTERVAL_1WEEK, "1min": client.KLINE_INTERVAL_1MINUTE, "3min": client.KLINE_INTERVAL_3MINUTE, "5min": client.KLINE_INTERVAL_5MINUTE, "15min": client.KLINE_INTERVAL_15MINUTE, "30min": client.KLINE_INTERVAL_30MINUTE, "1month": client.KLINE_INTERVAL_1MONTH, } symbol_binance = coin_map_df["Binance"] pair = symbol_binance + currency if check_valid_binance_str(pair): # console.print(f"{symbol_binance} loaded vs {currency.upper()}") candles = client.get_klines( symbol=pair, interval=interval_map[interval], limit=limit, ) candles_df = pd.DataFrame(candles).astype(float).iloc[:, :6] candles_df.columns = [ "date", "Open", "High", "Low", "Close", "Volume", ] df_coin = candles_df.set_index( pd.to_datetime(candles_df["date"], unit="ms")).drop("date", axis=1) title = f"{symbol_binance + currency} from {df_coin.index[0].strftime('%Y/%m/%d')} to {df_coin.index[-1].strftime('%Y/%m/%d')}" # noqa: E501 plot_candles( candles_df=df_coin, title=title, volume=True, ) if source == "cp": symbol_coinpaprika = coin_map_df["CoinPaprika"] df = coinpaprika_model.get_ohlc_historical(str(symbol_coinpaprika), currency.upper(), days) if df.empty: console.print("There is not data to plot chart\n") return df.drop(["time_close", "market_cap"], axis=1, inplace=True) df.columns = [ "date", "Open", "High", "Low", "Close", "Volume", ] df = df.set_index(pd.to_datetime(df["date"])).drop("date", axis=1) title = f"{symbol_coinpaprika}/{currency} from {df.index[0].strftime('%Y/%m/%d')} to {df.index[-1].strftime('%Y/%m/%d')}" # noqa: E501 df["Volume"] = df["Volume"] / 1_000_000 plot_candles( candles_df=df, title=title, volume=True, ylabel="Volume [1M]", ) console.print("") if source == "cg": symbol_coingecko = coin_map_df["CoinGecko"] coin = pycoingecko_model.Coin(symbol_coingecko) df = coin.get_coin_market_chart(currency, days) df = df["price"].resample("1D").ohlc().ffill() df.columns = [ "Open", "High", "Low", "Close", ] title = f"{symbol_coingecko}/{currency} from {df.index[0].strftime('%Y/%m/%d')} to {df.index[-1].strftime('%Y/%m/%d')}" # noqa: E501 plot_candles( candles_df=df, title=title, volume=False, ylabel="Volume [1M]", ) console.print("") if source == "cb": symbol_coinbase = coin_map_df["Coinbase"] coin, currency = symbol_coinbase.upper(), currency.upper() pair = f"{coin}-{currency}" if coinbase_model.check_validity_of_product(pair): df = coinbase_model.get_candles( product_id=pair, interval=interval or "24hour", ).head(limit) df = df.astype(float).iloc[:, :6] df.sort_values(by="date", inplace=True, ascending=True) df = df.set_index(pd.to_datetime(df["date"], unit="s")).drop("date", axis=1) title = f"{coin}/{currency} from {df.index[0].strftime('%Y/%m/%d')} to {df.index[-1].strftime('%Y/%m/%d')}" # noqa: E501 df["Volume"] = df["Volume"] / 1_000 plot_candles( candles_df=df, title=title, volume=True, ylabel="Volume [1K]", ) console.print("") if source == "yf": symbol_yf = coin_map_df["YahooFinance"] df = yf.download( symbol_yf, end=datetime.now(), start=datetime.now() - timedelta(days=days), progress=False, interval=interval, )[[ "Open", "High", "Low", "Close", "Volume", ]].copy() # Because the label has Volume [1M] df.Volume = df.Volume / 1_000_000 df.index.name = "date" title = f"{symbol_yf.replace('-', '/')} from {df.index[0].strftime('%Y/%m/%d')} to {df.index[-1].strftime('%Y/%m/%d')}" # noqa: E501 plot_candles( candles_df=df, title=title, volume=True, ylabel="Volume [1M]", ) console.print()
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 plot_chart( coin_map_df: pd.DataFrame, source: str, currency: str, **kwargs: Any ) -> None: """Load data for Technical Analysis Parameters ---------- coin_map_df: pd.DataFrame Cryptocurrency source: str Source of data: CoinGecko, Binance, CoinPaprika currency: str Quotes currency kwargs: days: int Days limit for coingecko, coinpaprika limit: int Limit for binance quotes interval: str Time interval for Binance Returns ---------- Tuple[pd.DataFrame, str] dataframe with prices quoted currency """ limit = kwargs.get("limit", 100) interval = kwargs.get("interval", "1day") days = kwargs.get("days", 30) if source == "bin": client = Client(cfg.API_BINANCE_KEY, cfg.API_BINANCE_SECRET) interval_map = { "1day": client.KLINE_INTERVAL_1DAY, "3day": client.KLINE_INTERVAL_3DAY, "1hour": client.KLINE_INTERVAL_1HOUR, "2hour": client.KLINE_INTERVAL_2HOUR, "4hour": client.KLINE_INTERVAL_4HOUR, "6hour": client.KLINE_INTERVAL_6HOUR, "8hour": client.KLINE_INTERVAL_8HOUR, "12hour": client.KLINE_INTERVAL_12HOUR, "1week": client.KLINE_INTERVAL_1WEEK, "1min": client.KLINE_INTERVAL_1MINUTE, "3min": client.KLINE_INTERVAL_3MINUTE, "5min": client.KLINE_INTERVAL_5MINUTE, "15min": client.KLINE_INTERVAL_15MINUTE, "30min": client.KLINE_INTERVAL_30MINUTE, "1month": client.KLINE_INTERVAL_1MONTH, } symbol_binance = coin_map_df["Binance"] pair = symbol_binance + currency if check_valid_binance_str(pair): # console.print(f"{symbol_binance} loaded vs {currency.upper()}") candles = client.get_klines( symbol=pair, interval=interval_map[interval], limit=limit, ) candles_df = pd.DataFrame(candles).astype(float).iloc[:, :6] candles_df.columns = [ "date", "Open", "High", "Low", "Close", "Volume", ] df_coin = candles_df.set_index( pd.to_datetime(candles_df["date"], unit="ms") ).drop("date", axis=1) plot_candles( df_coin, f"{symbol_binance + currency} from {df_coin.index[0].strftime('%Y/%m/%d')} to " f"{df_coin.index[-1].strftime('%Y/%m/%d')}", ) if source == "cp": symbol_coinpaprika = coin_map_df["CoinPaprika"] df = coinpaprika_model.get_ohlc_historical( str(symbol_coinpaprika), currency.upper(), days ) if df.empty: console.print("There is not data to plot chart\n") return df.drop(["time_close", "market_cap"], axis=1, inplace=True) df.columns = [ "date", "Open", "High", "Low", "Close", "Volume", ] df = df.set_index(pd.to_datetime(df["date"])).drop("date", axis=1) title = ( f"\n{symbol_coinpaprika}/{currency} from {df.index[0].strftime('%Y/%m/%d')} to {df.index[-1].strftime('%Y/%m/%d')}", # noqa: E501 ) df["Volume"] = df["Volume"] / 1_000_000 mpf.plot( df, type="candle", volume=True, ylabel_lower="Volume [1M]", title=str(title[0]) if isinstance(title, tuple) else title, xrotation=20, style="binance", figratio=(10, 7), figscale=1.10, figsize=(plot_autoscale()), update_width_config=dict( candle_linewidth=1.0, candle_width=0.8, volume_linewidth=1.0 ), ) if ion: plt.ion() plt.show() console.print("") if source == "cg": symbol_coingecko = coin_map_df["CoinGecko"] coin = pycoingecko_model.Coin(symbol_coingecko) df = coin.get_coin_market_chart(currency, days) df = df["price"].resample("1D").ohlc().ffill() df.columns = [ "Open", "High", "Low", "Close", ] title = ( f"\n{symbol_coingecko}/{currency} from {df.index[0].strftime('%Y/%m/%d')} " f"to {df.index[-1].strftime('%Y/%m/%d')}", ) mpf.plot( df, type="candle", volume=False, title=str(title[0]) if isinstance(title, tuple) else title, xrotation=20, style="binance", figratio=(10, 7), figscale=1.10, figsize=(plot_autoscale()), update_width_config=dict( candle_linewidth=1.0, candle_width=0.8, volume_linewidth=1.0 ), ) if ion: plt.ion() plt.show() console.print("") if source == "cb": symbol_coinbase = coin_map_df["Coinbase"] coin, currency = symbol_coinbase.upper(), currency.upper() pair = f"{coin}-{currency}" if coinbase_model.check_validity_of_product(pair): # console.print(f"{coin} loaded vs {currency}") df = coinbase_model.get_candles( product_id=pair, interval=interval or "24hour", ).head(limit) df = df.astype(float).iloc[:, :6] df.sort_values(by="date", inplace=True, ascending=True) df = df.set_index(pd.to_datetime(df["date"], unit="s")).drop("date", axis=1) title = ( f"\n{coin}/{currency} from {df.index[0].strftime('%Y/%m/%d')} to {df.index[-1].strftime('%Y/%m/%d')}", ) df["Volume"] = df["Volume"] / 1_000 mpf.plot( df, type="candle", volume=True, ylabel_lower="Volume [1K]", title=str(title[0]) if isinstance(title, tuple) else title, xrotation=20, style="binance", figratio=(10, 7), figscale=1.10, figsize=(plot_autoscale()), update_width_config=dict( candle_linewidth=1.0, candle_width=0.8, volume_linewidth=1.0 ), ) if ion: plt.ion() plt.show() console.print("")
def load( coin: str, other_args: List[str] ) -> Tuple[Union[Optional[str], pycoingecko_model.Coin], Any]: """Load cryptocurrency from given source. Available sources are: CoinGecko, CoinPaprika 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. other_args: List[str] Arguments to pass to argparse 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 """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="load", description="Load crypto currency to perform analysis on. " "Available data sources are CoinGecko, CoinPaprika, and Binance" "By default main source used for analysis is CoinGecko (cg). To change it use --source flag", ) parser.add_argument( "-c", "--coin", help="Coin to get", dest="coin", type=str, required="-h" not in other_args, ) parser.add_argument( "-s", "--source", help="Source of data", dest="source", choices=("cp", "cg", "bin"), default="cg", required=False, ) 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 coin, None source = ns_parser.source current_coin = "" # type: Optional[Any] for arg in ["--source", source]: if arg in other_args: other_args.remove(arg) if source == "cg": current_coin = pycoingecko_model.Coin(ns_parser.coin) return current_coin, source if source == "bin": current_coin = binance_view.load(other_args=other_args) return current_coin, source if source == "cp": current_coin = coinpaprika_view.load(other_args=other_args) return current_coin, source return current_coin, None except KeyError: print(f"Could not find coin: {ns_parser.coin}", "\n") return coin, None except SystemExit: print("") return coin, None except Exception as e: print(e, "\n") return coin, None