In our journey to understand the performance of AAPL and MSFT stocks over the past few years, we started by collecting the stock price data for both companies from Yahoo Finance. With this data in hand, we were ready to dive deep into the financial metrics that drive stock performance.
The first thing we did was to calculate the daily returns for each stock, which shows the percentage change in the stock price from one day to the next. This gave us a sense of how volatile the stocks are on a day-to-day basis.
To make sense of the stock price trends, we calculated moving averages for AAPL’s stock. We chose the 50-day and 200-day moving averages. The 50-day moving average helps capture short-term trends, while the 200-day moving average gives us insights into the longer-term trend. These averages helped us better visualize the overall direction of the stock price amidst daily fluctuations.
We also wanted to examine the distribution of daily returns to understand the risk involved. To do this, we plotted an interactive histogram of AAPL’s daily returns. This visual allowed us to see how often the stock experiences large fluctuations, which can be critical information for any investor.
Next, we decided to explore the trend of AAPL’s stock price over time by fitting a linear regression model. This model shows the general direction of the stock price, whether it’s on an upward trajectory, or if there’s any evidence of decline.
Since volatility is a key factor in stock price movements, we calculated the 30-day rolling volatility of AAPL. This metric tells us how much the stock price fluctuates over time. We plotted this volatility to see if there were periods of heightened risk or stability.
Finally, we wanted to see how a portfolio combining AAPL and MSFT would have performed. We merged the data for both stocks and computed the portfolio return, assuming each stock had a 50% weight in the portfolio. This gave us an interactive plot showing how the combined return of AAPL and MSFT would have behaved.
We begin by collecting stock price data for AAPL and MSFT from Yahoo Finance using the getSymbols() function.
## [1] "AAPL"
## [1] "MSFT"
We calculate the daily returns for both stocks and prepare the data frames accordingly.
AAPL_df = data.frame(Date = index(AAPL), coredata(AAPL))
AAPL_df = AAPL_df %>%
mutate(Daily_Return = (AAPL.Close - lag(AAPL.Close)) / lag(AAPL.Close)) %>%
filter(!is.na(Daily_Return))
MSFT_df = data.frame(Date = index(MSFT), coredata(MSFT))
MSFT_df = MSFT_df %>%
mutate(MSFT_Return = (MSFT.Close - lag(MSFT.Close)) / lag(MSFT.Close)) %>%
filter(!is.na(MSFT_Return))
We calculate the 50-day and 200-day moving averages for AAPL to analyze short-term and long-term trends.
plot_ly(AAPL_df, x = ~Date) %>%
add_lines(y = ~AAPL.Close, name = "Stock Price", line = list(color = 'black')) %>%
add_lines(y = ~MA_50, name = "50-Day Moving Average", line = list(color = 'red')) %>%
add_lines(y = ~MA_200, name = "200-Day Moving Average", line = list(color = 'blue')) %>%
layout(title = "AAPL Stock Price with Moving Averages",
xaxis = list(title = "Date"),
yaxis = list(title = "Price"),
legend = list(x = 0.1, y = 0.9))
We examine the distribution of AAPL’s daily returns using an interactive histogram.
A linear regression model is fitted to predict AAPL’s stock price based on the date.
AAPL_df$Date_num <- as.numeric(AAPL_df$Date)
model = lm(AAPL.Close ~ Date_num, data = AAPL_df)
summary(model)
##
## Call:
## lm(formula = AAPL.Close ~ Date_num, data = AAPL_df)
##
## Residuals:
## Min 1Q Median 3Q Max
## -41.239 -12.655 1.245 12.300 40.946
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -1.163e+03 2.348e+01 -49.53 <2e-16 ***
## Date_num 6.865e-02 1.236e-03 55.54 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 16.49 on 1003 degrees of freedom
## Multiple R-squared: 0.7547, Adjusted R-squared: 0.7544
## F-statistic: 3085 on 1 and 1003 DF, p-value: < 2.2e-16
plot_ly(AAPL_df, x = ~Date_num, y = ~AAPL.Close, type = 'scatter', mode = 'markers', name = "Stock Price") %>%
add_lines(y = predict(model), name = "Linear Regression", line = list(color = 'red')) %>%
layout(title = "Linear Regression of AAPL Stock Price",
xaxis = list(title = "Date"),
yaxis = list(title = "Closing Price"))
We calculate 30-day rolling volatility for AAPL and visualize the results.
AAPL_df = AAPL_df %>%
mutate(Rolling_Volatility = zoo::rollapply(Daily_Return, width = 30, FUN = sd, fill = NA, align = "right"))
plot_ly(AAPL_df, x = ~Date, y = ~Rolling_Volatility, type = 'scatter', mode = 'lines',
line = list(color = 'green')) %>%
layout(title = "30-Day Rolling Volatility of AAPL",
xaxis = list(title = "Date"),
yaxis = list(title = "Volatility"))
We merge AAPL and MSFT data and calculate the portfolio return with equal weights.
merged_data = merge(AAPL_df, MSFT_df, by = "Date", all = TRUE)
merged_data = merged_data %>%
filter(!is.na(Daily_Return) & !is.na(MSFT_Return))
weights = c(0.5, 0.5)
merged_data$Portfolio_Return <- (weights[1] * merged_data$Daily_Return) + (weights[2] * merged_data$MSFT_Return)
plot_ly(merged_data, x = ~Date, y = ~Portfolio_Return, type = 'scatter', mode = 'lines',
line = list(color = 'orange')) %>%
layout(title = "Portfolio Return of AAPL and MSFT",
xaxis = list(title = "Date"),
yaxis = list(title = "Portfolio Return"))
This analysis helped us understand the daily performance, risk, and trend of AAPL and MSFT stocks. Additionally, we evaluated the combined performance of both stocks through a portfolio, providing insights into how they might complement each other for an investor looking for a diversified strategy.