我是谷歌應用程式腳本的初學者,想問一個關于如何根據從我的電子表格中提取的資訊陣列為物件創建子類的問題。
這是一個示例表,其中包含“歷史”表中的一些資料。輸入資料是用戶投資的交易歷史。我的最終目標是在谷歌應用程式腳本中創建一個陣列,并為任何給定股票調整股票分割值。
但是,我的專案的第一步是以我可以執行這些計算的方式收集資料。為此,我需要創建一個這樣的物件:
stock symbol: {date:value, {quantity: value, price:value}}, {date:value, {split ratio:value}}
這樣做的原因是因為在此物件中,日期與數量價格和拆分比率相關聯。在以后的計算中,我會查看拆分值的日期是否小于或等于數量/價格值的日期,如果為真,則執行拆分比率 * 數量和價格/拆分比率。如果這不是真的,那么對于任何給定的股票,保持價格和數量不變。最后以與原始陣列相同的形式回傳這些物件。
這是我迄今為止所做的嘗試:
function createDate(date, quantity, price) {
this.date = date;
this.quantityPrice = new createDateData (quantity, price);
}
function createDateData(quantity, price) {
this.quantity = quantity;
this.price = price;
}
function retrieveData () {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const inputSheet = ss.getSheetByName('History');
const data = inputSheet.getRange(2, 1, inputSheet.getLastRow() - 1, 9).getValues();
const filterd = data.filter(row => row[2] == 'Buy' || row[2] == 'Sell' || row [2] == 'Split');
const sorted = filterd.sort((a, b) => {
if (a[0] < b[0]) return -1
if (a[0] > b[0]) return 1
else return 0
})
for ( let i of sorted) {
var sampleData= new createDate([i][0][0],[i][0][3],[i][0][4]);
console.log(sampleData);
}
}
這是我得到的輸出
{ date: Tue Jun 30 2020 18:00:00 GMT-0400 (Eastern Daylight Time),
quantityPrice: { quantity: 1, price: 40000 } }
哪個與所需的輸出不同?
問題:如何獲得所需的輸出?以亞馬遜為例:
AMZN: {9/28/2020, {1, 100}}, {9/28/2020, {0.5, 200}}, {10/19/2020 {0.2, 100}}, {11/27/2020, {10}}
EDIT2:有關所需輸出,請參閱“所需輸出”表。
uj5u.com熱心網友回復:
據我所知,“價格”列中有陣列公式,因此您只需要更新“數量”列。“價格”列將自動更新。
你確定你想要的輸出中的第 27 行應該改變嗎?我認為不應該,因為它是“現金”,而不是“亞馬遜”。
試試這個代碼:
function main() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('History');
var range = sheet.getRange(3,1,sheet.getLastRow(),9);
var data = range.getValues().reverse(); // reverse to iterate it from the top to the bottom
for (var row in data) {
var action = data[row][2];
if (action != 'Split') continue;
data = [...data.slice(0,row), ...update(data.slice(row))]; // update all rows below the 'Split'
}
// get column 'Quantity' from the data and put it on the sheet
var quantity = data.map(x => [x[3]]).reverse();
sheet.getRange(3,4,data.length,1).setValues(quantity);
}
// the function takes rows, recalculates quantity and returns the updated rows
function update(data) {
var security = data[0][1];
var ratio = data[0][8];
// if the security is the same as in the first row,
// and if the action is 'Buy' or 'Sell':
// the price will be multiply by the ratio
for (var row in data) {
if (data[row][1] != security) continue;
var action = data[row][2];
if (['Buy','Sell'].includes(action)) data[row][3] *= ratio;
try {if (row[ r 1][1] == 'Split') break} catch(e) {} // <-- updated line
}
return data;
}
該腳本暗示所有行都按日期排序。最新的日期在底部,最舊的日期在頂部。
沒有任何物件。我認為不需要它們。可能它可以用另一種方式完成,使用物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/334917.html
上一篇:格式化嵌套日期而不更改物件結構
下一篇:使用全域變數更新所有物件值
