excel - 计算没有辅助列/表的平均投资价格

标签 excel vba user-defined-functions stock fifo

这篇文章真的很值得一读。此主题的另一个更好的版本是可用的 here .
如果您查看下表,我会尝试在不添加辅助列的情况下查找每笔交易的平均价格。当边为 时,平均价格是正确的购买 但在 上显示不正确的平均价格卖我正在为“平均价格”列寻找公式、数组公式或 UDF 的一侧。


日期

数量
价格
值(value)
保持
平均价格


1-7月

225
10000
2250000
225
10000

7月2日

75
10200
765000
300
10050

7月3日

-150
9950
-1492500
150
10150


我的公式 值(value) =E3*D3 , 对于 控股=SUM($D$3:D3)对于 平均价格 =SUMPRODUCT($D$3:D3,$E$3:E3)/SUM($D$3:$D3)我向下拖动。除了最后一个值 之外,一切似乎都是正确的10150 .理想情况下应该有 10,100 根据下面给出的 FIFO 逻辑。
一阶:数量 = 225 |价格 = 卢比。 10,000.00
二阶:数量 = 75 |价格 = 卢比。 10,200.00
要计算平均价格,首先要计算值(value)(数量 x 价格)。因此:
第一次交易:卢比。 22,50,000.00
第二笔交易:卢比。 7,65,000.00
总量 = 300
前两个订单的总值(value):卢比。 30,15,000.00
用总值除以总量:
卢比。 30,15,000.00 ÷ 300 = 10,050.00 卢比(使用 =sumproduct 公式)

7 月 3 日,我们下了 150 个卖单(共 300 个)。价格:卢比。 9,950.00
现在这里将应用 FIFO(先进先出)方法。该方法将检查第一笔交易(在买方)。在这种情况下,它是 225。150 卖出的股票将从 225 中扣除(第一次持有)。第一次持有的余额是 225,现在是 225 - 150 = 75
先进先出后,表格在扣除卖出数量后变成这样。请参阅第一个数量从 225 更改为 75,因为已售出 150 个库存。


日期

数量
价格
值(value)
保持
平均价格


1-7月

75
10000
750000
75
10000

7月2日

75
10200
765000
150
10100


请注意:如果卖出数量超过225,那么它会转移到下一笔交易以扣除剩余数量。
现在要获得解决方案,需要额外的辅助列或辅助表,我希望消除并找到公式或数组公式或 UDF 来计算平均价格。我请求 excel 专家帮助我解决这个问题。

下面给出了我正在尝试的另一个示例,其中投资价格显示不正确:


日期

数量
价格
值(value)
保持
平均价格


1-7月

5
10
50
5
10

7月2日

-3
17
-51
2
-0.5

7月3日

17
3
51
19
2.63

7月4日

-15
7.8
-117
4
-16.75

编辑
从@Tom Sharpe 获得解决方案后完成
为了得到平均价格,我将两个变量 avgRate 和 sumRate 声明为 double 并修改了 For Each代码一点。请告知是否有有效的方法来做到这一点。感谢这是否可以转换为 UDF,这样我就不必一次又一次地运行代码。非常感谢您提供的精彩解决方案。

For Each bs In queue
    Debug.Print ("qty=" & bs.qty)
    Debug.Print ("rate=" & bs.rate)
    avgRate = avgRate + (bs.qty * bs.rate)
    sumRate = sumRate + bs.qty
    Debug.Print avgRate / sumRate
Next

最佳答案

好的,这里是 VBA 实现的测试版本。
算法:

If 'buy' transaction, just add to the queue.

If 'sell' transaction (negative quantity)

  Repeat 

    Take as much as possible from earliest transaction

    If more is required, look at next transaction

  until sell amount reduced to zero.

该程序使用类 BuySell,因此您需要创建一个类模块,将其重命名为 BuySell 并包含以下行
Public rate As Double
Public qty As Double
以下内容进入普通模块。
Option Explicit


    Sub FifoTrading()
    
        ' Create the queue
        
        Dim queue As Object
        Set queue = CreateObject("System.Collections.Queue") 'Create the Queue
        
        ' Declare some variables
        
        Dim bs As Object
        
        Dim qty As Double
        Dim rate As Double
        Dim qtySold As Double
        Dim qtyBought As Double
        Dim qtyRemaining As Double
        Dim rateBought As Double
        Dim i As Long
        
        For i = 2 To 5
        Debug.Print (Cells(i, 3).Value())
        Debug.Print (Cells(i, 4).Value())
        
            rate = Cells(i, 4).Value()
            qty = Cells(i, 3).Value()
            
            If qty > 0 Then
            
                'Buy
                
                Set bs = New BuySell
                
                bs.rate = rate
                bs.qty = qty
                
                queue.Enqueue bs
            
                
            Else
            
                'Sell
            
                qtyRemaining = -qty
                
                'Work through the 'buy' transactions in the queue starting at the oldest.
                
                While qtyRemaining > 0
                
                    If qtyRemaining < queue.peek().qty Then
                    
                    'More than enough stocks in this 'buy' to cover the sale so just work out what's left
                    
                        queue.peek().qty = queue.peek().qty - qtyRemaining
                        qtyRemaining = 0
                        
                        
                    ElseIf qtyRemaining = queue.peek().qty Then
                    
                    'Exactly enough stocks in this 'buy' to cover the sale so remove from queue
                    
                        Set bs = queue.dequeue()
                        qtyRemaining = 0
                        
                    Else
                    
                    'Not enough stocks in this 'buy' to cover the sale so remove from queue and reduce amount of sale remaining
                    
                        Set bs = queue.dequeue()
                        qtyRemaining = qtyRemaining - bs.qty
                        
                    End If
                    
                Wend
                
            End If
            
        Next i
        

        
        For Each bs In queue
            Debug.Print ("qty=" & bs.qty)
            Debug.Print ("rate=" & bs.rate)
        Next

        avRate = 0
        totQty = 0
    
        For Each bs In queue
            avRate = avRate + bs.qty * bs.rate
            totQty = totQty + bs.qty
        Next
    
        avRate = avRate / totQty
    
        Debug.Print ("average=" & avRate)
    
    
    End Sub
对于第一个表,输出是
enter image description here
所以平均利率是10100。
对于第二个表,输出是
enter image description here
所以平均利率是3。
编辑
这是 UDF 版本,称为
=avRate(qtyRange,rateRange)
Function avgRate(qtyRange As Range, rateRange As Range)


    ' Create the queue
    
    Dim queue As Object
    Set queue = CreateObject("System.Collections.Queue") 'Create the Queue
    
    ' Declare some variables
    
    Dim bs As Object
    
    Dim qty As Double
    Dim rate As Double
    Dim qtySold As Double
    Dim qtyBought As Double
    Dim qtyRemaining As Double
    Dim rateBought As Double
    Dim i As Long
    Dim sumRate As Double, totQty As Double
    
    For i = 1 To qtyRange.Cells().Count
    

    
        qty = qtyRange.Cells(i).Value()
        rate = rateRange.Cells(i).Value()
        
        If qty > 0 Then
        
            'Buy
            
            Set bs = New BuySell
            
            bs.rate = rate
            bs.qty = qty
            
            queue.Enqueue bs
        
            
        Else
        
            'Sell
        
            qtyRemaining = -qty
            
            'Work through the 'buy' transactions in the queue starting at the oldest.
            
            While qtyRemaining > 0
            
                If qtyRemaining < queue.peek().qty Then
                
                'More than enough stocks in this 'buy' to cover the sale so just work out what's left
                
                    queue.peek().qty = queue.peek().qty - qtyRemaining
                    qtyRemaining = 0
                    
                    
                ElseIf qtyRemaining = queue.peek().qty Then
                
                'Exactly enough stocks in this 'buy' to cover the sale so remove from queue
                
                    Set bs = queue.dequeue()
                    qtyRemaining = 0
                    
                Else
                
                'Not enough stocks in this 'buy' to cover the sale so remove from queue and reduce amount of sale remaining
                
                    Set bs = queue.dequeue()
                    qtyRemaining = qtyRemaining - bs.qty
                    
                End If
                
            Wend
            
        End If
        
    Next i

    'Calculate average rate over remaining stocks

    sumRate = 0
    totQty = 0
    
    For Each bs In queue
        sumRate = sumRate + bs.qty * bs.rate
        totQty = totQty + bs.qty
    Next
    
    avgRate = sumRate / totQty
    

    

End Function

关于excel - 计算没有辅助列/表的平均投资价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68243088/

相关文章:

使用 Apache POI 创建 .xlsx 文件时出现 java.lang.NoClassDefFoundError

python - Spark Dataframe 在转换后选择列

c# - 通过 Office 加载项更改键盘快捷方式?

VBA : Exit While in If

vba - WorksheetFunction.CountA 没有返回正确的值

vba - 字符串格式丢失

sql-server-2005 - SQL CLR 聚合函数错误处理

python - 在 pyspark 中应用用户定义聚合函数的替代方法

python - 将 Excel 文件转换为 JSON 并排除列

excel - 如何通过将两个工作表与类似 "in"的查询进行比较来创建新工作表?