簡體   English   中英

從熊貓數據幀(股票)計算數據的更有效方法

[英]More efficient way of calculating data from pandas dataframe (stock)

我想知道是否有更有效/更清潔的方法來進行以下操作。 假設我有一個數據框,其中包含2列,即百分比(基於先前價格)和操作,播放/購買(1)或不播放/出售(-1)。 它基本上是關於股票的。

為簡單起見,請考慮示例df:

Percent    Action
1.25       1
1.20       1
0.50       -1
0.75       1

我想產生以下內容。 我只在乎最終金額,我只顯示此表以供參考。 假設我們以$ 100開始,並且處於未玩狀態。 因此,我們應該得到以下金額:

Playing    Percent    Action    Money
No         1.25       1         $100
Yes        1.20       1         $120
Yes        0.50       -1        $60
No         0.75       1         $60
Yes        ...        ...       ...

由於我們還沒有參加比賽,因此第一排的金額沒有變化。 由於動作是1,我們將播放下一個。 百分比上升了20%,因此我們得到了120美元。 下一個動作仍然是1,所以我們仍然會在下一個動作中。 百分比下降到50%,因此我們最終得到了60美元。 下一個動作是-1,因此我們將不玩。 百分比下降到75%,但是由於我們不玩游戲,我們的錢保持不變。 等等。

目前,我有下面的代碼。 它工作正常,但只是想知道是否有使用numpy / pandas函數的更有效方法。 我的基本上是遍歷每一行並計算值。

playing = False
money = 10000

for index, row in df.iterrows():
   ## UPDATE MONEY IF PLAYING
   if index > 0 and playing == True:
      money = float(format(money*row['Percent'],'.2f'))

   ## BUY/SELL
   if row['Action'] == 1:
      if playing == False:
         playing = True         ## Buy, playing after this
      elif row['Action'] == -1:
         if playing == True:
            playing = False   ## Sell, not playing after this

您可以嘗試以下方法:

# decide whether to play based on action
df['Playing'] = df.Action.shift().eq(1)

# replace Percent for not playing row with 1 and then calculate the cumulative product
df['Money'] = '$' + df.Percent.where(df.Playing, 1).cumprod().mul(100).astype(str)

df
#Percent  Action  Playing    Money
#0  1.25       1    False   $100.0
#1  1.20       1     True   $120.0
#2  0.50      -1     True    $60.0
#3  0.75       1    False    $60.0

暫無
暫無

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

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