zScore and p-value in Java (survival function) - java

What would be the java equivalent of the following code?
import scipy
from scipy.stats import zscore
zlist = [9967,11281,10752,10576,2366,11882,11798,]
z = zscore(zlist)
for e in z:
print e,scipy.stats.norm.sf(abs(e))

And the answer is:
private void run() {
double[] values = {9967,11281,10752,10576,2366,11882,11798};
double variance = StatUtils.populationVariance(values);
double sd = Math.sqrt(variance);
double mean = StatUtils.mean(values);
NormalDistribution nd = new NormalDistribution();
for ( double value: values ) {
double stdscore = (value-mean)/sd;
double sf = 1.0 - nd.cumulativeProbability(Math.abs(stdscore));
System.out.println("" + stdscore + " " + sf);
}
}
This is using The Apache Commons Mathematics Library
EDIT: Or, even better:
import java.util.function.BiConsumer;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.commons.math3.distribution.RealDistribution;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
public class ZScore {
public static void main(String[] args) {
ZScore program = new ZScore();
double[] values = {9967,11281,10752,10576,2366,11882,11798};
program.computeZScoreAndSurvivalFunctions(
new DescriptiveStatistics(values),
new NormalDistribution(),
(zscore, sf)->System.out.println(""+zscore+" "+sf)
);
}
private void computeZScoreAndSurvivalFunctions(
DescriptiveStatistics ds,
RealDistribution dist,
BiConsumer<Double, Double> consumer
) {
double variance = ds.getPopulationVariance();
double sd = Math.sqrt(variance);
double mean = ds.getMean();
for ( int index = 0; index < ds.getN(); ++index) {
double zscore = (ds.getElement(index)-mean)/sd;
double sf = 1.0 - dist.cumulativeProbability(Math.abs(zscore));
consumer.accept(zscore, sf);
}
}
}

Related

How to format double to look like an integer in my programme? The chess board rice legend

If I run my programme it gives me double numbers, but in the end those numbers aren't like integers anymore because there is a point in them. Can you tell me how to format it or handle this? Thanks
package writingtofile;
import java.io.*;
import java.math.BigInteger;
public class WritingToFile {
public static void main(String[] args) throws IOException {
int counter = 1;
FileWriter out = null;
try{
out = new FileWriter("out.txt");
for(double number : FibanocciNumbers())
{
out.write("Spot:");
out.write(counter + " ");
out.write(String.valueOf(number) + "\r\n");
counter++;
}
}catch(IOException e)
{
System.out.println("Error!");
}
finally
{
out.close();
}
}
public static double[] FibanocciNumbers()
{
double[] fibNumbers = new double[64];
fibNumbers[0] = 1;
fibNumbers[1] = 2;
double lastNumber;
for(int i = 2; i < 64; i++)
{
lastNumber = fibNumbers[i-1];
fibNumbers[i] = lastNumber * 2;
}
return fibNumbers;
Spot:1 1.0
Spot:2 2.0
Spot:3 4.0
Spot:4 8.0
Spot:5 16.0
Spot:6 32.0
Spot:7 64.0
Spot:8 128.0
Spot:9 256.0
Spot:10 512.0
Spot:11 1024.0
Spot:12 2048.0
Spot:13 4096.0
Spot:14 8192.0
Spot:15 16384.0
Spot:16 32768.0
Spot:17 65536.0
Spot:18 131072.0
Spot:19 262144.0
Spot:20 524288.0
Spot:21 1048576.0
Spot:22 2097152.0
Spot:23 4194304.0
Spot:24 8388608.0
Spot:25 1.6777216E7
Spot:26 3.3554432E7
Spot:27 6.7108864E7
Spot:28 1.34217728E8
Spot:29 2.68435456E8
Spot:30 5.36870912E8
Spot:31 1.073741824E9
Spot:32 2.147483648E9
Spot:33 4.294967296E9
Spot:34 8.589934592E9
Spot:35 1.7179869184E10
Spot:36 3.4359738368E10
Spot:37 6.8719476736E10
Spot:38 1.37438953472E11
Spot:39 2.74877906944E11
Spot:40 5.49755813888E11
Spot:41 1.099511627776E12
Spot:42 2.199023255552E12
Spot:43 4.398046511104E12
Spot:44 8.796093022208E12
Spot:45 1.7592186044416E13
Spot:46 3.5184372088832E13
Spot:47 7.0368744177664E13
Spot:48 1.40737488355328E14
Spot:49 2.81474976710656E14
Spot:50 5.62949953421312E14
Spot:51 1.125899906842624E15
Spot:52 2.251799813685248E15
Spot:53 4.503599627370496E15
Spot:54 9.007199254740992E15
Spot:55 1.8014398509481984E16
Spot:56 3.6028797018963968E16
Spot:57 7.2057594037927936E16
Spot:58 1.44115188075855872E17
Spot:59 2.8823037615171174E17
Spot:60 5.7646075230342349E17
Spot:61 1.15292150460684698E18
Spot:62 2.305843009213694E18
Spot:63 4.6116860184273879E18
Spot:64 9.223372036854776E18
So I don't wnat those numbers with points in it, because I think it changes the way you should understand this. How to get them away or handle them? Tanks
This is your code using BigInteger. Its what you want, no decimal!!
also, double is not an integer, its like float but with capability to to hold large fractional numbers. btw you have named it FibanocciNumbers but those are not fibonnaci numbers
import java.io.*;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) throws IOException
{
int counter = 1;
FileWriter out = null;
try{
out = new FileWriter("out.txt");
for(BigInteger number : FibanocciNumbers())
{
out.write("Spot:");
out.write(counter + " ");
out.write(String.valueOf(number) + "\r\n");
System.out.println(number);
counter++;
}
}catch(IOException e)
{
System.out.println("Error!");
}
finally
{
out.close();
}
}
public static BigInteger[] FibanocciNumbers()
{
BigInteger[] fibNumbers = new BigInteger[64];
fibNumbers[0] = new BigInteger("1");
fibNumbers[1] = new BigInteger("2");
BigInteger lastNumber;
for(int i = 2; i < 64; i++)
{
lastNumber = fibNumbers[i-1];
fibNumbers[i] = lastNumber.multiply( new BigInteger("2") );
}
return fibNumbers;
}
}
last line of Output:
Spot:64 9223372036854775808

