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."
I just decided to start using GnuCash today, and I was also stuck in this position for around an hour before I figured out what to do exactly. The answer by @jldugger pointed me partially on the right track, so this answer is intended to help people waste less time in the future.  (Note: All numbers have been redacted for privacy issues, but I hope the images are sufficient to allow you to understand what is going on. ) Upon successfully importing your transactions, you should be able to see your transactions in the Checking Account and Savings Account (plus additional accounts you have imported). The Imbalance account (GBP in my case) will be negative of whatever you have imported. This is due to the double-entry accounting system that GnuCash uses.    Now, you will have to open your Savings Account.   Note that except for a few transactions, most of them are going to Imbalance. These are marked out with the red rectangles.   What you have to do, now, is to click on them individually and sort them into the correct account. Unfortunately (I do not understand why they did this), you cannot move multiple transactions at once. See also this thread. Fortunately, you only have to do this once.  This is what your account should look like after it is complete.   After this is done, you should not have to move any more accounts, since you can directly enter the transactions in the Transfer box. At this point, your Accounts tab should look like this:  Question solved! Outside of software that can calculate the returns:  You could calculate your possible returns on that leap spread as you ordinarily would, then place the return results of that and the return results for the covered call position side by side for any given price level of the stock you calculate, and net them out. (Netting out the dollar amounts, not percentage returns.)  Not a great answer, but there ya go. Software like OptionVue is expensive I have found a good explanation here: http://www.contracts-for-difference.com/Financing-charge.html Financing is calculated by taking the overall position size, and multiplying it by (LIBOR + say 2%) and then dividing by 365 x the amount of days the position is open. For instance, the interest rate applicable for overnight long positions may be 6% or 0.06. To calculate how much it would cost you to hold a long position for X number of days you would need to make this 'pro rata' meaning that you would need to divide the 0.06 by 365 and multiply it by X days and then multiply this by the trade size. So for example, for a trade size of $20,000, held for 30 days, the interest cost would be about $98.6. It is important to note that due to financing, long positions held for extended periods can reduce returns. "Standard deviation from Wikipedia : In statistics and probability theory, the standard deviation   (represented by the Greek letter sigma, σ) shows how much variation or   dispersion from the average exists.1 A low standard deviation   indicates that the data points tend to be very close to the mean (also   called expected value); a high standard deviation indicates that the   data points are spread out over a large range of values. In the case of stock returns, a lower value would indicate less volatility while a higher value would mean more volatility, which could be interpreted as high much change does the stock's price go through over time. Mean would be interpreted as if all the figures had to be the same, what would they be? So if a stock returns 10% each year for 3 years in a row, then 10% would be the mean or average return. Now, it is worth noting that there are more than a few calculations that may be done to derive a mean. First, there is the straight forward sum and division by the number of elements idea. For example, if the returns by year were 0%, 10%, and 20% then one may take the sum of 30% and divide by 3 to get a simple mean of 10%. However, some people would rather look at a Compound Annual Growth Rate which in this case would mean multiplying the returns together so 1*(1+.1)*(1+.2)=1.1*1.2=1.32 or 32% since there is some compounding here. Now, instead of dividing a cubic root is taken to get approximately 9.7% average annual return that is a bit lower yet if you compound it over 3 years it will get up to 32% as 10% compounded over 3 years would be 33.1% as (1.1)^3=1.331. Sharpe Ratio from Investopedia: A ratio developed by Nobel laureate William F. Sharpe to measure   risk-adjusted performance. The Sharpe ratio is calculated by   subtracting the risk-free rate - such as that of the 10-year U.S.   Treasury bond - from the rate of return for a portfolio and dividing   the result by the standard deviation of the portfolio returns. Thus, this is a way to think about given the volatility how much better did the portfolio do than the 10 year bond. R-squared, Alpha and Beta: These are all around the idea of ""linear regression"" modelling. The idea is to take some standard like say the ""S & P 500"" in the case of US stocks and see how well does the portfolio follow this and what if one were to use a linear model are the multipliers and addition components to it. R-squared can be thought of it as a measure as to how good is the fit on a scale of 0 to 1. An S & P 500 index fund may well have an R-squared of 1.00 or 0.99 to the index as it will track it extremely closely while other investments may not follow that well at all. Part of modern portfolio theory would be to have asset classes that move independently of each other and thus would have a lower R-squared so that the movement of the index doesn't indicate how an investment will do. Now, as for alpha and beta, do you remember the formula for a line in slope-intercept form, where y is the portfolio's return and x is the index's return: y=mx+b In this situation m is beta which is the multiple of the return, and b is the alpha or how much additional return one gets without the multiple. Going back to an index fund example, m will be near 1 and b will be near 0 and there isn't anything being done and so the portfolio's return computed based on the index's return is simply y=x. Other mutual funds may try to have a high alpha as this is seen as the risk-free return as there isn't the ups and downs of the market here. Other mutual funds may go for a high beta so that there is volatility for investors to handle." "From what I have read from O'Neil to Van Tharp, etc, etc, no one can pick winners more than 75% of the time regardless of the system they use and most traders consider themselves successful if 60% of the trades are winners and 40% are losers.  So I am on the side that the chart is only a reflection of the past and cannot tell you reliably what will happen in the future. It is difficult to realize this but here is a simple way for you to realize it. If you look at a daily chart and let's say it is 9:30 am at the open and you ask a person to look at the technical indicators, look at the fundamentals and decide the direction of the market by drawing the graph, just for the next hour. He will realize in just a few seconds that he will say to him or her self ""How on earth do you expect me to be able to do that?""  He will realize very quickly that it is impossible to tell the direction of the market and he realizes it would be foolhardy to even try. Because Mickey Mantle hit over 250 every year of his career for the first 15 years it would be a prudent bet to bet that he could do it again over the span of a season, but you would be a fool to try to  guess if the next pitch would be a ball or a strike. You would be correct about 50% of the time and wrong about 50% of the time. You can rely on LARGER PATTERNS OF BEHAVIOR OVER YEARS, but short hourly or even minute by minute prediction is foolish. That is why to be a trader you have to keep on trading and if you keep on trading and cut your losses to 1/2 of your wins you will eventually have a wonderful profit.  But you have to limit your risk on any one trade to 1% of your portfolio.  In that way you will be able to trade at least 100 times.  do the math.  trade a hundred times.  lose 5% and the next bet gain 10%.  Keep on doing it. You will have losses sometimes of 3 or 4 in a row and also wins sometimes of 3 or 4 in a row but overall if you keep on trading even the best traders are generally only ""right"" 60% of the time.  So lets do the math. If you took 100 dollars and make 100 trades and the first trade you made 10% and reinvested the total and the second trade you lost 5% of that and continue that win/loss sequence for 100 trades you would have 1284 dollars minus commissions. That is a 1200% return in one hundred trades.  If you do it in a roth IRA you pay no taxes on the short term gains.  It is not difficult to realize that the stock market DOES TREND. And the easiest way to make 10% quickly is to in general trade 3x leveraged funds or stocks that have at least 3 beta from the general index.  Take any trend up and count the number of days the stock is up and it is usually 66-75% and take any down trend and it is down 66-75% of the days.  So if you bet on the the beginning of a day when the stock was up and if you buy the next day about 66-75% of the time the stock will also be up. So the idea is to realize that 1/3 of the time at least you will cut your losses but 2/3 of the time you will be up then next day as well.  So keep holding the position based on the low of the previous day and as the stock rises to your trend line then tighten the stock to the low of the same day or just take your profit and buy something else.  But losing 1/3 times is just part of ""the unpredictable"" nature of the stock market which is causes simply because there are three types of traders all betting at the same time on the same stock.  Day traders who are trading from 1 to 10 times a day, swing traders trading from 1 day to several weeks and buy and hold investors holding out for long term capital gains. They each have different price targets and time horizons and THAT DIFFERENCE is what makes the market move.  ONE PERSON'S SHORT TERM EXIT PRICE AT A PROFIT IS ANOTHER PERSONS LONG TERM ENTRY POINT and because so many are playing at the same time with different time horizons, stop losses and exit targets it is impossible to draw the price action or volume.  But it is possible to cut your losses and ride your winners and if you keep on doing that you have a very fine return indeed." Thanks for the answer/comments! The time-based method was something we mooted and something I almost went with. But just to wrap this up, the method we settled on was this: Every time there is an entry or exit into the fund, we divvy out any unrealised market profits/losses according to each person's profit share (based on % of the asset purchased at buy-in) JUST BEFORE the entry/exit. These realised profits are then locked in for those particpants, and then the unrealised profits/loss counter starts at zero, we do a fresh recalculation of shareholding after the entry/exit, and then we start again. Hope this helps anyone with the same issue! Assuming you were immersed in math with your CS degree, the book **'A Non-Random Walk Down Wall Street' by Andrew Lo** is a very interesting book about the random walk hypothesis and it's application to financial markets and how efficient markets might not necessarily imply complete randomness.    Lots of higher level concepts in the book but it's an interesting topic if you are trying to branch out into the quant world.  The book isn't very specific towards algorithmic trading but it's good for concept and ideas.  Especially for general finance, that will give you a good run down about markets and the way we tackle modern finance.    **A Random Walk Down Wall Street** (which the book above is named after) by **Burton Malkiel** is also supposed to be a good read and many have suggested reading it before the one I listed above, but there really isn't a need to do so.    For investing specifically, many mention **'The Intelligent Investor' by Benjamin Graham** who is the role model for the infamous Warren Buffet.  It's an older book and really dry and I think kind of out dated but mostly still relevant.  It's more specifically about individual trading rather than markets as a whole or general markets.  It sounds like you want to learn more about markets and finance rather than simply trading or buying stocks.  So I'd stick to the Andrew Lo book first.    ---  Also, since you might not know, it would be a good idea to understand the capital asset pricing model, free cash flow models, and maybe some dividend discount models, the last of which isn't so much relevant but good foundations for your finance knowledge.  They are models using various financial concepts (TVM is almost used in every case) and utilizing them in various ways to model certain concepts.  You'd most likely be immersed in many of these topics by reading a math-oriented Finance book.  Try to stay away from those penny stock trading books, I don't think I need to tell a math major (who is probably much smarter than I am) that you don't need to be engaging in penny stocks, but do your DD and come to a conclusion yourself if you'd like.  I'm not sure what career path you're trying to go down (personal trading, quant firm analyst, regular analyst, etc etc) but it sounds like you have the credentials to be doing quant trading.    ---  Check out www.quantopian.com.  It's a website with a python engine that has all the necessary libraries installed into the website which means you don't have to go through the trouble yourself (and yes, it is fucking trouble--you need a very outdated OS to run one of the libraries).  It has a lot of resources to get into algorithmic trading and you can begin coding immediately.  You'd need to learn a little bit of python to get into this but most of it will be using matplotlib, pandas, or some other library and its own personal syntax. Learning about alpha factors and the Pipeline API is also moderately difficult to get down but entirely possible within a short amount of dedicated time.     Also, if you want to get into algorithmic trading, check out Sentdex on youtube.  He's a python programmer who does a lot of videos on this very topic and has his own tool on quantopian called 'Sentiment Analyzer' (or something like that) which basically quantifies sentiment around any given security using web scrapers to scrape various news and media outlets.  Crazy cool stuff being developed over there and if you're good, you can even be partnered with investors at quantopian and share in profits.    You can also deploy your algorithms through the website onto various trading platforms such as Robinhood and another broker and run your algorithms yourself.    Lots of cool stuff being developed in the finance sector right now.  Modern corporate finance and investment knowledge is built on quite old theorems and insights so expect a lot of things to change in today's world.  ---  With a math degree, finance should be like algebra I back in the day.  You just gotta get familiar with all of the different rules and ideas and concepts.  There isn't that much difficult math until you begin getting into higher level finance and theory, which mostly deals with statistics anyways like covariance and regression and other statistic-related concepts.  Any other math is simple arithmetic. "The wash sale rule only applies when the sale in question is at a loss.  So the rule does not apply at all to your cases 3, 4, 7, 8, 11, 12, 15, and 16, which all start with a gain.  You get a capital gain at the first sale and then a separately computed gain / loss at the second sale, depending on the case, BUT any gain or loss in the IRA is not a taxable event due to the usual tax-advantaged rules for the IRA. The wash sale does not apply to ""first"" sales in your IRA because there is no taxable gain or loss in that case.  That means that you wouldn't be seeking a deduction anyway, and there is nothing to get rolled into the repurchase. This means that the rule does not apply to 1-8.  For 5-8, where the second sale is in your brokerage account, you have a ""usual"" capital gain / loss as if the sale in the IRA didn't happen. (For 1-4, again, the second sale is in the IRA, so that sale is not taxable.) What's left are 9-10 (Brokerage -> IRA) and 13-14 (Brokerage -> Brokerage).   The easier two are 13-14.  In this case, you cannot take a capital loss deduction for the first sale at a loss.  The loss gets added to the basis of the repurchase instead.  When you ultimately close the position with the second sale, then you compute your gain or loss based on the modified basis.  Note that this means you need to be careful about what you mean by ""gain"" or ""loss"" at the second sale, because you need to be careful about when you account for the basis adjustment due to the wash sale. Example 1: All buys and sells are in your brokerage account.  You buy initially at $10 and sell at $8, creating a $2 loss.  But you buy again within the wash sale window at $9 and sell that at $12.  You get no deduction after the first sale because it's wash.  You have a $1 capital gain at the second sale because your basis is $11 = $9 + $2 due to the $2 basis adjustment from wash sale. Example 2: Same as Example 1, except that final sale is at $8 instead of at $12.  In this case you appear to have taken a $2 loss on the first buy-sell and another $1 loss on the second buy-sell.  For taxes however, you cannot claim the loss at the first sale due to the wash.  At the second sale, your basis is still $11 (as in Example 1), so your overall capital loss is the $3 dollars that you might expect, computed as the $8 final sale price minus the $11 (wash-adjusted) basis. Now for 9-10 (Brokerage->IRA), things are a little more complicated.  In the IRA, you don't worry about the basis of individual stocks that you hold because of the way that tax advantages of those accounts work.  You do need to worry about the basis of the IRA account as a whole, however, in some cases.  The most common case would be if you have non-deductable contributions to your traditional IRA.  When you eventually withdraw, you don't pay tax on any distributions that are attributable to those nondeductible contributions (because you already paid tax on that part).  There are other cases where basis of your account matters, but that's a whole question in itself - It's enough for now to understand 1. Basis in your IRA as a whole is a well-defined concept with tax implications, and 2. Basis in individual holdings within your account don't matter. So with the brokerage-IRA wash sale, there are two questions:  1. Can you take the capital loss on the brokerage side?  2. If no because of the wash sale, does this increase the basis of your IRA account (as a whole)?  The answer to both is ""no,"" although the reason is not obvious. The IRS actually put out a Special Bulletin to answer the question specifically because it was unclear in the law. Bottom line for 9-10 is that you apparently are losing your tax deduction completely in that case. In addition, if you were counting on an increase in the basis of your IRA to avoid early distribution penalties, you don't get that either, which will result in yet more tax if you actually take the early distribution. In addition to the Special Bulletin noted above, Publication 550, which talks about wash sale rules for individuals, may also help some."