R Markdown

Install required packages

install.packages(c(“quantmod”, “PerformanceAnalytics”, “pbapply”, “data.table”))

Load necessary libraries

library(quantmod) library(PerformanceAnalytics) library(pbapply) library(data.table)

Step 1: Load Historical Data

symbols <- c(“AAPL”, “MSFT”, “GOOGL”) # Example stocks getSymbols(symbols, src = “yahoo”, from = “2020-01-01”, to = “2025-01-01”, auto.assign = TRUE)

Extract adjusted closing prices and merge into a data frame

prices <- do.call(merge, lapply(symbols, function(sym) Cl(get(sym)))) colnames(prices) <- symbols

Step 2: Calculate Momentum

momentum <- function(price_data, n = 60) { ROC(price_data, n = n, type = “discrete”) }

Compute momentum for all assets

momentum_data <- na.omit(momentum(prices))

Step 3: Portfolio Rebalancing

rebalance_portfolio <- function(momentum_data, top_n = 5) { latest_momentum <- tail(momentum_data, 1) selected <- names(sort(latest_momentum, decreasing = TRUE)[1:top_n]) # Select top N assets return(selected) }

Step 4: Evaluate Performance

evaluate_performance <- function(asset) { returns <- Return.calculate(Cl(get(asset))) charts.PerformanceSummary(returns) }

Apply strategy

selected_assets <- rebalance_portfolio(momentum_data) print(paste(“Selected assets:”, paste(selected_assets, collapse = “,”)))

Evaluate performance for selected assets

lapply(selected_assets, evaluate_performance)