library(ggplot2)
library(dplyr)
library(scales)  # Load scales package
library(gridExtra)

data$End_week_date <- as.Date(data$End_week_date)
print("Converted End_week_date to Date format")

harvest_periods <- New_data %>%
  filter(Crop_Progression > 0)  %>%
  group_by(Year) %>% 
  summarise(start = min(End_week_date), end = max(End_week_date))
print("Harvest periods calculated")

harvest_periods$start <- as.Date(harvest_periods$start)
harvest_periods$end <- as.Date(harvest_periods$end)
print("Start and end dates in harvest periods converted to Date format")

# Function to create plots for specified date ranges
create_basis_plot <- function(data, start_date, end_date, harvest_periods) {
  print(paste("Creating basis plot for range:", start_date, "to", end_date))
  # Filter data based on the provided date range
  filtered_data <- data %>%
    filter(End_week_date >= as.Date(start_date) & End_week_date < as.Date(end_date))
  print(paste("Filtered data for the specified date range:", nrow(filtered_data), "rows"))
  
  # Create the plot
  date_breaks <- seq(from = as.Date("2005-01-01"), to = as.Date("2025-01-01"), by = "1 year")
  p <- ggplot(filtered_data) +
    geom_line(aes(x = End_week_date, y = DEC_BASIS, color = "DEC_BASIS"), size = 0.5) +
    geom_line(aes(x = End_week_date, y = PEO_BASIS, color = "PEO_BASIS"), size = 0.5) +
    geom_line(aes(x = End_week_date, y = ESL_BASIS, color = "ESL_BASIS"), size = 0.5) +
    geom_rect(data = harvest_periods %>% 
                filter(Year >= as.numeric(format(as.Date(start_date), "%Y")) & 
                         Year < as.numeric(format(as.Date(end_date), "%Y"))),
              aes(xmin = start, xmax = end, ymin = -Inf, ymax = Inf),
              fill = "darkgrey", alpha = 0.3) +
    labs(title = "Basis", x = "Date", y = "Basis Value") +
    scale_color_manual(values = c("DEC_BASIS" = "darkblue", 
                                  "PEO_BASIS" = "darkgreen", 
                                  "ESL_BASIS" = "darkred")) +
    guides(color = "none") +  # Remove legend
    scale_y_continuous(breaks = scales::pretty_breaks(n = 10)) +
    scale_x_date(
      breaks = scales::date_breaks("1 year"),
      labels = scales::date_format("%Y"),
      limits = c(min(filtered_data$End_week_date), max(filtered_data$End_week_date))  # Set limits based on data
    ) +
    theme_minimal(base_size = 10) +
    theme(
      axis.text.x = element_text(angle = 45, hjust = 1, size = 14),
      axis.text.y = element_text(size = 14),
      axis.title.x = element_text(size = 16),
      axis.title.y = element_text(size = 16),
      plot.title = element_text(size = 18, face = "bold")
    )
  
  print("Basis plot created")
  return(p)
}

# Function to create futures price plots for specified date ranges
create_futures_plot <- function(data, start_date, end_date, harvest_periods) {
  print(paste("Creating futures plot for range:", start_date, "to", end_date))
  # Filter data based on the provided date range
  filtered_data <- data %>%
    filter(End_week_date >= as.Date(start_date) & End_week_date < as.Date(end_date))
  print(paste("Filtered data for the specified date range:", nrow(filtered_data), "rows"))
  
  # Create the plot
  p <- ggplot(filtered_data) +
    geom_line(aes(x = End_week_date, y = FUT_1, color = "FUT_1"), size = 0.5) +
    geom_line(aes(x = End_week_date, y = FUT_2, color = "FUT_2"), size = 0.5) +
    geom_rect(data = harvest_periods %>% 
                filter(Year >= as.numeric(format(as.Date(start_date), "%Y")) & 
                         Year < as.numeric(format(as.Date(end_date), "%Y"))),
              aes(xmin = start, xmax = end, ymin = -Inf, ymax = Inf),
              fill = "darkgrey", alpha = 0.3) +
    labs(title = "Futures Prices", x = "Date", y = "Price") +
    scale_color_manual(values = c("FUT_1" = "darkviolet", "FUT_2" = "darkturquoise")) +
    guides(color = "none") +  # Remove legend
    scale_y_continuous(breaks = scales::pretty_breaks(n = 10)) +
    scale_x_date(breaks = date_breaks, labels = scales::date_format("%Y")) +  # Yearly breaks
    theme_minimal(base_size = 10) +
    theme(
      axis.text.x = element_text(angle = 45, hjust = 1, size = 14),
      axis.text.y = element_text(size = 14),
      axis.title.x = element_text(size = 16),
      axis.title.y = element_text(size = 16),
      plot.title = element_text(size = 18, face = "bold")
    )
  
  print("Futures plot created")
  return(p)
}

