如何通过FAS PSD Data API获取指定发布月份的WASDE数据?
如何通过FAS PSD Data API获取指定发布月份的WASDE数据?
我来帮你搞定这个问题!你已经把大部分流程走通了,只是在指定发布月份的参数配置上出了点小问题。咱们一起梳理下解决方案:
核心问题:缺少发布年份参数
你当前的请求URL只指定了releaseMonth,但API需要同时知道发布年份和月份才能定位到准确的WASDE报告(比如2024年1月和2023年1月是完全不同的两份报告)。
修正后的代码实现
我调整了你的world_snd函数,新增了release_year和release_month参数,同时更新了API请求的URL路径,把发布年份也加进去:
import requests import pandas as pd corn = "0440000" marketing_year = "2023" target_release_year = "2024" target_release_month = "01" # 注意要用两位数字格式 def get_attributes(): URL = "https://apps.fas.usda.gov/OpenData/api/psd/commodityAttributes" headers_dict = {"API_KEY": "my_api_key"} wData = requests.get(url=URL, headers=headers_dict) if wData.status_code == 200: data = wData.json() return pd.DataFrame(data) else: print(f"Request failed with status code {wData.status_code}") return None def get_units(): URL = "https://apps.fas.usda.gov/OpenData/api/psd/unitsOfMeasure" headers_dict = {"API_KEY": "my_api_key"} wData = requests.get(url=URL, headers=headers_dict) if wData.status_code == 200: data = wData.json() return pd.DataFrame(data) else: print(f"Request failed with status code {wData.status_code}") return None def world_snd(commodity_code, marketing_year, release_year, release_month): # 修正URL:添加releaseYear参数 URL = f"https://apps.fas.usda.gov/OpenData/api/psd/commodity/{commodity_code}/world/year/{marketing_year}/releaseYear/{release_year}/releaseMonth/{release_month}" headers_dict = {"API_KEY": "my_api_key"} wData = requests.get(url=URL, headers=headers_dict) if wData.status_code == 200: data = wData.json() df = pd.DataFrame(data) else: print(f"Request failed with status code {wData.status_code}") return None # 映射属性名称 attributes = get_attributes() if attributes is not None: df['attributeId'] = df['attributeId'].map(attributes.set_index('attributeId')['attributeName']) # 映射单位 units = get_units() if units is not None: df['unitId'] = df['unitId'].map(units.set_index('unitId')['unitDescription']) # 处理数值和索引 df['value'] = df['value'].round(0) df.set_index("attributeId", inplace=True) return df # 调用函数获取2024年1月的报告数据 df = world_snd(corn, marketing_year, target_release_year, target_release_month) print(df)
额外验证技巧
如果还是遇到请求失败的情况,可以先调用发布日期列表接口,确认目标月份的报告是否存在:
def get_release_dates(): URL = "https://apps.fas.usda.gov/OpenData/api/psd/releaseDates" headers_dict = {"API_KEY": "my_api_key"} wData = requests.get(url=URL, headers=headers_dict) if wData.status_code == 200: return pd.DataFrame(wData.json()) else: print(f"Request failed with status code {wData.status_code}") return None # 查看所有可用的发布日期 release_dates_df = get_release_dates() print(release_dates_df[['releaseYear', 'releaseMonth']].drop_duplicates())
这个接口会返回所有已发布报告的年份和月份组合,你可以从中确认是否有你需要的2024年1月数据,避免请求不存在的报告版本。
备注:内容来源于stack exchange,提问作者Fabian
相关产品推荐
相关产品推荐

