【发布时间】:2020-05-19 07:18:50
【问题描述】:
我正在尝试构建一个小型投资组合应用程序,并计算我的平均入门价格以及由此实现的收益。这是我到目前为止的工作,但很想知道是否有更优雅的方法来获得条件累积和而不创建额外的列。似乎需要很多步骤才能在 excel 中有效地使用 sumifs 语句。
输入数据框:
hist_pos = pd.DataFrame(data=[
[datetime(2020, 5, 1), 'PPT.AX', 30, 20.00, 15.00, 'Buy'],
[datetime(2020, 5, 2), 'RIO.AX', 25, 25.00, 15.00, 'Buy'],
[datetime(2018, 5, 3), 'BHP.AX', 100, 4.00, 15.00, 'Buy'],
[datetime(2019, 5, 3), 'BHP.AX', 50, 4.00, 15.00, 'Sell'],
[datetime(2019, 12, 3), 'PPT.AX', 80, 4.00, 15.00, 'Buy'],
[datetime(2020, 5, 3), 'RIO.AX', 100, 4.00, 15.00, 'Buy'],
[datetime(2020, 5, 5), 'PPT.AX', 50, 40.00, 15.00, 'Sell'],
[datetime(2020, 5, 10), 'PPT.AX', 15, 45.00, 15.00, 'Sell'],
[datetime(2020, 5, 18), 'PPT.AX', 30, 20.00, 15.00, 'Sell']],
columns=['Date', 'Ticker', 'Quantity', 'Price', 'Fees', 'Direction'])
代码库:
hist_pos.sort_values(['Ticker', 'Date'], inplace=True)
hist_pos.Quantity = pd.to_numeric(hist_pos.Quantity) #convert to number
# where direction is sale, make quantity negative
hist_pos['AdjQ'] = np.where(
hist_pos.Direction == 'Buy', 1, -1)*hist_pos.Quantity
#Sum quantity to get closing quantity for each ticker using the AdjQ column
hist_pos['CumQuan'] = hist_pos.groupby('Ticker')['AdjQ'].cumsum()
预期输出:
Date Ticker Quantity Price Fees Direction AdjQ CumQuan
2 2018-05-03 BHP.AX 100 4.0 15.0 Buy 100 100
3 2019-05-03 BHP.AX 50 4.0 15.0 Sell -50 50
4 2019-12-03 PPT.AX 80 4.0 15.0 Buy 80 80
0 2020-05-01 PPT.AX 30 20.0 15.0 Buy 30 110
6 2020-05-05 PPT.AX 50 40.0 15.0 Sell -50 60
7 2020-05-10 PPT.AX 15 45.0 15.0 Sell -15 45
8 2020-05-18 PPT.AX 30 20.0 15.0 Sell -30 15
1 2020-05-02 RIO.AX 25 25.0 15.0 Buy 25 25
5 2020-05-03 RIO.AX 100 4.0 15.0 Buy 100 125
上面的代码运行良好,并为 CumQuan 列生成了预期的输出。但是,我有更广泛的代码(在 Repl 中),我需要为各种列多次执行此过程。所以想知道是否有一种更简单的方法来处理数据以使用分组,累积和条件。
【问题讨论】:
-
我建议您提出一个问题并显示您对该特定问题的预期输出。现在有很多步骤没有明确的解释。
-
谢谢 - 已编辑使其更简单。干杯