Google Scripts automatically add date to column in Google Sheets - datetime

I am trying to use a Google script that retrieves 2 securities fields from GOOGLEFINANCE and saves the output to a Google Sheet file. I need the script to also add the datetime to the first column of the Sheet.
I have created a basic Google Sheet with 3 columns:
A is formatted to DateTime. It has column name date in row 1 and is empty in rows 2 onwards
C has the column name price in row 1 and is empty in rows 2 onwards
D has the column name pe in row 1 and is empty in rows 2 onwards
Here is my function:
function myStocks() {
var sh = SpreadsheetApp.getActiveSpreadsheet();
sh.insertRowAfter(1);
sh.getRange("A2").setValue(new Date());
sh.getRange("C2").setFormula('=GOOGLEFINANCE("GOOG", "price")');
sh.getRange("D2").setFormula('=GOOGLEFINANCE("GOOG", "pe")');
}
Here is the output:
Date price pe
12/10/2017 22:44:31 1037.05 34.55
12/10/2017 22:43:24 1037.05 34.55
The output of columns C and D is correct. The output of column A is wrong. Every time I run the function, each new row is added ABOVE the last row:
The first time I ran the function was at 12/10/2017 22:43:24 and it added that row first.
The second time I ran the function was 12/10/2017 22:44:31 BUT it added that row ABOVE the last row in the sheet - I wanted it to add the new row BELOW the last row.
Is there a way to auto fill the datetime downwards in a single column in GoogleSheets, using a script function?

How about the following modifications?
Modification points :
sh.insertRowAfter(1) means that a row is inserted between 1 row and 2 row.
In your situation, you can retrieve the last row using getLastRow().
getRange("A2").setValue(), getRange("C2").setFormula() and getRange("D2").setFormula() mean that the values are imported to "A2", "C2" and "D2", respectively.
By this, the values are always imported to 2 row.
When you want to import several values and formulas to sheet, you can use setValues() and setFormulas().
The script which was reflected above points is as follows.
Modified script :
function myStocks() {
var sh = SpreadsheetApp.getActiveSheet();
var lastrow = sh.getLastRow() + 1; // This means a next row of last row.
sh.getRange(lastrow, 1).setValue(new Date());
var formulas = [['=GOOGLEFINANCE("GOOG", "price")', '=GOOGLEFINANCE("GOOG", "pe")']];
sh.getRange(lastrow, 3, 1, 2).setFormulas(formulas);
}
Note :
In your script, date and 2 formulas are imported, simultaneously. The modified script works the same to this.
References :
insertRowAfter()
getLastRow()
setValues()
setFormulas()
If I misunderstand your question, please tell me. I would like to modify.

Related

How can I compare two excel files and write values row by row based on the ID

I have two excel files and I want to copy data row by row based on Column's values:
first file:
Id, X1, X2,......,Xn
1.11.2022, 10,20,....., 20
2.11.2022, 30, 40,....., 100
4.11.2022, 20, 30,......,70
.
30.11.2022, 10, 10,....., 50
as you can read in this file we do not have values of (3.11.2022)!!!!!
the second file I created the same one with all days like
Id, X1, X2,......,Xn
1.11.2022,
2.11.2022,
3.11.2022,
.
30.11.2022,
I want to write a code to read the first file row by row,
for i in file 1
for j in file 2
If i("ID")== j("ID")
write i with the same ID to J with the same ID
if j+1 = j + one day to check if the sequence in j is correct.
else i = Na, Na, ....., Na
if we do not have value like day( 3.11.2022)
I know this matter is easier in other languages.
It would be nice if someone can help me!
Thanks in advance
How can I write the code of this process

I am making a for/if loop and I am missing a step somewhere and I cant figure it out

strong text Below is my objective and the code I made to represent that Row 19 is the original street text and 24 is where street2 is located
https://www.opendataphilly.org/dataset/shooting-victims/resource/a6240077-cbc7-46fb-b554-39417be606ee << where the .csv is
Let's deal with the streets with '&' separating their names. Create a new column named street2 and set it equal to NA.
Then, iterate over the data frame using a for loop, testing if the street variable you created earlier contains an NA value.
In cases where this occurs, separate the names in block according to the & delimiter into the fields street and street2 accordingly.
Output the first 5 lines of the data frame to the screen.
Hint: for; if; :; nrow(); is.na(); strsplit(); unlist().
NewLocation$street2 <- 'NA'
Task7 <- unlist(NewLocation)
for (col in seq (1:dim(NewLocation)[19])) {
if (Task7[street2]=='NA'){
for row in seq (1:dim(NewLocation[24])){
NewLocation[row,col] <-strsplit(street,"&",(NewLocation[row,col]))
}
}
}

Working on loop and wanting some feedback, re-adding this to update code and list .csv

