def display_candles(product_id: str,
                    interval: str = "24h",
                    export: str = "") -> None:
    """Get candles for chosen trading pair and time interval. [Source: Coinbase]

    Parameters
    ----------
    product_id: str
        Trading pair of coins on Coinbase e.g ETH-USDT or UNI-ETH
    interval: str
        Time interval. One from 1m, 5m ,15m, 1h, 6h, 24h
    export : str
        Export dataframe data to csv,json,xlsx file
    """

    df = coinbase_model.get_candles(product_id, interval)
    df_data = df.copy()

    print_rich_table(df,
                     headers=list(df.columns),
                     show_index=True,
                     title="Trading Pair Candles")

    export_data(
        export,
        os.path.dirname(os.path.abspath(__file__)),
        "candles",
        df_data,
    )
def display_candles(product_id: str, interval: str, export) -> None:
    """Get candles for chosen trading pair and time interval. [Source: Coinbase]

    Parameters
    ----------
    product_id: str
        Trading pair of coins on Coinbase e.g ETH-USDT or UNI-ETH
    interval: str
        Time interval. One from 1m, 5m ,15m, 1h, 6h, 24h
    export : str
        Export dataframe data to csv,json,xlsx file
    """

    df = coinbase_model.get_candles(product_id, interval)
    df_data = df.copy()

    if gtff.USE_TABULATE_DF:
        print(
            tabulate(
                df,
                headers=df.columns,
                floatfmt=".1f",
                showindex=True,
                tablefmt="fancy_grid",
            ),
            "\n",
        )
    else:
        print(df.to_string, "\n")

    export_data(
        export,
        os.path.dirname(os.path.abspath(__file__)),
        "candles",
        df_data,
    )
Beispiel #3
0
def plot_chart(coin: Union[str, pycoingecko_model.Coin], source: str,
               currency: str, **kwargs: Any) -> None:
    """Load data for Technical Analysis

    Parameters
    ----------
    coin: str
        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,
        }

        assert isinstance(coin, str)
        pair = coin + currency

        if check_valid_binance_str(pair):
            print(f"{coin} 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 = [
                "Time0",
                "Open",
                "High",
                "Low",
                "Close",
                "Volume",
            ]
            df_coin = candles_df.set_index(
                pd.to_datetime(candles_df["Time0"], unit="ms")).drop("Time0",
                                                                     axis=1)

            plot_candles(
                df_coin,
                f"{coin + currency} from {df_coin.index[0].strftime('%Y/%m/%d')} to "
                f"{df_coin.index[-1].strftime('%Y/%m/%d')}",
            )

    if source == "cp":
        df = coinpaprika_model.get_ohlc_historical(str(coin), currency.upper(),
                                                   days)

        if df.empty:
            print("There is not data to plot chart\n")
            return

        df.drop(["time_close", "market_cap"], axis=1, inplace=True)
        df.columns = [
            "Time0",
            "Open",
            "High",
            "Low",
            "Close",
            "Volume",
        ]
        df = df.set_index(pd.to_datetime(df["Time0"])).drop("Time0", 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_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()
        print("")

    if source == "cg":
        assert isinstance(coin, pycoingecko_model.Coin)
        df = coin.get_coin_market_chart(currency, days)
        df = df["price"].resample("1D").ohlc().ffill()

        df.columns = [
            "Open",
            "High",
            "Low",
            "Close",
        ]

        title = (
            f"\n{coin.coin_symbol}/{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()
        print("")

    if source == "cb":
        assert isinstance(coin, str)
        coin, currency = coin.upper(), currency.upper()
        pair = f"{coin}-{currency}"

        if coinbase_model.check_validity_of_product(pair):
            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="Time0", inplace=True, ascending=True)
            df = df.set_index(pd.to_datetime(df["Time0"],
                                             unit="s")).drop("Time0", 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()
            print("")
Beispiel #4
0
def load_ta_data(coin: Union[str, pycoingecko_model.Coin], source: str,
                 currency: str, **kwargs: Any) -> Tuple[pd.DataFrame, str]:
    """Load data for Technical Analysis

    Parameters
    ----------
    coin: str
        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]
        df 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,
        }

        assert isinstance(coin, str)
        pair = coin + currency

        if check_valid_binance_str(pair):
            print(f"{coin} 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 = [
                "Time0",
                "Open",
                "High",
                "Low",
                "Close",
                "Volume",
            ]
            df_coin = candles_df.set_index(
                pd.to_datetime(candles_df["Time0"], unit="ms")).drop("Time0",
                                                                     axis=1)

            return df_coin, currency
        return pd.DataFrame(), currency

    if source == "cp":
        df = coinpaprika_model.get_ohlc_historical(str(coin), currency.upper(),
                                                   days)

        if df.empty:
            print("No data found", "\n")
            return pd.DataFrame(), ""

        df.drop(["time_close", "market_cap"], axis=1, inplace=True)
        df.columns = [
            "Time0",
            "Open",
            "High",
            "Low",
            "Close",
            "Volume",
        ]
        df = df.set_index(pd.to_datetime(df["Time0"])).drop("Time0", axis=1)
        return df, currency

    if source == "cg":
        assert isinstance(coin, pycoingecko_model.Coin)
        df = coin.get_coin_market_chart(currency, days)
        df = df["price"].resample("1D").ohlc().ffill()
        df.columns = [
            "Open",
            "High",
            "Low",
            "Close",
        ]
        df.index.name = "date"
        return df, currency

    if source == "cb":
        assert isinstance(coin, str)
        coin, currency = coin.upper(), currency.upper()
        pair = f"{coin}-{currency}"

        if coinbase_model.check_validity_of_product(pair):
            print(f"{coin} loaded vs {currency}")

            df = coinbase_model.get_candles(
                product_id=pair,
                interval=interval or "24hour",
            ).head(limit)

            df_coin = df.set_index(pd.to_datetime(df["Time0"],
                                                  unit="s")).drop("Time0",
                                                                  axis=1)
            return df_coin, currency

    return pd.DataFrame(), currency
