Overview

Stock Prices

Column

Tech - (META)

HealthCare - (JNJ)

Customer Goods - (PEP)

Finance - (JPM)

Energy - (BP)

Close Prices (Adjusted)

Column

Closing Prices (Adjusted)

Moving Average

Column

Moving Average For All Securities

Trading Volumes

Column

Trading Volumes for securities

MACD

Column

Moving Average Convergence Divergence for All Securities

RSI

Column

Relative Strength Index for All Securities

Summary

Column

Due to the geopolitical, macroeconomic environment shift in the year of 2022, the selection of securities are picked one from each key sectors for this project to provide one view of stock market.

  • Tech Sector: META (Meta Inc)

  • Healthcare Sector: JNJ (Johnson & Johnson)

  • Consumer Goods Sectors: PEP (PepiCo)

  • Financial Sectors: JPM (JPMorgan)

  • Energy Sector: BP (BP)

Many sectors are struggling to make a profit under current market.

Current studies in this lab are only using the basic tools to analyze the possible price trend. It’s the best to combine these three basic tools to gain insight of pricing trend given the existing situation.

  • Simple Moving Average
  • Relative Strength Index
  • Moving Average Convergence Divergence

Even for the most short term gains, considering all the factors, it is still a very difficult task to make good prediction.

Securities from 2017-01-01 to present date are analyzed and visualized. The data source is Yahoo. The first page shows an overview of daily closing prices of all securities. It followed by Stock Prices and Closing prices (Adjusted) per financial instrument. Futher, visualize them using SMA(Simple Moving Average), Volume, RSI(Relative Strength Index) and MACD (Moving Averaging Convergence/Divergence) separately to get a better understanding on pricing trends.

Considering all of the factors, JNJ seems to be a good option.

To actually invest, we will need more data and need a good selection of balanced portfolios.

---
title: "ANLY-512 Dashboard Lab 1"
author: "Hao Zhang"
output:
  flexdashboard::flex_dashboard:
    orientation: rows
    social: menu
    source_code: embed
    vertical_layout: fill
  html_document:
    df_print: paged
---    


Overview 
=====================================
```{r,setup, include=FALSE}
# loading necessary R libraries
library(flexdashboard)

library(dygraphs)
library(ggplot2)

library(dplyr)

library(lubridate)
library(scales)

library(TTR)
library(tidyquant)
library(pdfetch)
library(tidyr)



library(xts)

# Define all the tickers for  securities across a few sectors

## Tech Sector: AMZN (Aamzon Inc), META (Meta Inc),

## Healthcare Sector: JNJ (Johnson & Johnson), PFE (Pfizer Inc)

## Consumer Goods Sectors:  PEP (PepiCo), KO (Coca-Cola)

## Financial Sectors: JPM (JPMorgan), V (Visa Inc)

## Energy Sector: BP (BP), XOM (Exxon Mobile)


#
START_DATE <- as.Date("2017-01-01")

securities <- c("META", "JNJ", "PEP", "JPM", "BP") # To plot nicely, pick one security from each sector

 

# ABANDONED for now -  Define the tickers for the commodities - Have some issues to retrieve data --> TODO: Will come back to this

#commodities <- c("XAU", "WTI", "HG", "NG", "XAG")


# reference: https://github.com/business-science/tidyquant/blob/master/R/tq_get.R

# Get pricing for the selected securities
securities_data <- tq_get(securities, get = "stock.prices", from = START_DATE,  # NOTE: 2017-01-01 seems to be a popular choice
                            return_class = "tibble", 
                            adjust = TRUE,
                            col_rename = c("open" = "Open",
                                            "high" = "High",
                                            "low" = "Low",
                                            "close" = "Close",
                                            "volume" = "Volume"))

```



```{r, fig.show='hold'}
# Visualizing selected portfolio in one static plot

securities_data %>% 
  group_by(symbol) %>% 
  ggplot(aes(x = date, y = close, color=symbol)) +
  geom_line()  + coord_fixed(4) + 
  ggtitle("Close Price for Selected Securities for Each Key Sectors (Static)") +
  xlab("Year") +
  ylab("Close Price")



```



Stock Prices
=====================================

```{r}
# Create a function call for individual security price plot

PRC_OHLC = c("Open","High","Low","Close")

plot_individual_security <- function(ticker, ylab = "Stock Prices (OHLC)", group = "stockprices") {

    # Reference: https://rdrr.io/github/abielr/pdfetch/man/pdfetch_YAHOO.html

  x <- pdfetch_YAHOO(ticker, # NOTE: this function can be optimized....
                     fields = c("open", "high", "low", "close"), 
                     from = START_DATE, # 2017-01-01, choice source
                     interval = "1d") 

  colnames(x) <- PRC_OHLC # renaming the columns
  
    dygraph(x,
            ylab = ylab,
            group = group) %>%
      
    dyCandlestick() %>%
    
    dyRangeSelector()
}

# define group plot function call
plot_group_security <- function(my_data, main = "Closing Price (Adjusted)", ylab = "Closing Price (Adjusted)", group ="trading") {

# NOTE: formatting date
my_data$date <- as.Date(my_data$date)
rownames(my_data) <- my_data$date


my_data_xts <- xts(my_data[,-1], order.by = my_data$date) # NOTE: remove date column, always assuming date field at the first place.

dygraph(my_data_xts,
        main = main, 
        ylab = ylab,
        group = group) %>%
  
  # reference: https://www.rdocumentation.org/packages/dygraphs/versions/1.1.1.6/topics/dyHighlight
  dyHighlight(
              highlightSeriesBackgroundAlpha = 0.5, # 1 - fully opaque, 0 - fully transparent
              hideOnMouseOut = TRUE
              ) %>%
  
  dyOptions(strokeWidth = 2, # 2 is good for visual
           colors = scales::hue_pal()(5), # 5 colors, one for a security
            ) %>%
  
  dyRangeSelector()
}


```

Column {.tabset data-height=550}
-----------------------------------------------------------------------

### Tech - (META)

```{r}
# Tech Sector Pick

plot_individual_security("META")
```


### HealthCare - (JNJ)

```{r}
# HealthCare Sector Pick

plot_individual_security("JNJ")
```


### Customer Goods - (PEP)

```{r}
# Customer Goods Sector 

plot_individual_security("PEP")
```

### Finance -  (JPM)

```{r}

# Financial Sector

plot_individual_security("JPM")
```


### Energy -  (BP)
```{r}

# Energy Sector

plot_individual_security("BP")
```


Close Prices (Adjusted)
=====================================

Column {.tabset data-height=550}
-----------------------------------------------------------------------

### Closing Prices (Adjusted)
```{r}

# transformation
adjusting_data  <- securities_data %>%
  group_by(symbol) %>%
  select(date, adjusted) %>%
  spread(symbol, adjusted)

plot_group_security(adjusting_data)

```




Moving Average
=====================================

Column {.tabset data-height=550}
-----------------------------------------------------------------------

### Moving Average For All Securities
```{r}

# Calculate SMA for securities
sma_data <- securities_data %>% 
  group_by(symbol) %>% 
  mutate(sma = SMA(close, n = 50)) %>%
  select(date, sma) %>%
  spread(symbol, sma)


plot_group_security(sma_data, main = "50-Day Simple Moving Average Plot", ylab = "Simple Moving Average")


```

Trading Volumes
=====================================

Column {.tabset data-height=550}
-----------------------------------------------------------------------

### Trading Volumes for securities
```{r}

# Transformation
volume_data  <- securities_data %>%
  group_by(symbol) %>%
  select(date, volume) %>%
  spread(symbol, volume)


plot_group_security(volume_data, main = "Trading Volume Plot", ylab = "Volumes")

```


MACD
=====================================

Column {.tabset data-height=550}
-----------------------------------------------------------------------

### Moving Average Convergence Divergence for All Securities
```{r}

# Calculate MACD for securities
macd_data <- securities_data %>% 
  group_by(symbol) %>% 
  mutate(macd = MACD(close)) %>%
  select(date, macd) %>%
  spread(symbol, macd)

plot_group_security(macd_data, main = "Moving Average Convergence/Divergence  Plot", ylab = "MACD")

```


RSI
=====================================

Column {.tabset data-height=550}
-----------------------------------------------------------------------

### Relative Strength Index for All Securities
```{r}

# calculate RSI
rsi_data <- securities_data %>% 
  group_by(symbol) %>% 
  mutate(rsi = RSI(close)) %>%
  select(date, rsi) %>%
  spread(symbol, rsi)

plot_group_security(rsi_data, main = "Relative Strength Index Plot", ylab = "RSI")
```

Summary 
=====================================


Column {data-width=600}
-------------------------------------

###


Due to the geopolitical, macroeconomic environment shift in the year of 2022, the selection of securities are picked one from each key sectors for this project to provide one view of stock market.

* Tech Sector:  META (Meta Inc)

* Healthcare Sector: JNJ (Johnson & Johnson)

* Consumer Goods Sectors:  PEP (PepiCo)

* Financial Sectors: JPM (JPMorgan)

* Energy Sector: BP (BP)

Many sectors are struggling to make a profit under current market.

Current studies in this lab are only using the basic tools to analyze the possible price trend. It's the best to combine these three basic tools to gain insight of pricing trend given the existing situation.

<!-- Reference SMA: https://www.investopedia.com/ask/answers/012815/why-50-simple-moving-average-sma-so-common-traders-and-analysts.asp -->
* Simple Moving Average

<!-- Reference RSI : https://www.investopedia.com/terms/r/rsi.asp-->

* Relative Strength Index

<!-- Reference MACD: https://www.investopedia.com/terms/m/macd.asp -->
* Moving Average Convergence Divergence

Even for the most short term gains, considering all the factors, it is still a very difficult task to make good prediction.

Securities from 2017-01-01 to present date are analyzed and visualized. The data source is Yahoo. The first page shows an overview of daily closing prices of all securities. It followed by Stock Prices and  Closing prices (Adjusted) per financial instrument. Futher, visualize them using SMA(Simple Moving Average), Volume, RSI(Relative Strength Index) and MACD (Moving Averaging Convergence/Divergence) separately to get a better understanding on pricing trends.

Considering all of the factors, *JNJ* seems to be a good option. 

To actually invest, we will need more data and need a good selection of balanced portfolios.