├── img ├── rsi_heatmap.png └── rsi_heatmap_reference.png ├── requirements.txt ├── LICENSE ├── README.md ├── .gitignore └── src ├── data.py └── main.py /img/rsi_heatmap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StephanAkkerman/crypto-rsi-heatmap/HEAD/img/rsi_heatmap.png -------------------------------------------------------------------------------- /img/rsi_heatmap_reference.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StephanAkkerman/crypto-rsi-heatmap/HEAD/img/rsi_heatmap_reference.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy==1.24.4 2 | tqdm==4.65.0 3 | pycoingecko==3.1.0 4 | tradingview_ta==3.3.0 5 | matplotlib==3.9.0 6 | pandas==2.2.2 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Stephan Akkerman 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Crypto Market RSI Heatmap 📊 2 | 3 | This is a simple Python script that generates a RSI heatmap for the top 100 cryptocurrencies by volume using the style of [Coinglass](https://www.coinglass.com/pro/i/RsiHeatMap). The heatmap can be used to identify overbought and oversold conditions in the market. 4 | 5 |

6 | Supported versions 7 | License 8 | Code style: black 9 |

10 | 11 | --- 12 | 13 | ## Introduction 14 | 15 | I have previously recreated this chart for my [fintwit-bot](https://github.com/StephanAkkerman/fintwit-bot), unfortunately coinglass removed their API so I had to recreate it using other sources. I used the chart found on [Coinglass](https://www.coinglass.com/pro/i/RsiHeatMap) as a reference. The data is fetched using [Coingecko's API](https://www.coingecko.com/en/api) to get the top volume coins and combined with [TradingView's API](https://github.com/AnalyzerREST/python-tradingview-ta) to get the RSI values. 16 | 17 | ## Installation ⚙️ 18 | 19 | The required packages to run this code can be found in the requirements.txt file. To run this file, execute the following code block after cloning the repository: 20 | 21 | ```bash 22 | pip install -r requirements.txt 23 | ``` 24 | 25 | ## Usage ⌨️ 26 | 27 | To generate the chart, simply run the script using the following command: 28 | 29 | ```bash 30 | python src/main.py 31 | ``` 32 | 33 | ## Example 📊 34 | 35 | The following chart is an example of the output generated by the script. 36 | ![RSI Heatmap](img/rsi_heatmap.png) 37 | 38 | ### References 📚 39 | 40 | The following image was used as a reference to create the RSI heatmap. 41 | ![RSI Heatmap Reference](img/rsi_heatmap_reference.png) 42 | 43 | ## Other Projects 📦 44 | 45 | This project is part of a series of projects that I have created. You can find the other projects in the following list: 46 | 47 | - [Total Liquidation Chart](https://github.com/StephanAkkerman/liquidations-chart) 48 | - [Bitcoin Rainbow Chart](https://github.com/StephanAkkerman/bitcoin-rainbow-chart) 49 | - [Live Binance Charts](https://github.com/StephanAkkerman/live-binance-charts) 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | data/ 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | -------------------------------------------------------------------------------- /src/data.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pickle 3 | import time 4 | from datetime import datetime, timedelta 5 | 6 | import pandas as pd 7 | from pycoingecko import CoinGeckoAPI 8 | from tradingview_ta import get_multiple_analysis 9 | 10 | cg = CoinGeckoAPI() 11 | 12 | 13 | def get_RSI(coins: list, exchange: str = "BINANCE", time_frame: str = "1d") -> dict: 14 | # Format symbols exchange:symbol 15 | symbols = [f"{exchange.upper()}:{symbol}" for symbol in coins] 16 | 17 | analysis = get_multiple_analysis( 18 | symbols=symbols, interval=time_frame, screener="crypto" 19 | ) 20 | 21 | # For each symbol get the RSI 22 | rsi_dict = {} 23 | for symbol in symbols: 24 | if analysis[symbol] is None: 25 | # print(f"No analysis for {symbol}") 26 | continue 27 | clean_symbol = symbol.replace(f"{exchange.upper()}:", "") 28 | clean_symbol = clean_symbol.replace("USDT", "") 29 | rsi_dict[clean_symbol] = analysis[symbol].indicators["RSI"] 30 | 31 | # Save the RSI data to a CSV file 32 | save_RSI(rsi_dict, time_frame) 33 | 34 | return rsi_dict 35 | 36 | 37 | def get_closest_to_24h( 38 | file_path: str = "data/rsi_data.csv", time_frame: str = "1d" 39 | ) -> dict: 40 | # Read the CSV file into a DataFrame 41 | if not os.path.isfile(file_path): 42 | print(f"No data found in {file_path}") 43 | return {} 44 | 45 | df = pd.read_csv(file_path) 46 | 47 | # Filter on the timeframe 48 | df = df[df["Time Frame"] == time_frame] 49 | 50 | # Convert the 'Date' column to datetime 51 | df["Date"] = pd.to_datetime(df["Date"]) 52 | 53 | # Calculate the time difference from 24 hours ago 54 | target_time = datetime.now() - timedelta(hours=24) 55 | df["Time_Diff"] = abs(df["Date"] - target_time) 56 | 57 | # Find the minimum time difference 58 | min_time_diff = df["Time_Diff"].min() 59 | 60 | # Filter rows that have the minimum time difference 61 | closest_rows = df[df["Time_Diff"] == min_time_diff] 62 | 63 | # Convert the filtered rows to a dictionary with symbols as keys and RSI as values 64 | result = closest_rows.set_index("Symbol")["RSI"].to_dict() 65 | 66 | return result 67 | 68 | 69 | def save_RSI( 70 | rsi_dict: dict, time_frame: str, file_path: str = "data/rsi_data.csv" 71 | ) -> None: 72 | # Convert the RSI dictionary to a DataFrame 73 | df = pd.DataFrame(list(rsi_dict.items()), columns=["Symbol", "RSI"]) 74 | 75 | # Add the current date to the DataFrame 76 | df["Date"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S") 77 | df["Time Frame"] = time_frame 78 | 79 | # Check if the file exists 80 | if os.path.isfile(file_path): 81 | # Append data to the existing CSV file 82 | df.to_csv(file_path, mode="a", header=False, index=False) 83 | else: 84 | # Save the DataFrame to a new CSV file with header 85 | df.to_csv(file_path, index=False) 86 | 87 | print(f"RSI data saved to {file_path}") 88 | 89 | 90 | def get_top_vol_coins(length: int = 100) -> list: 91 | 92 | CACHE_FILE = "data/top_vol_coins_cache.pkl" 93 | CACHE_EXPIRATION = 24 * 60 * 60 # 24 hours in seconds 94 | # List of symbols to exclude 95 | STABLE_COINS = [ 96 | "OKBUSDT", 97 | "DAIUSDT", 98 | "USDTUSDT", 99 | "USDCUSDT", 100 | "BUSDUSDT", 101 | "TUSDUSDT", 102 | "PAXUSDT", 103 | "EURUSDT", 104 | "GBPUSDT", 105 | "CETHUSDT", 106 | "WBTCUSDT", 107 | ] 108 | 109 | # Check if the cache file exists and is not expired 110 | os.makedirs(CACHE_FILE.split("/")[0], exist_ok=True) 111 | if os.path.exists(CACHE_FILE): 112 | with open(CACHE_FILE, "rb") as f: 113 | cache_data = pickle.load(f) 114 | cache_time = cache_data["timestamp"] 115 | if time.time() - cache_time < CACHE_EXPIRATION: 116 | # Return the cached data if it's not expired 117 | print("Using cached top volume coins") 118 | return cache_data["data"][:length] 119 | 120 | # Fetch fresh data if the cache is missing or expired 121 | df = pd.DataFrame(cg.get_coins_markets("usd"))["symbol"].str.upper() + "USDT" 122 | 123 | sorted_volume = df[~df.isin(STABLE_COINS)] 124 | top_vol_coins = sorted_volume.tolist() 125 | 126 | # Save the result to the cache 127 | with open(CACHE_FILE, "wb") as f: 128 | pickle.dump({"timestamp": time.time(), "data": top_vol_coins}, f) 129 | 130 | return top_vol_coins[:length] 131 | -------------------------------------------------------------------------------- /src/main.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | from data import get_closest_to_24h, get_RSI, get_top_vol_coins 5 | 6 | FIGURE_SIZE = (12, 10) 7 | BACKGROUND_COLOR = "#0d1117" 8 | RANGES = { 9 | "Overbought": (70, 100), 10 | "Strong": (60, 70), 11 | "Neutral": (40, 60), 12 | "Weak": (30, 40), 13 | "Oversold": (0, 30), 14 | } 15 | COLORS_LABELS = { 16 | "Oversold": "#1d8b7a", 17 | "Weak": "#144e48", 18 | "Neutral": "#0d1117", 19 | "Strong": "#681f28", 20 | "Overbought": "#c32e3b", 21 | } 22 | SCATTER_COLORS = { 23 | "Oversold": "#1e9884", 24 | "Weak": "#165952", 25 | "Neutral": "#78797a", 26 | "Strong": "#79212c", 27 | "Overbought": "#cf2f3d", 28 | } 29 | 30 | 31 | def get_color_for_rsi(rsi_value: float) -> dict: 32 | for label, (low, high) in RANGES.items(): 33 | if low <= rsi_value < high: 34 | return SCATTER_COLORS[label] 35 | return None 36 | 37 | 38 | def plot_rsi_heatmap(num_coins: int = 100, time_frame: str = "1d") -> None: 39 | top_vol = get_top_vol_coins(num_coins) 40 | rsi_data = get_RSI(top_vol, time_frame=time_frame) 41 | old_rsi_data = get_closest_to_24h(time_frame=time_frame) 42 | 43 | # Create lists of labels and RSI values 44 | rsi_symbols = list(rsi_data.keys()) 45 | rsi_values = list(rsi_data.values()) 46 | 47 | # Calculate the average RSI value 48 | average_rsi = np.mean(rsi_values) 49 | 50 | # Create the scatter plot 51 | fig, ax = plt.subplots(figsize=FIGURE_SIZE) 52 | 53 | # Set the background color 54 | fig.patch.set_facecolor(BACKGROUND_COLOR) 55 | ax.set_facecolor(BACKGROUND_COLOR) 56 | 57 | # Define the color for each RSI range 58 | color_map = [] 59 | for k in RANGES: 60 | color_map.append((*RANGES[k], COLORS_LABELS[k], k)) 61 | 62 | # Fill the areas with the specified colors and create custom legend 63 | for i, (start, end, color, symbol) in enumerate(color_map): 64 | ax.fill_between([0, len(rsi_symbols) + 2], start, end, color=color, alpha=0.35) 65 | 66 | # Adjust the Y position for the first and last labels 67 | if i == 0: 68 | y_pos = start + 5 # Move down a bit from the top 69 | elif i == len(color_map) - 1: 70 | y_pos = end - 5 # Move up a bit from the bottom 71 | else: 72 | y_pos = (start + end) / 2 # Center for other labels 73 | 74 | # Add text to the right of the plot with the label (overbought, etc.) 75 | ax.text( 76 | len(rsi_symbols) + 1.5, # X position (to the right of the plot) 77 | y_pos, # Y position 78 | symbol.upper(), # Text to display 79 | va="center", # Vertical alignment 80 | ha="right", # Horizontal alignment 81 | fontsize=15, # Font size 82 | color="grey", # Text color 83 | ) 84 | 85 | # Plot each point with a white border for visibility 86 | for i, symbol in enumerate(rsi_symbols): 87 | # These are the dots on the plot 88 | ax.scatter( 89 | i + 1, 90 | rsi_values[i], 91 | color=get_color_for_rsi(rsi_values[i]), 92 | s=100, 93 | ) 94 | # Add the symbol text 95 | ax.annotate( 96 | symbol, 97 | (i + 1, rsi_values[i]), 98 | color="#b9babc", 99 | textcoords="offset points", 100 | xytext=(0, 10), 101 | ha="center", 102 | ) 103 | # Add line connecting the old and new RSI values 104 | if symbol in old_rsi_data: 105 | # Compare the previous RSI value with the current one 106 | rsi_diff = rsi_values[i] - old_rsi_data[symbol] 107 | 108 | # Set the color based on the difference 109 | line_color = "#1f9986" if rsi_diff > 0 else "#e23343" 110 | 111 | # Draw the line connecting the old and new RSI values 112 | ax.plot( 113 | [i + 1, i + 1], 114 | [old_rsi_data[symbol], rsi_values[i]], 115 | color=line_color, 116 | linestyle="--", 117 | linewidth=0.75, # Adjust the value to make the lines thinner 118 | ) 119 | 120 | # Draw the average RSI line and add the annotation 121 | ax.axhline( 122 | xmin=0, xmax=1, y=average_rsi, color="#d58c3c", linestyle="--", linewidth=0.75 123 | ) 124 | ax.text( 125 | len(rsi_symbols) + 1.5, # Increase to move the text to the right 126 | average_rsi, 127 | f"AVG RSI: {average_rsi:.2f}", 128 | color="#d58c3c", 129 | va="bottom", 130 | ha="right", 131 | fontsize=15, 132 | ) 133 | 134 | # Set the color of the tick labels to white 135 | ax.tick_params(colors="#a9aaab", which="both", length=0) 136 | 137 | # Set the y-axis limits based on RSI values 138 | ax.set_ylim(20, 80) 139 | 140 | # Extend the xlim to make room for the annotations 141 | ax.set_xlim(0, len(rsi_symbols) + 2) 142 | 143 | # Remove the x-axis ticks since we're annotating each point 144 | ax.set_xticks([]) 145 | 146 | add_legend(ax) 147 | 148 | # Set the color of the spines to match the background color or make them invisible 149 | for spine in ax.spines.values(): 150 | spine.set_edgecolor(BACKGROUND_COLOR) 151 | 152 | # Add the title in the top left corner 153 | plt.text( 154 | -0.025, 155 | 1.125, 156 | "Crypto Market RSI Heatmap", 157 | transform=ax.transAxes, 158 | fontsize=14, 159 | verticalalignment="top", 160 | horizontalalignment="left", 161 | color="white", 162 | weight="bold", 163 | ) 164 | 165 | plt.show() 166 | 167 | 168 | def add_legend(ax: plt.Axes) -> None: 169 | # Create custom legend handles with square markers, including BTC price 170 | adjusted_colors = list(COLORS_LABELS.values()) 171 | # Change NEUTRAL color to grey 172 | adjusted_colors[2] = "#808080" 173 | legend_handles = [ 174 | plt.Line2D( 175 | [0], 176 | [0], 177 | marker="s", 178 | color=BACKGROUND_COLOR, 179 | markerfacecolor=color, 180 | markersize=10, 181 | label=label, 182 | ) 183 | for color, label in zip( 184 | adjusted_colors, 185 | [label.upper() for label in list(COLORS_LABELS.keys())], 186 | ) 187 | ] 188 | 189 | # Add legend 190 | legend = ax.legend( 191 | handles=legend_handles, 192 | loc="upper center", 193 | bbox_to_anchor=(0.5, 1.05), 194 | ncol=len(legend_handles), 195 | frameon=False, 196 | fontsize="small", 197 | labelcolor="white", 198 | ) 199 | 200 | # Make legend text bold 201 | for text in legend.get_texts(): 202 | text.set_fontweight("bold") 203 | 204 | # Adjust layout to reduce empty space around the plot 205 | plt.subplots_adjust(left=0.05, right=0.95, top=0.875, bottom=0.1) 206 | 207 | 208 | if __name__ == "__main__": 209 | plot_rsi_heatmap(num_coins=100, time_frame="1d") 210 | --------------------------------------------------------------------------------