PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 8, 2022

[FIXED] How to calculate XIRR for each investment using python

 October 08, 2022     finance, function, lambda, python, statistics     No comments   

Issue

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.stack.imgur.com/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


Answered By - Alexander Volkovsky
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing