请求优化欧元兑英镑及反向汇率获取代码并调整输出格式
修改Python汇率获取代码方案
核心修改点
- 同时拉取EUR to GBP和GBP to EUR两组汇率数据
- 清洗原接口返回的
TIME_PERIOD/OBS_VALUE字段,只保留日期与对应汇率值 - 输出合并后的结构化数据,一行对应一个日期的双向汇率
完整代码示例
import requests import csv from datetime import datetime, timedelta def get_weekly_exchange_rates(): # 计算上周的日期范围(周一到周日,可按需调整) today = datetime.today() last_week_start = today - timedelta(days=today.weekday() + 7) last_week_end = today - timedelta(days=today.weekday() + 1) start_date = last_week_start.strftime("%Y-%m-%d") end_date = last_week_end.strftime("%Y-%m-%d") # 定义需要获取的汇率对 currency_pairs = [ ("EUR", "GBP"), ("GBP", "EUR") ] # 存储所有汇率数据,以日期为键 rate_data = {} # 批量请求汇率数据 for base, target in currency_pairs: # 以欧洲央行公开API为例,可替换为你正在使用的数据源接口 api_url = f"https://data.ecb.europa.eu/data/wfs/ECB_RTD?request=GetFeature&typename=RTD/MOB_EXR&outputFormat=json&srsname=EPSG:4326&filter=TIME_PERIOD between '{start_date}' and '{end_date}' and CURRENCY='{target}' and CURRENCY_DENOM='{base}' and EXR_TYPE='SP00' and EXR_SUFFIX='A'" response = requests.get(api_url) data = response.json() # 提取日期和汇率值 for feature in data["features"]: date = feature["properties"]["TIME_PERIOD"] rate = feature["properties"]["OBS_VALUE"] if date not in rate_data: rate_data[date] = {"date": date} rate_data[date][f"{base}_{target}"] = rate # 写入CSV文件 with open("weekly_exchange_rates.csv", "w", newline="", encoding="utf-8") as csvfile: fieldnames = ["date", "EUR_GBP", "GBP_EUR"] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for date in sorted(rate_data.keys()): writer.writerow(rate_data[date]) if __name__ == "__main__": get_weekly_exchange_rates()
代码说明
- 日期范围计算:自动计算上周起止日期,无需手动修改参数
- 批量请求处理:循环遍历两个汇率对,复用请求逻辑,减少冗余代码
- 数据清洗与合并:以日期为唯一键,将双向汇率整合到同一数据结构,避免重复日期行
- 输出格式调整:自定义CSV表头为
date、EUR_GBP、GBP_EUR,直接写入清洗后的数据,完全匹配需求格式
输出文件示例
date,EUR_GBP,GBP_EUR 2024-05-20,0.8523,1.1733 2024-05-21,0.8519,1.1738 2024-05-22,0.8531,1.1722
内容的提问来源于stack exchange,提问作者SeaBee
相关产品推荐
相关产品推荐

