Tutorial : R script using quantmod to analyze BTC-USD
Here is a complete, production-ready R script using quantmod to analyze BTC-USD.
This script covers the entire pipeline: ingestion, cleaning, technical indicator calculation, statistical analysis, and financial charting.
# ==============================================================================
# BTC-USD Quantitative Analysis Script using quantmod
# ==============================================================================
# 1. Load Required Libraries
# If not installed, run: install.packages(c("quantmod", "TTR", "PerformanceAnalytics"))
library(quantmod)
library(TTR)
library(PerformanceAnalytics)
# 2. Ingest Data (Yahoo Finance)
# auto.assign = FALSE prevents messing up your global environment
cat("Fetching BTC-USD historical data...\n")
btc_raw <- getSymbols("BTC-USD", src = "yahoo",
from = "2024-01-01",
to = Sys.Date(),
auto.assign = FALSE)
# Clean missing rows (crypto trades 24/7, but Yahoo occasionally has NA gaps)
btc <- na.omit(btc_raw)
# 3. Quick Data Inspection
print(head(btc))
cat("Data Frequency:", periodicity(btc)$scale, "\n")
# ==============================================================================
# 4. Feature Engineering & Column Extractions
# ==============================================================================
# Using quantmod wrappers to extract specific vectors safely
btc_close <- Cl(btc) # Closing price
btc_volume <- Vo(btc) # Volume
btc_ohlc <- OHLC(btc) # 4-column matrix (Open, High, Low, Close)
# Calculate Daily and Monthly Returns
btc_daily_ret <- dailyReturn(btc_close)
btc_monthly_ret <- monthlyReturn(btc_close)
# Create Lagged features (Useful for predicting tomorrow based on yesterday)
btc$Lag_Close_1 <- Lag(btc_close, k = 1)
btc$Lag_Vol_1 <- Lag(btc_volume, k = 1)
# ==============================================================================
# 5. Statistical Risk & Performance Metrics
# ==============================================================================
cat("\n--- Performance Metrics ---\n")
# Calculate annualized return and Sharpe ratio using PerformanceAnalytics
sharpe <- SharpeRatio.annualized(btc_daily_ret, Rf = 0.04/365) # assuming 4% risk-free rate
max_dd <- maxDrawdown(btc_daily_ret)
print(paste("Annualized Sharpe Ratio:", round(sharpe, 2)))
print(paste("Maximum Historical Drawdown:", round(max_dd * 100, 2), "%"))
# ==============================================================================
# 6. Advanced Charting Layouts (Quantmod Native)
# ==============================================================================
# Step A: Open a clean white-themed candlestick chart frame
chartSeries(btc,
type = "candlesticks",
theme = chartTheme("white"),
name = "BTC-USD Analysis Dashboard",
subset = "last 6 months") # Zoom into the last 6 months
# Step B: Layer Technical Indicators using the TTR wrapper system
addSMA(n = 50, col = "blue") # 50-day Simple Moving Average
addEMA(n = 200, col = "red") # 200-day Exponential Moving Average
addBBands(n = 20, sd = 2) # Bollinger Bands (Volatility)
addRSI(n = 14) # Relative Strength Index (Momentum)
addMACD() # Moving Average Convergence Divergence
What This Script Does:
Dynamic Dates: Automatically sets the end date to today (
Sys.Date()) and pulls fresh daily crypto data.Combats Look-Ahead Bias: Implements the
Lag()function, ensuring that any statistical models you build only use past data to predict future metrics.Professional Visuals: Rather than plotting standard lines,
chartSeries()builds a multi-pane financial dashboard detailing price actions, volumes, and overlays (like Bollinger Bands) automatically synced across the X-axis timeline.


Comments
Post a Comment