strange_doge.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. ### Python Code
  2. import requests
  3. import pandas as pd
  4. import numpy as np
  5. import time
  6. import schedule
  7. import smtplib
  8. from email.mime.text import MIMEText
  9. from email.mime.multipart import MIMEMultipart
  10. from datetime import datetime
  11. # Configuration
  12. CRYPTO = 'dogecoin' # CoinGecko ID for DOGE
  13. CURRENCY = 'usd' # Base currency
  14. API_URL = f'https://api.coingecko.com/api/v3/simple/price?ids={CRYPTO}&vs_currencies={CURRENCY}'
  15. CHECK_INTERVAL_SECONDS = 60 # Check every 60 seconds
  16. Z_SCORE_THRESHOLD = 3.0 # Flag as anomaly if |Z-score| > 3
  17. HISTORY_WINDOW = 100 # Keep last 100 prices for mean/std calculation
  18. # Email configuration (replace with your details)
  19. EMAIL_FROM = 'vortify-lc@algometic.com'
  20. EMAIL_TO = 'larry1chan@qq.com'
  21. EMAIL_PASSWORD = 'g33kPoppy!'
  22. SMTP_SERVER = 'hwsmtp.exmail.qq.com'
  23. SMTP_PORT = 465
  24. # In-memory storage for historical prices
  25. price_history = []
  26. def fetch_price():
  27. """Fetch current price from CoinGecko API."""
  28. try:
  29. response = requests.get(API_URL)
  30. response.raise_for_status()
  31. data = response.json()
  32. price = data[CRYPTO][CURRENCY]
  33. return price
  34. except Exception as e:
  35. print(f"Error fetching price: {e}")
  36. return None
  37. def detect_anomaly(current_price):
  38. """Detect if the current price is an anomaly based on Z-score."""
  39. if len(price_history) < 2: # Need at least 2 points for std dev
  40. return False, 0.0
  41. # Calculate mean and std dev from history
  42. df = pd.DataFrame(price_history, columns=['price'])
  43. mean = df['price'].mean()
  44. std_dev = df['price'].std()
  45. if std_dev == 0: # Avoid division by zero
  46. return False, 0.0
  47. z_score = (current_price - mean) / std_dev
  48. is_anomaly = abs(z_score) > Z_SCORE_THRESHOLD
  49. return is_anomaly, z_score
  50. def send_email_alert(current_price, z_score):
  51. """Send email alert for anomaly."""
  52. subject = f"Anomaly Detected in {CRYPTO.upper()} Price!"
  53. body = f"""
  54. Alert Time: {datetime.now()}
  55. Current Price: ${current_price:.4f}
  56. Z-Score: {z_score:.2f} (Threshold: {Z_SCORE_THRESHOLD})
  57. This indicates a potential anomalous movement (spike or drop).
  58. """
  59. msg = MIMEMultipart()
  60. msg['From'] = EMAIL_FROM
  61. msg['To'] = EMAIL_TO
  62. msg['Subject'] = subject
  63. msg.attach(MIMEText(body, 'plain'))
  64. try:
  65. server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
  66. server.starttls()
  67. server.login(EMAIL_FROM, EMAIL_PASSWORD)
  68. server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
  69. server.quit()
  70. print("Email alert sent successfully.")
  71. except Exception as e:
  72. print(f"Error sending email: {e}")
  73. def monitor():
  74. """Main monitoring function: Fetch price, check for anomaly, alert if needed."""
  75. current_price = fetch_price()
  76. if current_price is None:
  77. return
  78. # Append to history (maintain fixed window size)
  79. price_history.append(current_price)
  80. if len(price_history) > HISTORY_WINDOW:
  81. price_history.pop(0)
  82. is_anomaly, z_score = detect_anomaly(current_price)
  83. print(f"{datetime.now()} - Current {CRYPTO.upper()} Price: ${current_price:.4f} | Z-Score: {z_score:.2f}")
  84. if is_anomaly:
  85. print(f"ANOMALY DETECTED! Z-Score: {z_score:.2f}")
  86. send_email_alert(current_price, z_score)
  87. # Schedule the monitor to run every CHECK_INTERVAL_SECONDS
  88. schedule.every(CHECK_INTERVAL_SECONDS).seconds.do(monitor)
  89. # Run the monitoring loop
  90. print(f"Starting {CRYPTO.upper()} price anomaly monitor...")
  91. while True:
  92. schedule.run_pending()
  93. time.sleep(1) # Sleep to avoid high CPU usage