DEV Community

ggwork
ggwork

Posted on

Building a Position Averaging Calculator: Getting the Math Right Matters

Last week, I found myself staring at a spreadsheet trying to figure out my average cost after buying the same stock three times at different prices. You know the drill — you buy at 10, it drops, you buy more at 8, then it dips again and you're thinking about averaging down further. The math isn't hard, but it's tedious, and I kept second-guessing whether I was accounting for fees correctly.

The Problem with Existing Solutions

I searched for online calculators, and honestly, most of them were disappointing. Either they required sign-up, were buried in financial portal websites with more ads than functionality, or they ignored trading fees entirely. A few had the fee calculation, but they made assumptions that didn't match how my broker actually charged me.

The real issue? Most calculators ignore the fact that your break-even price isn't just your average cost. When you sell, you pay fees too. So if your average cost is 9.0051, you can't actually break even by selling at 9.0051 — you need to sell slightly higher to cover the sell-side fees.

That's the gap I wanted to fill.

The Core Math

The calculation itself is straightforward weighted averaging, but the fee handling is where things get interesting. Here's the essential logic:

function compute(buys, currentRaw, commRate, stampRate, transferRate, minComm, sym) {
  let totalShares = 0, totalCost = 0;

  for (const { price, shares } of buys) {
    const amt = price * shares;
    const fee = amt * (commRate + transferRate) / 100;
    const actualFee = Math.max(fee, minComm);
    totalCost += amt + actualFee;
    totalShares += shares;
  }

  const avgCost = totalCost / totalShares;
  // Break-even includes sell-side fees
  const sellFeePerShare = avgCost * (commRate + stampRate + transferRate) / 100;
  const breakEven = avgCost + sellFeePerShare;

  return { totalShares, totalCost, avgCost, breakEven };
}
Enter fullscreen mode Exit fullscreen mode

The key insight here is the break-even calculation. Most tools stop at avgCost, but that's misleading. If you sell at your average cost, you'll actually lose money because of sell-side fees. The break-even price needs to be slightly higher — it's the price where your sell proceeds (after fees) exactly equal your total buy cost (including buy fees).

Why I Chose Pure Frontend

I could have built this with a backend. I could have added user accounts, saved calculation history, all that stuff. But honestly, this is a privacy-sensitive calculation. Do you really want your stock positions floating around on some server?

Pure frontend means:

  • No data leaves the browser
  • No server costs for me
  • Instant load times
  • Works offline

The trade-off? No persistent history, no cross-device sync. For this use case, that's a trade-off I'm comfortable with. If you need to save results, just screenshot it.

The AI-Assisted Development Experience

This is where it gets interesting. I built this with heavy AI assistance, and the experience was... educational.

What AI Got Right

I described the requirements conversationally: "I need a calculator that takes multiple buy records with price and shares, calculates weighted average cost including fees, and shows break-even price." The AI generated a solid initial structure — the HTML layout, the dynamic row addition, the basic styling. It even handled the dark mode CSS without me asking.

Where AI Struggled

The first version had a subtle bug in the fee calculation. It was applying the minimum commission to every trade individually, which is correct, but it was also applying the minimum to the sell fee estimation in the break-even calculation. That's wrong — the minimum commission should only apply if the trade actually happens.

Here's the conversation that followed:

Me: The break-even price is too high. If I buy 100 shares at 10 with a 5 yuan minimum commission, the break-even shouldn't include the minimum commission because the sell fee is proportional to the sell amount.

AI: You're right. Let me fix the break-even calculation to use the percentage rate only, not the minimum.
Enter fullscreen mode Exit fullscreen mode

This is the pattern I've noticed with AI coding — it's great at generating the 80% solution, but the edge cases and financial logic accuracy require human domain knowledge. The AI doesn't "know" that minimum commissions don't apply proportionally; it just patterns from typical code.

Another AI Miss: Input Validation

The AI initially assumed all inputs would be valid numbers. It took me pointing out that someone might type "abc" or leave a field empty before it added proper validation. And even then, the first validation attempt was too aggressive — it blocked legitimate edge cases like zero shares (which should be an error, but the error message was confusing).

