O danych

Zestaw danych zawiera oferty sprzedaży (na przestrzeni dwunastu miesięcy) oraz oferty wynajmu (na przestrzeni ośmiu miesięcy) mieszkań z 15 największych miast w Polsce (Warszawa, Łódź, Kraków, Wrocław, Poznań, Gdańsk, Szczecin, Bydgoszcz, Lublin, Katowice, Białystok, Częstochowa). Dane pochodzą z lokalnych stron internetowych z ogłoszeniami o sprzedaży mieszkań. Aby jeszcze lepiej uchwycić cechy otoczenia każdego mieszkania, każda oferta została uzupełniona o dane z OpenStreetMap, zawierające odległości do punktów zainteresowania (POI – Points of Interest).

Dane są zbierane miesięcznie i obejmują okres od sierpnia 2023 roku do czerwca 2024 roku.

Parametry danych

  1. city - nazwa miasta, w którym znajduje się mieszkanie
  2. squareMeters - powierzchnia mieszkania w metrach kwadratowych
  3. rooms - liczba pomieszczeń w mieszkaniu
  4. floor,floorCount - piętro, na którym znajduje się mieszkanie oraz całkowita liczba pięter w mieszkaniu
  5. buildYear - rok wybudowania
  6. latitude, longitude - wysokość oraz szerokość geograficzna
  7. centreDistance - odległość od centrum mierzona w kilometrach
  8. poiCount - liczba POI w promieniu 500 metrów od mieszkania (szkoły, kliniki, poczty, przedszkola, restauracje, wydziały, apteki)
  9. [poiName]Distance - odległość od najblższego zadanego POI (szkoły, kliniki, poczty, przedszkola, restauracje, wydziały, apteki)
  10. condition - stan mieszkania
  11. has[features] - kluczowe cechy takie jak , balkon, winda, ochrona, schowek
  12. price - cena oferty w złotówkach
files_rent <- list.files("rent", pattern = "\\.csv$", full.names = TRUE)
files_apartments <- list.files("apartments", pattern = "\\.csv$", full.names = TRUE)
files_rent <- sort(files_rent)
files_apartments <- sort(files_apartments)

rent_list <- lapply(seq_along(files_rent), function(i) {
  d <- read.csv(files_rent[i])
  d$offer_type = "rent"
  d$month_id = i + 3
  d
})

apartments_list <- lapply(seq_along(files_apartments), function(i) {
  d <- read.csv(files_apartments[i])
  d$offer_type = "apartment"
  d$month_id = i
  d
})

df <- do.call(rbind, c(rent_list, apartments_list))

df$price_m2 <- df$price / df$squareMeters
df$log_price <- log10(df$price)
df$log_price_m2 <- log10(df$price_m2)
df$floor_ratio <- df$floor / df$floorCount
df$age <- 2024 - df$buildYear

df$city <- as.factor(df$city)
df$offer_type <- as.factor(df$offer_type)

has_cols <- grep("^has", names(df), value = TRUE)

df[has_cols] <- lapply(df[has_cols], function(x) {
  tolower(x) == "yes"
})

df <- df %>%
  group_by(city) %>%
  mutate(
    latitude_n  = as.numeric(scale(latitude)),
    longitude_n = as.numeric(scale(longitude))
  ) %>%
  ungroup() %>%
  group_by(offer_type) %>%
  mutate(
    price_n  = as.numeric(scale(price)),
    price_m2_n = as.numeric(scale(price_m2)),
    log_price_n = as.numeric(scale(log_price)),
    log_price_m2_n = as.numeric(scale(log_price_m2))
  ) %>%
  ungroup()


df <- df %>%
  mutate(city = str_to_title(city))

rent <- df[df$offer_type == "rent",]
rent_warsaw <- rent[rent$city == "Warszawa",]
apartments <- df[df$offer_type == "apartment",]
apartments_warsaw <- apartments[apartments$city == "Warszawa",]

Wstępna analiza

