[英]How to calculate XIRR for each investment using python
I am trying to apply an XIRR Formula so that the percentage of each investment is calculated separately.我正在尝试应用 XIRR 公式,以便单独计算每项投资的百分比。
I Have data in excel file like:我在 excel 文件中有数据,例如:
https://i.stack.imgur.com/yqMiV.png https://i.stack.imgur.com/yqMiV.png
headers: Script,date,Values标头:脚本、日期、值
result: Scrip and XIRR结果:Scrip 和 XIRR
Used Python library:使用 Python 库:
#pip install pyxirr #pip 安装 pyxirr
from pyxirr import xirr从 pyxirr 导入 xirr
I am Calculating for single script code like the below and appending it to a dataframe:我正在计算如下所示的单个脚本代码并将其附加到 dataframe:
S1= df[["Date","Value"]][df["Script"]=="S1"] S1= S1[["Date","Value"]] S1_1= round(xirr(S1),2)*100 S1_1= pd.DataFrame({"Script": "S1","XIRR": S1_1},index=[1]) XIRR = XIRR.append(S1_1, ignore_index=True)
How can I apply a function/loop to calculate different scripts at one place and create a new dataframe of the results(image is attached).如何应用一个函数/循环在一个地方计算不同的脚本并创建一个新的 dataframe 结果(附图片)。
You can group by your DataFrame
by Script
and apply xirr
function to the each group:您可以通过
Script
按DataFrame
分组,并将xirr
function 应用于每个组:
from io import StringIO
import pandas as pd
from pyxirr import xirr
# some data for reproducibility:
csv_content = """
Script,Date,Value,Comment
S1,10/20/2019,-2000,Invested
S1,11/19/2019,-1800,Invested
S1,12/19/2019,-1600,Invested
S1,11/29/2021,9000,Current Value
S2,9/25/2019,-2000,Invested
S2,10/25/2019,-1800,Invested
S2,11/24/2019,-1600,Invested
S2,11/28/2021,9000,Current Value
"""
df = pd.read_csv(StringIO(csv_content), parse_dates=["Date"])
# the code you actually need
# [["Date", "Value"]] selects only columns required for xirr
result = df.groupby("Script")[["Date", "Value"]].apply(xirr)
print(result)
result will be结果将是
Script
S1 0.285053
S2 0.275016
dtype: float64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.