The Refinement Process

After the initial AI-generated version, I went through several iterations:

  1. Fixed the fee calculation — the minimum commission logic needed adjustment for the break-even price
  2. Added input validation — with clear error messages in Chinese (the tool targets Chinese-speaking users)
  3. Improved the UX — the first version had all inputs on one line, which was cramped on mobile. I restructured to a grid layout that stacks on small screens.
  4. Added the optional current price field — this lets users see floating profit/loss without needing a separate calculator

The floating P&L calculation was another spot where I had to correct the AI:

// AI's first version — wrong
const floatPL = currentPrice * totalShares - totalCost;

// Correct version — includes sell fees
const sellFee = currentPrice * totalShares * (commRate + stampRate + transferRate) / 100;
const floatPL = currentPrice * totalShares - sellFee - totalCost;
Enter fullscreen mode Exit fullscreen mode

The difference matters. If you're showing someone their unrealized profit, it should reflect what they'd actually get if they sold right now, not a naive price-minus-cost calculation.

Lessons Learned

1. Domain Knowledge Still Matters

AI can write code, but it can't know that in Chinese stock markets, there's a stamp tax on sells (0.05%) that doesn't apply to buys, or that some brokers have a 5 yuan minimum commission. These domain-specific rules are where human input becomes critical.

2. Test with Real Numbers

The AI generated test cases, but they were too clean. I had to create edge cases myself:

  • What if the user enters a price of 0?
  • What if shares are negative?
  • What if the commission rate is 0 but the minimum is 5?
  • What about very small trades where the minimum commission dominates?

These edge cases exposed bugs that would have shipped otherwise.

3. AI Is Great for UI, Less Great for Logic

For this project, the AI's HTML/CSS was immediately usable. The JavaScript logic needed multiple rounds of correction. I've found this pattern holds across projects — AI excels at structure and boilerplate, but business logic requires careful human review.

The Result

After several hours of iteration, I had a working tool that handles the edge cases I care about:

  • Multiple buy records with dynamic add/remove
  • Commission, stamp tax, and transfer fees included in cost
  • Break-even price that accounts for sell-side fees
  • Optional current price for floating P&L
  • Dark mode (because I'm a developer, of course I added dark mode)
  • Pure frontend — no data leaves the browser

The calculation runs in milliseconds, the UI is responsive, and the whole thing is a single HTML file. No build step, no dependencies, no server.

Final Thoughts on AI-Assisted Development

This project reinforced my belief that AI coding tools are incredibly useful, but they're not a replacement for understanding the problem domain. The AI saved me maybe 60% of the time compared to writing everything from scratch, but the remaining 40% required me to actually understand what the tool needed to do.

The pattern I've settled into:

  1. Describe the problem clearly to the AI — the more specific, the better
  2. Review all generated logic carefully — especially anything involving money or dates
  3. Create edge case tests — the AI won't do this for you
  4. Iterate with targeted prompts — "fix the fee calculation" works better than "something's wrong"

If you're building a similar tool, whether it's a calculator or something else, the same principles apply. AI gets you 80% there quickly, but the last 20% is where the real engineering happens.

During this process, I built a small browser-based tool to make this workflow easier. It's free to use, handles all the fee calculations correctly (I hope), and respects your privacy since everything runs locally in your browser. If you're curious, you can find it here.

Now if you'll excuse me, I need to go check whether my actual average cost matches what the calculator says. Spoiler: it probably won't, because my broker's fee structure is apparently a mystery even to their own support team.

Top comments (1)

Collapse
 
topstar_ai profile image
Luis Cruz

I appreciate your focus on the break-even calculation, as it's a crucial aspect often overlooked in existing tools. The way you've handled fee calculations adds a lot of value and enhances the accuracy of the average cost determination. Have you considered implementing a feature that allows users to input their transaction history through a simple CSV upload? That could streamline the process even further. If you're exploring enhancements like these, I'd be interested in discussing potential collaboration to support the next stages of development.