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");
}
}
}
Related
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
So, i'm having trouble generating random numbers with uniform distribution in java, given the maximum and the minimun value of some attributes in some data set (Iris from UCI for machine learning). What i have is iris dataset, in some 2-d-array called samples. I put the random values according to the maximun and the minimun value of each attribute in iris data set (without the class attribute) in a 2-d-array called gworms (which has some extra fields for some other values of the algorithm).
So far, the full algorithm is not working properly, and my thoughts are in the fact that maybe the gworms (the points in 4-d space) are not generating correctly or with a good randomness. I think that the points are to close to each other (this i think because of some results obtained later whose code is not shown here). So, i'm asking for your help to validate this code in which i implement "uniform distribution" for gworms (for de first 4 positions):
/*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package glowworms;
import java.lang.Math;
import java.util.ArrayList;
import java.util.Random;
import weka.core.AttributeStats;
import weka.core.Instances;
/**
*
* #author oscareduardo937
*/
public class GSO {
/* ************ Initializing parameters of CGSO algorithm ******************** */
int swarmSize = 1000; // Swarm size m
int maxIte = 200;
double stepSize = 0.03; // Step size for the movements
double luciferin = 5.0; // Initial luciferin level
double rho = 0.4; // Luciferin decay parameter
double gamma = 0.6; // Luciferin reinforcement parameter
double rs = 0.38; // Initial radial sensor range. This parameter depends on the data set and needs to be found by running experiments
double gworms[][] = null; // Glowworms of the swarm.
/* ************ Initializing parameters of clustering problem and data set ******************** */
int numAtt; // Dimension of the position vector
int numClasses; // Number of classes
int total_data; //Number of instances
int threshold = 5;
int runtime = 1;
/*Algorithm can be run many times in order to see its robustness*/
double minValuesAtts[] = new double[this.numAtt]; // Minimum values for all attributes
double maxValuesAtts[] = new double[this.numAtt]; // Maximum values for all attributes
double samples[][] = new double[this.total_data][this.numAtt]; //Samples of the selected dataset.
ArrayList<Integer> candidateList;
double r;
/*a random number in the range [0,1)*/
/* *********** Method to put the instances in a matrix and get max and min values for attributes ******************* */
public void instancesToSamples(Instances data) {
this.numAtt = data.numAttributes();
System.out.println("********* NumAttributes: " + this.numAtt);
AttributeStats attStats = new AttributeStats();
if (data.classIndex() == -1) {
//System.out.println("reset index...");
data.setClassIndex(data.numAttributes() - 1);
}
this.numClasses = data.numClasses();
this.minValuesAtts = new double[this.numAtt];
this.maxValuesAtts = new double[this.numAtt];
System.out.println("********* NumClasses: " + this.numClasses);
this.total_data = data.numInstances();
samples = new double[this.total_data][this.numAtt];
double[] values = new double[this.total_data];
for (int j = 0; j < this.numAtt; j++) {
values = data.attributeToDoubleArray(j);
for (int i = 0; i < this.total_data; i++) {
samples[i][j] = values[i];
}
}
for(int j=0; j<this.numAtt-1; j++){
attStats = data.attributeStats(j);
this.maxValuesAtts[j] = attStats.numericStats.max;
this.minValuesAtts[j] = attStats.numericStats.min;
//System.out.println("** Min Value Attribute " + j + ": " + this.minValuesAtts[j]);
//System.out.println("** Max Value Attribute " + j + ": " + this.maxValuesAtts[j]);
}
//Checking
/*for(int i=0; i<this.total_data; i++){
for(int j=0; j<this.numAtt; j++){
System.out.print(samples[i][j] + "** ");
}
System.out.println();
}*/
} // End of method InstancesToSamples
public void initializeSwarm(Instances data) {
this.gworms = new double[this.swarmSize][this.numAtt + 2]; // D-dimensional vector plus luciferin, fitness and intradistance.
double intraDistance = 0;
Random r = new Random(); //Random r;
for (int i = 0; i < this.swarmSize; i++) {
for (int j = 0; j < this.numAtt - 1; j++) {
//Uniform randomization of d-dimensional position vector
this.gworms[i][j] = this.minValuesAtts[j] + (this.maxValuesAtts[j] - this.minValuesAtts[j]) * r.nextDouble();
}
this.gworms[i][this.numAtt - 1] = this.luciferin; // Initial luciferin level for all swarm
this.gworms[i][this.numAtt] = 0; // Initial fitness for all swarm
this.gworms[i][this.numAtt + 1] = intraDistance; // Intra-distance for gworm i
}
//Checking gworms
/*for(int i=0; i<this.swarmSize; i++){
for(int j=0; j<this.numAtt+2; j++){
System.out.print(gworms[i][j] + "** ");
}
System.out.println();
}*/
} // End of method initializeSwarm
}
The main class is this one:
package uniformrandomization;
/**
*
* #author oscareduardo937
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import weka.core.Instances;
import glowworms.GSO;
public class UniformRandomization {
public UniformRandomization(){
super();
}
//Loading the data from the filename file to the program. It can be .arff or .csv
public static BufferedReader readDataFile(String filename) {
BufferedReader inputReader = null;
try {
inputReader = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException ex) {
System.err.println("File not found: " + filename);
}
return inputReader;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
BufferedReader datafile1 = readDataFile("src/data/iris.arff");
Instances data = new Instances(datafile1);
GSO gso = new GSO();
gso.instancesToSamples(data);
gso.initializeSwarm(data);
System.out.println("Fin...");
}
}
So i want to know if with this code, the numbers of the position ij of the gworms are generating within the range of max value and min value for attribute j.
Thanks so much in advanced.
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
I am currently working with Ta-lib Java implementations. I can run properly MA & SUM. But having problem while try to run DEMA, TEMA. The output is all zeros.
I am calling the DEMA & TEMA method of Ta-lib as follows
import com.tictactec.ta.lib.Core;
import com.tictactec.ta.lib.MInteger;
public class TALibJava {
double[] array = {207.650, 205.160, 210.870, 209.350, 207.250, 209.960, 207.650, 205.160, 188.170, 186.020};
double[] output = new double[array.length];
int period = 5;
Core core = new Core();
int lookback = 0;
MInteger begin = new MInteger();
MInteger length = new MInteger();
public void callDEMA() {
lookback = core.demaLookback(period);
core.dema(0, array.length - 1, array, 0, begin, length, output);
System.out.println("DEMA Output: ");
print();
}
public void callTEMA() {
lookback = core.temaLookback(period);
core.tema(0, array.length - 1, array, 0, begin, length, output);
System.out.println("TEMA Output: ");
print();
}
public void print() {
for(int i=0;i<array.length;i++) {
System.out.print(output[i] + "\t ");
}
System.out.println("");
}
public static void main(String args[]) {
TALibJava obj = new TALibJava();
obj.callDEMA();
obj.callTEMA();
}
}
Perhaps the input parameters are not properly set. Please suggest me what I'm doing wrong.
According to the source code of dema(), optInTimePeriod cannot be 0:
else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) )
return RetCode.BadParam ;
That's why your current code returns "BadParam" and not "Success" when you call dema().
(Same thing goes for tema())
I've got some code that I don't think is able to be multithreaded, perhaps I'm wrong. I'd like to make execute this code on a clustered system but I'm unsure of how to scale it for such a deployment.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Coord {
public int a,b,c,d,e,f;
public static void main(String[] args) throws IOException {
FileOutputStream out = new FileOutputStream("/Users/evanlivingston/2b.txt");
PrintStream pout = new PrintStream(out);
Scanner sc = new Scanner(new File("/Users/evanlivingston/1.txt"));
List<Coord> coords = new ArrayList<Coord>();{
// for each line in the file
while(sc.hasNextLine()) {
String[] numstrs = sc.nextLine().split("\\s+");
Coord c = new Coord();
c.a = Integer.parseInt(numstrs[1]);
c.b = Integer.parseInt(numstrs[2]);
c.c = Integer.parseInt(numstrs[3]);
c.d = Integer.parseInt(numstrs[4]);
c.e = Integer.parseInt(numstrs[5]);
c.f = Integer.parseInt(numstrs[6]);
coords.add(c);
}
// now you have all coords in memory
{
for(int i=0; i<coords.size(); i++ )
for( int j=0; j<coords.size(); j++)
{
Coord c1 = coords.get(i);
Coord c2 = coords.get(j);
double foo = ((c1.a - c2.a) * (c1.a - c2.a)) *1 ;
double goo = ((c1.b - c2.b) * (c1.b - c2.b)) *1 ;
double hoo = ((c1.c - c2.c) * (c1.c - c2.c)) *2 ;
double joo = ((c1.d - c2.d) * (c1.d - c2.d)) *2 ;
double koo = ((c1.e - c2.e) * (c1.e - c2.e)) *4 ;
double loo = ((c1.f - c2.f) * (c1.f - c2.f)) *4 ;
double zoo = Math.sqrt(foo + goo + hoo + joo + koo + loo);
DecimalFormat df = new DecimalFormat("#.###");
pout.println(i + " " + j + " " + df.format(zoo));
System.out.println(i);
}
pout.flush();
pout.close();
}
}
}
}
I appreciate any help anyone can offer.
Splitting the inner for loop into separate tasks looks like a good candidate for where to make this process multithreaded. Here is one way this could be done with an ExecutorService and Futures
final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
final List<Future<String>> results = new LinkedList<Future<String>>();
// now you have all coords in memory
for (int i = 0; i < coords.size(); i++) {
final int index = i;
final Coord c1 = coords.get(index);
results.add(executor.submit(new Callable<String>() {
public String call() {
final StringBuilder stringBuilder = new StringBuilder();
for (int j = 0; j < coords.size(); j++) {
final Coord c2 = coords.get(j);
final double foo = ((c1.a - c2.a) * (c1.a - c2.a)) * 1;
final double goo = ((c1.b - c2.b) * (c1.b - c2.b)) * 1;
final double hoo = ((c1.c - c2.c) * (c1.c - c2.c)) * 2;
final double joo = ((c1.d - c2.d) * (c1.d - c2.d)) * 2;
final double koo = ((c1.e - c2.e) * (c1.e - c2.e)) * 4;
final double loo = ((c1.f - c2.f) * (c1.f - c2.f)) * 4;
final double zoo = Math.sqrt(foo + goo + hoo + joo + koo + loo);
final DecimalFormat df = new DecimalFormat("#.###");
stringBuilder.append(index + " " + j + " " + df.format(zoo));
System.out.println(index);
}
return stringBuilder.toString();
}
}));
}
for (Future<String> result : results) {
pout.print(result.get());
}
pout.flush();
pout.close();
executor.shutdown();
For clustering, I think Hazelcast offers a good solution that will allow you to define a shared ExecutorService and shared Collections. You would need two flavors of nodes, the single node responsible for all I/O and creating the list of Coords as well as submitting the tasks. And a processing node which simply executes the tasks. That is all my opinion of how I might do it. However, if your dataset is small enough to fit in memory it is likely not worth the effort to split up the processing this much.
It looks very parallelizable to me. Why don't you have threads process one row of data at a time? You could use an AtomicInteger to keep a count of how many rows have been claimed by worker threads. Each thread would do a counter.getAndIncrement to get a row to work on (if it returns coords.size() or higher, the thread should terminate), then do all the math for that row, and repeat.
The printing would be out of order, but you could instead fill some buffers with the results, then quickly print everything at the end.