Math calculation in Java

I am working on a simple program to calculate a mathematical equation. But there is a problem that I could not find. Any help would be greatly appreciated.
It seems a problem is with
alpha[j] = (double)(j-1)*2*Math.PI/(double)rotationNum;
NullPointerException is returned. There has to be some silly mistakes here.
import java.util.*;
import java.io.*;
//import Jama.Matrix;
class efun {
static double epso;
static double sigma;
static double alpha[];
static double charge;
static double axisR;
static double axisZ;
//static Random randGen;
static int numPoints = -1;
static int rotationNum;
public static void main (String[] args) {
try {
sigma = 300e-6*1e2;
epso = 8.854e-12;
/*Input arguments*/
numPoints = Integer.parseInt (args[0]);
FileReader fr = new FileReader(args[1]);
rotationNum = Integer.parseInt (args[2]);
BufferedReader br = new BufferedReader(fr);
double pointsR[] = new double[numPoints];
double pointsZ[] = new double[numPoints];
double chargeDensity[] = new double[numPoints];
double electricField = 0.0;
double ER = 0.0;
double EZ = 0.0;
double EY = 0.0;
for (int id = 0; id < numPoints; id++) {
// read file
while ( (line = br.readLine() )!= null) {
StringTokenizer stk = new StringTokenizer(line);
axisR = Double.parseDouble(stk.nextToken());
axisZ = Double.parseDouble(stk.nextToken());
charge = Double.parseDouble(stk.nextToken());
pointsR[id] = axisR;
pointsZ[id] = axisZ;
chargeDensity[id] = charge;
System.out.println("axisR: "+pointsR[id]+" and axisZ: "+ pointsZ[id]+"; its corresponding charge density is: "+ chargeDensity[id]);
double rotatedR[] = new double[numPoints];
double rotatedZ[] = new double[numPoints];
double rotatedY[] = new double[numPoints];
double sumSquarePoints[] = new double[numPoints];
for (int j = 1; j < rotationNum+1; j++) {
alpha[j] = (double)(j-1)*2*Math.PI/(double)rotationNum;
System.out.println("print alpha: "+alpha[j]);
rotatedR[id] = pointsR[id] - Math.cos(alpha[j])*pointsR[id];
rotatedZ[id] = pointsZ[id];
rotatedY[id] = pointsR[id] - Math.sin(alpha[j])*pointsR[id];
sumSquarePoints[id] = Math.sqrt(rotatedR[id]*rotatedR[id] + rotatedZ[id]*rotatedZ[id] + rotatedY[id]*rotatedY[id]);
ER += chargeDensity[id]*rotatedR[id]/(sumSquarePoints[id]*sumSquarePoints[id]*sumSquarePoints[id]);
EZ += chargeDensity[id]*rotatedZ[id]/(sumSquarePoints[id]*sumSquarePoints[id]*sumSquarePoints[id]);
EY += chargeDensity[id]*rotatedY[id]/(sumSquarePoints[id]*sumSquarePoints[id]*sumSquarePoints[id]);
System.out.println ("ER is: "+ ER);
System.out.println ("EZ is: "+ EZ);
System.out.println ("EY is: "+ EY);
}
}
}
electricField = sigma/(4*Math.PI*epso)*Math.sqrt(ER*ER + EZ*EZ + EY*EY);
System.out.println("electricField is: " + electricField);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
You never initialized alpha, you only declared it, so you can't access alpha[j]. Initialize it and make sure that its size is large enough for every j:
alpha = new double[MY_SIZE];
Also, make sure that you're passing in at least 3 arguments to main so that rotationNum is assigned correctly.
Your class variable alpha is declared, but not initialized, so Java gives it the default value of null. The variable was never initialized to any array.
static double alpha[];
However, it doesn't look like you're using any other intended value in the array except for the current value. Just declare it to be a local double (not an array), and use it as a normal variable.
double alpha = (double)(j-1)*2*Math.PI/(double)rotationNum;
And use alpha instead of alpha[j] a few lines down from there.
You've never initialized alpha[]. Just like pontsR, pointsZ, and chargeDensity, you need to point alpha at a new array of doubles before you can use it.
Add alpha = new double[rotationNum ]; after getting rotationNum

Missing Format Argument Exception

When compiling I get a "java.util.MissingFormatArgumentException: null (in java.util.Formater) I do not know why.
"Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier 's'"
Please Help.
import java.lang.*;
import java.util.Random;
import java.util.Scanner;
import static java.lang.System.out;
public class DartSimV1
{
static double[] SiXX(int Money)
{
double[] VarXX;
VarXX = new double[Money];
int IBS;
IBS = 0;
if (IBS < VarXX.length) {
do {
VarXX[IBS] = Math.random();
IBS++;
} while (IBS < VarXX.length);
}
return VarXX;
}
public static double[] SiYY(int Money)
{
double[] VarYY;
VarYY = new double[Money];
int IBS;
IBS = 0;
while (true) {
if (false) {
break;
}
if (!(IBS < VarYY.length)) {
break;
}
VarYY[IBS]=Math.random();
IBS++;
}
return VarYY;
}
public static double WhatPie(double[] IBS,double[] YYCoord)
{
double [] VarXX;
VarXX = IBS;
double [] VarYY;
VarYY = YYCoord;
double Totals;
Totals = 0;
double Contacts;
Contacts = 0;
int IBO;
IBO = 0;
if (IBO < VarXX.length) {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else Totals++;
IBO++;
if (IBO < VarXX.length) {
do {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else {
Totals++;
}
IBO++;
} while (IBO < VarXX.length);
}
}
double PIE;
PIE = 4 *
(Contacts
/
Totals);
return PIE;
}
public static void Answers(int Done, double New)
{
double PIE;
PIE = New;
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE);
}
public static void PieA(double[] New, int Done)
{
double[] PIE;
PIE = New;
int trials;
trials = Done;
double Totals;
Totals = 0.0;
int i;
i = 0;
if (i < PIE.length) {
double IBS;
IBS = PIE[i];
Totals += IBS;
i++;
if (i < PIE.length) {
do {
IBS = PIE[i];
Totals += IBS;
i++;
} while (i < PIE.length);
}
}
double PieA;
PieA = Totals/trials;
System.out.printf("AVG for π = %11.3f%s",PieA);
}
public static void main(String[] args)
{
Scanner show;
show = new Scanner(System.in);
System.out.print("# per trials?: ");
int dPt;
dPt = show.nextInt();
System.out.print("Trial #'s?: ");
int nTri;
nTri = show.nextInt();
double[] PieA;
PieA = new double[nTri];
int IBS=0;
while (IBS<nTri) {
double [] VarXX;
VarXX = SiXX(dPt);
double [] VarYY;
VarYY = SiYY(dPt);
double PIE;
PIE = WhatPie(VarXX,VarYY);
PieA[IBS]=PIE;
Answers(IBS,PIE);
IBS++;
}
PieA(PieA,nTri);
}
}
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE); has 2 parameters: one float %11.3f and one string %s. You've only given it one value to print PIE. It needs two - a float and a string.
Also: The exception gives you the full details of the problem - including the line number. You should include that in your question to give people the best chance of answering.

Simple neural network multiply training on untrained data gives big errors

i have made small multiplication neural network by using encog library with sigmoid activation function on the basic network.
My problem is i got big errors on untrained datas.
How can i enhance untrained data more good results.Less error prone.
First i tried:
train.getError() > 0.00001 to train.getError() > 0.0000001
decreasing error to less will make more sharp results.
But this did not helped.
Increasing hidden layer did not helped also: network.addLayer(new BasicLayer(new ActivationSigmoid(),false,128));
i tried to increase neuron count per layer but also not helped
How can i get more sharp results ?
Whats bias do ? When to use it ?
I've seen :
http://www.heatonresearch.com/wiki/Activation_Function
But i am only using sigmoid.When to use others or i need to change activation function?
Here is my code:
package org.encog.examples.neural.xor;
import org.encog.Encog;
import org.encog.engine.network.activation.ActivationSigmoid;
import org.encog.ml.data.MLData;
import org.encog.ml.data.MLDataPair;
import org.encog.ml.data.MLDataSet;
import org.encog.ml.data.basic.BasicMLDataSet;
import org.encog.neural.networks.BasicNetwork;
import org.encog.neural.networks.layers.BasicLayer;
import org.encog.neural.networks.training.propagation.resilient.ResilientPropagation;
import java.awt.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class MulHelloWorld {
/**
* The input necessary for MUL.
*/
public static double MUL_INPUT[][] = { { 0.0, 0.0 }, { 1.0, 0.0 },
{ 0.2, 0.4 }, { 0.3, 0.2 } , {0.12 , 0.11} , {0.7,0.2} , {0.32,0.42} , {0.9,0.3} , {0.5,0.2} , { 0.4 , 0.6 } , {0.9,0.1} };
/**
* The ideal data necessary for MUL.
*/
public static double MUL_IDEAL[][] = { { 0.0 }, { 0.0 }, { 0.08 }, { 0.06 } , {0.0132} , {0.14} , {0.1344} , {0.27} , {0.1} , {0.24} , {0.09} };
private static BasicNetwork network;
private static NumberFormat formatter = new DecimalFormat("###.#####");
public static final void retrain() {
network = new BasicNetwork();
network.addLayer(new BasicLayer(null,true,2));
network.addLayer(new BasicLayer(new ActivationSigmoid(),false,128));
network.addLayer(new BasicLayer(new ActivationSigmoid(),false,128));
network.addLayer(new BasicLayer(new ActivationSigmoid(),false,128));
network.addLayer(new BasicLayer(new ActivationSigmoid(),false,1));
network.getStructure().finalizeStructure();
network.reset();
// create training data
MLDataSet trainingSet = new BasicMLDataSet(MUL_INPUT, MUL_IDEAL);
// train the neural network
final ResilientPropagation train = new ResilientPropagation(network, trainingSet );
int epoch = 1;
do {
train.iteration();
System.out.println("Epoch #" + epoch + " Error:" + formatter.format(train.getError()));
epoch++;
} while(train.getError() > 0.00001);
train.finishTraining();
// test the neural network
System.out.println("Neural Network Results:");
for(MLDataPair pair: trainingSet ) {
final MLData output = network.compute(pair.getInput());
System.out.println(pair.getInput().getData(0) + "," + pair.getInput().getData(1)
+ ", actual=" + output.getData(0) + ",ideal=" + pair.getIdeal().getData(0));
}
}
/**
* The main method.
* #param args No arguments are used.
*/
public static void main(final String args[]) {
// create a neural network, without using a factory
retrain();
final double computedValue = compute(network, 0.01, 0.01);
final double diff = computedValue - 0.0001;
do {
if (diff < 0.001 && diff > -0.001) {
String f = formatter.format(computedValue);
System.out.println("0.0001:"+f);
System.out.println("0.0002:"+formatter.format(compute(network, 0.02, 0.01)));//0.0002
System.out.println("0.001:"+formatter.format(compute(network, 0.05, 0.02)));//0.001
Toolkit.getDefaultToolkit().beep();
try { Thread.sleep(7000); } catch (Exception epx) {}
retrain();
} else {
String f = formatter.format(computedValue);
System.out.println("0.0001:"+f);
System.out.println("0.0002:"+formatter.format(compute(network, 0.02, 0.01)));//0.0002
System.out.println("0.001:"+formatter.format(compute(network, 0.05, 0.02)));//0.001
System.exit(0);
}
} while (diff < 0.001 && diff > -0.001);
Encog.getInstance().shutdown();
}
public static final double compute(BasicNetwork network, double x, double y) {
final double value[] = new double[1];
network.compute( new double[] { x , y } , value );
return value[0];
}
}
Here is my last try seems a little more effective but not good yet:
package org.encog.examples.neural.xor;
import org.encog.Encog;
import org.encog.engine.network.activation.ActivationSigmoid;
import org.encog.ml.data.MLData;
import org.encog.ml.data.MLDataPair;
import org.encog.ml.data.MLDataSet;
import org.encog.ml.data.basic.BasicMLDataSet;
import org.encog.neural.networks.BasicNetwork;
import org.encog.neural.networks.layers.BasicLayer;
import org.encog.neural.networks.training.propagation.resilient.ResilientPropagation;
import java.awt.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
public class MulHelloWorld {
/**
* The input necessary for MUL.
*/
public static double MUL_INPUT[][] = {
{ 0.0, 0.0 }, { 1.0, 0.0 }, { 0.2, 0.4 }, { 0.3, 0.2 } ,
{0.12 , 0.11} , {0.7,0.2} , {0.32,0.42} , {0.9,0.3} ,
{0.5,0.2} , { 0.4 , 0.6 } , {0.9,0.1} , {0.1,0.1} ,
{0.34,0.42} , {0.3,0.3}
};
/**
* The ideal data necessary for MUL.
*/
public static double MUL_IDEAL[][] = {
{ 0.0 }, { 0.0 }, { 0.08 }, { 0.06 } ,
{0.0132} , {0.14} , {0.1344} , {0.27} ,
{0.1} , {0.24} , {0.09} , {0.01} ,
{0.1428} , {0.09} };
private static BasicNetwork network;
private static NumberFormat formatter = new DecimalFormat("###.##########");
private static final double acceptableDiff = 0.01;
public static final void retrain() {
network = new BasicNetwork();
network.addLayer(new BasicLayer(null,true,2));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,32));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,32));
network.addLayer(new BasicLayer(new ActivationSigmoid(),true,1));
network.getStructure().finalizeStructure();
network.reset();
ArrayList<Double> inputs = new ArrayList<Double>();
ArrayList<Double> inputs2 = new ArrayList<Double>();
ArrayList<Double> outputs = new ArrayList<Double>();
double j = 0;
int size = 64;
for (int i = 0; i < size; i++) {
final double random1 = Math.random();
final double random2 = Math.random();
inputs.add( random1 );
inputs2.add( random2 );
outputs.add( random1*random2 );
}
final Double x1[] = new Double[size];
final Double x2[] = new Double[size];
final Double x3[] = new Double[size];
final Double[] inputz1 = inputs.toArray(x1);
final Double[] inputz2 = inputs2.toArray(x2);
final Double[] outz = outputs.toArray(x3);
final double inputsAll[][] = new double[inputz1.length][2];
final double outputsAll[][] = new double[inputz1.length][1];
final int inputz1Size = inputz1.length;
for (int x = 0; x < inputz1Size ; x++) {
inputsAll[x][0] = inputz1[x];
inputsAll[x][1] = inputz2[x];
outputsAll[x][0] = outz[x];
}
// create training data
MLDataSet trainingSet = new BasicMLDataSet(inputsAll, outputsAll );
// train the neural network
final ResilientPropagation train = new ResilientPropagation(network, trainingSet );
int epoch = 1;
do {
train.iteration();
System.out.println("Epoch #" + epoch + " Error:" + formatter.format(train.getError()));
epoch++;
} while(train.getError() > acceptableDiff);
train.finishTraining();
// test the neural network
System.out.println("Neural Network Results:");
for(MLDataPair pair: trainingSet ) {
final MLData output = network.compute(pair.getInput());
System.out.println(pair.getInput().getData(0) + "," + pair.getInput().getData(1)
+ ", actual=" + output.getData(0) + ",ideal=" + pair.getIdeal().getData(0));
}
}
/**
* The main method.
* #param args No arguments are used.
*/
public static void main(final String args[]) {
// create a neural network, without using a factory
retrain();
double random3 = Math.random();
double random4 = Math.random();
double v2 = random3 * random4;
double computedValue = compute(network, random3, random4);
System.out.println(formatter.format(v2) + ":" + formatter.format(computedValue));
final double diff = computedValue - v2;
do {
if (diff < acceptableDiff || diff > -acceptableDiff ) {
String f = formatter.format(computedValue);
{
double random = Math.random();
double random1 = Math.random();
double v = random * random1;
System.out.println(formatter.format(v) + ":" + formatter.format(compute(network, random, random1)));
}
{
double random = Math.random();
double random1 = Math.random();
double v = random * random1;
System.out.println(formatter.format(v) + ":" + formatter.format(compute(network, random, random1)));
}
{
double random = Math.random();
double random1 = Math.random();
double v = random * random1;
System.out.println(formatter.format(v) + ":" + formatter.format(compute(network, random, random1)));
}
Toolkit.getDefaultToolkit().beep();
try { Thread.sleep(1000); } catch (Exception epx) {}
retrain();
} else {
String f = formatter.format(computedValue);
System.out.println("0.0001:"+f);
System.out.println("0.0002:"+formatter.format(compute(network, 0.02, 0.01)));//0.0002
System.out.println("0.001:"+formatter.format(compute(network, 0.05, 0.02)));//0.001
System.exit(0);
}
} while (diff < acceptableDiff || diff > -acceptableDiff);
Encog.getInstance().shutdown();
}
public static final double compute(BasicNetwork network, double x, double y) {
final double value[] = new double[1];
network.compute( new double[] { x , y } , value );
return value[0];
}
}
You might find that you are actually fitting the training set too closely and thus your net doesn't generalise well. A better strategy would be to have a third set, for validation. You could use this data to set your training error for an effective result, and then test the net on your untrained data.
I'm not familiar with this particular package but you might also want to look at other training methods. I've found scaled conjugate gradients to often be a bit better than basic back propagation.

