通过 investpy 在循环中下载数据时的错误日期

Wrong Dates when Downloading Data in Loop through investpy

我正在尝试调试我用来通过 investpy 下载数据的某些代码中的一些奇怪行为 API (investing.com)。

发生的情况是,我最初从 2000 年开始下载数据,但将开始日期更改为 2007 年以避免出现 NaN。我是 运行 通过 for 循环获取我想下载的所有系列的数据。出于某种原因,这样做不会改变开始日期,我不明白为什么。

为避免误解:我的问题不是关于如何截断缺失的观察结果,这很简单。我试图了解导致此问题的原因,因为我想避免我可能遗漏的另一个错误。

感谢您的帮助!

代码:

import investpy
import pandas as pd
maturities=['3M','6M','1Y','2Y','3Y','4Y','5Y','6Y','7Y','8Y','9Y','Germany 10-Year','20Y','30Y']
eu = list()
for x in maturities:
    search_result = investpy.search_quotes(text=x, products=['bonds'],
                                       countries=['germany'], n_results=1)
    historical_data = search_result.retrieve_historical_data(from_date='04/01/2007', to_date='23/07/2021')
    eu.append(historical_data.Close)
eu=pd.concat(eu, axis=1)
eu.columns=maturities
eu=eu.reindex(date).fillna(method='ffill')
eu=eu.add_prefix('eu_')
eu = eu.rename(columns={'eu_Germany 10-Year': 'eu_10Y'})
eu

我将在这里为那些最终遇到类似问题的人(由于 lazy/sloppy 代码风格)回答我自己的问题。我忘了复制解释它的重要行,这是完整的代码:

maturities=['3M','6M','1Y','2Y','3Y','4Y','5Y','6Y','7Y','8Y','9Y','Germany 10-Year','20Y','30Y']
eu = list()
date=pd.date_range('2007-01-04', '2021-07-23')
for x in maturities:
    search_result = investpy.search_quotes(text=x, products=['bonds'],
                                       countries=['germany'], n_results=1)
    historical_data = search_result.retrieve_historical_data(from_date='04/01/2007', to_date='23/07/2021')
    eu.append(historical_data.Close)
eu=pd.concat(eu, axis=1)
eu.columns=maturities
eu=eu.reindex(date).fillna(method='ffill')
eu=eu.add_prefix('eu_')
eu = eu.rename(columns={'eu_Germany 10-Year': 'eu_10Y'})
eu

在最高位(如您所猜)我仍然存储了以下行:

date=pd.date_range('2000-01-04', '2021-07-23')

这强制 re-indexation 从 2000 年开始的日期,为我在查询中选择的开始日期之前的所有日子创建 NaN。