I have a list of daily close prices for bitcoin in a column B and am trying to write a script that would put the %change between row i and rowi-1 in the adjacent column C (column A is the date). The calculation needs to start from the last row and go back up to row number 2.
I used the code below and get 2 types of issues:
For the logic I tried to work with 2 variable I could divide for the percentage calculation: rangePriceValues (prices at day 2) and rangePricelastValues (values at day 1).
I tried to find similar code online and couldn't find anything close (but am sure there must be one somewhere) I am new to Java and would really appreciate if someone could put me on the right track.
Thanks!!
function PopulateC()
{
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test__Price");
var rangePrice = sheet1.getRange(2,2,sheet1.getLastRow(),1); // full list of prices
var rangePriceValues = rangePrice.getValues(); // value of these prices
var secondLastRow = rangePrice.getNumRows()-2; //total number of rows minus one value
var rangePricelast = sheet1.getRange(2,2,secondLastRow.valueOf() ,1); // full list of prices minus one
var rangePricelastValues = rangePricelast.getValues(); //value of the prices at day+2
var percentage = [];
var percentageValue = [];
var rangePercentage = sheet1.getRange(2,3,rangePrice.getNumRows(),1);
for (i= rangePrice.getNumRows(); 2; i--)
{
percentage [i-1] = (rangePriceValues[i]/= rangePricelastValues[i]-1)* 100;
percentageValue= percentage.valueOf();
Logger.log(percentageValue) // this is where I see my array with [null, null,....]
rangePercentage.setValues([percentageValue]);
}
}
`
Change this: var rangePrice = sheet1.getRange(2,2,sheet1.getLastRow(),1);
to This: var rangePrice = sheet1.getRange(2,2,sheet1.getLastRow()-1,1);
I found a way to solve the problem by writing a simpler code. It works but the calculation is very slow. If anyone has a view on how to optimise the code I would be super grateful, as I am still learning. Thanks Cooper for the suggestions!
function SimplePerc() {
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test_Bitcoin_Price");
var rangePrice = sheet1.getRange(2,2,445,1);
var priceValue = rangePrice.getValues();
for (var i=sheet1.getLastRow() ; 2; i--)
{
var numerator = sheet1.getRange(i,2).getValue();
var denominator = sheet1.getRange(i+1,2).getValue();
var percentagecalc = (numerator /= denominator);
var percentageclean = (percentagecalc -1)*100;
sheet1.getRange(i,3).setValue(percentageclean);
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.