java program to calculate XIRR without using excel or any other library - xirr

My application have to calculate XIRR, but I cannot use excel, because it runs on Linux, can any one share the logic or java code to calculate XIRR without using excel.

as stated in the post : xirr-calculation in c#
According to XIRR function openoffice documentation (formula is same as in excel) you need to solve for XIRR variable in the following f(xirr) equation:
xirr equation
I just traduce the C# code in Java and it work well without any sup libraries. Even for date difference. But in production code, you will use something like apache common.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class XirrDate {
public static final double tol = 0.001;
public static double dateDiff(Date d1, Date d2){
long day = 24*60*60*1000;
return (d1.getTime() - d2.getTime())/day;
}
public static double f_xirr(double p, Date dt, Date dt0, double x) {
return p * Math.pow((1.0 + x), (dateDiff(dt0,dt) / 365.0));
}
public static double df_xirr(double p, Date dt, Date dt0, double x) {
return (1.0 / 365.0) * dateDiff(dt0,dt) * p * Math.pow((x + 1.0), ((dateDiff(dt0,dt) / 365.0) - 1.0));
}
public static double total_f_xirr(double[] payments, Date[] days, double x) {
double resf = 0.0;
for (int i = 0; i < payments.length; i++) {
resf = resf + f_xirr(payments[i], days[i], days[0], x);
}
return resf;
}
public static double total_df_xirr(double[] payments, Date[] days, double x) {
double resf = 0.0;
for (int i = 0; i < payments.length; i++) {
resf = resf + df_xirr(payments[i], days[i], days[0], x);
}
return resf;
}
public static double Newtons_method(double guess, double[] payments, Date[] days) {
double x0 = guess;
double x1 = 0.0;
double err = 1e+100;
while (err > tol) {
x1 = x0 - total_f_xirr(payments, days, x0) / total_df_xirr(payments, days, x0);
err = Math.abs(x1 - x0);
x0 = x1;
}
return x0;
}
private static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
public static Date strToDate(String str){
try {
return sdf.parse(str);
} catch (ParseException ex) {
return null;
}
}
public static void main(String... args) {
double[] payments = {-1151250,232912,233123,233336,233551,233768}; // payments
Date[] days = {strToDate("11/11/2015"),strToDate("25/11/2015"),strToDate("25/12/2015"),strToDate("25/01/2016"),strToDate("25/02/2016"),strToDate("25/03/2016")}; // days of payment (as day of year)
double xirr = Newtons_method(0.1, payments, days);
System.out.println("XIRR value is " + xirr);
}}

You can use org.decampo library for java implementation.
Note: The code which has been provided by #Doukya is showing wrong answer if you cross check with excel sheet calculated value.

Related

Fibonacci sequence, public static void xxx

I'm just a very beginner and need for help with Fibonacci sequence. So the problem is that I need to ask a number from the answerer and secondly print the Fibonacci number that fits with the answerer's number? Is the method that I need to use "public static void xxx" loop?
I hope someone understands my bad English and can help me with my problem.
I hope you need it in java:
import java.io.*;
public class Fibonacci{
// your method public static void xxx
public static void fib() throws IOException
{
// take input from user
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
// compute nth fibonacci: your loop
int f1 = 0, f2 = 1;
if(n == 0)
System.out.println(f1);
for(int i=2; i<n; i++)
{
int fi = f1 + f2;
f1 = f2;
f2 = fi;
}
// print your answer
System.out.println(f2);
}
public static void main(Strings args[])
{
// call fib method
fib();
}
}

Linear Regression Functions in Cypher

How can I find linear regression R-squared coefficient in cypher?
I want equivalent linear regression functions in Cypher as defined in Oracle Database:
REGR_R2(column_y, column_x)
You may write your own Java procedures in Neo4j and call them from Cypher.
For regression function we can use apache commons SimpleRegression class.
The following code will create procedure named regr and it will return basic regression values for given X and Y properties.
You may call this procedure from Cypher as: regr('MY_LABEL', 'Y', 'X')
public class Regression {
#Context public GraphDatabaseService db;
// Result class
public static class Output {
public double r2;
public double avg_x;
public double avg_y;
public double slope;
public Output(double r2, double avg_x, double avg_y, double slope){
this.r2 = r2;
this.avg_x = avg_x;
this.avg_y = avg_y;
this.slope = slope;
}
}
#Procedure("regr")
public Stream<Output> regr(#Name("label") String label,
#Name("property_y") String y, #Name("property_x") String x ) {
SimpleRegression regr = new SimpleRegression(false);
double regr_avgx = 0;
double regr_avgy = 0;
int count = 0;
try (ResourceIterator it = db.findNodes(Label.label(label))) {
while (it.hasNext()) {
Node node = (Node)it.next();
if(node.hasProperty(x) && node.hasProperty(y))
{
Object prop_x = node.getProperty(x);
Object prop_y = node.getProperty(y);
regr_avgx += (double) ((Long)prop_x);
regr_avgy += (double) ((Long)prop_y);
regr.addData((double) ((Long)prop_x), (double) ((Long)prop_y));
count++;
}
}
}
regr_avgx /= count;
regr_avgy /= count;
return Stream.of(new Output(regr.getRSquare(), regr_avgx, regr_avgy, regr.getSlope()));
}
}

