Professional Documents
Culture Documents
R for Finance
ANSWER 1
To load the data and create a time series matrix object with correct date stamps, we can use the
read.csv function to read the csv file and then convert the date column to a suitable format using
the as Date function. We can then create a time series matrix object using the xts function from
the xts package (Abhay Kumar Singh & David Edmund Allen, 2016).
library(xts)
# Create a time series matrix object with the correct date stamps
ANSWER 2
The sp500 is an index that monitors the performance of 500 significant companies listed on US
stock exchanges.
The Nasdaq100 is another index that focuses on 100 of the largest non-financial companies listed
on the Nasdaq exchange.
1
Global robotics & automation ETF (robo)
This is an exchange-traded fund (ETF) that invests in companies involved in the production and
development of robots and automation technology.
SINGLE STOCKS
ABB
Fanuc
Fanuc is a Japanese company that produces industrial robots and automation equipment.
Harmonic
Harmonic is a US company that develops and sells video and broadband infrastructure solutions
for cable, satellite, and telecom companies.
Siemens
Siemens is a German multinational corporation that produces a wide range of products, including
automation systems, power generators, and medical equipment.
Tesla
Tesla is a US company that designs and produces electric vehicles, energy storage systems, and
solar products.
ANSWER 3
To create a general function for summary statistics, we can define a function that takes the time
series matrix object as an input and then uses the apply function to apply the summary function
to each column of the matrix (Regenstein, 2018). We can then extract the required summary
statistics from the output of the summary function.
# Define a function to compute summary statistics for a time series matrix object
2
compute_summary <- function(data) {
# Extract the required summary statistics from the output of the summary function
return(summary_df)
summary_stats
This process utilizes the apply function to implement the summary function on every column of
a matrix. Then, we extract the relevant summary statistics from the summary function's output
and merge them into a data frame. The final summary data frame shows the mean, median,
standard deviation, and range for each column of the time series matrix object. It is important to
note that we applied the apply function with the 2nd argument to operate on each column of the
matrix because the apply function operates on matrices, where the first argument is the matrix,
3
and the second argument specifies the axis along which the function should be applied (1 for
rows and 2 for columns).
In addition, the function returns the summary data frame, which can be further used for
visualization or analysis.
ANSWER 4
To produce graphical summaries for each of the securities, we can use various plotting functions
available in R. Here are some examples:
To visualize the time series of each security, we can use the plot function from the xts package.
Here is an example for the S&P 500 index:
This will produce a time series plot of the S&P 500 index with the y-axis labeled as "Price".
Box plot
To visualize the distribution of each security, we can use the boxplot function. Here is an
example for the Nasdaq 100 index:
This will produce a box plot of the Nasdaq 100 index with the y-axis labeled as "Price".
Histogram
To visualize the frequency distribution of each security, we can use the hist function. Here is an
example for the robotics & automation ETF:
4
This will produce a histogram of the robotics & automation ETF with the x-axis labeled as
"Price".
Scatter plot
To visualize the relationship between two securities, we can use the plot function with two
variables. Here is an example for the relationship between the S&P 500 index and the robotics &
automation ETF:
# Scatter plot of S&P 500 index and robotics & automation ETF
plot(ts_data$sp500, ts_data$robo, main = "S&P 500 Index vs Robotics & Automation ETF",
This will produce a scatter plot of the S&P 500 index and the robotics & automation ETF with
the x-axis labeled as "S&P 500 Index" and the y-axis labeled as "Robotics & Automation ETF".
These are just a few examples of the many types of graphical summaries that can be produced
for each security. Depending on the research questions and the characteristics of the data,
different types of plots may be more appropriate.
ANSWER 5
Based on the summary statistics and graphical output, we can compare the securities in various
ways. Here are some observations:
Mean
The mean price of the securities varies widely, with Tesla having the highest mean price among
all securities, followed by Siemens and ABB. The mean price of the Nasdaq 100 index is slightly
higher than that of the S&P 500 index, while the mean price of the robotics & automation ETF is
lower than both.
Standard deviation
Tesla exhibits the highest standard deviation, indicating significant volatility when compared to
other securities. The standard deviation for the S&P 500 index is lower than that of the Nasdaq
5
100 index, indicating less volatility. The robotics and automation ETF exhibit the lowest standard
deviation among all securities, implying a relatively steady performance.
Range
The range of the securities also varies widely, with Tesla having the highest range among all
securities, indicating a wide range of prices over time. The range of the robotics & automation
ETF is the lowest among all securities, indicating a relatively narrow range of prices over time.
Graphical output
The graphical output also provides insights into the performance of each security over time. For
example, the time series plot of Tesla shows a steep increase in price from mid-2016 to mid-
2017, followed by a decline in late 2017 and early 2018, and then a subsequent increase in late
2018 and early 2019. The time series plot of the robotics & automation ETF, on the other hand,
shows a relatively stable performance with a gradual increase in price over time. The scatter plot
of the S&P 500 index and the robotics & automation ETF shows a positive correlation between
the two securities, while the scatter plot of Tesla and the Nasdaq 100 index shows a weak
correlation between the two securities.
Overall, comparing the securities based on the summary statistics and graphical output can
provide insights into the relative performance, volatility, and trends of each security over time. It
is important to note that the scale used for comparison may differ depending on the research
questions and the characteristics of the data, and that additional analyses and visualizations may
be needed to fully understand the relationships between the securities.
ANSWER 6
setClass("TimeSeriesMatrix",
6
# Constructor function for TimeSeriesMatrix
obj
In this class, we define a new class called "Timeseries Matrix" with two slots: "data" which is a
matrix containing the time series data, and "dates" which is a vector of class "Date" containing
the corresponding date stamps.
ANSWER 7
To append the new class to the object created in step 1, we can use the set Class Union function.
Here's an example:
class(tsm)
In this code, we first use the set Class Union function to append the "Timeseries Matrix" class to
the existing "xts" class. This creates a new class called "Timeseries" that includes both classes.
We then create a new Timeseries Matrix object using the data and date stamps from the object
created in step 1. Finally, we use the class function to check that the new object has the expected
class.
7
ANSWER 8
To define custom summary and print methods for our "TimeSeriesMatrix" class, we can use the
summary and print functions, respectively. Here's an example:
cat("\n")
print(summary(object@data))
print(x@data)
cat("\n")
cat("Date Stamps:\n\n")
print(x@dates)
In the summary method, we first print a title indicating that we are printing a time series
summary. We then print the start and end dates of the time series, and then call the summary
function on the data slot of the object.
8
In the print method, we first print a title indicating that we are printing the time series data. We
then print the data slot of the object, followed by a title indicating that we are printing the date
stamps, and then the dates slot of the object.
We can now use the summary and print functions to display summaries and data for our
"Timeseries Matrix" objects in a more readable format. Here's an example:
summary(tsm)
print(tsm)
In this code, we create a new "Timeseries Matrix" object using the data and date stamps from the
object created in step 1. We then call the summary function and the print function on the new
object to display its summary and data in our custom format.
ANSWER 9
To write a custom plot method for our "Timeseries Matrix" class, we can use the ggplot2
package to create a set of plots that display the time series data for each stock. Here's an
example:
library(ggplot2)
9
plot.TimeSeriesMatrix <- function(x, ...) {
# Set up a data frame containing the date stamps and data for each stock
SP500 = x@data[,1],
NASDAQ100 = x@data[,2],
ROBO = x@data[,3],
ABB = x@data[,4],
FANUC = x@data[,5],
HARMONIC = x@data[,6],
SIEMENS = x@data[,7],
TESLA = x@data[,8])
xlab("Date") +
ylab("Price") +
10
ggtitle("Time Series Plot")
return(p)
In this code, we define a new plot. Time Series Matrix function that takes a "Time Series Matrix"
object as input. We create a data frame containing the date stamps and data for each stock, and
then use ggplot2 to create a plot of the time series data for each stock.
We can now use the plot function to display the time series data for our "Time Series Matrix"
objects. Here's an example:
plot(tsm)
This code generates a plot of the time series data for each stock in our "Time Series Matrix"
object, and displays it in a plot window. This plot maintains the time series nature of the data, as
it displays the time series for each stock on the x-axis, with the price values on the y-axis.
11
REFERENCES
Abhay Kumar Singh, & David Edmund Allen. (2016). R in Finance and Economics. World
12