下载数据并附加到不同的数据框

Downloading data and appending to different dataframe

我正在尝试使用 Oanda API 从 Oanda 下载货币对数据 我能够创建一个代码来从 Oanda

下载一种货币

我有 2 个问题

首先,根据我对基本 python 的理解,我必须首先创建一个货币对列表,然后遍历列表中的每个货币对以下载该货币对的数据,然后附加它每对的每个数据帧。

# Input for downloading data using Oanda API
d1 = '2017-05-18'
d2 = str(datetime.today().strftime('%Y-%m-%d'))
list = ['USD_JPY','EUR_USD']
df = pd.DataFrame({'Pairs': list})


gbl = globals()
for i in list:
    gbl['df_'+i] = df[df.Pairs==i]


# Downloading Data

for pair in list:

    data = oanda.get_history(instrument=list, start=d1, end=d2, granularity='D')
    df_EUR_USD= df_EUR_USD.append(pd.DataFrame(data['candles']))

我能够为列表中的每一对创建数据库,但我无法下载数据,然后将这些下载的数据附加到每个单独的数据帧。

第二个问题,是关于pandas中的一般处理。这是处理所有这些数据的最佳方式吗?我的想法是下载这些数据并将它们附加到单个数据帧,然后 运行 循环遍历这些数据帧列表以执行一些数学函数,最后 运行 再次循环遍历数据帧列表以提取计算出的数据并将它们全部附加到一个新的数据框中。 这是最好的方法吗?或者有没有更好的方法来处理这种情况。

我认为你需要:

d1 = '2017-05-18'
#strftime return string, so cast is not necessary
d2 = pd.datetime.today().strftime('%Y-%m-%d')
L = ['USD_JPY','EUR_USD']

dfs = []
for pair in L:
    #return in loop DataFrame (not tested, because no access to oanda)
    data = oanda.get_history(instrument=pair, start=d1, end=d2, granularity='D')
    #append column to list
    dfs.append(data['candles'])

#create new DataFrame with columns by L
df = pd.concat(dfs, axis=1, keys=L)

如果需要输出为dict:

dfs = {}
for pair in L:
    data = oanda.get_history(instrument=pair, start=d1, end=d2, granularity='D')
    #add data to dict
    dfs[pair] = data['candles']

print (dfs['USD_JPY'])