python - 如何从 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
以此类推。按分钟间隔。我该怎么做?
解决方案
采用 -
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 小时的数据上显示了这一点。您可以相应地修改开始和结束日期
推荐阅读
- hyperledger-fabric - Hyperledger Fabric:/etc/hyperledger/fabric-ca-server/ca-chain.pem 中不存在链文件
- audio - 使用什么 ffmpeg 命令将无符号整数列表转换为音频文件?
- java - 如何在 Java 中使用 ComboBox 数据填充 ArrayList
- javascript - 发现奇怪的用户代理
- python - 如何从日志文件中提取java堆栈跟踪的时间戳?
- communication - 标准软件模式的 Word
- android - AppCompatDialogFragment 更改背景颜色
- r - 在 For Loop R 中操作迭代的 CSV 文件
- node.js - 开始在 npm prestart 上运行 cron 作业
- python - 带有 Python 3 和 virtualenv 的 AWS Lambda 无法安装依赖项