首页 > 解决方案 > 如何从 python 中的一系列日期获取历史上的外汇汇率?

问题描述

我能够实时获得一年中特定时间的费率。但是我怎么能只要求一个日期范围和那天的货币价值呢?

 from forex_python.converter import CurrencyRates
    ...: import datetime
    ...: 
    ...: c = CurrencyRates()
    ...: 
    ...: dt = datetime.datetime(2020, 3, 27, 11, 21, 13, 114505)
    ...: 
    ...: print(c.get_rate('CAD', 'USD', dt))
0.7072353585464853

我的目标是有一张桌子

Rate   DateTime                Currency
0.702   08-01-2007 1:15pm      CAD - USD
0.712   08-01-2007 1:16pm      CAD - USD

以此类推。按分钟间隔。我该怎么做?

标签: pythonpandasdatetimecurrencyforex

解决方案


采用 -

from forex_python.converter import CurrencyRates
c = CurrencyRates()

df['DateTime'] = pd.to_datetime(df['DateTime'], format='%d-%m-%Y %I:%M%p')
df['Rate_'] = df.apply(lambda x: c.get_rate(x['Currency'].split('-')[0].strip(), x['Currency'].split('-')[1].strip(), x['DateTime']), axis=1)

输出

                Rate            DateTime   Currency              Rate_
0 0.7020000000000001 2007-01-08 13:15:00  CAD - USD 0.8510666143174977
1 0.7120000000000001 2007-01-08 13:16:00  CAD - USD 0.8510666143174977

更新

基于OP的更新查询:

df = pd.DataFrame(pd.date_range(start='8/16/2021 10:00:00', end='8/16/2021 11:00:00', freq='1min'), columns=['DateTime'])

def get_rate(x):
    try:
        op = c.get_rate('CAD', 'USD', x)
    except Exception as re:
        print(re)
        op=None
    return op

df['Rate'] = df['DateTime'].apply(get_rate)

我仅在 1 小时的数据上显示了这一点。您可以相应地修改开始和结束日期


推荐阅读