2023-11-16

Getting Started

Importing the Data & Libraries

In this analysis, we are analyzing the stock trends on the electric car company, Tesla (stock symbol: TSLA) using data from Yahoo Finance. I utilized the “quantmod” package for financial modeling which I found through Google: https://cran.r-project.org/web/packages/quantmod/index.html. Additionally, I am using ggplot2 for data visualization. Setting up the environment involves installing and loading necessary packages, including setting a CRAN mirror with the official repository URL.

options(repos = c(CRAN = “https://cloud.r-project.org”))
install.packages(“quantmod”)
install.packages(“ggplot2”)
library(quantmod)
library(ggplot2)

getSymbols

After installing and loading the packages, we use the getSymbols function to download the stock price series and preprocess the data for analysis.

tesla <- getSymbols("TSLA", src = "yahoo", from = "2018-11-15", 
to = "2023-11-15", auto.assign = FALSE)

Quick Overview of the Data

Before we jump into processing the data, let’s familiarize ourselves with the data we just imported.

     Index              TSLA.Open        TSLA.High         TSLA.Low     
 Min.   :2018-11-15   Min.   : 12.07   Min.   : 12.45   Min.   : 11.80  
 1st Qu.:2020-02-19   1st Qu.: 37.47   1st Qu.: 38.26   1st Qu.: 35.95  
 Median :2021-05-18   Median :193.24   Median :198.00   Median :188.65  
 Mean   :2021-05-17   Mean   :165.61   Mean   :169.38   Mean   :161.53  
 3rd Qu.:2022-08-16   3rd Qu.:250.05   3rd Qu.:254.98   3rd Qu.:244.45  
 Max.   :2023-11-14   Max.   :411.47   Max.   :414.50   Max.   :405.67  
   TSLA.Close      TSLA.Volume        TSLA.Adjusted   
 Min.   : 11.93   Min.   : 29401800   Min.   : 11.93  
 1st Qu.: 37.20   1st Qu.: 79645800   1st Qu.: 37.20  
 Median :193.63   Median :109015000   Median :193.63  
 Mean   :165.55   Mean   :133767619   Mean   :165.55  
 3rd Qu.:250.97   3rd Qu.:158699100   3rd Qu.:250.97  
 Max.   :409.97   Max.   :914082000   Max.   :409.97  

Summary of Data

  • Index: The date of the data point.
  • TSLA.Open: The opening stock price of Tesla on that date.
  • TSLA.High: The highest stock price reached during the day.
  • TSLA.Low: The lowest stock price reached during the day.
  • TSLA.Close: The closing stock price of Tesla on that date.
  • TSLA.Volume: The trading volume, representing the total number of shares traded on that date.
  • TSLA.Adjusted: The adjusted closing price, which accounts for events such as stock splits and dividends.

Tesla Price Series

Price Series Analysis

In the ggplot of the previous slide, I used the Adjusted Price column and it incorporates events like splits and dividends distribution, which can affect the series.

Visually, the plot shows the past 10 years with the minimum price being $8 and its highest peak was $411.
We can see that there is an upward trend and it has exploded since beginning of 2020.

Moving Average Formula

\[MA^q_t = \frac{1}{q}\ \sum_{i=0}^{q-1} x_{t-1}\]


In stock technical analysis, the Moving Average is a commonly used technique involving the calculation of the arithmetic average of the last q days in a time series over the t time period. The moving average is valuable for trend identification and noise reduction in stock prices, with the responsiveness to price changes influenced by the chosen window size. It is best to calculate two moving averages for stock prices, one with a 10-day window and another with a 30-day window.

Tesla Moving Average

\[MA^q_t\]
The moving average at time t with a window size of q.
\[x_{t-1}\]
The closing price of Tesla stock at time t.
\[\sum_{i=0}^{q-1} x_{t-1}\]
The sum of the closing prices for the past q days, including the current day.


The moving average for Tesla stock at time t with a window size of q is the average of the closing prices for the past q days. To calculate it, you would sum up the closing prices for the most recent q days and then divide the result by q. This gives you the average closing price over that time window which is the stock’s price trend.

Tesla Moving Average ggplot

The process involves subsetting data from 2018 and using the rollmean() function to calculate a moving average for the adjusted price series. The function takes parameters such as the window of periods (q), optional fill values for incomplete calculations, and an alignment parameter to determine how the moving average is positioned relative to the day in the series. The resulting moving averages are added to two new columns in the original dataset. In Technical Analysis, if the moving averages of short (red) and long term (blue) cross each other, it is an indication of buying or selling the stock. When the short term moving average crosses the long term upwards, it’s a buy signal. When the opposite happens, then it’s a sell signal.

Tesla Moving Average

Calculating Stock Returns

The log return of a stock is a measure of the percentage change in the stock’s value over a specific period, expressed as the natural logarithm of the ratio of the final price to the initial price. It is commonly used in finance and investment to represent the relative change in the value of an asset over time.

The formula for calculating the log return (r) of a stock over a given period is: \[r_t = ln(1+R_t) = ln\frac{P_t}{P_(t-1)}\ = ln(P_t)-ln(P_t-1)\]

Calculate Tesla Returns

     Index            TSLA.Adjusted      
 Min.   :2018-11-16   Min.   :-0.236518  
 1st Qu.:2020-02-19   1st Qu.:-0.018147  
 Median :2021-05-18   Median : 0.001999  
 Mean   :2021-05-18   Mean   : 0.001851  
 3rd Qu.:2022-08-16   3rd Qu.: 0.021982  
 Max.   :2023-11-14   Max.   : 0.181445  
[1] 0.04106578

Tesla Returns Series

Overall Analysis

Mean Return: The mean (average) return for Tesla is approximately 0.001851 or 0.1851%. This represents the average return over the specified time period.

Median Return: The median return, which is the middle value when returns are sorted in ascending order, is 0.001999 or 0.1999%. This provides an insight into the central tendency of the returns distribution.

Standard Deviation: The standard deviation is a measure of the dispersion or volatility of returns. A standard deviation of 0.04106578 indicates the degree of variation in the returns. Higher standard deviation values suggest greater volatility.

Quartiles: The first quartile (25th percentile) is -0.018147, and the third quartile (75th percentile) is 0.021982. These values give an idea of the spread of returns within the lower and upper 25% and 75% of the distribution, respectively.

Minimum and Maximum Returns: The minimum return is -0.236518, and the maximum return is 0.181445. These values represent the extremes of the return distribution.

Conclusion

In summary, the statistics provide an overview of the central tendency, variability, and distribution of Tesla returns over the specified time period. The positive mean and median returns suggest a generally positive trend in the stock, while the standard deviation indicates the level of volatility. Understanding these metrics can assist investors in assessing risk and making informed decisions based on their investment objectives and risk tolerance.