2017-08-03 79 views
0

我試圖讓OANDA的歷史價格爲歐元兌美元。我試圖讓過去的5000,但我只收到180無法獲取OANDA歷史價格

這是我的代碼:

def get_data_oanda(num_periods, **keyword_parameters): 
    """ 
    Environment     Description 
    fxTrade (Live)    The live (real money) environment 
    fxTrade Practice (Demo)  The demo (simulated money) environment 
    """ 
    domainDict = { 'live' : 'api-fxtrade.oanda.com','demo' : 'api-fxpractice.oanda.com' } 
    environment = 'demo' 
    domain = domainDict[environment] 
    access_token = 'xxxx' 
    account_id = 'xxxx' 
    instruments = 'EUR_USD' 
    count = num_periods 
    granularity = "M1" 
    try: 
     s = requests.Session() 
     url = "https://" + domain + "/v1/candles" 
     headers = {'Authorization' : 'Bearer ' + access_token, 
        # 'X-Accept-Datetime-Format' : 'unix' 
        } 
     params = {'instrument' : instruments, 'accountId' : account_id, 'count' : count, 'granularity' : granularity} 
     req = requests.Request('GET', url, headers = headers, params = params) 
     pre = req.prepare() 
     resp = s.send(pre, stream = True, verify = True) 
     return resp 
    except Exception as e: 
     s.close() 
     print() 
     print("Caught exception when connecting to stream\n" + str(e)) 


num_periods = 5000 
my_date = datetime.datetime.now(pytz.timezone('America/Sao_Paulo')).strftime('%Y-%m-%dT%H:%M:%S') 
timezone = 'America/Sao_Paulo' 
response = get_data_oanda(num_periods) 
msg = json.loads(response.text) 
candles = msg['candles'] 
for candle in candles: 
    df_data = df_data.append({ 
      'date': datetime.datetime.strptime(candle['time'], '%Y-%m-%dT%H:%M:%S.000000Z').replace(tzinfo=pytz.utc).astimezone(local_tz).strftime('%Y-%m-%d %H:%M:%S'), 
      'instrument': msg['instrument'], 
      "open": candle['openAsk'], 
      "high": candle['highAsk'], 
      "low": candle['lowAsk'], 
      "close": candle['closeAsk'], 
      "volume": candle['volume'] 
     },ignore_index=True) 

但df_data只有180行,而不是5000

[180 rows x 7 columns] 

我該如何解決這個問題?

回答

1

如何解決這個問題是剝離下來的基礎。得到一個簡單的電話requests.get()的工作和打印文本。一旦你的API返回你所需要的結果,然後在熊貓一邊工作。如果API沒有返回您需要的結果,請聯繫服務提供商。

在熊貓加載JSON正確的方法就簡單得多了,就像這樣:

resp = requests.get(url, headers=headers, params=params, stream=True) 
df = pd.read_json(resp.raw) 
df_data = pd.io.json.json_normalize(df.candles) 
df_data['time'] = pd.to_datetime(df_data.time) 

類似的東西會取代大部分代碼,沒有緩慢的循環。

+0

你可以嘗試讓請求我在Oanda API上做過?我已經發了封郵件給他們,但他們沒有回答我 –

+0

發佈該請求本身,結果在你的問題。不是所有這些不相關的額外代碼。 –

0

此API調用我知道肯定,你應該使用:

stream = False 

也可以考慮使用可訪問REST的API的API包裝的一個。這些將你的代碼減少到幾行。 的https://github.com/hootnot/oanda-api-v20允許您下載超過5000條記錄也。

對於V1(使用壽命到期的2017年12月?)

https://github.com/oanda/oandapy

或V2:

https://github.com/oanda/v20-python

https://github.com/hootnot/oanda-api-v20

https://github.com/oanda/v20-python 
https://github.com/hootnot/oanda-api-v20