在 Google 电子表格上运行 Montecarlo 分析

Ore*_*sky 5 montecarlo google-sheets google-apps-script

一张复杂的 Google 电子表格有多个输入和一个输出,我需要对其运行蒙特卡洛分析。在 Excel 中,我会使用“DYI”蒙特卡罗方法,将公式如下

=norminv(rand(),expected_return,st_deviation)
Run Code Online (Sandbox Code Playgroud)

在输入上,并有一个带有循环的简单宏,通常运行 1000 次或以上,触发电子表格重新计算(相当于按 F9),并记录输出单元格的结果。

在 Google 电子表格上,我找不到从 google apps 脚本触发电子表格重新计算的方法。

有没有什么方法,或者更好/更智能的架构来在谷歌电子表格中进行蒙特卡罗分析(最好不要使用我不明白它们对数据做什么的加载项,或者需要无限制地访问我的所有文件)?

提前致谢!

Ore*_*sky 0

这似乎可以解决问题(来自此链接

/**
 * @OnlyCurrentDoc  Limits the script to only accessing the current spreadsheet.
 */


/**
 * Adds a custom menu with items to show the sidebar and dialog.
 *
 * @param {Object} e The event parameter for a simple onOpen trigger.
 */
function onOpen(e) {
  SpreadsheetApp.getUi()
      .createAddonMenu()
      .addItem('Re-calculate selected cells', 'recalculate')
      .addToUi();
}


/**
 * Force Spreadsheet to re-calculate selected cells
 */
function recalculate(){
  var activeRange = SpreadsheetApp.getActiveRange();
  var originalFormulas = activeRange.getFormulas();
  var originalValues = activeRange.getValues();

  var valuesToEraseFormula = [];
  var valuesToRestoreFormula = [];

  originalFormulas.forEach(function(outerVal, outerIdx){
    valuesToEraseFormula[outerIdx] = [];
    valuesToRestoreFormula[outerIdx] = [];
    outerVal.forEach(function(innerVal, innerIdx){
      if('' === innerVal){
        //The cell doesn't have formula
        valuesToEraseFormula[outerIdx][innerIdx] = originalValues[outerIdx][innerIdx];
        valuesToRestoreFormula[outerIdx][innerIdx] = originalValues[outerIdx][innerIdx];
      }else{
        //The cell has a formula.
        valuesToEraseFormula[outerIdx][innerIdx] = '';
        valuesToRestoreFormula[outerIdx][innerIdx] = originalFormulas[outerIdx][innerIdx];
      }
    })
  })

  activeRange.setValues(valuesToEraseFormula);
  activeRange.setValues(valuesToRestoreFormula);
}


/**
 * Runs when the add-on is installed; calls onOpen() to ensure menu creation and
 * any other initializion work is done immediately.
 *
 * @param {Object} e The event parameter for a simple onInstall trigger.
 */
function onInstall(e) {
  onOpen(e);
}
Run Code Online (Sandbox Code Playgroud)