summary(rent)
##          id               city              type        squareMeters   
##  Length   :70847   Length   :70847   Length   :70847   Min.   : 25.00  
##  N.unique :37941   N.unique :   15   N.unique :    4   1st Qu.: 40.00  
##  N.blank  :    0   N.blank  :    0   N.blank  :16762   Median : 50.00  
##  Min.nchar:   32   Min.nchar:    4   Min.nchar:    0   Mean   : 55.25  
##  Max.nchar:   32   Max.nchar:   11   Max.nchar:   17   3rd Qu.: 64.00  
##                                                        Max.   :150.00  
##                                                                        
##      rooms           floor         floorCount       buildYear    
##  Min.   :1.000   Min.   : 1.00   Min.   : 1.000   Min.   :1850   
##  1st Qu.:2.000   1st Qu.: 2.00   1st Qu.: 4.000   1st Qu.:1984   
##  Median :2.000   Median : 3.00   Median : 5.000   Median :2010   
##  Mean   :2.385   Mean   : 3.42   Mean   : 5.687   Mean   :1998   
##  3rd Qu.:3.000   3rd Qu.: 4.00   3rd Qu.: 7.000   3rd Qu.:2020   
##  Max.   :6.000   Max.   :30.00   Max.   :30.000   Max.   :2024   
##                  NAs    :8613    NAs    :1379     NAs    :19682  
##     latitude       longitude     centreDistance      poiCount     
##  Min.   :49.98   Min.   :14.45   Min.   : 0.020   Min.   :  0.00  
##  1st Qu.:51.08   1st Qu.:18.65   1st Qu.: 1.770   1st Qu.:  9.00  
##  Median :52.19   Median :19.96   Median : 3.380   Median : 17.00  
##  Mean   :51.79   Mean   :19.69   Mean   : 3.856   Mean   : 25.21  
##  3rd Qu.:52.25   3rd Qu.:21.01   3rd Qu.: 5.420   3rd Qu.: 30.00  
##  Max.   :54.58   Max.   :23.20   Max.   :16.620   Max.   :210.00  
##                                                                   
##  schoolDistance   clinicDistance   postOfficeDistance kindergartenDistance
##  Min.   :0.0020   Min.   :0.0010   Min.   :0.0010     Min.   :0.0010      
##  1st Qu.:0.1740   1st Qu.:0.3020   1st Qu.:0.2350     1st Qu.:0.1530      
##  Median :0.2850   Median :0.5500   Median :0.3880     Median :0.2590      
##  Mean   :0.3688   Mean   :0.7763   Mean   :0.4702     Mean   :0.3272      
##  3rd Qu.:0.4490   3rd Qu.:0.9700   3rd Qu.:0.5850     3rd Qu.:0.4010      
##  Max.   :4.8560   Max.   :4.9900   Max.   :4.9390     Max.   :4.7510      
##  NAs    :15       NAs    :50       NAs    :26         NAs    :43          
##  restaurantDistance collegeDistance pharmacyDistance     ownership    
##  Min.   :0.001      Min.   :0.004   Min.   :0.0010   Length   :70847  
##  1st Qu.:0.087      1st Qu.:0.520   1st Qu.:0.1360   N.unique :    1  
##  Median :0.180      Median :0.971   Median :0.2310   N.blank  :    0  
##  Mean   :0.261      Mean   :1.287   Mean   :0.3089   Min.nchar:   11  
##  3rd Qu.:0.329      3rd Qu.:1.809   3rd Qu.:0.3820   Max.nchar:   11  
##  Max.   :4.961      Max.   :5.000   Max.   :4.9860                    
##  NAs    :154        NAs    :874     NAs    :80                        
##   buildingMaterial     condition     hasParkingSpace hasBalcony     
##  Length   :70847   Length   :70847   Mode :logical   Mode :logical  
##  N.unique :    3   N.unique :    3   FALSE:43075     FALSE:27341    
##  N.blank  :28997   N.blank  :51665   TRUE :27772     TRUE :43506    
##  Min.nchar:    0   Min.nchar:    0                                  
##  Max.nchar:   12   Max.nchar:    7                                  
##                                                                     
##                                                                     
##  hasElevator     hasSecurity     hasStorageRoom      price      
##  Mode :logical   Mode :logical   Mode :logical   Min.   :  346  
##  FALSE:26784     FALSE:60614     FALSE:59833     1st Qu.: 2500  
##  TRUE :44063     TRUE :10233     TRUE :11014     Median : 3100  
##                                                  Mean   : 3853  
##                                                  3rd Qu.: 4490  
##                                                  Max.   :23000  
##                                                                 
##      offer_type       month_id         price_m2        log_price    
##  apartment:    0   Min.   : 4.000   Min.   : 11.30   Min.   :2.539  
##  rent     :70847   1st Qu.: 6.000   1st Qu.: 53.00   1st Qu.:3.398  
##                    Median : 8.000   Median : 65.96   Median :3.491  
##                    Mean   : 7.556   Mean   : 69.20   Mean   :3.528  
##                    3rd Qu.:10.000   3rd Qu.: 81.58   3rd Qu.:3.652  
##                    Max.   :11.000   Max.   :189.47   Max.   :4.362  
##                                                                     
##   log_price_m2    floor_ratio           age           latitude_n      
##  Min.   :1.053   Min.   :0.03571   Min.   :  0.00   Min.   :-3.45140  
##  1st Qu.:1.724   1st Qu.:0.33333   1st Qu.:  4.00   1st Qu.:-0.61459  
##  Median :1.819   Median :0.60000   Median : 14.00   Median : 0.01455  
##  Mean   :1.816   Mean   :0.61286   Mean   : 25.89   Mean   :-0.03835  
##  3rd Qu.:1.912   3rd Qu.:0.87500   3rd Qu.: 40.00   3rd Qu.: 0.52302  
##  Max.   :2.278   Max.   :1.00000   Max.   :174.00   Max.   : 3.07646  
##                  NAs    :8613      NAs    :19682                      
##   longitude_n           price_n          price_m2_n      log_price_n     
##  Min.   :-3.455168   Min.   :-1.4725   Min.   :-2.480   Min.   :-4.6446  
##  1st Qu.:-0.547195   1st Qu.:-0.5680   1st Qu.:-0.694   1st Qu.:-0.6098  
##  Median : 0.006403   Median :-0.3161   Median :-0.139   Median :-0.1709  
##  Mean   :-0.019618   Mean   : 0.0000   Mean   : 0.000   Mean   : 0.0000  
##  3rd Qu.: 0.516635   3rd Qu.: 0.2676   3rd Qu.: 0.530   3rd Qu.: 0.5849  
##  Max.   : 5.091046   Max.   : 8.0398   Max.   : 5.151   Max.   : 3.9180  
##                                                                          
##  log_price_m2_n   
##  Min.   :-5.2481  
##  1st Qu.:-0.6325  
##  Median : 0.0206  
##  Mean   : 0.0000  
##  3rd Qu.: 0.6554  
##  Max.   : 3.1718  
## 
summary(apartments)
##          id                city               type         squareMeters   
##  Length   :195568   Length   :195568   Length   :195568   Min.   : 25.00  
##  N.unique : 92967   N.unique :    15   N.unique :     4   1st Qu.: 44.00  
##  N.blank  :     0   N.blank  :     0   N.blank  : 42261   Median : 54.60  
##  Min.nchar:    32   Min.nchar:     4   Min.nchar:     0   Mean   : 58.70  
##  Max.nchar:    32   Max.nchar:    11   Max.nchar:    17   3rd Qu.: 68.55  
##                                                           Max.   :150.00  
##                                                                           
##      rooms           floor          floorCount       buildYear    
##  Min.   :1.000   Min.   : 1.000   Min.   : 1.000   Min.   :1850   
##  1st Qu.:2.000   1st Qu.: 2.000   1st Qu.: 3.000   1st Qu.:1967   
##  Median :3.000   Median : 3.000   Median : 4.000   Median :1994   
##  Mean   :2.679   Mean   : 3.332   Mean   : 5.309   Mean   :1986   
##  3rd Qu.:3.000   3rd Qu.: 4.000   3rd Qu.: 6.000   3rd Qu.:2016   
##  Max.   :6.000   Max.   :29.000   Max.   :29.000   Max.   :2024   
##                  NAs    :34594    NAs    :2383     NAs    :32216  
##     latitude       longitude     centreDistance      poiCount     
##  Min.   :49.98   Min.   :14.45   Min.   : 0.010   Min.   :  0.00  
##  1st Qu.:51.11   1st Qu.:18.52   1st Qu.: 2.010   1st Qu.:  7.00  
##  Median :52.19   Median :19.90   Median : 3.980   Median : 14.00  
##  Mean   :52.03   Mean   :19.47   Mean   : 4.351   Mean   : 20.67  
##  3rd Qu.:52.41   3rd Qu.:20.99   3rd Qu.: 6.150   3rd Qu.: 24.00  
##  Max.   :54.61   Max.   :23.21   Max.   :16.940   Max.   :212.00  
##                                                                   
##  schoolDistance   clinicDistance   postOfficeDistance kindergartenDistance
##  Min.   :0.0020   Min.   :0.0010   Min.   :0.0010     Min.   :0.0010      
##  1st Qu.:0.1760   1st Qu.:0.3560   1st Qu.:0.2390     1st Qu.:0.1560      
##  Median :0.2900   Median :0.6760   Median :0.3930     Median :0.2620      
##  Mean   :0.4127   Mean   :0.9703   Mean   :0.5163     Mean   :0.3676      
##  3rd Qu.:0.4680   3rd Qu.:1.2370   3rd Qu.:0.6230     3rd Qu.:0.4160      
##  Max.   :4.9460   Max.   :4.9990   Max.   :4.9700     Max.   :4.9610      
##  NAs    :168      NAs    :728      NAs    :248        NAs    :207         
##  restaurantDistance collegeDistance pharmacyDistance     ownership     
##  Min.   :0.0010     Min.   :0.004   Min.   :0.0010   Length   :195568  
##  1st Qu.:0.1140     1st Qu.:0.577   1st Qu.:0.1420   N.unique :     3  
##  Median :0.2290     Median :1.120   Median :0.2390   N.blank  :     0  
##  Mean   :0.3453     Mean   :1.443   Mean   :0.3581   Min.nchar:     6  
##  3rd Qu.:0.4090     3rd Qu.:2.055   3rd Qu.:0.4060   Max.nchar:    11  
##  Max.   :4.9850     Max.   :5.000   Max.   :4.9920                     
##  NAs    :479        NAs    :5436    NAs    :277                        
##   buildingMaterial      condition      hasParkingSpace hasBalcony     
##  Length   :195568   Length   :195568   Mode :logical   Mode :logical  
##  N.unique :     3   N.unique :     3   FALSE:142410    FALSE:83519    
##  N.blank  : 77382   N.blank  :146307   TRUE :53158     TRUE :112049   
##  Min.nchar:     0   Min.nchar:     0                                  
##  Max.nchar:    12   Max.nchar:     7                                  
##                                                                       
##                                                                       
##  hasElevator     hasSecurity     hasStorageRoom      price        
##  Mode :logical   Mode :logical   Mode :logical   Min.   : 150000  
##  FALSE:103364    FALSE:173630    FALSE:110583    1st Qu.: 520000  
##  TRUE :92204     TRUE :21938     TRUE :84985     Median : 699000  
##                                                  Mean   : 784183  
##                                                  3rd Qu.: 930000  
##                                                  Max.   :3250000  
##                                                                   
##      offer_type        month_id         price_m2       log_price    
##  apartment:195568   Min.   : 1.000   Min.   : 3000   Min.   :5.176  
##  rent     :     0   1st Qu.: 3.000   1st Qu.: 9681   1st Qu.:5.716  
##                     Median : 6.000   Median :12979   Median :5.844  
##                     Mean   : 6.182   Mean   :13548   Mean   :5.844  
##                     3rd Qu.: 9.000   3rd Qu.:16770   3rd Qu.:5.968  
##                     Max.   :11.000   Max.   :32097   Max.   :6.512  
##                                                                     
##   log_price_m2    floor_ratio           age           latitude_n      
##  Min.   :3.477   Min.   :0.04167   Min.   :  0.00   Min.   :-3.71358  
##  1st Qu.:3.986   1st Qu.:0.37500   1st Qu.:  8.00   1st Qu.:-0.68352  
##  Median :4.113   Median :0.66667   Median : 30.00   Median : 0.05679  
##  Mean   :4.101   Mean   :0.64014   Mean   : 38.02   Mean   : 0.01389  
##  3rd Qu.:4.225   3rd Qu.:1.00000   3rd Qu.: 57.00   3rd Qu.: 0.69648  
##  Max.   :4.506   Max.   :1.00000   Max.   :174.00   Max.   : 3.48508  
##                  NAs    :34594     NAs    :32216                      
##   longitude_n           price_n          price_m2_n       log_price_n       
##  Min.   :-3.538183   Min.   :-1.5479   Min.   :-2.0994   Min.   :-3.200929  
##  1st Qu.:-0.675968   1st Qu.:-0.6448   1st Qu.:-0.7695   1st Qu.:-0.611967  
##  Median : 0.009675   Median :-0.2079   Median :-0.1133   Median : 0.004085  
##  Mean   : 0.007107   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.000000  
##  3rd Qu.: 0.681978   3rd Qu.: 0.3559   3rd Qu.: 0.6413   3rd Qu.: 0.598712  
##  Max.   : 5.428035   Max.   : 6.0185   Max.   : 3.6919   Max.   : 3.204402  
##                                                                             
##  log_price_m2_n    
##  Min.   :-3.75574  
##  1st Qu.:-0.69366  
##  Median : 0.07238  
##  Mean   : 0.00000  
##  3rd Qu.: 0.74217  
##  Max.   : 2.43884  
## 
df_city <- df %>%
  count(city) %>%
  mutate(
    perc = n / sum(n) * 100,
    label = paste0(round(perc, 1), "%")
  )

