This worksheet looks at some common trading rules, modeling and forecasting, and some fundamental analysis.
Remember to always set your working directory to the source file location. Go to ‘Session’, scroll down to ‘Set Working Directory’, and click ‘To Source File Location’. Read carefully the below and follow the instructions to complete the tasks and answer any questions. Submit your work to RPubs as detailed in previous notes.
Always read carefully the instructions on Sakai. For clarity, tasks/questions to be completed/answered are highlighted in red color (visible in preview) and numbered according to their particular placement in the task section. Quite often you will need to add your own code chunk.
Execute all code chunks, preview, publish, and submit link on Sakai follwoing the naming convention. Make sure to add comments to your code where appropriate. Use own language!
This task follows the example in the book R Example 6.1/p 185 A new package will be required for this worksheet. All packages are included, for your convenience, in the code chunks below.
#Install package quantmod
if(!require("quantmod",quietly = TRUE))
install.packages("quantmod",dependencies = TRUE, repos = "https://cloud.r-project.org")
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
## Version 0.4-0 included new data defaults. See ?getSymbols.
#Install package fArma for modelling ARMA time series processes
if(!require("fArma",quietly = TRUE))
install.packages("fArma",dependencies = TRUE, repos = "https://cloud.r-project.org")
## Warning in library(package, lib.loc = lib.loc, character.only = TRUE,
## logical.return = TRUE, : there is no package called 'fArma'
## Warning: package 'fArma' is not available (for R version 3.3.3)
The following questions are for a stock of your choice from S&P500 (other than AAPL and your colleague!) and for the time-period from Jan 1, 2015 to present.
Observing the crossings or intersections between two simple moving averages can provide signals for buying or selling.
##### 1A) Create a chart of close prices and add the two simple moving averages over the periods n=20 and n=50. Clearly label the plots or provide a legend
library("quantmod")
getSymbols("ABBV",src='yahoo', from="2015-01-01", to="2019-1-16")
## 'getSymbols' currently uses auto.assign=TRUE by default, but will
## use auto.assign=FALSE in 0.5-0. You will still be able to use
## 'loadSymbols' to automatically load data. getOption("getSymbols.env")
## and getOption("getSymbols.auto.assign") will still be checked for
## alternate defaults.
##
## This message is shown once per session and may be disabled by setting
## options("getSymbols.warning4.0"=FALSE). See ?getSymbols for details.
##
## WARNING: There have been significant changes to Yahoo Finance data.
## Please see the Warning section of '?getSymbols.yahoo' for details.
##
## This message is shown once per session and may be disabled by setting
## options("getSymbols.yahoo.warning"=FALSE).
## Warning in strptime(xx, f <- "%Y-%m-%d", tz = "GMT"): unknown timezone
## 'default/America/Chicago'
## [1] "ABBV"
chartSeries(ABBV, subset="2015-01::2019-01", theme=chartTheme("white",up.col="green",dn.col="red"), TA=c(addSMA(n=50, col="blue"), addSMA(n=20, col="black")))
##### 1B) Select a particular crossover point to explain how you would implement a trading strategy (ref p184)
If we find a upper trend, where the 20 frequency line crosses the 50 frequency line in an upward fashion, the price is on the rise and it is a signal to buy. If we find a downward trend, where the 20 frequency line crosses the 50 frequency line in a downward fashion, the price is falling and it is a signal to sell the asset.
At the peak of this chart, right after January 2nd, 2018, there is a doward crossing on the 20 frequency line on the 50 frequency line. This signals a for a selling trading strategy.
Bollinger bands are a kind of a trading bands or moving average envelopes. The high and low limits of a Bollinger band are calculated based on a x-number of standard deviation (usually 2) away from the moving average. A standard deviation is also a measure of volatility, as such the band will widen when volatility increases and contract when volatility decreases. As with bands and envelopes the idea of Bollinger band is that prices tend to stay within the band. When prices reach the top band it is assumed that resistance will be encountered and the price will fall. Opposite true when the lower band is reached. When the price moves outside the bands, a continuation of the current trend is expected.
##### 1C) Chart the Bollinger Bands based on the 20-days moving average and two standard deviations. Select a particular point to explain how the BB can be used in a trading strategy (ref p185)
library("quantmod")
getSymbols("ABBV",src='yahoo', from="2015-01-01", to="2019-1-16")
## [1] "ABBV"
chartSeries(ABBV, subset="2015-01::2019-01", theme=chartTheme("white",up.col="green",dn.col="red"), TA=c(addBBands(n=20, sd=2)))
After June of 2016, there is a dip below the Bollinger Band, indicating that the price will continue its current trend downward and that one should sell the stock before it drops any lower.
RSI measures the velocity of price changes. Rapid price increases is an indication of stock overbought conditions, and rapid price decreases result in oversold conditions. When used properly RSI can assist in optimizing proper entry and exit decisions.
##### 1D) Chart the Relative Strength Index (RSI) based on 14-days moving average. Select a particular point to explain how RSI can be used in a trading strategy (ref p206)
library("quantmod")
getSymbols("ABBV",src='yahoo', from="2015-01-01", to="2019-1-16")
## [1] "ABBV"
chartSeries(ABBV, subset="2015-01::2019-01", theme=chartTheme("white",up.col="green",dn.col="red"), TA=c(addRSI(n=14)))
When the RSI crosses the Entry Threshold and rises above 100-ET, it signals to sell.
When the RSI crosses the Entry Threshold and falls below the ET, it is a signal to buy.
I belive the Entry Threshold is 44.207, and at point around January 2, 2018, the RSI rises above 80, indicating that high volatility and overbought stock conditions. This is a signal to sell.
Similar to lab03 pick a currency exchange rates of your choice. Follow R Example 4.2/p 119. Pay special attention to Remark 4.1/p 112 and class notes for the correct interpretation and representation of results. Depending on the R version, the package fArma may not be available (true for 3.5 and up). One can use instead the function arima() to fit an AR(1) and the print to obtain the model coefficients. Check the illustrated example below and read the Help in R, as needed, for more insights on how to use commands.
#ar1 = arima(dataset, order = c(1,0,0)) to obtain the equivalent of an AR(1) model fit. dataset is in reference to your particular currency exchange pair like RUBUSD for example.
#print(ar1) to print the coffecients of the model. Pay attention to the interpretation of intercept
First we derive an autoregressive model of order 1, excluding the out-of-sample points. To exclude ppints check the example below
#ar1 = arimadataset[1:n], order - c(1,0,0)). This will build an AR(1) model based on the time series dataset [1:n] where n is the length of the tie series minus the last four points. For example EURUSD[1:175] is for the case where the total time series for the EURUSD is 179 observation points.
##### 2A) Derive an AR(1) model excluding the last four points from your time series (the out-of-sample). Note the values of the model coefficients, and write down the correspondng mathematical representation of the model.
getFX("GBP/USD")
## [1] "GBPUSD"
ar1 = arima(GBPUSD[1:175], order = c(1,0,0))
print(ar1)
##
## Call:
## arima(x = GBPUSD[1:175], order = c(1, 0, 0))
##
## Coefficients:
## ar1 intercept
## 0.9670 1.2924
## s.e. 0.0176 0.0084
##
## sigma^2 estimated as 1.763e-05: log likelihood = 708.1, aic = -1410.2
Next we apply the derived model to predict the rates, within confidence levels, for the out-of-sample points.
##### 2B) Using the fitted model, predict the rates for the excluded points corresponding to the four days ahead. Select one particular forecasted day to illustrate manually how the reported predicted rate can be reproduced using the derived AR(1) model.
predict(ar1,n.ahead=4,n.back=10)
## $pred
## Time Series:
## Start = 176
## End = 179
## Frequency = 1
## [1] 1.293075 1.293053 1.293032 1.293012
##
## $se
## Time Series:
## Start = 176
## End = 179
## Frequency = 1
## [1] 0.004198522 0.005840344 0.007037083 0.007995622
Finally we want to assess the goodness of the model by conducting a quantitative analysis.
##### 2C) Formulate and execute a way to test the fitness of the model. Share your results.
The Mean Suared Error Test can be used to measure the fitness of the model.
MSE = \(\frac{1}{m}\sum_{x=1}^{m}(y_{t} - y_{t-1})^{2}\) ### Task 3: Fundamental Analysis
Consider two stocks of your choice. Unfortunately the code in the R Example 6.2/p 202 is no more valid as Google stopped providing such data as of March 2018. Instead you are advised to use Bloomberg or other sources to extract the needed information. The information in Bloomberg is available in the security description page of a stock.
##### 3A) For each stock report the P/B, P/E, and Assets/Debts ratios. Note also the fiscal calendar date associated with the reported ratios.
1/30/2019 Microsoft (MSFT:US) P/B=9.5331 P/E=27.52 Debt Ratio = 0.67
4/16/2018 IBM P/B=6.1041 P/E=9.5433 Debt Ratio = 0.83
##### 3B) Based on solely the three reported ratios which company has a stronger financial condition. Explain your logic. A P/B close to 1 means a fair price, a lower than 1 means share price is undervalued or something wrong with the company, similarly a higher than 1 means overvalued
All else being equal, a lower PE ratio is better. Historically the ratio has been around 15-25
high debt ratio means high leveraged company
Microsoft: overvalued, high P/E meaning investors expect higher earnings, somewhat leveraged
IBM: overvalued, low P/E meaning stock might be undervalued, very leveraged.
I believe that Microsoft has a stronger financial condition. the P/B ratio indicates that Microsoft is overvalued, the P/E ratio indicates that investors expect higher earnings, and it has a healthy debt ratio- meaning that they have leverage and that it has a healthy amount of volatlity *http://computationalfinance.lsi.upc.edu
plot(cars)
Add a new chunk by clicking the Insert Chunk button on the toolbar or by pressing Cmd+Option+I.
When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the Preview button or press Cmd+Shift+K to preview the HTML file).
The preview shows you a rendered HTML copy of the contents of the editor. Consequently, unlike Knit, Preview does not run any R code chunks. Instead, the output of the chunk when it was last run in the editor is displayed.