# Load the txt file
data <- read.table("6_Portfolios_2x3 edited.txt", skip = 11, header = FALSE)

# Rename columns
colnames(data) <- c("Date", "SL", "SM", "SH", "BL", "BM", "BH")

# Convert Date to numeric
data$Date <- as.numeric(data$Date)

# Keep Jan 1930 - Dec 2018
data <- subset(data, Date >= 193001 & Date <= 201812)

# Replace missing values
data[data == -99.99] <- NA
data[data == -999] <- NA

# Remove rows with NA
data <- na.omit(data)

# Keep only portfolio returns
returns <- data[, 2:7]
# Split dataset in half
n <- nrow(returns)
half <- floor(n / 2)
first_half <- returns[1:half, ]
second_half <- returns[(half + 1):n, ]
# Install/load package for skewness & kurtosis
if (!require(moments)) install.packages("moments", repos = "https://cran.r-project.org")
## Loading required package: moments
library(moments)

# Function to compute statistics
calc_stats <- function(x) {
  data.frame(
    Mean     = round(apply(x, 2, mean),     4),
    SD       = round(apply(x, 2, sd),       4),
    Skewness = round(apply(x, 2, skewness), 4),
    Kurtosis = round(apply(x, 2, kurtosis), 4)
  )
}

# Compute statistics
stats_first  <- calc_stats(first_half)
stats_second <- calc_stats(second_half)

# Print results
cat("===== FIRST HALF =====\n")
## ===== FIRST HALF =====
print(stats_first)
##        Mean       SD Skewness Kurtosis
## SL 168.9127 386.3932   2.4928   8.1160
## SM 185.2396 378.5362   2.1073   6.0899
## SH 213.2045 455.8514   2.3740   7.8312
## BL 193.2564 327.7421   2.4341   9.2749
## BM 149.7639 253.7822   2.9231  14.1226
## BH  95.8329 235.1379   5.2952  37.6979
cat("===== SECOND HALF =====\n")
## ===== SECOND HALF =====
print(stats_second)
##         Mean        SD Skewness Kurtosis
## SL   38.8416  142.3184   4.3729  22.8237
## SM   37.9919  136.5532   4.2713  21.5158
## SH   22.6995   78.1955   4.4623  23.7303
## BL 1414.4932 4952.0677   3.9410  19.0677
## BM 1000.1574 3634.3422   4.3112  22.0722
## BH  892.4264 3428.9861   4.7594  26.8721