Bollinger Bands Using Talib

I am trying to implement a simple BBands application using talib.
I do not have any expirience in Talib and technical Indicators.
Can someone have a look at say whether this is a good implementation of Bollinger Bands using Talib and give me advice how can it be improved. If anyone has expirience with Talib and Bollinger Bands it would be much appriciated to give me a hand. Here is the code.
import com.tictactec.ta.lib.Core;
import com.tictactec.ta.lib.MInteger;
import com.tictactec.ta.lib.RetCode;
import com.tictactec.ta.lib.*;
import com.tictactec.ta.lib.meta.helpers.*;
public class ExampleTALib
{
/**
* The total number of periods to generate data for.
*/
public static final int TOTAL_PERIODS = 100;
/**
* The number of periods to average together.
*/
public static final int PERIODS_AVERAGE = 20;
public static void main(String[] args)
{
double[] closePrice = new double[TOTAL_PERIODS];
double[] out = new double[TOTAL_PERIODS];
MInteger begin = new MInteger();
MInteger length = new MInteger();
double[] outRealUpperBand = new double[TOTAL_PERIODS];
double[] outRealMiddleBand = new double[TOTAL_PERIODS];
double[] outRealLowerBand = new double[TOTAL_PERIODS];
for (int i = 0; i < closePrice.length; i++) {
closePrice[i] = (double) i;
}
Core c = new Core();
// RetCode retCode = c.sma(0, closePrice.length - 1, closePrice, PERIODS_AVERAGE, begin, length, out);
// RetCode re = c.sma(startIdx, endIdx, inReal, optInTimePeriod, outBegIdx, outNBElement, outReal)
RetCode retCode = c.bbands(0, closePrice.length - 1, closePrice, PERIODS_AVERAGE,
1.0, 3.0, MAType.Ema, begin, length, outRealUpperBand, outRealMiddleBand, outRealLowerBand);
// RetCode re = c.bbands(startIdx, endIdx, inReal, optInTimePeriod, optInNbDevUp, optInNbDevDn, optInMAType, outBegIdx, outNBElement, outRealUpperBand, outRealMiddleBand, outRealLowerBand)
if (retCode == RetCode.Success) {
System.out.println("Output Begin:" + begin.value);
System.out.println("Output Begin:" + length.value);
for (int i = begin.value; i < closePrice.length; i++) {
StringBuilder line = new StringBuilder();
line.append("Period #");
line.append(i+1);
line.append(" close= ");
line.append(closePrice[i]);
line.append(" mov avg=");
line.append(out[i-begin.value]);
System.out.println(line.toString());
}
}
else {
System.out.println("Error");
}
}
}

Categories