# Example usage of the function
print("Creating plots for 2005-2010")
p1 <- create_basis_plot(data, "2005-01-01", "2010-01-01", harvest_periods)
p2 <- create_basis_plot(data, "2010-01-01", "2015-01-01", harvest_periods)
p3 <- create_basis_plot(data, "2015-01-01", "2020-01-01", harvest_periods)
p4 <- create_basis_plot(data, "2020-01-01", "2025-01-01", harvest_periods)
p5 <- create_basis_plot(data, "2005-01-01", "2025-01-01", harvest_periods)

# Example usage of the function
p1_future <- create_futures_plot(data, "2005-01-01", "2010-01-01", harvest_periods)
p2_future <- create_futures_plot(data, "2010-01-01", "2015-01-01", harvest_periods)
p3_future <- create_futures_plot(data, "2015-01-01", "2020-01-01", harvest_periods)
p4_future <- create_futures_plot(data, "2020-01-01", "2025-01-01", harvest_periods)
p5_future <- create_futures_plot(data, "2005-01-01", "2025-01-01", harvest_periods)

print("Created all individual plots")

# Create a combined legend
legend <- ggplot() +
  scale_color_manual(name = "Legend",
                     values = c("DEC_BASIS" = "darkblue", 
                                "PEO_BASIS" = "darkgreen", 
                                "ESL_BASIS" = "darkred",
                                "FUT_1" = "darkviolet",
                                "FUT_2" = "darkturquoise"),
                     breaks = c("FUT_1", "FUT_2", "DEC_BASIS", "PEO_BASIS", "ESL_BASIS")) +
  geom_line(aes(x = 1, y = 1, color = "DEC_BASIS"), size = 5) +
  geom_line(aes(x = 1, y = 2, color = "PEO_BASIS"), size = 5) +
  geom_line(aes(x = 1, y = 3, color = "ESL_BASIS"), size = 5) +
  geom_line(aes(x = 1, y = 4, color = "FUT_1"), size = 5) +
  geom_line(aes(x = 1, y = 5, color = "FUT_2"), size = 5) +
  theme_void() +
  theme(legend.position = "bottom")

print("Legend created")

# Combine all plots and the new legend with an explicit layout
grid.arrange(
  p1_future,
  p1,
  legend,
  nrow = 3,
  top = "Time Series (2005-2010)",
  heights = c(1, 1, 0.2)
)
print("Combined 2005-2010 plot")

grid.arrange(
  p2_future,
  p2,
  legend,
  nrow = 3,
  top = "Time Series (2010-2015)",
  heights = c(1, 1, 0.2)
)
print("Combined 2010-2015 plot")

grid.arrange(
  p3_future,
  p3,
  legend,
  nrow = 3,
  top = "Time Series (2015-2020)",
  heights = c(1, 1, 0.2)
)
print("Combined 2015-2020 plot")

grid.arrange(
  p4_future,
  p4,
  legend,
  nrow = 3,
  top = "Time Series (2020-2025)",
  heights = c(1, 1, 0.2)
)
print("Combined 2020-2025 plot")

