Data Understanding

The files I read into the file was as followed: AAPL.csv ADBE.csv AMZN.csv BABA.csv BIDU.csv FB.csv MSFT.csv PCTY.csv TWTR.csv ZM.csv

I used head(), anyNA(), and summary()

Yes the files share the same structure columns are date, open, high, low, close, adj.close, and volume.

All the files appear to have the same type of data however, adbe data open seems to be all 0’s and wanted to note this data outlier

using anyNA() no there are no missing values in any of the datasheets.

My understanding of these datasets is that they are very similar in format, with consistent structure and columns across files. Some files contain more records than others, which could make their analyses more reliable or informative. The data is generally clear and well-structured, allowing for further analysis and asking meaningful questions. For example, the Date column enables grouping and sorting by time, while the Volume column can reveal patterns of large trades or bulk purchases, which may be useful for identifying trends in stock activity.


ones used are mean, max, min, median, and quartiles 1st and 3rd.

Price of Stocks: Stocks like AAPL, AMZN, and MSFT show a wide range of prices (large difference between min and max), whereas minor companies like ZM or PCTY have a smaller range. Their prices fluctuate more compared to ZM or PCTY. This is just a pattern in the data, showing which stocks are more varied.

Trading Volume Differences: AAPL and MSFT show high trading volumes on certain days, while TWTR or PCTY have lower volumes overall. These spikes in trading activity could help identify patterns of high market interest in the data.

Mean vs. Median Differences: For some stocks, the mean price is higher than the median. The price distribution is slightly off, with some unusually high values affecting the average.


Visual Analysis

Apple Candlestick Chart Data used: Date, Open, Close, High, Low Pattern: Stock shows daily price ranges; green bars = price gain, red = price drop. Noticeable up-and-down drastic changes over time.

Facebook Line Plot Data used: Date, Close Pattern: Closing price trends over time; shows general growth or decline pattern with visible fluctuations.

Amazon Histogram Plot Data used: Date, Close Pattern: Shows how Amazon’s closing price changes over time; general upward trend with short periods of dips or corrections.

library(readr)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggplot2)

# ------------------------
# Load data
# ------------------------
aaplData <- read_csv("AAPL.csv", show_col_types = FALSE)
## Warning: One or more parsing issues, call `problems()` on your data frame for details,
## e.g.:
##   dat <- vroom(...)
##   problems(dat)
fbData   <- read_csv("FB.csv", show_col_types = FALSE)
amznData <- read_csv("AMZN.csv", show_col_types = FALSE)

# ------------------------
# 1. Apple Candlestick Chart
# ------------------------
aaplData$Date <- as.Date(aaplData$Date)
aaplData <- aaplData %>%
  filter(!is.na(Open) & !is.na(Close) & !is.na(High) & !is.na(Low))

ggplot(aaplData, aes(x = Date)) +
  geom_segment(aes(y = Low, yend = High, xend = Date), color = "black") +
  geom_rect(aes(ymin = pmin(Open, Close),
                ymax = pmax(Open, Close),
                xmin = Date - 0.7,
                xmax = Date + 0.7,
                fill = Close > Open)) +
  scale_fill_manual(values = c("TRUE" = "green", "FALSE" = "red")) +
  labs(title = "Apple Candlestick Chart", x = "Date", y = "Price (USD)") +
  theme_minimal()

# ------------------------
# 2. Facebook Line Plot
# ------------------------
fbData$Date <- as.Date(fbData$Date)

ggplot(fbData, aes(x = Date, y = Close)) +
  geom_line(color = "blue") +
  labs(title = "Facebook Closing Price Over Time",
       x = "Date", y = "Closing Price (USD)") +
  theme_minimal()

# ------------------------
# 3. Amazon Histogram of Daily Returns
# ------------------------
amznData$Date <- as.Date(amznData$Date)
amznData <- amznData %>%
  arrange(Date) %>%
  mutate(Return = (Close / lag(Close)) - 1)

ggplot(amznData, aes(x = Return)) +
  geom_histogram(binwidth = 0.01, fill = "yellow", color = "black") +
  labs(title = "Amazon Histogram of Daily Returns",
       x = "Daily Return", y = "Frequency") +
  theme_minimal()
## Warning: Removed 1 row containing non-finite outside the scale range
## (`stat_bin()`).


Functions for Figure Drawing

#Comments for figure 1

# Load file

# Conversion of data type

# Subset startRow and endRow

# Filter out rows with missing values

# Calculate width for candlestick bars based on date

# Create candlestick chart with colored rectangles

# Comments for figure 2

# Load file

# Conversion

# rows between startRow and endRow

# Plot Close price over time as a blue line

# Comments for figure 2

# Load data file

# Conversion

# calculate daily returns based on Close price

# histogram of daily returns with yellow fill and black border

library(dplyr)
library(ggplot2)

# Function 1: Candlestick plot
# This function creates a candlestick chart for a stock based on OHLC data.
# Parameters:
#   filename - CSV file containing stock data
#   startRow - first row to include in plot
#   endRow   - last row to include in plot
drawFigure1 <- function(filename, startRow, endRow) {
  # Read file
  df <- read.csv(filename)
  
  # Convert the 'Date' column to Date class
  df$Date <- as.Date(df$Date)
  
  # Subset the dataframe to only include rows between startRow and endRow
  df <- df[startRow:endRow, ]
  
  # Remove missing values in key columns: Open, Close, High, Low
  df <- df %>%
    filter(!is.na(Open) & !is.na(Close) & !is.na(High) & !is.na(Low))
  
  # Calculate width of each candlestick based on median spacing of dates
  # Multiplying by 0.8 padding between bars
  width <- 0.8 * median(diff(as.numeric(df$Date)))
  
  # using ggplot2
  ggplot(df, aes(x = Date)) +
    # Draw vertical line from Low to High 
    geom_segment(aes(y = Low, yend = High, xend = Date), color = "black") +
    # Draw rectangles between Open and Close prices; fill color based on price increase/decrease
    geom_rect(aes(ymin = pmin(Open, Close),
                  ymax = pmax(Open, Close),
                  xmin = Date - width / 2,
                  xmax = Date + width / 2,
                  fill = Close > Open)) +
    # Define colors: green if Close > Open (price up), red if price down
    scale_fill_manual(values = c("TRUE" = "green", "FALSE" = "red")) +
    # Add titles and axis labels
    labs(title = paste("Candlestick Chart:", filename),
         x = "Date", y = "Price (USD)") +
    # Use minimal theme 
    theme_minimal()
}

# Function 2: Line plot of Close price over time
# This function plots the closing price of a stock as a line chart.
# Parameters:
#   filename - CSV file containing stock data
#   startRow - first row to include in plot
#   endRow   - last row to include in plot
drawFigure2 <- function(filename, startRow, endRow) {
  # Read CSV file 
  df <- read.csv(filename)
  
  # Convert 'Date' column to Date type
  df$Date <- as.Date(df$Date)
  
  # Subset rows as specified
  df <- df[startRow:endRow, ]
  
  # line plot of closing price over time with blue line
  ggplot(df, aes(x = Date, y = Close)) + 
    geom_line(color = "blue") +
    # Add title and axis labels
    labs(title = paste("Closing Price Over Time:", filename),
         x = "Date", y = "Closing Price (USD)") +
    # minimal theme
    theme_minimal()
}

# Function 3: Histogram of daily returns
# This function calculates daily returns from closing prices and plots their distribution.
# Parameters:
#   filename - CSV file containing stock data
#   startRow - first row to include in plot
#   endRow   - last row to include in plot
drawFigure3 <- function(filename, startRow, endRow) {
  # Load data
  df <- read.csv(filename)
  
  # Convert 'Date' column to Date class
  df$Date <- as.Date(df$Date)
  
  # Subset rows, arrange by date, calculate daily return as percentage change Close price
  df <- df[startRow:endRow, ] %>%
    arrange(Date) %>%
    mutate(Return = (Close / lag(Close)) - 1)
  
  # Plot histogram of daily returns with yellow bars and black borders
  ggplot(df, aes(x = Return)) +
    geom_histogram(binwidth = 0.01, fill = "yellow", color = "black") +
    # Add title and axis labels
    labs(title = paste("Histogram of Daily Returns:", filename),
         x = "Daily Return", y = "Frequency") +
    # Minimal theme 
    theme_minimal()
}
# Example 

drawFigure1("AAPL.csv", 10, 30)  # Apple candlestick chart

drawFigure2("FB.csv", 10, 30)    # Facebook closing price line plot

drawFigure3("AMZN.csv", 10, 30)  # Amazon daily returns histogram
## Warning: Removed 1 row containing non-finite outside the scale range
## (`stat_bin()`).


Extra Credit

Did you identify any patterns or relationships in stock price data?
Yes, several patterns were identified in the stock price data. Candlestick charts showed that stocks like AAPL experience more daily variation. Line plots revealed upward trends in companies like Facebook and Amazon, showing growth over time. Histogram analysis of daily returns showed that most price changes are small, suggesting a relationship for market shocks or news events. Mean prices were often higher than medians, right-skewed data due to unusually high prices. High trading volume frequently aligned with significant price changes, confirming variation in patterns.

Describe what you did and summarize any interesting results. Loaded and cleaned the data: I imported CSV files for AAPL, FB, AMZN, and check for no missing values. Converted Date column to proper date format and filtered the rows based on index range. Visualized the data with three types of plots: Candlestick charts: Helped observe daily price ranges for a stock, showing whether the stock price closed higher (green) or lower (red) than it opened. Line plots of closing prices: Used for Facebook, this showed an upward trend over time, indicating long-term growth. Histograms of daily returns: most stock returns were small, but large jumps/drops occurred; I assum outside sources or factors like news caused these changes. Calculated basic statistics: Using mean(), median(), and summary(), I saw that many stocks had means higher than medians, indicating right-skewed distributions. Observed volume vs. price behavior: trading volume matched with large prices, suggesting these may reflect reactions to market shifts.


Notes

Use this section to include any reflections, challenges, or ideas for future analysis. I could not get the standard deviation to work. According to statistical analysis this is important when analyzing data so I am super sad I could not get it to function at this time.