如何正确地将数据添加到多索引并重新采样

时间:2021-02-13 22:11:01

标签: python pandas multi-index pandas-resample

以下函数旨在通过 1 分钟、5 分钟、15 分钟、30 分钟、1 小时、4 小时这 6 个时间帧重新采样货币数据。

该函数的第一次使用是在应用程序启动时,从 main 调用 20 次(每个货币对一次)然后在每个时间范围内循环一次,每次成功执行重新采样数据并执行必要的操作计算。

第二次调用该函数是从 on_message 函数调用的,该函数是一个接收聚合分钟 ohlc 数据的 websocket。将此分钟数据添加到 dfMaster,然后调用该函数对数据进行重新采样。该函数一直运行到这一行 dfTemp = dfMinuteBars.resample(t).apply(ohlc_dict).dropna(how='any') 然后退出,返回到在没有错误消息的情况下监听 websocket 上的消息。

无论如何编辑 dfMaster 可以防止数据被重新采样

我尝试过的事情 不添加新记录并从 on_message 函数调用该函数 - 该函数按其应有的方式执行,但显然需要新数据。

将 cp 变量设置为静态值以确保启动时传递的变量与 on_message 传递的变量之间没有区别 - 函数在重新采样时退出。

在调用函数之前添加新数据后对 dfMaster 进行排序 - 函数在重新采样时退出。

运行 dfMinuteBars['t'] = pd.to_datetime(dfMinuteBars['t']) 以确保在重新采样之前所有值都采用日期时间格式。 - 函数在重新采样时退出。

在添加新数据后重新索引 dfMaster - 函数在重新采样时退出。这是代码,提前感谢您的帮助。

for i in currencyPairs:
    dfCurrTemp = pd.read_csv(f'cache/{i[0].replace("/", "")}.csv')
    dfMaster = dfMaster.append(dfCurrTemp)
dfMaster['t'] = pd.to_datetime(dfMaster['t'])
dfMaster.set_index(['p', 't'], inplace=True)


def buildIndicators(cp):
    global dfIndVals
    global dfMaster
    dfMinuteBars = dfMaster.loc[cp]
    print(f'This is minutes bars for {cp}\n', dfMinuteBars)
    for t in timeframes:
        print(f'Resampled Data for {cp}-{t}\n')
        ohlc_dict = {'o': 'first', 'h': 'max', 'l': 'min', 'c': 'last'}
        dfTemp = dfMinuteBars.resample(t).apply(ohlc_dict).dropna(how='any')

        dfTemp = dfMinuteBars.resample(t).apply(ohlc_dict).dropna(how='any')
        dfTemp['upBB'], dfTemp['midBB'], dfTemp['lowBB'] = talib.BBANDS(dfTemp['c'], timeperiod=10, nbdevup=2,
                                                                        nbdevdn=2)
        dfTemp['sRSI'] = talib.RSI(dfTemp['c'], timeperiod=14)
        dfIndVals.loc[(cp, t), :] = [dfTemp['upBB'][-1], dfTemp['midBB'][-1], dfTemp['lowBB'][-1], dfTemp['sRSI'][-1]]

    print(dfIndVals)

    return 'indicators rebuilt'

for i in currencyPairs:
    print(buildIndicators(i[0]), i[0])



def on_message(ws, message):
    global dfMaster
    print(message)
    message = json.loads(message)

    if message[0]["ev"] == "CA":
        dfMaster.loc[(message[0]["pair"], datetime.utcfromtimestamp(message[0]["e"] / 1000).strftime("%Y-%m-%d %H:%M:%S")), :] = message[0]["o"], message[0]["h"], message[0]["l"], message[0]["c"], message[0]["v"]
        print('This is DF Master Updated and resorted- \n', dfMaster)
        print(buildIndicators(message[0]["pair"]))

0 个答案:

没有答案