Search code examples
pythonfunctionlambdastatisticsfinance

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.

I Have data in excel file like:

https://i.sstatic.net/yqMiV.png

headers: Script,date,Values

result : Scrip and XIRR

Used Python library:

#pip install pyxirr

from pyxirr import xirr

I am Calculating for single script code like the below and appending it to a 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).


Solution

  • You can group by your DataFrame by Script and apply xirr function to the each group:

    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