【发布时间】:2023-01-11 11:35:18
【问题描述】:
我有这个先出资本收益/损失计划,但结果似乎很低,超过我在手动计算我的资本收益后提交的税款的一半(这也可能是错误的)。如果有任何财务人员可以对我的程序进行健全性检查,将不胜感激。我已经包含了一组虚拟数据。
#Create a dataframe with the transaction data
transactions = pd.DataFrame({
'Date': ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05'],
'Operation': ['Buy', 'Buy', 'Buy', 'Sell', 'Sell'],
'Stock Price': [100.0, 110.0, 120.0, 130.0, 140.0],
'Shares': [10.0, 20.0, 30.0, 15.0, 25.0]
})
# Create a new column to store the cost basis (purchase price)
transactions['Cost Basis'] = transactions['Stock Price'] * transactions['Shares']
# Create a new column to store the capital gain or loss
transactions['Capital Gain/Loss'] = 0.0
# Create a new column to store the remaining shares
transactions['Remaining Shares'] = 0.0
# Initialize variables to keep track of the remaining shares and cost basis
remaining_shares = 0.0
cost_basis = 0.0
# Iterate through the transactions in reverse chronological order
for i, row in transactions.sort_values('Date', ascending=False).iterrows():
if row['Operation'] == 'Buy':
# If the operation is "Buy", add the shares to the remaining shares
remaining_shares += row['Shares']
cost_basis += row['Cost Basis']
transactions.at[i, 'Remaining Shares'] = remaining_shares
elif row['Operation'] == 'Sell':
# If the operation is "Sell", calculate the capital gain or loss and
# update the remaining shares and cost basis
if remaining_shares > 0:
if remaining_shares >= row['Shares']:
capital_gain_loss = row['Shares'] * (row['Stock Price'] - cost_basis/remaining_shares)
remaining_shares -= row['Shares']
cost_basis -= row['Shares'] * (cost_basis/remaining_shares)
else:
capital_gain_loss = remaining_shares * (row['Stock Price'] - cost_basis/remaining_shares)
remaining_shares = 0
cost_basis = 0
transactions.at[i, 'Capital Gain/Loss'] = capital_gain_loss
transactions.at[i, 'Remaining Shares'] = remaining_shares
#group the capital gain or loss by year
transactions['Year'] = pd.to_datetime(transactions['Date']).dt.year
result = transactions.groupby('Year')['Capital Gain/Loss'].sum()
print(result)
【问题讨论】:
-
为什么要按时间倒序迭代?如果您这样做,您的第一行将在 remaining_shares = 0.0 时卖出。您确定必须按照交易执行的顺序处理交易吗?
-
我想我把它搞混了,ascending=False 是先入后出,所以最后一个事务首先处理。虽然 ascending=True 是先进先出,因为这产生了更有意义的数字,但仍然与我认为的不匹配。测试集显示使用先进后出方法的资本收益为 0,这是不正确的。