使用欧洲央行数据的货币转换器。
CurrencyConverter的Python项目详细描述
这是一个使用历史汇率对参考货币(欧元)的货币转换器。
货币数据源
默认源是European Central Bank。这是欧洲央行自1999年以来42种货币对欧元的历史汇率。 可以在这里下载:eurofxref-hist.zip。 只要格式相同,转换器就可以使用不同的源。
安装
克隆后可以直接安装:
$ python setup.py install --user
或者使用python包:
$ pip install --user currencyconverter
命令行工具
安装后,您的$PATH中应该有currency_converter:
$ currency_converter 100 USD --to EUR 100.000 USD=87.512 EUR on 2016-05-06
python api
创建一次currency converter对象:
>>>fromcurrency_converterimportCurrencyConverter>>>c=CurrencyConverter()
使用最后可用的速率从EUR转换为USD:
>>>c.convert(100,'EUR','USD')# doctest: +SKIP137.5...
默认目标货币为EUR:
>>>c.convert(100,'EUR')100.0>>>c.convert(100,'USD')# doctest: +SKIP72.67...
您可以更改费率日期:
>>>fromdatetimeimportdate# datetime works too>>>c.convert(100,'EUR','USD',date=date(2013,3,21))129...
回退
缺少一些费率:
>>>c.convert(100,'BGN',date=date(2010,11,21))Traceback(mostrecentcalllast):RateNotFoundError:BGNhasnoratefor2010-11-21
但是我们有一个后备模式,使用 最接近的已知汇率,只要您要求的日期在货币日期范围内:
>>>c=CurrencyConverter(fallback_on_missing_rate=True)>>>c.convert(100,'BGN',date=date(2010,11,21))51.12...
对于超出货币界限的日期,我们也有一个后备模式:
>>>c=CurrencyConverter()>>>c.convert(100,'EUR','USD',date=date(1986,2,2))Traceback(mostrecentcalllast):RateNotFoundError:1986-02-02notinUSDbounds1999-01-04/2016-04-29>>>>>>c=CurrencyConverter(fallback_on_wrong_date=True)>>>c.convert(100,'EUR','USD',date=date(1986,2,2))# fallback to 1999-01-04117.89...
其他属性
- bounds让您知道每种货币的第一个和最后一个可用日期
>>>first_date,last_date=c.bounds['USD']>>>first_datedatetime.date(1999,1,4)>>>last_date# doctest: +SKIPdatetime.date(2016,11,14)
- currencies是包含所有可用货币的集合
>>>c.currencies# doctest: +SKIPset(['SGD','CAD','SEK','GBP',...>>>'AAA'inc.currenciesFalse>>>c.convert(100,'AAA')Traceback(mostrecentcalllast):ValueError:AAAisnotasupportedcurrency
最后,您可以使用自己的货币文件,只要它具有相同的格式(ecb):
# Load the packaged data (might not be up to date)c=CurrencyConverter()# Load the up to date full historyc=CurrencyConverter('http://www.ecb.int/stats/eurofxref/eurofxref-hist.zip')# Load only the latest rates (single day data source)c=CurrencyConverter('http://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip')# Load your custom filec=CurrencyConverter('./path/to/currency/file.csv')