# Load required packages
#install.packages(c("quantmod", "xts", "lubridate"))
library(quantmod)
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(xts)
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
# Read data
etf56 <- read.table("tw0056_20070101_20191231(1).txt", header = TRUE)
etf56 <- etf56[c(3, 7)]
colnames(etf56) <- c("date", "price")

# Convert to xts object
etf56.xts <- xts(etf56$price, order.by = as.Date(as.character(etf56$date), format = "%Y%m%d"))
colnames(etf56.xts) <- 'price'

# Simple Moving Average (SMA) Calculation
md <- 50
sma <- SMA(etf56.xts, n = md)

# Generate Buy/Sell Signals based on SMA crossover
signals <- ifelse(etf56.xts > sma, 1, 0)  # 1 for buy, 0 for sell

# Plot the data and SMA
plot(etf56.xts, main = "TW56 ETF Prices", type = "l")  # Use type = "l" for a line plot

lines(sma, col = "red")

# Plot Buy/Sell Signals
points(index(etf56.xts), signals * max(etf56.xts), 
       col = ifelse(signals == 1, "green", "red"), pch = 19)