Yes, I can help you with that! Below is a Python script that fetches the top 50 cryptocurrencies by market capitalization using the CoinGecko API, calculates their 100-day moving average (MA100), and reports which ones have closed above their MA100 on the latest day.
Please note: This script uses the pycoingecko Python package to interact with the CoinGecko API and the pandas library for data manipulation. You'll need to install these packages if you haven't already:
pip install pycoingecko pandas
Here’s the script:
import pandas as pd
from pycoingecko import CoinGeckoAPI
from datetime import datetime, timedelta
def get_top_n_coins(n):
cg = CoinGeckoAPI()
# Get the top n coins by market cap
coins = cg.get_coins_markets(vs_currency='usd', order='market_cap_desc', per_page=n, page=1)
return [coin['id'] for coin in coins]
def get_historical_data(coin_id, days):
cg = CoinGeckoAPI()
# Get market chart data for the last 'days' days
data = cg.get_coin_market_chart_by_id(id=coin_id, vs_currency='usd', days=days)
prices = data['prices'] # Each entry: [timestamp, price]
df = pd.DataFrame(prices, columns=['timestamp', 'price'])
df['date'] = pd.to_datetime(df['timestamp'], unit='ms').dt.date
df = df.groupby('date').last().reset_index()
return df
def calculate_ma100(df):
df['MA100'] = df['price'].rolling(window=100).mean()
return df
def main():
top_coins = get_top_n_coins(50)
coins_above_ma100 = []
for coin_id in top_coins:
try:
df = get_historical_data(coin_id, 120) # Fetch data for the last 120 days to ensure we have at least 100 data points
if len(df) < 100:
print(f"Not enough data for {coin_id}. Skipping.")
continue
df = calculate_ma100(df)
latest_close = df.iloc[-1]['price']
latest_ma100 = df.iloc[-1]['MA100']
if pd.isna(latest_ma100):
print(f"MA100 not available for {coin_id}. Skipping.")
continue
if latest_close > latest_ma100:
coins_above_ma100.append(coin_id)
print(f"{coin_id} is above MA100.")
except Exception as e:
print(f"Error processing {coin_id}: {e}")
print("\nCoins that closed above their daily MA100:")
for coin in coins_above_ma100:
print(coin)
if __name__ == "__main__":
main()
Explanation:
-
get_top_n_coins(n): Fetches the top n coins by market capitalization using the CoinGecko API.
-
get_historical_data(coin_id, days): Retrieves historical daily closing prices for the specified coin over the past days.
-
calculate_ma100(df): Calculates the 100-day moving average (MA100) on the price data.
-
main(): Orchestrates the process for each coin:
- Fetch historical data.
- Calculate MA100.
- Check if the latest closing price is above the MA100.
Notes:
-
We fetch data for the last 120 days to ensure we have at least 100 valid data points, accounting for any missing data or days when the market was inactive.
-
We group the prices by date and take the last price of the day as the closing price.
-
The script handles exceptions and skips coins that don't have enough data.
Requirements:
- Python 3.x
- Libraries:
pycoingecko: To interact with the CoinGecko API.
pandas: For data manipulation.
Installation:
Install the required packages using pip:
pip install pycoingecko pandas
Running the Script:
Save the script to a file, for example, crypto_ma100.py, and run it using:
python crypto_ma100.py
Sample Output:
bitcoin is above MA100.
ethereum is above MA100.
...
Coins that closed above their daily MA100:
bitcoin
ethereum
...
This output lists the cryptocurrencies from the top 50 that closed above their 100-day moving average.
Disclaimer:
-
Data Accuracy: The data obtained from the CoinGecko API is for informational purposes only and may not be accurate or up to date. Cryptocurrency markets are highly volatile, and prices can change rapidly.
-
Investment Decisions: This script is for informational purposes and should not be used as the sole basis for investment decisions. Always conduct your own research and consider consulting a financial advisor.
-
API Usage Limits: Be mindful of the API usage limits set by CoinGecko. Excessive requests may result in your IP being temporarily blocked.
Further Improvements:
-
Error Handling: Enhance error handling to manage network issues or API downtime.
-
Data Caching: Implement caching to store API responses and reduce the number of requests.
-
Visualization: Add code to visualize price trends and moving averages using libraries like matplotlib.
-
Extended Analysis: Include other technical indicators or compare with MA50, MA200, etc.
Let me know if you need any adjustments or further assistance with the script!