rent_city <- rent %>%
  group_by(city) %>%
  summarise(
    mean_price_m2 = mean(price_m2, na.rm = TRUE),
    se = sd(price_m2, na.rm = TRUE) / sqrt(sum(!is.na(price_m2))),
    lwr = mean_price_m2 - qt(0.975, df = sum(!is.na(price_m2)) - 1) * se,
    upr = mean_price_m2 + qt(0.975, df = sum(!is.na(price_m2)) - 1) * se,
    .groups = "drop"
  )

apartments_city <- apartments %>%
  group_by(city) %>%
  summarise(
    mean_price_m2 = mean(price_m2, na.rm = TRUE),
    se = sd(price_m2, na.rm = TRUE) / sqrt(sum(!is.na(price_m2))),
    lwr = mean_price_m2 - qt(0.975, df = sum(!is.na(price_m2)) - 1) * se,
    upr = mean_price_m2 + qt(0.975, df = sum(!is.na(price_m2)) - 1) * se,
    .groups = "drop"
  )


df_city_pie <- df_city %>%
  mutate(
    city = fct_lump(city, n = 7, w = perc),
    city = fct_recode(city, "Inne" = "Other")
  ) %>%
  group_by(city) %>%
  summarise(
    perc = sum(perc),
    .groups = "drop"
  ) %>%
  mutate(city = fct_reorder(city, city == "Inne", .fun = max)) %>%
  arrange(desc(city == "Inne"), desc(perc)) %>%
  mutate(
    city = factor(city, levels = city),
    legend_label = paste0(city, " (", round(perc, 1), "%)")
  )

