Calculating Exact Share Counts to Lower Your Average Cost in Vanilla JS
A DEV Community tutorial explains how investors can use a closed-form equation to determine how many shares to buy during a price dip to reach a target average cost. It notes that a simple arithmetic mean of prices is only accurate when equal share quantities are bought, so it instead uses the volume-weighted average price for multi-lot purchases. The author provides a zero-dependency JavaScript function that calculates the cost basis across purchase lots, with rounding for precision. The piece then derives the formula for the number of shares needed at a dip price to reach a specified target average, including input validation for edge cases. It also covers the Harmonic Mean perspective on dollar-cost averaging and handling fractional cryptocurrency decimals.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.


Discussion (0)
Log in to join the discussion and vote.
Log in