Skip to main content

Compute cost basis of stocks with FIFO method in Google Sheets

After selling a portion of my holdings in a stock, the cost basis for the remain shares of that stock in my portfolio is not simply the sum of all transactions. When selling, I need to decide which shares I want to sell. One of the most common accounting methods is FIFO (first in, first out), meaning that the shares I bought earliest will be the shares I sell first.

As you might already know, I use Google Sheets extensively to manage my stock portfolio investment, but, at the moment of writing this post, I find that Google Sheets does not provide a built-in formula for FIFO. Luckily, with lots of effort, I succeeded in building my own FIFO solution in Google Sheets, and I want to share it on this blog.

In this post, I explain how to implement FIFO method in Google Sheets to compute cost basis in stocks investing.

FIFO function in Google Sheets

FIFO example

Firstly, I present an FIFO example to clarify the concept of this method and to use it later as test case for my FIFO formula.

Let's assume that I have bought and sold several time stocks of TotalEnergies SE (EPA:TTE). The table below presents my transactions for TotalEnergies stock.

DateTypeSymbolAmountShares
26/11/2021BUYEPA:TTE-494.2612
19/08/2021BUYEPA:TTE-404.0911
30/04/2021BUYEPA:TTE-479.5513
23/03/2021BUYEPA:TTE-477.1712
05/02/2021BUYEPA:TTE-499.9914
07/10/2020BUYEPA:TTE-496.4717
18/09/2020BUYEPA:TTE-474.8515
06/07/2020BUYEPA:TTE-57.602
04/05/2020BUYEPA:TTE-489.8516
02/04/2020SELLEPA:TTE483.76-13
24/03/2020SELLEPA:TTE482.51-17
18/03/2020BUYEPA:TTE-479.4220
12/03/2020BUYEPA:TTE-476.3517
24/02/2020BUYEPA:TTE-471.4411
03/10/2019BUYEPA:TTE-497.7011
09/05/2018SELLEPA:TTE468.35-9
02/02/2018BUYEPA:TTE-421.809

I use a spreadsheet on Google Sheets to keep track of my stock portfolio's transactions. I insert a new transaction into the spreadsheet whenever I deposit money, withdraw money, use deposited money to buy stocks, receive money by selling stocks, and receive dividends by holding stocks. Each transaction is a row containing information about Date, Type, Symbol, Amount and Shares of that transaction. For further details, you should read my post Manage stock transactions with Google Sheets.

If I use the average method, dividing the total amount (4785.92 €) by the total number of shares (141), the unit cost for TotalEnergies stock in my portfolio is: 4785.92 / 141 = 33.94 €. However, in this case, the shares I bought first always have an impact on my current unit cost. This might raise some issues, especially in the case of long-term investment during which a stock can have a significant price change and I make many transactions (BUY and SELL) on that stock.

If I apply the FIFO accounting method, the shares I bought earliest will be the shares I sell first and the sold shares will not have any more impact on my current unit cost price. The table below shows the result of applying FIFO accounting method after each transaction. In this case, my current unit cost is actually 4605.44 / 141 = 32.66 € that is better than 33.94 € with the everage method above. Why that? That's because I have made some losses on some transactions but those losses are closed up and will not show up in the current situation.

DateTypeSymbolAmountSharesTransaction UnitRemaining SharesCost of remainingCost of soldRealized gain
26/11/2021BUYEPA:TTE-494.2612-41.191414605.440.00
19/08/2021BUYEPA:TTE-404.0911-36.741294111.180.00
30/04/2021BUYEPA:TTE-479.5513-36.891183707.090.00
23/03/2021BUYEPA:TTE-477.1712-39.761053227.540.00
05/02/2021BUYEPA:TTE-499.9914-35.71932750.370.00
07/10/2020BUYEPA:TTE-496.4717-29.20792250.380.00
18/09/2020BUYEPA:TTE-474.8515-31.66621753.910.00
06/07/2020BUYEPA:TTE-57.62-28.80471279.060.00
04/05/2020BUYEPA:TTE-489.8516-30.62451221.460.00
02/04/2020SELLEPA:TTE483.76-13-37.2129731.61438.46922.22
24/03/2020SELLEPA:TTE482.51-17-28.38421170.06754.851237.36
18/03/2020BUYEPA:TTE-479.4220-23.97591924.910.00
12/03/2020BUYEPA:TTE-476.3517-28.02391445.490.00
24/02/2020BUYEPA:TTE-471.4411-42.8622969.140.00
03/10/2019BUYEPA:TTE-497.711-45.2511497.700.00
09/05/2018SELLEPA:TTE468.35-9-52.0400.00421.80890.15
02/02/2018BUYEPA:TTE-421.89-46.879421.800.00

On the 02/02/2018, I bought 9 shares of TotalEnergies SE (EPA:TTE) then sold them all on 09/05/2018. After these 2 transactions, it's straightforward that I didn't own any more the stock and the cost of sold for 9 shares were exactly the amount that I bought them from the first place.

From 03/10/2019 until 18/03/2020, I bought 4 times shares of TotalEnergies SE (EPA:TTE) at 4 different prices (45.25 €; 42.86 €; 28.02 €; 23.97€). The cost of remaining after each of these transactions does not involve the first 2 transactions because they were closed up with the FIFO method. After the 4 BUY transactions, I had 59 shares at the cost of 1924.91€ that are both the sums of the 4 transactions.

On the 24/03/2020, I sold a 17 shares of TotalEnergies SE (EPA:TTE) but at how much cost? By applying the FIFO method, I break down the 17 shares into 2 groups:

  • The first 11 shares belong to the BUY transaction on the 03/10/2019, therefore, it costs me 497.70
  • The next 6 shares belong to the BUY transaction on the 24/02/2020, therefore, it costs me 471.44 / 11 * 6 = 257.15€
  • Totally, the 17 shares costs me 497.70 + 257.15 = 754.85€
  • After this sale, I still had 59 - 17 = 42 shares, of which
    • 5 shares were bought on 24/02/2020 for total of 471.44 / 11 * 5 = 214.29€
    • 17 shares were bought on 12/03/2020 for total of 476.35€
    • 20 shares were bought on 18/03/2020 for total of 479.42€
    • Totally, the 42 shares remaining costs me 1170.06€

By following the same analysis with FIFO method, I can compute all the remaining quantities, cost of remaining, cost of sold, etc. after every transaction.

How to do FIFO in Google Sheets

At the moment of writing this post, I find that Google Sheets does not support an out-of-the-box formula for FIFO accounting. However, with Apps Script, it is possible to extend Google Sheets with new custom formulas. My rule of thumb when working with Google Sheets is that: what is not available by default, I will find a solution with Apps Script.

I write an Apps Script function named FIFO accepting 2 parameters:

  • The first one is a list of amounts of transactions ordered by time ascending.
  • The second is a list of quantities of transactions ordered by time ascending.

This FIFO functions returns:

  • The remaining quantities after the last transaction
  • The cost of remaining after the last transaction
  • The cost of goods sold for the last transaction if it is a SELL transaction

In the world of programming, when we talk about FIFO, we think of a queue. In my FIFO implementation, I use a queue to store the unit costs of shares. Each element in the queue represents a share and each share is associated with its unit cost.

I iterate every transaction from the oldest to the latest:

  • If it is a BUY transaction, I push shares to the back of the queue.
  • If it is a SELL transaction, I remove shares at the front of the queue. The sum of all removed shares is actually the cost of goods sold for this SELL transaction.

At the end of the iteration:

  • The length of the queue is actually the number of remaining shares.
  • The sum of the queue is actually the cost of remaining.

How to use FIFO formula in Google Sheets

This FIFO function written in Apps Script is available for use in Google Sheets as same as any other built-in formulas.

Simple usage

Here is how I use the FIFO formula in Google Sheets for the first 2 transactions 02/02/2018 and 09/05/2018.

=FIFO({-421.8;468.35},{9;-9})

Here is how I use the FIFO formula in Google Sheets for the first 7 transactions from 02/02/2018 until 24/03/2020.

=FIFO({-421.8;468.35;-497.7;-471.44;-476.35;-479.42;482.51},{9;-9;11;11;17;20;-17})

If I have the amounts on column D and the quantities on column E, both already ordered ascending by time, I can use the FIFO formula in Google Sheets as:

=FIFO(D2:D10, E2:E10)

Use FIFO with QUERY formula

As I have a dedicated Transactions sheet for registering my transactions, I can apply the FIFO method for any stock on any specific date by combining it with the QUERY formula.

The idea is to use the QUERY formula to extract transactions by stock and by date, then sort them ascending by time.

Here is an example of using the FIFO formula with the QUERY formula in Google Sheets:

=FIFO(QUERY(Transactions!A:E,"select D where C='EPA:CS' and B!='DIVIDEND' and A <= date '2020-03-24' order by A asc",0), QUERY(Transactions!A:E,"select E where C='EPA:CS' and B!='DIVIDEND' and A <= date '2020-03-24' order by A asc",0))

Demo

You can take a look and make a copy of the spreadsheet: FIFO with Google Sheets to getting started.

How to use FIFO function in Google Sheets

Conclusion

In this post, I have explained how to apply FIFO formula in Google Sheets to compute cost basis of a stock portfolio investment. The process involves writing the FIFO function with Apps Script and then use it as a normal formula in Google Sheets. The FIFO formula returns the remaining quantities, the cost of goods sold and the cost of remaining after the last transaction.

Comments

People also enjoyed…

Create personal stock portfolio tracker with Google Sheets and Google Data Studio

I have been investing in the stock market for a while. I was looking for a software tool that could help me better manage my portfolio, but, could not find one that satisfied my needs. One day, I discovered that the Google Sheets application has a built-in function called GOOGLEFINANCE which fetches current or historical prices of stocks into spreadsheets. So I thought it is totally possible to build my own personal portfolio tracker with Google Sheets. I can register my transactions in a sheet and use the pivot table, built-in functions such as GOOGLEFINANCE, and Apps Script to automate the computation for daily evolutions of my portfolio as well as the current position for each stock in my portfolio. I then drew some sort of charts within the spreadsheet to have some visual ideas of my portfolio. However, I quickly found it inconvenient to have the charts overlapped the table and to switch back and forth among sheets in the spreadsheet. That's when I came to know the existen

Use SPARKLINE to create 52-week range price indicator chart for stocks in Google Sheets

The 52-week range price indicator chart shows the relative position of the current price compared to the 52-week low and the 52-week high price. It visualizes whether the current price is closer to the 52-week low or the 52-week high price. In this post, I explain how to create a 52-week range price indicator chart for stocks by using the SPARKLINE function and the GOOGLEFINANCE function in Google Sheets. Concept Demo Conclusion Concept With the GOOGLEFINANCE function, it's possible to retrieve the current price, the 52-week low price, and the 52-week high price of a stock by using the below formulas: =GOOGLEFINANCE("AAPL") returns the latest price of APPLE stock =GOOGLEFINANCE("AAPL","low52") returns the 52-week low price of APPLE stock =GOOGLEFINANCE("AAPL","high52") returns the 52-week high price of APPLE stock To measure the relative position of the current price compared to the 52-week low price and 52-wee

How to convert column index into letters with Google Apps Script

Although Google Sheets does not provide a ready-to-use function that takes a column index as an input and returns corresponding letters as output, we can still do the task by leveraging other built-in functions ADDRESS , REGEXEXTRACT , INDEX , SPLIT as shown in the post . However, in form of a formula, that solution is not applicable for scripting with Google Apps Script. In this post, we look at how to write a utility function with Google Apps Script that converts column index into corresponding letters. With the solution in the form of a formula , we don't even need to understand how column index and letters map each other. With apps script, we need to understand the mapping to come up with an algorithm. In a spreadsheet, columns are indexed alphabetically, starting from A. Obviously, the first 26 columns correspond to 26 alphabet characters, A to Z. The next 676 columns ( 26*26 ), from 27th to 702nd, are indexed with 2 letters. [AA, AB, ... AY, AZ], [BA, BB, ... BY, BZ],

How to copy data in Google Sheets as HTML table

I often need to extract some sample data in Google Sheets and present it in my blog as an HTML table. However, when copying a selected range in Google Sheets and paste it outside the Google Sheets, I only get plain text. In this post, I explain how to copy data in Google Sheets as an HTML table by writing a small Apps Script program. Concept Implementation Source Code Demo HTML table code HTML table visualization Getting Started Conclusion Concept On a spreadsheet, users select a range that they want to copy as HTML table. With the selected range, users trigger a command Copy AS HTML table . The command can be added to the toolbar, or to the contextual menu, or accessed via a keyboard shortcut. The command is executed to transform the selected range into HTML code for table. The HTML code can be added to the clipboard or can be displayed somewhere so users can copy it manually. The HTML table must consist of all displayed cells of the selected range and the widths

Stock Correlation Analysis With Google Sheets

Correlation is a statistical relationship that measures how related the movement of one variable is compared to another variable. For example, stock prices fluctuate over time and are correlated accordingly or inversely to one another. Understanding stock correlation and being able to perform analysis are very helpful in managing a stock portfolio investment. In this post, we will look at how to perform stock correlation analysis with Google Sheets. Understanding correlation and its applications in stock investing Stock correlation analysis with Google Sheets Getting started User guide Conclusion Understanding correlation and its applications in stock investing The most familiar correlation measure is the Pearson product-moment correlation coefficient . The strength of the relationship between two variables is expressed numerically between -1 and 1. For example: Two stocks are positively correlated when their prices always go up or go down together. Their coefficient

Create a dividend income tracker with Google Sheets by simply using pivot tables

As my investment strategy is to buy stocks that pay regular and stable dividends during a long-term period, I need to monitor my dividends income by stocks, by months, and by years, so that I can answer quickly and exactly the following questions: How much dividend did I receive on a given month and a given year? How much dividend did I receive for a given stock in a given year? Have a given stock's annual dividend per share kept increasing gradually over years? Have a given stock's annual dividend yield been stable over years? In this post, I explain how to create a dividend tracker with Google Sheets. Manage stock transactions with Google Sheets Create dividend tracker with Google Sheets Track annual dividend amount of stocks Track dividend amount by month and by year Track annual dividend per share of stocks Track annual dividend yield of stocks Demo Conclusion References Manage stock transactions with Google Sheets I use a spreadsheet on Goo

Stock Portfolio Tracker Dashboard With Google Data Studio

In the series of building personal stock portfolio tracker, we have learned how to use Google Sheets to register transactions . We have then used the pivot table and GOOGLEFINANCE function to compute the latest position of the stock portfolio . We have made a step further to use Apps Scripts to compute automatically and daily the stock portfolio's evolution . However, after all, we have several tables of data as the result which do not tell any story yet. We need to present those data in graphs to understand the portfolio's performance and make improvements accordingly. We can effectively plot graphs in different aspects directly in Google Sheets as it provides many charting tools. However, in my experience, having charts and data in the same spreadsheet is not very convenient because charts and tables tend to overlap each other and of lack of interactivity. We should have a dedicated dashboard to have an overview of the stock portfolio and we can do it greatly with Google Data

Monitor stock portfolio with Google Sheets (Pivot table and GOOGLEFINANCE function)

As an investor, it is important to know the latest state of the stock portfolio. We need to know what stocks currently owned in the portfolio, how many shares for each one, how much dividend or gain contributed so far by each stock, etc. As we have registered stock transactions in a spreadsheet with Google Sheets, we can easily have the latest update from the stock portfolio by using pivot tables and GOOGLEFINANCE function. Use a pivot table to group transactions by symbols Configure the pivot table Positions Use GOOGLEFINANCE function to get real-time information for stocks Conditional formatting columns Demo Note References Use a pivot table to group transactions by symbols The pivot table helps to see relationships between data points. To see how each stock contributes to the portfolio, we will create a pivot table that originated from the Transactions sheet. Select the Transactions sheet. Select the 5 columns A:E . In the menu at the top, click Data and then

Manage Stock Transactions With Google Sheets

The first task of building a stock portfolio tracker is to design a solution to register transactions. A transaction is an event when change happens to a stock portfolio, for instance, selling shares of a company, depositing money, or receiving dividends. Transactions are essential inputs to a stock portfolio tracker and it is important to keep track of transactions to make good decisions in investment. In this post, I will explain step by step how to keep track of stock transactions with Google Sheets. Define the structure of transactions Use Google Sheets to register transactions Demo Note References Define the structure of transactions In the example, I assume that a transaction generally has 5 main attributes: Date : It is the moment when a transaction happened. Type : It can be one of the following values: DEPOSIT : When money is added to the portfolio BUY : When money in the portfolio is used to buy shares of a company SELL : When money is added into

Demo stock portfolio tracker with Google Sheets

As explained in the post Create personal stock portfolio tracker with Google Sheets and Google Data Studio , a personal stock portfolio tracker consists of 2 main elements: a spreadsheet in Google Sheets and an interactive dashboard in Google Data Studio. You can take a look at the sample spreadsheet below to have an idea of how the data is organized and related. It is possible to make a copy of the spreadsheet to study it thoroughly. NOTE: An enhanced version was published at Create personal stock portfolio tracker with Google Sheets and Google Data Studio . Make a copy Note Disclaimer Make a copy Click here to make a copy Note To better understand the overall concept, please check out this post Create personal stock portfolio tracker with Google Sheets and Google Data Studio . Disclaimer The post is only for informational purposes and not for trading purposes or financial advice.