Beispiel #5
0
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()
Beispiel #6
0
def load_ta_data(coin_map_df: pd.DataFrame, source: str, currency: str,
                 **kwargs: Any) -> Tuple[pd.DataFrame, str]:
    """Load data for Technical Analysis

    Parameters
    ----------
    coin_map_df: pd.DataFrame
        Cryptocurrency
    source: str
        Source of data: CoinGecko, Binance, CoinPaprika, Yahoo Finance
    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]
        df 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.upper()

        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)

            return df_coin, currency
        return pd.DataFrame(), currency

    if source == "cp":
        symbol_coinpaprika = coin_map_df["CoinPaprika"]
        df = coinpaprika_model.get_ohlc_historical(symbol_coinpaprika,
                                                   currency.upper(), days)

        if df.empty:
            console.print("No data found", "\n")
            return pd.DataFrame(), ""

        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)
        return df, currency

    if source == "cg":
        coin_id = coin_map_df["CoinGecko"]
        # coin = pycoingecko_model.Coin(symbol_coingecko)
        df = pycoingecko_model.get_coin_market_chart(coin_id, currency, days)
        df = df["price"].resample("1D").ohlc().ffill()
        df.columns = [
            "Open",
            "High",
            "Low",
            "Close",
        ]
        df.index.name = "date"
        return df, currency

    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_coin = df.set_index(pd.to_datetime(df["date"],
                                                  unit="s")).drop("date",
                                                                  axis=1)

            return df_coin[::-1], currency

    if source == "yf":

        interval_map = {
            "1min": "1m",
            "2min": "2m",
            "5min": "5m",
            "15min": "15m",
            "30min": "30m",
            "60min": "60m",
            "90min": "90m",
            "1hour": "1h",
            "1day": "1d",
            "5day": "5d",
            "1week": "1wk",
            "1month": "1mo",
            "3month": "3mo",
        }

        symbol_yf = coin_map_df["YahooFinance"]

        df_coin = yf.download(
            symbol_yf,
            end=datetime.now(),
            start=datetime.now() - timedelta(days=days),
            progress=False,
            interval=interval_map[interval],
        ).sort_index(ascending=False)

        df_coin.index.names = ["date"]

        if df_coin.empty:
            console.print(
                f"Could not download data for {symbol_yf} from Yahoo Finance")
            return pd.DataFrame(), currency

        return df_coin[::-1], currency

    return pd.DataFrame(), currency