"What is my average price?" sounds like a one line problem. It is, but the obvious one liner is wrong, and the bug is common enough to be worth a short post.
Disclosure: I am the founder of copy.top. We publish a free dca and average price calculator , and this post explains the math behind that kind of tool. The code below is a minimal version written for this article.
The bug
You buy twice, 100 dollars each time: once at 1.00 and once at 0.50.
The tempting answer is the mean of the two prices:
( 1.0 + 0.5 ) / 2 ; // 0.75, wrong
Enter fullscreen mode
Exit fullscreen mode
It is wrong because you did not buy the same number of coins each time. The first buy got 100 coins, the second got 200. You hold 300 coins for 200 dollars, so the average price is 200 / 300 , about 0.667.
When each buy is a fixed amount of money, the average price is the harmonic mean of the prices, not the arithmetic mean.…