Learn R-QUANT-PACKAGES with Real Code Examples
Updated Nov 27, 2025
Code Sample Descriptions
1
Download Stock Data with quantmod
library(quantmod)
getSymbols('AAPL', src='yahoo', from='2024-01-01', to='2025-01-01')
chartSeries(AAPL, type='candlesticks', theme='white')
Use quantmod to download historical stock data and plot a candlestick chart.
2
Calculate Moving Averages with TTR
library(TTR)
data <- Cl(AAPL) # Closing prices
sma20 <- SMA(data, n=20)
sma50 <- SMA(data, n=50)
plot(data, main='AAPL Closing Price')
lines(sma20, col='blue')
lines(sma50, col='red')
Compute a 20-day simple moving average (SMA) and a 50-day SMA on stock closing prices.
3
Portfolio Performance with PerformanceAnalytics
library(PerformanceAnalytics)
returns <- na.omit(ROC(Cl(AAPL)))
charts.PerformanceSummary(returns, main='AAPL Performance Summary')
Calculate returns and visualize the cumulative returns of a portfolio.
4
Compute Exponential Moving Average (EMA)
ema12 <- EMA(Cl(AAPL), n=12)
ema26 <- EMA(Cl(AAPL), n=26)
plot(Cl(AAPL), main='AAPL EMA')
lines(ema12, col='blue')
lines(ema26, col='red')
Compute a 12-day and 26-day EMA for stock data.
5
Calculate Relative Strength Index (RSI)
rsi14 <- RSI(Cl(AAPL), n=14)
plot(rsi14, main='AAPL 14-day RSI')
abline(h=70, col='red', lty=2)
abline(h=30, col='green', lty=2)
Compute 14-day RSI to analyze momentum.
6
Bollinger Bands with TTR
bbands <- BBands(Cl(AAPL), n=20, sd=2)
plot(Cl(AAPL), main='AAPL with Bollinger Bands')
lines(bbands$up, col='red')
lines(bbands$dn, col='blue')
lines(bbands$mavg, col='green')
Add Bollinger Bands to stock price chart for volatility analysis.
7
Compute Daily Returns
returns <- dailyReturn(Cl(AAPL))
plot(returns, main='AAPL Daily Returns')
Compute daily percentage returns for a stock.
8
Sharpe Ratio of a Portfolio
portfolio_returns <- na.omit(ROC(Cl(AAPL)))
SharpeRatio.annualized(portfolio_returns, Rf=0.01/252)
Calculate the Sharpe Ratio using portfolio returns.
9
Correlation Between Stocks
getSymbols(c('AAPL','MSFT','GOOG'), src='yahoo', from='2024-01-01', to='2025-01-01')
prices <- na.omit(merge(Cl(AAPL), Cl(MSFT), Cl(GOOG)))
cor(prices)
Compute correlation matrix between multiple stocks.
10
Draw Candlestick Chart with Volume
chartSeries(AAPL, type='candlesticks', theme='white')
addVo()
Plot candlestick chart and overlay trading volume.