In R cannot use AdjustedSharpeRatio() from 'Performance Analytics' - r

I have some troubles using the function AdjustedSharpeRatio() from the package PerformanceAnalytics, the following code sample in R 3.0.0:
library(PerformanceAnalytics)
logrets = array(dim=c(3,2),c(1,2,3,4,5,6))
weights = c(0.4,0.6)
AdjustedSharpeRatio(rowSums(weights*logrets),0.01)
gives the following error:
Error in checkData(R) :
The data cannot be converted into a time series. If you are trying to pass in
names from a data object with one column, you should use the form 'data[rows,
columns, drop = FALSE]'. Rownames should have standard date formats, such as
'1985-03-15'.
Replacing the last line with zoo gives the same error:
AdjustedSharpeRatio(zoo(rowSums(weights*logrets)),0.01)
Am I missing something obvious ?

Hmm...not too sure what you are trying to achieve with the logrets and weights objects there....but if logrets are already in percentages. then maybe something like this...
AdjustedSharpeRatio(xts(rowSums(weights*logrets)/100,Sys.Date()-(c(3:1)*365)), Rf=0.01)

This might work:
a <- rowSums(weights*logrets)
names(a) <- c('1985-03-15', '1985-03-16', '1985-03-17')
AdjustedSharpeRatio(a,0.01)

Related

Error in x[is.na(x)] <- na.string : replacement has length zero when exporting data frame to openxlsx in R

I have an issue when I try to export a data frame with the library openxlsx to an Excel. When I tried, this error happen:
openxlsx::write.xlsx(usertl_lp, file = "Mi_Exportación.xlsx")
Error in x[is.na(x)] <- na.string : replacement has length zero
usertl_lp_clean <- usertl_lp %>% mutate(across(where(is.list), as.character))
openxlsx::write.xlsx(usertl_lp_clean, file = "Mi_Exportación.xlsx")
This error may be caused by cells containing vectors. So, using across to modify the vector to character.
I posted this here for others in need.
I think you are looking for the writeData function from the same package.
Check out writeFormula from the same package as well or even write_xlsx from the writexl package.
I was having a similar problem in a data frame, but, in my case, I was using the related openxlsx::writeData.
The data frame was generated using sapply, with functions which could deliver errors because of the data. So, I coded to fill with NA when an error were generated. I ended up with NaN and NAs in the same column.
What worked for me is conducting the following treatment before writeData:
df[is.na(df)]<-''
so, for your problem, the following may work:
df[is.na(df)]<-''
openxlsx::write.xlsx(as.data.frame(df), file = "df.xlsx", colNames = TRUE, rowNames = FALSE, append = FALSE)

Reading CSV file in R and formatting dates and time while reading and avoiding missing values marked as?

I am trying to Reading CSV file in R . How can I read and format dates and times while reading and avoid missing values marked as ?. The data I load after reading should be clean.
I tried something like
data <- read.csv("Data.txt")
It worked, but the dates and times were as is.
Also how can I extract a subset of data from specific data range?
For this I tried something like
subdata <- subset(data,
Date== 01/02/2007 & Date==02/02/2007,
select = Date:Sub_metering_3)
I get error Error in eval(expr, envir, enclos) : object 'Date' not found
Date is the first column.
The functions read.csv() and read.table() are not set up to do detailed fancy conversion of things like dates that can have many formats. When these functions don't automatically do what's wanted, I find it best to read the data in as text and then convert variables after the fact.
data <- read.csv("Data.txt",colClasses="character",na.strings="?")
data$FixedDate <- as.Date(data$Date,format="%Y/%m/%d")
or whatever your date format is. The variable FixedDate will then be of type Date and you can use equality and other conditions to subset.
Also, in your example code you are putting 01/02/2007 as bare code, which results in dividing 1 by 2 and then by 2007 yielding 0.0002491281, rather than inserting a meaningful date. Consider as.Date("2007-01-02") instead.

