【问题标题】:First in First out capital gains/loss program using Python and Pandas, sanity check使用 Python 和 Pandas 的先进先出资本收益/损失程序,健全性检查
【发布时间】: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,这是不正确的。

标签: python pandas


【解决方案1】:

您在确定成本基础时的逻辑有问题。在您开始销售之前一切都很好。到那时,您从 15 股股票中获利。该利润基于您的平均成本(总成本基础/总份额)。您的错误是您确定新成本基础的下一步:

cost_basis -= row['Shares'] * (cost_basis/remaining_shares)

在这里,您使用旧成本基础计算新的平均成本价,但使用新的剩余份额。这给你一个不正确的平均成本。您必须将 rows['Shares'] 添加到除数中的 remaining_shares 以便您的平均成本保持不变:

cost_basis -= row['Shares'] * (cost_basis/(remaining_shares+row['Shares']))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 2021-12-24
    • 2021-10-26
    相关资源
    最近更新 更多