如何使用先进先出法计算股票交易的已实现盈亏?
我正在寻找一个 Python 插件,可以使用 FIFO 方法计算大量股票交易的已实现损益。
例如,假设我们有以下三笔 MSFT 交易:
+75 MSFT 25.10
+50 MSFT 25.12
-100 MSFT 25.22
在 25.22 卖出 100 股将完全抵消在 25.10 买入 75 股的净值,并部分抵消在 25.12 买入 50 股的净值,即已
实现损益 = 75 * (25.22 - 25.10) + 25 * (25.22 - 25.12) = 11.50 美元
未平仓头寸为:
+25 MSFT 25.12
I'm looking for a Python plugin that would calculate the realized P&L for a number of stock transactions using the FIFO method.
For example, assume we have the following three MSFT trades:
+75 MSFT 25.10
+50 MSFT 25.12
-100 MSFT 25.22
The sell of 100 shares at 25.22 would fully net against the buy of 75 at 25.10 and partially net against the buy of 50 at 25.12 i.e.
Realized P&L = 75 * (25.22 - 25.10) + 25 * (25.22 - 25.12) = $ 11.50
The outstanding position would be:
+25 MSFT 25.12
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
用 Python 自己编写这应该很容易。 “FIFO”是“先进先出队列”的缩写。购买被添加到队列的后面。从队列前面出售大量购买的商品(或其中的一部分)。
Python的collection.deque(双端队列)就是你所需要的对于机械师来说。
This should be easy to write yourself in Python. "FIFO" is short for "first in, first out queue". Buys are added to the back of the queue. Sells munch buys (or parts of them) off the front of the queue.
Python's collection.deque (double-ended queue) is what you need for the mechanics.
没有 Python,但是 R 项目 blotter --- 这是更大的 TradeAnalytics 项目 R- Forge 就是这么做的。
我最近需要 C++ 中的功能子集,并使用了 blotter 用于基准测试的代码/指导我移植到 C++。 (那是在工作中,所以没有公共 C++,抱歉。)
No Python, but the R project blotter --- which is part / core of the larger TradeAnalytics project on R-Forge does just that.
I recently needed a subset of the functionality in C++ and used the blotter code to benchmark / guide my port to C++. (That was at work, so no public C++ from that, sorry.)
有一个不太为人所知的 python 包 accfifo 在 FIFO 会计方面做得非常好。它是 pip 可安装的:
pip install accfifo
,可用于计算已实现损益和未平仓头寸。对于此队列,您可以计算未完成数量:
或者如果您想要购买剩余股票的价格信息:
可以使用来自
fifo.trace
的数据计算已实现损益:这对应于原作者的计算。
There is lesser known python package accfifo which does pretty good job when comes to FIFO accounting. It is pip installable:
pip install accfifo
and can be used to calculate Realized P&L and outstanding position.For this queue you can calculate outstanding quantity:
or if you want information at which prices were bought remaining stocks:
Realized P&L can be calculated using data from
fifo.trace
:which corresponds to calculations of original author.