Find range from stock quote - java

Using the share quote I need to find the range with the following input parameters:
price step : minimal price movement possible. Step = 0.01 mean that quotes can be 100.01, 100.1, but not 100.015. Can be > 1 for 'big' shares.
number of steps in range. Steps = 10 mean I need interval with 10 minimal price movements. Like [100.1 ; 100.2) Interval needs to be adjusted to minimal movement, so no [100.015; 100.15) intervals possible.
Input quote any double (6 digits after . is enough), may or may not obey price step rule (for example, direct value from stock market obeys, but average value is not). Obviously, quote should be in interval. I tried different approaches, but all of them fails.
Range is rather trivial:
public class Range<T extends Comparable> {
private T from = null;
private T to = null;
public Range(T from, T to) {
this.from = from;
this.to = to;
}
public T getFrom() {
return from;
}
public T getTo() {
return to;
}
#SuppressWarnings("unchecked")
public boolean contains(T value) {
return from.compareTo(value) <= 0 && to.compareTo(value) > 0;
}
#Override
public String toString() {
return "Range{" +
"from=" + from +
", to=" + to +
'}';
}
}
protected static Range<Double> getRangeFromPrice(double pips, int step, double price) {
BigDecimal modifier = new BigDecimal(pips * step).setScale(6, BigDecimal.ROUND_HALF_DOWN);
BigDecimal begin = new BigDecimal(price).divide(modifier, 0, BigDecimal.ROUND_HALF_DOWN).multiply(modifier);
return new Range<>(begin.doubleValue(), begin.add(modifier).doubleValue());
}
This function works most of the time, for example for pips = 0.01 and step = 10
price = 132 Range{from=132.0, to=132.1} OK
price = 132.01 Range{from=132.0, to=132.1} OK
price = 132.1 Range{from=132.1, to=132.2} OK
price = 132.15 Range{from=132.2, to=132.3} <- ERROR, price not in interval
I tried different rounding strategies, but all of them fails (in one example or another). Now I totally run out of ideas. How can I choose rounding strategy automatically?

Consider:
Decimal STEP = 0.1; // floating-point 0.1 is always imprecise.
Decimal shifted = price / step; // make steps integral.
Decimal left = trunc(price) * step; // always ≤ price.
Decimal right = trunc(price + 1) * step; // always > left.
return Range(left, right);

protected static Range<Double> getRangeFromPrice(double step, int count, double price) {
BigDecimal modifier = new BigDecimal(count * step).setScale(Common.PRICE_RESOLUTION, BigDecimal.ROUND_HALF_UP);
BigDecimal div = new BigDecimal(price).divide(modifier, Common.PRICE_RESOLUTION, BigDecimal.ROUND_HALF_EVEN).setScale(0, BigDecimal.ROUND_FLOOR);
BigDecimal begin = div.multiply(modifier);
Range<Double> ret = new Range<>(begin.doubleValue(), begin.add(modifier).doubleValue());
assert ret.contains(price);
return ret;
}
I solved original issue with the following code. Price shouldn't be really double, I use number(19,6) in database, however in application I use double as BigDecimal is rather slow.
If you want to use double, extra rounding is required.
This code pass my unit tests.

Related

Optimization: Finding the best Simple Moving Average takes too much time

I've created a simple Spring-Application with a MySQL-DB.
In the DB there are 20 years of stock data (5694 lines):
The Goal is to find the Best Moving Average (N) for that 20 years of stock data. Inputs are the closing prices of every trading day.
The calculated average depends on the N. So p.e. if N=3 the average of a reference day t, is given by ((t-1)+(t-2)+(t-3)/N).
Output is the Best Moving Average (N) and the Result you made with all the buying & selling transactions of the Best N.
I did not find a proper algorithm in the Internet, so I implemented the following:
For every N (249-times) the program does the following steps:
SQL-Query: calculates averages & return list
#Repository
public interface StockRepository extends CrudRepository<Stock, Integer> {
/*
* This sql query calculate the moving average of the value n
*/
#Query(value = "SELECT a.date, a.close, Round( ( SELECT SUM(b.close) / COUNT(b.close) FROM stock AS b WHERE DATEDIFF(a.date, b.date) BETWEEN 0 AND ?1 ), 2 ) AS 'avg' FROM stock AS a ORDER BY a.date", nativeQuery = true)
List<AverageDTO> calculateAverage(int n);
Simulate buyings & sellings – > calculate result
Compare result with bestResult
Next N
#RestController
public class ApiController {
#Autowired
private StockRepository stockRepository;
#CrossOrigin(origins = "*")
#GetMapping("/getBestValue")
/*
* This function tries all possible values in the interval [min,max], calculate
* the moving avg and simulate the gains for each value to choose the best one
*/
public ResultDTO getBestValue(#PathParam("min") int min, #PathParam("max") int max) {
Double best = 0.0;
int value = 0;
for (int i = min; i <= max; i++) {
Double result = simulate(stockRepository.calculateAverage(i));
if (result > best) {
value = i;
best = result;
}
}
return new ResultDTO(value, best);
}
/*
* This function get as input the close and moving average of a stock and
* simulate the buying/selling process
*/
public Double simulate(List<AverageDTO> list) {
Double result = 0.0;
Double lastPrice = list.get(0).getClose();
for (int i = 1; i < list.size(); i++) {
if (list.get(i - 1).getClose() < list.get(i - 1).getAvg()
&& list.get(i).getClose() > list.get(i).getAvg()) {
// buy
lastPrice = list.get(i).getClose();
} else if (list.get(i - 1).getClose() > list.get(i - 1).getAvg()
&& list.get(i).getClose() < list.get(i).getAvg()) {
// sell
result += (list.get(i).getClose() - lastPrice);
lastPrice = list.get(i).getClose();
}
}
return result;
}
}
When I put Min=2 and Max=250 it takes 45 minutes to finish.
Since, I'm a beginner in Java & Spring I do not know how I can optimize it.
I'm happy for every input.
This problem is equivalent with finding the best moving N sum. Simply then divide by N. Having such a slice, then the next slice subtracts the first value and adds a new value to the end. This could lead to an algorithm for finding local growths with a[i + N] - a[i] >= 0.
However in this case a simple sequential ordered query with
double[] slice = new double[N];
double sum = 0.0;
suffices. (A skipping algorithm on a database is probably too complicated.)
Simply walk through the table keeping the slice as window, keeping N values and keys, and maintaining the maximum upto now.
Use the primitive type double instead of the object wrapper Double.
If the database transport is a serious factor, a stored procedure would do. Keeping a massive table as really many entities just for a running maximum is unfortunate.
It would be better to have a condensed table or better field with the sum of N values.

FASTEST way to truncate a float in Java

I have a program that takes in anywhere from 20,000 to 500,000 velocity vectors and must output these vectors multiplied by some scalar. The program allows the user to set a variable accuracy, which is basically just how many decimal places to truncate to in the calculations. The program is quite slow at the moment, and I discovered that it's not because of multiplying a lot of numbers, it's because of the method I'm using to truncate floating point values.
I've already looked at several solutions on here for truncating decimals, like this one, and they mostly recommend DecimalFormat. This works great for formatting decimals once or twice to print nice user output, but is far too slow for hundreds of thousands of truncations that need to happen in a few seconds.
What is the most efficient way to truncate a floating-point value to n number of places, keeping execution time at utmost priority? I do not care whatsoever about resource usage, convention, or use of external libraries. Just whatever gets the job done the fastest.
EDIT: Sorry, I guess I should have been more clear. Here's a very simplified version of what I'm trying to illustrate:
import java.util.*;
import java.lang.*;
import java.text.DecimalFormat;
import java.math.RoundingMode;
public class MyClass {
static class Vector{
float x, y, z;
#Override
public String toString(){
return "[" + x + ", " + y + ", " + z + "]";
}
}
public static ArrayList<Vector> generateRandomVecs(){
ArrayList<Vector> vecs = new ArrayList<>();
Random rand = new Random();
for(int i = 0; i < 500000; i++){
Vector v = new Vector();
v.x = rand.nextFloat() * 10;
v.y = rand.nextFloat() * 10;
v.z = rand.nextFloat() * 10;
vecs.add(v);
}
return vecs;
}
public static void main(String args[]) {
int precision = 2;
float scalarToMultiplyBy = 4.0f;
ArrayList<Vector> velocities = generateRandomVecs();
System.out.println("First 10 raw vectors:");
for(int i = 0; i < 10; i++){
System.out.print(velocities.get(i) + " ");
}
/*
This is the code that I am concerned about
*/
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.DOWN);
long start = System.currentTimeMillis();
for(Vector v : velocities){
/* Highly inefficient way of truncating*/
v.x = Float.parseFloat(df.format(v.x * scalarToMultiplyBy));
v.y = Float.parseFloat(df.format(v.y * scalarToMultiplyBy));
v.z = Float.parseFloat(df.format(v.z * scalarToMultiplyBy));
}
long finish = System.currentTimeMillis();
long timeElapsed = finish - start;
System.out.println();
System.out.println("Runtime: " + timeElapsed + " ms");
System.out.println("First 10 multiplied and truncated vectors:");
for(int i = 0; i < 10; i++){
System.out.print(velocities.get(i) + " ");
}
}
}
The reason it is very important to do this is because a different part of the program will store trigonometric values in a lookup table. The lookup table will be generated to n places beforehand, so any velocity vector that has a float value to 7 places (i.e. 5.2387471) must be truncated to n places before lookup. Truncation is needed instead of rounding because in the context of this program, it is OK if a vector is slightly less than its true value, but not greater.
Lookup table for 2 decimal places:
...
8.03 -> -0.17511085919
8.04 -> -0.18494742685
8.05 -> -0.19476549993
8.06 -> -0.20456409661
8.07 -> -0.21434223706
...
Say I wanted to look up the cosines of each element in the vector {8.040844, 8.05813164, 8.065688} in the table above. Obviously, I can't look up these values directly, but I can look up {8.04, 8.05, 8.06} in the table.
What I need is a very fast method to go from {8.040844, 8.05813164, 8.065688} to {8.04, 8.05, 8.06}
The fastest way, which will introduce rounding error, is going to be to multiply by 10^n, call Math.rint, and to divide by 10^n.
That's...not really all that helpful, though, considering the introduced error, and -- more importantly -- that it doesn't actually buy anything. Why drop decimal points if it doesn't improve efficiency or anything? If it's about making the values shorter for display or the like, truncate then, but until then, your program will run as fast as possible if you just use full float precision.

