Skip to content

Instantly share code, notes, and snippets.

@MattGoldwater
Created May 4, 2020 20:22
Show Gist options
  • Save MattGoldwater/40564e35dee892a5291630ceb00b3e76 to your computer and use it in GitHub Desktop.
Save MattGoldwater/40564e35dee892a5291630ceb00b3e76 to your computer and use it in GitHub Desktop.
// tax lot - each group of purchases
// long term, what price you bought at
//portfolio of tax lots
// relief fifo, lifo, least tax liability, highest cost
// sellList array of objects
// return new portfolio
// highest cost
function highestCostRelief(portfolio, sellList) {
portfolio.sort((a,b) => {
if (a.price > b.price) {
return -1;
}
return 1;
})
const sharesToSell = {}
sellList.forEach((item) => {
sharesToSell[item.ticker] = (sharesToSell[item.ticker] || 0) + item.shares
})
portfolio.forEach((item) => {
if (sharesToSell[item.ticker] > item.shares) {
sharesToSell[item.ticker] -= item.shares;
item.shares = 0;
} else if (sharesToSell[item.ticker] <= item.shares) {
item.shares -= sharesToSell[item.ticker];
sharesToSell[item.ticker] = 0;
}
})
}
function changePortfolio (portfolio, relief, sellList) {
const reliefMethods = {
highestCost: highestCostRelief
}
if (reliefMethods[relief]) {
highestCostRelief(portfolio, sellList)
}
return portfolio;
}
const portfolio = [
{ticker: 'goog', price: 500, shares: 10, date: '05/13/2019'},
{ticker: 'app', price: 1000, shares: 100, date: '04/03/2020'},
{ticker: 'goog', price: 400, shares: 20, date: '04/04/2020'},
{ticker: 'app', price: 2000, shares: 50, date: '04/03/2020'},
]
console.log(changePortfolio(portfolio, 'highestCost', [{ticker: 'goog', shares: 13}, {ticker: 'app', shares: 70}, {ticker: 'goog', shares: 1}]));
// [ { ticker: 'app', price: 2000, shares: 0, date: '04/03/2020' }, { ticker: 'app', price: 1000, shares: 80, date: '04/03/2020' }, { ticker: 'goog', price: 500, shares: 0, date: '05/13/2019' }, { ticker: 'goog', price: 400, shares: 16, date: '04/04/2020' } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment