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 Portfolio Tools menu to menu bar of the spreadsheet

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

  • 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 portfolio

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

  • Open your Google portfolio spreadsheet where you register your transactions
  • Select Tools then Script editor from the menu bar to open Apps Script editor
  • Copy the script stored in this github repository into the 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.

References

Disclaimer

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

Comments

Popular posts from this blog

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 existenc

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

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. 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.

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 Disclaimer 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 Dat