grid.arrange(
  p5_future, 
  p5,
  legend,
  nrow = 3,
  top = "Time Series (2005-2025)",
  heights = c(1, 1, 0.2)
)
print("Combined 2005-2025 plot")






> library(ggplot2)
> library(dplyr)
> library(scales)  # Load scales package
> library(gridExtra)
> 
> data$End_week_date <- as.Date(data$End_week_date)
> print("Converted End_week_date to Date format")
[1] "Converted End_week_date to Date format"
> 
> harvest_periods <- New_data %>%
+   filter(Crop_Progression > 0)  %>%
+   group_by(Year) %>% 
+   summarise(start = min(End_week_date), end = max(End_week_date))
> print("Harvest periods calculated")
[1] "Harvest periods calculated"
> 
> harvest_periods$start <- as.Date(harvest_periods$start)
> harvest_periods$end <- as.Date(harvest_periods$end)
> print("Start and end dates in harvest periods converted to Date format")
[1] "Start and end dates in harvest periods converted to Date format"
> 
> # Function to create plots for specified date ranges
> create_basis_plot <- function(data, start_date, end_date, harvest_periods) {
+   print(paste("Creating basis plot for range:", start_date, "to", end_date))
+   # Filter data based on the provided date range
+   filtered_data <- data %>%
+     filter(End_week_date >= as.Date(start_date) & End_week_date < as.Date(end_date))
+   print(paste("Filtered data for the specified date range:", nrow(filtered_data), "rows"))
+   
+   # Create the plot
+   date_breaks <- seq(from = as.Date("2005-01-01"), to = as.Date("2025-01-01"), by = "1 year")
+   p <- ggplot(filtered_data) +
+     geom_line(aes(x = End_week_date, y = DEC_BASIS, color = "DEC_BASIS"), size = 0.5) +
+     geom_line(aes(x = End_week_date, y = PEO_BASIS, color = "PEO_BASIS"), size = 0.5) +
+     geom_line(aes(x = End_week_date, y = ESL_BASIS, color = "ESL_BASIS"), size = 0.5) +
+     geom_rect(data = harvest_periods %>% 
+                 filter(Year >= as.numeric(format(as.Date(start_date), "%Y")) & 
+                          Year < as.numeric(format(as.Date(end_date), "%Y"))),
+               aes(xmin = start, xmax = end, ymin = -Inf, ymax = Inf),
+               fill = "darkgrey", alpha = 0.3) +
+     labs(title = "Basis", x = "Date", y = "Basis Value") +
+     scale_color_manual(values = c("DEC_BASIS" = "darkblue", 
+                                   "PEO_BASIS" = "darkgreen", 
+                                   "ESL_BASIS" = "darkred")) +
+     guides(color = "none") +  # Remove legend
+     scale_y_continuous(breaks = scales::pretty_breaks(n = 10)) +
+     scale_x_date(
+       breaks = scales::date_breaks("1 year"),
+       labels = scales::date_format("%Y"),
+       limits = c(min(filtered_data$End_week_date), max(filtered_data$End_week_date))  # Set limits based on data
+     ) +
+     theme_minimal(base_size = 10) +
+     theme(
+       axis.text.x = element_text(angle = 45, hjust = 1, size = 14),
+       axis.text.y = element_text(size = 14),
+       axis.title.x = element_text(size = 16),
+       axis.title.y = element_text(size = 16),
+       plot.title = element_text(size = 18, face = "bold")
+     )
+   
+   print("Basis plot created")
+   return(p)
+ }
> 
> # Function to create futures price plots for specified date ranges
> create_futures_plot <- function(data, start_date, end_date, harvest_periods) {
+   print(paste("Creating futures plot for range:", start_date, "to", end_date))
+   # Filter data based on the provided date range
+   filtered_data <- data %>%
+     filter(End_week_date >= as.Date(start_date) & End_week_date < as.Date(end_date))
+   print(paste("Filtered data for the specified date range:", nrow(filtered_data), "rows"))
+   
+   # Create the plot
+   p <- ggplot(filtered_data) +
+     geom_line(aes(x = End_week_date, y = FUT_1, color = "FUT_1"), size = 0.5) +
+     geom_line(aes(x = End_week_date, y = FUT_2, color = "FUT_2"), size = 0.5) +
+     geom_rect(data = harvest_periods %>% 
+                 filter(Year >= as.numeric(format(as.Date(start_date), "%Y")) & 
+                          Year < as.numeric(format(as.Date(end_date), "%Y"))),
+               aes(xmin = start, xmax = end, ymin = -Inf, ymax = Inf),
+               fill = "darkgrey", alpha = 0.3) +
+     labs(title = "Futures Prices", x = "Date", y = "Price") +
+     scale_color_manual(values = c("FUT_1" = "darkviolet", "FUT_2" = "darkturquoise")) +
+     guides(color = "none") +  # Remove legend
+     scale_y_continuous(breaks = scales::pretty_breaks(n = 10)) +
+     scale_x_date(breaks = date_breaks, labels = scales::date_format("%Y")) +  # Yearly breaks
+     theme_minimal(base_size = 10) +
+     theme(
+       axis.text.x = element_text(angle = 45, hjust = 1, size = 14),
+       axis.text.y = element_text(size = 14),
+       axis.title.x = element_text(size = 16),
+       axis.title.y = element_text(size = 16),
+       plot.title = element_text(size = 18, face = "bold")
+     )
+   
+   print("Futures plot created")
+   return(p)
+ }
> 
> # Example usage of the function
> print("Creating plots for 2005-2010")
[1] "Creating plots for 2005-2010"
> p1 <- create_basis_plot(data, "2005-01-01", "2010-01-01", harvest_periods)
[1] "Creating basis plot for range: 2005-01-01 to 2010-01-01"
[1] "Filtered data for the specified date range: 209 rows"
[1] "Basis plot created"
> p2 <- create_basis_plot(data, "2010-01-01", "2015-01-01", harvest_periods)
[1] "Creating basis plot for range: 2010-01-01 to 2015-01-01"
[1] "Filtered data for the specified date range: 258 rows"
[1] "Basis plot created"
> p3 <- create_basis_plot(data, "2015-01-01", "2020-01-01", harvest_periods)
[1] "Creating basis plot for range: 2015-01-01 to 2020-01-01"
[1] "Filtered data for the specified date range: 259 rows"
[1] "Basis plot created"
> p4 <- create_basis_plot(data, "2020-01-01", "2025-01-01", harvest_periods)
[1] "Creating basis plot for range: 2020-01-01 to 2025-01-01"
[1] "Filtered data for the specified date range: 217 rows"
[1] "Basis plot created"
> p5 <- create_basis_plot(data, "2005-01-01", "2025-01-01", harvest_periods)
[1] "Creating basis plot for range: 2005-01-01 to 2025-01-01"
[1] "Filtered data for the specified date range: 943 rows"
[1] "Basis plot created"
> 
> # Example usage of the function
> p1_future <- create_futures_plot(data, "2005-01-01", "2010-01-01", harvest_periods)
[1] "Creating futures plot for range: 2005-01-01 to 2010-01-01"
[1] "Filtered data for the specified date range: 209 rows"
[1] "Futures plot created"
> p2_future <- create_futures_plot(data, "2010-01-01", "2015-01-01", harvest_periods)
[1] "Creating futures plot for range: 2010-01-01 to 2015-01-01"
[1] "Filtered data for the specified date range: 258 rows"
[1] "Futures plot created"
> p3_future <- create_futures_plot(data, "2015-01-01", "2020-01-01", harvest_periods)
[1] "Creating futures plot for range: 2015-01-01 to 2020-01-01"
[1] "Filtered data for the specified date range: 259 rows"
[1] "Futures plot created"
> p4_future <- create_futures_plot(data, "2020-01-01", "2025-01-01", harvest_periods)
[1] "Creating futures plot for range: 2020-01-01 to 2025-01-01"
[1] "Filtered data for the specified date range: 217 rows"
[1] "Futures plot created"
> p5_future <- create_futures_plot(data, "2005-01-01", "2025-01-01", harvest_periods)
[1] "Creating futures plot for range: 2005-01-01 to 2025-01-01"
[1] "Filtered data for the specified date range: 943 rows"
[1] "Futures plot created"
> 
> print("Created all individual plots")
[1] "Created all individual plots"
> 
> # Create a combined legend
> legend <- ggplot() +
+   scale_color_manual(name = "Legend",
+                      values = c("DEC_BASIS" = "darkblue", 
+                                 "PEO_BASIS" = "darkgreen", 
+                                 "ESL_BASIS" = "darkred",
+                                 "FUT_1" = "darkviolet",
+                                 "FUT_2" = "darkturquoise"),
+                      breaks = c("FUT_1", "FUT_2", "DEC_BASIS", "PEO_BASIS", "ESL_BASIS")) +
+   geom_line(aes(x = 1, y = 1, color = "DEC_BASIS"), size = 5) +
+   geom_line(aes(x = 1, y = 2, color = "PEO_BASIS"), size = 5) +
+   geom_line(aes(x = 1, y = 3, color = "ESL_BASIS"), size = 5) +
+   geom_line(aes(x = 1, y = 4, color = "FUT_1"), size = 5) +
+   geom_line(aes(x = 1, y = 5, color = "FUT_2"), size = 5) +
+   theme_void() +
+   theme(legend.position = "bottom")
> 
> print("Legend created")
[1] "Legend created"
> 
> # Combine all plots and the new legend with an explicit layout
> grid.arrange(
+   p1_future,
+   p1,
+   legend,
+   nrow = 3,
+   top = "Time Series (2005-2010)",
+   heights = c(1, 1, 0.2)
+ )
Error in `transformation$transform()`:
! `transform_date()` works with objects of
  class <Date> only
