# Section 3.3 script

source("prep.R")

# set working directory to the data repositor
### setwd("YOUR WD")
fta <- read_csv("Data/public_price_data.csv") # note this file already excludes TPO systems
c(nrow(fta),sum(fta$cl=="H")) # sample sizes
# t tests based on 2024 data
t.test(install_price_real_w~loan,data=filter(fta,year==2024))
t.test(install_price_real_w~loan,data=filter(fta,year==2024,cl=="H"))

# figure by year
ffa<-aggregate(install_price_real_w~year+loan,data=fta,mean) %>%
  inner_join(aggregate(install_price_real_w~year+loan,data=filter(fta,cl=="H"),mean) %>% rename(hc=install_price_real_w)) %>%
  mutate(lo=ifelse(install_price_real_w<hc,install_price_real_w,hc),
         hi=ifelse(install_price_real_w>hc,install_price_real_w,hc))
ggsave("Figures/figure8.jpg",
       plot=base(ffa)+coord_cartesian(ylim=c(0,6))+
         geom_ribbon(aes(x=year,ymin=lo,ymax=hi,fill=factor(loan)),alpha=0.6)+
         geom_line(aes(year,install_price_real_w,color=factor(loan)))+
         geom_line(aes(year,hc,color=factor(loan)),linetype='dashed')+
         ylab("Average\nPrice\n($/W)")+
         theme(axis.title.x=element_blank())+
         ant("Customer financed",2019,4,5,'darkcyan')+
         ant("Loans",2022,5.5,5,"navy")+
         scale_fill_manual(values=c("darkcyan",'navy'),guide="none")+
         scale_color_manual(values=c("darkcyan","navy"),guide="none")+
         geom_segment(x=2017.4,xend=2018.2,y=1.4,yend=1.4,color='gray50')+ant("Full sample",2019.1,1.4,4,'gray50')+
         geom_segment(x=2017.4,xend=2018.2,y=1,yend=1,color='gray50',linetype="dashed")+ant("High-confidence sample",2019.96,1,4,'gray50'),
       width=5,height=4)

# price regression
rgta<-read_csv("Data/public_regression_data.csv")

# see Barbose et al. [4] for further details on the regression variables
library(fixest)
r1<-feols(log(price_w)~loan+ # the loan coefficient is the result of interest reported in the paper
            sys_size+sys_size2+ # control variables
            prem_module+microinv+dc_optimizer+ 
            mkt_size000+inst_exp000+ 
            hh_sqmi000+median_income000+
            new_constr+groundmount+battery| 
            state+qtr, # fixed effects
          data=rgta)
summary(r1)
rh<-feols(log(price_w)~loan+
            sys_size+sys_size2+ 
            prem_module+microinv+dc_optimizer+
            mkt_size000+inst_exp000+
            hh_sqmi000+median_income000+
            new_constr+groundmount+battery| 
            state+qtr, 
          data=filter(rgta,cl=="H"))
summary(rh)


