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

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.
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.
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 personal stock portfolio tracker with Google Sheets and Google Data Studio

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
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?
GOOGLEFINANCE Best Practices

GOOGLEFINANCE Best Practices

Anyone using Google Sheets to manage stock portfolio investment must know how to use the GOOGLEFINANCE function to fetch historical prices of stocks. As I have used it extensively to manage my stock portfolio investment in Google Sheets , I have learned several best practices for using the GOOGLEFINANCE function that I would like to share in this post.
Stock Correlation Analysis With Google Sheets

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, I explain in details how to perform correlation analysis among stocks in Google Sheets.
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.
Manage Stock Transactions With Google Sheets

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.