histpx_top20.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import csv
  2. from binance.client import Client
  3. from datetime import datetime, timedelta
  4. # Replace with your Binance API key and secret
  5. api_key = 'WFIEaBuUafZ9ldAiMHLZ4Z1qHdVnpoDUVZM8MughMf6zmbSqGx5pEmQFBJysjwFp' # Optional for public data
  6. api_secret = 'C9HtmLk7fBCidyJI2lPtUbYhj4T0FdmJ0NE0LLipFiwUSR7euf1TEzJblEx1O6oA' # Optional for public data
  7. # Initialize the Binance client
  8. client = Client(api_key, api_secret)
  9. def get_top_traded_coins(limit=20):
  10. """Get the top traded coins by volume."""
  11. tickers = client.get_ticker()
  12. # Sort by quote volume (most traded)
  13. sorted_tickers = sorted(tickers, key=lambda x: float(x['quoteVolume']), reverse=True)
  14. # Extract the top 'limit' coins
  15. top_coins = [ticker['symbol'] for ticker in sorted_tickers[:limit]]
  16. return top_coins
  17. def get_historical_prices(symbol, days=30):
  18. """Get historical prices for a symbol over the last 'days' days."""
  19. end_time = datetime.now()
  20. start_time = end_time - timedelta(days=days)
  21. klines = client.get_historical_klines(symbol, Client.KLINE_INTERVAL_1DAY, start_time.strftime("%d %b, %Y"), end_time.strftime("%d %b, %Y"))
  22. # Extract closing prices
  23. prices = [float(kline[4]) for kline in klines]
  24. return prices
  25. def save_to_csv(data, days, filename='crypto_prices.csv'):
  26. """Save the data to a CSV file."""
  27. with open(filename, mode='w', newline='') as file:
  28. writer = csv.writer(file)
  29. writer.writerow(['Symbol'] + [f'Day {i+1}' for i in range(days)])
  30. for symbol, prices in data.items():
  31. writer.writerow([symbol] + prices)
  32. def main():
  33. # Get the top 20 traded coins
  34. top_coins = get_top_traded_coins(20)
  35. # Fetch historical prices for each coin
  36. crypto_prices = {}
  37. for coin in top_coins:
  38. print(f"Fetching prices for {coin}...")
  39. prices = get_historical_prices(coin, 60)
  40. crypto_prices[coin] = prices
  41. # Save the data to a CSV file
  42. save_to_csv(crypto_prices, 60)
  43. print("Data saved to crypto_prices.csv")
  44. if __name__ == "__main__":
  45. main()