Python中的外汇历史数据

时间:2017-06-17 12:06:32

标签: python api forex

一直在寻找好几个小时,所以请善待。

需要使用Python获取历史外汇数据的解决方案。

对于股票来说很容易:

import pandas as pd
import pandas_datareader as pdr

start = dt.date.today() - dt.timedelta(days=30)
end = dt.date.today()

df = pdr.DataReader('AAPL', 'google', start, end)
print(df.head())

尝试过google,yahoo,fred和oanda。似乎没什么用。

请举例说明如何申请数据。 (在大多数情况下,一行应该没问题。)

谢谢。

7 个答案:

答案 0 :(得分:3)

您只需要历史货币值吗?

尝试将 forex_python 模块与datetime类(来自datetime模块)一起使用。我使用python 3,但我怀疑这太重要了。

这些汇率是自1999年以来欧洲中央银行的下午3点(CET)数据。

>>> from datetime import datetime
>>> from forex_python.converter import get_rate

>>> t = datetime(2001, 10, 18)  # the 18th of October, 2001
>>> get_rate("USD", "GBP", t)
0.69233
>>> get_rate("GBP", "USD", t)
1.4444
>>> 1 / 1.4444   # check
0.6923289947382997 

>>> t = datetime(2006, 6, 26)  # June 26th, 2006
>>> get_rate("GBP", "USD", t)
1.8202

因此
在18/10/01,1 USD == 0.69 GBP,
2006年6月26日,1英镑== 1.82美元。

答案 1 :(得分:2)

零售经纪人供稿总是偏斜,但我不同意没有好的历史供稿。 FX的行业标准是EBS feed。但是,这是一个昂贵的选择。 FXMarketAPI提供的供稿与此非常匹配。它不隶属于任何经纪人。该API有一个熊猫端点,可帮助您提取数据。虽然免费用户有1000个请求的限制。您可以在下面看到一个示例。

URL = "https://fxmarketapi.com/apipandas"
params = {'currency' : 'EURUSD',
'start_date' : '2018-07-02',
'end_date':'2018-12-06',
'api_key':'**************'}

response = requests.get("https://fxmarketapi.com/apipandas", params=params)
df= pd.read_json(response.text)

答案 2 :(得分:2)

从2009年开始,胡椒粉每月以csv格式免费提供基于滴答的历史数据(访问:https://www.truefx.com/?page=downloads),对于大多数最受欢迎的货币对,我已经使用selenium编写了python代码,以下载所有csv文件(脚本将下载)将所有csv文件放入文件夹名称forex):

import datetime, time, os
from dateutil.relativedelta import relativedelta

from selenium import webdriver

tmp_dir = os.path.join(os.getcwd(), 'forex')
if not os.path.isdir(tmp_dir): os.makedirs(tmp_dir)
options = webdriver.ChromeOptions();
options.add_argument("--window-size=1300,900")
options.add_experimental_option("prefs", {
    "download.default_directory": tmp_dir,
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": False,
    "safebrowsing.disable_download_protection": True
})
options.add_argument("--disable-gpu")
options.add_argument("--disable-extensions")
options.add_argument('--disable-logging')
options.add_argument('--ignore-certificate-errors')
options.add_argument('--ignore-certificate-errors-spki-list')
options.add_argument('--no-sandbox')
browser = webdriver.Chrome(options=options)

pairs = ['AUDJPY', 'AUDNZD', 'AUDUSD', 'CADJPY', 'CHFJPY', 'EURCHF', 'EURGBP', 'EURJPY', 'EURUSD', 'GBPJPY', 'GBPUSD', 'NZDUSD', 'USDCAD', 'USDCHF', 'USDJPY']
for pair in pairs:
    curr_date = datetime.datetime(2015, 1, 1)
    while curr_date + relativedelta(months=1) < datetime.datetime.now():
        file_name = '{p}-{ym2}.zip'.format(p=pair, ym2=curr_date.strftime('%Y-%m'))
        url = 'http://www.truefx.com/dev/data/{y}/{ym1}/{p}-{ym2}.zip'.format(
            y=curr_date.strftime('%Y'),
            ym1=curr_date.strftime('%B').upper()+'-'+curr_date.strftime('%Y') if curr_date <= datetime.datetime(2017, 3, 1) else curr_date.strftime('%Y-%m'),
            p=pair,
            ym2=curr_date.strftime('%Y-%m')
        )
        file_found = False
        for root, dirs, files in os.walk(tmp_dir):
            for file in files:
                if file_name in file: file_found = True 
        if not file_found:
            time.sleep(5)
            browser.get (url)
            file_downloaded = False
            while not file_downloaded:
                time.sleep(1)
                for root, dirs, files in os.walk(tmp_dir):
                    for file in files:
                        if file_name in file and not '.crdownload' in file: file_downloaded = True
            print(file_name, 'downloaded from', url)
        curr_date = curr_date + relativedelta(months=1)
print('completed')

要点: https://gist.github.com/mamedshahmaliyev/bca9242b7ea6a13b3f76dee7a5aa111a

答案 3 :(得分:1)

也许你看起来不够努力:)一个非常好看的小伙子几个月前发表了这篇文章。不可否认,这不是最好的代码(第一个开源项目),但是,它目前正在开发中并且在不断改进。下一个版本将更加高效和清洁。

fx_collect