Printing Calendar Sideways with the use of Calendar API

Hi guys So i have this problem.. i wanted to print a calendar, utilizing the Calendar API.
condition:
user inputs a Year, anInteger between 1000 - 9999.
then it will output the calendar of that year and 2 more succeeding years.
so if i input 2012 it will output the Calendar of 2012 , 2013 and 2014.
here is the catch it must be SIDEWAYS!
package lessons;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class lesson3 {
static String[] days = {"SUN","MON","TUE","WED","THU","FRI","SAT"};
static int counter = 0;
public static void main(String[] args) {
GregorianCalendar gcal = new GregorianCalendar();
Scanner scanner = new Scanner(System.in);
System.out.print("Year: ");
int input = scanner.nextInt(); //month input
//System.out.print("YEAR (): ");
//int input2 = scanner.nextInt();
scanner.close();
int year = input;
gcal.set(Calendar.YEAR,input);
for(int monthCount = 0;monthCount<12;monthCount++){
gcal.set(Calendar.MONTH,monthCount); // month counter 0 - 11 producing jan to dec.
monthCheck(monthCount); // converting months to readable names
int x = gcal.get(Calendar.DAY_OF_WEEK);
int max = gcal.getActualMaximum(Calendar.DAY_OF_MONTH);
for(int i = 0;i<days.length;i++){
System.out.printf("%8s",days[i]);
}
System.out.println("");
for(int i = 0; i < x-1;i++){
System.out.printf("%8s","");
counter++;
if(counter%7==0){
System.out.println("");
}
}
for(int i = 1;i<=max;i++){
System.out.printf("%8s",i);
counter++;
if(counter%7==0){
System.out.println("");
}
}
System.out.println("");
//System.out.println(x);
}
}
static void monthCheck(int monthCount){
ArrayList monthsList = new ArrayList<String>();
String[] months = new DateFormatSymbols().getMonths();
for (int i = 0; i < months.length-1; i++) {
String monthArr = months[i];
monthsList.add(months[i]);
}
System.out.println(months[monthCount]);
}
}
This is what i can do with the code Above, click here!
this is what i am aiming for now. CLICK HERE!

Using scanner to read phrases

Hey StackOverflow Community,
So, I have this line of information from a txt file that I need to parse.
Here is an example lines:
-> date & time AC Power Insolation Temperature Wind Speed
-> mm/dd/yyyy hh:mm.ss kw W/m^2 deg F mph
Using a scanner.nextLine() gives me a String with a whole line in it, and then I pass this off into StringTokenizer, which then separates them into individual Strings using whitespace as a separator.
so for the first line it would break up into:
date
&
time
AC
Power
Insolation
etc...
I need things like "date & time" together, and "AC Power" together. Is there anyway I can specify this using a method already defined in StringTokenizer or Scanner? Or would I have to develop my own algorithm to do this?
Would you guys suggest I use some other form of parsing lines instead of Scanner? Or, is Scanner sufficient enough for my needs?
ejay
oh, this one was tricky, maybe you could build up some Trie structure with your tokens, i was bored and wrote a little class which solves your problem. Warning: it's a bit hacky, but was fun to implement.
The Trie class:
class Trie extends HashMap<String, Trie> {
private static final long serialVersionUID = 1L;
boolean end = false;
public void addToken(String strings) {
addToken(strings.split("\\s+"), 0);
}
private void addToken(String[] strings, int begin) {
if (begin == strings.length) {
end = true;
return;
}
String key = strings[begin];
Trie t = get(key);
if (t == null) {
t = new Trie();
put(key, t);
}
t.addToken(strings, begin + 1);
}
public List<String> tokenize(String data) {
String[] split = data.split("\\s+");
List<String> tokens = new ArrayList<String>();
int pos = 0;
while (pos < split.length) {
int tokenLength = getToken(split, pos, 0);
tokens.add(glue(split, pos, tokenLength));
pos += tokenLength;
}
return tokens;
}
public String glue(String[] parts, int pos, int length) {
StringBuilder sb = new StringBuilder();
sb.append(parts[pos]);
for (int i = pos + 1; i < pos + length; i++) {
sb.append(" ");
sb.append(parts[i]);
}
return sb.toString();
}
private int getToken(String[] tokens, int begin, int length) {
if (end) {
return length;
}
if (begin == tokens.length) {
return 1;
}
String key = tokens[begin];
Trie t = get(key);
if (t != null) {
return t.getToken(tokens, begin + 1, length + 1);
}
return 1;
}
}
and how to use it:
Trie t = new Trie();
t.addToken("AC Power");
t.addToken("date & time");
t.addToken("date & foo");
t.addToken("Speed & fun");
String data = "date & time AC Power Insolation Temperature Wind Speed";
List<String> tokens = t.tokenize(data);
for (String s : tokens) {
System.out.println(s);
}

Print Canvas from Processing

I am trying to make something along the lines of this: http://instaprint.me/, however I don't have a dedicated Linux machine, ink-less paper and WiFi. I do, on the other hand, have a desktop connected to the internet and a color photo-printer.
So what I had in mind was this -
Set up an Instagram API App that gets all the information of the most recent photo
A PHP script and a server that can produce a static URL for the most recent photo with a header("Content-Type: image/jpeg"), so that every time I take a new photo, the contents of the image on that static page changes to be the most recent photo.
Other pages, like the one mentioned above, that change to reflect the new location and caption of each photo I take, hosted on a static URL.
Some basic knowledge of Processing.
So here's how for I've got so far - I can download the most recent photo ID, and if it has changed since the last time it checked (15 seconds ago), then it proceeds to download the most recent image, caption and location.
I can then arrange these on the canvas to look like an old-fashioned polaroid. Now the only thing I have to do is print the canvas, at 150dpi, on a piece of 6x4in photo paper.
Anyone got any idea how I could do this?
Focusing on the part about bringing up large images in Processing, I did a Google search and came up with this thread. Quoting their problem and results:
The goal is to print a 180 pdi image with a shape depending on the
original canvas. So can be diffrent but it will end up being a
1500x1000mm picture approximately. So a big image. I'm not trying to
display it just to dump it into a file.
Then I setup a 64bits JVM. The latest one from Oracle website. Then I
created different size of picture and push the memory up to 1024MB. 5000x7500 test OK and 6000x9000 test OK
I tried to setup the memory up to 1500MB, but the JVM was not able to start.
So I tried 1200MB 8000x12000 test OK
So it doesn't do the image-printing part but it brings up key information on getting large images in memory via a Java Virtual Machine (JVM).
Lastly, this thread describes a TileSaver class for viewing/printing a large number of pixels using OpenGL. I pasted a large code block below. (This may be unrelated to your question but makes the answer more complete for other uses.)
import processing.opengl.*;
import toxi.geom.*;
Tiler tiler;
void setup() {
size(640,480,OPENGL);
tiler=new Tiler((PGraphics3D)g,NUM_TILES);
}
void draw() {
// see thread
}
/**
* Implements a screen tile exporter with support for FOV,
* clip planes and flexible file formats.
*
* Re-engineered from an older version by Marius Watz:
* http://workshop.evolutionzone.com/unlekkerlib/
*
* #author toxi <info at postspectacular dot com>
*/
class Tiler {
protected PGraphics3D gfx;
protected PImage buffer;
protected Vec2D[] tileOffsets;
protected double top;
protected double bottom;
protected double left;
protected double right;
protected Vec2D tileSize;
protected int numTiles;
protected int tileID;
protected float subTileID;
protected boolean isTiling;
protected String fileName;
protected String format;
protected double cameraFOV;
protected double cameraFar;
protected double cameraNear;
public Tiler(PGraphics3D g, int n) {
gfx = g;
numTiles = n;
}
public void chooseTile(int id) {
Vec2D o = tileOffsets[id];
gfx.frustum(o.x, o.x + tileSize.x, o.y, o.y + tileSize.y,
(float) cameraNear, (float) cameraFar);
}
public void initTiles(float fov, float near, float far) {
tileOffsets = new Vec2D[numTiles * numTiles];
double aspect = (double) gfx.width / gfx.height;
cameraFOV = fov;
cameraNear = near;
cameraFar = far;
top = Math.tan(cameraFOV * 0.5) * cameraNear;
bottom = -top;
left = aspect * bottom;
right = aspect * top;
int idx = 0;
tileSize = new Vec2D((float) (2 * right / numTiles), (float) (2 * top / numTiles));
double y = top - tileSize.y;
while (idx < tileOffsets.length) {
double x = left;
for (int xi = 0; xi < numTiles; xi++) {
tileOffsets[idx++] = new Vec2D((float) x, (float) y);
x += tileSize.x;
}
y -= tileSize.y;
}
}
public void post() {
if (isTiling) {
subTileID += 0.5;
if (subTileID > 1) {
int x = tileID % numTiles;
int y = tileID / numTiles;
gfx.loadPixels();
buffer.set(x * gfx.width, y * gfx.height, gfx);
if (tileID == tileOffsets.length - 1) {
buffer.save(fileName + "_" + buffer.width + "x"
+ buffer.height + "." + format);
buffer = null;
}
subTileID = 0;
isTiling = (++tileID < tileOffsets.length);
}
}
}
public void pre() {
if (isTiling) {
chooseTile(tileID);
}
}
public void save(String path, String baseName, String format) {
(new File(path)).mkdirs();
this.fileName = path + "/" + baseName;
this.format = format;
buffer = new PImage(gfx.width * numTiles, gfx.height * numTiles);
tileID = 0;
subTileID = 0;
isTiling = true;
}
public boolean isTiling() {
return isTiling;
}
}

Resources