Пример #1
0
def get_coin_potential_returns(
    main_coin: str,
    vs: Union[str, None] = None,
    top: Union[int, None] = None,
    price: Union[int, None] = None,
) -> pd.DataFrame:
    """Fetch data to calculate potential returns of a certain coin. [Source: CoinGecko]

    Parameters
    ----------
    main_coin   : str
        Coin loaded to check potential returns for (e.g., algorand)
    vs          : str | None
        Coin to compare main_coin with (e.g., bitcoin)
    top         : int | None
        Number of coins with highest market cap to compare main_coin with (e.g., 5)
    price
        Target price of main_coin to check potential returns (e.g., 5)

    Returns
    -------
    pd.DataFrame
            Potential returns data
            Columns: Coin, Current Price, Target Coin, Potential Price, Potential Market Cap ($), Change (%)
    """
    client = CoinGeckoAPI()
    COLUMNS = [
        "Coin",
        "Current Price ($)",
        "Current Market Cap ($)",
        "Target Coin",
        "Potential Price ($)",
        "Potential Market Cap ($)",
        "Change (%)",
    ]
    if top and top > 0:  # user wants to compare with top coins
        data = client.get_price(
            ids=f"{main_coin}",
            vs_currencies="usd",
            include_market_cap=True,
            include_24hr_vol=False,
            include_24hr_change=False,
            include_last_updated_at=False,
        )
        top_coins_data = client.get_coins_markets(vs_currency="usd",
                                                  per_page=top,
                                                  order="market_cap_desc")
        main_coin_data = data[main_coin]
        diff_arr = []
        for coin in top_coins_data:
            market_cap_difference_percentage = calc_change(
                coin["market_cap"], main_coin_data["usd_market_cap"])
            future_price = main_coin_data["usd"] * (
                1 + market_cap_difference_percentage / 100)
            diff_arr.append([
                main_coin,
                main_coin_data["usd"],
                main_coin_data["usd_market_cap"],
                coin["id"],
                future_price,
                coin["market_cap"],
                market_cap_difference_percentage,
            ])
        return pd.DataFrame(
            data=diff_arr,
            columns=COLUMNS,
        )

    if vs:  # user passed a coin
        data = client.get_price(
            ids=f"{main_coin},{vs}",
            vs_currencies="usd",
            include_market_cap=True,
            include_24hr_vol=False,
            include_24hr_change=False,
            include_last_updated_at=False,
        )
        main_coin_data = data[main_coin]
        vs_coin_data = data[vs]

        if main_coin_data and vs_coin_data:
            market_cap_difference_percentage = calc_change(
                vs_coin_data["usd_market_cap"],
                main_coin_data["usd_market_cap"])
            future_price = main_coin_data["usd"] * (
                1 + market_cap_difference_percentage / 100)
            return pd.DataFrame(
                data=[[
                    main_coin,
                    main_coin_data["usd"],
                    main_coin_data["usd_market_cap"],
                    vs,
                    future_price,
                    vs_coin_data["usd_market_cap"],
                    market_cap_difference_percentage,
                ]],
                columns=COLUMNS,
            )

    if price and price > 0:  # user passed a price
        data = client.get_price(
            ids=main_coin,
            vs_currencies="usd",
            include_market_cap=True,
            include_24hr_vol=False,
            include_24hr_change=False,
            include_last_updated_at=False,
        )
        main_coin_data = data[main_coin]
        if main_coin_data:
            final_market_cap = (main_coin_data["usd_market_cap"] * price /
                                main_coin_data["usd"])
            market_cap_difference_percentage = calc_change(
                final_market_cap, main_coin_data["usd_market_cap"])
            future_price = main_coin_data["usd"] * (
                1 + market_cap_difference_percentage / 100)
            return pd.DataFrame(
                data=[[
                    main_coin,
                    main_coin_data["usd"],
                    main_coin_data["usd_market_cap"],
                    "",
                    future_price,
                    final_market_cap,
                    market_cap_difference_percentage,
                ]],
                columns=COLUMNS,
            )

    return pd.DataFrame()
Пример #2
0
    def call_load(self, other_args):
        """Process load command"""
        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, Binance, Coinbase"
            "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(
            "--source",
            help="Source of data",
            dest="source",
            choices=("cp", "cg", "bin", "cb"),
            default="cg",
            required=False,
        )
        parser.add_argument(
            "-s",
            "--start",
            type=valid_date_in_past,
            default=(datetime.now() -
                     timedelta(days=366)).strftime("%Y-%m-%d"),
            dest="start",
            help="The starting date (format YYYY-MM-DD) of the crypto",
        )
        parser.add_argument(
            "--vs",
            help="Quote currency (what to view coin vs)",
            dest="vs",
            default="usd",
            type=str,
        )
        parser.add_argument(
            "-i",
            "--interval",
            help="Interval to get data (Only available on binance/coinbase)",
            dest="interval",
            default="1day",
            type=str,
        )

        if other_args and "-" not in other_args[0][0]:
            other_args.insert(0, "-c")

        ns_parser = parse_known_args_and_warn(parser, other_args)
        delta = (datetime.now() - ns_parser.start).days
        if ns_parser:
            source = ns_parser.source
            for arg in ["--source", source]:
                if arg in other_args:
                    other_args.remove(arg)

            res = ns_parser.resolution if delta < 90 else "1D"
            self.resolution = res

            # TODO: protections in case None is returned
            (
                self.coin,
                self.source,
                self.symbol,
                self.coin_map_df,
                self.current_df,
                self.current_currency,
            ) = cryptocurrency_helpers.load(
                coin=ns_parser.coin,
                source=ns_parser.source,
                should_load_ta_data=True,
                days=delta,
                interval=ns_parser.interval,
                vs=ns_parser.vs,
            )
            if self.symbol:
                self.current_interval = ns_parser.interval
                first_price = self.current_df["Close"].iloc[0]
                last_price = self.current_df["Close"].iloc[-1]
                second_last_price = self.current_df["Close"].iloc[-2]
                interval_change = calc_change(last_price, second_last_price)
                since_start_change = calc_change(last_price, first_price)
                if isinstance(self.current_currency,
                              str) and self.PATH == "/crypto/":
                    col = "green" if interval_change > 0 else "red"
                    self.price_str = f"""Current Price: {round(last_price,2)} {self.current_currency.upper()}
Performance in interval ({self.current_interval}): [{col}]{round(interval_change,2)}%[/{col}]
Performance since {ns_parser.start.strftime('%Y-%m-%d')}: [{col}]{round(since_start_change,2)}%[/{col}]"""  # noqa

                    console.print(f"""
Loaded {self.coin} against {self.current_currency} from {CRYPTO_SOURCES[self.source]} source

{self.price_str}
""")  # noqa
                else:
                    console.print(
                        f"{delta} Days of {self.coin} vs {self.current_currency} loaded with {res} resolution.\n"
                    )