旨在将所有FXCM的历史数据存储在Mariadb本地。

    +---------------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+--------+
    | date                | bidopen   | bidhigh   | bidlow    | bidclose  | askopen   | askhigh   | asklow    | askclose  | volume |
    +---------------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+--------+
    | 2017-04-27 10:01:00 | 17.294000 | 17.296000 | 17.289000 | 17.290000 | 17.340000 | 17.340000 | 17.334000 | 17.335000 |    113 |
    | 2017-04-27 10:02:00 | 17.290000 | 17.298000 | 17.285000 | 17.295000 | 17.335000 | 17.342000 | 17.330000 | 17.340000 |    114 |
    | 2017-04-27 10:03:00 | 17.295000 | 17.301000 | 17.289000 | 17.299000 | 17.340000 | 17.347000 | 17.340000 | 17.344000 |     98 |
    | 2017-04-27 10:04:00 | 17.299000 | 17.300000 | 17.286000 | 17.295000 | 17.344000 | 17.345000 | 17.330000 | 17.340000 |    124 |
    | 2017-04-27 10:05:00 | 17.295000 | 17.295000 | 17.285000 | 17.292000 | 17.340000 | 17.340000 | 17.330000 | 17.336000 |    130 |
    | 2017-04-27 10:06:00 | 17.292000 | 17.292000 | 17.279000 | 17.292000 | 17.336000 | 17.336000 | 17.328000 | 17.332000 |     65 |
    | 2017-04-27 10:07:00 | 17.292000 | 17.304000 | 17.287000 | 17.298000 | 17.332000 | 17.348000 | 17.332000 | 17.345000 |    144 |
    | 2017-04-27 10:08:00 | 17.298000 | 17.306000 | 17.297000 | 17.302000 | 17.345000 | 17.350000 | 17.343000 | 17.346000 |     96 |
    | 2017-04-27 10:09:00 | 17.302000 | 17.303000 | 17.294000 | 17.294000 | 17.346000 | 17.346000 | 17.338000 | 17.338000 |     50 |
    | 2017-04-27 10:10:00 | 17.294000 | 17.296000 | 17.281000 | 17.291000 | 17.338000 | 17.338000 | 17.328000 | 17.333000 |     50 |

或者如果您只是想要基本工具来帮助您开始构建自己的工具。

python-forexconnect

需要Demo或Live FXCM帐户才能获取数据。他们在不同的时间范围内提供免费的10年历史数据(fxcm)。

答案 4 :(得分:1)

FXCM最近发布了官方的forexconnect python包装器。

有一个支持论坛: http://www.fxcodebase.com/code/viewforum.php?f=51&sid=e2b414c06f9714c605f117f74d689a9b

有关获取历史记录的文章中有一个代码段:

from forexconnect import fxcorepy, ForexConnect
    with ForexConnect() as fx:
        try:
            fx.login("user_id", "password", "fxcorporate.com/Hosts.jsp",
                     "Demo", session_status_callback=session_status_changed)

            history = fx.get_history("EUR/USD", "H1",
                                    datetime.datetime.strptime("MM.DD.YYYY HH:MM:SS", '%m.%d.%Y %H:%M:%S').replace(tzinfo=datetime.timezone.utc),
                                    datetime.datetime.strptime("MM.DD.YYYY HH:MM:SS", '%m.%d.%Y %H:%M:%S').replace(tzinfo=datetime.timezone.utc))

答案 5 :(得分:0)

您可以使用fxcmpy。 http://fxcmpy.tpq.io/

这是一个简单的例子:

import matplotlib.pyplot as plt
import datetime as dt
import fxcmpy

con = fxcmpy.fxcmpy(config_file='fxcm.cfg') 
# must optain API Token, see link for details.

start = dt.datetime(2018, 7, 6,8,0,0)
end = dt.datetime(2018, 7, 7,18,0,0)

c = con.get_candles('XAU/USD', period='m1', columns=['bidclose','tickqty'], start=start, end=end )

# Basic plotting of close and volumne data

fig, ax = plt.subplots(figsize=(11,8))
ax.plot(c.index,c['bidclose'], lw=1, color='B',label="Close")
ax2= ax.twinx()
ax2.plot(c.index,c['tickqty'], lw=1, color='G',label="Volume")
plot.show()

答案 6 :(得分:-2)

(cit。:) 在大多数情况下,一行应该没问题?

在这方面不能错。

外汇历史数据没有任何内容。每个外汇交易调解员(经纪人)创建他们自己的交易条款&amp;条件。即使是相同的经纪商也可能为同一货币对交易提供几种不同的(或者如果愿意的话不一致)价格 - 这样就可以满足每种“产品”的T&amp; C。

FOREX生态系统是一个分散的,多代理/多角色,主要是分布式的全球市场。

所以请忘记拥有一个SLOC,一个神奇的单行程,以从一些不存在的神圣API获得普遍有效的响应。没有这样的。

是的,可以接收外汇数据 - 但每个经纪商提供不同的图片:

enter image description here 是的,对于一种特定类型的交易账户,可以将localhost进程与来自一个特定Broker的不同API服务集成(参考相应的T&amp; C,以获取此类数据馈送的详细上下文)。

一些经纪人发布他们的本地刻度数据,有些则没有。一些研究机构可能会帮助您进行一些研究动机,并分享特定CCY对的选定数据。但全球整合并不存在。它没有理由聚合这种没有增值的服务。

如果一个人的体外定量模型应该有意义,那么该模型应该针对同一个市场进行验证,预计交易将在体内进行。

因此,您需要一个特定的市场访问调解员数据(经纪人要求这样做),您的服务将在那里进行体内操作。