Calling other methods to main in java

I am having a little issue with formatting returned methods in the main method. I have created the methods and done the calculation, but my issue is if i am calling the other two methods to the main method correctly. I am also having and issue with formatting each method in columns. Do i need to make the columns in the respected methods? or do i need to create them in the main method?
Write a program that analyzes an object falling for 10 seconds. It should contain main and two additional methods. One of the additional methods should return the distance an object falls in meters when passed the current second as an argument. See the formula needed below. The third method should convert meters to feet. You can look up the conversion factor needed online. The main method should use one loop to call the other methods and generate a table as shown below. The table should be displayed in formatted columns with decimals as shown. I believe i am on
SEC METERS FEET
1 4.9 16.1
2 19.6 64.3
3 44.1 144.7
4 78.4 257.2
5 122.5 401.9
6 176.4 578.7
7 240.1 787.7
8 313.6 1028.9
9 396.9 1302.2
10 490.0 1607.6
My code
package week4.yedkois;
public class project3 {
public static void main(String[] args) {
System.out.printf("SEC" + "\n");
meters();
feet();
for (int time = 1; time <= 10; time++) {
System.out.println(time);
}
}
public static void meters() {
double Meters;
double G = 9.8; // meters = .5(9.8)(seconds) ^2
for (int time = 1; time <= 10; time++) {
Meters = (.5 * 9.8 * Math.pow(time, 2));
System.out.printf("%.1f\n", Meters);
}
return;
}
public static void feet() {
double Feet;
double G = 9.8; // meters = .5(9.8)(seconds) ^2
for (int time = 1; time <= 10; time++) {
Feet = (.5 * 9.8 * Math.pow(time, 2) * 3.28084);
System.out.printf("%.1f\n", Feet);
}
return;
}
}
Here is my solution. I use a Tab ("\t") to achieve the same space between the different values. And then I had to redesign your code a little. I use only one if-loop directly in the main-method and hand the current time-value as a parameter into both methods meters() and feet(). That makes it much easier to get all values of one round in line.
Here are some additional remarks:
Java is not C++, so you don't have to use an empty return statement at the end of a method. It's useless there.
In Java variables and method-names always start with a small letter, _ or $. Only class-names and constants start with a capital letter.
Hope this helps for a start.
public class Project3 {
public static void main(String[] args){
System.out.printf("%3s\t%6s\t%6s\n", "SEC", "METERS", "FEET");
for(int time = 1; time <= 10; time++)
{
System.out.print(time + "\t");
meters(time);
feet(time);
System.out.println();
}
}
public static void meters(int time){
double meters;
double g = 9.8; // meters = .5(9.8)(seconds) ^2
meters = (.5 * 9.8 * Math.pow(time, 2));
// the longer the expected maximum length of a result gets
// the higher your reserved number of digits has
// to be, to gain the wanted right bound effect!
System.out.printf("%6.1f\t", meters);
}
public static void feet(int time){
double feet;
double g = 9.8; // meters = .5(9.8)(seconds) ^2
feet = (.5 * 9.8 * Math.pow(time, 2) * 3.28084);
// the longer the expected maximum length of a result gets
// the higher your reserved number of digits has
// to be, to gain the wanted right bound effect!
System.out.printf("%6.1f", feet);
}
}

