Javascript: Average cost per share

Date: 2021-10-11

Keywords: Crypto, Stock

(() => {
    const fee = 0.01;

    const transactions = [
        { quantity: 100, price: 0.688 },
        { quantity: 50, price: 0.82 },
        { quantity: 100, price: 0.72 },
        { quantity: -50, price: 0.89 },
        { quantity: 100, price: 0.92 },
        { quantity: 750, price: 0.86 },
    ];

    function getAveragePrice(transactions, fee) {
        const x = {
            quantity: 0,
            qtyBought: 0,
            totalPrice: 0,
            avgPrice: 0,
        };
        for (const t of transactions) {
            x.quantity += t.quantity;
            if (t.quantity > 0) {
                x.qtyBought += t.quantity;
                const price = t.quantity * t.price;
                const priceWithFee = price + Math.abs(price * fee);
                x.totalPrice += priceWithFee;
            }
        }
        x.avgPrice = x.totalPrice / x.qtyBought;
        return x;
    }


    // begin: Calculate with a single price/quantity value
    let addedQty = 0;
    let addedAvg = 0;
    function addTransaction(qty, price) {
        if (qty <= 0) return;
        addedAvg = ((addedAvg * addedQty) + (price * qty)) / (addedQty + qty);
        addedQty += qty;
        console.log("add", addedQty, addedAvg);
    }
    for (const t of transactions) {
        const priceWithFee = t.price + Math.abs(t.price * fee);
        addTransaction(t.quantity, priceWithFee);
    }
    console.log("added avg: ", addedAvg);
    // end: Calculate with a single price/quantity value

    const avg = getAveragePrice(transactions, fee);

    const rjust = (s, width, c = " ") =>
        s.length < width ? c.slice(0, 1).repeat(width - s.length) + s : s;
    const display = (n) => rjust(Number(n).toFixed(3), 12);

    console.log(`own:           ${display(avg.quantity)}`);
    console.log(`price:       $ ${display(avg.avgPrice * avg.quantity)}`);
    console.log(`price/share: $ ${display(avg.avgPrice)}`);
})();
/* RESULT:
own:               1050.000
price:       $      885.807
price/share: $        0.844
*/

54450cookie-checkJavascript: Average cost per share