ggplot(df_city_pie,
       aes(x = "", y = perc, fill = city)) +
  geom_col(width = 1, color = "white") +
  coord_polar(theta = "y", start = pi/2) +
  scale_fill_discrete(
    labels = df_city_pie$legend_label
  ) +
  labs(
    title = "Procent ofert wg miasta",
    fill = "Miasto"
  ) +
  theme_void() +
  theme(
    plot.title = element_text(hjust = 0.5),
    legend.position = "right"
  )

ggplot(apartments_city, aes(x = reorder(city, mean_price_m2),
                      y = mean_price_m2)) +
  geom_col(fill = "purple") +
  geom_errorbar(aes(ymin = lwr, ymax = upr), width = 0.2) +
  coord_flip() +
  labs(
    title = "Średnia cena/m² wg miasta (kupno)",
    x = "Miasto",
    y = "Średnia cena w PLN/m²"
  ) +
  theme_minimal()

ggplot(rent_city, aes(x = reorder(city, mean_price_m2),
                      y = mean_price_m2)) +
  geom_col(fill = "seagreen") +
  geom_errorbar(aes(ymin = lwr, ymax = upr), width = 0.2) +
  coord_flip() +
  labs(
    title = "Średnia cena/m² wg miasta (wynajem)",
    x = "Miasto",
    y = "Średnia cena w PLN/m²"
  ) +
  theme_minimal()

features <- c("hasBalcony", "hasElevator", "hasParkingSpace", "hasSecurity", "hasStorageRoom")

wilson_ci <- map_dfr(features, function(f) {
  
  x <- sum(apartments[[f]] == TRUE, na.rm = TRUE)
  n <- sum(!is.na(apartments[[f]]))
  
  res <- binom.confint(x, n, methods = "wilson")
  
  tibble(
    feature = f,
    x = x,
    n = n,
    prop = x / n,
    lower = res$lower,
    upper = res$upper
  )
})

ggplot(wilson_ci, aes(x = reorder(feature, prop), y = prop)) +
  geom_col(fill = "steelblue") +
  geom_errorbar(
    aes(ymin = lower, ymax = upper),
    width = 0.2
  ) +
  coord_flip() +
  theme_minimal() +
  labs(
    title = "Udział cech w populacji mieszkań (+ przedziały Wilsona)",
    x = "Cecha",
    y = "Proporcja mieszkań"
  )

Analiza cen

Ceny/m^2 w miastach

ggplot(apartments, aes(x = city, y = price_m2)) +
  geom_violin(fill = "purple", alpha = 0.3) +
  geom_boxplot(width = 0.1, outlier.alpha = 0.01) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  labs(title = "Zależność ceny za m² w od miasta (kupno)",
       x = "Miasto",
       y = "Cena za m² (PLN)")