Test Case failing when expected is equal to output

Before I get into detail, YES this is a HOMEWORK ASSIGNMENT. NO I DON'T WANT ANSWERS, JUST TIPS and/or Suggestions to try this or that.
The problem introduces with this:
Create a class, ExactNumber, that uses two long properties named left
and right (representing the portion of the number that is to the left
and right of the decimal point respectively). For example, 3.75 would
be represented by new ExactNumber(3, 7500000000000000L). Note the L on
the end which tells Java the large number is a long. This translates
to: 3 + 7500000000000000/10000000000000000 = 3.75
Here is my code:
public class ExactNumber {
private long left;
private long right;
public ExactNumber(long left, long right) {
this.left = left;
this.right = right;
}
public String toString() {
return String.valueOf(doubleValue());
}
public double doubleValue() {
return ((double) left + (double) (right/ 100000000000000L) / 100);
}
public int compareTo (ExactNumber exactNumber) {
if(exactNumber.left < left) {
return 1;
}
else if (exactNumber.left == left) {
if (exactNumber.right < right) {
return 1;
}
else if (exactNumber.right == right) {
return 0;
}
else {
return -1;
}
}
else {
return -1;
}
}
public boolean equal(ExactNumber thisobject) {
if (thisobject instanceof ExactNumber) {
if (thisobject.doubleValue() == this.doubleValue()) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
public double add(ExactNumber exactNumber) {;
return ((left+exactNumber.left) + (double)((right+exactNumber.right)*1E-16));
}
}
My problem are the tests coming up as an error when the expected value is equal to the actual value. Here are the test cases (NOTE: there are more test cases, but they pass the JUnit test):
public class TestExactNumber extends TestCase {
ExactNumber threesevenfive = new ExactNumber(3, 7500000000000000L);
ExactNumber threesevenfive_andalittlebit = new ExactNumber(3, 7500000000000001L);
ExactNumber threesevenfive_dupe = new ExactNumber(3, 7500000000000000L);
ExactNumber ten = new ExactNumber(10, 0);
ExactNumber thirteensevenfive = new ExactNumber(13, 7500000000000000L);
ExactNumber sevenfifty = new ExactNumber(7, 5000000000000000L);
public void test_equals() {
assertFalse(threesevenfive.equals(threesevenfive_andalittlebit));
assertEquals(threesevenfive, threesevenfive_dupe);
}
public void test_add() {
assertEquals(threesevenfive.add(ten), thirteensevenfive);
assertEquals(threesevenfive.add(threesevenfive), sevenfifty);
The assertEquals above failed in the JUnit test, but says like (for an example) expected = 13.75 and actual = 13.75.
Any tips or hints at what I need to do with my code is greatly appreciated. And thank you in advanced.
NOTES:
According to my instructor, I should not be using the doubleValue method to implement my equals method. I know that I do have it in my code, but that was prior to the tip the instructor gave me and I am just unsure about how to change it.
I am using eclipse for java to code this.
Your equal Method is never used. The Java Method used by assertEquals() is called equalS (and you have to override the equals() method derived from Object).
Therefore, the assertion will use equals inherited from Object, which will compare the actual instances rather than using YOUR equal method which will compare the objet values. And since they are two different INSTANCES, they are not equal.
Finally, the two instances will be plotted with toString() resulting in expected = 13.75 and actual = 13.75. (Because your toString() returns only the values, ignoring the difference between instances)
Your Instructors Response:
A Long in Java is a 64 bit long number. Double in Java is implemented with the IEEE754 Standard, which only leaves 52 bit for the mantissa. Meaning: Any conversion of a Long Number to a double, where the Long Number has set bits on bit 53 to 63 - will cause the exponent to be shifted in a way, that you loose precision arround the LSBs - resulting in an unprecice Double Value.
Therefore comparing the double values to determine equality is not sufficent for your desired Design of a "Exact Number".
Example:
Long bigLong = 1L<<51; //picked 51: 52 and 53 already causing rounding issues.
Long long1 = bigLong + 1L;
Long long2 = bigLong + 2L;
System.out.println(long1+" -> " + long1.doubleValue());
System.out.println(long2+" -> " + long2.doubleValue());
//false, enough precision to preserve bit "0" and "1".
System.out.println(long1.doubleValue()==long2.doubleValue());
Output:
2251799813685262 -> 2.251799813685262E15
2251799813685263 -> 2.251799813685263E15
false
When setting bit 54:
Long bigLong = 1L<<54;
Long long1 = bigLong + 1L;
Long long2 = bigLong + 2L;
System.out.println(long1+" -> " + long1.doubleValue());
System.out.println(long2+" -> " + long2.doubleValue());
System.out.println(long1.doubleValue()==long2.doubleValue());
Output:
18014398509481985 -> 1.8014398509481984E16
18014398509481986 -> 1.8014398509481984E16
true
Note the Exponent beeing increased from 15 to 16, which will cut off the difference of "1" between both longs.
To solve this, you can compare left1 to left2 and right1 to right2 without converting it to a double.
Your equal method should ideally test every necessary value in your class. In this case, it should be checking to see if your left and right values are the same between the two objects. If they are the same, then you can consider the objects to be equal.
In your case, you should probably put a debug point in your equals method to see why the function is returning back a false.
Try using Eclipse's built in functionality to create equals and hashcode methods for you. You can create that by going to Source->Generate hashCode() and equals(). The methods will be very different from what you have created.
Another thing, in your AssertEquals method, make sure both the values passed in are of the same type. In your case, you're checking a Double with an ExactNumber object. They will definitely not be the same. You need to either
Change your Add method to return a ExactNumber object
Have a method in your ExactNumber class called getDouble() and use that as the second parameter instead.
Hope this helps.

Java convert float to integer

I want to do an operation like this : if the given float numbers are like 1.0 , 2.0 , 3.0 , I want to save them to database as integer (1,2,3 ), if they are like 1.1 , 2.1 , ,3.44 , I save them as float. what's the best solution for this problem using java ? The corresponding field in database is type of varchar.
Just try int i = (int) f;.
EDIT : I see the point in the question. This code might work :
int i = (int) f;
String valToStore = (i == f) ? String.valueOf(i) : String.valueOf(f);
String result = "0";
if (floatVar == Math.floor(floatVar)) {
result = Integer.toString((int) floatVar);
} else {
result = Float.toString(floatVar);
}
The if-clause checks whether the number is a whole number - i.e. if it is equal to the result of rounding it down to the closest whole value.
But this is very odd requirement indeed, and perhaps you should reconsider the need for such a thing.
Seems like you want to save Floats with no trailing numbers as Integers, while saving those with significant trailing numbers as Floats. I would rather just save it all as Float to the DB, but it's your question so here's my answer:
/**
* Method to determine if trailing numbers are significant or not. Significant
* here means larger than 0
*
* #param fFloat
* #return
*/
public static boolean isTrailingSignificant(Float fFloat)
{
int iConvertedFloat = fFloat.intValue();// this drops trailing numbers
// checks if difference is 0
return ((fFloat - iConvertedFloat) > 0);
}
This is how you would use this method:
Number oNumToSave = null;
if (isTrailingSignificant(fFloat))
{
// save float value as is
oNumToSave = fFloat;
}
else
{
// save as int
oNumToSave = fFloat.intValue();// drops trailing numbers
}
After that, you can do the database operation using the variable oNumToSave.
Not sure this is the best solution, but you can try to write a method like this :
String convertToString(Float f) {
if (f.toString().endsWith(".0"))
return f.intValue().toString();
else
return f.toString();
}
Kotlin:
val mAmount = 3.0
val intAmount = mAmount.toInt()
val amountToDisplay = if (intAmount.compareTo(mAmount) == 0) intAmount.toString() else java.lang.String.valueOf(mAmount)

Categories