Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigDecimal for Stock Prices?

I realize that we should use BigDecimal for all monetary values, but what about stock prices in dollars?

I noticed that data feed API from major vendors uses the type double for stock quotes. Does anyone know why?

Does that mean my application can use the type double to store stock quotes that come from these vendors?

like image 562
Tom Tucker Avatar asked Mar 12 '11 21:03

Tom Tucker


2 Answers

The reason for not using binary floating-point for money is that money uses decimal fractions and people (and accounting regulations) expect specific decimal behaviour from arithmetic operations performed on it - which binary floating-point does not provide.

However, stock quote feeds aren't generally used for accounting. They're displayed, compared, used as input for various chart analysis indicators or trading algorithms - all much closer to scientific applications than accounting, and not requiring decimal behaviour or precision. Instead, because of the large amount of data, storage efficiency and performance are relevant, and BigDecimal really sucks at those.

like image 174
Michael Borgwardt Avatar answered Oct 05 '22 23:10

Michael Borgwardt


I work in the field. BigDecimal is obviously ideal from a precision perspective, but it sucks from a performance perspective. doubles are an option in some circumstances (particularly when dealing with normal equity prices, doubles are easily - with appropriate precautions - able to represent the entirety of the price range of all the equity exchanges I regularly deal with).

Another option is, if you know the range of DP used by the exchanges in question, to use fixed-point and a normal int or long. To take an example I know well, Xetra (the German electronic exchange) currently has at most 3 decimal places. Using 3dp, you can represent prices up to 2,147,483.647 with a normal int. Fine for an individual price, no good for representing the total of a day's trading.

It's all a question of what data you're receiving, what the precision of that data is and how you're processing it.

like image 32
Jon Bright Avatar answered Oct 06 '22 01:10

Jon Bright