diff --git a/finance.js b/finance.js index bd7c954..ab41660 100644 --- a/finance.js +++ b/finance.js @@ -22,4 +22,23 @@ function payback_period(initial, flows = []) { return -1; } -module.exports = exports = { payback_period } \ No newline at end of file +/** + * Calculate the portfolio weights (roughtly) required to reach a target + * beta for a portfolio composed of 2 stocks, given their betas. + */ +function portfolio_weights(stock_a_beta, stock_b_beta, target_beta = 1, resolution = 0.0001) { + let stock_a_weight = 1 + let stock_b_weight = 0 + + let target = (a_w, b_w) => (stock_a_beta * a_w) + (stock_b_beta * b_w) + let roughly = value => (value < (target_beta + (2 * resolution))) && (value > (target_beta - (2 * resolution))) + while ( stock_a_weight >= 0 && !roughly(target(stock_a_weight, stock_b_weight)) ) { + stock_b_weight += resolution + stock_a_weight -= resolution + } + + if ( stock_a_weight < 0 ) return false + return { stock_a_weight, stock_b_weight } +} + +module.exports = exports = { payback_period, portfolio_weights }