Untitled

 avatar
unknown
plain_text
a year ago
3.8 kB
8
Indexable
import ccxt
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import matplotlib.patches as mpatches

def plot_price_weighted_index_with_volume(tokens, exchange_id, title_suffix=""):
    exchange = getattr(ccxt, exchange_id)()
    data_frames = []

    # Fetch historical data for tokens over the last 200 days
    for token in tokens:
        try:
            bars = exchange.fetch_ohlcv(f"{token}/USDT", timeframe="1d", limit=200)
            df = pd.DataFrame(bars, columns=["timestamp", "open", "high", "low", "close", "volume"])
            df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
            df.set_index("timestamp", inplace=True)
            data_frames.append(df)
        except Exception as e:
            print(f"Failed to fetch data for {token}: {e}")

    if data_frames:
        # Calculate the Price Index and its SMA
        index_df = pd.concat(data_frames).groupby(level=0).mean()
        index_df["sma21"] = index_df["close"].rolling(window=21).mean()

        # Fetch BTCUSDT data over the last 200 days
        try:
            btc_bars = exchange.fetch_ohlcv("BTC/USDT", timeframe="1d", limit=200)
            btc_df = pd.DataFrame(btc_bars, columns=["timestamp", "open", "high", "low", "close", "volume"])
            btc_df["timestamp"] = pd.to_datetime(btc_df["timestamp"], unit="ms")
            btc_df.set_index("timestamp", inplace=True)
            index_df["btc_ratio"] = index_df["close"] / btc_df["close"]
            index_df["btc_ratio_sma21"] = index_df["btc_ratio"].rolling(window=21).mean()

            # Create the figure and subplots
            fig, axes = plt.subplots(3, 1, figsize=(12, 8), gridspec_kw={'height_ratios': [3, 1, 1]})
            fig.set_facecolor("yellow")

            # Plot candlestick chart
            for idx, row in index_df.iterrows():
                color = 'blue' if row["close"] >= row["open"] else 'red'
                axes[0].plot([idx, idx], [row["low"], row["high"]], color=color)
                axes[0].bar(idx, row["close"] - row["open"], bottom=row["open"], color=color, width=0.5)

            axes[0].plot(index_df.index, index_df["sma21"], label="21-day SMA", color="grey")
            axes[0].legend()
            axes[0].set_title(f"{title_suffix} Index")

            # Plot volume bars
            volume_colors = ['blue' if row["close"] >= row["open"] else 'red' for idx, row in index_df.iterrows()]
            axes[1].bar(index_df.index, index_df["volume"], color=volume_colors)
            axes[1].set_title("Volume")

            # Plot BTC ratio and its SMA
            axes[2].plot(index_df.index, index_df["btc_ratio"], label="BTC Ratio", color="blue")
            axes[2].plot(index_df.index, index_df["btc_ratio_sma21"], label="21-day SMA of BTC Ratio", color="grey")
            axes[2].legend()

            # Set x-axis date formatting
            for ax in axes:
                ax.xaxis.set_major_locator(mticker.MaxNLocator(10))
                ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
                plt.setp(ax.get_xticklabels(), rotation=45, ha="right")

            # Adjust y value as needed to place the text below the title but above the plot
            coin_list_str = ", ".join(tokens)
            fig.text(0.5, 0.93, f"Coins: {coin_list_str}", ha="center", fontsize=13, wrap=True)

            plt.tight_layout()
            plt.show()
        except Exception as e:
            print("Failed to fetch BTCUSDT data:", e)
    else:
        print("No data fetched for tokens")

# Example usage
exchange_id = "binance"
tokens = ['ETH', 'ADA', 'BNB', 'SOL', 'AVAX', 'TRX']
plot_price_weighted_index_with_volume(tokens, exchange_id, "Layer1")
Editor is loading...
Leave a Comment