1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
| import requests import json import time from datetime import datetime import os from typing import Dict, List import pandas as pd
class RealtimeExchangeMonitor: """实时汇率监控器(专业版)""" def __init__(self, config_file='monitor_config.json'): self.config_file = config_file self.monitoring = False self.load_config() def load_config(self): """加载监控配置""" default_config = { "base_currency": "USD", "monitor_pairs": [ {"currency": "CNY", "target": 7.25, "direction": "below", "active": True}, {"currency": "EUR", "target": 0.92, "direction": "above", "active": False}, {"currency": "JPY", "target": 150, "direction": "above", "active": False} ], "check_interval": 300, "alert_sound": True, "save_history": True, "history_file": "exchange_history.csv" } if os.path.exists(self.config_file): try: with open(self.config_file, 'r', encoding='utf-8') as f: self.config = json.load(f) print("✅ 配置加载成功") except: self.config = default_config print("⚠️ 配置加载失败,使用默认配置") else: self.config = default_config self.save_config() print("📄 创建默认配置文件") def save_config(self): """保存配置""" with open(self.config_file, 'w', encoding='utf-8') as f: json.dump(self.config, f, ensure_ascii=False, indent=2) def add_monitor_pair(self): """添加监控货币对""" print("\n" + "="*40) print("添加监控货币对") print("="*40) base = input("基础货币(如USD): ").strip().upper() target = input("目标货币(如CNY): ").strip().upper() target_rate = float(input("目标汇率: ").strip()) direction = input("方向(above/below): ").strip().lower() new_pair = { "currency": target, "target": target_rate, "direction": direction, "active": True } self.config["monitor_pairs"].append(new_pair) self.save_config() print(f"✅ 已添加 {base}/{target} 监控") def get_rate_with_fallback(self, base: str, target: str) -> Dict: """获取汇率(带备用API)""" try: result = get_exchange_rate(base, target) if result['状态'] == '成功': return result except: pass try: print("尝试备用API...") url = f"https://api.frankfurter.app/latest?base={base}&symbols={target}" response = requests.get(url, timeout=5) data = response.json() if 'rates' in data and target in data['rates']: return { '汇率': data['rates'][target], '更新时间': data.get('date', ''), '状态': '成功', '基础货币': base, '目标货币': target } except Exception as e: print(f"备用API也失败: {e}") return {'状态': '失败', '错误': '所有API不可用', '汇率': 0} def save_to_history(self, rates: Dict): """保存到历史记录CSV""" if not self.config['save_history']: return timestamp = datetime.now() history_file = self.config['history_file'] row = { '时间戳': timestamp.strftime('%Y-%m-%d %H:%M:%S'), '基础货币': self.config['base_currency'] } for currency, rate in rates.items(): row[f'{currency}_汇率'] = rate if os.path.exists(history_file): df = pd.read_csv(history_file) df = pd.concat([df, pd.DataFrame([row])], ignore_index=True) else: df = pd.DataFrame([row]) df = df.tail(1000) df.to_csv(history_file, index=False) print(f"💾 历史记录已更新: {history_file}") def show_history_chart(self): """显示汇率走势图(需要matplotlib)""" try: import matplotlib.pyplot as plt history_file = self.config['history_file'] if not os.path.exists(history_file): print("⚠️ 暂无历史数据") return df = pd.read_csv(history_file) df['时间戳'] = pd.to_datetime(df['时间戳']) plt.figure(figsize=(12, 6)) currencies = ['CNY', 'EUR', 'JPY', 'GBP'] colors = ['red', 'blue', 'green', 'orange'] for i, currency in enumerate(currencies): col = f'{currency}_汇率' if col in df.columns: plt.plot(df['时间戳'], df[col], marker='o', label=f'{self.config["base_currency"]}/{currency}', color=colors[i]) plt.title(f'{self.config["base_currency"]}汇率走势', fontsize=14) plt.xlabel('时间') plt.ylabel('汇率') plt.legend() plt.xticks(rotation=45) plt.grid(True, linestyle='--', alpha=0.6) plt.tight_layout() plt.savefig(f'汇率走势图_{datetime.now().strftime("%Y%m%d")}.png', dpi=150) plt.show() except ImportError: print("⚠️ 未安装matplotlib,无法显示图表") def run_monitor(self): """运行监控""" print("\n🤖 启动汇率自动监控系统") print(f"监控基础货币: {self.config['base_currency']}") print(f"检查间隔: {self.config['check_interval']}秒") active_pairs = [p for p in self.config['monitor_pairs'] if p['active']] if not active_pairs: print("⚠️ 没有激活的监控项") return self.monitoring = True try: check_count = 0 while self.monitoring: check_count += 1 print(f"\n{'='*50}") print(f"第 {check_count} 次检查 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") print(f"{'='*50}") rates = {} for pair in active_pairs: target = pair['currency'] result = self.get_rate_with_fallback(self.config['base_currency'], target) if result['状态'] == '成功': rate = result['汇率'] rates[target] = rate target_rate = pair['target'] direction = pair['direction'] if direction == 'above' and rate >= target_rate: print(f"🎯 {self.config['base_currency']}/{target} 达到目标!") self._send_alert(self.config['base_currency'], target, rate, target_rate) elif direction == 'below' and rate <= target_rate: print(f"🎯 {self.config['base_currency']}/{target} 达到目标!") self._send_alert(self.config['base_currency'], target, rate, target_rate) else: diff = abs(rate - target_rate) print(f" {target}: {rate:.4f} (距离目标{target_rate:.4f}差{diff:.4f})") else: print(f" {target}: 查询失败") time.sleep(1) if rates: self.save_to_history(rates) print(f"\n⏰ 等待 {self.config['check_interval']} 秒后下次检查...") time.sleep(self.config['check_interval']) except KeyboardInterrupt: print("\n\n用户手动停止监控") self.monitoring = False def _send_alert(self, base: str, target: str, current: float, target_rate: float): """发送提醒""" print("\n" + "="*50) print("🚨 汇率监控提醒") print("="*50) print(f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") print(f"货币对: {base}/{target}") print(f"当前汇率: {current:.4f}") print(f"目标汇率: {target_rate:.4f}") if current >= target_rate: print("📈 汇率上涨突破目标!") else: print("📉 汇率下跌跌破目标!") if self.config.get('alert_sound', False): print('\a') print("="*50) alert_file = "汇率提醒记录.txt" with open(alert_file, 'a', encoding='utf-8') as f: f.write(f"{datetime.now()} - {base}/{target}: {current:.4f} (目标: {target_rate:.4f})\n")
def main(): """主菜单""" monitor = RealtimeExchangeMonitor() print("=" * 60) print("实时汇率监控器(专业版)") print("支持多货币对监控,自动记录历史,触发提醒") print("=" * 60) while True: print("\n" + "=" * 45) print("功能菜单") print("=" * 45) print("1. 查询当前汇率") print("2. 查看历史记录") print("3. 添加监控货币对") print("4. 查看配置") print("5. 启动自动监控") print("6. 显示汇率走势图") print("7. 退出") print("=" * 45) choice = input("请选择: ").strip() if choice == "1": base = input("基础货币(默认USD): ").strip().upper() or 'USD' target = input("目标货币(如CNY): ").strip().upper() if target: result = monitor.get_rate_with_fallback(base, target) if result['状态'] == '成功': print(f"\n✅ 1 {base} = {result['汇率']:.4f} {target}") print(f"⏰ 更新时间: {result['更新时间']}") elif choice == "2": monitor.show_history(10) elif choice == "3": monitor.add_monitor_pair() elif choice == "4": print("\n当前配置:") print(json.dumps(monitor.config, ensure_ascii=False, indent=2)) elif choice == "5": print("\n启动前请确保配置正确。") confirm = input("确认启动自动监控?(y/n): ").strip() if confirm.lower() == 'y': monitor.run_monitor() elif choice == "6": monitor.show_history_chart() elif choice == "7": print("👋 感谢使用,监控已停止!") monitor.monitoring = False break else: print("请输入1-7!")
if __name__ == "__main__": main()
|