Skip to main content

Compute daily evolutions of a stock portfolio with Google Sheets and Apps Script

When it comes to investment, it is not only important to know the up-to-date state of portfolio but also to track its evolution day by day. We need to know on a specific day, how much money has been invested in the portfolio, the current market value of owned shares, the available cash and the current profit. Visualizing those historical data points on a time-based graph helps us to identify which transactions were good and which were bad. This post shows how to compute automatically those historical data points by using data in Transactions sheet and the built-in GOOGLEFINANCE function of Google Sheets. A sample spreadsheet can be found in this post Demo stock portfolio tracker with Google Sheets. You can take a look at the sample spreadsheet 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.

Compute daily evolutions of a stock portfolio with Google Sheets and Apps Script

Concept

We need to compute daily historical data points for the portfolio from its first transaction date until today. A data point consists of:

  • Date: Run from the first transaction date until today
  • Invested Money: The amount of DEPOSIT money minus the amount of WITHDRAW money so far until that date
  • Cash: The amount of money available in the portfolio that can be used to buy more shares
  • Market Value: The value of current owned shares based on their closing prices on that date
  • Portfolio Value: The sum of Market Value and Cash
  • Gain: The difference between Portfolio Value and Invested Money

As every transaction is registered, it is easy to know on a specific day:

  • Invested Money: It is the sum of the amount of DEPOSIT and WITHDRAW transactions until the date.
  • Cash: It is the sum of the amount of all transactions until the date.
  • The number of shares for a given stock: It is the sum of shares of BUY and SELL transactions for that stock until the date.
Date Type Symbol Amount Shares
15/01/2018 DEPOSIT 1,000.00
25/01/2018 BUY EPA:SEV -495.71 42
24/02/2018 DEPOSIT 300
26/03/2018 DEPOSIT 300
25/04/2018 DEPOSIT 400
04/05/2018 BUY EPA:MMT -354.6 17
11/05/2018 BUY EPA:MMT -488.24 24
16/05/2018 DIVIDEND EPA:MMT 38.95 41
22/05/2018 DIVIDEND EPA:SEV 27.3 42
21/06/2018 DEPOSIT 400
21/07/2018 DEPOSIT 400
20/08/2018 DEPOSIT 400

For instance, with the transactions above, we can compute the position on the date 01/07/2018:

  • Only the first 11 transactions are used because they were executed before 01/07/2018.
  • Until 01/07/2018, we have deposited 5 times with total Invested Money of 2400.
  • Until 01/07/2018, we have spent 1338.55 to buy shares and have received 66.25 in terms of dividends. Totally, it remains 2400 - 1338.55 + 66.25 = 1127.70 in Cash.
  • On 01/07/2018, there were 2 stocks in the portfolio, with respectively: 41 shares for MMT and 42 shares for SEV.

The only missing parameters are closing prices for MMT and SEV on 01/07/2018. If we have those prices, we can know their Market Value on that date, and eventually the Portfolio Value as well as the Gain on that date

Fetch historical data with GOOGLEFINANCE

With GOOGLEFINANCE it is not only possible to get the latest price for stock but also to query its historical prices. For example, to fetch historical prices for MMT and SEV from the first transaction date of the portfolio, which is 15/01/2018, we can use the 2 functions below:

  • =GOOGLEFINANCE("EPA:SEV", "price", "15/01/2018", TODAY(), "DAILY")
  • =GOOGLEFINANCE("EPA:MMT", "price", "15/01/2018", TODAY(), "DAILY")

The result is presented in 2 columns, one is Date, the other is Close.

At this point, we have found the missing parameters in order to finish the computation for the position of the portfolio on 01/07/2018.

  • On 01/07/2018, the close price for MMT was 17.13. The owned 41 shares worthed so 702.33.
  • On 01/07/2018, the close price for SEV was 11.11. The owned 42 shares worthed so 466.62.
  • On 01/07/2018, the Market Value was 702.33 + 466.62 = 1168.95
  • On 01/07/2018, the Portfolio Value was 1168.95 + 1127.70 = 2296.65
  • On 01/07/2018, the Gain was 2296.65 - 2400 = -103.35

Until this point, you might have already wondered that it requires a certain amount of detailed manual works in order to compute just only one position of the portfolio on 01/07/2018. In a long-term investment, it may involve many dates and maybe many different stocks, and nobody wants to spend precious time to calculate manually historical points of the portfolio.

Automate with Apps Script

Luckily, the Google Sheets provides script ability with Apps Script which allows the automation of process. The process we want to automate is computing daily evolutions of the portfolio from its first transaction date until today. The process consists of small sub-processes:

  • For each stock presented in the portfolio, create automatically a sheet named by the symbol of the stock to store its historical prices. For example, the sheet named EPA:SEV is created to store results of the function =GOOGLEFINANCE("EPA:SEV", "price", "15/01/2018", TODAY(), "DAILY").
  • Compute daily evolutions and store them in a sheet named Evolutions of 5 columns: Date, Invested Money, Cash, Market Value, Portfolio Value and Gain

To access Apps Script editor, you need to select the menu Tools then the item Script editor on the menu bar of the Google spreadsheet.

Open Apps Script editor from the menu of spreadsheet

Create a historical data sheet for each bought stock

We need to extract unique symbols from transactions and the very first transaction date.

The function extractSymbolsFromTransactions retrieves values from the column Symbol of the sheet Transactions, which is the column C starting from the 2nd row and eliminate all duplicates.

/** * Extract unique symbols from the Transactions sheets */ function extractSymbolsFromTransactions() { var spreadsheet = SpreadsheetApp.getActive() var transactionsSheet = spreadsheet.getSheetByName('Transactions') var rows = transactionsSheet.getRange('C2:C').getValues() var symbols = new Set() // Use Set to avoid duplicates for (var i = 0; i < rows.length; i++) { var symbol = rows[i][0] if (symbol.length > 0) { symbols.add(symbol) } } // Convert from Set to array return [...symbols] }

The function extractFirstTransactionDate retrieves transactions from the sheet Transactions and sort them ascending by date and return the date of the first transaction, which is hence the first transaction date.

/** * Get the first transaction date from the sheet Transactions. */ function extractFirstTransactionDate() { var spreadsheet = SpreadsheetApp.getActive() var transactionsSheet = spreadsheet.getSheetByName('Transactions') var rows = transactionsSheet.getRange('A:E').getValues() var transactions = [] for (var i = 1; i < rows.length; i++) { var row = rows[i] if (row[0].length === 0) { break } transactions.push({ date: row[0] }) } // Order by date ascending transactions.sort((t1, t2) => t1.date < t2.date ? -1 : 1) console.log(transactions[0].date) return transactions[0].date }

The function generateHistoricalPricesSheets iterate each symbol and call generateHistoricalPriceSheetForSymbol on each one:

  • Create a sheet (if not existing) and name it by the symbol
  • Set the formula =GOOGLEFINANCE(SYMBOL, "price", FIRST_TRANSACTION_DATE, TODAY(), "DAILY") on the cell A1
  • Format the column A as dd/mm/yyyy
  • Format the column B as #.###
/** * Generate a sheet for each unique symbol found in the Transactions tab. * Each sheet contains historical prices of the symbol until today. */ function generateHistoricalPricesSheets() { var symbols = extractSymbolsFromTransactions() var firstTransactionDate = extractFirstTransactionDate() symbols.forEach(symbol => generateHistoricalPriceSheetForSymbol(symbol, firstTransactionDate)) } /** * Create a new sheet whose name is name of the symbol * for its historical prices until today. * * The formula below is added to A1 cell. * GOOGLEFINANCE("SYMBOL", "price", "1/1/2014", TODAY(), "DAILY") * @param {String} symbol */ function generateHistoricalPriceSheetForSymbol(symbol, fromDate) { // Create a new empty sheet for the symbol var spreadsheet = SpreadsheetApp.getActive() var sheetName = symbol var symbolSheet = spreadsheet.getSheetByName(sheetName) if (symbolSheet) { symbolSheet.clear() symbolSheet.activate() } else { symbolSheet = spreadsheet.insertSheet(sheetName, spreadsheet.getNumSheets()) } let fromDateFunction = "DATE(" + fromDate.getFullYear() + "," + (fromDate.getMonth() + 1) + "," + fromDate.getDate() + ")" var historicalPricesFormula = 'GOOGLEFINANCE("' + symbol + '", "price", ' + fromDateFunction + ', TODAY(), "DAILY")' symbolSheet.getRange('A1').setFormula(historicalPricesFormula) symbolSheet.getRange('A:A').setNumberFormat('dd/mm/yyyy') symbolSheet.getRange('B:B').setNumberFormat('#.###') }

Compute daily evolutions

The first step is to know the composition of the portfolio on a given day, which consists of Invested Money, Cash and number of shares for each stock.

  • The sum of amount of all the transactions until the given date is available Cash on that date.
  • The sum of amount of all the DEPOSIT and WITHDRAWN transactions until the given date is Invested Money on that date.
  • The sum of shares of all the BUY and SELL transactions until the given date for a given stock is the number of shares for that stock on that date.
/** * Compute the composition of portfolio on each day of transaction. * A composition of portfolio contains: * - Amount of invested money so far (Deposit - Withdrawal) * - Amount of available cash * - Number of shares for each bought stock * * { * invested: 10000, * cash: 2001.42, * APPL: 400, * GOOGL: 500 * } * @param {Array} transactions */ function computePortfolioByTransactionDate(transactions) { var portfolioByDate = {} var portfolioSnapshot = { invested: 0, cash: 0 } for (var i = 0; i < transactions.length; i++) { var transaction = transactions[i] var tDate = transaction.date.toISOString().substring(0, 10) var tType = transaction.type var tSymbol = transaction.symbol var tAmount = transaction.amount var tShares = transaction.shares if (tType === 'BUY' || tType === 'SELL') { if (!portfolioSnapshot.hasOwnProperty(tSymbol)) { portfolioSnapshot[tSymbol] = 0 } portfolioSnapshot[tSymbol] += Number(tShares) } if (tType === 'DEPOSIT' || tType === 'WITHDRAWAL') { portfolioSnapshot.invested += Number(tAmount) } portfolioSnapshot.cash += Number(tAmount) var portfolioCloned = {} Object.assign(portfolioCloned, portfolioSnapshot) portfolioByDate[tDate] = portfolioCloned } return portfolioByDate }

The second step is to use historical prices of stocks to calculate their market values on a given date and hence to calculate eventually the Portfolio Value and Gain.

  • Iterate each date starting from the first transaction date until today
  • On each date, retrieve its composition
  • On each date, for each stock whose number of shares is greater than 0, find the closing price on that date and multiply with the number of shares to determine its market value.
  • On each date, the portfolio value is sum of the market value and available cash.
  • On each date, the gain is the difference between the portfolio and the invested money.
  • Write all those computed evolution data point in a sheet named Evolutions of 5 columns: Date, Invested Money, Cash, Market Value, Portfolio Value and Gain
/** * From the Transactions sheet and all historical prices sheets for all symbols: * - Compute daily evolution of the portfolio from the first transaction date * - Write evolutions into Evolutions sheet * * 'Date', 'Invested Money', 'Cash', 'Market Value', 'Portfolio Value', 'Gain' */ function generateDailyEvolution() { var transactions = extractTransactions() var portfolioByTransactionDate = computePortfolioByTransactionDate(transactions) var historicalPricesBySymbol = {} var symbols = extractSymbolsFromTransactions() symbols.forEach(symbol => { historicalPricesBySymbol[symbol] = getHistoricalPricesBySymbol(symbol) }) var firstTransactionDate = transactions[0].date // var now = new Date() // Compute Evolutions var evolutions = [['Date', 'Invested Money', 'Cash', 'Market Value', 'Portfolio Value', 'Gain']] var portfolioSnapshot for (var aDate = firstTransactionDate; aDate <= new Date(); aDate.setDate(aDate.getDate() + 1)) { var dString = aDate.toISOString().substring(0, 10) var invested = 0 var cash = 0 var value = 0 portfolioSnapshot = portfolioByTransactionDate[dString] ? portfolioByTransactionDate[dString] : portfolioSnapshot if (portfolioSnapshot) { for (const key in portfolioSnapshot) { switch (key) { case 'cash': cash = portfolioSnapshot.cash break case 'invested': invested = portfolioSnapshot.invested break default: var symbol = key var numShares = portfolioSnapshot[symbol] if (numShares > 0) { var priceOfSymbolOnDate = historicalPricesBySymbol[symbol][dString] if (priceOfSymbolOnDate) { value += numShares * priceOfSymbolOnDate } else { value = -1 break } } break } } } if (value > -1) { var portfolioValue = value + cash var gain = portfolioValue - invested evolutions.push([new Date(aDate.getTime()), invested, cash, value, portfolioValue, gain]) } } // Write the evolutions var spreadsheet = SpreadsheetApp.getActive() var sheetName = 'Evolutions' var sheet = spreadsheet.getSheetByName(sheetName) if (sheet) { sheet.clear() sheet.activate() } else { sheet = spreadsheet.insertSheet(sheetName, spreadsheet.getNumSheets()) } sheet.getRange(1, 1, evolutions.length, 6).setValues(evolutions) }

Test

Execute a function from the Apps Script editor

It's the moment of truth:

  • On the top menu bar of the Apps Script editor, select the function generateHistoricalPricesSheets
  • Click on the Run button to execute the function. If you comeback to your spreadsheet, you will see newly created sheets for every symbol presented in the portfolio. Each sheet contains only to columns Date and Close
Generate historical prices sheet for each stock with Apps Script
  • On the top menu bar of the Apps Script editor, select the function generateDailyEvolution
  • Click on the Run button to execute the function. If you comeback to your spreadsheet, you will see the sheet Evolutions is updated.
Compute and generate Evolutions sheet with Apps Script

Add Portfolio Tools menu to the toolbar

Whenever you add new transactions to your portfolio (no matter if it is a transaction made today or 2 years ago that you forget to add), you need to re-run the 2 about main functions: generateHistoricalPricesSheets and generateDailyEvolution. It might not be so convenient to open the Apps Script editor to execute functions as described above. In fact, we can add a menu directly on the menu bar of the spreadsheet and execute the functions directly there without going to the Apps Script editor. We just need to add the onOpen function below to add a menu named Portfolio Tools to the spreadsheet whenever it is opened:

/** * Add tab to the menu bar */ function onOpen() { var spreadsheet = SpreadsheetApp.getActive() var menuItems = [ { name: 'Generate Historical Prices Sheets', functionName: 'generateHistoricalPricesSheets' }, { name: 'Generate Daily Evolution of Portfolio', functionName: 'generateDailyEvolution' }, { name: 'Delete Historical Prices Sheets', functionName: 'deleteHistoricalPricesSheets' } ] spreadsheet.addMenu('Portfolio Tools', menuItems) }
Add new item to menu bar of the Google Sheets

Schedule daily

So far, we have automated successfully a big process which saves us several hours of detailed manual works. However, if you notice, there are still one manually thing you need to do, which is to trigger the script daily. We can effectively schedule the execution of the script daily, for instance, at 7 a.m before the opening of the market.

  • Select the menu Triggers on the left side panel of the Apps Script editor
  • Click the button + Add Trigger
Use time-based triggers to execute automatically and daily the functions of Google Apps Script

  • Choose generateHistoricalPricesSheets for the select Choose which function to run
  • Choose Time-driven for the select Select event source
  • Choose Day timer for the select Select type of time based trigger
  • Choose 6am to 7am for the select Select time of day
  • Save the trigger
  • Create another trigger with the same attributes for the function generateDailyEvolution
  • Choose 7am to 8am for the select Select time of day to make sure that generateDailyEvolution is executed after generateHistoricalPricesSheets
  • Save the trigger
Time-based trigger to generate daily evolution of the stock investment portfolio in Google Sheets

With the 2 triggers, every day, at 6am, a historical prices sheet is generated for each symbol presented in the portfolio. At 7am, the Evolutions sheet is computed and populated.

Conclusion

In this post, we have identified the need to compute daily evolutions of the portfolio. We then have found a solution with Google Sheets and its useful GOOGLEFINANCE function. We have made a step further with Google Apps Script to automate the process and schedule it daily. We can still do more, for example:

  • Visualize those daily evolutions in a time-based graph within the dashboard in Google Data Studio
  • Compare the evolution of portfolio with the evolution of market index over a same period of time

TLDR

  • Make a copy of the demo spreadsheet that is available here
  • Select Tools then Script editor from the menu bar to open Apps Script editor

  • On the top menu bar of the Apps Script editor, select the function generateHistoricalPricesSheets
  • Click on the Run button to execute the function. If you comeback to your spreadsheet, you will see newly created sheets for every symbol presented in the portfolio. Each sheet contains only to columns Date and Close
  • On the top menu bar of the Apps Script editor, select the function generateDailyEvolution
  • Click on the Run button to execute the function. If you comeback to your spreadsheet, you will see the sheet Evolutions is updated.
  • Add the 2 triggers for the functions generateHistoricalPricesSheets and generateDailyEvolution

Note

To better understand the overall concept, please check out this post Create personal stock portfolio tracker with Google Sheets and Google Data Studio.

How to compute the daily evolution of a stock investment portfolio by simply using only the available built-in functions in Google Sheets

The solution explained in this post requires certain experiences in programming, especially with Google Apps Script. However, there is another solution using only built-in functions in Google Sheets. I have explained that solution in detail in the post How to compute the daily evolution of a stock investment portfolio by simply using only the available built-in functions in Google Sheets

The evolution chart of a stock investment portfolio in Google Sheets
how to compute the daily evolution of a stock investment portfolio by simply using the available built-in function in Google Sheets

References

Disclaimer

The post is only for informational purposes and not for trading purposes or financial advice.

Feedback

If you have any feedback, question, or request please:

Support this blog

If you value my work, please support me with as little as a cup of coffee! I appreciate it. Thank you!

Share with your friends

If you read it this far, I hope you have enjoyed the content of this post. If you like it, share it with your friends!

Comments

  1. Thank you so much for your work, I am really impressed with all the possibilities we have on google sheets...
    I was hoping you had a sample google sheet to calculate daily historical evolution?

    Thank you,
    David

    ReplyDelete
    Replies
    1. Hi, thank you for your interest in creating a stock investment portfolio tracker with Google Sheets.

      Yes, I am impressed too with the capabilities of Google Sheets, that's why I am sharing what I know about that on this blog.

      You can find the full demo about calculating the daily historical evolution of a stock investment portfolio in Google Sheets in this post https://www.allstacksdeveloper.com/p/lion-stock-portfolio-tracker.html#demo

      I just want to let you know that I am working on a simpler solution for calculating the historical evolution of a stock investment portfolio in Google Sheets without writing complicated code with Google Apps Script. That solution uses only available built-in formulas of Google Sheets. So if that interests you, please stay tuned to this blog. I'll soon publish it.

      Delete

Post a Comment

Popular posts

How to convert column index into letters with Google Sheets

How to convert column index into letters with Google Sheets

In Google Sheets, rows are indexed numerically, starting from 1, but columns are indexed alphabetically, starting from A. Hence, it is pretty straightforward to work with rows and trickier to work with columns as we need to convert between column index and corresponding letters. For example, what are the letters of column 999th in Google Sheets? In this post, we will look at how to convert a column index into its corresponding letters by using the built-in functions of Google Sheets. What are letters of the column 999th in a spreadsheet? Unfortunately, Google Sheets does not provide a ready-to-use function that takes a column index as an input and returns corresponding letters as output. However, there is a little trick of combining other available built-in functions to do the task. In Google Sheets, there is the ADDRESS function that returns the cell reference, according to the specified row index (first parameter) and column index (second parameter) in the input. For example,
Create a dividend income tracker with Google Sheets by simply using pivot tables

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 for a stock investment portfolio with Google Sheets by simply using pivot tables.
Use SPARKLINE to create 52-week range price indicator chart for stocks in Google Sheets

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.
Compute daily evolution of a stock investment portfolio by using only built-in functions of Google Sheets

Compute daily evolution of a stock investment portfolio by using only built-in functions of Google Sheets

To effectively track a stock investment portfolio, it is necessary to know its evolution in the past. As I use Google Sheets to track my stock investment portfolio, I have researched and successfully implemented several solutions. In this post, I am happy to share in detail how to compute the daily evolution of a stock investment portfolio by simply using only the available built-in functions in Google Sheets.
How to convert column index into letters with Google Apps Script

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.
Create dividend income tracker with Google Data Studio

Create dividend income tracker with Google Data Studio

With transactions registered, it is easy to create a dividend income tracker with Google Sheets. However, a dividend income tracker in Google Sheets is not interactive. Instead of having different pivot tables and switching forth and back among them, I can create an interactive dividend income tracker with a single-page report on Google Data Studio. In this post, I explain how to create a dividend income tracker with Google Data Studio.
Slice array in Google Sheets

Slice array in Google Sheets

Many functions in Google Sheets return an array as the result. However, I find that there is a lack of built-in support functions in Google Sheets when working with an array. For example, the GOOGLEFINANCE function can return the historical prices of a stock as a table of two columns and the first-row being headers Date and Close. How can I ignore the headers or remove the headers from the results?
Compute cost basis of stocks with FIFO method in Google Sheets

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.
Compare stock portfolio to market indexes

Compare stock portfolio to market indexes

As investors, we always want to see our portfolio grows over time. If a portfolio made a 1000$ of gain in one year, is it good enough? Should we gauge the portfolio's performance against an alternative investment, for instance, a market index? Should we aim to beat that index? In this post, we will see how to compare a stock portfolio to market indexes by using Google Sheets, Apps Script, and Google Data Studio. Select market indexes to compare Method to compare Guides Prepare data with Google Sheets and Apps Script Visualize benchmark in Google Data Studio Demo Conclusion Note References Select market indexes to compare In the context of stock investment, investors can compare the performance of their portfolios over a period of time with an alternative investment such as a market index, a portfolio of another investor, or even a single stock if they don't want any diversification, etc. In general, a market index is a good benchmark because it represents t
How to copy data in Google Sheets as HTML table

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.