install.packages('downloader')
library(downloader)
# Specify URL where file is stored
url <- "https://www.stats.govt.nz/assets/Uploads/Alcohol-available-for-consumption/Alcohol-available-for-consumption-Year-ended-December-2020/Download-data/alcohol-available-for-consumption-year-ended-december-2020-csv.csv"
# Specify destination where file should be saved
destfile<-"C:/Users/Name/Desktop/FE_HW2/alcohol for consumption.csv"
download.file(url,destfile)
install.packages('ggplot2')
library(ggplot2)
#ggplot2: example 1 (boxplot)
P1 <- ggplot(msleep) + #first layer
geom_boxplot(aes(x = sleep_total, #second layer
y = vore,
fill = vore))
P1
#ggplot2: example 2 (line chart)
P2 <- ggplot(msleep) +
geom_bar(aes(y = vore, fill = vore))
P2
#ggplot2: example 3 (scatterplot)
P3 <- ggplot(msleep) +
geom_point(aes(x = bodywt,
y = sleep_total,
colour = vore))+
scale_x_log10()
P3
## ggplot2ç example 4 (histogram=
P4<-ggplot(faithful) +
geom_histogram(aes(x = eruptions, fill = waiting < 60), position = 'dodge', alpha = 15, stat_bin = 30) #all the specification of the histogram are
# made in the second layer, but if we wanted our graph more general we should have added a third layer.
P4
#Update all existing packages first
update.packages(ask = FALSE, repos = 'https://cran.r-project.org')
install.packages('knitr',repos = c('https://xran.yihui.org','https://cran.r-project.org'))
library(knitr)
# If options are not explicitly specified, knitr will try to guess reaasonable default settings
# A few manuals are available, such as the main manual and the graphics manual
# For a more organized reference, see knirt book
Knitr is a package that allows for the creation of reports directly from R. The package enables to present in the form of a report the conglomerate of three major factors, namely chuncks of text, R code and the related output or result of the code. The report generated when employing the knitr package can have three formats: html, pdf and word.For more details on using Knitr, refer to https://yihui.org/knitr/.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
summary(cars)
It is also possible to insert charts in the report without showing the code, for example:
Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot. ``
It is possible as well to include a chart in the report and display the related code, for example:
plot(cars)
install.packages('TTR')
library(TTR)
#Install and Load needed packages
install.packages("urca")
install.packages("AER")
library(urca)
library(AER)
#Dataset
data("EuStockMarkets")
DAXData<-EuStockMarkets[1:204,1]
plot(DAXData)
#Urca Package: Dickey-Fuller Test
DAX0 <- summary(ur.df(DAXData))
DAX0
#Test with type=none: no intercept, no trend
DAX1<- summary(ur.df(DAXData,type = "none",lags = 1))
DAX1
#Test with type=drift:intercept, no trend
DAX2<-summary(ur.df(DAXData,type = "drift",lags = 1,selectlags = "Fixed"))
DAX2
#Test with type=trend: intercept and trend
DAX3<- summary(ur.df(DAXData,type = "trend",lags = 1,selectlags = "Fixed"))
DAX3
# R PACKAGE: zoo
install.packages('zoo')
library('quantmod','zoo')
#Zoo Example 1
Data<-getSymbols('^GSPC',from='2021-01-01')
chartSeries(GSPC,theme = 'white',
TA = 'addVo();addBBands();addCCI()',majorticks = 'weeks',majorticks='weeks',multicolor=T)
#Zoo Example 2
Data1 <- getSymbols('^DJI',from='2021-01-01')
chartSeries(DJI, theme = 'white',
TA = 'addVo();addBBands();addCCI()',majorticks = 'weeks',majorticks = 'weeks',multicolor=T)
GSPC_INDEX <- read.csv('C:\\Users\\Domenico\\Desktop\\Domenico\\University\\Erasmus courses\\Financial Econometrics\\GSPC.csv',
header = T)
my_data <- GSPC_INDEX$GSPC.Adjusted
diff_sum <- function(Y)
{
Y = na.omit(Y)
N = matrix(0, nrow = length(my_data), ncol = 1)
N[1] = Y[1]
for (i in 1:length(Y)-1)
{
N[i] = Y[i] - Y[i+1]
}
return(sum(N))
}
diff_sum(my_data)
sum(my_data)
#Install and load needed packages
install.packages('tidyverse')
library(tidyverse)
#Example 1: sin plot function
Sin_plot <- plot(
sin,
from = -pi,
to = 2 * pi,
axes = FALSE,
main = "Sin function"
)
axis(
1, # bottom axis
pi * (-1:2),
c(expression(-pi), 0, expression(pi), expression(2 * pi))
)
axis(2) # left axis
#Example 2
#linear regression plot
linreg <- lm(dist ~ speed, cars) #linear regression, distance regressed on speed
linreg_coeffs <- coef(linreg) #coefficients of the linear regression
lineq <- paste("distance = ", linreg_coeffs[2], " * speed + ", linreg_coeffs[1]) # concatenate the vector and making the arguments characters
plot(cars, main = "Car distance by speed", sub = lineq, xlab = "speed", ylab = "distance", pch = 19) #plot
abline(linreg, col = "blue") #add line of the regression
#R PACKAGE TTR
install.packages('TTR')
install.packages('tidyquant')
library(TTR)
library(ggplot2)
library(quantmod)
library(tidyquant)
#SMA() Function
#Create a dataframe
AMZN_Data<-getSymbols("AMZN", from ='2020-01-01', to ='2021-01-01', warnings = FALSE, auto.assign = FALSE)
AMZN_Data <- data.frame(AMZN_Data)
#Change Names in the Dataframe
names(AMZN_Data)<-c('Open','High','Low','Close','Volume','Adjusted')
#Convert row names to a column
AMZN_Data$Date<-as.Date(rownames(AMZN_Data))
#Calculate the 5 and 25 days moving average
AMZN_Data$SMA5<-TTR::SMA(AMZN_Data$Close,n=5, na.omit = T)
AMZN_Data$SMA25<-TTR::SMA(AMZN_Data$Close,n=25, na.omit = T)
AMZN_Data <- na.omit(AMZN_Data)
#Plot the moving average
AMZN_SMA<-ggplot(AMZN_Data) +
aes( y = AMZN_Data$Close, x=AMZN_Data$Date) +
geom_line(aes(y=Close,color="Close")) +
geom_line(aes(y=SMA5,color="SMA5")) +
geom_line(aes(y=SMA25,color="SMA25")) +
theme(panel.grid = element_line(colour="grey"),
legend.position = 'top') +
labs(title="SMA AMZ (Jan2020-Jan2021)",
color="Prices")
AMZN_SMA
#EMA() Function
#Calculate the 5 and 25 days exponential moving average
AMZN_Data$EMA5<-TTR::EMA(AMZN_Data$Close,n=5,wilder = FALSE,ratio = NULL)
AMZN_Data$EMA25<-TTR::EMA(AMZN_Data$Close,n=25, wilder = FALSE,ratio = NULL)
AMZN_Data <- na.omit(AMZN_Data)
#Plot the moving average
AMZN_EMA<-ggplot(AMZN_Data, aes(x=Date)) +
geom_candlestick(aes(ymin = AMZN_Data$Low, ymax = AMZN_Data$High, fill_up = 'green') +
geom_line(aes(y=EMA5,color="EMA5")) +
geom_line(aes(y=EMA25,color="EMA25")) +
theme(panel.grid.major.y = element_line(colour="grey")) +
theme(panel.grid.minor.y = element_line(colour="grey"),
legend.position = "top") +
labs(title="EMA AMZ (Jan2020-Jan2021)") +
labs(color="Green"))
AMZN_EMA
install.packages('FitAR')
library(FitAR)
library(quantmod)
#clear previous graphic
graphics.off()
#fetch data: monthly U.S. unemployment rate
getSymbols("UNRATE",src="FRED")
chartSeries(UNRATE)
#create a regular vector, instead of a xts-object
unrate <- as.numeric(UNRATE)
#print last data
tail(UNRATE)
#fit exact MLE to AR(4)
ans1<-FitAR(unrate,4, lag.max = 'default')
#plot original data
TimeSeriesPlot(unrate, aspect=0.2,ylab = "Unemployment Rate",main = "Unemployment")
#simulate the fitted AR
w <-Boot.FitAR(ans1, R = 1, ARModel = ARp)
w1 <- Boot.FitAR(ans1, R = 1, ARModel = ARz)
#plot simulated data in green
lines(w, col='green')
lines(w1, col = 'red')
#Install and Load needed packages
install.packages('quantmod')
library('quantmod')
Data <- getSymbols('^GSPC', from = '2021-01-01')
chartSeries(GSPC, theme = 'white',
TA='addVo();addBBands();addCCI()', majorticks = 'weeks', majorticks = 'weeks', multicolor = T)
Data_1 <- getSymbols('^DJI', from = '2021-01-01')
chartSeries(DJI, theme = 'white',
TA='addVo();addBBands();addCCI()', majorticks = 'weeks', majorticks = 'weeks', multicolor = T)
Output <- merge(Ad(GSPC), Ad(DJI))
chart_Series(Ad(DJI))
chart_Series(Ad(GSPC))
#Install and Load needed package
install.packages("quantmod")
library(quantmod)
#Read and return the data file for S&P500
#Option 1
sp.data<- getSymbols("^GSPC",start="1990-01-01",auto.assign = FALSE)
#Option 2
my_startdate <- as.Date("1990-01-01")
sp.data<- getSymbols("^GSPC",from=my_startdate,auto.assign = FALSE)
#Option 3
sp.data<- getSymbols("^GSPC",from="1990-01-01",auto.assign = FALSE)
#R DATASETS REARRANGEMENT: (une_rt_m.tsv and unemployment.csv)
#Load the Dataset
install.packages('tidyverse')
library('tidyverse')
une_rt_m <- read_tsv("C:\\Users\\Elisa\\Desktop\\FE_Assignment_6_data/une_rt_m.tsv")
#Delete one column (geographical info)
une_rt_m2 <- subset(une_rt_m,select = 2:50)
#Reverse order of columns
une_rt_m2 <- une_rt_m2[,order(ncol(une_rt_m2):1)]
#Tidy Data (from columns to rows)
une_rt_m2 <- tidyr::pivot_longer(une_rt_m2, cols = 1:49, names_to = 'MonthYear', values_to = 'UnRate')
une_rt_m2 <- data.frame(une_rt_m2)
#Change Columns Name
names(une_rt_m2)[1]<-"MonthYear"
names(une_rt_m2)[2]<-"UnRate"
une_rt_m2 <- separate(une_rt_m2, MonthYear, sep = 'M', into = c('Year', 'Month'))
une_rt_m2 <- unite(une_rt_m2,Month, Year, col = "MonthYear", sep = "-")
as.Date(une_rt_m2$MonthYear, format('%M-%Y'))
as.numeric(une_rt_m2$UnRate)
na.omit(une_rt_m2$UnRate)
#Add Column
install.packages("dplyr")
library(dplyr)
une_rt_m2$RowID<-c(1:2131)
une_rt_m2<-une_rt_m2%>%relocate(RowID,.before = MonthYear)
#Create a Dataset and combine the data
#Load datasets
Developed_3_Factors <- read.csv('C:\\Users\\Domenico\\Desktop\\Assignment_5\\Developed_3_Factors_YearMonth.csv',
header = T)
mydata <- read.csv('C:\\Users\\Domenico\\Desktop\\Assignment_5\\F-F_Size_Portfolios_formed_on_ME_Value_Weight_Returns_Monthly.csv',
header = T)
#Remove unnecessary columns and/or rows
F_F_Size <- mydata[-c(1:768),-c(2,3,4,5)]
#Merge datasets
New_data <- merge(F_F_Size, Developed_3_Factors)
#Create a CAPM for Lo Portfolio
#Linear Regression Function
Lo.10.capm <- lm(New_data$"Lo.10" ~ New_data$Mkt.RF)
#Coefficients
coef(Lo.10.capm)
#Summary of coefficients and important statistics tests
mod.s1<-summary(Lo.10.capm)
values1<-vector() #Empty vector
values1[1]<-mod.s1$r.squared
values1[2]<-mod.s1$adj.r.squared
f.stat<-mod.s1$fstatistic
values1[3]<-f.stat[1]
values1[4]<-f.stat[2]
values1[5]<-f.stat[3]
values1[6]<-pf(values1[3],values1[4],values1[5],lower.tail = FALSE) #Create F-Distribution
values1[7]<-values1[1]/(1-values1[1])
values1.et<-c("R^2","adj R^2","F","df num.","df den.","p(F)","f^2") #Names of the variables put in the vector
values1.m<-cbind(round(values1,digits=5)) #bind by columns
rownames(values1.m)<-values1.et #Assign names to the binded row vectors
colnames(values1.m) <- c('Lo.10.capm') #Name of the column
#Summary
ris1<-cbind(coef(mod.s1)[,1],coef(mod.s1)[,3:4])
colnames(ris1) <- c('Estimate', 't-value', 'Pr>|t|')
####################################
Qnt2.capm <- lm(New_data$"Qnt.2" ~ New_data$Mkt.RF)
coef(Qnt2.capm)
mod.s2<-summary(Qnt2.capm)
values2<-vector()
values2[1]<-mod.s2$r.squared
values2[2]<-mod.s2$adj.r.squared
f.stat<-mod.s2$fstatistic
values2[3]<-f.stat[1]
values2[4]<-f.stat[2]
values2[5]<-f.stat[3]
values2[6]<-pf(values2[3],values2[4],values2[5],lower.tail = FALSE)
values2[7]<-values2[1]/(1-values2[1])
values2.et<-c("R^2","adj R^2","F","df num.","df den.","p(F)","f^2")
values2.m<-cbind(round(values2,digits=5))
rownames(values2.m)<-values2.et
colnames(values2.m) <- c('Qnt2.capm')
ris2<-cbind(coef(mod.s2)[,1],coef(mod.s2)[,3:4])
colnames(ris2) <- c('Estimate', 't-value', 'Pr>|t|')
#####################################
Qnt3.capm <- lm(New_data$"Qnt.3" ~ New_data$Mkt.RF)
coef(Qnt2.capm)
mod.s3<-summary(Qnt2.capm)
values3<-vector()
values3[1]<-mod.s3$r.squared
values3[2]<-mod.s3$adj.r.squared
f.stat<-mod.s3$fstatistic
values3[3]<-f.stat[1]
values3[4]<-f.stat[2]
values3[5]<-f.stat[3]
values3[6]<-pf(values3[3],values3[4],values3[5],lower.tail = FALSE)
values3[7]<-values2[1]/(1-values2[1])
values3.et<-c("R^2","adj R^2","F","df num.","df den.","p(F)","f^2")
values3.m<-cbind(round(values3,digits=5))
rownames(values3.m)<-values3.et
colnames(values3.m) <- c('Qnt3.capm')
ris3<-cbind(coef(mod.s3)[,1],coef(mod.s3)[,3:4])
colnames(ris3) <- c('Estimate', 't-value', 'Pr>|t|')
#####################################
Qnt4.capm <- lm(New_data$"Qnt.4" ~ New_data$Mkt.RF)
coef(Qnt4.capm)
mod.s4<-summary(Qnt4.capm)
values4<-vector()
values4[1]<-mod.s4$r.squared
values4[2]<-mod.s4$adj.r.squared
f.stat<-mod.s4$fstatistic
values4[3]<-f.stat[1]
values4[4]<-f.stat[2]
values4[5]<-f.stat[3]
values4[6]<-pf(values4[3],values4[4],values4[5],lower.tail = FALSE)
values4[7]<-values4[1]/(1-values4[1])
values4.et<-c("R^2","adj R^2","F","df num.","df den.","p(F)","f^2")
values4.m<-cbind(round(values4,digits=5))
rownames(values4.m)<-values4.et
colnames(values4.m) <- c('Qnt4.capm')
ris4<-cbind(coef(mod.s4)[,1],coef(mod.s4)[,3:4])
colnames(ris4) <- c('Estimate', 't-value', 'Pr>|t|')
#####################################
Hi.20.capm <- lm(New_data$"Hi.20" ~ New_data$Mkt.RF)
coef(Hi.20.capm)
mod.s5<-summary(Hi.20.capm)
values5<-vector()
values5[1]<-mod.s5$r.squared
values5[2]<-mod.s5$adj.r.squared
f.stat<-mod.s5$fstatistic
values5[3]<-f.stat[1]
values5[4]<-f.stat[2]
values5[5]<-f.stat[3]
values5[6]<-pf(values5[3],values5[4],values5[5],lower.tail = FALSE)
values5[7]<-values5[1]/(1-values5[1])
values5.et<-c("R^2","adj R^2","F","df num.","df den.","p(F)","f^2")
values5.m<-cbind(round(values5,digits=5))
rownames(values5.m)<-values5.et
colnames(values5.m) <- c('Hi.20.capm')
ris5<-cbind(coef(mod.s5)[,1],coef(mod.s5)[,3:4])
colnames(ris5) <- c('Estimate', 't-value', 'Pr>|t|')
#####################################
Dec.2.capm <- lm(New_data$"Dec.2" ~ New_data$Mkt.RF)
coef(Dec.2.capm)
mod.s6<-summary(Dec.2.capm)
values6<-vector()
values6[1]<-mod.s6$r.squared
values6[2]<-mod.s6$adj.r.squared
f.stat<-mod.s6$fstatistic
values6[3]<-f.stat[1]
values6[4]<-f.stat[2]
values6[5]<-f.stat[3]
values6[6]<-pf(values6[3],values6[4],values6[5],lower.tail = FALSE)
values6[7]<-values6[1]/(1-values6[1])
values6.et<-c("R^2","adj R^2","F","df num.","df den.","p(F)","f^2")
values6.m<-cbind(round(values6,digits=5))
rownames(values6.m)<-values6.et
colnames(values6.m) <- c('Dec.2.capm')
ris6<-cbind(coef(mod.s6)[,1],coef(mod.s6)[,3:4])
colnames(ris6) <- c('Estimate', 't-value', 'Pr>|t|')
#####################################
Dec.3.capm <- lm(New_data$"Dec.3" ~ New_data$Mkt.RF)
coef(Dec.3.capm)
mod.s7<-summary(Dec.3.capm)
values7<-vector()
values7[1]<-mod.s7$r.squared
values7[2]<-mod.s7$adj.r.squared
f.stat<-mod.s7$fstatistic
values7[3]<-f.stat[1]
values7[4]<-f.stat[2]
values7[5]<-f.stat[3]
values7[6]<-pf(values7[3],values7[4],values7[5],lower.tail = FALSE)
values7[7]<-values7[1]/(1-values7[1])
values7.et<-c("R^2","adj R^2","F","df num.","df den.","p(F)","f^2")
values7.m<-cbind(round(values7,digits=5))
rownames(values6.m)<-values7.et
colnames(values6.m) <- c('Dec.3.capm')
ris7<-cbind(coef(mod.s7)[,1],coef(mod.s7)[,3:4])
colnames(ris7) <- c('Estimate', 't-value', 'Pr>|t|')
#####################################
Dec.4.capm <- lm(New_data$"Dec.4" ~ New_data$Mkt.RF)
coef(Dec.4.capm)
mod.s8<-summary(Dec.4.capm)
values8<-vector()
values8[1]<-mod.s8$r.squared
values8[2]<-mod.s8$adj.r.squared
f.stat<-mod.s8$fstatistic
values8[3]<-f.stat[1]
values8[4]<-f.stat[2]
values8[5]<-f.stat[3]
values8[6]<-pf(values8[3],values8[4],values8[5],lower.tail = FALSE)
values8[7]<-values8[1]/(1-values8[1])
values8.et<-c("R^2","adj R^2","F","df num.","df den.","p(F)","f^2")
values8.m<-cbind(round(values8,digits=5))
rownames(values8.m)<-values8.et
colnames(values8.m) <- c('Dec.4.capm')
ris8<-cbind(coef(mod.s8)[,1],coef(mod.s8)[,3:4])
colnames(ris8) <- c('Estimate', 't-value', 'Pr>|t|')
#####################################
Dec.5.capm <- lm(New_data$"Dec.5" ~ New_data$Mkt.RF)
coef(Dec.5.capm)
mod.s9<-summary(Dec.5.capm)
values9<-vector()
values9[1]<-mod.s9$r.squared
values9[2]<-mod.s9$adj.r.squared
f.stat<-mod.s9$fstatistic
values9[3]<-f.stat[1]
values9[4]<-f.stat[2]
values9[5]<-f.stat[3]
values9[6]<-pf(values9[3],values9[4],values9[5],lower.tail = FALSE)
values9[7]<-values9[1]/(1-values9[1])
values9.et<-c("R^2","adj R^2","F","df num.","df den.","p(F)","f^2")
values9.m<-cbind(round(values6,digits=5))
rownames(values9.m)<-values6.et
colnames(values9.m) <- c('Dec.5.capm')
ris9<-cbind(coef(mod.s9)[,1],coef(mod.s9)[,3:4])
colnames(ris9) <- c('Estimate', 't-value', 'Pr>|t|')
#####################################
Dec.6.capm <- lm(New_data$"Dec.6" ~ New_data$Mkt.RF)
coef(Dec.6.capm)
mod.s10<-summary(Dec.6.capm)
values10<-vector()
values10[1]<-mod.s10$r.squared
values10[2]<-mod.s10$adj.r.squared
f.stat<-mod.s10$fstatistic
values10[3]<-f.stat[1]
values10[4]<-f.stat[2]
values10[5]<-f.stat[3]
values10[6]<-pf(values10[3],values10[4],values10[5],lower.tail = FALSE)
values10[7]<-values10[1]/(1-values10[1])
values10.et<-c("R^2","adj R^2","F","df num.","df den.","p(F)","f^2")
values10.m<-cbind(round(values10,digits=5))
rownames(values10.m)<-values10.et
colnames(values10.m) <- c('Dec.6.capm')
ris10<-cbind(coef(mod.s10)[,1],coef(mod.s10)[,3:4])
colnames(ris10) <- c('Estimate', 't-value', 'Pr>|t|')
#####################################
SUMMARY <-cbind(values1.m, values2.m, values3.m, values4.m, values5.m, values6.m, values7.m, values8.m, values9.m, values10.m)
T_values <- rbind(ris1, ris2, ris3, ris4, ris5, ris6, ris7, ris8, ris9, ris10)