Calculating return on a series of stock positions with multiple uneven transactions
"Generally if you are using FIFO (first in, first out) accounting, you will need to match the transactions based on the number of shares. In your example, at the beginning of day 6, you had two lots of shares, 100 @ 50 and 10 @ 52.  On that day you sold 50 shares, and using FIFO, you sold 50 shares of the first lot.  This leaves you with 50 @ 50 and 10 @ 52, and a taxable capital gain on the 50 shares you sold. Note that commissions incurred buying the shares increase your basis, and commissions incurred selling the shares decrease your proceeds.  So if you spent $10 per trade, your basis on the 100 @ 50 lot was $5010, and the proceeds on your 50 @ 60 sale were $2990.  In this example you sold half of the lot, so your basis for the sale was half of $5010 or $2505, so your capital gain is $2990 - 2505 = $485. The sales you describe are also ""wash sales"", in that you sold stock and bought back an equivalent stock within 30 days.  Generally this is only relevant if one of the sales was at a loss but you will need to account for this in your code.  You can look up the definition of wash sale, it starts to get complex. If you are writing code to handle this in any generic situation you will also have to handle stock splits, spin-offs, mergers, etc. which change the number of shares you own and their cost basis.  I have implemented this myself and I have written about 25-30 custom routines, one for each kind of transaction that I've encountered.  The structure of these deals is limited only by the imagination of investment bankers so I think it is impossible to write a single generic algorithm that handles them all, instead I have a framework that I update each quarter as new transactions occur."
Ok well in that case here are my thoughts.  Its been a while since I've done this type of school work so hope it's right/helpful.  AR Oustanding = Avg AR / (credit sales/Operating Cycle*) = 35   *I'm guessing they didn't give you sales for the year or else I would divide by 365 but since you mentioned operating cycle I'm assuming thats the sales number you were given.  So you want to divide the sales by 50 and then times it by the 35.  Should give you the average AR.  Inventory - I really don't remember having to calculate this so I'm just thinking logically here.  You should be able to take COGS divide by the days in the period then times it by In Invetory.  So = (COGS/Operating Cycle)* In Inventory = (COGS/50)*15  Accounts Payable....man, I'm afraid to drive you in the wrong direction on this one.  Avg Accounts Payable/(COGS/Operating Cycle) = 40  Plug in COGS, divide by the operating cycle, 50 then times by 40, the days vendor credit. i will not calculate it for you but just calculate the discounted cash flow (by dividing with 1.1 / 1.1^2 / 1.1^3   ...)of each single exercise as stated and deduct the 12.000 of the above sum.  in the end compare which has the highest npv Firstly 795 is not even. Secondly - generally you would pay tax on the sale of the 122 shares, whether you buy them back or not, even one minute later, has nothing to do with it. The only reason this would not create a capital gains event is if your country (which you haven't specified) has some odd rules or laws about this that I, and most others, have never heard of before. If annualized rate of return is what you are looking for, using a tool would make it a lot easier.   In the post I've also explained how to use the spreadsheet.   Hope this helps. Technically you should take the quarterly dividend yield as a fraction, add one, take the cube root, and subtract one (and then multiple by the stock price, if you want a dollar amount per share rather than a rate).  This is to account for the fact that you could have re-invested the monthly dividends and earned dividends on that reinvestment. However, the difference between this and just dividing by three is going to be negligible over the range of dividend rates that are realistically paid out by ordinary stocks. It depends to some extent on how you interpret the situation, so I think this is the general idea. Say you purchase one share at $50, and soon after, the price moves up, say, to $55. You now have an unrealized profit of $5. Now, you can either sell and realize that profit, or hold on to the position, expecting a further price appreciation. In either case, you will consider the price change from this traded price, which is $55, and not the price you actually bought at. Hence, if the price fell to $52 in the next trade, you have a loss of $3 on your previous profit of $5. This (even though your net P&L is calculated from the initial purchase price of $50), allows you to think in terms of your positions at the latest known prices. This is similar to a Markov process, in the sense that it doesn't matter which route the stock price (and your position's P&L) took to get to the current point; your decision should be based on the current/latest price level. To complement farnsy's answer, I want to warn people against market prediction scams. If they give uniformly distributed buy/sell predictions to 256 people, one of them will get eight correct predictions in a row. They are trading a few cents of Amazon server time for 3% of your capital. "Wow, this analysis really surprised me. Very complete and useful, but i think my teacher request was easier. He just said: ""Try to build a diversified portfolio. Then try to add a commodity (like silver or gold) and understand how the risk vary introducing an asset like this."" So, i'm basically making a stocks portfolio and i'm calculating its expected return and risk. (for example 40%FB, 10%JNJ, 20%GS, 10%F and 20%MCD) then i'm adding GLD (so now i have something like 20%FB, 10%JNJ, 10%GS, 10%F and 20%MCD 30%GLD) and i'm actually making an excel spreadsheet where i calculate all the: -Expected returns -St Deviation -Covariance  At the end i compare the returns and the risks on the 2 different portfolios." Annualize quarterly returns:      AR = (1+QR)^4  Where *QR* is a decimal return, e.g. 0.05.  Standard deviations are similar:      Annual SD = SD * sqrt(T)  If you have quarterly deviations, *T=4*, if you have daily, *T=252*, etc.  As an aside, for work with money riding on it, it is *not* okay to aggregate standard deviations if there's autocorrelation amongst observations at a smaller time scale. Volatility is often quoted this way and that's fine, but it is dangerous to do any sort of risk management with this and you'll require more due diligence. It's a good enough approximation for napkin math, though. "What you are seeking is termed ""Alpha"", the mispricing in the market. Specifically, Alpha is the price error when compared to the market return and beta of the stock. Modern portfolio theory suggests that a portfolio with good Alpha will maximize profits for a given risk tolerance. The efficient market hypotheses suggests that Alpha is always zero. The EMH also suggests that taxes, human effort and information propagation delays don't exist (i.e. it is wrong). For someone who is right, the best specific answer to your question is presented Ben Graham's book ""The Intelligent Investor"" (starting on page 280). And even still, that book is better summarized by Warren Buffet (see Berkshire Hathaway Letters to Shareholders). In a great disservice to the geniuses above it can be summarized much further: closely follow the company to estimate its true earnings potential... and ignore the prices the market is quoting. ADDENDUM: And when you have earnings potential, calculate value with: NPV = sum(each income piece/(1+cost of capital)^time) Update: See http://finance.fortune.cnn.com/2014/02/24/warren-buffett-berkshire-letter/ ""When Charlie Munger and I buy stocks..."" for these same ideas right from the horse's mouth" You'd need millions of dollars to trade the number of shares it would take to profit from these penny variations.  What you bring up here is the way high frequency firms front-run trades and profit on these pennies. Say you have a trade commission of $5.  Every time you buy you pay $5, every time you sell you pay $5.  So you need a gain in excess of $10, a 10% gain on $100.  Now if you wanted to trade on a penny movement from $100 to $100.01, you need to have bought 1,000 shares totaling $100,000 for the $0.01 price movement to cover your commission costs.  If you had $1,000,000 to put at risk, that $0.01 price movement would net you $90 after commission, $10,000,000 would have made you $990.  You need much larger gains at the retail level because commissions will equate to a significant percentage of the money you're investing. Very large trading entities have much different arrangements and costs with the exchanges.  They might not pay a fee on each transaction but something that more closely resembles a subscription fee, and costs something that more closely resembles a house. Now to your point, catching these price movements and profiting.  The way high frequency trading firms purportedly make money relates to having a very low latency network connection to a particular exchange.  Their very low latency/very fast network connection lets them see orders and transact orders before other parties.   Say some stock has an ask at $101 x 1,000 shares.  The next depth is $101.10.  You see a market buy order come in for 1,000 shares and place a buy order for 1,000 shares at $101 which hits the exchange first, then immediately place a sell order at $101.09, changing the ask from $101.00 to $101.09 and selling in to the market order for a gain of $0.09 per share. I’m going to answer this because: Accounting books only reflect the dollar value of inventories. Which means if you look at the balance sheet of McDonalds, you will not see how many bags of French fries are remaining at their storage facility, you will only see the total value at cost basis.  Your requirement for noting the number of shares purchased is not part of the double entry accounting system.  When you transfer $10000 from bank to broker, the entries would be:  The bank’s name and the broker’s name will not appear on the balance sheet.  When you purchase 50 shares at $40 per share, the accounting system does not care about the number of shares or the price. All it cares is the $2000 total cost and the commission of $10.  You have two choices, either place $10 to an expense account, or incorporate it into the total cost (making it $2010).  The entries for the second method would be: Now your balance sheet would reflect: What happens if the price increases from $40 per share to $50 per share tomorrow? Do nothing. Your balance sheet will show the cost of $2010 until the shares are sold or the accounting period ends. It will not show the market value of $2500.  Instead, the Portfolio Tracker would show $2500. The most basic tracker is https://www.google.com/finance/portfolio .  Later if you finally sell the shares at $50 per share with $10 commission: Again, the number of shares will not be reflected anywhere in the accounting system. Only the total proceeds from the sale matters. Generally speaking.  1. Take the position size / average daily volume.  2. Multiply that number by 10 or whatever 1/whatever % of volume you think you can execute, ( you can at best acct for 10 percent of traded volume on a day).  3. You now have days until liquidation (x)  4. Take the days until liquidation sample the return over  time x. I.e. if days until liquidation is 10, you would sample 10 day returns.  5. Calculate the distribution characteristics of this window (mean, var, skew, kurt) and calculate VaR based on some confidence.  You can now have a liquidity risk expected loss and a VaR.  If position is on margin don't forget to add the interest cost.  Note: Instead of taking 10 day return, you can take the 10 day VWAP and calculate return between Open and 10 day vwap. You have only sold 200 shares for $4.75 from those bought for $3.15. So your profit on those 200 shares is $1.60 per share or $320 or 51%. From that you have 110 shares left that cost you $3.15 and 277 shares that cost you $3.54. So the total cost of your remaining shares is $1,327.08 (110 x $3.15 + 277 x $3.54). So your remaining shares have a average cost of $3.429 per share ($1,327.08/387). We don't know what the current share price is as you haven't provided it, nor do we know what the company is, so lets say that the current price is $5 (or that you sell the remaining 387 shares for $5 per share). Then the profit on these 387 shares would be $1.571 per share or $607.92 or 46%. Your total profit would then be $320 + $ 607.92 = $927.92 or 47% (note that this profit neglects any brokerage or other fees, as you have not provided any). Edit due to new info. provided in question With the current share price at $6.06 then the profit on these 387 shares would be $2.631 per share or $1018.20 or 77%. Your total profit would then be $320 + $1018.20 = $1338.20 or 75% (note that this profit neglects any brokerage or other fees, as you have not provided any). Don't let tax considerations be the main driver. That's generally a bad idea. You should keep tax in mind when making the decision, but don't let it be the main reason for an action. selling the higher priced shares (possibly at a loss even) - I think   it's ok to do that, and it doesn't necessarily have to be FIFO? It is OK to do that, but consider also the term. Long term gain has much lower taxes than short term gain, and short term loss will be offsetting long term gain - means you can lose some of the potential tax benefit. any potential writeoffs related to buying a home that can offset capital gains? No, and anyway if you're buying a personal residence (a home for yourself) - there's nothing to write off (except for the mortgage interest and property taxes of course). selling other investments for a capital loss to offset this sale? Again - why sell at a loss? anything related to retirement accounts? e.g. I think I recall being able to take a loan from your retirement account in order to buy a home You can take a loan, and you can also withdraw up to 10K without a penalty (if conditions are met). Bottom line - be prepared to pay the tax on the gains, and check how much it is going to be roughly. You can apply previous year refund to the next year to mitigate the shock, you can put some money aside, and you can raise your salary withholding to make sure you're not hit with a high bill and penalties next April after you do that. As long as you keep in mind the tax bill and put aside an amount to pay it - you'll be fine. I see no reason to sell at loss or pay extra interest to someone just to reduce the nominal amount of the tax. If you're selling at loss - you're losing money. If you're selling at gain and paying tax - you're earning money, even if the earnings are reduced by the tax.