Initial commit of RTVS lab files from my repo

This commit is contained in:
John Lam 2017-05-03 08:41:26 -07:00
Родитель dc7af7adec
Коммит 925369cce1
13 изменённых файлов: 563 добавлений и 0 удалений

1
.gitignore поставляемый
Просмотреть файл

@ -245,3 +245,4 @@ _Pvt_Extensions
# JetBrains Rider
.idea/
*.sln.iml
*.RHistory

Двоичный файл не отображается.

Просмотреть файл

@ -0,0 +1,13 @@
Version: 1.0
RestoreWorkspace: Default
SaveWorkspace: Default
AlwaysSaveHistory: Default
EnableCodeIndexing: Yes
UseSpacesForTab: Yes
NumSpacesForTab: 2
Encoding: UTF-8
RnwWeave: Sweave
LaTeX: pdfLaTeX

Просмотреть файл

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<ProjectGuid>b518b26c-a1cf-42ce-9fe5-54c0b67d6898</ProjectGuid>
</PropertyGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
</PropertyGroup>
<PropertyGroup>
<StartupFile>script.R</StartupFile>
</PropertyGroup>
<ProjectExtensions>
<VisualStudio>
<UserProperties />
</VisualStudio>
</ProjectExtensions>
<Target Name="Build" />
<Import Project="$(MSBuildUserExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Rules\rtvs.rules.props" Condition="Exists('$(MSBuildUserExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Rules\rtvs.rules.props')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Rules\rtvs.rules.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Rules\rtvs.rules.props') And !Exists('$(MSBuildUserExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Rules\rtvs.rules.props')" />
<Import Project="$(MSBuildUserExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Targets\Microsoft.R.targets" Condition="Exists('$(MSBuildUserExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Targets\Microsoft.R.targets')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Targets\Microsoft.R.targets" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Targets\Microsoft.R.targets') And !Exists('$(MSBuildUserExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Targets\Microsoft.R.targets')" />
<Import Project="Solution.InMemory.Targets" Condition="Exists('Solution.InMemory.Targets')" />
</Project>

Просмотреть файл

@ -0,0 +1,88 @@
library(shiny)
library(quantmod)
library(highcharter)
library(rhandsontable)
starting.investment = 100000
start.date = "2017-01-01"
compute.portfolio.daily.book.value <- function(portfolio, dollars) {
portfolio <- cbind(portfolio, dollars = portfolio$percentage * dollars)
df <- NULL
compute.daily.book.value <- function(symbol, dollars) {
symbol.data <- getSymbols(
symbol,
auto.assign = FALSE,
from = start.date)
shares <- dollars / as.numeric(first(Op(symbol.data)))
book.value <- Ad(symbol.data) * shares
if (is.null(df)) {
df <<- data.frame(book.value)
}
else {
df <<- cbind(df, data.frame(book.value))
}
}
mapply(compute.daily.book.value, portfolio$symbols, portfolio$dollars)
# Compute totals for each day
return(cbind(df, data.frame(Total = rowSums(df))))
}
convert.totals.dataframe.to.xts <- function(df) {
return(xts(df$Total, as.POSIXct(rownames(df))))
}
function(input, output) {
v <- reactiveValues(portfolio = NULL, index = NULL)
observeEvent(input$go, {
if (is.null(input$hot)) return()
# Compute the value of the portfolio and the comparison
# portfolio (we do QQQ here)
portfolio = hot_to_r(input$hot)
v$portfolio <- compute.portfolio.daily.book.value(portfolio, starting.investment)
v$index <- compute.portfolio.daily.book.value(
data.frame(
symbols = c("QQQ"),
percentage = c(1.0),
stringsAsFactors = FALSE
),
starting.investment
)
print(v$index)
})
output$chart <- renderHighchart({
if (is.null(v$portfolio) || is.null(v$index)) return()
highchart(type = "stock") %>%
hc_add_series(convert.totals.dataframe.to.xts(v$portfolio), name = "Portfolio") %>%
hc_add_series(convert.totals.dataframe.to.xts(v$index), name = "QQQ") %>%
hc_add_theme(hc_theme_538())
})
output$hot <- renderRHandsontable({
if (!is.null(input$hot)) {
portfolio = hot_to_r(input$hot)
} else {
portfolio = data.frame(
symbols = c("FB", "AMZN", "NFLX", "GOOG"),
percentage = c(0.25, 0.25, 0.25, 0.25),
stringsAsFactors = FALSE)
}
rhandsontable(portfolio) %>%
hot_table(highlightCol = TRUE, highlightRow = TRUE)
})
}

Просмотреть файл

@ -0,0 +1,18 @@
library(shiny)
library(highcharter)
library(rhandsontable)
shinyUI(
fluidPage(
tags$link(rel = "stylesheet", type = "text/css", href = "https://bootswatch.com/paper/bootstrap.css"),
fluidRow(
column(width = 3, class = "panel",
actionButton("go", label = "Plot returns vs. QQQ"),
rHandsontableOutput("hot")
),
column(width = 9,
highchartOutput("chart", height = "700px")
)
)
)
)

Просмотреть файл

@ -0,0 +1,13 @@
# Dependencies
install_if_not_present <- function(name) {
if (!(name %in% rownames(installed.packages()))) {
install.packages(name)
}
}
install_if_not_present("shiny")
install_if_not_present("quantmod")
install_if_not_present("highcharter")
install_if_not_present("rhandsontable")

Просмотреть файл

@ -0,0 +1,153 @@
# Load the quantmod library, so that we gain access to its functions
library(quantmod)
# We are comparing our performance against QQQ
# which tracks the Nasdaq 100
start.date <- "2017-01-01"
QQQ <- getSymbols("QQQ", auto.assign = FALSE, from = start.date)
# View this in variable explorer
# Open table viewer
# Export to Excel
# Now lets plot QQQ for the YTD using the HighCharter package
library(highcharter)
highchart(type = "stock") %>%
hc_add_series(QQQ, type = "ohlc")
# Let's get another stock MSFT and plot that in a comparison chart
MSFT <- getSymbols("MSFT", auto.assign = FALSE, from = start.date)
highchart(type = "stock") %>%
hc_add_series(QQQ, type = "ohlc") %>%
hc_add_series(MSFT) %>%
hc_add_theme(hc_theme_538())
# Let's examine the data again in QQQ. You can see that it contains
# open, high, low, close, volume, and adjusted prices.
View(as.data.frame(QQQ))
# We really are only interested in the adjusted prices at close
# for the purposes of computing daily returns, which we can
# extract using the Ad() function
QQQ.adjusted <- Ad(QQQ)
# Let's view the first few rows of the xts result set. We can see
# that it contains both dates and the adjusted price for QQQ.
View(as.data.frame(QQQ.adjusted))
# Now let's compute returns by buying a certain number of shares of the stock
starting.investment = 100000
# Compute the number of shares we can buy by dividing starting investment by opening price
MSFT.starting.shares = starting.investment / as.numeric(first(Op(MSFT)))
QQQ.starting.shares = starting.investment / as.numeric(first(Op(QQQ)))
# Now compute the daily adjusted book value of our shares
# This is a vector * scalar which yields another vector
MSFT.daily.book.value = Ad(MSFT) * MSFT.starting.shares
QQQ.daily.book.value = Ad(QQQ) * QQQ.starting.shares
highchart(type = "stock") %>%
hc_add_series(QQQ.daily.book.value, name = "QQQ") %>%
hc_add_series(MSFT.daily.book.value, name = "MSFT") %>%
hc_add_theme(hc_theme_538())
# Now let's compute the book value based on the amount invested in a stock
compute.daily.book.value <- function(symbol, dollars) {
symbol.data <- getSymbols(symbol, auto.assign = FALSE, from = start.date)
shares <- dollars / first(Op(symbol.data))
return(Ad(symbol.data) * shares)
}
# Now, let's get the daily returns, expressed as a percentage
# gain or loss, based on the adjusted prices
QQQ.daily.book.value <- compute.daily.book.value("QQQ", starting.investment)
View(as.data.frame(QQQ.daily.book.value))
# Let's test it on TSLA
TSLA.daily.book.value <- compute.daily.book.value("TSLA", starting.investment)
View(TSLA.daily.book.value)
TSLA.cumulative.returns <- cumsum(TSLA.daily.returns * starting.investment)
head(TSLA.cumulative.returns)
# Now let's do the same thing for an equal weight portfolio of FANG
portfolio <- data.frame(
symbols = c("FB", "AMZN", "NFLX", "GOOG"),
percentage = c(0.25, 0.25, 0.25, 0.25),
stringsAsFactors = FALSE)
# We need to adjust our daily book value function to compute against portfolio of stocks
compute.portfolio.daily.book.value <- function(portfolio, dollars) {
portfolio <- cbind(portfolio, dollars = portfolio$percentage * dollars)
df <- NULL
compute.daily.book.value <- function(symbol, dollars) {
symbol.data <- getSymbols(
symbol,
auto.assign = FALSE,
from = start.date)
shares <- dollars / as.numeric(first(Op(symbol.data)))
book.value <- Ad(symbol.data) * shares
if (is.null(df)) {
df <<- data.frame(book.value)
}
else {
df <<- cbind(df, data.frame(book.value))
}
}
mapply(compute.daily.book.value, portfolio$symbols, portfolio$dollars)
# Compute totals for each day
df <- cbind(df, data.frame(Total = rowSums(df)))
return(df)
}
portfolio.daily.book.value <- compute.portfolio.daily.book.value(portfolio, starting.investment)
index <- data.frame(
symbols = c("QQQ"),
percentage = c(1.0),
stringsAsFactors = FALSE)
index.daily.book.value <- compute.portfolio.daily.book.value(index, starting.investment)
# Now let's plot the two curves against each other
# This loses the date labels - better to remove columns?
convert.totals.dataframe.to.xts <- function(df) {
return(xts(df$Total, as.POSIXct(rownames(df))))
}
highchart(type = "stock") %>%
hc_add_series(convert.totals.dataframe.to.xts(index.daily.book.value), name = "QQQ") %>%
hc_add_series(convert.totals.dataframe.to.xts(portfolio.daily.book.value), name = "Portfolio") %>%
hc_add_theme(hc_theme_538())
# Now the next step in this is to turn this analysis into an applicatoin
# where you can pick the stocks to add to your asset allocation and their
# proportions. The constraint is that they must add up to 100% in your allocation.
# Hit the compute button to generate the results.

Просмотреть файл

@ -0,0 +1,13 @@
Version: 1.0
RestoreWorkspace: Default
SaveWorkspace: Default
AlwaysSaveHistory: Default
EnableCodeIndexing: Yes
UseSpacesForTab: Yes
NumSpacesForTab: 2
Encoding: UTF-8
RnwWeave: Sweave
LaTeX: pdfLaTeX

Просмотреть файл

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<ProjectGuid>8f371ca3-e5aa-40d9-8e42-d962d271071f</ProjectGuid>
</PropertyGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
</PropertyGroup>
<PropertyGroup>
<StartupFile>script.R</StartupFile>
</PropertyGroup>
<ProjectExtensions>
<VisualStudio>
<UserProperties />
</VisualStudio>
</ProjectExtensions>
<Target Name="Build" />
<Import Project="$(MSBuildUserExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Rules\rtvs.rules.props" Condition="Exists('$(MSBuildUserExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Rules\rtvs.rules.props')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Rules\rtvs.rules.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Rules\rtvs.rules.props') And !Exists('$(MSBuildUserExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Rules\rtvs.rules.props')" />
<Import Project="$(MSBuildUserExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Targets\Microsoft.R.targets" Condition="Exists('$(MSBuildUserExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Targets\Microsoft.R.targets')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Targets\Microsoft.R.targets" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Targets\Microsoft.R.targets') And !Exists('$(MSBuildUserExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\RTVS\Targets\Microsoft.R.targets')" />
<Import Project="Starter.InMemory.Targets" Condition="Exists('Starter.InMemory.Targets')" />
</Project>

Просмотреть файл

@ -0,0 +1,13 @@
# Dependencies
install_if_not_present <- function(name) {
if (!(name %in% rownames(installed.packages()))) {
install.packages(name)
}
}
install_if_not_present("shiny")
install_if_not_present("quantmod")
install_if_not_present("highcharter")
install_if_not_present("rhandsontable")

Просмотреть файл

@ -0,0 +1,173 @@
# Load the quantmod library, so that we gain access to its functions
library(quantmod)
# We are comparing our performance against QQQ
# which tracks the Nasdaq 100 index. Run the lines of code
# below to get all the data from the beginning of the year.
start.date <- "2017-01-01"
QQQ <- getSymbols("QQQ", auto.assign = FALSE, from = start.date)
# View the contents of the data frame in variable explorer. Try:
#
# 1. Clicking on the chevron to the left of the QQQ variable to
# drill down into its internal structure.
#
# 2. Clicking on the hourglass icon to the right of the QQQ
# variable to open up the data in the Data Table viewer.
#
# 3. Clicking on the Excel icon to the right of the QQQ variable
# to open the data frame in Excel.
# Now lets plot QQQ for the YTD using the HighCharter package
# You should see a chart open up in the default browser, showing
# a plot of the Open, High, Low, and Close prices for each date.
library(highcharter)
# Notice the %>% operator. It's also known as the "pipe" operator
# which lets you chain together multiple function calls into a
# single statement.
highchart(type = "stock") %>%
hc_add_series(QQQ, type = "ohlc")
# Next, let's grab data for another stock, MSFT, and create a chart
# that compares the performance of MSFT vs. the QQQ S&P100 index.
MSFT <- getSymbols("MSFT", auto.assign = FALSE, from = start.date)
# Here, we generate a chart, showing both stocks head-to-head.
# However, because the stock prices are at different scales, it's
# hard to see a clear analysis of their performance.
highchart(type = "stock") %>%
hc_add_series(QQQ, type = "ohlc") %>%
hc_add_series(MSFT) %>%
hc_add_theme(hc_theme_538())
# Let's examine the data again in QQQ. You can see that it contains
# open, high, low, close, volume, and adjusted prices.
View(as.data.frame(QQQ))
# We really are only interested in the adjusted prices at close
# for the purposes of computing daily returns, which we can
# extract using the Ad() function
QQQ.adjusted <- Ad(QQQ)
# Let's view the first few rows of the xts result set. We can see
# that it contains both dates and the adjusted price for QQQ.
View(as.data.frame(QQQ.adjusted))
# Now let's compute returns by buying a certain number of shares of the stock
starting.investment = 100000
# Compute the number of shares we can buy by dividing starting investment by opening price
MSFT.starting.shares = starting.investment / as.numeric(first(Op(MSFT)))
QQQ.starting.shares = starting.investment / as.numeric(first(Op(QQQ)))
# Now compute the daily adjusted book value of our shares
# This is a vector * scalar which yields another vector
MSFT.daily.book.value = Ad(MSFT) * MSFT.starting.shares
QQQ.daily.book.value = Ad(QQQ) * QQQ.starting.shares
highchart(type = "stock") %>%
hc_add_series(QQQ.daily.book.value, name = "QQQ") %>%
hc_add_series(MSFT.daily.book.value, name = "MSFT") %>%
hc_add_theme(hc_theme_538())
# Now let's compute the book value based on the amount invested in a stock
compute.daily.book.value <- function(symbol, dollars) {
symbol.data <- getSymbols(symbol, auto.assign = FALSE, from = start.date)
shares <- dollars / first(Op(symbol.data))
return(Ad(symbol.data) * shares)
}
# Now, let's get the daily returns, expressed as a percentage
# gain or loss, based on the adjusted prices
QQQ.daily.book.value <- compute.daily.book.value("QQQ", starting.investment)
View(as.data.frame(QQQ.daily.book.value))
# Let's test it on TSLA
TSLA.daily.book.value <- compute.daily.book.value("TSLA", starting.investment)
View(TSLA.daily.book.value)
TSLA.cumulative.returns <- cumsum(TSLA.daily.returns * starting.investment)
head(TSLA.cumulative.returns)
# Now let's do the same thing for an equal weight portfolio of FANG
portfolio <- data.frame(
symbols = c("FB", "AMZN", "NFLX", "GOOG"),
percentage = c(0.25, 0.25, 0.25, 0.25),
stringsAsFactors = FALSE)
# We need to adjust our daily book value function to compute against portfolio of stocks
compute.portfolio.daily.book.value <- function(portfolio, dollars) {
portfolio <- cbind(portfolio, dollars = portfolio$percentage * dollars)
df <- NULL
compute.daily.book.value <- function(symbol, dollars) {
symbol.data <- getSymbols(
symbol,
auto.assign = FALSE,
from = start.date)
shares <- dollars / as.numeric(first(Op(symbol.data)))
book.value <- Ad(symbol.data) * shares
if (is.null(df)) {
df <<- data.frame(book.value)
}
else {
df <<- cbind(df, data.frame(book.value))
}
}
mapply(compute.daily.book.value, portfolio$symbols, portfolio$dollars)
# Compute totals for each day
df <- cbind(df, data.frame(Total = rowSums(df)))
return(df)
}
portfolio.daily.book.value <- compute.portfolio.daily.book.value(portfolio, starting.investment)
index <- data.frame(
symbols = c("QQQ"),
percentage = c(1.0),
stringsAsFactors = FALSE)
index.daily.book.value <- compute.portfolio.daily.book.value(index, starting.investment)
# Now let's plot the two curves against each other
# This loses the date labels - better to remove columns?
convert.totals.dataframe.to.xts <- function(df) {
return(xts(df$Total, as.POSIXct(rownames(df))))
}
highchart(type = "stock") %>%
hc_add_series(convert.totals.dataframe.to.xts(index.daily.book.value), name = "QQQ") %>%
hc_add_series(convert.totals.dataframe.to.xts(portfolio.daily.book.value), name = "Portfolio") %>%
hc_add_theme(hc_theme_538())
# Now the next step in this is to turn this analysis into an applicatoin
# where you can pick the stocks to add to your asset allocation and their
# proportions. The constraint is that they must add up to 100% in your allocation.
# Hit the compute button to generate the results.

Просмотреть файл

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26228.13
MinimumVisualStudioVersion = 10.0.40219.1
Project("{DA7A21FA-8162-4350-AD77-A8D1B671F3ED}") = "Starter", "Starter\Starter.rxproj", "{8F371CA3-E5AA-40D9-8E42-D962D271071F}"
EndProject
Project("{DA7A21FA-8162-4350-AD77-A8D1B671F3ED}") = "Solution", "Solution\Solution.rxproj", "{B518B26C-A1CF-42CE-9FE5-54C0B67D6898}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{8F371CA3-E5AA-40D9-8E42-D962D271071F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8F371CA3-E5AA-40D9-8E42-D962D271071F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8F371CA3-E5AA-40D9-8E42-D962D271071F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8F371CA3-E5AA-40D9-8E42-D962D271071F}.Release|Any CPU.Build.0 = Release|Any CPU
{B518B26C-A1CF-42CE-9FE5-54C0B67D6898}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B518B26C-A1CF-42CE-9FE5-54C0B67D6898}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B518B26C-A1CF-42CE-9FE5-54C0B67D6898}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B518B26C-A1CF-42CE-9FE5-54C0B67D6898}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal