Skip to main content

Google Apps Script tips and tricks

When working with Google Apps Script, there are some tasks that I need to perform quite often. For that, I create a list of snippets that I can easily copy whenever needed. In this post, I share my useful snippets and my tips and tricks when working with apps script. If you have any snippet/tip/trick, you can share in the comment section.

Use SPARKLINE column chart to show stock price trend in Google Sheets

Effective use of the GOOGLEFINANCE function to get historical prices of stocks in a spreadsheet (Sheets, Apps Script)

As I manage my stock portfolio with Google Sheets, I have used the GOOGLEFINANCE function to get the historical prices of a stock. However, I experienced that the repetitive use of the GOOGLEFINANCE function cause performance issues for my spreadsheet. To avoid that problem, I create for each stock a dedicated tab to store its historical prices during a period that I'm interested in.

For example, if I need to get prices of GOOGL stock during the last 10 years

  • I create a new tab and name it GOOGL (the ticker symbol itself).
  • I put in the A1 cell this formula =GOOGLEFINANCE("GOOGL","price",TODAY()-10*365,TODAY()).
  • As the result, the column A and B contain respectively Date and Close prices of GOOGL during the last 10 years.
  • And then:
    • If I need to query the prices directly in the spreadsheet, I will use the VLOOKUP function on the above sheet instead of repetitive use of the GOOGLEFINANCE function.
    • If I need to query the prices in an Apps Script program, I will read the content of the above sheet in an object whose key is Date and whose value is Close price.
/**
 * Each symbol has its own sheet for its historical prices.
 * 
 * Return a map from date to close price on that date.
 * {
 *  '2020-01-31': 22.30,
 *  '2020-02-01': 21.54
 * }
 * @param {String} symbol 
 */
function getHistoricalPricesBySymbol(symbol) {
  var spreadsheet = SpreadsheetApp.getActive()
  var historySheet = spreadsheet.getSheetByName(symbol)
  var rows = historySheet.getRange('A:B').getValues()

  var priceByDate = {}
  for (var i = 1; i < rows.length; i++) { // Start from 1 to ignore headers
    var tDate = rows[i][0]
    if (tDate) {
      tDate = getDateString(rows[i][0])
      var close = rows[i][1]
      priceByDate[tDate] = close
    } else {
      break // it means empty row.
    }
  }
  return priceByDate
}

/**
 * Convert date to a string YYYY-MM-DD
 * @param {Date} aDate 
 * @returns String
 */
function getDateString(aDate) {
  return aDate.getFullYear() + '-' + (aDate.getMonth() + 1) + '-' + aDate.getDate()
}

Clean empty cells for a sheet (Sheets, Apps Script)

When working on a spreadsheet, I often use Apps Script for automating some workflows, such as, create a new sheet and populate some data into that. Most of the time, I know in advance how many cells I need to store the data but apps script tends to create more cells than needed. For instance, each new sheet is created by default with 26 columns and 1000 rows. So it is quite wasted and not optimal for reading the sheet later on. Moreover, if we have too many sheets, we need to be aware of a spreadsheet's limitation in terms of size. In my opinion, it is better to not have empty cells and I always clean empty cells of the sheet after populating data into it. Here is the snippet with Google Apps Script.

function cleanEmptyCells(sheet) {
  var lastColumn = sheet.getLastColumn()
  var totalNumberOfColumns = sheet.getMaxColumns()
  if (totalNumberOfColumns > lastColumn) {
    sheet.deleteColumns(lastColumn + 1, totalNumberOfColumns - lastColumn)
  }
  
  var lastRow = sheet.getLastRow()
  var totalNumberOfRows = sheet.getMaxRows()
  if (totalNumberOfRows > lastRow) {
    sheet.deleteRows(lastRow + 1, totalNumberOfRows - lastRow)
  }
}

Get letter for a column index (Sheets, Apps Script)

Array in Javascript is indexed numerically, starting from 0, whereas, columns in a sheet are indexed alphabetically. If I iterate an array to populate data in columns, I need to convert a numerical index to a column letter. For example, an index 53 corresponds to the column BA in a sheet. Below is the utility function that I wrote to do the conversion. You can find a demo in this post or you can convert column index to column letter directly with formulas in a spreadsheet.

function getColumnLetters(columnIndexStartFromOne) {
  const ALPHABETS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

  if (columnIndexStartFromOne < 27) {
    return ALPHABETS[columnIndexStartFromOne - 1]
  } else {
    var res = columnIndexStartFromOne % 26
    var div = Math.floor(columnIndexStartFromOne / 26)
    if (res === 0) {
      div = div - 1
      res = 26
    }
    return getColumnLetters(div) + ALPHABETS[res - 1]
  }
}

Copy a sheet as HTML table (Sheets, Apps Script)

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. That's why I wrote the function below to help me copying a selected range in Google Sheets as an HTML table. You can find a demo in this post.

function copyAsHTMLTable() {
  var spreadsheet = SpreadsheetApp.getActive();
  var values = spreadsheet.getActiveRange().getDisplayValues()
  var text = '<table>'
  for (var row = 0; row < values.length; row++) {
    text += '<tr>'
    for (var col = 0; col < values[0].length; col++) {
      text += '<td>'
      text += values[row][col]
      text += '</td>'
    }
    text += '</tr>'
  }
  text += '</table>'
  var ui = SpreadsheetApp.getUi()
  ui.alert('Please manually select and copy the text below', text, ui.ButtonSet.OK)
}

Add a menu on opening a spreadsheet (Sheets, Apps Script)

function onOpen() {
  var spreadsheet = SpreadsheetApp.getActive()
  var menuItems = [
    { name: 'Generate Historical Prices Sheets', functionName: 'generateHistoricalPricesSheets' },
    { name: 'Delete Historical Prices Sheets', functionName: 'deleteHistoricalPricesSheets' },
    { name: 'Show Historical Prices Sheets', functionName: 'showHistoricalPricesSheets' },
    { name: 'Hide Historical Prices Sheets', functionName: 'hideHistoricalPricesSheets' },
    { name: 'Update Values Sheet', functionName: 'updateValuesSheet' },
    { name: 'Generate Evolutions Sheet', functionName: 'generateEvolutionsSheet' },
    { name: 'Generate Buy-Sell Evaluation Sheet', functionName: 'generateBuySellEvaluationSheet' },
    { name: 'Generate Benchmarks Sheet', functionName: 'generateBenchmarksSheet' },
    { name: 'Clear All Caches', functionName: 'clearAllCaches' }
  ]
  spreadsheet.addMenu('Lion Stock Portfolio Tracker', menuItems)
}

Hide a sheet by name (Sheets, Apps Script)

function hideSheet(sheetName) {
  var spreadsheet = SpreadsheetApp.getActive()
  var sheet = spreadsheet.getSheetByName(sheetName)
  if (sheet) {
    sheet.hideSheet()
  }
}

Show a sheet by name (Sheets, Apps Script)

function showSheet(sheetName) {
  var spreadsheet = SpreadsheetApp.getActive()
  var sheet = spreadsheet.getSheetByName(sheetName)
  if (sheet) {
    sheet.showSheet()
  }
}

Create a new sheet or clear content of an old sheet if exists (Sheets, Apps Script)

function createNewOrClearOldSheet(sheetName) {
  var spreadsheet = SpreadsheetApp.getActive()
  var sheet = spreadsheet.getSheetByName(sheetName)
  if (sheet) {
    sheet.clear()
  } else {
    sheet = spreadsheet.insertSheet(sheetName, spreadsheet.getNumSheets())
  }
  return sheet
}

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

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.
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
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.
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?
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.
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.
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.
Compute daily evolutions of a stock portfolio with Google Sheets and Apps Script

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.