{r}
Assuming price_data already excludes the ‘Date’ column and has been converted to a matrix for calculations
prices <- as.matrix(price_data[,-1]) # This line remains unchanged
log_returns <- diff(log(prices)) # Calculate log returns for assets
returns_data <- na.omit(log_returns) # Remove NAs
Creation of an Index - Represented as the average return of selected stocks
For simplicity, let’s assume an equally weighted index of all assets, adjust as necessary
index_log_returns <- rowMeans(log_returns, na.rm = TRUE) # Mean log return of all assets per time period
index_returns_data <- na.omit(index_log_returns)
Combine the individual assets’ returns with the index returns for a comprehensive analysis
all_returns_data <- cbind(returns_data, index_returns_data)
colnames(all_returns_data) <- c(colnames(returns_data), “Market Index”)
Ensure all_returns_data is in a format acceptable by basicStats or convert it
library(fPortfolio)
if (!is.timeSeries(all_returns_data)) {
all_returns_data <- as.timeSeries(all_returns_data)
}
Estimate Summary Statistics for the Returns (Both Individual Assets and the Market Index)
summary_stats <- basicStats(all_returns_data)
print(summary_stats)
{r}
Assuming ‘price_data’ is a data frame with the first column as ‘Date’ and the rest as asset prices.
Converting price data to log returns for individual assets
prices <- as.matrix(price_data[,-1]) # Exclude ‘Date’ column and convert to a matrix
log_returns <- diff(log(prices)) # Calculate log returns
Handling missing values if present
returns_data <- na.omit(log_returns) # Remove NAs from returns data
Calculate the index returns as the average of all asset log returns per time period
This assumes an equally weighted index
index_log_returns <- rowMeans(returns_data, na.rm = TRUE) # Mean log return of all assets
Adding index returns to the matrix of returns for analysis
Ensure that ‘index_log_returns’ is properly formatted to match dimensions
It should be a single column matrix to bind with ‘returns_data’
index_log_returns_matrix <- matrix(index_log_returns, ncol = 1)
Adding the index returns as a new column in ‘returns_data’
all_returns_data <- cbind(returns_data, index_log_returns_matrix)
Providing appropriate column names, especially for the newly added index
colnames(all_returns_data) <- c(colnames(returns_data), “Index Returns”)
Ensure all_returns_data is in a format acceptable by fPortfolio::basicStats
library(fPortfolio)
if (!is.timeSeries(all_returns_data)) {
all_returns_data <- as.timeSeries(all_returns_data)
}
Estimate Summary Statistics for the Returns (Both Individual Assets and the “Market Index”)
summary_stats <- basicStats(all_returns_data)
print(summary_stats)
{r}
Recalculate with explicit column creation for RewardToRisk
assets <- assets %>%
mutate(RewardToRisk = MedianReturn / StandardDeviation)
Now proceed with Strategy 1 selection, ensuring the RewardToRisk column exists.
strategy1_selection <- assets %>%
arrange(desc(RewardToRisk)) %>%
group_by(Category) %>%
mutate(rank = row_number()) %>%
ungroup() %>%
filter((Category == “Forex” & rank == 1) | (Category == “Commodities” & rank == 1) | Category == “Stocks”) %>%
arrange(desc(RewardToRisk)) %>%
head(5)
if (nrow(filter(strategy1_selection, Category == “Forex”)) < 1 || nrow(filter(strategy1_selection, Category == “Commodities”)) < 1) {
print(“Adjust selection to meet criteria”)
} else {
print(“Strategy 1 Selection:”)
print(strategy1_selection)
}
Attempt Strategy 2 selection
strategy2_selection <- assets %>%
arrange(PERatio) %>%
group_by(Category) %>%
mutate(rank = row_number()) %>%
ungroup() %>%
filter((Category == “Forex” & rank == 1) | (Category == “Commodities” & rank == 1) | Category == “Stocks”) %>%
arrange(PERatio) %>%
head(5)
if (nrow(filter(strategy2_selection, Category == “Forex”)) < 1 || nrow(filter(strategy2_selection, Category == “Commodities”)) < 1) {
print(“Adjust selection to meet criteria”)
} else {
print(“Strategy 2 Selection:”)
print(strategy2_selection)
}
Export (Choose accordingly based on your selected strategy)
write.csv(strategy1_selection, “Strategy1Selection.csv”)
write.csv(strategy2_selection, “Strategy2Selection.csv”) # Use write.xlsx for .xlsx files, but that requires the openxlsx or writexl package.
{r}
Load necessary libraries
library(ggplot2)
library(corrplot) # For correlation plots
Assuming ‘strategy1_selection’ and ‘strategy2_selection’ have been defined as before
For the purpose of this example, let’s assume you’re exploring these metrics
metrics <- c(“MedianReturn”, “StandardDeviation”, “PERatio”, “RewardToRisk”)
Combine Strategy 1 and 2 selections for analysis
combined_selection <- rbind(
mutate(strategy1_selection, Strategy = ‘1’),
mutate(strategy2_selection, Strategy = ‘2’)
)
HISTOGRAMS with ggplot2
Using ggplot2 for histogram because it’s flexible and powerful
for(metric in metrics) {
ggplot(combined_selection, aes_string(x = metric)) +
geom_histogram(bins = 30, fill = “#69b3a2”, color = “#e9ecef”) +
facet_wrap(~Strategy) +
labs(title = paste(“Histogram of”, metric), x = metric, y = “Frequency”) +
theme_minimal() -> p
print§
}
Q-Q PLOTS
Base R’s qqnorm and qqline for demonstration, customized for each metric
for(metric in metrics) {
qqnorm(combined_selection[[metric]], main = paste(“Q-Q Plot of”, metric))
qqline(combined_selection[[metric]], col = ‘steelblue’, lwd = 2)
}
BOX PLOTS with ggplot2
Again, using ggplot2 for refined visualizations
for(metric in metrics) {
ggplot(combined_selection, aes_string(x = “Strategy”, y = metric)) +
geom_boxplot(fill = “#009E73”) +
labs(title = paste(“Box Plot of”, metric), x = “Strategy”, y = metric) +
theme_minimal() -> p
print§
}
CORRELATION PLOT
Calculate correlations among metrics for combined_selection
Note: Ensure combined_selection[metrics] does not include non-numeric columns
cor_matrix <- cor(combined_selection[metrics], use = “complete.obs”)
Use corrplot for visualization
corrplot(cor_matrix, method = “circle”, type = “upper”, tl.cex = 0.8, tl.col = “black”)
The above is already done like calculating log returns as well…now say what should i do with that error After this i am doing "{r}
library(quadprog)
library(PerformanceAnalytics)
Assuming ‘selected_returns1’ and ‘selected_returns2’ are your log returns for Strategy 1 & 2
Define risk-free rate, adjust this as per your data
rf_rate <- 0.03
Function to calculate portfolio return
calc_portfolio_return <- function(weights, returns) {
sum(weights * colMeans(returns))
}
Function to calculate portfolio variance
calc_portfolio_variance <- function(weights, cov_matrix) {
sum((weights %*% cov_matrix) * weights)
}
Function to calculate Sharpe ratio
calc_sharpe_ratio <- function(portfolio_return, portfolio_variance, rf_rate) {
(portfolio_return - rf_rate) / sqrt(portfolio_variance)
}
GMVP calculation using ‘quadprog’ package
calculate_GMVP <- function(returns) {
dvec <- rep(0, ncol(returns)) # Objective function is to minimize variance which is quadprog’s dvec
Amat <- cbind(1, diag(ncol(returns))) # Adding constraint for weights sum = 1
bvec <- c(1, rep(0, ncol(returns))) # Boundary conditions
solve.QP(cov(returns)*2, dvec, Amat, bvec, meq = 1)$solution
}
Assuming ‘selected_returns1’ and ‘selected_returns2’ are matrices of log returns under both strategies
weights_GMVP1 <- calculate_GMVP(selected_returns1)
weights_GMVP2 <- calculate_GMVP(selected_returns2)
Implement Tangency portfolio assuming it’s similarly created based on your own framework
Print weights for GMVP
print(weights_GMVP1)
print(weights_GMVP2)
Calculate portfolio return and variance for GMVP
gmvp1_return <- calc_portfolio_return(weights_GMVP1, selected_returns1)
gmvp1_variance <- calc_portfolio_variance(weights_GMVP1, cov(selected_returns1))
gmvp1_sharpe <- calc_sharpe_ratio(gmvp1_return, gmvp1_variance, rf_rate)
gmvp2_return <- calc_portfolio_return(weights_GMVP2, selected_returns2)
gmvp2_variance <- calc_portfolio_variance(weights_GMVP2, cov(selected_returns2))
gmvp2_sharpe <- calc_sharpe_ratio(gmvp2_return, gmvp2_variance, rf_rate)
Print results for GMVP
cat(“GMVP Strategy 1 Return:”, gmvp1_return, “Variance:”, gmvp1_variance, “Sharpe Ratio:”, gmvp1_sharpe, “\n”)
cat(“GMVP Strategy 2 Return:”, gmvp2_return, “Variance:”, gmvp2_variance, “Sharpe Ratio:”, gmvp2_sharpe, “\n”)"...................................here i got weights_GMVP2 <- calculate_GMVP(selected_returns2)
Error: object 'selected_returns2' not found this error