ggplot(rent, aes(x = city, y = price_m2)) +
  geom_violin(fill = "green", alpha = 0.3) +
  geom_boxplot(width = 0.1, outlier.alpha = 0.01) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  labs(title = "Zależność ceny za m² od miasta (wynajem)",
       x = "Miasto",
       y = "Cena za m² (PLN)")

Zgodność rozkładów pomiędzy miesiącami

ks_long <- apartments %>%
  group_split(city) %>%
  set_names(unique(apartments$city)) %>%
  imap_dfr(function(df, city_name) {
    
    months <- sort(unique(df$month_id))
    
    expand_grid(m1 = months, m2 = months) %>%
      mutate(
        ks = map2_dbl(m1, m2, ~{
          x <- df %>% filter(month_id == .x) %>% pull(log_price_m2)
          y <- df %>% filter(month_id == .y) %>% pull(log_price_m2)
          ks.test(x, y)$statistic
        }),
        p = map2_dbl(m1, m2, ~{
          x <- df %>% filter(month_id == .x) %>% pull(log_price_m2)
          y <- df %>% filter(month_id == .y) %>% pull(log_price_m2)
          ks.test(x, y)$p.value
        }),
        city = city_name
      )
  })

ggplot(ks_long, aes(m1, m2, fill = ks)) +
  geom_tile() +
  facet_wrap(~city) +
  scale_fill_viridis_c(option = "plasma") +
  theme_minimal() +
  labs(
    title = "Statystyka K-S D pomiędzy miesiącami (kupno)",
    x = "Miesiąc", y = "Miesiąc", fill = "D"
  )

ggplot(ks_long, aes(m1, m2, fill = p >= 0.05)) +
  geom_tile() +
  facet_wrap(~city) +
  scale_fill_viridis_c(option = "plasma") +
  theme_minimal() +
  labs(
    title = "Kiedy odrzucamy H_0 (dystrubuanty z tego samego rozkładu)",
    x = "Miesiąc", y = "Miesiąc", fill = "p >= 0.05"
  )

ks_long <- rent %>%
  group_split(city) %>%
  set_names(unique(rent$city)) %>%
  imap_dfr(function(df, city_name) {
    
    months <- sort(unique(df$month_id))
    
    expand_grid(m1 = months, m2 = months) %>%
      mutate(
        ks = map2_dbl(m1, m2, ~{
          x <- df %>% filter(month_id == .x) %>% pull(log_price_m2)
          y <- df %>% filter(month_id == .y) %>% pull(log_price_m2)
          ks.test(x, y)$statistic
        }),
        p = map2_dbl(m1, m2, ~{
          x <- df %>% filter(month_id == .x) %>% pull(log_price_m2)
          y <- df %>% filter(month_id == .y) %>% pull(log_price_m2)
          ks.test(x, y)$p.value
        }),
        city = city_name
      )
  })

ggplot(ks_long, aes(m1, m2, fill = ks)) +
  geom_tile() +
  facet_wrap(~city) +
  scale_fill_viridis_c() +
  theme_minimal() +
  labs(
    title = "Statystyka K-S D pomiędzy miesiącami (wynajem)",
    x = "Miesiąc", y = "Miesiąc", fill = "D"
  )

ggplot(ks_long, aes(m1, m2, fill = p >= 0.05)) +
  geom_tile() +
  facet_wrap(~city) +
  scale_fill_viridis_c() +
  theme_minimal() +
  labs(
    title = "Kiedy odrzucamy H_0 (dystrubuanty z tego samego rozkładu)",
    x = "Miesiąc", y = "Miesiąc", fill = "p >= 0.05"
  )

Czy ceny są log-normalne?

Porównanie dystrybuant empirycznych z dystrybuantami estymowanych rozkładów normalnych

z <- seq(min(rent$log_price_m2,apartments$log_price_m2), max(rent$log_price_m2,apartments$log_price_m2), length.out = 300000)

dystrybuanta_empiryczna_wynajem<-ecdf(rent$log_price_m2)
dystrybuanta_empiryczna_kupno<-ecdf(apartments$log_price_m2)
dystrybuanta_teoretyczna_wynajem<-pnorm(z, mean=mean(rent$log_price_m2), sd=sd(rent$log_price_m2))
dystrybuanta_teoretyczna_kupno<-pnorm(z, mean=mean(apartments$log_price_m2), sd=sd(apartments$log_price_m2))

df$colour = lapply(df$offer_type, function (t) if(t == "rent") "seagreen" else "purple")


ggplot(df, aes(x = log_price_m2_n, fill = colour)) +
  geom_histogram(aes(y = after_stat(density)),
                 bins = 50,
                 color = "white") +
  facet_wrap(~ offer_type) +
  labs(
    title = "Rozkład Log ceny na m²",
    x = "Log ceny na m²",
    y = "Gestosc"
  ) +
  scale_fill_identity()

qqnorm(apartments$log_price_m2_n)
qqline(apartments$log_price_m2_n, col = "red")

qqnorm(rent$log_price_m2_n)
qqline(rent$log_price_m2_n, col = "red")

