跟踪DF中的清算股票头寸?

2024-10-01 11:23:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas数据框,其中包含一系列股票交易,我试图跟踪我在给定证券中卖出全部头寸的次数,以便计算我最近持有的头寸的正确平均买入金额以及我之前清算的头寸的净/损失

简化示例DF:

import pandas as pd


test = pd.DataFrame({'Date': [180201,190403,190609,190611,190912,191014,200101],
                     'Ticker': ['stockA', 'stockA', 'stockA', 'stockA', 'stockA', 'stockA', 'stockA'],
                     'Amount': [30, -10, -20, 20, -20, 10, 50],
                     'Total': [-30000, 35000, 35000, -40000, 23000, -60000, -30000],
                     'Transaction': ['Buy', 'Sell', 'Sell', 'Buy', 'Sell', 'Buy', 'Buy']})

     Date  Ticker  Amount  Total Transaction
0  180201  stockA      30 -30000          Buy
1  190403  stockA     -10  35000         Sell
2  190609  stockA     -20  35000         Sell
3  190611  stockA      20 -40000          Buy
4  190912  stockA     -20  23000         Sell
5  191014  stockA      10 -60000          Buy
6  200101  stockA      50 -30000          Buy

根据上述给定的DF,我想计算我当前持有的金额(以及总额/金额)和我的卖出头寸的净利润/亏损。我唯一想到的是添加一个新的列,通过逐行迭代来标记已售出的位置,如下所示:

counter = test['Amount'].add(test['Amount'].shift(-1))
for i in range(0, len(test)):
    if counter.loc[i] == 0:
        test.loc[i, 'Liquidated'] = 1
    else:
        test.loc[i, 'Liquidated'] = 0

这显然没有考虑到,如果某些东西被部分售出,并且需要跳过最后一行,以便下一次计数,因为前一行为零。我真的不知道如何才能做到这一点


Tags: testpandasdfdatebuy金额amountloc