Acses to
https://www.opendataphilly.org/dataset/shooting-victims/resource/a6240077-cbc7-46fb-b554 39417be606ee
I have gotten close and got my loop to run, but not gotten the output I want
want a split of street # any '&' locations to a col called 'street$2
**Main objective explained et's deal with the streets with & separating their names. Create a new column named street2 and set it equal to NA.
Then, iterate over the data frame using a for loop, testing if the street variable you created earlier contains an NA value.
In cases where this occurs, separate the names in block according to the & delimiter into the fields street and street2 accordingly.
Output the first 5 lines of the data frame to the screen.
Hint: mutate(); for; if; :; nrow(); is.na(); strsplit(); unlist().
library('readr')
NewLocation$street2 <- 'NA'
#head(NewLocation)
Task7 <- unlist(NewLocation$street2)
for (row in seq(from=1,to=nrow(NewLocation))){
if (is.na(Task7[NewLocation$street])){
NewLocation$street2 <-strsplit(NewLocation$street,"&",(NewLocation[row]))
}
}
This is changing all on my street2 to equal street 1 and get rid of my "NA"s

R for Loop Add Value to New Column

I am trying to run a for loop in a R data frame to pull the Last Price of dataframe of stocks. I am having trouble appending the result to the original dataframe and using it as a second column. Here is the code I am working with thus far. I can get it to print but not add to a new column. I tried to set the loop value equal to a new column but I get an error
for (i in df_financials$Ticker){
df_financials$Last_Price=(bdp(i,'PX_LAST'))
}
Error in `$<-.data.frame`(`*tmp*`, "Last_Price", value = list(PX_LAST =
NA_real_)) :
replacement has 1 row, data has 147
Print(df_financials)
Ticker
1 ENH Equity
2 AXS Equity
3 BOH Equity
4 CNA Equity
5 TRH Equity
You first need to specify the order to apply your command to the stated vector and when to stop [i.e., use 1:length(df$Var) within for()]. Second, specify which row (i) of your new column to replace (i.e.,df$var[i]). Give the code below a try and see if that works.
for (i in 1:length(df_financials$Ticker)){
df_financials$Last_Price[i]=(bdp(i,'PX_LAST'))
}
I'm not familiar with the bdp() function itself. However, I suspect the
problem is that you are trying to pull data from a list with more stocks than you are interested in. If this is the case you need to reference the stock in row i that you want to obtain the last price for. If I'm understanding this correctly the code below should do the trick.
I'll assume that the list is something like
Stock<-data.frame(other_stocks = c("ENH","AXS","Rando1","BOH","CNA","TRH","Rando2","Rando3"),
PX_LAST=c(1,2,3,4,5,6,7,8))
Stock
for (i in 1:length(df$Ticker)){
df$Last_Price[i]=(bdp(df$Ticker[i],'PX_LAST'))
}

creating list of objects with names from a list

hopefully it is not a duplicate, rather difficult to phrase it correctly (relatively new to R)
So the problem is: I want to use sequences of dates excluding certain weekdays based on the row information. I can use bizdays and create calendar objects on the fly but it is quite inefficient - I would rather have them created before and use as needed. On the other side I do not want to create a calendar for every single object that can happen to occur (too many to bother, combination of all weekdays plus versions with/without holidays).
I can create a dataframe with list of dates between start/end date for every row, but i need to provide a calendar with weekdays
P <- setDT(R)[, list(ID=ID,
dt=bizseq(Start.Date,End.Date, cal)
), by=1:nrow(R)]
To provide a calendar I have to define it like
cal <- Calendar(weekdays=c("monday", "tuesday"))
now a working dataset that could explain what i am struggling with
> M <-c(0,1,1,0)
> T <- c(1,1,1,0)
> W <- c(0,0,0,1)
> df <- data.frame(M,T,W)
> df$S <-paste0("c",df$M,df$T,df$W)
> udf <- unique(df)
> udf
M T W S
1 0 1 0 c010
2 1 1 0 c110
4 0 0 1 c001
using udf i would like to create a list of calendar objects that i can afterwards pass to the bizseq using get(df$S), something along the lines of
require(bizdays)
loop or apply?
.... <- Calendar(weekdays=c(ifelse(udf$M==0,"","monday"), ifelse(udf$T==0,"","tuesday"),ifelse(udf$W==0,"","wednesday")))
So now the right questions;) Firstly - is it the best approach? then if so - how to create these 3 objects under their names ("c101" etc), so for example the c100 will match the calendar with Monday on - it is not a question how to create a calendar as the method above works (it is enough to substitute the dots with the name), but how to create object c101 that would become a calendar if i create names in a dynamic way? I could imagine looping through the rows, but have no idea how to force the resulting object to be named udf$S. Unless you reckon there is any better method of providing the corresponding calendar than get() from a list of pre-created objects (for a dataframe with thousands of dates and combination of days off).
I would like basically to end up with 3 calendar objects named c010, c110, c001, but if the expanded table has more unique options to create all other combinations before i run the setDT() function
Afterthought: I can add ID to the udf and call the calendars by index and then return the index to df, but I wonder if it is possible to create dynamic names of objects just as I tried
NOTE
following Sathish's lead I used what seems sufficient:
for(i in 1:nrow(udf)) {
cal <- Calendar(weekdays=c(ifelse(udf[i,1]==0,"","monday"), ifelse(udf[i,2]==0,"","tuesday"),ifelse(udf[i,3]==0,"","wednesday")))
assign(udf[i,4], cal)
}

Resources