ggplot() +
  geom_step(
    aes(x = z, y = dystrybuanta_empiryczna_wynajem(z), color = "Empiryczna wyn"),
    linewidth = 1,
    linetype = "solid"
  ) +
  geom_line(
    aes(x = z, y = dystrybuanta_teoretyczna_wynajem, color = "Teoretyczna wyn"),
    linewidth = 1,
    linetype = "dashed"
  ) +
  geom_step(
    aes(x=z, y=dystrybuanta_empiryczna_kupno(z), color = "Empiryczna kupna"),
    linewidth = 1,
    linetype="solid"
  ) +
  geom_line(
    aes(x=z, y=dystrybuanta_teoretyczna_kupno, color = "Teoretyczna kupna"),
    linewidth = 1,
    linetype="dashed"
  ) +
  scale_color_manual(
    values = c("Empiryczna wyn" = "green" , "Teoretyczna wyn" = "blue" , "Empiryczna kupna" = "purple", "Teoretyczna kupna" = "red" ),
    labels = c("Empiryczna kupna", "Empiryczna wyn", "Teoretyczna kupna", "Teoretyczna wyn")
  ) +
  labs(
    title = "Dystrybuanty empiryczne i teoretyczne",
    x = "Wartość",
    y = "Prawdopodobieństwo skumulowane",
    color = "Typ dystrybuanty"
  ) +
  theme_minimal() +
  theme(plot.title = element_text(hjust = 0.5))

lillie.test(apartments$log_price_m2)
## 
##  Lilliefors (Kolmogorov-Smirnov) normality test
## 
## data:  apartments$log_price_m2
## D = 0.033659, p-value < 2.2e-16
lillie.test(rent$log_price_m2)
## 
##  Lilliefors (Kolmogorov-Smirnov) normality test
## 
## data:  rent$log_price_m2
## D = 0.02033, p-value < 2.2e-16
var.test(rent$log_price_m2, apartments$log_price_m2)
## 
##  F test to compare two variances
## 
## data:  rent$log_price_m2 and apartments$log_price_m2
## F = 0.76599, num df = 70846, denom df = 195567, p-value < 2.2e-16
## alternative hypothesis: true ratio of variances is not equal to 1
## 95 percent confidence interval:
##  0.7567541 0.7753755
## sample estimates:
## ratio of variances 
##          0.7659948

Cena a dokładna lokalizacja

ggplot(apartments, aes(x=longitude_n, y=latitude_n, col=price_m2_n)) +
  geom_point(alpha=0.01, size=0.4) +
  facet_wrap(~ city) +
  scale_color_viridis_c(option="plasma", name = "Koszt kupna za m² (PLN)\n(ciemne znaczy droższe)", direction=-1) +
  theme_minimal()+
  labs(
    title = "Dokładne położenie na mapie a koszt zakupu",
    x = "długość geograficzna",
    y = "szerokość geograficzna")

ggplot(rent, aes(x=longitude_n, y=latitude_n, col=price_m2_n)) +
  geom_point(alpha=0.03, size=0.4) +
  facet_wrap(~ city) +
  scale_color_viridis_c(name = "Koszt wynajmu za m² (PLN)\n(ciemne znaczy droższe)", direction=-1) +
  theme_minimal()+
  labs(
    title = "Dokładne położenie na mapie a koszt wynajmu",
    x = "długość geograficzna",
    y = "szerokość geograficzna")

Warszawa

ggplot(apartments_warsaw, aes(x=longitude, y=latitude, col=log_price)) +
  geom_point(alpha=0.1, size=0.4) +
  scale_color_viridis_c(option="plasma", name = "Koszt kupna za m² (PLN)\n(ciemne znaczy droższe)", direction=-1) +
  theme_minimal()+
  labs(
    title = "Dokładne położenie na mapie a koszt zakupu",
    x = "długość geograficzna",
    y = "szerokość geograficzna")

ggplot(rent_warsaw, aes(x=longitude, y=latitude, col=log_price)) +
  geom_point(alpha=0.2, size=0.4) +
  scale_color_viridis_c(name = "Koszt wynajmu za m² (PLN)\n(ciemne znaczy droższe)", direction=-1) +
  theme_minimal()+
  labs(
    title = "Dokładne położenie na mapie a koszt wynajmu",
    x = "długość geograficzna",
    y = "szerokość geograficzna")

Regresja

ggplot(apartments, aes(x=centreDistance, y=price_m2)) +
  geom_point(color = "purple", alpha=0.1, size=0.3) +
  geom_smooth(method = "lm", se = TRUE, color = "orange") +
  facet_wrap(~ city) +
  theme_minimal() +
  labs(
    title = "Zależność ceny za m² od odległości od centrum (kupno)",
    x = "Odległość od centrum (km)",
    y = "Cena za m² (PLN)")

ggplot(rent, aes(x=centreDistance, y=price_m2)) +
  geom_point(color = "green",alpha=0.1, size=0.3) +
  geom_smooth(method = "lm", se = TRUE, color = "orange") +
  facet_wrap(~ city) +
  theme_minimal() +
  labs(
    title = "Zależność ceny za m² od odległości od centrum (wynajem)",
    x = "Odległość od centrum (km)",
    y = "Cena za m² (PLN)")

Model liniowy

model_apartments <- lm(log_price_m2 ~ month_id + centreDistance +
                  squareMeters +
                  age +
                  floor_ratio +
                  city +
                  hasElevator +
                  hasBalcony +
                  hasSecurity +
                  hasParkingSpace +
                  hasStorageRoom +
                  poiCount +
                  condition,
                data = apartments, na.action = na.exclude)


coef_apartments <- tidy(model_apartments, conf.int = TRUE) %>%
  filter(term != "(Intercept)") %>%
  arrange(estimate)