Run `rlang::last_trace()` to see where the error occurred.
> rlang::last_trace()
<error/rlang_error>
Error in `transformation$transform()`:
! `transform_date()` works with objects of
  class <Date> only
---
Backtrace:
     ▆
  1. └─gridExtra::grid.arrange(...)
  2.   └─gridExtra::arrangeGrob(...)
  3.     └─base::lapply(grobs[toconv], ggplot2::ggplotGrob)
  4.       └─ggplot2 (local) FUN(X[[i]], ...)
  5.         ├─ggplot2::ggplot_gtable(ggplot_build(x))
  6.         │ └─ggplot2:::attach_plot_env(data$plot$plot_env)
  7.         │   └─base::options(ggplot2_plot_env = env)
  8.         ├─ggplot2::ggplot_build(x)
  9.         └─ggplot2:::ggplot_build.ggplot(x)
 10.           └─layout$setup_panel_params()
 11.             └─ggplot2 (local) setup_panel_params(..., self = self)
 12.               └─base::Map(setup_panel_params, scales_x, scales_y)
 13.                 └─base::mapply(FUN = f, ..., SIMPLIFY = FALSE)
 14.                   └─ggplot2 (local) `<fn>`(dots[[1L]][[1L]], dots[[2L]][[1L]])
 15.                     └─self$coord$setup_panel_params(scale_x, scale_y, params = self$coord_params)
 16.                       └─ggplot2 (local) setup_panel_params(..., self = self)
 17.                         └─ggplot2:::view_scales_from_scale(scale_x, self$limits$x, self$expand)
 18.                           └─ggplot2:::view_scale_primary(scale, limits, continuous_range)
 19.                             └─scale$get_breaks(continuous_scale_sorted)
 20.                               └─ggplot2 (local) get_breaks(..., self = self)
 21.                                 └─ggproto_parent(ScaleContinuous, self)$get_breaks(limits)
 22.                                   └─ggplot2 (local) get_breaks(..., self = self)
 23.                                     └─transformation$transform(breaks)
Run rlang::last_trace(drop = FALSE) to see 2 hidden frames.