The error message you encountered, Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : 0 (non-NA) cases, suggests that the function lm() was unable to perform a linear regression because the data you provided doesn't contain any non-NA (not missing) observations. This can happen for a few reasons:
-
Your filtered dataset (company_data) has no rows: This could occur if the condition used in subset (e.g., ISIN == "Specific_ISIN_of_Company") doesn't match any rows in your original stock_market_data dataset. Ensure the ISIN you're looking for is present in the dataset and that there's no typo.
-
Your variables (Daily_Return_stock or Daily_Return_index) contain only NA values: It's possible that after subsetting, the specific variables you want to model contain NA (missing) values only. This can happen if the data was not properly recorded or if there’s an issue with how the data was filtered or imported.
-
The dataset actually has no non-NA cases after filtering: This is similar to the second reason, but here, even if there are rows in the filtered dataset, all the relevant cases for lm() are NAs.
How to Correct It
- Check the ISIN and filtering criterion:
First, ensure that the ISIN value you're using to filter the dataset is correct and present in the stock_market_data. You may also want to confirm that the filtering operation is being performed correctly.
# You might want to check if the ISIN exists in the dataset:
unique(stock_market_data$ISIN)
# Ensuring correct filtering
company_data <- subset(stock_market_data, ISIN == "Actual_ISIN_Value_Here")
- Check for NAs in key variables:
Ensure that the columns you're using for the regression (Daily_Return_stock, Daily_Return_index) don't exclusively contain NA values in the filtered data.
# Checking for NAs
summary(company_data$Daily_Return_stock)
summary(company_data$Daily_Return_index)
If you find that these columns contain NAs, you may need to address these missing values. This could involve removing rows with NAs (na.omit()) or imputing missing values depending on what makes the most sense for your dataset and analysis.
- Modify the regression code to handle NA values:
You can explicitly tell the lm function to omit NA values by using the argument na.action = na.omit.
model <- lm(Daily_Return_stock ~ Daily_Return_index, data=company_data, na.action = na.exclude)
Finally, after ensuring that your dataset company_data is correctly filtered and ready (i.e., it actually has rows and the relevant columns have non-NA values), you can rerun the regression and prediction lines.
Keep in mind that it's crucial to understand the nature of your dataset and the implications of any data cleaning steps you take, especially when dealing with financial data where accuracy and precision are paramount.