{"id":5445,"date":"2021-10-11T18:22:18","date_gmt":"2021-10-11T17:22:18","guid":{"rendered":"https:\/\/solidt.eu\/site\/?p=5445"},"modified":"2022-07-25T08:35:41","modified_gmt":"2022-07-25T07:35:41","slug":"javascript-average-cost-per-share","status":"publish","type":"post","link":"https:\/\/solidt.eu\/site\/javascript-average-cost-per-share\/","title":{"rendered":"Javascript: Average cost per share"},"content":{"rendered":"\n<p>Keywords: Crypto, Stock<\/p>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"javascript\" data-theme=\"monokai\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">(() => {\n    const fee = 0.01;\n\n    const transactions = [\n        { quantity: 100, price: 0.688 },\n        { quantity: 50, price: 0.82 },\n        { quantity: 100, price: 0.72 },\n        { quantity: -50, price: 0.89 },\n        { quantity: 100, price: 0.92 },\n        { quantity: 750, price: 0.86 },\n    ];\n\n    function getAveragePrice(transactions, fee) {\n        const x = {\n            quantity: 0,\n            qtyBought: 0,\n            totalPrice: 0,\n            avgPrice: 0,\n        };\n        for (const t of transactions) {\n            x.quantity += t.quantity;\n            if (t.quantity > 0) {\n                x.qtyBought += t.quantity;\n                const price = t.quantity * t.price;\n                const priceWithFee = price + Math.abs(price * fee);\n                x.totalPrice += priceWithFee;\n            }\n        }\n        x.avgPrice = x.totalPrice \/ x.qtyBought;\n        return x;\n    }\n\n\n    \/\/ begin: Calculate with a single price\/quantity value\n    let addedQty = 0;\n    let addedAvg = 0;\n    function addTransaction(qty, price) {\n        if (qty &lt;= 0) return;\n        addedAvg = ((addedAvg * addedQty) + (price * qty)) \/ (addedQty + qty);\n        addedQty += qty;\n        console.log(\"add\", addedQty, addedAvg);\n    }\n    for (const t of transactions) {\n        const priceWithFee = t.price + Math.abs(t.price * fee);\n        addTransaction(t.quantity, priceWithFee);\n    }\n    console.log(\"added avg: \", addedAvg);\n    \/\/ end: Calculate with a single price\/quantity value\n\n    const avg = getAveragePrice(transactions, fee);\n\n    const rjust = (s, width, c = \" \") =>\n        s.length &lt; width ? c.slice(0, 1).repeat(width - s.length) + s : s;\n    const display = (n) => rjust(Number(n).toFixed(3), 12);\n\n    console.log(`own:           ${display(avg.quantity)}`);\n    console.log(`price:       $ ${display(avg.avgPrice * avg.quantity)}`);\n    console.log(`price\/share: $ ${display(avg.avgPrice)}`);\n})();\n\/* RESULT:\nown:               1050.000\nprice:       $      885.807\nprice\/share: $        0.844\n*\/<\/pre><\/div>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Keywords: Crypto, Stock<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[5,4,1],"tags":[],"class_list":["post-5445","post","type-post","status-publish","format-standard","hentry","category-javascript","category-programming","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/5445","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/comments?post=5445"}],"version-history":[{"count":11,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/5445\/revisions"}],"predecessor-version":[{"id":6371,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/5445\/revisions\/6371"}],"wp:attachment":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/media?parent=5445"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/categories?post=5445"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/tags?post=5445"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}