summary(model_apartments)
## 
## Call:
## lm(formula = log_price_m2 ~ month_id + centreDistance + squareMeters + 
##     age + floor_ratio + city + hasElevator + hasBalcony + hasSecurity + 
##     hasParkingSpace + hasStorageRoom + poiCount + condition, 
##     data = apartments, na.action = na.exclude)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.35577 -0.05333 -0.00386  0.04864  0.47458 
## 
## Coefficients:
##                       Estimate Std. Error  t value Pr(>|t|)    
## (Intercept)          4.017e+00  2.132e-03 1883.521  < 2e-16 ***
## month_id             7.267e-03  6.618e-05  109.802  < 2e-16 ***
## centreDistance      -1.324e-02  1.034e-04 -128.049  < 2e-16 ***
## squareMeters        -1.085e-03  1.026e-05 -105.742  < 2e-16 ***
## age                 -7.191e-04  9.067e-06  -79.315  < 2e-16 ***
## floor_ratio         -9.421e-03  7.573e-04  -12.440  < 2e-16 ***
## cityBydgoszcz       -5.179e-02  2.142e-03  -24.174  < 2e-16 ***
## cityCzestochowa     -1.150e-01  3.415e-03  -33.685  < 2e-16 ***
## cityGdansk           2.139e-01  1.990e-03  107.466  < 2e-16 ***
## cityGdynia           1.648e-01  2.124e-03   77.614  < 2e-16 ***
## cityKatowice        -4.303e-03  2.400e-03   -1.793   0.0729 .  
## cityKrakow           2.442e-01  1.942e-03  125.771  < 2e-16 ***
## cityLodz            -1.882e-02  2.049e-03   -9.186  < 2e-16 ***
## cityLublin           2.308e-02  2.213e-03   10.428  < 2e-16 ***
## cityPoznan           8.567e-02  2.200e-03   38.946  < 2e-16 ***
## cityRadom           -1.270e-01  2.512e-03  -50.561  < 2e-16 ***
## cityRzeszow          3.160e-02  2.962e-03   10.669  < 2e-16 ***
## citySzczecin         1.129e-02  2.211e-03    5.107 3.28e-07 ***
## cityWarszawa         3.021e-01  1.939e-03  155.805  < 2e-16 ***
## cityWroclaw          1.569e-01  1.966e-03   79.817  < 2e-16 ***
## hasElevatorTRUE      2.527e-02  5.129e-04   49.278  < 2e-16 ***
## hasBalconyTRUE       7.911e-03  4.864e-04   16.266  < 2e-16 ***
## hasSecurityTRUE      2.017e-02  6.913e-04   29.172  < 2e-16 ***
## hasParkingSpaceTRUE  7.079e-03  5.110e-04   13.854  < 2e-16 ***
## hasStorageRoomTRUE  -2.099e-02  4.868e-04  -43.120  < 2e-16 ***
## poiCount             8.315e-04  1.118e-05   74.390  < 2e-16 ***
## conditionlow        -4.566e-02  7.274e-04  -62.766  < 2e-16 ***
## conditionpremium     2.797e-02  6.338e-04   44.125  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.07932 on 135101 degrees of freedom
##   (60439 observations deleted due to missingness)
## Multiple R-squared:  0.7556, Adjusted R-squared:  0.7555 
## F-statistic: 1.547e+04 on 27 and 135101 DF,  p-value: < 2.2e-16
ggplot(coef_apartments, aes(x = reorder(term, estimate), y = estimate)) +
  geom_col(fill = "purple") +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high),
                width = 0.2) +
  coord_flip() +
  theme_minimal() +
  labs(
    title = "Wpływ zmiennych na log(cena/m²) – kupno",
    x = "Zmienna",
    y = "Współczynnik"
  )

par(mfrow = c(2,2))
plot(model_apartments)

numeric_df <- apartments %>%
  select(price_m2, month_id,
                  centreDistance,
                  squareMeters,
                  age,
                  floor_ratio,
                  hasElevator,
                  hasBalcony,
                  hasSecurity,
                  hasParkingSpace,
                  hasStorageRoom,
                  poiCount)

corr <- cor(numeric_df, use = "complete.obs")

melted <- melt(corr)

ggplot(melted, aes(Var1, Var2, fill = value)) +
  geom_tile() +
  scale_fill_viridis_c(option = "plasma") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

model_rent <- lm(log_price_m2 ~ month_id + centreDistance +
                   squareMeters +
                   age +
                   floor_ratio +
                   city +
                   hasElevator +
                   hasBalcony +
                   hasSecurity +
                   hasParkingSpace +
                   hasStorageRoom +
                   poiCount +
                   condition,
                 data = rent, na.action = na.exclude)

coef_rent <- tidy(model_rent, conf.int = TRUE) %>%
  filter(term != "(Intercept)") %>%
  arrange(estimate)

