簡體   English   中英

為什么我的用戶定義 function 在執行 groupby.apply 時只返回第一組的返回?

[英]Why my user define function returns only first group's return when executing groupby.apply?

概括

使用 groupby 時,結果如下。 在此處輸入圖像描述

2.19 的值是用戶定義函數的第一組返回值。 也就是說,當為 mulCut[(mulCut['date'] == '2018-03-05') & (mulCut['moneyness'] == 'atm')] 實施 function 時,我得到 2.19。

解釋

我試圖通過 using.groupby.apply() 獲得不同組的不同回報。 在我的例子中,組被兩個變量“日期”和“金錢”分開,如下所示。 正如您在下面看到的 DataFrame 所示,“date”包含四個分類組“atm”、“itm”、“otm”和“tot”。 在此處輸入圖像描述

而我的用戶自定義function如下。 function 計算 9:05 至 14:50 之間交易 kospi 指數的回報。 簡而言之,交易策略是根據信號買入或賣出 kospi 指數。 '>= 敏感度' 是買入信號,'<= 1/敏感度' 是賣出信號。 由於我假設我可以為每個信號賣出或買入我所有的預算,所以當賣空已經發生時,賣出信號被忽略。 同樣,如果我已經買入 kospi 指數,買入信號將被忽略。 最后,在最后一刻(14:50),交易必須被清算。 也就是說,如果我在 14:49 的狀態是賣空,那么無論我在 14:50 收到什么信號,我都必須買入 kospi200。 同樣,如果我的狀態是在 14:49 買入,我必須賣出 kospi200。

def get_onedayRt(onedayDf, timeVrbl, cpVrbl, kospiVrbl, sensitivity):
    onedayDf['action'] = np.nan
    state = 0 # 0: can buy or short sell, 1: can only sell, -1: can only buy
    value = 0 # return of simulation
    targetDf = onedayDf.sort_values(timeVrbl)
    targetDf = targetDf.reset_index(drop = True)
    lastidx = len(onedayDf) - 1

    for idx, timeData in targetDf.iterrows():
        if timeData[cpVrbl] >= sensitivity:
            if state == -1:
                state += 1
                targetDf.loc[idx, 'action'] = 1 #buy
                value -= timeData[kospiVrbl]

            elif state == 0:
                state += 1
                targetDf.loc[idx, 'action'] = 1
                value -= timeData[kospiVrbl]

        elif timeData[cpVrbl] <= 1/sensitivity:
            if state == 1:
                state -= 1
                targetDf.loc[idx, 'action'] = -1 # sell
                value += timeData[kospiVrbl]

            elif state == 0:
                state -= 1
                targetDf.loc[idx, 'action'] = -1
                value += timeData[kospiVrbl]

        if lastidx - 1 == idx:
            break # last action needs to be determied as below

    if state == -1:
        targetDf.loc[lastidx, 'action'] = 1
        value -= targetDf.loc[lastidx, kospiVrbl]
    elif state == 1:
        targetDf.loc[lastidx, 'action'] = -1
        value += targetDf.loc[lastidx, kospiVrbl]

    return value

我發現我的 function 適用於每個特定組。 也就是說,下面的代碼有效。 我可以得到我想要的 2.97。

tmp = mulCut[(mulCut['date'] == '2018-03-05') & (mulCut['moneyness'] == 'tot')]
get_onedayRt(tmp, 'time', 'call/put', 'kospi200', 1)

因此,我想知道為什么我的用戶定義 function 在執行 groupby.apply 時只返回第一組的返回? 以及如何編輯我的代碼來解決問題?

感謝您閱讀我的長問題。

我終於解決了我的問題......我的 function 的第一行是我的問題的根源。 刪除該行后,我的代碼可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM