VeighNa量化社区
你的开源社区量化交易平台
Member
avatar
加入于:
帖子: 4
声望: 0

不好意思刚开始学习,想请问下如何下载oanda外汇历史数据的?我使用策略回测的时候显示历史数据下载失败。。
求帮忙解答一下感激!!

Administrator
avatar
加入于:
帖子: 4550
声望: 325

OANDA没提供历史数据下载服务呢

Member
avatar
加入于:
帖子: 1
声望: 0

代码如下,自己用吧。论坛的排版似乎有问题。
`

from oandapyV20 import API
import oandapyV20.endpoints.instruments as instruments
import oandapyV20.endpoints.accounts as accounts
import pandas as pd
import datetime
from dateutil import parser

access_token = "xxx"
client = API(access_token)

step = 21600 # equals to 6h in UNIX_time.Depends on granulariy. for 5s 6 hours is maximum granularity time. for 1m 2160012 for 5m 2160012*5.
granularity = "M1"

begin_unix = int(parser.parse("2003-01-01 00:00:00 EDT").strftime('%s'))
end_unix = int(parser.parse("2020-01-23 00:000:00 EDT").strftime('%s'))

i = begin_unix+step
dataset = pd.DataFrame()

params = {"from": str(i-step),
"to": str(i),
"granularity":granularity,
"price":'M' } # 'A' stands for ask price; if you want to get Bid use 'B' instead or 'AB' for both.

name = "AUD_USD"

while i <= end_unix:
params['from'] = str(i-step)
params['to'] = str(i)
r = instruments.InstrumentsCandles(instrument=name,params=params)
data = client.request(r)
if data['candles']:
print(data['candles'][0]["time"])
results = [
{
"time": x['time'],
"open": float(x['mid']['o']),
"high": float(x['mid']['h']),
"low": float(x['mid']['l']),
"close": float(x['mid']['c']),
"volume": float(x['volume'])
} for x in data['candles']
]
df = pd.DataFrame(results)

if dataset.empty:
    dataset = df.copy()
else:
    dataset = dataset.append(df,
                             ignore_index=True)

if (i+step) >= end_unix:
    params['from'] = str(i)
    params['to'] = str(end_unix)
    r=instruments.InstrumentsCandles(instrument=name,
                                     params=params)
    data = client.request(r)
    results= [
                {
                    "time": x['time'],
                    "open": float(x['mid']['o']),
                    "high": float(x['mid']['h']),
                    "low": float(x['mid']['l']),
                    "close": float(x['mid']['c']),
                    "volume": float(x['volume'])
                } for x in data['candles']
             ]

    df = pd.DataFrame(results)

    i = i + step

    dataset = dataset.append(df,
                             ignore_index=True)

if len(dataset) > 2000000:
    dataset.to_csv(name+"_"+granularity+"_"+dataset['time'][0].split('T')[0]+"_"+dataset['time'][len(dataset)-1].split('T')[0]+'.csv',index=False)
    dataset=pd.DataFrame()
i = i + step

dataset.tocsv(name+""+granularity+""+dataset['time'][0].split('T')[0]+""+dataset['time'][len(dataset)-1].split('T')[0]+'.csv',index=False)

`

© 2015-2022 上海韦纳软件科技有限公司
备案服务号:沪ICP备18006526号

沪公网安备 31011502017034号

【用户协议】
【隐私政策】
【免责条款】