summary(model_rent)
## 
## Call:
## lm(formula = log_price_m2 ~ month_id + centreDistance + squareMeters + 
##     age + floor_ratio + city + hasElevator + hasBalcony + hasSecurity + 
##     hasParkingSpace + hasStorageRoom + poiCount + condition, 
##     data = rent, na.action = na.exclude)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.55400 -0.06394 -0.00385  0.05956  0.41200 
## 
## Coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)          1.685e+00  5.908e-03 285.257  < 2e-16 ***
## month_id            -5.041e-04  1.917e-04  -2.630  0.00855 ** 
## centreDistance      -1.435e-02  2.177e-04 -65.903  < 2e-16 ***
## squareMeters        -7.686e-04  1.985e-05 -38.729  < 2e-16 ***
## age                 -9.862e-04  1.863e-05 -52.924  < 2e-16 ***
## floor_ratio          1.343e-02  1.558e-03   8.622  < 2e-16 ***
## cityBydgoszcz        6.391e-02  6.528e-03   9.790  < 2e-16 ***
## cityCzestochowa      1.172e-02  1.054e-02   1.112  0.26628    
## cityGdansk           2.255e-01  5.777e-03  39.041  < 2e-16 ***
## cityGdynia           1.668e-01  6.258e-03  26.663  < 2e-16 ***
## cityKatowice         9.361e-02  5.925e-03  15.801  < 2e-16 ***
## cityKrakow           2.132e-01  5.494e-03  38.813  < 2e-16 ***
## cityLodz             6.050e-02  5.682e-03  10.649  < 2e-16 ***
## cityLublin           8.319e-02  6.555e-03  12.691  < 2e-16 ***
## cityPoznan           1.208e-01  5.743e-03  21.037  < 2e-16 ***
## cityRadom           -8.441e-03  1.079e-02  -0.783  0.43388    
## cityRzeszow          8.809e-02  6.939e-03  12.695  < 2e-16 ***
## citySzczecin         1.118e-01  6.090e-03  18.356  < 2e-16 ***
## cityWarszawa         3.324e-01  5.499e-03  60.446  < 2e-16 ***
## cityWroclaw          1.972e-01  5.581e-03  35.324  < 2e-16 ***
## hasElevatorTRUE      2.012e-02  1.134e-03  17.736  < 2e-16 ***
## hasBalconyTRUE      -1.670e-03  1.004e-03  -1.663  0.09638 .  
## hasSecurityTRUE      5.100e-03  1.226e-03   4.159 3.20e-05 ***
## hasParkingSpaceTRUE -3.787e-03  9.585e-04  -3.950 7.81e-05 ***
## hasStorageRoomTRUE  -5.829e-03  1.247e-03  -4.675 2.94e-06 ***
## poiCount             4.513e-04  2.156e-05  20.934  < 2e-16 ***
## conditionlow        -4.857e-02  7.972e-03  -6.093 1.12e-09 ***
## conditionpremium     1.519e-02  9.983e-04  15.217  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.09289 on 45442 degrees of freedom
##   (25377 observations deleted due to missingness)
## Multiple R-squared:  0.5246, Adjusted R-squared:  0.5243 
## F-statistic:  1857 on 27 and 45442 DF,  p-value: < 2.2e-16
ggplot(coef_rent, aes(x = reorder(term, estimate), y = estimate)) +
  geom_col(fill = "seagreen") +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high),
                width = 0.2) +
  coord_flip() +
  theme_minimal() +
  labs(
    title = "Wpływ zmiennych na log(cena/m²) – wynajem",
    x = "Zmienna",
    y = "Współczynnik"
  )

par(mfrow = c(2,2))
plot(model_rent)

numeric_df <- rent %>%
  select(price_m2, month_id,
                  centreDistance,
                  squareMeters,
                  age,
                  floor_ratio,
                  hasElevator,
                  hasBalcony,
                  hasSecurity,
                  hasParkingSpace,
                  hasStorageRoom,
                  poiCount)

corr <- cor(numeric_df, use = "complete.obs")

melted <- melt(corr)

ggplot(melted, aes(Var1, Var2, fill = value)) +
  geom_tile() +
  scale_fill_viridis_c() +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

Przewidywania rynku najmu/sprzedaży

rent_pred <- cbind(
  rent,
  predict(model_rent, interval = "confidence") %>%
    as.data.frame()
)

apartments_pred <- cbind(
  apartments,
  predict(model_apartments, interval = "confidence") %>%
    as.data.frame()
)

rent_plot <- rent_pred %>%
  group_by(month_id) %>%
  summarise(
    fit = mean(fit, na.rm = TRUE),
    lwr = mean(lwr, na.rm = TRUE),
    upr = mean(upr, na.rm = TRUE),
    .groups = "drop"
  )

apartments_plot <- apartments_pred %>%
  group_by(month_id) %>%
  summarise(
    fit = mean(fit, na.rm = TRUE),
    lwr = mean(lwr, na.rm = TRUE),
    upr = mean(upr, na.rm = TRUE),
    .groups = "drop"
  )

ggplot(apartments_plot,
       aes(x = month_id, y = fit)) +

  geom_line(color = "purple", linewidth = 1.3) +
  geom_point(color = "purple", size = 2) +

  geom_ribbon(aes(ymin = lwr, ymax = upr),
              alpha = 0.2,
              fill = "purple") +

  theme_minimal() +

  labs(
    title = "Trend przewidywanych cen (kupno)",
    x = "Miesiąc",
    y = "log(cena/m²)"
  )

ggplot(rent_plot,
       aes(x = month_id, y = fit)) +

  geom_line(color = "darkgreen", linewidth = 1.3) +
  geom_point(color = "darkgreen", size = 2) +

  geom_ribbon(aes(ymin = lwr, ymax = upr),
              alpha = 0.2,
              fill = "green") +

  theme_minimal() +

  labs(
    title = "Trend przewidywanych cen (wynajem)",
    x = "Miesiąc",
    y = "log(cena/m²)"
  )

Porównanie rynków

monthly_means <- df %>%
  group_by(month_id, offer_type) %>%
  summarise(
    mean_log_price = mean(log_price_m2, na.rm = TRUE),
    .groups = "drop"
  )

wide <- monthly_means %>%
  pivot_wider(names_from = offer_type,
              values_from = mean_log_price)

wide$divergence <- wide$apartment - wide$rent

ggplot(wide, aes(x = month_id, y = divergence, group = 1)) +
  geom_line(linewidth = 1.2) +
  geom_point() +
  theme_minimal() +
  labs(
    title = "Dywergencja rynku mieszkań: kupno vs wynajem",
    subtitle = "Różnica średniej log-ceny m² (kupno - wynajem)",
    x = "Miesiąc",
    y = "Dywergencja (log price m²)"
  ) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))