How to convert a zoo object in a ts object in order to use strucchange

Ok. I´ve tried several foruns and threads, but I couldn't find this. I imported my database to R using this:
teste <- read.zoo("bitcoin2.csv", header=TRUE, sep=",", format = "%m/%d/%Y")
Which worked fine. My xyplot gave me the right plot. So I tried to convert it to ts in order to use strucchange and other outlier/breakpoints packages.
aba <- as.ts(zoo(z$Weighted_Price))
When I did it, it seems to have been lost the index time. The plot still has the same shape, but the X-axis doesn't look as a regular time series plot.
Anyway, I´ve tried the strucchange. After loading it, I made this simple test:
test<-breakpoints(teste$Weighted_Price~1)
But R returned me:
Error in my.RSS.table[as.character(i), 3:4] <- c(pot.index[opt], break.RSS[opt]) :
replacement has length zero
I presume my mistake is that the coercion from zoo to ts was not correct. Any help would be great.

Error importing SPSS data into R

I imported a dataset in the .sav SPSS format, and I'm getting an error that I haven't seen before.
1: In read.spss("C:\\Users\\acer\\Desktop\\X\\X\\PIREDEU\\ees2009_v0.9_20110622.sav", ... :
C:\Users\acer\Desktop\X\X\PIREDEU\ees2009_v0.9_20110622.sav: File contains duplicate label for value 1.1 for variable V200
Error in cat(list(...), file, sep, fill, labels, append) :
argument 2 (type 'list') cannot be handled by 'cat'
This came up after I typed warnings(PIREDEU). I imported the data using the foreign library:
library(foreign)
PIREDEU<-read.spss("C:\\Users\\acer\\Desktop\\X\\X\\PIREDEU\\ees2009_v0.9_20110622.sav", use.value.labels=TRUE, max.value.labels=Inf, to.data.frame=TRUE)
I've fiddled with various combinations for the latter three arguments of the read.spss function, and I've gotten nowhere.
Anyone have any suggestions?
I used the below one and it worked perfectly, just ignore the warning message and check data by typing its name:
mydata4<-read.spss("C:\\Work\\data.sav",use.value.labels=F,to.data.frame=T)
mydata4 # check data
Do you have long strings in the file - longer than 8 bytes? Statistics uses some special arrangements to handle those. It looks like the problem is with the value labels. If you can delete those (using SPSS) you might be able to get the rest of the data.
Try to read data without labels.
library(foreign)
PIREDEU <- read.spss("C:\\Users\\acer\\Desktop\\X\\X\\PIREDEU\\ees2009_v0.9_20110622.sav",
use.value.labels = F,
to.data.frame = T)
Does it work?
Convert the spss datafile into .por (portable file) and in R, install the packages hMisc, memisc and foreign and load the package using library(foreign), library(hMisc) and library(memisc).
Then type the following:
mydata <- spss.get("c:/mydata.por", use.value.labels=TRUE)
# last option converts value labels to R factors

Declare yearly data in read.zoo

I am trying to read in yearly data with gaps using the read.zoo function from the zoo package. I am having some trouble finding the FUN that declares the data to be yearly data. The data set is located here.
The function call I am trying is
tsGDP <- read.zoo("us-gross-domestic-product-192919.csv", sep=",", format="%Y",
regular=FALSE, header=TRUE, index.column=1)
plot(log(tsGDP))
This works fine, but it chokes when I try to plot the ACF of the series
> acf(tsGDP)
Error in na.fail.default(as.ts(x)) : missing values in object
This R-list posting seems to indicate that this is because I am not declaring yearly data correctly.
Without data , it is hard to reproduce problem.
But , from the documentation of acf
By default, no missing values are allowed. If the na.action function passes through missing values (as na.pass does), the covariances are computed from the complete cases.
why not to try with
acf(x = tsGDP, na.fail = na.pass)

Resources