├── .DS_Store ├── .Rapp.history ├── .Rprofile ├── .gitattributes ├── .gitignore ├── 2016-06-25-hello-world!.Rmd ├── 2016-06-25-hello-world!.html ├── 2016-07-02-Publishing-documents-in-R.Rmd ├── 2016-07-02-Publishing-documents-in-R.html ├── 2016-07-05-Interactive-Plots-in-R.Rmd ├── 2016-07-09-unit-testing.Rmd ├── Data Analysis-Intro to wdcplot-mtcars Example.Rmd ├── Data Analysis-Statistics Tutorial.Rmd ├── EARL_Boston_2015.Rnw ├── HoExample4.Rnw ├── Jerzy Pawlowski RFinance 2015.Rmd ├── Jerzy_Pawlowski_RFinance_2017.html ├── Jerzy_Pawlowski_RFinance_2019.md ├── Jerzy_Pawlowski_RFinance_2019_old.md ├── Jerzy_Pawlowski_RFinance_slides_2019.html ├── Jerzy_Pawlowski_RFinance_slides_2019_draft.html ├── Jerzy_Pawlowski_Stevens_2019.Rmd ├── Jerzy_Pawlowski_Stevens_2019.html ├── Jerzy_Pawlowski_Stevens_abstract_2019.md ├── MTslides.css ├── My first shiny deprecate.Rmd ├── README template.md ├── README.md ├── RFinance_2015.Rnw ├── RFinance_2015_abstract.Rnw ├── RFinance_2016.Rnw ├── RFinance_2016_abstract.Rnw ├── RFinance_2016_final.R ├── RFinance_2016_final.Rnw ├── RFinance_2017.Rmd ├── RFinance_2017.html ├── RFinance_2017_abstract.Rmd ├── RFinance_2017_notes.txt ├── RFinance_2019.Rmd ├── RFinance_2020.Rmd ├── RFinance_2020_abstract.Rmd ├── RFinance_2022_abstract.Rmd ├── RFinance_Chicago_2022.Rnw ├── Sweave example.Rnw ├── ToDoList.txt ├── abstract.txt ├── animated_chi_squared ├── chi_squared1.png ├── chi_squared10.png ├── chi_squared11.png ├── chi_squared12.png ├── chi_squared13.png ├── chi_squared14.png ├── chi_squared15.png ├── chi_squared16.png ├── chi_squared17.png ├── chi_squared18.png ├── chi_squared19.png ├── chi_squared2.png ├── chi_squared3.png ├── chi_squared4.png ├── chi_squared5.png ├── chi_squared6.png ├── chi_squared7.png ├── chi_squared8.png └── chi_squared9.png ├── app_calc_weights.R ├── app_cdo_tranche.R ├── app_coint.R ├── app_credit_portfolio_loss.R ├── app_credit_portfolio_loss_bis.R ├── app_credit_portfolio_loss_mc_solution.R ├── app_dygraphs.R ├── app_dygraphs_ticks.R ├── app_efficient_frontier2.R ├── app_ema_plot.R ├── app_ema_plot2.R ├── app_ema_quantmod.Rmd ├── app_highcharts.R ├── app_highcharts_ticks.R ├── app_highchartsma.R ├── app_ornstein_uhlenbeck.Rmd ├── app_pair_returns copy 2.R ├── app_pair_returns copy.R ├── app_pair_stockETF.R ├── app_portfolio.R ├── app_range.R ├── app_reactive.R ├── app_simple.R ├── app_trifilter.R ├── app_wealth_distribution_hw.R ├── app_wealth_distribution_solution.R ├── backtest.png ├── bib_template.Rnw ├── change_output_HTML_file_size.html ├── cloud-computing.Rmd ├── cloud-computing.html ├── coinflipping.jpg ├── deprecated └── app_pairs_dynamicrb_depr.R ├── dygraphs_dashboard.Rmd ├── dygraphs_dashboard.html ├── dygraphs_plots.Rmd ├── dygraphs_pnls.Rmd ├── dygraphs_pnls1.Rmd ├── dygraphs_synchronization.Rmd ├── dygraphs_synchronization.html ├── ensemble.png ├── equation_examples.Rmd ├── figure ├── .DS_Store ├── CDO.jpg ├── CDO2.jpg ├── EMA.mov ├── EMA.mp4 ├── EMA_price_volatility.png ├── EMA_prices.png ├── EMA_return_volatility.png ├── Jeremy_Clarkson_Linus_Torvalds.jpg ├── MT_Logo.png ├── MT_robot.png ├── SMA_price_volatility.png ├── SMA_prices.png ├── SMA_return_volatility.png ├── backtest.png ├── bollinger_docs.png ├── bolllinger_zscores.png ├── confirm_trades.png ├── create_flow_variables.png ├── create_trade_tables_pairs.png ├── data_queue.png ├── data_queueo.png ├── download_trade_tables.png ├── ensemble.png ├── erase_trade_tables.png ├── get_price.png ├── initialize_flow_variables.png ├── initialize_parameters.png ├── initialize_prices.png ├── initialize_technical_indicators.png ├── intervals_rolling.png ├── liquidate_positions.png ├── long_short.png ├── mt_moving_average_price_volatility.png ├── mt_moving_average_price_volatilityo.png ├── pair_docs.png ├── pair_performance.png ├── pair_xlkqqq.png ├── pair_zscores.png ├── run_bollinger_strategy.png ├── run_pair_strategy.png ├── statarb_vti_svxy_vxx.png ├── statarb_xlb_dbc_xle.png ├── telegram_alert.png ├── trade_manually.png ├── trend_following.png ├── under_construction.gif └── update_technical_indicators.png ├── first └── app.R ├── generic_rpresentation.Rpres ├── generic_rpresentation.md ├── image ├── CC_License.png ├── CRAN_Package.png ├── CRAN_Package_old.png ├── CRAN_Views.png ├── GPLv3_Logo.png ├── MT2.png ├── MT4.png ├── MTLogo.png ├── MTLogoLarge.png ├── RStudio.png ├── RStudio_logo.png ├── Rlogo.jpg ├── Thumbs.db ├── chi_squared.gif ├── easy_button.png ├── engineering_long_color.png ├── engineering_long_white.png ├── npp.jpg ├── olimpiada.png ├── rstudio_debug.png ├── smile.png ├── smile_small.png ├── splitapply.png ├── stack_exchange2.png ├── tandon_long_color.png ├── tandon_stacked_color.png └── treasury_curve.gif ├── ioslides.css ├── ioslides_MachineTrader.Rmd ├── ioslides_MachineTrader.html ├── ioslides_MachineTrader_files └── figure-html │ └── normal_dist_css-1.png ├── ioslides_example.Rmd ├── ioslides_example.html ├── ioslides_example2.Rmd ├── ioslides_example2.html ├── ioslides_example_files └── figure-html │ └── normal_dist_css-1.png ├── ioslides_shiny_cdo_tranche.Rmd ├── ioslides_shiny_example.Rmd ├── ioslides_treasury_yield_curve.Rmd ├── ioslides_treasury_yield_curve.html ├── ioslides_two_column_tests.Rmd ├── ioslides_two_column_tests.html ├── kaggle_credit_card_model.Rmd ├── knitr_article_demo.Rnw ├── knitr_presentation_demo.Rnw ├── logfile.txt ├── long_short.png ├── markdown_simple.html ├── markdown_simple.md ├── markdown_tests.html ├── multiple_coin_flips.Rmd ├── multiple_coin_flips.html ├── my_first.html ├── olimpiada_matematyczna.Rmd ├── overlays.Rnw ├── rhtml.html ├── rmarkdown_example.Rmd ├── rmarkdown_example.html ├── rmarkdown_tests.Rmd ├── rmarkdown_to_html_example.Rmd ├── rmarkdown_to_html_example.html ├── rmarkdown_to_pdf_example.Rmd ├── rpresentation_simple.Rpres ├── rpresentation_simple.md ├── rpresentations.Rpres ├── rsconnect └── documents │ ├── app_simple.R │ └── shinyapps.io │ │ └── algoquant │ │ └── presentations.dcf │ └── dygraphs_dashboard.Rmd │ └── rpubs.com │ └── rpubs │ ├── Document.dcf │ └── Publish Document.dcf ├── select_manager.Rmd ├── select_manager.html ├── shiny ├── chart_series │ ├── server.R │ └── ui.R ├── normal_dist │ ├── server.R │ └── ui.R └── stockVis │ ├── helpers.R │ ├── server.R │ └── ui.R ├── shiny_demo_html.Rmd ├── shiny_ioslides.html ├── shiny_ioslides_cache └── html │ └── __packages ├── shiny_isolate_example.R ├── shiny_isolate_example_roll_portfolio.R ├── shinyapp_cdo_tranche ├── rsconnect │ └── shinyapps.io │ │ └── algoquant │ │ └── normal_dist.dcf ├── server.R └── ui.R ├── shinyapp_cdo_tranche_assignment ├── rsconnect │ └── shinyapps.io │ │ └── algoquant │ │ └── normal_dist.dcf ├── server.R └── ui.R ├── single_coin_flips.Rmd ├── single_coin_flips.html ├── slides.css ├── strat_autoreg.R ├── strat_autoreg_pca.R ├── strat_autoregfact.R ├── strat_bollinger.R ├── strat_bollinger_doubled_pairs.R ├── strat_bollinger_ladder.R ├── strat_bollinger_ladder2.R ├── strat_bollinger_ladderv.R ├── strat_bollinger_plus.R ├── strat_contrarian.R ├── strat_contrarian_scaled.R ├── strat_cppi.R ├── strat_crossover.R ├── strat_dual_crossover.R ├── strat_dual_crossover_hw.R ├── strat_dual_crossover_solution.R ├── strat_dualema.R ├── strat_ema2.Rmd ├── strat_ema_dual_poly.R ├── strat_ema_threshold.R ├── strat_ema_vol.R ├── strat_ema_volume.R ├── strat_ema_volume_scaled.R ├── strat_hampel_prices.R ├── strat_hampel_prices_eventReactive.R ├── strat_hampel_prices_volume.R ├── strat_hampel_prices_volume_old.R ├── strat_hampel_prices_volume_strat_reactiveValues.R ├── strat_hampel_reactive.R ├── strat_hampel_reactive_old.R ├── strat_hampel_returns.R ├── strat_hampel_simple.R ├── strat_hampel_stocks.R ├── strat_hfreq.R ├── strat_intraday_dualema.R ├── strat_intraday_ema.R ├── strat_kelly.R ├── strat_logistic_zscores.R ├── strat_macd_crossover.R ├── strat_market_making.R ├── strat_mean_revert.R ├── strat_mean_revert15.R ├── strat_mean_revert2.R ├── strat_mean_revert25.R ├── strat_momentum.Rmd ├── strat_momentum_07-19.Rmd ├── strat_ohlc.R ├── strat_pair_autoreg.R ├── strat_pair_dynamic.R ├── strat_pair_dynamicr.R ├── strat_pair_dynamicrb.R ├── strat_pair_dynamicro.R ├── strat_pair_dynamicrr.R ├── strat_pair_dynamicru.R ├── strat_pair_dynamicrus.R ├── strat_pair_fixed.R ├── strat_pair_runreg.R ├── strat_portf_mom_stocks.R ├── strat_portf_quantiles.R ├── strat_portf_static.R ├── strat_portf_static_copy.R ├── strat_portfolio_outofsample.R ├── strat_ratchet.R ├── strat_ratchet_intraday_ema.R ├── strat_ratchet_intraday_open.R ├── strat_ratchet_triple.R ├── strat_regime_switching.R ├── strat_regres_spy.Rmd ├── strat_returns_volume_scaled.R ├── strat_revert_intraday.R ├── strat_risk_parity.R ├── strat_roll_count2.R ├── strat_roll_portf.R ├── strat_roll_portf_Rcpp.R ├── strat_roll_portfolio.R ├── strat_roll_portfolio_RSpectra.R ├── strat_roll_portfolio_onlinePCA.R ├── strat_roll_portfolior.R ├── strat_roll_revert.R ├── strat_roll_trend_vol_scaled.R ├── strat_rsi.R ├── strat_run_pca_momentum.R ├── strat_run_pca_portf.R ├── strat_run_portf_Rcpp.R ├── strat_running_zscores_plot.R ├── strat_runreg_daily.R ├── strat_runreg_dailyo.R ├── strat_runreg_minutes.R ├── strat_sharpe_returns.R ├── strat_sharpe_returns_intraday.R ├── strat_statarb.R ├── strat_statarb_old.R ├── strat_statarb_stocks.R ├── strat_static_betas.Rmd ├── strat_static_betas2.Rmd ├── strat_stock_etf.Rmd ├── strat_stop_start.R ├── strat_tech_indicators.R ├── strat_trend_simple.R ├── strat_two_windows.R ├── strat_vol_long_short.R ├── strat_vol_long_short_fixed.R ├── strat_volvix.R ├── strat_volvix_add.R ├── strat_volvix_dual.R ├── strat_volvix_dual_copy.R ├── strat_volvix_dual_copy2.R ├── strat_volvix_old.R ├── strat_vwap.R ├── strat_vwap_plot.R ├── strat_zscore_daytime.R ├── strat_zscore_multiv.R ├── strat_zscore_plot.R ├── strat_zscore_prices.R ├── strat_zscore_prices2.R ├── strat_zscore_prices3.R ├── strat_zscore_returns.R ├── strat_zscore_returns_082021.R ├── strat_zscore_returns_minutes.R ├── strat_zscore_returns_old.R ├── strat_zscore_single.R ├── strat_zscore_single_running.R ├── syllabus_example.Rmd ├── temp.Rmd ├── temp.Rpres ├── temp.html ├── test_flexdashboard.Rmd ├── test_flexdashboard.html ├── test_fun.cpp ├── trend_following.png ├── xts_vignette.Rmd ├── yield_curve_plotly.Rmd └── yield_curve_plotly.html /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/.DS_Store -------------------------------------------------------------------------------- /.Rapp.history: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/.Rapp.history -------------------------------------------------------------------------------- /.Rprofile: -------------------------------------------------------------------------------- 1 | # ## Example of .Rprofile 2 | # options(width=65, digits=5) 3 | # options(show.signif.stars=FALSE) 4 | # setHook(packageEvent("grDevices", "onLoad"), 5 | # function(...) grDevices::ps.options(horizontal=FALSE)) 6 | # set.seed(1234) 7 | # .First <- function() cat("n Welcome to R!nn") 8 | # .Last <- function() cat("n Goodbye!nn") 9 | 10 | library(HighFreq) 11 | options(rgl.useNULL=TRUE) 12 | 13 | # Suppress spurious timezone warning message: "timezone of object is different than current timezone" 14 | options(xts_check_TZ=FALSE) 15 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | 3 | ############# 4 | ## Python 5 | ############# 6 | 7 | *.py[co] 8 | 9 | # Packages 10 | *.egg 11 | *.egg-info 12 | dist/ 13 | build/ 14 | eggs/ 15 | parts/ 16 | var/ 17 | sdist/ 18 | develop-eggs/ 19 | .installed.cfg 20 | 21 | # Installer logs 22 | pip-log.txt 23 | 24 | # Unit test / coverage reports 25 | .coverage 26 | .tox 27 | 28 | #Translations 29 | *.mo 30 | 31 | #Mr Developer 32 | .mr.developer.cfg 33 | 34 | # RStudio 35 | *.Rhistory 36 | *.RData 37 | 38 | # knitr, markdown and LaTEX files 39 | # figure/ 40 | shiny_ioslides_cache/ 41 | ioslides_example_cache/ 42 | ioslides_shiny_cache/ 43 | R_Markdown_to_ioslides_example_cache/ 44 | *.aux 45 | *.log 46 | *.nav 47 | *.out 48 | *.pdf 49 | *.snm 50 | *.sty 51 | *.synctex.gz 52 | *.tex 53 | *.toc 54 | *.vrb 55 | *.bbl 56 | *-blx.bib 57 | *.bbl.txt 58 | *.bcf 59 | *.run.xml 60 | *.csv 61 | *cache* 62 | RFinanceChicago2022/ 63 | -------------------------------------------------------------------------------- /2016-06-25-hello-world!.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: Hello World! 3 | date: 2016-06-25 12:00:00 4 | layout: post 5 | categories: websites 6 | output: html_document 7 | --- 8 | 9 | ### I finally took the time to set up my home page on GitHub 10 | 11 | Unfortunately it forced me to learn more about coding in *HTML*, *CSS*, *YAML*, and [*liquid*](https://shopify.github.io/liquid/){:target="_blank"} than I ever cared to know. Fortunately I discovered a decent amount of blogs and tutorials online to be able to set up the website without too much pain. 12 | 13 | 14 | ### Selecting *Jekyll* for generating the website 15 | 16 | There are many different website technologies for creating static websites. Since I chose to host my website on [GitHub](https://pages.github.com/){:target="_blank"} (where I already have a repository for other projects), I decided to explore website technologies used by other GitHub users. 17 | As it happens, GitHub has developed a website generator written in Ruby, called [*Jekyll*](https://jekyllrb.com/){:target="_blank"}, which has become very popular, so I chose to use *Jekyll* for building my website as well. 18 | 19 | 20 | ### Selecting a *Jekyll theme* 21 | 22 | A *Jekyll theme* is a set of *HTML* and *CSS* files that determine the appearance of a website, like fonts, colors, shading, and page layouts. A *Jekyll theme* can be adapted to create websites with the same appearance as the theme. 23 | I wanted to choose a visually attractive theme, but with additional features, like a sidebar containing icons and text, with links to my website pages and to other websites. I chose to adapt the 24 | Jekyll-Architect theme 25 | by 26 | Pietro Menna, 27 | and the 28 | Beautiful-Jekyll theme 29 | by 30 | Dean Attali. 31 | Here you can find more: [Jekyll themes](http://jekyll.tips/templates/){:target="_blank"}. 32 | I also added *Disqus* comments to my blog posts. 33 | 34 | 35 | ### You're welcome to adapt my website for your own needs 36 | 37 | You can download the website files using the buttons on the right sidebar. 38 | You can read about how to set up this website in the [README.md]({{ site.name | prepend: site.githuburl }}/blob/master/README.md){:target="_blank"} file. But be aware that this website isn't a static website theme, but rather it's a complete website, and its contents change over time. 39 | Please follow the same copyright rules as those for the original website themes that it's based on. 40 | 41 | 42 | ### Building websites using *R Markdown* and *knitr* 43 | 44 | I use *R* for all my work, so in the future I may also try building my websites using *R Markdown* and *knitr*. Here are some references about building websites using *R Markdown* and *knitr*: 45 | 46 | [Building websites using *R Markdown* and *knitr*](https://brendanrocks.com/blogging-with-rmarkdown-knitr-jekyll/){:target="_blank"} 47 | [Hacking *htmlwidgets* into website using *rmarkdown*](https://brendanrocks.com/htmlwidgets-knitr-jekyll/){:target="_blank"} 48 | [Hacking *htmlwidgets* into website using *Jekyll*](http://benjcunningham.org/2016/06/13/hacking-together-htmlwidgets-for-jekyll.html){:target="_blank"} 49 | -------------------------------------------------------------------------------- /Data Analysis-Intro to wdcplot-mtcars Example.Rmd: -------------------------------------------------------------------------------- 1 | # Intro to wdcplot; mtcars Example 2 | === 3 | *** 4 | When in edit mode, run the analysis using the "play" (arrow) button in the navigation bar. 5 | 6 | ## Let's load the popular mtcars dataset. It comes pre-bundled with R. 7 | ```{r} 8 | data(mtcars) 9 | ``` 10 | 11 | ## What does the data look like? 12 | ```{r} 13 | head(mtcars) 14 | ``` 15 | # Looks like mtcars is a data frame: 16 | ```{r} 17 | class(mtcars) 18 | ``` 19 | ## So the structure is ... 20 | 21 | ```{r} 22 | str(mtcars) 23 | ``` 24 | ## What are the total number of rows? 25 | ```{r} 26 | nrow(mtcars) 27 | ``` 28 | ## How do we access a column? 29 | ```{r} 30 | head(mtcars$mpg) 31 | ``` 32 | ## What's the type/class? 33 | ```{r} 34 | class(mtcars$mpg) 35 | 36 | ## OR 37 | head(mtcars[,1]) 38 | 39 | ## OR 40 | head(mtcars[, "mpg"]) 41 | ``` 42 | ## We don't want a numeric vector. We want a data.frame slice. 43 | 44 | ```{r} 45 | head(mtcars["mpg"]) 46 | ``` 47 | ## Did we do it right? What's the type/class? 48 | 49 | ```{r} 50 | class(mtcars["mpg"]) 51 | ``` 52 | ## How do I get more than one column? 53 | 54 | ```{r} 55 | head(mtcars[c("mpg","hp")]) 56 | ``` 57 | ## How do we know the row names? 58 | 59 | ```{r} 60 | row.names(mtcars) 61 | ``` 62 | ## How do we access a specific value? 63 | 64 | ```{r} 65 | mtcars["Mazda RX4", "cyl"] 66 | 67 | # OR 68 | mtcars[1,2] 69 | ``` 70 | ## How do I access a row? 71 | 72 | ```{r} 73 | mtcars["Mazda RX4", ] 74 | ``` 75 | ## Also the same as ... 76 | ```{r} 77 | mtcars[1, ] 78 | ``` 79 | ## Vehicles with automatic transmission? 80 | 81 | ```{r} 82 | head(mtcars[mtcars$am==0,]) 83 | ``` 84 | ## Mileage for automatic transmission vehicles? 85 | 86 | ```{r} 87 | mtcars[mtcars$am==0,]$mpg 88 | ``` 89 | ## Let's know our data better. 90 | 91 | ```{r} 92 | summary(mtcars) 93 | ``` 94 | ## We don't want to keep typing mtcars$... so we use attach: 95 | 96 | ```{r} 97 | attach(mtcars) 98 | ``` 99 | 100 | ## You can now directly refer mtcars$mpg as mpg. 101 | 102 | ```{r} 103 | identical(mtcars$mpg, mpg) 104 | ``` 105 | ## Let's summarize our data: 106 | 107 | ```{r} 108 | table(cyl) 109 | ``` 110 | ## Plotting is easy... 111 | 112 | ## bar plot 113 | ```{r} 114 | barplot(mpg) 115 | ``` 116 | ## OR a histogram 117 | ```{r} 118 | hist(mpg) 119 | 120 | ``` 121 | ## OR a boxplot 122 | ```{r} 123 | boxplot(mpg) 124 | ``` 125 | ## Looks like mpg are pretty low: 126 | 127 | ```{r} 128 | mean(mpg) 129 | ``` 130 | ## Mean of mileage for 4 cylinder cars: 131 | 132 | ```{r} 133 | mean(mpg[cyl==4]) 134 | ``` 135 | ## vs 8 cylinder cars: 136 | 137 | ```{r} 138 | mean(mpg[cyl==8]) 139 | ``` 140 | ## Is that because of a higher number of cylinders? 141 | 142 | ```{r} 143 | 144 | plot(cyl, mpg) 145 | 146 | ``` 147 | ## Let's fit a regression line: 148 | 149 | ```{r} 150 | lm(mpg~cyl+hp) 151 | 152 | 153 | ``` 154 | ## Pearson correlation, is that a good fit? 155 | 156 | ```{r} 157 | cor(mpg,cyl)^2 158 | cor(mpg, hp)^2 159 | ``` 160 | ## Let's plot based on number of cylinders 161 | 162 | ```{r} 163 | plot(hp,mpg,pch=19, col=cyl) 164 | # add a legend 165 | legend(250, 30, pch=19, col=c(4,6,8), legend=c("4 cylinders","6 cylinders","8 cylinders")) 166 | ``` 167 | ## Now we do the cool stuff: 168 | ```{r fig.width=11, fig.height=11, tidy=FALSE} 169 | require(rcloud.dcplot) 170 | wdcplot(mtcars, 171 | dimensions(..index.., mpg, wt, cyl), 172 | groups(mpgGroup = group(mpg, bin(2)), 173 | wtGroup = group(wt, group = bin(0.5)), 174 | cylinders = group(cyl)), 175 | charts(SWvL = bubble('Miles Per Gallon vs. Weight', 176 | dimension = ..index.., 177 | color = cyl, 178 | x = wt, 179 | y = mpg, 180 | r = ..selected.. * 3, 181 | label = NULL), 182 | cyl = pie("Cylinders",group = cylinders), 183 | PW = bar('Miles Per Gallon', group = mpgGroup, x.domain = c(10.4,33.9)), 184 | PL = bar('Weight', group = wtGroup, x.domain = c(1.5,5.5)) 185 | )) 186 | ``` 187 | ```{r} 188 | detach(mtcars) 189 | ``` 190 | -------------------------------------------------------------------------------- /Jerzy Pawlowski RFinance 2015.Rmd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/Jerzy Pawlowski RFinance 2015.Rmd -------------------------------------------------------------------------------- /Jerzy_Pawlowski_RFinance_2019.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Real-time Trading With Packages iBrokers2, Rcpp, and Interactive Brokers 3 | author: Jerzy Pawlowski, NYU Tandon School of Engineering 4 | date: "April 4, 2019" 5 | output: pdf_document 6 | --- 7 | 8 | ### Abstract 9 | 10 | We demonstrate how to perform fully automated, algorithmic trading in real-time with packages *iBrokers2*, *Rcpp*, and *Interactive Brokers*. Real-time trading means trading in a programmatic loop, in which continuous streaming market data is used to update a trading model, and the model outputs are used to place orders via the API. Real-time trading requires three components: acquisition of streaming market data and account data, trading model execution, and trade order management. 11 | The package *IBrokers2* contains *R* functions for executing real-time trading via the API of Interactive Brokers. *IBrokers2* is derived from package *IBrokers*, and is fully backward compatible with it. This means that all the *IBrokers* functions and variables are preserved exactly in *IBrokers2*, while some additional functions have been added. The additional functions in *IBrokers2* provide functionality for the three components required for real-time trading. They provide a *trade wrapper* environment for live data, and a programmatic *callback* loop for executing the trading model and for placing orders via the API. 12 | We provide examples of simple trading strategies and explain how they can be modified by users. 13 | -------------------------------------------------------------------------------- /Jerzy_Pawlowski_RFinance_2019_old.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Efficient Portfolio Optimization Under Large Skewness and Fat Tails 3 | author: Jerzy Pawlowski, NYU Tandon School of Engineering 4 | date: "January 27, 2019" 5 | output: pdf_document 6 | --- 7 | 8 | ### Abstract 9 | The large standard errors in the estimation of the mean of asset returns and their correlations produce large errors in their forecasts and in portfolio optimization. This is exacerbated by the large skewness and fat tails (kurtosis) of asset returns, which cause the mean estimator to be less efficient than the median. We study alternative estimators of the centrality and correlation using the median and the quantiles of asset returns, together with the Cornish-Fisher expansion. We study the bias-variance tradeoff associated with the length of the look-back interval used for estimation, using cross-validation (backtesting). 10 | -------------------------------------------------------------------------------- /Jerzy_Pawlowski_Stevens_abstract_2019.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Real-time Trading via Interactive Brokers with Package iBrokers2 3 | subtitle: Stevens Conference on High-Frequency Finance and Analytics 4 | author: Jerzy Pawlowski, NYU Tandon School of Engineering 5 | date: June 27, 2019 6 | address: Stevens Institute of Technology 7 | output: pdf_document 8 | --- 9 | 10 | ### Abstract 11 | 12 | We introduce the *R* package *iBrokers2*, for implementing real-time trading via the API of *Interactive Brokers*. The package *IBrokers2* provides the essential functionality needed for trading in real time. 13 | First, it contains functions for collecting live market data, and a *trade wrapper* environment for storing market data and portfolio state information. 14 | Second, it implements a programmatic *callback* loop for updating the trading model with live market data. 15 | Third, it contains functions for placing trade orders via the IB API. 16 | We provide on overview of the package *iBrokers2*. We also provide examples of how to implement simple trading strategies, and explain how they can be modified by users. 17 | -------------------------------------------------------------------------------- /MTslides.css: -------------------------------------------------------------------------------- 1 | 2 | 3 | /** define logo layout **/ 4 | 5 | /* define logo dimensions */ 6 | .gdbar img { 7 | width: 600px !important; 8 | height: 100px !important; 9 | } 10 | 11 | /* define logo position */ 12 | .gdbar { 13 | width: 650px !important; 14 | height: 120px !important; 15 | } 16 | 17 | /* define title slide background color */ 18 | .title-slide { 19 | background: rgb(255, 100, 10); 20 | } 21 | 22 | 23 | 24 | 25 | /* define code chunk format */ 26 | pre { 27 | width: 100%; /* 106%; */ 28 | left: 0; /* -60px; */ 29 | padding: 10px 15px 10px 15px; /* 10px 0 10px 60px; */ 30 | } 31 | 32 | /** define footer format **/ 33 | slides > slide:not(.nobackground):before { 34 | width: 300px; 35 | height: 50px; 36 | background-size: 300px 50px; 37 | } 38 | 39 | /** define two-column layouts **/ 40 | 41 | .column_left_50 { 42 | float: left; 43 | width: 45%; 44 | text-align: left; 45 | } 46 | 47 | .column_right_50 { 48 | float: right; 49 | width: 48%; 50 | text-align: left; 51 | } 52 | 53 | .column_left_40 { 54 | float: left; 55 | width: 40%; 56 | text-align: left; 57 | } 58 | 59 | .column_right_60 { 60 | float: right; 61 | width: 59%; 62 | text-align: left; 63 | } 64 | 65 | .column_left_60 { 66 | float: left; 67 | width: 60%; 68 | text-align: left; 69 | } 70 | 71 | .column_right_40 { 72 | float: right; 73 | width: 40%; 74 | text-align: left; 75 | } 76 | -------------------------------------------------------------------------------- /My first shiny deprecate.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "My first shiny" 3 | author: "Jerzy Pawlowski" 4 | date: "October 25, 2017" 5 | output: html_document 6 | runtime: shiny 7 | --- 8 | 9 | ```{r setup, include=FALSE} 10 | knitr::opts_chunk$set(echo = TRUE) 11 | library(shiny) 12 | library(quantmod) 13 | interval <- 31 14 | closep <- quantmod::Cl(rutils::env_etf$VTI) 15 | plot_theme <- chart_theme() 16 | plot_theme$col$line.col <- c("orange", "blue") 17 | ``` 18 | 19 | ## EWMA Prices 20 | 21 | This is a simple *R* Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see . 22 | 23 | ```{r, echo=FALSE} 24 | inputPanel( 25 | sliderInput("lambda", label="lambda:", 26 | min=0.01, max=0.2, value=0.1, step=0.01) 27 | ) # end inputPanel 28 | 29 | renderPlot({ 30 | # calculate EWMA prices 31 | lambda <- input$lambda 32 | weightv <- exp(-lambda*1:interval) 33 | weightv <- weightv/sum(weightv) 34 | ewmap <- filter(closep, filter=weightv, sides=1) 35 | ewmap[1:(interval-1)] <- ewmap[interval] 36 | ewmap <- xts(cbind(closep, ewmap), order.by=index(closep)) 37 | colnames(ewmap) <- c("VTI", "VTI EWMA") 38 | # plot EWMA prices 39 | chobj <- chart_Series(ewmap, theme=plot_theme, name="EWMA prices") 40 | plot(chobj) 41 | legend("top", legend=colnames(ewmap), 42 | inset=0.1, bg="white", lty=c(1, 1), lwd=c(2, 2), 43 | col=plot_theme$col$line.col, bty="n") 44 | }) # end renderPlot 45 | 46 | ``` 47 | -------------------------------------------------------------------------------- /README template.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/README template.md -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Presentations 2 | ======== 3 | ## R files for creating presentations (knitr, shiny, etc.) 4 | ======== 5 | Task list: 6 | - [ ] create a few simple Markdown documents 7 | - [ ] idea 1 8 | - [x] add Markdown to README file 9 | -------------------------------------------------------------------------------- /RFinance_2015_abstract.Rnw: -------------------------------------------------------------------------------- 1 | % Define knitr options 2 | % !Rnw weave=knitr 3 | % Set global chunk options 4 | <>= 5 | library(knitr) 6 | opts_chunk$set(prompt=TRUE, tidy=FALSE, strip.white=FALSE, comment=NA, highlight=FALSE, message=FALSE, warning=FALSE, size='scriptsize', fig.width=4, fig.height=4) 7 | options(width=60, dev='pdf') 8 | thm <- knit_theme$get("acid") 9 | knit_theme$set(thm) 10 | @ 11 | 12 | 13 | % Define document options 14 | \documentclass[10pt]{beamer} 15 | \mode 16 | \usetheme{Madrid} 17 | % \usecolortheme{whale} 18 | % Uncover everything in a step-wise fashion 19 | % \beamerdefaultoverlayspecification{<+->} 20 | % mathtools package for math symbols 21 | % \usepackage{mathtools} 22 | \usepackage[latin1]{inputenc} 23 | \usepackage{hyperref} 24 | \usepackage{fancybox} 25 | \usepackage{url} 26 | \usepackage[backend=bibtex,style=alphabetic]{biblatex} % bibstyle=numeric 27 | % \bibliographystyle{amsalpha} % doesn't work 28 | \addbibresource{FRE_lectures.bib} 29 | % \addbibresource[location=remote]{http://www.citeulike.org/user/jerzyp} 30 | \renewcommand\bibfont{\footnotesize} 31 | \renewcommand{\pgfuseimage}[1]{\scalebox{0.75}{\includegraphics{#1}}} % scale bib icons 32 | \setbeamertemplate{bibliography item}[text] % set bib icons 33 | % \setbeamertemplate{bibliography item}{} % remove bib icons 34 | 35 | % \usepackage{enumerate} 36 | % \let\emph\textbf 37 | % \let\alert\textbf 38 | % Define colors for hyperlinks 39 | \definecolor{links}{HTML}{2A1B81} 40 | \hypersetup{colorlinks=true,linkcolor=,urlcolor=links} 41 | % Make url text footnotesize 42 | \renewcommand\UrlFont{\footnotesize} 43 | % Make institute text italic and small 44 | \setbeamerfont{institute}{size=\small,shape=\itshape,bg=red,fg=red} 45 | \setbeamerfont{date}{size=\small} 46 | \setbeamerfont{block title}{size=\normalsize} % shape=\itshape 47 | \setbeamerfont{block body}{size=\footnotesize} 48 | 49 | 50 | % Title page setup 51 | \title[Are High Frequency Traders Prudent and Temperate?]{Are High Frequency Traders Prudent and Temperate?} 52 | \subtitle{R/Finance Chicago 2015} 53 | % \subject{Getting Started With R} 54 | \institute[NYU Polytechnic]{NYU Tandon School of Engineering} 55 | \titlegraphic{\includegraphics[scale=0.2]{image/tandon_long_color}} 56 | \author[Jerzy Pawlowski]{Jerzy Pawlowski \emph{\href{mailto:jp3900@nyu.edu}{jp3900@nyu.edu}}} 57 | % \email{jp3900@poly.edu} 58 | % \date{January 27, 2014} 59 | \date{\today} 60 | % \pgfdeclareimage[height=0.5cm]{university-logo}{engineering_long_white} 61 | % \logo{\pgfuseimage{engineering_long_white}} 62 | 63 | 64 | %%%%%%%%%%%%%%% 65 | \begin{document} 66 | 67 | 68 | %%%%%%%%%%%%%%% 69 | \maketitle 70 | 71 | 72 | 73 | %%%%%%%%%%%%%%% 74 | \section{Introduction} 75 | 76 | 77 | %%%%%%%%%%%%%%% 78 | \subsection{Abstract} 79 | \begin{frame}[fragile,t]{\subsecname} 80 | \vspace{-1em} 81 | \begin{block}{} 82 | Risk averse investors are known to prefer assets with return distributions characterized by large positive \emph{means} (first moment) and small \emph{variance} (second moment), i.e. large \emph{Sharpe} ratios. 83 | \vskip1ex 84 | Studies indicate that investors also have preferences for higher \emph{moments} - they prefer large positive odd moments and small even moments. 85 | \vskip1ex 86 | \emph{Prudence} refers to the preference for large positive \emph{skewness} (third moment), while \emph{temperance} refers to the preference for small \emph{kurtosis} (fourth moment). 87 | \vskip1ex 88 | We estimate \emph{skewness} and \emph{kurtosis} from high frequency data, under microstructure noise. 89 | \vskip1ex 90 | We then study the relationship between higher \emph{moments} and future asset returns. 91 | \vskip1ex 92 | We finally explore the implications of risk preferences for higher \emph{moments} on asset allocation strategies. 93 | \end{block} 94 | 95 | \end{frame} 96 | 97 | 98 | \end{document} 99 | -------------------------------------------------------------------------------- /RFinance_2016_abstract.Rnw: -------------------------------------------------------------------------------- 1 | % Define knitr options 2 | % !Rnw weave=knitr 3 | % Set global chunk options 4 | <>= 5 | library(knitr) 6 | opts_chunk$set(prompt=TRUE, tidy=FALSE, strip.white=FALSE, comment=NA, highlight=FALSE, message=FALSE, warning=FALSE, size='scriptsize', fig.width=4, fig.height=4) 7 | options(width=60, dev='pdf') 8 | thm <- knit_theme$get("acid") 9 | knit_theme$set(thm) 10 | @ 11 | 12 | 13 | % Define document options 14 | \documentclass[10pt]{beamer} 15 | \mode 16 | \usetheme{Madrid} 17 | % \usecolortheme{whale} 18 | % Uncover everything in a step-wise fashion 19 | % \beamerdefaultoverlayspecification{<+->} 20 | % mathtools package for math symbols 21 | % \usepackage{mathtools} 22 | \usepackage[latin1]{inputenc} 23 | \usepackage{hyperref} 24 | \usepackage{fancybox} 25 | \usepackage{url} 26 | \usepackage[backend=bibtex,style=alphabetic]{biblatex} % bibstyle=numeric 27 | % \bibliographystyle{amsalpha} % doesn't work 28 | \addbibresource{FRE_lectures.bib} 29 | % \addbibresource[location=remote]{http://www.citeulike.org/user/jerzyp} 30 | \renewcommand\bibfont{\footnotesize} 31 | \renewcommand{\pgfuseimage}[1]{\scalebox{0.75}{\includegraphics{#1}}} % scale bib icons 32 | \setbeamertemplate{bibliography item}[text] % set bib icons 33 | % \setbeamertemplate{bibliography item}{} % remove bib icons 34 | 35 | % \usepackage{enumerate} 36 | % \let\emph\textbf 37 | % \let\alert\textbf 38 | % Define colors for hyperlinks 39 | \definecolor{links}{HTML}{2A1B81} 40 | \hypersetup{colorlinks=true,linkcolor=,urlcolor=links} 41 | % Make url text footnotesize 42 | \renewcommand\UrlFont{\footnotesize} 43 | % Make institute text italic and small 44 | \setbeamerfont{institute}{size=\small,shape=\itshape,bg=red,fg=red} 45 | \setbeamerfont{date}{size=\small} 46 | \setbeamerfont{block title}{size=\normalsize} % shape=\itshape 47 | \setbeamerfont{block body}{size=\footnotesize} 48 | 49 | 50 | % Title page setup 51 | \title[Exloring Higher Order Risk Premia Using High Frequency Data]{Exloring Higher Order Risk Premia Using High Frequency Data} 52 | \subtitle{R/Finance Chicago 2016} 53 | % \subject{Getting Started With R} 54 | \institute[NYU Tandon]{NYU Tandon School of Engineering} 55 | \titlegraphic{\includegraphics[scale=0.2]{image/tandon_long_color}} 56 | \author[Jerzy Pawlowski]{Jerzy Pawlowski \emph{\href{mailto:jp3900@nyu.edu}{jp3900@nyu.edu}}} 57 | % \email{jp3900@nyu.edu} 58 | % \date{January 27, 2014} 59 | \date{\today} 60 | % \pgfdeclareimage[height=0.5cm]{university-logo}{engineering_long_white} 61 | % \logo{\pgfuseimage{engineering_long_white}} 62 | 63 | 64 | %%%%%%%%%%%%%%% 65 | \begin{document} 66 | 67 | 68 | %%%%%%%%%%%%%%% 69 | \maketitle 70 | 71 | 72 | 73 | %%%%%%%%%%%%%%% 74 | \section{Introduction} 75 | 76 | 77 | %%%%%%%%%%%%%%% 78 | \subsection{Abstract} 79 | \begin{frame}[fragile,t]{\subsecname} 80 | \vspace{-1em} 81 | \begin{block}{} 82 | Recent academic research is suggesting the existence of risk premia associated with higher \emph{moments} of the return distribution. 83 | \vskip1ex 84 | For example \emph{skewness} (third moment) is believed to predict lower future returns. 85 | \vskip1ex 86 | This may be caused by investor demand for assets with positive skewness (lottery tickets), which reduces their future returns. 87 | \vskip1ex 88 | We explore this phenomenon using \emph{high frequency data}, since it allows for more accurate and timely estimation of higher order moments (bias-variance tradeoff). 89 | \vskip1ex 90 | Furthermore, we also explore the interaction between skewness and the \emph{momentum} factor, since some recent research is suggesting that momentum returns are enhanced by skewness. 91 | \vskip1ex 92 | But using high frequency data can present a challenge, since the data size may cause \texttt{R} programs to run very slowly. 93 | \vskip1ex 94 | We demonstrate how to perform the analysis using vectorized \texttt{R} code designed for \emph{speed}. 95 | \vskip1ex 96 | We present our results using \emph{interactive visualizations} afforded by new \texttt{R} packages. 97 | \end{block} 98 | 99 | \end{frame} 100 | 101 | 102 | \end{document} 103 | -------------------------------------------------------------------------------- /RFinance_2017_abstract.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "How Can Machines Learn to Trade?" 3 | author: Jerzy Pawlowski, NYU Tandon School of Engineering 4 | date: February 25, 2017 5 | output: pdf_document 6 | --- 7 | 8 | ## Abstract 9 | 10 | Machine learning has been successfuly applied to speech and image recognition, but has faced challenges in automated trading. For example forecasting models which rely on historical prices have very poor performance, because asset returns have a very low signal to noise ratio. As a result, model forecasts have large standard errors, making them difficult to apply in practice. The problem is often exacerbated by the high dimensionality of many financial models, for example portfolio optimization. 11 | 12 | We study several techniques which can help to reduce the problem of large standard errors, such as parameter regularization (shrinkage), dimensionality reduction, and ensembles of models. We use bootstrap simulation to estimate the standard errors, and to quantify the effect of these techniques. 13 | -------------------------------------------------------------------------------- /RFinance_2020_abstract.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: Nonparametric Estimators as Machine Learning Features 3 | author: Jerzy Pawlowski, NYU Tandon School of Engineering 4 | date: June 5, 2020 5 | output: pdf_document 6 | --- 7 | 8 | ## Abstract 9 | 10 | The large standard errors in the estimation of mean asset returns and their correlations produce large errors in portfolio optimization and machine learning models. This is exacerbated by the large fat tails (leptokurtosis) of asset returns, especially for the highly leptokurtic high frequency returns. For highly leptokurtic distributions, nonparametric estimators have lower standard errors than traditional moment estimators. For example, the sample median has a smaller standard error than the sample mean. But the median estimator is biased for skewed distributions. We are thus faced with the bias-variance tradeoff. 11 | 12 | We introduce nonparametric estimators of the location, dispersion, and skewness, by expressing them as weighted sums of the median and higher quantiles of asset returns. This is analogous to the Cornish–Fisher expansion. The weights are chosen to reduce the estimator bias while still maintaining low variance, to achieve the best bias-variance tradeoff. 13 | 14 | We apply the nonparametric estimators to portfolio optimization and demonstrate better out-of-sample performance. We implement the cross-validation simulations using an R package written in RcppArmadillo. 15 | 16 | 17 | -------------------------------------------------------------------------------- /RFinance_2022_abstract.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: Package *backpack* for Fast Backtest Simulations of Trading Strategies 3 | author: Jerzy Pawlowski, NYU Tandon School of Engineering 4 | date: June 3, 2022 5 | output: pdf_document 6 | --- 7 | 8 | ## Abstract 9 | 10 | We introduce the **R** package **backpack**, for fast backtest simulations of trading strategies. The package **backpack** uses the Armadillo **C++** library and the **R** package RcppArmadillo, to accelerate its performance. Armadillo is a high level **C++** library designed for machine learning and linear algebra, with expressive syntax similar to **Matlab**. The enhanced speed allows performing path-dependent simulations with state variables, and rolling portfolio optimizations. The features of package **backpack** are demonstrated on examples using shiny web apps. 11 | 12 | -------------------------------------------------------------------------------- /Sweave example.Rnw: -------------------------------------------------------------------------------- 1 | \documentclass{article} 2 | 3 | \begin{document} 4 | 5 | This document is a very simple example of a Sweave document (.Rnw) 6 | 7 | Here are some equations:\\ 8 | This is an in-line fraction: $\frac{2}{3}$. 9 | 10 | \vspace{5em} 11 | 12 | This is an in-line formula: $\hat{\lambda}=1.02$.\\ 13 | And another formula: $\sqrt{4}=2$. 14 | 15 | \vspace{5em} 16 | 17 | The binomial probability: $$f(y|N,p) = \frac{N!}{y!(N-y)!}\cdot p^y \cdot (1-p)^{N-y} = {{N}\choose{y}} \cdot p^y \cdot (1-p)^{N-y}$$ 18 | 19 | 20 | \end{document} 21 | -------------------------------------------------------------------------------- /ToDoList.txt: -------------------------------------------------------------------------------- 1 | ############ 2 | # ToDo list for R presentations 3 | 4 | ### R/Finance 2016 tasks 5 | 6 | - [ ] regress current returns on skew 7 | 8 | - [ ] regress future returns on skew 9 | 10 | - [ ] regression of returns versus skews 11 | divide time series into periods of high and low liquidity, and study if momentum or skew have more forecasting power. 12 | study effect of changing the rolling window size. 13 | 14 | - [ ] remove earl_vwap_scatter? 15 | 16 | - [x] perform daily and 10-minute aggregations of vol, skew, and hurst 17 | 18 | - [x] how do volatility, volume, illiquidity, skew, and hurst change intraday (intraday seasonality)? 19 | 20 | - [x] is market illiquidity a proxy for volatility? 21 | 22 | - [x] does market illiquidity create trading opportunities? 23 | use intra-day data 24 | divide time series into periods of high and low liquidity, and study if momentum or skew have more forecasting power. 25 | do periods of high skew coincide with high present or future returns? 26 | 27 | - [x] regression of Hurst (autocorrelation) versus volatility 28 | 29 | - [x] add slides: 30 | explain Hurst exponent 31 | daily seasonality of Hurst exponent 32 | regress daily volume versus volatility 33 | show that volatility and volume are proportional, so illiquidity index is just proportional to square root of volatility 34 | 35 | - [x] slide High Frequency OHLC Data: 36 | OHLC data offers data compression 37 | packages xts and quantmod 38 | change code to lazy load 39 | 40 | - [x] slide Estimating Skew From OHLC Data: 41 | rename to Estimating Skew From OHLC Data 42 | emph skew-like 43 | 44 | - [ ] slide Daily Volatility and Skew From OHLC Data: 45 | remove colnames() 46 | explain skew_ohlc() 47 | 48 | - [ ] prove analytically that function skew_ohlc() is a skew estimator 49 | 50 | - [ ] investigate relationship between skew and ohlc skew 51 | create matrix of synthetic time series with varying levels of skew. 52 | use Poisson distribution? 53 | aggregate the synthetic data to OHLC. 54 | show that the output from function skew_ohlc() is proportional to the skew estimator. 55 | 56 | - [ ] add qmao functions: 57 | gaa() for "get, apply, assign" 58 | gsa() stands for "get, subset, assign". 59 | To, get data for some tickers, subset the data, and then assign into an environment 60 | http://stackoverflow.com/questions/15980985/get-xts-objects-from-within-an-environment?rq=1 61 | 62 | -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared1.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared10.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared11.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared11.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared12.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared12.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared13.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared13.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared14.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared14.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared15.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared15.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared16.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared17.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared17.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared18.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared18.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared19.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared19.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared2.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared3.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared4.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared5.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared6.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared7.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared8.png -------------------------------------------------------------------------------- /animated_chi_squared/chi_squared9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/animated_chi_squared/chi_squared9.png -------------------------------------------------------------------------------- /app_calc_weights.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app for visualizing calc_weights 3 | # 4 | # Just press the "Run App" button on upper right of this panel. 5 | ############################## 6 | 7 | ## Below is the setup code that runs once when the shiny app is started 8 | 9 | # load packages 10 | library(HighFreq) 11 | library(shiny) 12 | library(dygraphs) 13 | # Rcpp::sourceCpp(file="/Users/jerzy/Develop/lecture_slides/assignments/rcpp_strat.cpp") 14 | # Model and data setup 15 | # dimax <- 2 16 | load("/Users/jerzy/Develop/lecture_slides/data/sp500_returns.RData") 17 | # retv <- returns100 18 | retv <- retv[, !is.na(retv[NROW(retv), ])] 19 | retv <- retv[, !is.na(retv[NROW(retv)-1000, ])] 20 | retv <- na.omit(retv) 21 | nweights <- NCOL(retv) 22 | # riskf <- 0.03/260 23 | # excess <- (retv - riskf) 24 | # calculate returns on equal weight portfolio 25 | # indeks <- xts(cumsum(retv %*% rep(1/sqrt(nweights), nweights)), index(retv)) 26 | 27 | 28 | # End setup code 29 | 30 | 31 | ## Create elements of the user interface 32 | uifun <- shiny::fluidPage( 33 | titlePanel("Visualize Weights for S&P500 Portfolio"), 34 | 35 | # create single row with two slider inputs 36 | fluidRow( 37 | # Input number of eigenvalues for regularized matrix inverse 38 | column(width=4, numericInput("dimax", "Number of eigenvalues:", value=5)), 39 | # Input end points interval 40 | # column(width=4, selectInput("interval", label="End points Interval", 41 | # choices=c("weeks", "months", "years"), selected="months")), 42 | # Input look-back interval 43 | # column(width=4, sliderInput("lookb", label="Lookback interval:", 44 | # min=1, max=30, value=12, step=1)), 45 | # Input end_stub interval 46 | # column(width=4, sliderInput("end_stub", label="End_stub interval:", 47 | # min=1, max=90, value=30, step=1)), 48 | # Input the shrinkage intensity 49 | # column(width=4, sliderInput("alpha", label="Shrinkage intensity:", 50 | # min=0.01, max=0.99, value=0.1, step=0.05)) 51 | ), # end fluidRow 52 | 53 | # create output plot panel 54 | plotOutput("plotobj") 55 | ) # end fluidPage interface 56 | 57 | 58 | ## Define the server code 59 | servfun <- function(input, output) { 60 | 61 | # Recalculate the data and rerun the model 62 | weightv <- shiny::reactive({ 63 | # get model parameters from input argument 64 | # interval <- input$interval 65 | dimax <- input$dimax 66 | # lookb <- input$lookb 67 | # end_stub <- input$end_stub 68 | # alpha <- input$alpha 69 | 70 | # Define end points 71 | # endp <- rutils::calc_endpoints(retv, interval=interval) 72 | # endp <- ifelse(endp<(nweights+1), nweights+1, endp) 73 | # endp <- endp[endp > (nweights+1)] 74 | # nrows <- NROW(endp) 75 | # Define startp 76 | # startp <- c(rep_len(1, lookb-1), endp[1:(nrows-lookb+1)]) 77 | # rerun the model 78 | weightv <- HighFreq::calc_weights(retv, dimax=dimax); 79 | 80 | # pnls <- roll_portf_n(excess=retv, 81 | # returns=retv, 82 | # startp=startp-1, 83 | # endp=endp-1, 84 | # dimax=dimax, 85 | # alpha=alpha, 86 | # min_var=FALSE) 87 | # pnls[which(is.na(pnls)), ] <- 0 88 | # pnls <- sd(rutils::diffit(indeks))*pnls/sd(rutils::diffit(pnls)) 89 | # pnls <- cumsum(pnls) 90 | # pnls <- cbind(pnls, indeks) 91 | # colnames(pnls) <- c("Strategy", "Index") 92 | # pnls[c(1, endp), ] 93 | sort(weightv) 94 | }) # end reactive code 95 | 96 | # return to output argument a dygraph plot with two y-axes 97 | output$plotobj <- shiny::renderPlot({ 98 | plot(weightv()) 99 | }) # end renderPlot 100 | 101 | } # end server code 102 | 103 | ## Return a Shiny app object 104 | shiny::shinyApp(ui=uifun, server=servfun) 105 | -------------------------------------------------------------------------------- /app_dygraphs.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | library(dygraphs) 3 | library(datasets) 4 | 5 | 6 | # Define the UI 7 | ui <- shiny::shinyUI(fluidPage( 8 | 9 | titlePanel("Predicted Deaths from Lung Disease (UK)"), 10 | 11 | sidebarLayout( 12 | sidebarPanel( 13 | numericInput("months", label = "Months to Predict", 14 | value = 72, min = 12, max = 144, step = 12), 15 | selectInput("interval", label = "Prediction Interval", 16 | choices = c("0.80", "0.90", "0.95", "0.99"), 17 | selected = "0.95"), 18 | checkboxInput("showgrid", label = "Show Grid", value = TRUE) 19 | ), 20 | mainPanel( 21 | dygraphs::dygraphOutput("dygraph") 22 | ) 23 | ) 24 | )) 25 | 26 | 27 | # Define the server code 28 | server <- shiny::shinyServer(function(input, output) { 29 | 30 | predicted <- shiny::reactive({ 31 | hw <- HoltWinters(ldeaths) 32 | predict(hw, n.ahead = input$months, 33 | prediction.interval = TRUE, 34 | level = as.numeric(input$interval)) 35 | }) 36 | 37 | output$dygraph <- dygraphs::renderDygraph({ 38 | dygraph(predicted(), main = "Predicted Deaths/Month") %>% 39 | dySeries(c("lwr", "fit", "upr"), label = "Deaths") %>% 40 | dyOptions(drawGrid = input$showgrid) 41 | }) 42 | 43 | }) 44 | 45 | # Return a Shiny app object 46 | shiny::shinyApp(ui = ui, server = server) 47 | -------------------------------------------------------------------------------- /app_dygraphs_ticks.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app for a Dygraph plot of SPY tick prices. 3 | # Just press the "Run App" button on the upper right of RStudio. 4 | # Or run the app in MacBook terminal: 5 | # Rscript -e "shiny::runApp("Users/jerzy/Develop/Presentations/app_dygraphs_ticks.R", port=7775)" 6 | # On mini6 run: 7 | # Rscript -e "shiny::runApp("Users/jerzy/Develop/R/app_dygraphs_ticks.R", host="0.0.0.0", port=7775)" 8 | # And in browser load the page: http://206.72.197.242:7775 9 | ############################## 10 | 11 | 12 | ## Below is the setup code that runs once when the shiny app is started 13 | 14 | # Load packages 15 | library(quantmod) 16 | library(shiny) 17 | library(shinythemes) 18 | # library(highcharter) 19 | 20 | ## Load SPY ticks 21 | 22 | load(file="/Users/jerzy/Develop/data/spy_ticks.RData") 23 | # load(file="/Users/danielsavage/Public/dans_public/spyticks.RData") 24 | 25 | maxsize <- quantile(spyticks$size, 0.99) 26 | maxsizem <- median(spyticks$size) 27 | 28 | # Setup end 29 | 30 | ## Create elements of the user interface 31 | uifun <- shiny::fluidPage( 32 | theme=shinythemes::shinytheme("paper"), 33 | 34 | # Title 35 | h3("Dygraph Plot of SPY Tick Prices"), 36 | 37 | # Widgets 38 | fluidRow( 39 | # Input minimum trade size 40 | column(width=2, sliderInput("minsize", label="Minimum trade size:", 41 | min=1, max=maxsizem, value=1, step=1)), 42 | # Input maximum trade size 43 | column(width=2, sliderInput("maxsize", label="Maximum trade size:", 44 | min=100, max=maxsize, value=(maxsize %/% 2), step=1)) 45 | # # Input stock symbol 46 | # column(width=2, selectInput("symbol", label="Symbol:", choices=symbolv, selected=symbol)), 47 | # # Input time span 48 | # column(width=2, selectInput("tspan", label="Time span:", choices=c("day", "minute"), selected="day")), 49 | # # Input the look-back interval 50 | # column(width=2, numericInput("minsize", label="Look-back days:", value=1000, step=1)) 51 | ), # end fluidRow 52 | 53 | # Output plot panel 54 | dygraphs::dygraphOutput("dyplot", width="90%", height="550px") 55 | # highchartOutput("hchart", width="80%", height="600px") 56 | 57 | ) # end fluidPage interface 58 | 59 | ## Define the server function 60 | servfun <- function(input, output) { 61 | 62 | # Recalculate the prices 63 | pricev <- shiny::reactive({ 64 | cat("Calculating prices \n") 65 | # Get model parameters from input argument 66 | minsize <- input$minsize 67 | maxsize <- input$maxsize 68 | 69 | pricev <- spyticks 70 | # Remove prices with very small size 71 | pricev <- prices[(pricev$size >= minsize), ] 72 | # Remove prices with very large size 73 | pricev <- prices[(pricev$size <= maxsize), ] 74 | 75 | pricev 76 | 77 | }) # end reactive code 78 | 79 | 80 | # Return the Dygraph plot to output argument 81 | output$dyplot <- dygraphs::renderDygraph({ 82 | 83 | # Copy shiny parameters 84 | # tspan <- input$tspan 85 | # minsize <- input$minsize 86 | 87 | # Set minsize to 30 days if time span = minute 88 | # if (tspan == "minute") 89 | # minsize <- 30 90 | # 91 | # startd <- Sys.Date() - minsize 92 | 93 | # Load ETF prices 94 | # ohlc <- get(input$symbol, rutils::etfenv) 95 | # Load stock prices from Polygon 96 | # ohlc <- rutils::getpoly(symbol=input$symbol, startd=startd, tspan=tspan, apikey=apikey) 97 | # Plot Dygraph 98 | dygraphs::dygraph(pricev()$price, main="SPY Tick Prices") %>% 99 | dyLegend(width=500) 100 | # highcharter::hchart(spyticks$price) 101 | # highcharter::highchart(type="stock") %>% hc_add_series(ohlc, type="candlestick") 102 | 103 | }) 104 | 105 | } # end server code 106 | 107 | 108 | ## Run the Shiny app 109 | shiny::shinyApp(ui=uifun, server=servfun) 110 | 111 | -------------------------------------------------------------------------------- /app_ema_plot.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is an example of creating a dynamic shiny app 3 | # which produces an interactive dygraphs plot. 4 | # Just press the "Run App" button on upper right of this panel. 5 | ############################## 6 | 7 | library(shiny) 8 | library(dygraphs) 9 | library(rutils) 10 | 11 | 12 | # Define elements of the UI user interface 13 | uifun <- shiny::shinyUI(fluidPage( 14 | 15 | # titlePanel("EMA Prices"), 16 | 17 | # Create single row of widgets 18 | h3(fluidRow( 19 | # Input look-back interval 20 | column(width=12, sliderInput("lambda", label="Lambda decay factor", 21 | min=0.5, max=0.99, value=0.9, step=0.01)) 22 | )), # end fluidRow 23 | 24 | 25 | # Create output plot panel 26 | dygraphs::dygraphOutput("dyplot", width="700px", height="400px") 27 | 28 | )) # end shinyUI interface 29 | 30 | 31 | # Define the server code 32 | servfun <- function(input, output) { 33 | 34 | # Calculate the data for plotting 35 | datav <- shiny::reactive({ 36 | # get model parameters from input 37 | lambda <- input$lambda 38 | # Calculate close prices 39 | pricev <- log(quantmod::Cl(rutils::etfenv$VTI["2008/2009"])) 40 | 41 | # Calculate EMA prices using filter 42 | # pricema <- filter(pricev, filter=weights, sides=1) 43 | # weights <- exp(-lambda*(1:widthp)) 44 | # weights <- weights/sum(weights) 45 | # pricema <- .Call(stats:::C_cfilter, pricev, filter=weights, sides=1, circular=FALSE) 46 | # pricema[1:(widthp-1)] <- pricema[widthp] 47 | 48 | # Calculate EMA prices recursively 49 | pricema <- HighFreq::run_mean(pricev, lambda=lambda) 50 | pricema <- cbind(pricev, pricema) 51 | colnames(pricema) <- c("VTI", "EMA") 52 | pricema # Return data for plotting 53 | }) # end reactive data 54 | 55 | # Define the output plot 56 | output$dyplot <- dygraphs::renderDygraph({ 57 | dygraph(datav(), main="EMA Prices") %>% 58 | dySeries(name="VTI", label="VTI", strokeWidth=2, color="blue") %>% 59 | dySeries(name="EMA", label="EMA", strokeWidth=2, color="red") 60 | }) # end output plot 61 | 62 | } # end server code 63 | 64 | # Return a Shiny app object 65 | shiny::shinyApp(ui=uifun, server=servfun) 66 | -------------------------------------------------------------------------------- /app_ema_plot2.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app for plotting an EMA moving average. 3 | # Just press the "Run App" button on upper right of this panel. 4 | ############################## 5 | 6 | ## Below is the setup code that runs once when the shiny app is started 7 | 8 | ## Load packages 9 | library(HighFreq) 10 | library(shiny) 11 | library(dygraphs) 12 | 13 | 14 | ## Set up ETF data 15 | 16 | datenv <- rutils::etfenv 17 | symbolv <- get("symbolv", datenv) 18 | symboln <- "VTI" 19 | 20 | ## End setup code 21 | 22 | 23 | ## Create elements of the user interface 24 | uifun <- shiny::fluidPage( 25 | titlePanel("VTI EMA Prices"), 26 | 27 | # Create single row of widgets with two slider inputs 28 | fluidRow( 29 | # Input stock symbol 30 | column(width=2, selectInput("symboln", label="Symbol", 31 | choices=symbolv, selected=symboln)), 32 | # Input look-back interval 33 | column(width=2, sliderInput("lambda", label="Lambda decay factor", 34 | min=0.5, max=0.99, value=0.9, step=0.01)) 35 | ), # end fluidRow 36 | 37 | # Create output plot panel 38 | dygraphs::dygraphOutput("dyplot", width="90%", height="600px") 39 | 40 | ) # end fluidPage interface 41 | 42 | 43 | ## Define the server function 44 | servfun <- shiny::shinyServer(function(input, output) { 45 | 46 | # Get the close prices in a reactive environment 47 | pricev <- shiny::reactive({ 48 | cat("Getting the close prices\n") 49 | # Get the data 50 | ohlc <- get(input$symboln, datenv) 51 | pricev <- log(quantmod::Cl(ohlc["2008/2009"])) 52 | # Return the data 53 | pricev 54 | }) # end reactive code 55 | 56 | # Calculate the EMA indicator in a reactive environment 57 | pricema <- shiny::reactive({ 58 | cat("Calculating the EMA indicator\n") 59 | # Get model parameters from input argument 60 | lambda <- input$lambda 61 | # Calculate EMA prices recursively using RcppArmadillo 62 | pricev <- pricev() 63 | pricema <- HighFreq::run_mean(pricev, lambda=lambda) 64 | pricema[is.na(pricema)] <- 0 65 | # Return the plot data 66 | pricema <- cbind(pricev, pricema) 67 | colnames(pricema) <- c(input$symboln, "EMA Prices") 68 | pricema 69 | }) # end reactive code 70 | 71 | # Return the dygraph plot to output argument 72 | output$dyplot <- dygraphs::renderDygraph({ 73 | cat("Plotting the dygraph\n") 74 | colnamev <- colnames(pricema()) 75 | dygraph(pricema(), main=paste(colnamev, collapse=" ")) %>% 76 | dySeries(name=colnamev[1], strokeWidth=2, color="blue") %>% 77 | dySeries(name=colnamev[2], strokeWidth=2, color="red") 78 | }) # end output plot 79 | }) # end server code 80 | 81 | ## Return a Shiny app object 82 | shiny::shinyApp(ui=uifun, server=servfun) 83 | -------------------------------------------------------------------------------- /app_ema_quantmod.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "EWMA prices" 3 | author_no_print: "Jerzy Pawlowski" 4 | affiliation: NYU Tandon School of Engineering 5 | date_no_print: '`r format(Sys.time(), "%m/%d/%Y")`' 6 | email: jp3900@nyu.edu 7 | output: html_document 8 | runtime: shiny 9 | --- 10 | 11 | ```{r setup, include=FALSE} 12 | knitr::opts_chunk$set(echo=TRUE) 13 | library(HighFreq) # load package HighFreq 14 | # select OHLC data 15 | ohlc <- rutils::etfenv$VTI["/2011"] 16 | # calculate close prices 17 | closep <- Cl(ohlc) 18 | # define lookback window and decay parameter 19 | look_back <- 51 20 | plot_theme <- chart_theme() 21 | plot_theme$col$line.col <- c("orange", "blue") 22 | 23 | # source("/Users/jerzy/Develop/R/scripts/ewma_model.R") 24 | ``` 25 | 26 | ```{r ewma_model, echo=FALSE} 27 | inputPanel( 28 | sliderInput("lambda", label="lambda:", 29 | min=0.01, max=0.2, value=0.1, step=0.01) 30 | ) # end inputPanel 31 | 32 | renderPlot({ 33 | 34 | lambda <- input$lambda 35 | 36 | # calculate EWMA prices 37 | weightv <- exp(-lambda*1:look_back) 38 | weightv <- weightv/sum(weightv) 39 | ewmap <- filter(closep, filter=weightv, sides=1) 40 | ewmap <- as.numeric(ewmap) 41 | ewmap[1:(look_back-1)] <- ewmap[look_back] 42 | ewmap <- xts(cbind(closep, ewmap), order.by=index(ohlc)) 43 | colnames(ewmap) <- c("VTI", "VTI EWMA") 44 | 45 | # plot EWMA prices 46 | # x11(width=12, height=9) 47 | chobj <- chart_Series(ewmap, theme=plot_theme, name="EWMA prices") 48 | plot(chobj) 49 | legend("topleft", legend=colnames(ewmap), 50 | inset=0.1, bg="white", lty=1, lwd=6, 51 | col=plot_theme$col$line.col, bty="n") 52 | 53 | }) # end renderPlot 54 | ``` 55 | -------------------------------------------------------------------------------- /app_highcharts.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app for a HighCharts candlestick plot of OHLC stock prices. 3 | # Just press the "Run App" button on the upper right of RStudio. 4 | # Or run the app in MacBook terminal: 5 | # Rscript -e "shiny::runApp("~/Develop/Presentations/app_highcharts.R", port=7775)" 6 | # On mini6 run: 7 | # Rscript -e "shiny::runApp("~/Develop/R/app_highcharts.R", host="0.0.0.0", port=7775)" 8 | # And in browser load the page: http://206.72.197.242:7775 9 | ############################## 10 | 11 | 12 | ## Below is the setup code that runs once when the shiny app is started 13 | 14 | # Load packages 15 | library(quantmod) 16 | library(shiny) 17 | library(shinythemes) 18 | library(highcharter) 19 | 20 | ## Load ETF symbols 21 | # symbolv <- rutils::etfenv$symbolv 22 | # symbol <- "VTI" 23 | 24 | ## Setup for Polygon 25 | startd <- as.Date("1990-01-01") 26 | # startd <- as.Date("2022-03-01") 27 | endd <- Sys.Date() 28 | tspan <- "day" 29 | # tspan <- "minute" 30 | apikey <- "UJcr9ctoMBXEBK1Mqu_KQAkUuBxLvEtE" 31 | 32 | sp500table <- read.csv(file="/Users/jerzy/Develop/lecture_slides/data/sp500_constituents.csv") 33 | symbolv <- sp500table$Ticker 34 | symbol <- "AAPL" 35 | 36 | 37 | # Setup end 38 | 39 | ## Create elements of the user interface 40 | interface <- fluidPage( 41 | theme=shinytheme("paper"), 42 | 43 | # Title 44 | h3("HighCharts Candlestick Plot of OHLC Stock Prices"), 45 | 46 | # Widgets 47 | fluidRow( 48 | # Input stock symbol 49 | column(width=2, selectInput("symbol", label="Symbol:", choices=symbolv, selected=symbol)), 50 | # Input time span 51 | column(width=2, selectInput("tspan", label="Time span:", choices=c("day", "minute"), selected="day")), 52 | # Input the look-back interval 53 | column(width=2, numericInput("lookb", label="Look-back days:", value=1000, step=1)) 54 | ), # end fluidRow 55 | 56 | # Output plot panel 57 | highchartOutput("hchart", width="80%", height="600px") 58 | 59 | ) # end fluidPage interface 60 | 61 | ## Define the server function 62 | server <- function(input, output) { 63 | 64 | # Return the Highchart plot to output argument 65 | output$hchart <- renderHighchart({ 66 | 67 | # Copy shiny parameters 68 | tspan <- input$tspan 69 | lookb <- input$lookb 70 | 71 | # Set lookb to 30 days if time span = minute 72 | if (tspan == "minute") 73 | lookb <- 30 74 | 75 | startd <- Sys.Date() - lookb 76 | 77 | # Load ETF prices 78 | # ohlc <- get(input$symbol, rutils::etfenv) 79 | # Load stock prices from Polygon 80 | ohlc <- rutils::getpoly(symbol=input$symbol, startd=startd, tspan=tspan, apikey=apikey) 81 | # Plot highchart 82 | highcharter::highchart(type="stock") %>% hc_add_series(ohlc, type="candlestick") 83 | 84 | }) 85 | 86 | } # end server code 87 | 88 | 89 | ## Run the Shiny app 90 | shinyApp(ui=interface, server=server) 91 | 92 | -------------------------------------------------------------------------------- /app_highcharts_ticks.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app for a HighCharts plot of SPY tick prices. 3 | # Just press the "Run App" button on the upper right of RStudio. 4 | # Or run the app in MacBook terminal: 5 | # Rscript -e "shiny::runApp("Users/jerzy/Develop/Presentations/app_highcharts_ticks.R", port=7775)" 6 | # On mini6 run: 7 | # Rscript -e "shiny::runApp("Users/jerzy/Develop/R/app_highcharts_ticks.R", host="0.0.0.0", port=7775)" 8 | # And in browser load the page: http://206.72.197.242:7775 9 | ############################## 10 | 11 | 12 | ## Below is the setup code that runs once when the shiny app is started 13 | 14 | # Load packages 15 | library(quantmod) 16 | library(shiny) 17 | library(shinythemes) 18 | library(highcharter) 19 | 20 | ## Load SPY ticks 21 | 22 | load(file="/Users/jerzy/Develop/data/spy_ticks.RData") 23 | # load(file="/Users/danielsavage/Public/dans_public/spyticks.RData") 24 | 25 | # Setup end 26 | 27 | ## Create elements of the user interface 28 | uifun <- shiny::fluidPage( 29 | theme=shinythemes::shinytheme("paper"), 30 | 31 | # Title 32 | h3("HighCharts Plot of SPY Tick Prices"), 33 | 34 | # Widgets 35 | # fluidRow( 36 | # # Input stock symbol 37 | # column(width=2, selectInput("symbol", label="Symbol:", choices=symbolv, selected=symbol)), 38 | # # Input time span 39 | # column(width=2, selectInput("tspan", label="Time span:", choices=c("day", "minute"), selected="day")), 40 | # # Input the look-back interval 41 | # column(width=2, numericInput("lookb", label="Look-back days:", value=1000, step=1)) 42 | # ), # end fluidRow 43 | 44 | # Output plot panel 45 | highchartOutput("hchart", width="80%", height="600px") 46 | 47 | ) # end fluidPage interface 48 | 49 | ## Define the server function 50 | servfun <- function(input, output) { 51 | 52 | # Return the Highchart plot to output argument 53 | output$hchart <- renderHighchart({ 54 | 55 | # Copy shiny parameters 56 | # tspan <- input$tspan 57 | # lookb <- input$lookb 58 | 59 | # Set lookb to 30 days if time span = minute 60 | # if (tspan == "minute") 61 | # lookb <- 30 62 | # 63 | # startd <- Sys.Date() - lookb 64 | 65 | # Load ETF prices 66 | # ohlc <- get(input$symbol, rutils::etfenv) 67 | # Load stock prices from Polygon 68 | # ohlc <- rutils::getpoly(symbol=input$symbol, startd=startd, tspan=tspan, apikey=apikey) 69 | # Plot highchart 70 | highcharter::hchart(spyticks$price) 71 | # highcharter::highchart(type="stock") %>% hc_add_series(ohlc, type="candlestick") 72 | 73 | }) 74 | 75 | } # end server code 76 | 77 | 78 | ## Run the Shiny app 79 | shiny::shinyApp(ui=uifun, server=servfun) 80 | 81 | -------------------------------------------------------------------------------- /app_highchartsma.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app for a HighCharts candlestick plot of OHLC stock pricev, 3 | # with a moving average line. 4 | # Just press the "Run App" button on the upper right of RStudio. 5 | # Or run the app in MacBook terminal: 6 | # Rscript -e "shiny::runApp('~/Develop/Presentations/app_highchartsma.R', port=7775)" 7 | # On mini6 run: 8 | # Rscript -e "shiny::runApp('~/Develop/R/app_highchartsma.R', host='0.0.0.0', port=7775)" 9 | # And in browser load the page: http://206.72.197.242:7775 10 | ############################## 11 | 12 | 13 | ## Below is the setup code that runs once when the shiny app is started 14 | 15 | # Load packages 16 | library(quantmod) 17 | library(shiny) 18 | library(shinythemes) 19 | library(highcharter) 20 | 21 | ## Load ETF symbols 22 | # symbolv <- rutils::etfenv$symbolv 23 | # symbol <- "VTI" 24 | 25 | ## Setup for Polygon 26 | startd <- as.Date("1990-01-01") 27 | # startd <- as.Date("2022-03-01") 28 | endd <- Sys.Date() 29 | tspan <- "day" 30 | # tspan <- "minute" 31 | apikey <- "UJcr9ctoMBXEBK1Mqu_KQAkUuBxLvEtE" 32 | 33 | ## Load S&P500 symbols 34 | sp500table <- read.csv(file="/Users/jerzy/Develop/lecture_slides/data/sp500_constituents.csv") 35 | symbolv <- sp500table$Ticker 36 | symbol <- "AAPL" 37 | 38 | lookb <- 1e2 39 | 40 | # Setup end 41 | 42 | ## Create elements of the user interface 43 | interface <- fluidPage( 44 | theme=shinytheme("paper"), 45 | 46 | # Title 47 | h3("HighCharts Candlestick Plot of OHLC Stock Prices"), 48 | 49 | # Widgets 50 | fluidRow( 51 | # Input stock symbol 52 | column(width=2, selectInput("symbol", label="Symbol:", choices=symbolv, selected=symbol)), 53 | # Input time span 54 | column(width=2, selectInput("tspan", label="Time span:", choices=c("day", "minute"), selected="day")), 55 | # Input lambda decay parameter 56 | column(width=3, sliderInput("lambda", label="lambda:", min=0.01, max=0.99, value=0.2, step=0.01)) 57 | ), # end fluidRow 58 | 59 | # Output plot panel 60 | highchartOutput("hchart", width="80%", height="600px") 61 | 62 | ) # end fluidPage interface 63 | 64 | ## Define the server function 65 | server <- function(input, output) { 66 | 67 | # Load the data 68 | ohlc <- shiny::reactive({ 69 | 70 | symbol <- input$symbol 71 | tspan <- input$tspan 72 | # Set lookb to 30 days if time span = minute 73 | if (tspan == "minute") 74 | lookb <- 30 75 | startd <- Sys.Date() - lookb 76 | 77 | cat("Loading data for ", symbol, "\n") 78 | 79 | # Load ETF prices 80 | # ohlc <- get(input$symbol, rutils::etfenv) 81 | # Load stock prices from Polygon 82 | ohlc <- rutils::getpoly(symbol=symbol, startd=startd, tspan=tspan, apikey=apikey) 83 | ohlc[, c("Open", "High", "Low", "Close", "VWAP")] <- log(ohlc[, c("Open", "High", "Low", "Close", "VWAP")]) 84 | ohlc 85 | 86 | }) # end Load the data 87 | 88 | # Return the Highchart plot to output argument 89 | output$hchart <- renderHighchart({ 90 | 91 | ohlc <- ohlc() 92 | 93 | # Copy shiny parameters 94 | lambda <- input$lambda 95 | # lookb <- input$lookb 96 | 97 | # Calculate the running mean prices 98 | closep <- quantmod::Cl(ohlc) 99 | means <- HighFreq::run_mean(closep, lambda=lambda) 100 | means <- xts::xts(means, zoo::index(ohlc)) 101 | # Plot highchart 102 | highcharter::highchart(type="stock") %>% 103 | hc_add_series(ohlc, type="candlestick") %>% 104 | hc_add_series(means, yAxis=0, name="MA", color="red") 105 | 106 | }) 107 | 108 | } # end server code 109 | 110 | 111 | ## Run the Shiny app 112 | shinyApp(ui=interface, server=server) 113 | 114 | -------------------------------------------------------------------------------- /app_ornstein_uhlenbeck.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Ornstein-Uhlenbeck process" 3 | # author: "Jerzy Pawlowski" 4 | affiliation: NYU Tandon School of Engineering 5 | # date: '`r format(Sys.time(), "%m/%d/%Y")`' 6 | email: jp3900@nyu.edu 7 | output: html_document 8 | runtime: shiny 9 | --- 10 | 11 | ```{r setup, include=FALSE} 12 | knitr::opts_chunk$set(echo=TRUE) 13 | set.seed(1121) # Reset random numbers 14 | nrows <- 1000 15 | innov <- rnorm(nrows) 16 | # source("/Users/jerzy/Develop/R/scripts/ewma_model.R") 17 | ``` 18 | 19 | ```{r OUmodel, echo=FALSE} 20 | 21 | inputPanel( 22 | sliderInput("volatp", label="Volatility:", 23 | min=0.001, max=0.05, value=0.01, step=0.001), 24 | sliderInput("priceq", label="Equlibrium price:", 25 | min=1.0, max=10.0, value=5.0, step=0.1), 26 | sliderInput("thetav", label="Theta parameter:", 27 | min=0.0001, max=0.05, value=0.005, step=0.0001) 28 | ) # end inputPanel 29 | 30 | renderPlot({ 31 | 32 | cat("Simulating Ornstein-Uhlenbeck process", "\n") 33 | # cat("nrows = ", nrows, "\n") 34 | 35 | volatp <- input$volatp 36 | priceq <- input$priceq 37 | thetav <- input$thetav 38 | 39 | # Perform the loop 40 | retv <- numeric(nrows) 41 | pricev <- numeric(nrows) 42 | pricev[1] <- priceq 43 | for (i in 2:nrows) { 44 | retv[i] <- thetav*(priceq - pricev[i-1]) + volatp*innov[i] 45 | pricev[i] <- pricev[i-1] * exp(retv[i]) 46 | } # end for 47 | 48 | # Plot 49 | plot(pricev, type="l", cex.lab=1.7, cex.axis=1.7, lwd=2, col="blue", 50 | xlab="time", ylab="price", 51 | main="Ornstein-Uhlenbeck process") 52 | legend("topright", 53 | title=paste(c(paste0("Volatility = ", volatp), 54 | paste0("Equlibrium price = ", priceq), 55 | paste0("Theta parameter = ", thetav)), 56 | collapse="\n"), 57 | legend="", cex=1.7, 58 | inset=0.01, bg="white", bty="n") 59 | 60 | }, height=600, width=1000) # end renderPlot 61 | ``` 62 | -------------------------------------------------------------------------------- /app_pair_returns copy 2.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app which plots the daily, daytime, and 3 | # overnight returns of a stock pair with a fixed beta. 4 | # 5 | # Just press the "Run App" button on upper right of this panel. 6 | ############################## 7 | 8 | ## Below is the setup code that runs only once when the shiny app is started 9 | 10 | ## Load packages 11 | library(HighFreq) 12 | library(shiny) 13 | library(dygraphs) 14 | 15 | ## Load daily S&P500 stock prices and returns 16 | # load(file="/Users/jerzy/Develop/lecture_slides/data/sp500_prices.RData") 17 | # load(file="/Users/jerzy/Develop/lecture_slides/data/sp500_returns.RData") 18 | # pricerefs <- sort(colnames(pricestock)) 19 | # pricetarg <- "AAPL" 20 | # 21 | # symbolsetf <- colnames(rutils::etfenv$prices) 22 | # priceref <- "XLK" 23 | 24 | symboltarg <- "SVXY" 25 | symbolref <- "VTI" 26 | 27 | ohlctarg <- log(get(symboltarg, rutils::etfenv)) 28 | datev <- zoo::index(ohlctarg) 29 | ohlcref <- log(get(symbolref, rutils::etfenv)) 30 | ohlcref <- ohlcref[datev] 31 | 32 | opentarg <- quantmod::Op(ohlctarg) 33 | closetarg <- quantmod::Cl(ohlctarg) 34 | retontarg <- (opentarg - rutils::lagit(closetarg, lagg=1, pad_zeros=FALSE)) 35 | retdtarg <- (closetarg - opentarg) 36 | retdtarg <- rutils::lagit(retdtarg) 37 | 38 | openref <- quantmod::Op(ohlcref) 39 | closeref <- quantmod::Cl(ohlcref) 40 | retonref <- (openref - rutils::lagit(closeref, lagg=1, pad_zeros=FALSE)) 41 | retdref <- (closeref - openref) 42 | retdref <- rutils::lagit(retdref) 43 | 44 | nrows <- NROW(ohlcref) 45 | symbolpair <- paste0(symboltarg, "/", symbolref) 46 | captiont <- paste0("Ratchet Strategy For ", symbolpair) 47 | 48 | 49 | # pricerefs <- rutils::etfenv$symbolv 50 | # pricetargs <- pricerefs 51 | 52 | 53 | # captiont <- paste("Stat-arb Portfolio Strategy app_statarb_strat.R") 54 | 55 | ## End setup code 56 | 57 | 58 | ## Create elements of the user interface 59 | uifun <- shiny::fluidPage( 60 | titlePanel("Returns of a Stock Pair With Fixed Beta"), 61 | 62 | # create single row with four slider inputs 63 | fluidRow( 64 | # Input stock symbol 65 | # column(width=1, selectInput("pricetarg", label="Stock", choices=pricetargs, selected=pricetarg)), 66 | # Input ETF symbol 67 | # column(width=1, selectInput("priceref", label="ETF", choices=pricerefs, selected=priceref)), 68 | # Input beta parameter 69 | column(width=2, sliderInput("betac", label="beta:", min=0.0, max=2.0, value=1.0, step=0.1)), 70 | ), # end fluidRow 71 | 72 | # create output plot panel 73 | dygraphs::dygraphOutput("dyplot", width="90%", height="600px") 74 | # mainPanel(dygraphs::dygraphOutput("dyplot"), width=12) 75 | ) # end fluidPage interface 76 | 77 | 78 | ## Define the server code 79 | servfun <- shiny::shinyServer(function(input, output) { 80 | 81 | # Rerun the strategy 82 | pnls <- shiny::reactive({ 83 | 84 | cat("Recalculating strategy", "\n") 85 | # Get model parameters from input argument 86 | # lagg <- input$lagg 87 | # coeff <- as.numeric(input$coeff) 88 | reton <- retontarg - input$betac*retonref 89 | retd <- retdtarg - input$betac*retdref 90 | 91 | # Trade the overnight returns based on the lagged daytime returns 92 | pnls <- (reton*sign(retd)) 93 | colnames(pnls) <- c("Strategy") 94 | pnls 95 | # pnls <- pnls*sd(reton[reton<0])/sd(pnls[pnls<0]) 96 | 97 | }) # end reactive code 98 | 99 | 100 | # Return the dygraph plot to output argument 101 | output$dyplot <- dygraphs::renderDygraph({ 102 | 103 | pnls <- pnls() 104 | # colnamev <- colnames(pricev) 105 | 106 | dygraphs::dygraph(cumsum(pnls), main=captiont) %>% 107 | dyOptions(colors="blue", strokeWidth=1) %>% 108 | dyLegend(show="always", width=300) 109 | 110 | }) # end output plot 111 | 112 | }) # end server code 113 | 114 | ## Return a Shiny app object 115 | shiny::shinyApp(ui=uifun, server=servfun) 116 | -------------------------------------------------------------------------------- /app_range.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app for calculating the average rescaled 3 | # range of daily prices for a pair of stocks, as a function 4 | # of the beta weight parameter. 5 | 6 | ## Below is the setup code that runs once when the shiny app is started 7 | 8 | # Load R packages 9 | library(HighFreq) 10 | library(shiny) 11 | library(dygraphs) 12 | 13 | ## Model and data setup 14 | 15 | # Load the intraday minute prices 16 | load(paste0("/Users/jerzy/Develop/data/SPY_minute_202425.RData")) 17 | pricetarg <- pricel 18 | load(paste0("/Users/jerzy/Develop/data/XLK_minute_202425.RData")) 19 | priceref <- pricel 20 | 21 | priceref <- do.call(rbind, priceref) 22 | pricetarg <- do.call(rbind, pricetarg) 23 | 24 | # Calculate the symbol names 25 | symboltarg <- rutils::get_name(colnames(pricetarg)) 26 | symbolref <- rutils::get_name(colnames(priceref)) 27 | symbolpair <- paste0(symboltarg, "/", symbolref) 28 | captiont <- paste0("Range For ", symbolpair) 29 | 30 | ## End setup code 31 | 32 | 33 | ## Create elements of the user interface 34 | uifun <- shiny::fluidPage( 35 | titlePanel(captiont), 36 | 37 | fluidRow( 38 | # Input the beta parameter 39 | column(width=2, sliderInput("betac", label="beta:", min=0.0, max=3.0, value=2.0, step=0.1)), 40 | ), # end fluidRow 41 | 42 | # Create output plot panel 43 | dygraphs::dygraphOutput("dyplot", width="90%", height="600px") 44 | 45 | ) # end fluidPage interface 46 | 47 | 48 | ## Define the server code 49 | servfun <- function(input, output) { 50 | 51 | # Create an empty list of reactive values. 52 | values <- reactiveValues() 53 | 54 | # Recalculate the range 55 | pricev <- shiny::reactive({ 56 | 57 | cat("Recalculating the range for", symbolpair, "\n") 58 | 59 | # Calculate the pair prices 60 | pricev <- pricetarg - input$betac*priceref 61 | colnames(pricev) <- "Pair" 62 | # Calculate the range of daily prices for VTI 63 | ohlc <- xts::to.daily(pricev) 64 | openp <- quantmod::Op(ohlc) 65 | closep <- quantmod::Cl(ohlc) 66 | retd <- (closep - openp) 67 | colnames(retd) <- "daytime" 68 | highp <- quantmod::Hi(ohlc) 69 | lowp <- quantmod::Lo(ohlc) 70 | hilo <- highp - lowp 71 | # Actual value of the rescaled range is: 72 | rangev <- mean(hilo)/sd(retd) 73 | values$rangev <- round(rangev, 3) 74 | # cat("range =", rangev, "\n") 75 | 76 | pricev 77 | 78 | }) # end Recalculate the range 79 | 80 | 81 | # Plot the pair 82 | output$dyplot <- dygraphs::renderDygraph({ 83 | 84 | # Get the PnLs 85 | pricev <- pricev() 86 | colnamev <- colnames(pricev) 87 | 88 | # Get the range 89 | rangev <- values$rangev 90 | # cat("range =", rangev, "\n") 91 | captiont <- paste0(captiont, " / range = ", rangev) 92 | # Return to the output argument a dygraph plot 93 | dygraphs::dygraph(pricev, main=captiont) 94 | 95 | }) # end output plot 96 | 97 | } # end server code 98 | 99 | ## Return a Shiny app object 100 | shiny::shinyApp(ui=uifun, server=servfun) 101 | -------------------------------------------------------------------------------- /app_simple.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a simple shiny app. 3 | # To run it, just press the "Run App" button on upper right of this panel. 4 | ############################## 5 | 6 | ############################## 7 | # Below is the setup code that runs only once at startup 8 | # when the shiny app is started. 9 | # In the setup code you can load packages, define functions 10 | # and variables, source files, and load data. 11 | 12 | ndata <- 1e4 13 | stdev <- 1.0 14 | 15 | # End setup code 16 | ############################## 17 | 18 | 19 | ############################## 20 | ## Define the user interface 21 | 22 | uifun <- shiny::fluidPage( 23 | 24 | titlePanel("A Simple Shiny App"), 25 | 26 | ## Create interface for the input parameters. 27 | 28 | # Create numeric input for the number of data points. 29 | numericInput("ndata", "Number of data points:", value=ndata), 30 | 31 | # Create slider input for the standard deviation parameter. 32 | sliderInput("stdev", label="Standard deviation:", 33 | min=0.1, max=3.0, value=stdev, step=0.1), 34 | 35 | ## Produce output. 36 | # Render plot in a panel. 37 | plotOutput("plotobj", height=300, width=500) 38 | 39 | ) # end user interface 40 | 41 | 42 | 43 | ############################## 44 | ## Define the server function, with the arguments "input" and "output". 45 | # The server function performs the calculations and creates the plots. 46 | 47 | servfun <- function(input, output) { 48 | 49 | ## Recalculate the model with new parameters 50 | # The function shiny::reactive() accepts a block of expressions 51 | # which calculate the model, and returns the model output. 52 | datav <- shiny::reactive({ 53 | cat("Calculating the data\n") 54 | 55 | # Simulate the data 56 | rnorm(input$ndata, sd=1) 57 | 58 | }) # end reactive code 59 | 60 | 61 | # Plot the data 62 | output$plotobj <- shiny::renderPlot({ 63 | cat("Plotting the data\n") 64 | 65 | datav <- input$stdev*datav() 66 | 67 | # Plot the data 68 | par(mar=c(2, 4, 4, 0), oma=c(0, 0, 0, 0)) 69 | hist(datav, xlim=c(-4, 4), main="Histogram of Random Data") 70 | 71 | }) # end renderPlot 72 | 73 | } # end servfun 74 | 75 | 76 | ## Return a Shiny app object 77 | 78 | shiny::shinyApp(ui=uifun, server=servfun) 79 | -------------------------------------------------------------------------------- /app_trifilter.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app for identifying isolated price spikes in 3 | # intraday data using a three-point classifier (tri-filter). 4 | # Just press the "Run App" button on upper right of this panel. 5 | ############################## 6 | 7 | ## Below is the setup code that runs once when the shiny app is started 8 | 9 | ## Load packages 10 | library(HighFreq) 11 | library(shiny) 12 | library(dygraphs) 13 | 14 | 15 | ## Load the intraday prices 16 | 17 | load(file="/Users/jerzy/Develop/lecture_slides/data/xlk_tick_trades_20200316.RData") 18 | symboln <- rutils::get_name(colnames(taq)[1]) 19 | captiont <- paste(symboln, "EMA Prices") 20 | 21 | 22 | ## End setup code 23 | 24 | 25 | ## Create elements of the user interface 26 | uifun <- shiny::fluidPage( 27 | 28 | titlePanel(captiont), 29 | 30 | # Create single row of widgets with two slider inputs 31 | fluidRow( 32 | # Input stock symbol 33 | # column(width=2, selectInput("symboln", label="Symbol", 34 | # choices=symbolv, selected=symboln)), 35 | # Input look-back interval 36 | column(width=2, sliderInput("lambda", label="Lambda decay factor", 37 | min=0.5, max=0.99, value=0.9, step=0.01)) 38 | ), # end fluidRow 39 | 40 | # Create output plot panel 41 | dygraphs::dygraphOutput("dyplot", width="90%", height="600px") 42 | 43 | ) # end fluidPage interface 44 | 45 | 46 | ## Define the server function 47 | servfun <- shiny::shinyServer(function(input, output) { 48 | 49 | # Get the close prices in a reactive environment 50 | pricev <- shiny::reactive({ 51 | cat("Getting the close prices\n") 52 | # Get the close prices 53 | pricev <- quantmod::Cl(taq) 54 | pricev 55 | }) # end reactive code 56 | 57 | # Calculate the EMA indicator in a reactive environment 58 | pricema <- shiny::reactive({ 59 | cat("Calculating the EMA indicator\n") 60 | # Get model parameters from input argument 61 | lambda <- input$lambda 62 | # Calculate EMA prices recursively using RcppArmadillo 63 | pricev <- pricev() 64 | pricema <- HighFreq::run_mean(pricev, lambda=lambda) 65 | pricema[is.na(pricema)] <- 0 66 | # Return the plot data 67 | pricema <- cbind(pricev, pricema) 68 | colnames(pricema) <- c(symboln, "EMA Prices") 69 | pricema 70 | }) # end reactive code 71 | 72 | # Return the dygraph plot to output argument 73 | output$dyplot <- dygraphs::renderDygraph({ 74 | cat("Plotting the dygraph\n") 75 | colnamev <- colnames(pricema()) 76 | dygraph(pricema(), main=paste(colnamev, collapse=" ")) %>% 77 | dySeries(name=colnamev[1], strokeWidth=2, color="blue") %>% 78 | dySeries(name=colnamev[2], strokeWidth=2, color="red") 79 | }) # end output plot 80 | 81 | }) # end server code 82 | 83 | ## Return a Shiny app object 84 | shiny::shinyApp(ui=uifun, server=servfun) 85 | -------------------------------------------------------------------------------- /app_wealth_distribution_hw.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app for simulating the wealth distributions 3 | # of VTI and IEF portfolios, for different holding periods. 4 | # 5 | # Just press the "Run App" button on upper right of this panel. 6 | ############################## 7 | 8 | 9 | ############################## 10 | # Below is the setup code that runs only once at startup 11 | # when the shiny app is started. 12 | # In the setup code you can load packages, define functions 13 | # and variables, source files, and load data. 14 | 15 | # Load packages here (if needed) 16 | library(rutils) 17 | # Coerce the log prices from xts time series to matrix 18 | pricev <- na.omit(rutils::etfenv$prices[, c("VTI", "IEF")]) 19 | pricev <- log(zoo::coredata(pricev)) 20 | nrows <- NROW(pricev) 21 | 22 | # Define the risk-adjusted wealth measure 23 | riskretfun <- function(wealthv) { 24 | mean(wealthv)/sd(wealthv) 25 | } # end riskretfun 26 | 27 | # Set the number of bootstrap samples 28 | nboot <- 1e3 29 | 30 | 31 | # End setup code 32 | ############################## 33 | 34 | 35 | ############################## 36 | ## Define the user interface 37 | 38 | uifun <- shiny::fluidPage( 39 | titlePanel("Terminal Wealth Distribution of a VTI and IEF Portfolio"), 40 | 41 | # Create four slider inputs with parameters to lossdistr() 42 | fluidRow( 43 | column(width=2, sliderInput("weightv", label="VTI weight:", 44 | min=0.01, max=0.99, value=0.5, step=0.01)), 45 | column(width=2, sliderInput("holdp", label="Holding period (years):", 46 | min=1.0, max=(nrows %/% 252), value=(nrows %/% 252)/2, step=0.1)) 47 | ), # end fluidRow 48 | 49 | # Render plot in panel 50 | shiny::plotOutput("plotobj", width="100%", height=650) 51 | ) # end fluidPage interface 52 | 53 | 54 | ############################## 55 | ## Define the server code 56 | # The function servfun() accepts the arguments "input" and "output". 57 | 58 | servfun <- function(input, output) { 59 | 60 | ## Recalculate the model with new parameters 61 | # The function shiny::reactive() accepts a block of expressions 62 | # which calculate the model, and returns the model output. 63 | wealthv <- shiny::reactive({ 64 | 65 | # Extract model parameters from the argument "input" 66 | weightv <- input$weightv 67 | holdp <- 252*input$holdp 68 | 69 | # Sample the start dates for the bootstrap 70 | set.seed(1121, "Mersenne-Twister", sample.kind="Rejection") 71 | startd <- sample.int(nrows-holdp, nboot, replace=TRUE) 72 | 73 | # Calculate a vector of portfolio wealths from startd and weightv 74 | # Hint: Perform an sapply() loop over startd 75 | 76 | ### Write your code here 77 | 78 | wealthv 79 | 80 | }) # end reactive code 81 | 82 | ## Create plot and return it to the output argument 83 | output$plotobj <- shiny::renderPlot({ 84 | 85 | # Copy the wealth data 86 | wealthv <- wealthv() 87 | 88 | # Calculate the wealth parameters 89 | meanv <- mean(wealthv) 90 | stdev <- sd(wealthv) 91 | skewv <- mean(((wealthv - meanv)/stdev)^3) 92 | 93 | # Calculate the risk-adjusted wealth measure 94 | 95 | ### Write your code here 96 | 97 | # Calculate the density of wealth distribution 98 | 99 | ### Write your code here 100 | 101 | # Plot the density of portfolio wealth 102 | # Hint: Use the functions plot(), abline(), and text() 103 | 104 | ### Write your code here 105 | 106 | 107 | }) # end output plot 108 | 109 | } # end server function 110 | 111 | 112 | ############################## 113 | ## Return a Shiny app object 114 | 115 | shiny::shinyApp(ui=uifun, server=servfun) 116 | -------------------------------------------------------------------------------- /backtest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/backtest.png -------------------------------------------------------------------------------- /bib_template.Rnw: -------------------------------------------------------------------------------- 1 | % 2 | % This file presents the 'numeric' style 3 | % 4 | \documentclass[a4paper]{article} 5 | \usepackage[T1]{fontenc} 6 | \usepackage[american]{babel} 7 | \usepackage{csquotes} 8 | \usepackage[style=numeric,subentry]{biblatex} 9 | \usepackage{hyperref} 10 | \addbibresource{FRE6811_bib.bib} 11 | % Some generic settings. 12 | \newcommand{\cmd}[1]{\texttt{\textbackslash #1}} 13 | \setlength{\parindent}{0pt} 14 | \begin{document} 15 | 16 | \section*{The \texttt{numeric} style} 17 | 18 | This style prints numeric citations in square brackets. It is 19 | similar to the standard bibliographic facilities provided by LaTeX 20 | and to the \texttt{plain.bst} style of legacy BibTeX. 21 | 22 | \subsection*{\cmd{cite} examples} 23 | 24 | \cite{website:rintro} 25 | 26 | \cite[59]{website:rintro} 27 | 28 | \cite[see][]{website:rintro} 29 | 30 | \cite[see][59--63]{website:rintro} 31 | 32 | \subsection*{\cmd{parencite} examples} 33 | 34 | % With the numeric style, the \parencite command is similar to \cite 35 | % at first glance, but the placement of the prenote argument is 36 | % different. 37 | 38 | This is just filler text \parencite{website:rintro}. 39 | 40 | This is just filler text \parencite[59]{website:rintro}. 41 | 42 | This is just filler text \parencite[see][]{website:rintro}. 43 | 44 | This is just filler text \parencite[see][59--63]{website:rintro}. 45 | 46 | \subsection*{\cmd{textcite} examples} 47 | 48 | % The \textcite command is intended for citations integrated in the 49 | % flow of text, replacing the subject of the sentence. 50 | 51 | \textcite{website:rintro} show that this is just filler text. 52 | 53 | \textcite[59]{website:rintro} show that this is just filler text. 54 | 55 | \textcite[see][]{website:rintro} show that this is just filler text. 56 | 57 | \textcite[see][59--63]{website:rintro} show that this is just filler text. 58 | 59 | \subsection*{\cmd{supercite} examples} 60 | 61 | This is just filler text.\supercite{website:rintro} 62 | 63 | \subsection*{\cmd{autocite} examples} 64 | 65 | % By default, the \autocite command works like \parencite. 66 | 67 | This is just filler text \autocite{website:rintro}. 68 | 69 | \subsection*{Multiple citations} 70 | 71 | % By default, a list of multiple citations is not sorted. You can 72 | % enable sorting by setting the 'sortcites' package option. 73 | 74 | \cite{website:rintro,augustine,bertram,cotton,hammond,massa,murray} 75 | 76 | \subsection*{Reference sets} 77 | 78 | % Reference sets are cited like any other item: 79 | 80 | \cite{set,hammond,stdmodel,massa,murray} 81 | 82 | % Note that this style provides a package option called 'subentry' 83 | % which affects the handling of citations referring to members of 84 | % a reference set. If this option is enabled, such citations get an 85 | % extra letter which identifies the member (it is also printed in 86 | % the bibliography): 87 | 88 | \cite{glashow,yoon,salam,aksin} 89 | 90 | % Note that this options is disabled by default but has been enabled 91 | % in this example. If disabled, citations referring to a set member 92 | % will point to the set, i.e., the above citations would be similar 93 | % to this one: 94 | 95 | \cite{set,stdmodel} 96 | 97 | % The list of references 98 | 99 | \clearpage 100 | \printbibliography 101 | 102 | \end{document} 103 | -------------------------------------------------------------------------------- /coinflipping.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/coinflipping.jpg -------------------------------------------------------------------------------- /dygraphs_dashboard.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Dashboard of Interactive Time Series Plots" 3 | author: "Jerzy Pawlowski, at Algoquants" 4 | email: algoquant@algoquants.ch 5 | affiliation: Algoquants 6 | date: '`r format(Sys.time(), "%m-%d-%Y %H:%M")`' 7 | output: 8 | html_document: 9 | fig_width: 6 10 | fig_height: 4 11 | --- 12 | 13 | ```{r setup, include=FALSE} 14 | # This is an R setup chunk, containing default options applied to all other chunks 15 | library(rutils) 16 | library(dygraphs) 17 | ``` 18 | 19 | 20 | ### A dashboard of interactive time series plots written in Rmarkdown 21 | 22 | Uses the package *dygraphs* to create the dygraphs objects in a loop, and then uses the package *htmltools* to render (plot) the *dygraphs* objects. Click and drag to zoom into any plot. 23 | 24 | 25 | 26 | ```{r echo=FALSE, fig.width=2, fig.height=2} 27 | ## Load time series data from csv files into an environment. 28 | 29 | # create new environment for data 30 | data_env <- new.env() 31 | dir_data <- "/Users/jerzy/Develop/data/bbg_records" 32 | # symbols <- c("SPX", "VIX") 33 | # file_names <- paste0(symbols, ".csv") 34 | file_names <- dir(dir_data) 35 | symbols <- rutils::get_name(file_names) 36 | 37 | # load data from csv files into the environment 38 | out <- rutils::get_data(symbols=symbols, 39 | data_dir=dir_data, 40 | data_env=data_env, 41 | echo=FALSE) 42 | 43 | 44 | ## Extract the closing prices into a single xts time series 45 | 46 | # prices <- lapply(as.list(data_env)[symbols], quantmod::Cl) 47 | # flatten (cbind) prices into single xts series 48 | # prices <- rutils::do_call(cbind, prices) 49 | 50 | prices <- rutils::get_col(ohlc=ls(data_env), 51 | data_env=data_env) 52 | # remove NA values 53 | prices <- rutils::na_locf(prices) 54 | prices <- rutils::na_locf(prices, from_last=TRUE) 55 | # save column names 56 | colnamevs <- colnames(prices) 57 | 58 | 59 | cat("\n") 60 | # create a list of dygraphs objects in loop 61 | dyplots <- lapply(1:NCOL(prices), function(i) { 62 | # cat("Plot of: ", symbols[i], "\n") 63 | # plot(zoo::coredata(prices[, i]), main=paste("Plot of:", symbols[i]), t="l") 64 | # plot(quantmod::chart_Series(prices[, i], name=paste("Plot of:", symbols[i]))) 65 | # the fig.width and fig.height chunck options are ignored by dygraphs, so need to use the width and height parameters directly 66 | dygraphs::dygraph(prices[, i], main=paste("Plot of:", colnamevs[i]), width=600, height=400) 67 | }) # end lapply 68 | 69 | # render the dygraphs objects 70 | htmltools::tagList(dyplots) 71 | ``` 72 | -------------------------------------------------------------------------------- /dygraphs_plots.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Dashboard of Interactive Time Series Plots" 3 | author: "Jerzy Pawlowski at NYU Tandon" 4 | affiliation: NYU Tandon School of Engineering 5 | email: jp3900@nyu.edu 6 | date: '`r format(Sys.time(), "%m-%d-%Y %H:%M")`' 7 | output: 8 | html_document: 9 | fig_width: 6 10 | fig_height: 4 11 | --- 12 | 13 | ```{r setup, include=FALSE} 14 | # This is an R setup chunk, containing default options applied to all other chunks 15 | knitr::opts_chunk$set(echo=FALSE) 16 | library(rutils) 17 | library(dygraphs) 18 | ``` 19 | 20 | 21 | ### A dashboard of interactive time series plots written in *Rmarkdown* 22 | 23 | This *Rmarkdown* document contains interactive *dygraphs* plots of time series contained in the package *rutils*. The interactive time series plots are produced using the package *dygraphs*. It creates a list of *dygraphs* objects in a loop, and then uses the package *htmltools* to render (plot) the *dygraphs* objects. 24 | 25 | ### You can click and drag your mouse to zoom into any plot. 26 | 27 | Double-click your mouse to restore the plot. 28 | 29 | 30 | ```{r echo=FALSE} 31 | # Extract the closing ETF prices into a list of xts time series 32 | # pricel <- lapply(rutils::etfenv$symbolv, function(symboln) { 33 | # quantmod::Cl(get(symboln, envir=rutils::etfenv)) 34 | # }) # end lapply 35 | 36 | # Flatten (cbind) list of prices into single xts series 37 | # prices <- rutils::do_call(cbind, pricel) 38 | 39 | # Overwrite NA values 40 | # prices <- zoo::na.locf(price) 41 | # prices <- zoo::na.locf(prices, from_last=TRUE) 42 | 43 | # Make nice column names 44 | # colnames(prices) <- rutils::do_call_rbind(strsplit(colnames(prices), split="[.]"))[, 1] 45 | 46 | # Create a list of dygraphs objects in loop 47 | dyplots <- lapply(rutils::etfenv$symbolv, function(symboln) { 48 | pricev <- quantmod::Cl(get(symboln, envir=rutils::etfenv)) 49 | dygraphs::dygraph(pricev, main=paste("Plot of:", rutils::get_name(colnames(pricev))), width=600, height=400) 50 | }) # end lapply 51 | 52 | # Load S&P500 stock prices 53 | # load("/Users/jerzy/Develop/lecture_slides/data/sp500_prices.RData") 54 | # Load old tickers 55 | # sp500old <- read.csv(file="/Users/jerzy/Develop/lecture_slides/data/sp500_old.csv") 56 | # symbolb <- sp500old$Ticker 57 | # prico <- pricestock[, symbolb] 58 | # Create a list of dygraphs objects in loop 59 | # dyplots <- lapply(prico, function(pricev) { 60 | # dygraphs::dygraph(pricev, main=paste("Plot of:", colnames(pricev)), width=600, height=400) 61 | # }) # end lapply 62 | 63 | # Render the dygraphs objects 64 | htmltools::tagList(dyplots) 65 | ``` 66 | -------------------------------------------------------------------------------- /dygraphs_pnls.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Plot of Strategy PnLs" 3 | author: "Jerzy Pawlowski" 4 | affiliation: MachineTrader.io 5 | email: jpawlowski@machinetrader.io 6 | date: '`r format(Sys.time(), "%m-%d-%Y %H:%M")`' 7 | output: html_document 8 | runtime: shiny 9 | --- 10 | 11 | ```{r setup, include=FALSE} 12 | # This is an R setup chunk, containing default options applied to all other chunks 13 | knitr::opts_chunk$set(echo=FALSE) 14 | library(rutils) 15 | library(data.table) 16 | library(dygraphs) 17 | library(shiny) 18 | 19 | # Download the PnLs array 20 | # system("/Users/jerzy/Develop/shell/download_trade_tables3.sh") 21 | 22 | # Get the strategy names 23 | dirin <- "/Users/jerzy/Develop/data/raw/" 24 | filev <- Sys.glob(paste0(dirin, "Strat*pnl_*.csv")) 25 | filev <- sapply(filev, function(x) { 26 | strsplit(x, "/") %>% unlist %>% tail(1) %>% strsplit("_") %>% unlist %>% head(1) 27 | }) # end sapply 28 | stratv <- unique(unname(filev)) 29 | 30 | # Set the column names 31 | colv <- c("price", "EMA", "volatility", "zscore", "position", "realPnL", "unrealPnL", "totalPnL") 32 | 33 | ``` 34 | 35 | This *Rmarkdown* document plots a *dygraph* plot of the PnLs array. 36 | 37 | 38 | ```{r shiny, echo=FALSE} 39 | shiny::fluidPage( 40 | shiny::fluidRow( 41 | # Input stock symbol 42 | column(width=2, selectInput("stratn", label="Strategy name", choices=stratv, selected=stratv[1])), 43 | # Input the column 1 name 44 | column(width=2, shiny::selectInput("col1", label="Column 1:", choices=colv, selected=colv[1])), 45 | # Input the column 2 name 46 | column(width=2, shiny::selectInput("col2", label="Column 2:", choices=colv, selected=colv[2])), 47 | ), # end fluidRow 48 | 49 | # Create output plot panel 50 | dygraphs::dygraphOutput("dyplot", width="90%", height="500px") 51 | 52 | ) # end fluidPage interface 53 | 54 | # Calculate the data 55 | datav <- shiny::reactive({ 56 | cat("Calculating the data\n") 57 | # Load the PnL arrays 58 | filev <- Sys.glob(paste0(dirin, input$stratn, "*.csv")) 59 | datam <- lapply(filev, function(x) { 60 | dframe <- read.csv(x) 61 | dframe <- dframe[drop(dframe[, 1] > 0), ] 62 | }) # end lapply 63 | # Bind the PnL arrays 64 | datam <- do.call(rbind, datam) 65 | 66 | # Coerce the PnL array to time series 67 | datev <- as.POSIXct(datam[, 1]/1e3, origin="1970-01-01", tz="America/New_York") 68 | datam <- xts::xts(datam[, -1], order.by=datev) 69 | ncols <- NCOL(datam) 70 | datam <- cbind(datam, datam[, ncols-1] + datam[, ncols]) 71 | colnames(datam) <- colv 72 | 73 | # Get the two columns 74 | series1 <- get(input$col1, datam) 75 | series2 <- get(input$col2, datam) 76 | datav <- cbind(series1, series2) 77 | colnamev <- c(input$col1, input$col2) 78 | colnames(datav) <- colnamev 79 | datav 80 | 81 | }) # end reactive code 82 | 83 | 84 | output$dyplot <- dygraphs::renderDygraph({ 85 | datav <- datav() 86 | colnamev <- colnames(datav) 87 | # Plot the dygraph 88 | dygraphs::dygraph(datav, main="captiont") %>% 89 | dyAxis("y", label=colnamev[1], independentTicks=TRUE) %>% 90 | dyAxis("y2", label=colnamev[2], independentTicks=TRUE) %>% 91 | dySeries(name=colnamev[1], axis="y", strokeWidth=1, col="blue") %>% 92 | dySeries(name=colnamev[2], axis="y2", strokeWidth=1, col="red") 93 | 94 | # dygraphs::dygraph(get(input$col1, pnls), width="80%", height="600px") 95 | }) # end renderDygraph 96 | ``` 97 | 98 | -------------------------------------------------------------------------------- /dygraphs_pnls1.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Plot of the Strategy Data" 3 | # author: "Jerzy Pawlowski" 4 | affiliation: MachineTrader.io 5 | email: jpawlowski@machinetrader.io 6 | # date: '`r format(Sys.time(), "%m-%d-%Y %H:%M")`' 7 | output: html_document 8 | runtime: shiny 9 | --- 10 | 11 | ```{r setup, include=FALSE, echo=TRUE} 12 | # This is an R setup chunk, containing default options applied to all other chunks 13 | knitr::opts_chunk$set(echo=FALSE) 14 | library(rutils) 15 | library(data.table) 16 | library(dygraphs) 17 | library(shiny) 18 | 19 | # Download the PnLs array 20 | # system("/Users/jerzy/Develop/shell/download_trade_tables3.sh") 21 | 22 | # Get the strategy name 23 | filen <- "/Users/jerzy/Develop/data/raw/StratRatchetPatModPairMSFT1SPY1pnl_20240807.csv" 24 | stratn <- strsplit(filen, "/") %>% unlist %>% tail(1) 25 | stratn <- strsplit(stratn, "_") %>% unlist 26 | datev <- stratn[2] 27 | datev <- strsplit(datev, "[.]") %>% unlist 28 | datev <- datev[1] 29 | stratn <- stratn[1] 30 | # stratn <- strsplit(filen, "/") %>% unlist %>% tail(1) %>% strsplit("_") %>% unlist %>% head(1) 31 | stratn <- substr(stratn, 6, nchar(stratn)-3) 32 | 33 | # Load the PnLs array 34 | dframe <- read.csv(filen) 35 | dframe <- dframe[drop(dframe[, 1] > 0), ] 36 | datev <- as.POSIXct(dframe[, 1]/1e3, origin="1970-01-01", tz="America/New_York") 37 | pnls <- xts::xts(dframe[, -1], order.by=datev) 38 | ncols <- NCOL(pnls) 39 | pnls <- cbind(pnls, pnls[, ncols-1] + pnls[, ncols]) 40 | ncols <- NCOL(pnls) 41 | colnames(pnls)[ncols] <- "totalPnL" 42 | colv <- colnames(pnls) 43 | 44 | ``` 45 | 46 | ```{r blah, include=FALSE} 47 | print("This *Rmarkdown* document plots a *dygraph* plot of the PnLs array.") 48 | 49 | 50 | ``` 51 | 52 | 53 | 54 | ```{r shiny, echo=FALSE} 55 | shiny::fluidPage( 56 | shiny::fluidRow( 57 | # Input the column 1 name 58 | column(width=2, shiny::selectInput("col1", label="Column 1:", choices=colv, selected=colv[1])), 59 | # Input the column 2 name 60 | column(width=2, shiny::selectInput("col2", label="Column 2:", choices=colv, selected=colv[2])), 61 | ), # end fluidRow 62 | 63 | # Create output plot panel 64 | dygraphs::dygraphOutput("dyplot", width="90%", height="500px") 65 | 66 | ) # end fluidPage interface 67 | 68 | # Calculate the data 69 | datav <- shiny::reactive({ 70 | cat("Calculating the data\n") 71 | series1 <- get(input$col1, pnls) 72 | series2 <- get(input$col2, pnls) 73 | datav <- cbind(series1, series2) 74 | colnamev <- c(input$col1, input$col2) 75 | colnames(datav) <- colnamev 76 | datav 77 | }) # end reactive code 78 | 79 | 80 | output$dyplot <- dygraphs::renderDygraph({ 81 | datav <- datav() 82 | colnamev <- colnames(datav) 83 | # Plot the dygraph 84 | captiont <- paste("Strategy:", stratn, "/ Data for", colnamev[1], "and", colnamev[2]) 85 | 86 | if (colnamev[2] == "pricEMA") { 87 | dygraphs::dygraph(datav, main=captiont) %>% 88 | dyOptions(colors=c("blue", "red")) 89 | } else { 90 | dygraphs::dygraph(datav, main=captiont) %>% 91 | dyAxis("y", label=colnamev[1], independentTicks=TRUE) %>% 92 | dyAxis("y2", label=colnamev[2], independentTicks=TRUE) %>% 93 | dySeries(name=colnamev[1], axis="y", strokeWidth=1, col="blue") %>% 94 | dySeries(name=colnamev[2], axis="y2", strokeWidth=1, col="red") 95 | } # end if 96 | 97 | # dygraphs::dygraph(get(input$col1, pnls), width="80%", height="600px") 98 | }) # end renderDygraph 99 | ``` 100 | 101 | -------------------------------------------------------------------------------- /dygraphs_synchronization.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Synchronization" 3 | --- 4 | 5 | ```{r, include=FALSE} 6 | library(dygraphs) 7 | ``` 8 | 9 | ```{r, echo=FALSE,fig.height=2.0} 10 | dygraph(ldeaths, main = "All", group = "lung-deaths") 11 | dygraph(mdeaths, main = "Male", group = "lung-deaths") 12 | dygraph(fdeaths, main = "Female", group = "lung-deaths") 13 | ``` 14 | -------------------------------------------------------------------------------- /ensemble.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/ensemble.png -------------------------------------------------------------------------------- /equation_examples.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: Equation Examples in R Markdown 3 | author: Jerzy Pawlowski 4 | date: '`r format(Sys.time(), "%m/%d/%Y")`' 5 | output: html_document 6 | --- 7 | 8 | ## Getting started with equations 9 | 10 | We can write fractions: $\frac{2}{3}$. We can also handle things like estimated population growth rate, e.g., $\hat{\lambda}=1.02$. And, $\sqrt{4}=2$. 11 | 12 | $$\alpha, \beta, \gamma, \Gamma$$ 13 | 14 | $$a \pm b$$ 15 | $$x \ge 15$$ 16 | $$a_i \ge 0~~~\forall i$$ 17 | 18 | ## Linear Algebra 19 | 20 | A Matrix: 21 | 22 | $$A_{m,n} = 23 | \begin{pmatrix} 24 | a_{1,1} & a_{1,2} & \cdots & a_{1,n} \\ 25 | a_{2,1} & a_{2,2} & \cdots & a_{2,n} \\ 26 | \vdots & \vdots & \ddots & \vdots \\ 27 | a_{m,1} & a_{m,2} & \cdots & a_{m,n} 28 | \end{pmatrix}$$ 29 | 30 | 31 | 32 | The Cauchy-Schwarz Inequality: 33 | 34 | $$ 35 | \left( \sum_{k=1}^n a_k b_k \right)^2 36 | \leq 37 | \left( \sum_{k=1}^n a_k^2 \right) 38 | \left( \sum_{k=1}^n b_k^2 \right) 39 | $$ 40 | 41 | 42 | ## Statistics 43 | 44 | The binomial probability: $$f(y|N,p) = \frac{N!}{y!(N-y)!}\cdot p^y \cdot (1-p)^{N-y} = {{N}\choose{y}} \cdot p^y \cdot (1-p)^{N-y}$$ 45 | 46 | To calculate the **mean** of \textit{n} observations of variable \textit{x}, you can use: $$\bar{x} = \frac{1}{n} \sum_{i=1}^{n}x_{i}$$ 47 | 48 | Note that this equation looks quite nice above where it's in display math mode. It is more compact but not quite as nice looking if we present it using inline mode, e.g., $\bar{x} = \frac{1}{n} \sum_{i=1}^{n}x_{i}$. 49 | 50 | Let's do the same with the equation for **variance**. First the inline version, which is 51 | $\sigma^{2} = \frac{\sum\limits_{i=1}^{n} \left(x_{i} - \bar{x}\right)^{2}} {n-1}$. And then the display mode version: 52 | $$\sigma^{2} = \frac{\sum_{i=1}^{n} 53 | \left(x_{i} - \bar{x}\right)^{2}} 54 | {n-1}$$ 55 | 56 | And, finally, we'll end with the **standard deviation**. Here's the inline version, $\sigma = \sqrt{\frac{\sum\limits_{i=1}^{n} \left(x_{i} - \bar{x}\right)^{2}} {n-1}}$. And here's the display version. 57 | $$\sigma = \sqrt{\frac{\sum\limits_{i=1}^{n} \left(x_{i} - \bar{x}\right)^{2}} {n-1}}$$ 58 | 59 | There are helpful online editors - [check this one out](http://mathstat.uohyd.ernet.in/equationeditor/equationeditor.php) 60 | -------------------------------------------------------------------------------- /figure/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/.DS_Store -------------------------------------------------------------------------------- /figure/CDO.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/CDO.jpg -------------------------------------------------------------------------------- /figure/CDO2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/CDO2.jpg -------------------------------------------------------------------------------- /figure/EMA.mov: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/EMA.mov -------------------------------------------------------------------------------- /figure/EMA.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/EMA.mp4 -------------------------------------------------------------------------------- /figure/EMA_price_volatility.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/EMA_price_volatility.png -------------------------------------------------------------------------------- /figure/EMA_prices.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/EMA_prices.png -------------------------------------------------------------------------------- /figure/EMA_return_volatility.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/EMA_return_volatility.png -------------------------------------------------------------------------------- /figure/Jeremy_Clarkson_Linus_Torvalds.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/Jeremy_Clarkson_Linus_Torvalds.jpg -------------------------------------------------------------------------------- /figure/MT_Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/MT_Logo.png -------------------------------------------------------------------------------- /figure/MT_robot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/MT_robot.png -------------------------------------------------------------------------------- /figure/SMA_price_volatility.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/SMA_price_volatility.png -------------------------------------------------------------------------------- /figure/SMA_prices.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/SMA_prices.png -------------------------------------------------------------------------------- /figure/SMA_return_volatility.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/SMA_return_volatility.png -------------------------------------------------------------------------------- /figure/backtest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/backtest.png -------------------------------------------------------------------------------- /figure/bollinger_docs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/bollinger_docs.png -------------------------------------------------------------------------------- /figure/bolllinger_zscores.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/bolllinger_zscores.png -------------------------------------------------------------------------------- /figure/confirm_trades.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/confirm_trades.png -------------------------------------------------------------------------------- /figure/create_flow_variables.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/create_flow_variables.png -------------------------------------------------------------------------------- /figure/create_trade_tables_pairs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/create_trade_tables_pairs.png -------------------------------------------------------------------------------- /figure/data_queue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/data_queue.png -------------------------------------------------------------------------------- /figure/data_queueo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/data_queueo.png -------------------------------------------------------------------------------- /figure/download_trade_tables.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/download_trade_tables.png -------------------------------------------------------------------------------- /figure/ensemble.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/ensemble.png -------------------------------------------------------------------------------- /figure/erase_trade_tables.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/erase_trade_tables.png -------------------------------------------------------------------------------- /figure/get_price.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/get_price.png -------------------------------------------------------------------------------- /figure/initialize_flow_variables.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/initialize_flow_variables.png -------------------------------------------------------------------------------- /figure/initialize_parameters.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/initialize_parameters.png -------------------------------------------------------------------------------- /figure/initialize_prices.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/initialize_prices.png -------------------------------------------------------------------------------- /figure/initialize_technical_indicators.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/initialize_technical_indicators.png -------------------------------------------------------------------------------- /figure/intervals_rolling.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/intervals_rolling.png -------------------------------------------------------------------------------- /figure/liquidate_positions.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/liquidate_positions.png -------------------------------------------------------------------------------- /figure/long_short.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/long_short.png -------------------------------------------------------------------------------- /figure/mt_moving_average_price_volatility.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/mt_moving_average_price_volatility.png -------------------------------------------------------------------------------- /figure/mt_moving_average_price_volatilityo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/mt_moving_average_price_volatilityo.png -------------------------------------------------------------------------------- /figure/pair_docs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/pair_docs.png -------------------------------------------------------------------------------- /figure/pair_performance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/pair_performance.png -------------------------------------------------------------------------------- /figure/pair_xlkqqq.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/pair_xlkqqq.png -------------------------------------------------------------------------------- /figure/pair_zscores.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/pair_zscores.png -------------------------------------------------------------------------------- /figure/run_bollinger_strategy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/run_bollinger_strategy.png -------------------------------------------------------------------------------- /figure/run_pair_strategy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/run_pair_strategy.png -------------------------------------------------------------------------------- /figure/statarb_vti_svxy_vxx.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/statarb_vti_svxy_vxx.png -------------------------------------------------------------------------------- /figure/statarb_xlb_dbc_xle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/statarb_xlb_dbc_xle.png -------------------------------------------------------------------------------- /figure/telegram_alert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/telegram_alert.png -------------------------------------------------------------------------------- /figure/trade_manually.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/trade_manually.png -------------------------------------------------------------------------------- /figure/trend_following.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/trend_following.png -------------------------------------------------------------------------------- /figure/under_construction.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/under_construction.gif -------------------------------------------------------------------------------- /figure/update_technical_indicators.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/figure/update_technical_indicators.png -------------------------------------------------------------------------------- /first/app.R: -------------------------------------------------------------------------------- 1 | # 2 | # This is a Shiny web application. You can run the application by clicking 3 | # the 'Run App' button above. 4 | # 5 | # Find out more about building applications with Shiny here: 6 | # 7 | # http://shiny.rstudio.com/ 8 | # 9 | 10 | library(shiny) 11 | 12 | # Define UI for application that draws a histogram 13 | ui <- fluidPage( 14 | 15 | # Application title 16 | titlePanel("Old Faithful Geyser Data"), 17 | 18 | # Sidebar with a slider input for number of bins 19 | sidebarLayout( 20 | sidebarPanel( 21 | sliderInput("bins", 22 | "Number of bins:", 23 | min = 1, 24 | max = 50, 25 | value = 30) 26 | ), 27 | 28 | # Show a plot of the generated distribution 29 | mainPanel( 30 | plotOutput("distPlot") 31 | ) 32 | ) 33 | ) 34 | 35 | # Define server logic required to draw a histogram 36 | server <- function(input, output) { 37 | 38 | output$distPlot <- renderPlot({ 39 | # generate bins based on input$bins from ui.R 40 | x <- faithful[, 2] 41 | bins <- seq(min(x), max(x), length.out = input$bins + 1) 42 | 43 | # draw the histogram with the specified number of bins 44 | hist(x, breaks = bins, col = 'darkgray', border = 'white') 45 | }) 46 | } 47 | 48 | # Run the application 49 | shinyApp(ui = ui, server = server) 50 | 51 | -------------------------------------------------------------------------------- /image/CC_License.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/CC_License.png -------------------------------------------------------------------------------- /image/CRAN_Package.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/CRAN_Package.png -------------------------------------------------------------------------------- /image/CRAN_Package_old.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/CRAN_Package_old.png -------------------------------------------------------------------------------- /image/CRAN_Views.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/CRAN_Views.png -------------------------------------------------------------------------------- /image/GPLv3_Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/GPLv3_Logo.png -------------------------------------------------------------------------------- /image/MT2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/MT2.png -------------------------------------------------------------------------------- /image/MT4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/MT4.png -------------------------------------------------------------------------------- /image/MTLogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/MTLogo.png -------------------------------------------------------------------------------- /image/MTLogoLarge.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/MTLogoLarge.png -------------------------------------------------------------------------------- /image/RStudio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/RStudio.png -------------------------------------------------------------------------------- /image/RStudio_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/RStudio_logo.png -------------------------------------------------------------------------------- /image/Rlogo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/Rlogo.jpg -------------------------------------------------------------------------------- /image/Thumbs.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/Thumbs.db -------------------------------------------------------------------------------- /image/chi_squared.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/chi_squared.gif -------------------------------------------------------------------------------- /image/easy_button.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/easy_button.png -------------------------------------------------------------------------------- /image/engineering_long_color.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/engineering_long_color.png -------------------------------------------------------------------------------- /image/engineering_long_white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/engineering_long_white.png -------------------------------------------------------------------------------- /image/npp.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/npp.jpg -------------------------------------------------------------------------------- /image/olimpiada.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/olimpiada.png -------------------------------------------------------------------------------- /image/rstudio_debug.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/rstudio_debug.png -------------------------------------------------------------------------------- /image/smile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/smile.png -------------------------------------------------------------------------------- /image/smile_small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/smile_small.png -------------------------------------------------------------------------------- /image/splitapply.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/splitapply.png -------------------------------------------------------------------------------- /image/stack_exchange2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/stack_exchange2.png -------------------------------------------------------------------------------- /image/tandon_long_color.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/tandon_long_color.png -------------------------------------------------------------------------------- /image/tandon_stacked_color.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/tandon_stacked_color.png -------------------------------------------------------------------------------- /image/treasury_curve.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/image/treasury_curve.gif -------------------------------------------------------------------------------- /ioslides.css: -------------------------------------------------------------------------------- 1 | /* define logo dimensions */ 2 | .gdbar img { 3 | width: 500px !important; 4 | height: 100px !important; 5 | margin: 8px 8px; 6 | } 7 | 8 | /* define logo position */ 9 | .gdbar { 10 | width: 550px !important; 11 | height: 120px !important; 12 | } 13 | 14 | my_logo img { 15 | width: 50%; 16 | height: 100%; 17 | max-height: none; 18 | max-width: none; 19 | } 20 | 21 | slides > slide.backdrop { 22 | background: white; 23 | border-bottom: 0px; 24 | box-shadow: 0 0 0; 25 | } 26 | 27 | 28 | slides > slide { 29 | font-family: 'Open Sans', Helvetica, Arial, sans-serif; 30 | border-bottom: 3px solid #F66733; 31 | box-shadow: 0 3px 0 #522D80; 32 | 33 | } 34 | 35 | .title-slide hgroup h1 { 36 | color: #522D80; 37 | font-size: 48px; 38 | 39 | } 40 | 41 | .title-slide hgroup h2 { 42 | font-size: 28px; 43 | } 44 | 45 | 46 | h2 { 47 | 48 | color: #522D80; 49 | } 50 | 51 | slides > slide.dark { 52 | background: #522D80 !important; 53 | border-bottom: 0; 54 | box-shadow: 0 0 0; 55 | } 56 | 57 | .segue h2 { 58 | color: white; 59 | } 60 | 61 | slides > slide.title-slide { 62 | border-bottom: 0; 63 | box-shadow: 0 0 0; 64 | } 65 | 66 | ol, ul { 67 | 68 | padding-bottom: 10px; 69 | 70 | } 71 | 72 | slides > slide:not(.nobackground):before { 73 | font-size: 12pt; 74 | content: ""; 75 | position: absolute; 76 | bottom: 20px; 77 | left: 60px; 78 | background: no-repeat 0 50%; 79 | -webkit-background-size: 30px 30px; 80 | -moz-background-size: 30px 30px; 81 | -o-background-size: 30px 30px; 82 | background-size: 30px 30px; 83 | padding-left: 40px; 84 | height: 30px; 85 | line-height: 1.9; 86 | } 87 | -------------------------------------------------------------------------------- /ioslides_MachineTrader_files/figure-html/normal_dist_css-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/ioslides_MachineTrader_files/figure-html/normal_dist_css-1.png -------------------------------------------------------------------------------- /ioslides_example2.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: An Example R Markdown Document 3 | subtitle: (A Subtitle Would Go Here if This Were a Class) 4 | author: Steven V. Miller 5 | institute: Department of Political Science 6 | titlegraphic: image/MTLogoLarge.png 7 | fontsize: 10pt 8 | output: 9 | ioslides_presentation: 10 | widescreen: true 11 | smaller: true 12 | logo: image/MTLogoLarge.png 13 | css: ioslides.css 14 | beamer_presentation: 15 | template: image/MTLogoLarge.png 16 | keep_tex: true 17 | # toc: true 18 | slide_level: 2 19 | --- 20 | 21 | 22 | 23 | 24 | # Pop Songs and Political Science 25 | 26 | ## Sheena Easton and Game Theory 27 | 28 | Sheena Easton describes the following scenario for her baby: 29 | 30 | 1. Takes the morning train 31 | 2. Works from nine 'til five 32 | 3. Takes another train home again 33 | 4. Finds Sheena Easton waiting for him 34 | 35 | Sheena Easton and her baby are playing a **zero-sum (total conflict) game**. 36 | 37 | - Akin to Holmes-Moriarty game (see: von Neumann and Morgenstern) 38 | - Solution: **mixed strategy** 39 | 40 | ## Rick Astley's Re-election Platform 41 | 42 | Rick Astley's campaign promises: 43 | 44 | - Never gonna give you up. 45 | - Never gonna let you down. 46 | - Never gonna run around and desert you. 47 | - Never gonna make you cry. 48 | - Never gonna say goodbye. 49 | - Never gonna tell a lie and hurt you. 50 | 51 | Whereas these pledges conform to the preferences of the **median voter**, we expect Congressman Astley to secure re-election. 52 | 53 | ## Caribbean Queen and Operation Urgent Fury 54 | 55 | Billy Ocean released "Caribbean Queen" in 1984. 56 | 57 | - Emphasized sharing the same dream 58 | - Hearts beating as one 59 | 60 | "Caribbean Queen" is about the poor execution of Operation Urgent Fury. 61 | 62 | - Coordination problems plagued its execution from the start. 63 | - Echoed JCS chairman David Jones' frustrations with military establishment. 64 | 65 | Billy Ocean is advocating for what became the Goldwater-Nichols Act. 66 | 67 | - Wanted to take advantage of **economies of scale**, resolve **coordination problems** in U.S. military. 68 | 69 | ## The Good Day Hypothesis 70 | 71 | We know the following about Ice Cube's day. 72 | 73 | 1. The Lakers beat the Supersonics. 74 | 2. No helicopter looked for a murder. 75 | 3. Consumed Fatburger at 2 a.m. 76 | 4. Goodyear blimp: "Ice Cube's a pimp." 77 | 78 | This leads to two different hypotheses: 79 | 80 | - $H_0$: Ice Cube's day is statistically indistinguishable from a typical day. 81 | - $H1$: Ice Cube is having a good (i.e. greater than average) day. 82 | 83 | These hypotheses are tested using archival data of Ice Cube's life. 84 | 85 | # Example R code 86 | ## Example R stuff 87 | 88 | ```{r cars, echo = TRUE} 89 | summary(cars) 90 | ``` 91 | 92 | ## Slide with Plot 93 | 94 | ```{r pressure} 95 | plot(pressure) 96 | ``` 97 | 98 | ## ggplot code 99 | 100 | ```{r createdata, echo=TRUE, eval=FALSE} 101 | df <- data.frame(x = rnorm(1000)) 102 | x <- df$x 103 | base <- ggplot(df, aes(x)) + geom_density() + scale_x_continuous(limits = c(-5, 5)) 104 | base + stat_function(fun = dnorm, colour = "red") 105 | ``` 106 | 107 | 108 | ## Another Plot 109 | 110 | ```{r plotit, echo=FALSE} 111 | library(ggplot2) 112 | df <- data.frame(x = rnorm(1000)) 113 | x <- df$x 114 | base <- ggplot(df, aes(x)) + geom_density() + scale_x_continuous(limits = c(-5, 5)) 115 | base + stat_function(fun = dnorm, colour = "red") 116 | ``` -------------------------------------------------------------------------------- /ioslides_example_files/figure-html/normal_dist_css-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/ioslides_example_files/figure-html/normal_dist_css-1.png -------------------------------------------------------------------------------- /ioslides_shiny_cdo_tranche.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: Collateralized Debt Obligations 3 | author: Jerzy Pawlowski 4 | affiliation: NYU Tandon School of Engineering 5 | date: '`r format(Sys.Date(), "%m/%d/%Y")`' 6 | email: jp3900@nyu.edu 7 | css: slides.css 8 | output: 9 | ioslides_presentation: 10 | widescreen: true 11 | smaller: true 12 | transition: 0.1 13 | self_contained: true 14 | logo: image/tandon_long_color.png 15 | runtime: shiny 16 | --- 17 | 18 | ```{r setup, include=FALSE} 19 | # This is an R setup chunk, containing default options applied to all other chunks 20 | library(knitr) 21 | # This sets the chunk default options 22 | opts_chunk$set(cache=TRUE, collapse=TRUE, error=FALSE, prompt=TRUE) 23 | # This sets the chunk display theme 24 | knit_theme$set(knit_theme$get("acid")) 25 | # This sets some display options 26 | options(digits=3) 27 | options(width=80) 28 | ``` 29 | 30 | 31 | ## Collateralized Debt Obligations *CDOs* 32 | 33 | 34 |
35 | Collateralized Debt Obligations (cash CDOs) are securities (bonds) collateralized by other debt assets. 36 | The CDO assets can be debt instruments like bonds, loans, and mortgages. 37 | 38 | The CDO liabilities are CDO tranches, which receive cashflows from the CDO assets, and are exposed to their defaults. 39 | 40 | CDO tranches have an attachment point (subordination, i.e. the percentage of asset default losses at which the tranche starts absorbing those losses), and a detachment point when the tranche is wiped out (suffers 100% losses). 41 | 42 | The equity tranche is the most junior tranche, and is the first to absorb default losses. 43 | 44 |
45 | 46 |
47 | 48 | The mezzanine tranches are senior to the equity tranche and absorb losses ony after the equity tranche is wiped out. 49 | 50 | The senior tranche is the most senior tranche, and is the last to absorb losses. 51 | 52 | ![CDO](figure/CDO.jpg){width=70%} 53 | ![CDO2](figure/CDO2.jpg){width=70%} 54 | 55 |
56 | 57 | 58 | ## *shiny* Application for CDO tranche Losses 59 | 60 | This is an embedded external *shiny* application, for calculating CDO tranche losses under the Vasicek model. 61 | It uses the function shinyAppDir() which executes R code contained in the files ui.R and server.R, stored in the subdirectory shinyapp_cdo_tranche: 62 | 63 | ```{r, eval=TRUE, echo=FALSE, cache=FALSE} 64 | library(shiny) 65 | shinyAppDir( 66 | appDir="shinyapp_cdo_tranche", 67 | options=list(width="100%", height=400) 68 | ) # end shinyAppDir 69 | ``` 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /ioslides_treasury_yield_curve.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: An *ioslides* With Animated Yield Curve 3 | author: Your Name 4 | affiliation: NYU Tandon School of Engineering 5 | date: '`r format(Sys.time(), "%m/%d/%Y")`' 6 | email: jp3900@nyu.edu 7 | css: slides.css 8 | output: 9 | ioslides_presentation: 10 | widescreen: true 11 | smaller: true 12 | transition: 0.1 13 | self_contained: true 14 | logo: image/tandon_long_color.png 15 | --- 16 | 17 | ```{r setup, include=FALSE} 18 | # This is an R setup chunk, containing default options applied to all other chunks 19 | library(knitr) 20 | # This sets the chunk default options 21 | opts_chunk$set(cache=TRUE, collapse=TRUE, error=FALSE, prompt=TRUE, size="scriptsize") 22 | # This sets the chunk display theme 23 | knit_theme$set(knit_theme$get("acid")) 24 | # This sets some display options 25 | options(digits=3) 26 | options(width=80) 27 | ``` 28 | 29 | 30 | ## Animated *gif* of the Treasury Yield Curve 31 | 32 |
33 | 34 | The yield curve shape changes depending on the economic conditions: 35 | 36 | In recessions rates drop and the curve flattens, 37 | 38 | While in expansions rates rise and the curve steepens. 39 | 40 |
41 | 42 |
43 | 44 | ![](image/treasury_curve.gif) 45 | 46 |
47 | 48 | -------------------------------------------------------------------------------- /knitr_article_demo.Rnw: -------------------------------------------------------------------------------- 1 | % knitr demo of article document 2 | % Includes printing functions and making charts with captions and subcaptions 3 | 4 | % Define knitr options 5 | % !Rnw weave = knitr 6 | <>= 7 | library(knitr) 8 | # set global chunk options 9 | opts_chunk$set(comment=NA, fig.width=6, fig.height=6) 10 | opts_knit$set(use.highlight = TRUE) 11 | opts_chunk$set(highlight = TRUE) 12 | thm <- knit_theme$get("acid") 13 | knit_theme$set(thm) 14 | # opts_knit$set(out.format = "html") 15 | # opts_knit$set(...., highlight=FALSE) 16 | # render_html() 17 | @ 18 | 19 | 20 | % Define document options 21 | \documentclass[8pt]{article} 22 | % Uncover everything in a step-wise fashion 23 | % \beamerdefaultoverlayspecification{<+->} 24 | \usepackage[latin1]{inputenc} 25 | % \usepackage[T1]{fontenc} 26 | \usepackage{subcaption} 27 | \usepackage{color} 28 | \usepackage{hyperref} 29 | \usepackage{url} 30 | % \usepackage{enumerate} 31 | % \let\emph\textbf 32 | % \let\alert\textbf 33 | 34 | % \usetheme{AnnArbor} 35 | 36 | % Define colors for hyperlinks 37 | % \definecolor{links}{HTML}{2A1B81} 38 | % \hypersetup{colorlinks,linkcolor=,urlcolor=links} 39 | 40 | % \pagestyle{fancy} 41 | 42 | 43 | % Define function for pretty printing R functions 44 | <>= 45 | insert_fun = function(name) { 46 | read_chunk(lines = capture.output(dump(name, '')), labels = paste(name, 'source', sep = '-')) 47 | } 48 | @ 49 | 50 | \begin{document} 51 | 52 | % First slide 53 | \begin{frame} 54 | 55 | \textbf{Hello World!}\\ 56 | % \textsc{Hello World!}\\ 57 | \textit{Hello World!}\\ 58 | \color{red}{\emph{Hello World!}}\\ 59 | 60 | The value of $\pi$ is \Sexpr{pi}\\ 61 | You can also write inline expressions, e.g. $\pi=\Sexpr{pi}$, and \Sexpr{1.598673e8} is a big number. 62 | 63 | Download R program from CRAN (Comprehensive R Archive Network)\\ 64 | \url{http://cran.r-project.org}\\ 65 | 66 | \end{frame} 67 | 68 | \begin{frame}[fragile] 69 | <>= 70 | summary(cars) 71 | @ 72 | \end{frame} 73 | 74 | 75 | \begin{frame}[fragile] 76 | This example shows you how to separate the source and output boxes by injecting 77 | the \texttt{kframe} environments between them. 78 | 79 | <>= 80 | # modify the default chunk hook 81 | hook_chunk = knit_hooks$get('chunk') 82 | knit_hooks$set(chunk = function(x, options) { 83 | out = hook_chunk(x, options) 84 | gsub('(\\\\end\\{alltt\\})\\s*(\\\\begin\\{verbatim\\})', 85 | '\\1\\\\end{kframe}\\\\begin{kframe}\\2', out) 86 | }) 87 | @ 88 | 89 | But it's a hackish solution... 90 | \end{frame} 91 | 92 | This is ordinary printing: 93 | 94 | <>= 95 | fivenum 96 | @ 97 | 98 | We insert the source of fivenum into knitr and print it in the chunk fivenum-source: 99 | 100 | <>= 101 | insert_fun('fivenum') 102 | <>= 103 | @ 104 | 105 | 106 | % \lhead{}\chead{}\rhead{By \myurlshort{http://biostat.jhsph.edu/~lcollado/}{Jerzy Pawlowski}}\lfoot{}\cfoot{\thepage}\rfoot{\today} 107 | 108 | Here is a code chunk. 109 | 110 | <>= 111 | 1+1 112 | letters 113 | chartr('xie', 'XIE', c('xie yihui', 'Yihui Xie')) 114 | par(mar=c(4, 4, .2, .2)); plot(rnorm(100)) 115 | @ 116 | 117 | You can also write inline expressions, e.g. $\pi=\Sexpr{pi}$, and \Sexpr{1.598673e8} is a big number. 118 | 119 | You can include sub-figures using the \textbf{subcaption} package. For example, 120 | Figure \ref{fig:test} contains \ref{fig:test-a} and \ref{fig:test-b}. 121 | 122 | \begin{figure} 123 | % Chart1 124 | \begin{subfigure}{.5\textwidth} 125 | <>= 126 | plot(1:10) 127 | @ 128 | \caption{This is Figure a. \label{fig:test-a}} 129 | \end{subfigure} 130 | % Chart2 131 | \begin{subfigure}{.5\textwidth} 132 | <>= 133 | plot(rnorm(100)) 134 | @ 135 | \caption{This is Figure b. \label{fig:test-b}} 136 | \end{subfigure} 137 | \caption{This figure contains two subfigures. \label{fig:test}} 138 | 139 | \end{figure} 140 | 141 | 142 | \end{document} 143 | -------------------------------------------------------------------------------- /logfile.txt: -------------------------------------------------------------------------------- 1 | all FRE6811 files moved to own directory 2 | 3 | knitr_article_demo: knitr demo of generic article document 4 | 5 | knitr_presentation_demo: knitr demo of generic presentation (slideshow) document 6 | 7 | FRE6811_Lecture_1: First lecture in Beamer/knitr format 8 | 9 | -------------------------------------------------------------------------------- /long_short.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/long_short.png -------------------------------------------------------------------------------- /markdown_simple.md: -------------------------------------------------------------------------------- 1 | --- 2 | output: 3 | html_document: default 4 | pdf_document: default 5 | --- 6 | 7 | This page is 8 | ![](figure/under_construction.gif) 9 | 10 | 11 | Please visit my [algoquant GitHub page](https://github.com/algoquant) 12 | 13 | ## This is huge text 14 | 15 | ### This is large text 16 | 17 | #### This is small text 18 | 19 | 20 | quote: 21 | > Pardon my french 22 | 23 | *This text will be italic* 24 | **This text will be bold** 25 | **Everyone _must_ attend the meeting at 5 o'clock today.** 26 | 27 | lists: 28 | 29 | * Item 1 30 | * Item 2 31 | * Item 3 32 | 33 | 1. Item 1 34 | 2. Item 2 35 | 3. Item 3 36 | -------------------------------------------------------------------------------- /my_first.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | My First HTML 6 | 7 | 8 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | Written by Jon Doe.
28 | Visit us at:
29 | Example.com
30 | Box 564, Disneyland
31 | USA 32 |
33 | 34 | 35 | 36 |

This is a big blue heading

37 |

This is a smaller red heading with some blue text in it

38 |

This is an even smaller heading with lightblue background

39 |

This is a paragraph.

40 |

This is bold text.

41 |

This is strong text.

42 |

This is italic text.

43 |

This is emphasized text.

44 |

This is small text.

45 |

This is marked (highlighted) text.

46 |

This is quoted text.

47 | 48 | 49 | 50 |

Here is a quote: 51 |

This is quoted text
52 |

53 | 54 |

55 | This is another paragraph with courier text. 56 |

57 | 58 |
59 |

This is a block of text

60 |

London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.

61 |
62 | 63 |

This is text in a preserved tag, 
 64 | it displays in courier font,
 65 | and preserves line breaks,
 66 |   and  preserves   spacings  hey!
 67 | 

68 | 69 |

Coding Example:
70 | 71 | var person={ 72 | firstName:"John", 73 | lastName:"Doe", 74 | age:50, 75 | eyeColor:"blue" 76 | } 77 |

78 | 79 | 80 |

This is a paragraph with a web link: 81 | 82 | HTML tutorial 83 | 84 |

85 |
86 |

This is a paragraph with an image: 87 | can't find image 88 |

89 | 90 | 91 |

To open a file, select:
92 | File | Open...

93 | 94 |

This is some computer output:
95 | 96 | demo.example.com login: Apr 12 09:10:17 97 | Linux 2.6.10-grsec+gg3+e+fhs6b+nfs+gr0501+++p3+c4a+gr2b-reslog-v6.189 98 |
99 | R v3.1 100 |

101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /olimpiada_matematyczna.Rmd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/olimpiada_matematyczna.Rmd -------------------------------------------------------------------------------- /rhtml.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | My First HTML 6 | 7 | 8 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | Written by Jon Doe.
29 | Visit us at:
30 | Example.com
31 | Box 564, Disneyland
32 | USA 33 |
34 | 35 | 36 | 37 |

This is a big blue heading

38 |

This is a smaller red heading with some blue text in it

39 |

This is an even smaller heading with lightblue background

40 |

This is a paragraph.

41 |

This is bold text.

42 |

This is strong text.

43 |

This is italic text.

44 |

This is emphasized text.

45 |

This is small text.

46 |

This is marked (highlighted) text.

47 |

This is some important text.

48 |

This is quoted text.

49 | 50 | 51 | 52 |

Here is a quote: 53 |

This is quoted text
54 |

55 | 56 |

57 | This is another paragraph with courier text. 58 |

59 | 60 |
61 |

This is a block of text

62 |

London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.

63 |
64 | 65 |

This is text in a preserved tag, 
 66 | it displays in courier font,
 67 | and preserves line breaks,
 68 |   and  preserves   spacings  hey!
 69 | 

70 | 71 |

Coding Example:
72 | 73 | var person={ 74 | firstName:"John", 75 | lastName:"Doe", 76 | age:50, 77 | eyeColor:"blue" 78 | } 79 |

80 | 81 | 82 |

This is a paragraph with a web link: 83 | 84 | HTML tutorial 85 | 86 |

87 |
88 |

This is a paragraph with an image: 89 | can't find image 90 |

91 | 92 | 93 |

To open a file, select:
94 | File | Open...

95 | 96 |

This is some computer output:
97 | 98 | demo.example.com login: Apr 12 09:10:17 99 | Linux 2.6.10-grsec+gg3+e+fhs6b+nfs+gr0501+++p3+c4a+gr2b-reslog-v6.189 100 |
101 | R v3.1 102 |

103 | 104 | 105 | 106 | -------------------------------------------------------------------------------- /rmarkdown_example.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Example R markdown Document" 3 | author: "Jerzy Pawlowski" 4 | date: '`r format(Sys.time(), "%m/%d/%Y")`' 5 | output: html_document 6 | --- 7 | 8 | ```{r setup, include=FALSE} 9 | knitr::opts_chunk$set(echo=TRUE) 10 | 11 | # install package quantmod if it can't be loaded successfully 12 | if (!require("quantmod")) 13 | install.packages("quantmod") 14 | ``` 15 | 16 | ### R markdown 17 | 18 | This is an *R markdown* document. Markdown is a simple formatting syntax for authoring *HTML*, *pdf*, and *MS Word* documents. For more details on using *R markdown* see . 19 | 20 | One of the advantages of writing documents *R markdown* is that they can be compiled into *HTML* documents, which can incorporate interactive plots, 21 | 22 | You can read more about publishing documents using *R* here: 23 | https://algoquant.github.io/r,/markdown/2016/07/02/Publishing-documents-in-R/ 24 | 25 | 26 | You can read more about using *R* to create *HTML* documents with interactive plots here: 27 | https://algoquant.github.io/2016/07/05/Interactive-Plots-in-R/ 28 | 29 | 30 | You can read more markdown tutorials: 31 | http://daringfireball.net/projects/markdown/syntax 32 | https://guides.github.com/features/mastering-markdown/ 33 | http://markdown-guide.readthedocs.io/en/latest/basics.html 34 | 35 | Here are markdown cheatsheets: 36 | https://markdown-it.github.io/ 37 | https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet 38 | https://daringfireball.net/projects/markdown/ 39 | https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet 40 | 41 | This is a markdown interpreter: 42 | http://www.markitdown.net/markdown 43 | 44 | You can read more about R markdown: 45 | http://rmarkdown.rstudio.com/ 46 | https://guides.github.com/features/mastering-markdown/ 47 | 48 | 49 | ### The **knitr** package 50 | 51 | The main difference between *markdown* and *R markdown*, is that *R markdown* allows including *R* code chunks. 52 | 53 | Clicking the **knit** button in *RStudio*, compiles the *R markdown* document, including embedded *math formulas* and *R* code chunks, into the output document. 54 | 55 | Example of an *R* code chunk: 56 | 57 | ```{r cars} 58 | summary(cars) 59 | ``` 60 | 61 | 62 | ### Math formulas in *R markdown* documents 63 | 64 | Math formulas can also be embedded in *R markdown* documents. 65 | 66 | For example inline formulas: $\frac{2}{3}$, $\sqrt{b^2 - 4ac}$, and $\hat{\lambda}=1.02$. 67 | 68 | Or display formulas (the Cauchy-Schwarz inequality): 69 | 70 | $$ 71 | \left( \sum_{k=1}^n a_k b_k \right)^2 72 | \leq 73 | \left( \sum_{k=1}^n a_k^2 \right) 74 | \left( \sum_{k=1}^n b_k^2 \right) 75 | $$ 76 | 77 | 78 | 79 | 80 | ### Plots in *R markdown* documents 81 | 82 | Plots can also be embedded, for example: 83 | 84 | ```{r pressure, echo=FALSE} 85 | plot(pressure) 86 | ``` 87 | 88 | Note that the `echo = FALSE` parameter may be added to the code chunk to prevent printing of the *R* code that generated the plot. 89 | 90 | 91 | 92 | 93 | ### Dynamic *dygraphs* plots in *R markdown* documents 94 | 95 | *R markdown* allows including dynamic *dygraphs* plots if the output format is *HTML*. 96 | For example: 97 | 98 | ```{r dygraph, echo=TRUE} 99 | dygraphs::dygraph(log(Cl(rutils::etfenv$VTI)), main="VTI Stock Price (log)") 100 | ``` 101 | 102 | -------------------------------------------------------------------------------- /rmarkdown_tests.Rmd: -------------------------------------------------------------------------------- 1 | ################################################################## 2 | 3 | ################################################################## 4 | 5 | ################################################################## 6 | 7 | --- 8 | title: "Change size of output HTML file by reducing resolution of plot image" 9 | author: "My Name" 10 | date: "September 7, 2015" 11 | output: html_document 12 | --- 13 | 14 | ```{r} 15 | # load ggplot2 silently 16 | suppressWarnings(library(ggplot2)) 17 | # chunk option dev="svg" produces very large vector graphics files 18 | knitr::opts_chunk$set(dev="svg") 19 | # chunk option dev="png" is the default raster graphics format for HTML output 20 | knitr::opts_chunk$set(dev="png") 21 | ``` 22 | 23 | ```{r, dpi=36, out.width="600px", out.height="600px"} 24 | # chunk option dpi=72 is the default resolution 25 | set.seed(1) 26 | mydf <- data.frame(x=rnorm(5e4),y=rnorm(5e4)) 27 | ggplot(mydf, aes(x,y)) + geom_point(alpha=0.6) 28 | ``` 29 | 30 | ################################################################## 31 | 32 | ################################################################## 33 | 34 | ################################################################## 35 | 36 | --- 37 | title: "Create Markdown Heading From R Code Using Package pander" 38 | author: "John Doe" 39 | date: '`r format(Sys.time(), "%m/%d/%Y")`' 40 | output: html_document 41 | --- 42 | 43 | ```{r setup, include=FALSE} 44 | # This is an R setup chunk, containing default options applied to all other chunks 45 | library(knitr) 46 | knitr::opts_chunk$set(echo=TRUE, prompt=TRUE) 47 | # This sets the chunk display theme 48 | knit_theme$set(knit_theme$get("acid")) 49 | # This sets some display options 50 | options(digits=3) 51 | options(width=80) 52 | ``` 53 | 54 | #### `r 'This is a Heading Created by Inline R Code'` 55 | 56 | ```{r mt_cars, echo=(-(1:2)), results="asis"} 57 | # This chunk creates a dynamic markdown heading using pander 58 | suppressWarnings(library(pander, quietly=TRUE)) 59 | # Get number of rows to be displayed 60 | nrows <- sample(x=3:7, size=1) 61 | # Create dynamic heading using pander 62 | pandoc.header(paste("Here is", nrows, "rows of the 'mtcars' data frame"), level=4) 63 | head(mtcars, nrows) 64 | ``` 65 | -------------------------------------------------------------------------------- /rmarkdown_to_html_example.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: Publishing *pdf* Documents Using *R Markdown* 3 | author: Jerzy Pawlowski 4 | date: '`r format(Sys.time(), "%m/%d/%Y")`' 5 | output: html_document 6 | --- 7 | 8 | ```{r setup, include=FALSE} 9 | # This is an R setup chunk, containing default options applied to all other chunks 10 | knitr::opts_chunk$set(echo=TRUE) 11 | ``` 12 | 13 | ### *R Markdown* Documents 14 | 15 | This is a *pdf* file knitted from an *R Markdown* document. Markdown is a simple formatting language for publishing *HTML*, *pdf*, and *MS Word* documents. For more details on using *R Markdown* see this [**RStudio website**](http://rmarkdown.rstudio.com). 16 | 17 | Creating *pdf* files from *R Markdown* documents isn't difficult at all! 18 | ![easy](image/easy_button.png){width="30%"} 19 | 20 | 21 | ### Including *R* Code Chunks 22 | 23 | *R* code chunks can be embedded in *R Markdown* documents. They are automatically executed and their output is embedded in the output document. 24 | This is an *R* code chunk: 25 | 26 | ```{r mtcars, echo=TRUE} 27 | head(mtcars) 28 | ``` 29 | 30 | 31 | ### Including Math Formulas 32 | 33 | Math formulas can be written in *LaTeX*. For example, the Normal probability density function is given by: 34 | 35 | $$ 36 | P(x) = \frac{e^{-(x-\mu)^2/2\sigma^2}}{\sigma\sqrt{2 \pi}} 37 | $$ 38 | 39 | ### Including Plots 40 | 41 | You can also embed plots in *pdf* files, produced by *R* code chunks. For example, the *R* code chunk to plot the Normal probability density function: 42 | 43 | ```{r normal, echo=TRUE} 44 | xvar <- seq(-5, 7, length=100) 45 | yvar <- dnorm(xvar, mean=1.0, sd=2.0) 46 | plot(xvar, yvar, type="l", lty="solid", 47 | xlab="", ylab="") 48 | title(main="Normal Density Function", line=0.5) 49 | startd <- 3; endd <- 5 # set lower and upper bounds 50 | # set polygon base 51 | subv <- ((xvar >= startd) & (xvar <= endd)) 52 | polygon(c(startd, xvar[subv], endd), # draw polygon 53 | c(-1, yvar[subv], -1), col="red") 54 | ``` 55 | 56 | 57 | Note that the `echo = FALSE` parameter can be added to the code chunk to prevent printing of the *R* code that generated the plot. 58 | 59 | 60 | Hope that you enjoy using *R Markdown*! 61 | ![smiling_face](image//smile_small.png){width="30%"} 62 | 63 | -------------------------------------------------------------------------------- /rmarkdown_to_pdf_example.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: Publishing *pdf* Documents Using *R Markdown* 3 | author: Jerzy Pawlowski 4 | date: '`r format(Sys.time(), "%m/%d/%Y")`' 5 | # date: July 2, 2016 6 | output: pdf_document 7 | --- 8 | 9 | ```{r setup, include=FALSE} 10 | # This is an R setup chunk, containing default options applied to all other chunks 11 | knitr::opts_chunk$set(echo=TRUE) 12 | ``` 13 | 14 | ### *R Markdown* Documents 15 | 16 | This is a *pdf* file knitted from an *R Markdown* document. Markdown is a simple formatting language for publishing *HTML*, *pdf*, and *MS Word* documents. For more details on using *R Markdown* see this [**RStudio website**](http://rmarkdown.rstudio.com). 17 | 18 | Creating *pdf* files from *R Markdown* documents isn't difficult at all! 19 | ![easy](image/easy_button.png){width="30%"} 20 | 21 | 22 | ### Including *R* Code Chunks 23 | 24 | *R* code chunks can be embedded in *R Markdown* documents. They are automatically executed and their output is embedded in the output document. 25 | This is an *R* code chunk: 26 | 27 | ```{r mtcars, echo=TRUE} 28 | head(mtcars) 29 | ``` 30 | 31 | 32 | ### Including Math Formulas 33 | 34 | Math formulas can be written in *LaTeX*. For example, the Normal probability density function is given by: 35 | 36 | $$ 37 | P(x) = \frac{e^{-(x-\mu)^2/2\sigma^2}}{\sigma\sqrt{2 \pi}} 38 | $$ 39 | 40 | ### Including Plots 41 | 42 | You can also embed plots in *pdf* files, produced by *R* code chunks. For example, the *R* code chunk to plot the Normal probability density function: 43 | 44 | ```{r normal, echo=TRUE} 45 | xvar <- seq(-5, 7, length=100) 46 | yvar <- dnorm(xvar, mean=1.0, sd=2.0) 47 | plot(xvar, yvar, type="l", lty="solid", 48 | xlab="", ylab="") 49 | title(main="Normal Density Function", line=0.5) 50 | startd <- 3; endd <- 5 # set lower and upper bounds 51 | # set polygon base 52 | subv <- ((xvar >= startd) & (xvar <= endd)) 53 | polygon(c(startd, xvar[subv], endd), # draw polygon 54 | c(-1, yvar[subv], -1), col="red") 55 | ``` 56 | 57 | 58 | Note that the `echo = FALSE` parameter can be added to the code chunk to prevent printing of the *R* code that generated the plot. 59 | 60 | 61 | Hope that you enjoy using *R Markdown*! 62 | ![smiling_face](image//smile_small.png){width="30%"} 63 | 64 | -------------------------------------------------------------------------------- /rpresentation_simple.Rpres: -------------------------------------------------------------------------------- 1 | Simple R Presentation 2 | ======================================================== 3 | title: "Simple R Presentation" 4 | author: John Doe 5 | date: `r format(Sys.time(), "%m/%d/%Y")` 6 | width: 1900 7 | height: 1000 8 | 9 | ```{r setup, include=FALSE} 10 | # This is an R setup chunk, containing default options applied to all other chunks 11 | library(knitr) 12 | # This sets the chunk default options 13 | opts_chunk$set(cache=TRUE, collapse=TRUE, error=FALSE, prompt=TRUE) 14 | # This sets the chunk display theme 15 | knit_theme$set(knit_theme$get("acid")) 16 | # This sets some display options 17 | options(digits=3) 18 | options(width=80) 19 | ``` 20 | 21 | 22 | My First Slide 23 | ======================================================== 24 | Hello World! 25 | Creating Rpresentations isn't difficult at all! 26 | 27 | 28 | 29 | 30 | *** 31 | 32 | The Cauchy-Schwarz Inequality: 33 | 34 | $$ 35 | \left( \sum_{k=1}^n a_k b_k \right)^2 36 | \leq 37 | \left( \sum_{k=1}^n a_k^2 \right) 38 | \left( \sum_{k=1}^n b_k^2 \right) 39 | $$ 40 | 41 | 42 | 43 | Slide With R Code Chunk and Output in Two Columns 44 | ======================================================== 45 | 46 | First column contains simple R code that returns the summary of the cars data frame: 47 | ```{r, summ_cars, eval=FALSE, echo=TRUE, results="hold", size="tiny"} 48 | summary(cars) 49 | ``` 50 | 51 | *** 52 | 53 | Second column contains the output of the code in the first column: 54 | ```{r, summ_cars, eval=TRUE, echo=FALSE, size="tiny"} 55 | ``` 56 | 57 | 58 | 59 | Slide With Plot 60 | ======================================================== 61 | 62 | First column with R code: 63 | ```{r, plot_cars, eval=TRUE, echo=(-(1:1)), fig.show="hide"} 64 | par(cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5) 65 | plot(cars) 66 | ``` 67 | 68 | *** 69 | 70 | Second column with plot: 71 | ```{r, plot_cars, eval=TRUE, echo=FALSE, fig.width=10, fig.height=8} 72 | ``` 73 | 74 | 75 | 76 | Slide with Interactive 3d Surface Plot 77 | ======================================================== 78 | 79 | First column with R code: 80 | ```{r, rgl_surf3d, eval=FALSE, echo=TRUE, webgl=TRUE, fig.show="hide"} 81 | library(rgl) # load rgl 82 | knit_hooks$set(webgl=hook_webgl) 83 | # define function of two variables 84 | foo <- function(x, y) y*sin(x) 85 | # draw 3d surface plot of function 86 | persp3d(x=foo, xlim=c(-5, 5), ylim=c(-5, 5), col="green", axes=FALSE) 87 | ``` 88 | 89 | *** 90 | 91 | Second column with plot: 92 | ```{r, rgl_surf3d, eval=TRUE, echo=FALSE, webgl=TRUE, fig.width=10, fig.height=8} 93 | ``` 94 | 95 | -------------------------------------------------------------------------------- /rsconnect/documents/app_simple.R/shinyapps.io/algoquant/presentations.dcf: -------------------------------------------------------------------------------- 1 | name: presentations 2 | title: presentations 3 | username: 4 | account: algoquant 5 | server: shinyapps.io 6 | hostUrl: https://api.shinyapps.io/v1 7 | appId: 657560 8 | bundleId: 1827231 9 | url: https://algoquant.shinyapps.io/presentations/ 10 | when: 1548089138.7673 11 | asMultiple: FALSE 12 | asStatic: FALSE 13 | ignoredFiles: .gitattributes|.RData|2016-06-25-hello-world!.Rmd|2016-07-02-Publishing-documents-in-R.Rmd|2016-07-05-Interactive-Plots-in-R.Rmd|2016-07-09-unit-testing.Rmd|abstract.txt|app_calc_weights.R|app_cdo_tranche.R|app_credit_portfolio_loss.R|app_dygraphs.R|app_dygraphs2.R|app_market_making.R|app_roll_portf2.R|app_roll_portf3.R|app_roll_portf4.R|app_roll_portf5.R|app_roll_portf5o.R|app_roll_portf6.R|app_strategy_mean_revert - Copy.R|app_strategy_mean_revert.R|app_strategy_mean_revert2 - Copy.R|app_strategy_mean_revert2.R|app_strategy_mean_revert3.R|app_strategy_tech_indicators.R|backtest.png|bib_template.Rnw|change_output_HTML_file_size.html|cloud-computing.html|cloud-computing.Rmd|coinflipping.jpg|dygraphs_dashboard.html|dygraphs_dashboard.Rmd|dygraphs_synchronization.html|dygraphs_synchronization.Rmd|EARL_Boston_2015.Rnw|ensemble.png|equation_examples.html|equation_examples.Rmd|generic_rpresentation.md|generic_rpresentation.Rpres|history.Rhistory|HoExample4.Rnw|ioslides_example.html|ioslides_example.Rmd|ioslides_shiny_cdo_tranche.Rmd|ioslides_shiny_example.Rmd|ioslides_test.Rmd|Jerzy Pawlowski RFinance 2015.Rmd|Jerzy_Pawlowski_EARL_Boston_2015.pdf|Jerzy_Pawlowski_RFinance_2015.pdf|Jerzy_Pawlowski_RFinance_2015_abstract.pdf|Jerzy_Pawlowski_RFinance_2016.pdf|Jerzy_Pawlowski_RFinance_2016_abstract.pdf|Jerzy_Pawlowski_RFinance_2017.html|Jerzy_Pawlowski_RFinance_2017_abstract.pdf|knitr_article_demo.Rnw|knitr_presentation_demo.Rnw|logfile.txt|long_short.png|markdown_tests.html|markdown_tests.Rmd|multiple_coin_flips.html|multiple_coin_flips.Rmd|my_first.html|myfirstgit.md|Olimpiada_Matematyczna.pdf|olimpiada_matematyczna.Rmd|overlays.Rnw|R_Markdown_to_pdf_example.Rmd|README template.md|README.md|RFinance_2015.Rnw|RFinance_2015_abstract.pdf|RFinance_2015_abstract.Rnw|RFinance_2016.Rnw|RFinance_2016_abstract.Rnw|RFinance_2016_final.R|RFinance_2016_final.Rnw|RFinance_2017.html|RFinance_2017.Rmd|RFinance_2017_abstract.Rmd|RFinance_2017_notes.txt|rhtml.html|rpresentations.Rpres|select_manager.html|select_manager.Rmd|shiny_demo_html.Rmd|shiny_ewma_quantmod.Rmd|shiny_ewma2.Rmd|shiny_ioslides.html|shiny_ornstein_uhlenbeck.Rmd|shiny_static_betas.Rmd|shiny_static_betas_strategy.Rmd|simple_rpresentation.md|simple_rpresentation.Rpres|single_coin_flips.html|single_coin_flips.Rmd|slides.css|Sweave example.Rnw|temp.Rpres|test_flexdashboard.html|test_flexdashboard.Rmd|ToDoList.txt|trend_following.png|yield_curve_plotly.html|yield_curve_plotly.Rmd|first/app.R|ioslides_example_files/figure-html/normal_dist-1.png|ioslides_example_files/figure-html/normal_dist_css-1.png|shinyapp_cdo_tranche/server.R|shinyapp_cdo_tranche/ui.R|shinyapp_cdo_tranche/rsconnect/shinyapps.io/algoquant/normal_dist.dcf|shinyapp_cdo_tranche_assignment/server.R|shinyapp_cdo_tranche_assignment/ui.R|shinyapp_cdo_tranche_assignment/rsconnect/shinyapps.io/algoquant/normal_dist.dcf|figure|image|shiny|shiny_ioslides_cache 14 | -------------------------------------------------------------------------------- /rsconnect/documents/dygraphs_dashboard.Rmd/rpubs.com/rpubs/Document.dcf: -------------------------------------------------------------------------------- 1 | name: Document 2 | title: 3 | username: 4 | account: rpubs 5 | server: rpubs.com 6 | hostUrl: rpubs.com 7 | appId: https://api.rpubs.com/api/v1/document/313748/55c3b7516870466db40f047e0ad9d958 8 | bundleId: https://api.rpubs.com/api/v1/document/313748/55c3b7516870466db40f047e0ad9d958 9 | url: http://rpubs.com/publish/claim/313748/9b5f28a91987484cac9e256289c31f84 10 | when: 1506805889.53086 11 | -------------------------------------------------------------------------------- /rsconnect/documents/dygraphs_dashboard.Rmd/rpubs.com/rpubs/Publish Document.dcf: -------------------------------------------------------------------------------- 1 | name: Publish Document 2 | title: 3 | username: 4 | account: rpubs 5 | server: rpubs.com 6 | hostUrl: rpubs.com 7 | appId: https://api.rpubs.com/api/v1/document/313748/55c3b7516870466db40f047e0ad9d958 8 | bundleId: https://api.rpubs.com/api/v1/document/313748/55c3b7516870466db40f047e0ad9d958 9 | url: http://rpubs.com/jp3900/313748/edit 10 | when: 1506806040.40033 11 | -------------------------------------------------------------------------------- /select_manager.Rmd: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | --- 5 | title: "Identifying Investment Managers Who Possess Skill" 6 | author: "Jerzy Pawlowski" 7 | affiliation: NYU Tandon School of Engineering 8 | date: '`r format(Sys.time(), "%m/%d/%Y")`' 9 | email: jp3900@nyu.edu 10 | output: html_document 11 | --- 12 | 13 | ### Is it possible to identify managers who possess skill, based on their past returns? 14 | 15 | Can we identify the best manager, who possesses the most skill in producing returns in excess of others, by selecting the one with the best past returns? What is the probability of selecting the best manager, when we select the manager with the best past returns? 16 | 17 | The binomial coin flipping model can be adapted for identifying the best manager. 18 | Imagine two managers, one with skill, and the other without skill. 19 | The daily returns of both managers are binary: either positive $+1$ or negative $-1$. 20 | The returns of the manager without skill are random, with zero mean. 21 | The returns of the skilled manager are also random, but with a positive drift, so that she produces a positive daily return more often than a negative return. 22 | If the probability of a positive return is equal to $p > 0.5$, then the average daily return is equal to $(2*p-1)$, and the daily standard deviation is equal to $1$. 23 | The annual return is equal to $250*(2*p-1)$, while the annual standard deviation is equal to $\sqrt{250}$, and the annual Sharpe ratio is equal to $\sqrt{250}*(2p-1)$. 24 | 25 | 26 | ```{r eval=TRUE, echo=TRUE, fig.width=5.5, fig.height=3.5} 27 | # Sharpe ratio as function of daily probability 28 | # sharpe_ratio <- sqrt(250)*(2*probv-1) 29 | 30 | # Daily probability as function of Sharpe ratio 31 | sharpe_ratio <- 0.4 32 | probv <- (sharpe_ratio/sqrt(250)+1)/2 33 | 34 | # Calculate probability of selecting skilled manager. 35 | # Use normal approximation for the binomial coefficient. 36 | confi_dence <- function(nu_m, p1, p2) { 37 | if (p1^nu_m > 1e-10) 38 | binom1 <- choose(nu_m, 0:nu_m) * p1^(0:nu_m) * (1-p1)^(nu_m:0) 39 | else 40 | binom1 <- dnorm(0:nu_m, mean=nu_m*p1, sd=sqrt(nu_m*p1*(1-p1))) 41 | if (p2^nu_m > 1e-10) 42 | binom2 <- choose(nu_m, 0:nu_m) * p2^(0:nu_m) * (1-p2)^(nu_m:0) 43 | else 44 | binom2 <- dnorm(0:nu_m, mean=nu_m*p2, sd=sqrt(nu_m*p2*(1-p2))) 45 | cum_binom2 <- cumsum(binom2) 46 | cum_binom2 <- c(0, cum_binom2[-NROW(cum_binom2)]) 47 | sum(binom1 * (cum_binom2 + binom2/2)) 48 | } # end confi_dence 49 | 50 | # Probability of selecting skilled manager with 20 years of data 51 | confi_dence(20*250, probv, 0.5) 52 | 53 | # Annual probabilities of selecting skilled manager 54 | years <- 1:50 55 | probs <- sapply(250*years, confi_dence, p1=probv, p2=0.5) 56 | 57 | # Years of data needed to select the skilled manager, with 95% confidence 58 | num_years <- findInterval(0.95, probs) 59 | num_years 60 | 61 | # Load plotly 62 | suppressMessages(suppressWarnings(library(plotly))) 63 | # Create data frame 64 | datav <- data.frame(years=years, probs=probs) 65 | # Plot with plotly using pipes syntax 66 | datav %>% 67 | plot_ly(x=~years, y=~probs, type="scatter", mode="lines + markers", name="probability") %>% 68 | add_trace(x=range(years), y=0.95, mode="lines", line=list(color="red"), name="95% confidence") %>% 69 | add_trace(x=num_years, y=range(probs), mode="lines", line=list(color="green"), name=paste(num_years, "years")) %>% 70 | layout(title="Probability of selecting skilled manager", 71 | xaxis=list(title="years"), 72 | yaxis=list(title="probabilities"), 73 | legend=list(x=0.1, y=0.1)) 74 | ``` 75 | 76 | 77 | -------------------------------------------------------------------------------- /shiny/chart_series/server.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | library(quantmod) 3 | # Define server logic required to plot xts 4 | shinyServer(function(input, output) { 5 | # Expression that generates a histogram. The expression is 6 | # wrapped in a call to renderPlot to indicate that: 7 | # 1) It is "reactive" and therefore should be automatically 8 | # re-executed when inputs change 9 | # 2) Its output type is a plot 10 | output$custom_plot <- renderPlot({ 11 | # plot a Normal probability distribution 12 | chartSeries(input$x_ts, 13 | name=strsplit(names(input$x_ts)[1], split="[.]")[[1]][1], 14 | theme=chartTheme("white")) 15 | 16 | curve(expr=dnorm(x, mean=input$mean, sd=input$std_dev), type="l", 17 | xlim=c(-3, 3), 18 | xlab="", ylab="", lwd=2, col="blue") 19 | }) # end renderPlot 20 | }) # end shinyServer 21 | -------------------------------------------------------------------------------- /shiny/chart_series/ui.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | # Define UI for application that draws a histogram 3 | shinyUI(fluidPage( 4 | # application title 5 | titlePanel("Normal distribution"), 6 | # sidebar with a slider input for the std dev 7 | sidebarLayout( 8 | sidebarPanel( 9 | # slider input for the mean 10 | sliderInput(inputId="mean", 11 | label="mean:", 12 | min=-2.0, 13 | max=2.0, 14 | value=0.0, 15 | step=0.1), # end sliderInput 16 | # slider input for the std dev 17 | sliderInput(inputId="std_dev", 18 | label="std dev:", 19 | min=0.1, 20 | max=2.0, 21 | value=1.0) # end sliderInput 22 | ), # end sidebarPanel 23 | # Show a plot of the generated distribution 24 | mainPanel( 25 | plotOutput("custom_plot") 26 | ) # end mainPanel 27 | ) # end sidebarLayout 28 | )) # end shinyUI 29 | -------------------------------------------------------------------------------- /shiny/normal_dist/server.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | # Define server logic required to draw a plot 3 | shinyServer(function(input, output) { 4 | # Expression that generates a plot. The expression is 5 | # wrapped in a call to renderPlot to indicate that: 6 | # 1) It is "reactive" and therefore should be automatically 7 | # re-executed when inputs change 8 | # 2) Its output type is a plot 9 | output$distPlot <- renderPlot({ 10 | # plot a Normal probability distribution 11 | par(mar=c(3, 2, 0, 0), oma=c(0, 0, 0, 0)) 12 | curve(expr=dnorm(x, mean=input$mean, sd=input$std_dev), type="l", 13 | xlim=c(-4, 4), 14 | xlab="", ylab="", lwd=2, col="blue") 15 | }, height=300, width=500) # end renderPlot 16 | }) # end shinyServer 17 | -------------------------------------------------------------------------------- /shiny/normal_dist/ui.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | # Define UI for application that draws a histogram 3 | shinyUI(fluidPage( 4 | # application title 5 | titlePanel("Normal distribution"), 6 | # sidebar with a slider input for the std dev 7 | sidebarLayout( 8 | sidebarPanel( 9 | # slider input for the mean 10 | sliderInput(inputId="mean", 11 | label="mean:", 12 | min=-2.0, 13 | max=2.0, 14 | value=0.0, 15 | step=0.1), # end sliderInput 16 | # slider input for the std dev 17 | sliderInput(inputId="std_dev", 18 | label="std dev:", 19 | min=0.1, 20 | max=2.0, 21 | value=1.0) # end sliderInput 22 | ), # end sidebarPanel 23 | # Show a plot of the generated distribution 24 | mainPanel( 25 | plotOutput("distPlot")) # end mainPanel 26 | ) # end sidebarLayout 27 | )) # end shinyUI 28 | -------------------------------------------------------------------------------- /shiny/stockVis/helpers.R: -------------------------------------------------------------------------------- 1 | if (!exists(".inflation")) { 2 | .inflation <- getSymbols('CPIAUCNS', src = 'FRED', 3 | auto.assign = FALSE) 4 | } 5 | 6 | # adjusts yahoo finance data with the monthly consumer price index 7 | # values provided by the Federal Reserve of St. Louis 8 | # historical prices are returned in present values 9 | adjust <- function(data) { 10 | 11 | latestcpi <- last(.inflation)[[1]] 12 | inf.latest <- time(last(.inflation)) 13 | months <- split(data) 14 | 15 | adjust_month <- function(month) { 16 | date <- substr(min(time(month[1]), inf.latest), 1, 7) 17 | coredata(month) * latestcpi / .inflation[date][[1]] 18 | } 19 | 20 | adjs <- lapply(months, adjust_month) 21 | adj <- do.call("rbind", adjs) 22 | axts <- xts(adj, order.by = time(data)) 23 | axts[ , 5] <- Vo(data) 24 | axts 25 | } -------------------------------------------------------------------------------- /shiny/stockVis/server.R: -------------------------------------------------------------------------------- 1 | # server.R 2 | 3 | library(quantmod) 4 | # source("helpers.R") 5 | 6 | # Define server logic required to plot xts 7 | shinyServer(function(input, output) { 8 | 9 | output$plot <- renderPlot({ 10 | ran_ge <- paste(input$dates[1], input$dates[2], sep="/") 11 | chartSeries(get(input$sym_bol)[ran_ge], 12 | name=input$sym_bol, 13 | theme=chartTheme("white")) 14 | }) 15 | 16 | }) -------------------------------------------------------------------------------- /shiny/stockVis/ui.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | 3 | # Define UI for application that plots an xts 4 | shinyUI(fluidPage( 5 | titlePanel("chartSeries High Frequency Data"), 6 | 7 | sidebarLayout( 8 | sidebarPanel( 9 | helpText("Select a stock symbol to plot"), 10 | 11 | textInput(inputId="sym_bol", label="Symbol", value="SPY"), 12 | 13 | dateRangeInput("dates", 14 | "Date range", 15 | start="2013-01-01", 16 | end=as.character(Sys.Date())) 17 | ), 18 | 19 | mainPanel(plotOutput("plot")) 20 | ) 21 | )) -------------------------------------------------------------------------------- /shiny_demo_html.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "shiny_test" 3 | author: "Jerzy Pawlowski" 4 | affiliation: NYU Tandon School of Engineering 5 | date: '`r format(Sys.time(), "%m/%d/%Y")`' 6 | email: jp3900@nyu.edu 7 | output: html_document 8 | runtime: shiny 9 | --- 10 | 11 | ```{r setup, include=FALSE} 12 | knitr::opts_chunk$set(echo = TRUE) 13 | ``` 14 | 15 | This R Markdown document is made interactive using Shiny. Unlike the more traditional workflow of creating static reports, you can now create documents that allow your readers to change the assumptions underlying your analysis and see the results immediately. 16 | 17 | To learn more, see [Interactive Documents](http://rmarkdown.rstudio.com/authoring_shiny.html). 18 | 19 | ## Inputs and Outputs 20 | 21 | You can embed Shiny inputs and outputs in your document. Outputs are automatically updated whenever inputs change. This demonstrates how a standard R plot can be made interactive by wrapping it in the Shiny `renderPlot` function. The `selectInput` and `sliderInput` functions create the input widgets used to drive the plot. 22 | 23 | ```{r eruptions, echo=FALSE} 24 | inputPanel( 25 | selectInput("n_breaks", label = "Number of bins:", 26 | choices = c(10, 20, 35, 50), selected = 20), 27 | 28 | sliderInput("bw_adjust", label = "Bandwidth adjustment:", 29 | min = 0.2, max = 2, value = 1, step = 0.2) 30 | ) 31 | 32 | renderPlot({ 33 | hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks), 34 | xlab = "Duration (minutes)", main = "Geyser eruption duration") 35 | 36 | dens <- density(faithful$eruptions, adjust = input$bw_adjust) 37 | lines(dens, col = "blue") 38 | }) 39 | ``` 40 | 41 | ## Embedded Application 42 | 43 | It's also possible to embed an entire Shiny application within an R Markdown document using the `shinyAppDir` function. This example embeds a Shiny application located in another directory: 44 | 45 | ```{r tabsets, echo=FALSE} 46 | shinyAppDir( 47 | system.file("examples/06_tabsets", package = "shiny"), 48 | options = list( 49 | width = "100%", height = 550 50 | ) 51 | ) 52 | ``` 53 | 54 | Note the use of the `height` parameter to determine how much vertical space the embedded application should occupy. 55 | 56 | You can also use the `shinyApp` function to define an application inline rather then in an external directory. 57 | 58 | In all of R code chunks above the `echo = FALSE` attribute is used. This is to prevent the R code within the chunk from rendering in the document alongside the Shiny components. 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /shiny_ioslides_cache/html/__packages: -------------------------------------------------------------------------------- 1 | base 2 | shiny 3 | knitr 4 | dygraphs 5 | -------------------------------------------------------------------------------- /shiny_isolate_example.R: -------------------------------------------------------------------------------- 1 | # 2 | # This is a Shiny web application. 3 | # You can run the application by clicking the 'Run App' button above. 4 | # 5 | # Find out more about building applications with Shiny here: 6 | # http://shiny.rstudio.com/ 7 | # 8 | # Find out more about controlling Recalculation using isolate() here: 9 | # https://shiny.rstudio.com/articles/isolation.html 10 | 11 | 12 | ## Below is the setup code that runs once when the shiny app is started 13 | 14 | library(shiny) 15 | 16 | # Simulate random data 17 | datav <- rnorm(1e3) 18 | 19 | ## End setup code 20 | 21 | 22 | # Define user interface for application that draws a histogram 23 | uifun <- fluidPage( 24 | 25 | # Application title 26 | titlePanel("Example of Controlling Recalculation Using isolate()"), 27 | h4("The Shiny App simulates random data and plots a histogram."), 28 | h4("The number of histogram breaks can be specified by the user."), 29 | h4("The Shiny App Recalculates only after the user clicks the button 'Recalculate plot'."), 30 | 31 | # Sidebar with a slider input for number of bins 32 | sidebarLayout( 33 | sidebarPanel( 34 | sliderInput("n_bins", 35 | "Number of bins:", 36 | min=1, 37 | max=50, 38 | value=30), 39 | # The Shiny App is recalculated when the actionButton is clicked and the recalcb variable is updated 40 | h4("Click the button 'Recalculate plot' to Recalculate the Shiny App."), 41 | actionButton("recalcb", "Recalculate plot") 42 | ), 43 | 44 | # Show a plot of the generated distribution 45 | plotOutput("histp") 46 | 47 | ) # end sidebarLayout 48 | 49 | ) # end fluidPage 50 | 51 | # Define server code required to draw a histogram 52 | serv_er <- function(input, output) { 53 | 54 | # Plot the histogram of the simulated data 55 | output$histp <- shiny::renderPlot({ 56 | # isolate() prevents automatic Recalculation when n_bins is updated 57 | n_bins <- isolate(input$n_bins) 58 | # Model is recalculated when the recalcb variable is updated 59 | input$recalcb 60 | # Calculate breaks based on input$bins from ui.R 61 | break_s <- seq(min(datav), max(datav), length.out=n_bins+1) 62 | 63 | # Plot the histogram with the specified number of breaks 64 | hist(datav, breaks=break_s, col="darkgray", border="white", 65 | main="Histogram of random data") 66 | }) # end renderPlot 67 | 68 | } # end serv_er 69 | 70 | # Run the Shiny application 71 | shinyApp(ui=uifun, server=serv_er) 72 | 73 | -------------------------------------------------------------------------------- /shinyapp_cdo_tranche/rsconnect/shinyapps.io/algoquant/normal_dist.dcf: -------------------------------------------------------------------------------- 1 | name: normal_dist 2 | account: algoquant 3 | server: shinyapps.io 4 | bundleId: 253418 5 | url: https://algoquant.shinyapps.io/normal_dist 6 | when: 1440711198.43965 7 | -------------------------------------------------------------------------------- /shinyapp_cdo_tranche/ui.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | # Define UI for application that draws a histogram 3 | fluidPage( 4 | 5 | # Application title 6 | # titlePanel("Normal distribution"), 7 | sidebarLayout( 8 | # div(style="height: 10px;", 9 | sidebarPanel( 10 | # style = paste0("height: 50vh; overflow-y: auto;"), ##CHANGE 11 | # Slider inputs 12 | fluidRow( 13 | column(width=6, sliderInput("rho", label="Correlation:", min=0.0, max=0.9, value=0.2, step=0.01)), 14 | column(width=6, sliderInput("defprob", label="Default probability:", min=0.0, max=0.9, value=0.2, step=0.01))), 15 | fluidRow( 16 | column(width=6, sliderInput("lgd", label="Loss severity:", min=0.0, max=0.9, value=0.4, step=0.01)), 17 | column(width=6, sliderInput("attachp", label="Tranche attachment:", min=0.0, max=0.5, value=0.15, step=0.01))), 18 | fluidRow( 19 | column(width=6, sliderInput("detachp", label="Tranche detachment:", min=0.0, max=0.5, value=0.2, step=0.01))), 20 | height=4, width=4 21 | ), # end sidebarPanel 22 | 23 | # Render plot in panel 24 | mainPanel(plotOutput("plot_portf", width="100%", height=400)) 25 | ) # end sidebarLayout 26 | 27 | ) # end fluidPage 28 | -------------------------------------------------------------------------------- /shinyapp_cdo_tranche_assignment/rsconnect/shinyapps.io/algoquant/normal_dist.dcf: -------------------------------------------------------------------------------- 1 | name: normal_dist 2 | account: algoquant 3 | server: shinyapps.io 4 | bundleId: 253418 5 | url: https://algoquant.shinyapps.io/normal_dist 6 | when: 1440711198.43965 7 | -------------------------------------------------------------------------------- /shinyapp_cdo_tranche_assignment/server.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | # Define server logic required to draw a histogram 3 | function(input, output) { 4 | # Expression that generates a histogram. The expression is 5 | # wrapped in a call to renderPlot to indicate that: 6 | # 1) It is "reactive" and therefore should be automatically 7 | # re-executed when inputs change 8 | # 2) Its output type is a plot 9 | output$plo_t <- renderPlot({ 10 | # plot a Normal probability distribution 11 | curve(expr=dnorm(x, mean=input$mean, sd=input$std_dev), type="l", 12 | xlim=c(-3, 3), 13 | xlab="", ylab="", lwd=2, col="blue") 14 | }) # end renderPlot 15 | 16 | } # end server function 17 | -------------------------------------------------------------------------------- /shinyapp_cdo_tranche_assignment/ui.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | # Define UI for application that draws a histogram 3 | fluidPage( 4 | 5 | # application title 6 | titlePanel("Normal distribution"), 7 | # sidebar with a slider input for the std dev 8 | sidebarLayout( 9 | sidebarPanel( 10 | # slider input for the mean 11 | sliderInput(inputId="mean", label="mean:", min=-2.0, max=2.0, value=0.0, step=0.1), 12 | # slider input for the std dev 13 | sliderInput(inputId="std_dev", label="std dev:", min=0.1, max=2.0, value=1.0) 14 | ), # end sidebarPanel 15 | 16 | # Show a plot of the generated distribution 17 | mainPanel(plotOutput("plo_t")) 18 | ) # end sidebarLayout 19 | 20 | ) # end fluidPage 21 | -------------------------------------------------------------------------------- /single_coin_flips.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Number of Coin Flips Needed to Identify Biased Coin" 3 | author: "Jerzy Pawlowski" 4 | affiliation: NYU Tandon School of Engineering 5 | date: '`r format(Sys.time(), "%m/%d/%Y")`' 6 | email: jp3900@nyu.edu 7 | output: html_document 8 | --- 9 | 10 | ### How Many Coin Flips Are Needed to Decide if a Coin is Biased? 11 | 12 | You're given a coin, but you don't know if it's biased or not, so you flip it many times to see if it produces more heads than tails. You do know that the coin is either biased (with a 60% probability of heads), or that it's unbiased. You also know that the probability of getting either a biased or an unbiased coin is 50-50. 13 | 14 | Assume that you flip the coin $n$ times, and that you obtain $k$ heads. You decide if the coin is biased or not by comparing the two binomial probabilities of obtaining $k$ heads. If the probability of obtaining $k$ heads is greater for the biased coin, then you decide that it's biased, otherwise you decide that it's not biased. In each case there's a probability that you're making a mistake, purely by chance. The sum of those two probabilities is the probability that you're making a mistake and selecting the wrong coin. 15 | 16 | The probability of selecting the wrong coin depends on the number of coin flips, and decreases with more coin flips. The function $confi\_dence()$ calculates the probability of selecting the correct coin, as a function of the number of coin flips. 17 | 18 | ```{r eval=TRUE, echo=TRUE, fig.width=6, fig.height=5} 19 | # Calculate the probability of selecting the correct coin, as a function of the number of coin flips. 20 | confi_dence <- function(nu_m, probv=0.6) { 21 | # use normal approximation for the binomial coefficients. 22 | bi_nom <- dnorm(0:nu_m, mean=nu_m*probv, sd=sqrt(nu_m*probv*(1-probv))) 23 | bi_nom_even <- dnorm(0:nu_m, mean=0.5*nu_m, sd=sqrt(0.25*nu_m)) 24 | choos_e <- (bi_nom > bi_nom_even) 25 | 1 - 0.5*(sum(bi_nom[!choos_e]) + sum(bi_nom_even[choos_e])) 26 | } # end confi_dence 27 | 28 | # Calculate the probability of selecting the correct coin after 200 coin flips 29 | confi_dence(200, probv=0.6) 30 | 31 | # Calculate vector of probabilities of selecting the correct coin 32 | num_flips <- 250:270 33 | probs <- sapply(num_flips, confi_dence, probv=0.6) 34 | 35 | # Calculate the number of coin flips needed to select the correct coin, with 95% confidence 36 | min_num_flips <- num_flips[findInterval(0.95, probs)] 37 | min_num_flips 38 | 39 | # Plot vector of probabilities of selecting the correct coin 40 | # Load plotly 41 | suppressMessages(suppressWarnings(library(plotly))) 42 | # Create data frame 43 | datav <- data.frame(num_flips=num_flips, probs=probs) 44 | # Plot with plotly using pipes syntax 45 | datav %>% 46 | plot_ly(x=~num_flips, y=~probs, type="scatter", mode="lines + markers", name="probability") %>% 47 | add_trace(x=range(num_flips), y=0.95, mode="lines", line=list(color="red"), name="95% confidence") %>% 48 | add_trace(x=min_num_flips, y=range(probs), mode="lines", line=list(color="green"), name=paste(min_num_flips, "coin flips")) %>% 49 | layout(title="Number of Coin Flips Needed to Identify Biased Coin", 50 | xaxis=list(title="coin flips"), 51 | yaxis=list(title="probabilities"), 52 | legend=list(x=0.1, y=0.1)) 53 | ``` 54 | 55 | 56 | -------------------------------------------------------------------------------- /slides.css: -------------------------------------------------------------------------------- 1 | 2 | 3 | /** define logo layout **/ 4 | 5 | /* define logo dimensions */ 6 | .gdbar img { 7 | width: 300px !important; 8 | height: 50px !important; 9 | margin: 8px 8px; 10 | } 11 | 12 | /* define logo position */ 13 | .gdbar { 14 | width: 500px !important; 15 | height: 100px !important; 16 | } 17 | 18 | my_logo img { 19 | width: 50%; 20 | height: 100%; 21 | max-height: none; 22 | max-width: none; 23 | } 24 | 25 | /* define code chunk format */ 26 | pre { 27 | width: 100%; /* 106%; */ 28 | left: 0; /* -60px; */ 29 | padding: 10px 15px 10px 15px; /* 10px 0 10px 60px; */ 30 | } 31 | 32 | /** define footer format **/ 33 | slides > slide:not(.nobackground):before { 34 | width: 300px; 35 | height: 50px; 36 | background-size: 300px 50px; 37 | } 38 | 39 | /** define two-column layouts **/ 40 | 41 | .column_left_50 { 42 | float: left; 43 | width: 45%; 44 | text-align: left; 45 | } 46 | 47 | .column_right_50 { 48 | float: right; 49 | width: 48%; 50 | text-align: left; 51 | } 52 | 53 | .column_left_40 { 54 | float: left; 55 | width: 40%; 56 | text-align: left; 57 | } 58 | 59 | .column_right_60 { 60 | float: right; 61 | width: 59%; 62 | text-align: left; 63 | } 64 | 65 | .column_left_60 { 66 | float: left; 67 | width: 60%; 68 | text-align: left; 69 | } 70 | 71 | .column_right_40 { 72 | float: right; 73 | width: 40%; 74 | text-align: left; 75 | } 76 | -------------------------------------------------------------------------------- /strat_ema2.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Performance of Strategy with Two EWMAs" 3 | author_no_print: "Jerzy Pawlowski" 4 | affiliation: NYU Tandon School of Engineering 5 | date_no_print: '`r format(Sys.time(), "%m/%d/%Y")`' 6 | email: jp3900@nyu.edu 7 | output: html_document 8 | runtime: shiny 9 | --- 10 | 11 | ```{r setup, include=FALSE} 12 | knitr::opts_chunk$set(echo=TRUE) 13 | source("/Users/jerzy/Develop/lecture_slides/scripts/ewma_model.R") 14 | ``` 15 | 16 | ```{r ewma_model, echo=FALSE} 17 | inputPanel( 18 | sliderInput("lambda1", label="lambda1:", 19 | min=0.01, max=0.5, value=0.25, step=0.01), 20 | sliderInput("lambda2", label="lambda2:", 21 | min=0.01, max=0.5, value=0.05, step=0.01), 22 | numericInput("widthp", label="widthp:", min=10, max=201, value=51) 23 | ) # end inputPanel 24 | 25 | renderPlot({ 26 | 27 | lambda1 <- input$lambda1 28 | lambda2 <- input$lambda2 29 | widthp <- input$widthp 30 | 31 | library(HighFreq) # load package HighFreq 32 | # select OHLC data 33 | ohlc <- rutils::etfenv$VTI["/2011"] 34 | # calculate close prices 35 | closep <- Cl(ohlc) 36 | 37 | # simulate EWMA strategy 38 | ewma_strat <- simu_ewma2(ohlc=ohlc, lambda1=lambda1, lambda2=lambda2, widthp=widthp) 39 | 40 | # collect and combine output 41 | ewma1 <- ewma_strat[, "ewma1"] 42 | ewma2 <- ewma_strat[, "ewma2"] 43 | positions <- xts(ewma_strat[, "positions"], order.by=index(ohlc)) 44 | pnlv <- cumsum(ewma_strat[, "returns"]) 45 | pnlv <- cbind(closep-as.numeric(closep[1, ]), pnlv, ewma1, ewma2) 46 | colnames(pnlv) <- c("VTI", "EWMA PnL", "ewma1", "ewma2") 47 | returns <- rutils::diffxts(closep) 48 | sharper <- sqrt(260)*sum(returns)/sd(returns)/NROW(returns) 49 | returns <- ewma_strat[, "returns"] 50 | sharpewma <- sqrt(260)*sum(returns)/sd(returns)/NROW(returns) 51 | 52 | # plot EWMA strategy with custom line colors and position shading 53 | plot_theme <- chart_theme() 54 | plot_theme$col$line.col <- c("orange", "blue", "yellow", "magenta2") 55 | 56 | chobj <- chart_Series(pnlv, theme=plot_theme, 57 | name="Performance of Strategy with Two EWMAs") 58 | add_TA(positions > 0, on=-1, 59 | col="lightgreen", border="lightgreen") 60 | add_TA(positions < 0, on=-1, 61 | col="lightgrey", border="lightgrey") 62 | plot(chobj) 63 | legend("bottomleft", 64 | title=paste(c(paste0(colnames(pnlv)[1], " Sharpe ratio = ", format(sharper, digits=3)), 65 | paste0("strategy Sharpe ratio = ", format(sharpewma, digits=3))), 66 | collapse="\n"), 67 | legend=colnames(pnlv), 68 | inset=0.05, bg="white", lty=rep(1, 4), lwd=rep(8, 4), 69 | col=plot_theme$col$line.col, bty="n") 70 | 71 | }) # end renderPlot 72 | ``` 73 | -------------------------------------------------------------------------------- /strat_portf_static_copy.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app for calculating the returns of 3 | # a static portfolio of ETFs defined by the weights input 4 | # by the user. 5 | # Just press the "Run App" button on upper right of this panel. 6 | ############################## 7 | 8 | ## Below is the setup code that runs once when the shiny app is started 9 | 10 | # Load packages 11 | library(HighFreq) 12 | library(shiny) 13 | library(dygraphs) 14 | 15 | ## Model and data setup 16 | 17 | # Select ETFs 18 | # retv <- rutils::etfenv$returns 19 | # symbolv <- colnames(retv) 20 | # symbolv <- symbolv[!(symbolv %in% c("VXX", "SVXY", "MTUM", "IEF"))] 21 | symbolv <- c("VTI", "VXX", "SVXY") 22 | retv <- na.omit(rutils::etfenv$returns[, symbolv]) 23 | 24 | 25 | # End setup code 26 | 27 | 28 | ## Create elements of the user interface 29 | uifun <- shiny::fluidPage( 30 | titlePanel(paste("Static Portfolio of ETFs")), 31 | 32 | # Create single row with two slider inputs 33 | fluidRow( 34 | # Input weights 35 | column(width=2, sliderInput("weight1", label=paste0("Weight for ", symbolv[1], ":"), 36 | min=-2, max=2, value=1, step=0.1)), 37 | column(width=2, sliderInput("weight2", label=paste0("Weight for ", symbolv[2], ":"), 38 | min=-2, max=2, value=-2, step=0.1)), 39 | column(width=2, sliderInput("weight3", label=paste0("Weight for ", symbolv[3], ":"), 40 | min=-2, max=2, value=-2, step=0.1)) 41 | ), # end fluidRow 42 | 43 | # Create output plot panel 44 | mainPanel(dygraphs::dygraphOutput("dyplot"), width=12) 45 | ) # end fluidPage interface 46 | 47 | 48 | ## Define the server code 49 | servfun <- function(input, output) { 50 | 51 | # Recalculate the data and rerun the model 52 | pnls <- shiny::reactive({ 53 | # get model parameters from input argument 54 | weight1 <- input$weight1 55 | weight2 <- input$weight2 56 | weight3 <- input$weight3 57 | 58 | weights <- c(weight1, weight2, weight3) 59 | (retv %*% weights) 60 | }) # end reactive code 61 | 62 | # Return to output argument a dygraph plot with two y-axes 63 | output$dyplot <- dygraphs::renderDygraph({ 64 | pnls <- pnls() 65 | # Variance ratio 66 | # tre_nd <- HighFreq::calc_var_ag(pnls, lagg)/HighFreq::calc_var_ag(pnls)/lagg 67 | pnls <- xts::xts(cumsum(pnls), zoo::index(retv)) 68 | dygraphs::dygraph(pnls, main="Static Portfolio of ETFs") 69 | # colnamev <- colnames(pnls()) 70 | # dygraphs::dygraph(pnls(), main="ETF Portfolio Optimization") %>% 71 | # dyAxis("y", label=colnamev[1], independentTicks=TRUE) %>% 72 | # dyAxis("y2", label=colnamev[2], independentTicks=TRUE) %>% 73 | # dySeries(name=colnamev[1], axis="y", strokeWidth=1, col="red") %>% 74 | # dySeries(name=colnamev[2], axis="y2", strokeWidth=1, col="blue") 75 | }) # end output plot 76 | 77 | # output$dygraph <- dygraphs::renderDygraph({ 78 | # dygraph(pnls(), main="Rolling Portfolio Optimization Strategy") %>% 79 | # dySeries("strategy", label="strategy", strokeWidth=1, color="red") 80 | # }) # end output plot 81 | 82 | } # end server code 83 | 84 | ## Return a Shiny app object 85 | shiny::shinyApp(ui=uifun, server=servfun) 86 | -------------------------------------------------------------------------------- /strat_regres_spy.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Backtest of Contrarian SPY Strategy" 3 | author_no_print: "Jerzy Pawlowski" 4 | affiliation: NYU Tandon School of Engineering 5 | date_no_print: '`r format(Sys.time(), "%m/%d/%Y")`' 6 | email: jp3900@nyu.edu 7 | output: html_document 8 | runtime: shiny 9 | --- 10 | 11 | This is a shiny app with a backtest of a contrarian trading strategy for 1-minute SPY returns. 12 | 13 | The strategy calculates the z-scores from a rolling time series regression of 1-minute SPY returns against the time index, over a lookback period. 14 | 15 | The rolling z-scores are calculated using the RcppArmadillo function HighFreq::roll_zscores(). 16 | 17 | The strategy identifies an oversold signal if the z-score is less than minus the threshold value, and an overbought signal if the z-score is greater than the threshold value. 18 | 19 | The strategy trading rule is to buy (enter into a long position) if there is an oversold signal, and sell (enter a short position) if there is an overbought signal. 20 | 21 | Then hold the long or short position until the next signal arrives. 22 | 23 | The trading strategy has two parameters: the length of the lookback period and the threshold value. 24 | 25 | The shiny app allows choosing the values of the lookback and the threshold parameters, and plots the cumulative PnL of the trading strategy. 26 | 27 | 28 | ```{r setup, include=FALSE} 29 | # This is the R chunk setup code 30 | knitr::opts_chunk$set(echo=TRUE) 31 | library(HighFreq) # load package HighFreq 32 | # End R chunk setup code 33 | 34 | # Data setup code 35 | look_backs <- c(11, 111, 511, 1111, 5111) 36 | prices <- as.numeric(HighFreq::SPY[, "SPY.Close"]) 37 | returns <- rutils::diffit(HighFreq::SPY[, "SPY.Close"]) 38 | load("/Users/jerzy/Develop/R/data/zscores_spy.RData") 39 | 40 | # Define the strategy function 41 | run_strategy <- function(returns, zscores, threshold) { 42 | # Intitialize positions 43 | nrows <- NROW(returns) 44 | posv <- rep.int(NA_integer_, nrows) 45 | posv[1] <- 0 46 | # Handle signals 47 | bu_y <- (zscores < (-threshold)) 48 | posv[bu_y] <- 1 49 | se_ll <- (zscores > threshold) 50 | posv[se_ll] <- (-1) 51 | posv <- zoo::na.locf(posv) 52 | # Lag the positions by two periods 53 | posv <- rutils::lagit(posv, lagg=2) 54 | # Return strategy PnL 55 | cumsum(posv*returns) 56 | } # end run_strategy 57 | 58 | 59 | ### Run the initial z-score data setup below once ### 60 | # indeks <- matrix(.index(HighFreq::SPY), nc=1) 61 | # zscores <- lapply(look_backs, function(look_back) { 62 | # z_score <- HighFreq::roll_zscores(response=returns, predictor=indeks, look_back=look_back) 63 | # HighFreq::roll_scale(z_score, look_back=look_back, use_median=TRUE) 64 | # }) # end lapply 65 | # zscores <- rutils::do_call(cbind, zscores) 66 | # colnames(zscores) <- paste0("look_back=", look_backs) 67 | # zscores[which(!is.finite(zscores), arr.ind=TRUE)] <- 0 68 | # save(zscores, file="/Users/jerzy/Develop/R/data/zscores_spy.RData") 69 | ### End initial data setup ### 70 | ``` 71 | 72 | 73 | ```{r trading_strategy, echo=FALSE} 74 | # R chunk with shiny code 75 | 76 | # Define the input panel 77 | inputPanel( 78 | selectInput("look_back", label="lookback value:", 79 | choices=look_backs, selected=look_backs[4]), 80 | # actionButton("recalcb", "Recalculate z-scores"), 81 | sliderInput("threshold", label="threshold value:", 82 | min=0.01, max=5.0, value=0.5, step=0.01) 83 | ) # end inputPanel 84 | 85 | cat("Please Wait While Model is Running...\n") 86 | 87 | # Run the trading strategy and plot it 88 | renderPlot({ 89 | # Extract from input the strategy model parameters 90 | look_back <- paste0("look_back=", input$look_back) 91 | zscores <- subset(zscores, select=look_back) 92 | # threshold <- input$threshold*sum(abs(range(zscores)))/2 93 | threshold <- input$threshold 94 | 95 | # Run the trading strategy and plot it 96 | pnls <- run_strategy(returns, zscores, threshold)[endpoints(HighFreq::SPY, on="days")] 97 | chart_Series(pnls, name="Cumulative PnL of the Contrarian Strategy for 1-minute SPY Returns") 98 | 99 | }) # end renderPlot 100 | ``` 101 | -------------------------------------------------------------------------------- /strat_roll_portf.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app for simulating rolling portfolio 3 | # optimization strategies, which produces an interactive 4 | # dygraphs plot. 5 | # Just press the "Run App" button on upper right of this panel. 6 | ############################## 7 | 8 | ## Below is the setup code that runs once when the shiny app is started 9 | 10 | # Load packages 11 | library(shiny) 12 | library(dygraphs) 13 | library(rutils) 14 | 15 | # Model and data setup 16 | 17 | symbolv <- c("DBC", "IEF", "VTI", "XLB", "XLE", "XLF", "XLI", "XLK", "XLP", "XLU", "XLV", "XLY") 18 | nweights <- NROW(symbolv) 19 | retv <- rutils::etfenv$returns[, symbolv] 20 | retv <- zoo::na.locf(retv, na.rm=FALSE) 21 | retv <- zoo::na.locf(retv, fromLast=TRUE) 22 | # Calculate the vector of average daily excess returns. 23 | # riskf is the daily risk-free rate. 24 | riskf <- 0.03/260 25 | excess <- returns - riskf 26 | 27 | # Calculate equal weight portfolio 28 | # ncols <- NCOL(retv) 29 | indeks <- xts::xts(cumprod(1 + rowMeans(retv)), 30 | index(retv)) 31 | 32 | # Define endpoints 33 | endpoints <- rutils::calc_endpoints(retv, interval="months") 34 | endpoints <- endpoints[endpoints > 2*nweights] 35 | nrows <- NROW(endpoints) 36 | 37 | # End setup code 38 | 39 | 40 | ## Define elements of the UI user interface 41 | uiface <- shiny::shinyUI(fluidPage( 42 | 43 | titlePanel("Max Sharpe Strategy"), 44 | 45 | sidebarLayout( 46 | sidebarPanel( 47 | # Define lookb interval 48 | sliderInput("lookb", label="lookback interval (months):", 49 | min=2, max=30, value=6, step=1), 50 | sliderInput("dimax", label="dimax:", 51 | min=2, max=nweights, value=3, step=1), 52 | # Define the shrinkage intensity 53 | sliderInput("alpha", label="shrinkage intensity alpha:", 54 | min=0.01, max=0.99, value=0.5, step=0.05) 55 | ), 56 | mainPanel( 57 | dygraphOutput("dygraph") 58 | ) 59 | ) 60 | )) # end shinyUI interface 61 | 62 | 63 | ## Define the server code 64 | servfunc <- shiny::shinyServer(function(input, output) { 65 | 66 | # Re-calculate the data and rerun the model 67 | datav <- reactive({ 68 | # get model parameters from input 69 | lookb <- input$lookb 70 | dimax <- input$dimax 71 | alpha <- input$alpha 72 | # define startpoints 73 | startpoints <- c(rep_len(1, lookb-1), endpoints[1:(nrows-lookb+1)]) 74 | # rerun the model 75 | retp <- drop(HighFreq::back_test(excess=excess, 76 | returns=retv, 77 | startpoints=startpoints-1, 78 | endpoints=endpoints-1, 79 | alpha=alpha, 80 | dimax=dimax)) 81 | strat_rets <- cbind(indeks, 82 | cumprod(1 + retp)) 83 | colnames(strat_rets) <- c("equal_weight", "strat_rets") 84 | strat_rets 85 | }) # end reactive code 86 | 87 | # Create the output plot 88 | output$dygraph <- renderDygraph({ 89 | dygraph(datav(), main="Max Sharpe Strategy") %>% 90 | dyAxis("y", label="strat_rets", independentTicks=TRUE) %>% 91 | dyAxis("y2", label="equal_weight", independentTicks=TRUE) %>% 92 | dySeries(name="strat_rets", strokeWidth=1, axis="y", col="red") %>% 93 | dySeries(name="equal_weight", strokeWidth=1, axis="y2", col="blue") 94 | 95 | }) # end output plot 96 | 97 | }) # end server code 98 | 99 | ## Return a Shiny app object 100 | shiny::shinyApp(ui=uiface, server=servfunc) 101 | -------------------------------------------------------------------------------- /strat_static_betas.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Identify turning points from SPY_predictor data" 3 | author_no_print: "Jerzy Pawlowski" 4 | affiliation: NYU Tandon School of Engineering 5 | abstract: "Shiny app for trading rule: buy and hold for a fixed interval, and then revert to short, allows changing betas and plots cumulative PnL." 6 | date_no_print: '`r format(Sys.time(), "%m/%d/%Y")`' 7 | email: jp3900@nyu.edu 8 | output: html_document 9 | runtime: shiny 10 | --- 11 | 12 | ```{r setup, include=FALSE} 13 | knitr::opts_chunk$set(echo=TRUE) 14 | library(HighFreq) # load package HighFreq 15 | load("/Users/jerzy/Develop/data/SPY_predictor.RData") 16 | returns_running <- 60*HighFreq::run_returns(xtes=HighFreq::SPY) 17 | # colnames(returns_running) <- "returns" 18 | # rangev <- match(index(SPY_predictor["2009-03-10/2009-03-13"]), index(SPY_predictor)) 19 | # source("/Users/jerzy/Develop/R/scripts/ewma_model.R") 20 | ``` 21 | 22 | ```{r ewma_model, echo=FALSE} 23 | inputPanel( 24 | sliderInput("returns", label="returns:", 25 | min=-2.0, max=5.0, value=2.0, step=0.01), 26 | sliderInput("variance", label="variance:", 27 | min=-2.0, max=2.0, value=0.0, step=0.01), 28 | sliderInput("ske_w", label="skew:", 29 | min=-2.0, max=2.0, value=0.0, step=0.01), 30 | sliderInput("hu_rst", label="hurst:", 31 | min=-2.0, max=2.0, value=2.0, step=0.01), 32 | sliderInput("interval", label="interval:", 33 | min=1.0, max=200.0, value=60, step=1.0) 34 | ) # end inputPanel 35 | 36 | renderPlot({ 37 | 38 | returns <- input$returns 39 | variance <- input$variance 40 | ske_w <- input$ske_w 41 | hu_rst <- input$hu_rst 42 | interval <- input$interval 43 | 44 | betas <- c(returns, variance, ske_w, hu_rst) 45 | n_col <- NCOL(SPY_predictor) 46 | posv <- rep.int(NA, NROW(SPY_predictor)) 47 | posv[1] <- 0 48 | # buy signal 49 | bu_y <- (SPY_predictor %*% betas[1:n_col] < -1) 50 | posv[bu_y] <- 1.0 51 | se_ll <- as.logical(rutils::lagit(bu_y, lag=interval)) 52 | # sell signal 53 | posv[se_ll] <- -1.0 54 | posv[bu_y] <- 1.0 55 | posv <- zoo::na.locf(posv) 56 | # Lag the positions 57 | posv <- c(0, posv[-NROW(posv)]) 58 | # pnls <- posv*returns 59 | # betav <- (sum(pnls * returns) - sum(pnls) * sum(returns)) / (sum(pnls * pnls) - sum(pnls)^2 ) 60 | # -(exp(sum(pnls) - betav * sum(returns)) - 1) 61 | # -(exp(sum(posv*returns))-1) # / (sum(abs(rutils::diffit(posv))) / 2/ 1e5) / abs(sum(posv>0) - sum(posv<0)) 62 | # pnls <- xts(exp(cumsum((posv * returns_running)))-1, order.by=index(SPY_predictor)) 63 | chart_Series((exp(cumsum((posv * returns_running)))-1)[endpoints(SPY_predictor[, 1], on="days")], name="Backtest of static beta strategy for SPY") 64 | 65 | # plot(exp(cumsum((posv * returns_running)))-1, t="l", xlab="", ylab="") 66 | # chobj <- chart_Series(HighFreq::SPY[rangev, 4]) 67 | # plot(chobj) 68 | # abline(v=which(bu_y[rangev] < -1), col="red", lwd=1) 69 | 70 | }) # end renderPlot 71 | ``` 72 | -------------------------------------------------------------------------------- /strat_static_betas2.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Identify turning points from SPY_predictor data" 3 | author_no_print: "Jerzy Pawlowski" 4 | affiliation: NYU Tandon School of Engineering 5 | abstract: "Shiny app allows changing betas for a static betas strategy, and displays the buy signals." 6 | date_no_print: '`r format(Sys.time(), "%m/%d/%Y")`' 7 | email: jp3900@nyu.edu 8 | output: html_document 9 | runtime: shiny 10 | --- 11 | 12 | ```{r setup, include=FALSE} 13 | knitr::opts_chunk$set(echo=TRUE) 14 | library(HighFreq) # load package HighFreq 15 | load("/Users/jerzy/Develop/data/SPY_predictor.RData") 16 | # returns_running <- 60*HighFreq::run_returns(xtes=HighFreq::SPY) 17 | # colnames(returns_running) <- "returns" 18 | rangev <- match(index(SPY_predictor["2009-03-10/2009-03-13"]), index(SPY_predictor)) 19 | # source("/Users/jerzy/Develop/R/scripts/ewma_model.R") 20 | ``` 21 | 22 | ```{r ewma_model, echo=FALSE} 23 | inputPanel( 24 | sliderInput("returns", label="returns:", 25 | min=-1.0, max=1.0, value=0.0, step=0.01), 26 | sliderInput("variance", label="variance:", 27 | min=-1.0, max=1.0, value=0.0, step=0.01), 28 | sliderInput("skew", label="skew:", 29 | min=-1.0, max=1.0, value=0.25, step=0.01), 30 | sliderInput("hurst", label="hurst:", 31 | min=-1.0, max=1.0, value=-0.25, step=0.01) 32 | ) # end inputPanel 33 | 34 | renderPlot({ 35 | 36 | returns <- input$returns 37 | variance <- input$variance 38 | skew <- input$skew 39 | hurst <- input$hurst 40 | 41 | betas <- c(returns, variance, skew, hurst) 42 | bu_y <- xts(SPY_predictor %*% betas[1:NCOL(SPY_predictor)], order.by=index(SPY_predictor)) 43 | # se_ll <- xts(SPY_predictor %*% betas[(NCOL(SPY_predictor)+1):(2*NCOL(SPY_predictor))], order.by=index(SPY_predictor)) 44 | 45 | # plot(as.numeric(HighFreq::SPY[rangev, 4]), t="l", xlab="", ylab="") 46 | chobj <- chart_Series(HighFreq::SPY[rangev, 4]) 47 | plot(chobj) 48 | abline(v=which(bu_y[rangev] < -1), col="red", lwd=1) 49 | 50 | }) # end renderPlot 51 | ``` 52 | -------------------------------------------------------------------------------- /strat_tech_indicators.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app for simulating strategy using 3 | # static betas times OHLC technical indicators, with 4 | # dygraphs plot. 5 | # Just press the "Run App" button on upper right of this panel. 6 | ############################## 7 | 8 | ## Below is the setup code that runs once when the shiny app is started 9 | 10 | 11 | # load packages 12 | library(shiny) 13 | library(dygraphs) 14 | library(rutils) 15 | 16 | # Calculate indicator_s matrix of OHLC technical indicators 17 | source(file="/Users/jerzy/Develop/R/scripts/technical_indicators.R") 18 | 19 | # End setup code 20 | 21 | 22 | ## Create elements of the user interface 23 | uifun <- shiny::fluidPage( 24 | titlePanel("Strategy with Static Betas Times OHLC Technical Indicators"), 25 | 26 | # create single row with four slider inputs 27 | fluidRow( 28 | # input the returns beta 29 | column(width=4, sliderInput("beta_ret", label="returns beta:", 30 | min=-20.0, max=20.0, value=0.0, step=0.1)), 31 | # input the vol beta 32 | column(width=4, sliderInput("beta_vol", label="vol beta:", 33 | min=-20.0, max=20.0, value=20.0, step=0.1)), 34 | # input the skew beta 35 | column(width=4, sliderInput("betaskew", label="skew beta:", 36 | min=-20.0, max=20.0, value=-20.0, step=0.1)), 37 | # # input the momentum beta 38 | # column(width=4, sliderInput("betamoment", label="momentum beta:", 39 | # min=-5.0, max=5.0, value=-5.0, step=0.1)), 40 | # # input the openp-highp beta 41 | # column(width=4, sliderInput("beta_ophi", label="openp-highp beta:", 42 | # min=-5.0, max=5.0, value=-5.0, step=0.1)), 43 | # # input the closep-highp beta 44 | # column(width=4, sliderInput("beta_clhi", label="closep-highp beta:", 45 | # min=-5.0, max=5.0, value=-5.0, step=0.1)), 46 | # input the closep-highp beta 47 | column(width=4, sliderInput("beta_zscore", label="zscore beta:", 48 | min=-20.0, max=20.0, value=0.0, step=0.1)) 49 | ), # end fluidRow 50 | 51 | # create output plot panel 52 | mainPanel(dygraphs::dygraphOutput("dygraph"), width=12) 53 | ) # end fluidPage interface 54 | 55 | 56 | ## Define the server code 57 | servfun <- shiny::shinyServer(function(input, output) { 58 | 59 | # Recalculate the data and rerun the model 60 | datav <- shiny::reactive({ 61 | # get model parameters from input argument 62 | beta_ret <- input$beta_ret 63 | beta_vol <- input$beta_vol 64 | betaskew <- input$betaskew 65 | # betamoment <- input$betamoment 66 | # beta_ophi <- input$beta_ophi 67 | # beta_clhi <- input$beta_clhi 68 | beta_zscore <- input$beta_zscore 69 | weights <- c(beta_ret, beta_vol, betaskew, beta_zscore) 70 | # weights <- c(beta_ret, beta_vol, betaskew, betamoment, beta_ophi, beta_clhi) 71 | 72 | # simulate strategy 73 | score <- xts(indicator_s %*% weights, order.by=index(ohlc)) 74 | score <- rutils::lagit(score) 75 | pnls <- cumsum(score*retv) 76 | colnames(pnls) <- "strategy" 77 | pnls 78 | }) # end reactive code 79 | 80 | # return the dygraph plot to output argument 81 | output$dygraph <- dygraphs::renderDygraph({ 82 | dygraphs::dygraph(cbind(closep, datav()), main="OHLC Technicals Strategy") %>% 83 | dyAxis("y", label="VTI", independentTicks=TRUE) %>% 84 | dyAxis("y2", label="strategy", independentTicks=TRUE) %>% 85 | dySeries("strategy", axis="y2", col=c("blue", "red")) 86 | }) # end output plot 87 | 88 | }) # end server code 89 | 90 | ## Return a Shiny app object 91 | shiny::shinyApp(ui=uifun, server=servfun) 92 | -------------------------------------------------------------------------------- /strat_vwap_plot.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app for plotting a VWAP moving average. 3 | # Just press the "Run App" button on upper right of this panel. 4 | ############################## 5 | 6 | ## Below is the setup code that runs once when the shiny app is started 7 | 8 | ## Load packages 9 | library(HighFreq) 10 | library(shiny) 11 | library(dygraphs) 12 | 13 | 14 | ## Set up ETF data 15 | 16 | datenv <- rutils::etfenv 17 | symbolv <- get("symbolv", datenv) 18 | symbol <- "VTI" 19 | 20 | ## End setup code 21 | 22 | 23 | ## Create elements of the user interface 24 | uifun <- shiny::fluidPage( 25 | titlePanel("VWAP Moving Average"), 26 | 27 | # Create single row of widgets with two slider inputs 28 | fluidRow( 29 | # Input stock symbol 30 | column(width=2, selectInput("symbol", label="Symbol", 31 | choices=symbolv, selected=symbol)), 32 | # Input look-back interval 33 | column(width=2, sliderInput("lookb", label="Lookback interval", 34 | min=1, max=150, value=11, step=1)) 35 | ), # end fluidRow 36 | 37 | # Create output plot panel 38 | dygraphs::dygraphOutput("dyplot", width="90%", height="600px") 39 | 40 | ) # end fluidPage interface 41 | 42 | 43 | ## Define the server function 44 | servfun <- shiny::shinyServer(function(input, output) { 45 | 46 | # Get the close and volume data in a reactive environment 47 | closep <- shiny::reactive({ 48 | cat("Getting the close and volume data\n") 49 | # Get the data 50 | ohlc <- get(input$symbol, datenv) 51 | closep <- log(quantmod::Cl(ohlc)) 52 | volumes <- quantmod::Vo(ohlc) 53 | # Return the data 54 | cbind(closep, volumes) 55 | }) # end reactive code 56 | 57 | # Calculate the VWAP indicator in a reactive environment 58 | vwapv <- shiny::reactive({ 59 | cat("Calculating the VWAP indicator\n") 60 | # Get model parameters from input argument 61 | lookb <- input$lookb 62 | # Calculate the VWAP indicator 63 | closep <- closep()[, 1] 64 | volumes <- closep()[, 2] 65 | vwapv <- rutils::roll_sum(xtes=closep*volumes, lookb=lookb) 66 | volume_rolling <- rutils::roll_sum(xtes=volumes, lookb=lookb) 67 | vwapv <- ifelse(volume_rolling>0, vwapv/volume_rolling, 0) 68 | vwapv[is.na(vwapv)] <- 0 69 | # Return the plot data 70 | datav <- cbind(closep, vwapv) 71 | colnames(datav) <- c(input$symbol, "VWAP") 72 | datav 73 | }) # end reactive code 74 | 75 | # Return the dygraph plot to output argument 76 | output$dyplot <- dygraphs::renderDygraph({ 77 | cat("Plotting the dygraph\n") 78 | colnamev <- colnames(vwapv()) 79 | dygraphs::dygraph(vwapv(), main=paste(colnamev[1], "VWAP")) %>% 80 | dyAxis("y", label=colnamev[1], independentTicks=TRUE) %>% 81 | dyAxis("y2", label=colnamev[2], independentTicks=TRUE) %>% 82 | dySeries(name=colnamev[1], axis="y", strokeWidth=2, col="blue") %>% 83 | dySeries(name=colnamev[2], axis="y2", strokeWidth=2, col="red") 84 | }) # end output plot 85 | }) # end server code 86 | 87 | ## Return a Shiny app object 88 | shiny::shinyApp(ui=uifun, server=servfun) 89 | -------------------------------------------------------------------------------- /strat_zscore_plot.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # This is a shiny app for plotting an EMA moving average. 3 | # Just press the "Run App" button on upper right of this panel. 4 | ############################## 5 | 6 | ## Below is the setup code that runs once when the shiny app is started 7 | 8 | ## Load packages 9 | library(HighFreq) 10 | library(shiny) 11 | library(dygraphs) 12 | 13 | 14 | ## Set up ETF data 15 | 16 | datenv <- rutils::etfenv 17 | symbolv <- get("symbolv", datenv) 18 | symboln <- "VTI" 19 | 20 | ## End setup code 21 | 22 | 23 | ## Create elements of the user interface 24 | uifun <- shiny::fluidPage( 25 | titlePanel("VTI EMA Prices"), 26 | 27 | # Create single row of widgets with two slider inputs 28 | fluidRow( 29 | # Input stock symbol 30 | column(width=2, selectInput("symboln", label="Symbol", 31 | choices=symbolv, selected=symboln)), 32 | # Input look-back interval 33 | column(width=2, sliderInput("lambdaf", label="Lambda decay factor", 34 | min=0.5, max=0.99, value=0.9, step=0.01)) 35 | ), # end fluidRow 36 | 37 | # Create output plot panel 38 | dygraphs::dygraphOutput("dyplot", width="90%", height="600px") 39 | 40 | ) # end fluidPage interface 41 | 42 | 43 | ## Define the server function 44 | servfun <- shiny::shinyServer(function(input, output) { 45 | 46 | # Get the close prices in a reactive environment 47 | pricev <- shiny::reactive({ 48 | cat("Getting the close prices\n") 49 | # Get the data 50 | ohlc <- get(input$symboln, datenv) 51 | pricev <- log(quantmod::Cl(ohlc["2008/2009"])) 52 | # Return the data 53 | pricev 54 | }) # end reactive code 55 | 56 | # Calculate the EMA indicator in a reactive environment 57 | pricema <- shiny::reactive({ 58 | cat("Calculating the EMA indicator\n") 59 | # Get model parameters from input argument 60 | lambdaf <- input$lambdaf 61 | # Calculate EMA prices recursively using RcppArmadillo 62 | pricev <- pricev() 63 | zscores <- HighFreq::run_zscores(pricev, lambda=lambdaf) 64 | # pricema <- HighFreq::run_mean(pricev, lambda=lambdaf) 65 | # pricema[is.na(pricema)] <- 0 66 | # Return the plot data 67 | pricema <- cbind(pricev, zscores[, 1]) 68 | colnames(pricema) <- c(input$symboln, "EMA Prices") 69 | pricema 70 | }) # end reactive code 71 | 72 | # Return the dygraph plot to output argument 73 | output$dyplot <- dygraphs::renderDygraph({ 74 | cat("Plotting the dygraph\n") 75 | colnamev <- colnames(pricema()) 76 | dygraph(pricema(), main=paste(colnamev, collapse=" ")) %>% 77 | dySeries(name=colnamev[1], strokeWidth=2, color="blue") %>% 78 | dySeries(name=colnamev[2], strokeWidth=2, color="red") 79 | }) # end output plot 80 | }) # end server code 81 | 82 | ## Return a Shiny app object 83 | shiny::shinyApp(ui=uifun, server=servfun) 84 | -------------------------------------------------------------------------------- /temp.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "My First R Markdown Document" 3 | author: Jerzy Pawlowski 4 | date: '`r format(Sys.time(), "%m/%d/%Y")`' 5 | output: html_document 6 | --- 7 | 8 | ```{r setup, include=FALSE} 9 | knitr::opts_chunk$set(echo = TRUE) 10 | 11 | # install package quantmod if it can't be loaded successfully 12 | if (!require("quantmod")) 13 | install.packages("quantmod") 14 | ``` 15 | 16 | ### R Markdown 17 | This is an *R Markdown* document. Markdown is a simple formatting syntax for authoring *HTML*, *pdf*, and *MS Word* documents. For more details on using *R Markdown* see . 18 | 19 | One of the advantages of writing documents *R Markdown* is that they can be compiled into *HTML* documents, which can incorporate interactive plots, 20 | 21 | You can read more about publishing documents using *R* here: 22 | https://algoquant.github.io/r,/markdown/2016/07/02/Publishing-documents-in-R/ 23 | 24 | You can read more about using *R* to create *HTML* documents with interactive plots here: 25 | https://algoquant.github.io/2016/07/05/Interactive-Plots-in-R/ 26 | 27 | Clicking the **Knit** button in *RStudio*, compiles the *R Markdown* document, including embedded *math formulas* and *R* code chunks, into output documents. 28 | 29 | Example of an *R* code chunk: 30 | ```{r cars} 31 | summary(cars) 32 | ``` 33 | 34 | ### Plots in *R Markdown* documents 35 | 36 | Plots can also be embeded, for example: 37 | ```{r pressure, echo=FALSE} 38 | plot(pressure) 39 | ``` 40 | Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot. 41 | 42 | ### Math formulas in *R Markdown* documents 43 | Math formulas can also be embeded in *R Markdown* documents. 44 | 45 | For example inline formulas: $\frac{2}{3}$, $\sqrt{b^2 - 4ac}$, and $\hat{\lambda}=1.02$. 46 | Or display formulas (the Cauchy-Schwarz inequality): 47 | 48 | $$ 49 | \left( \sum_{k=1}^n a_k b_k \right)^2 50 | \leq 51 | \left( \sum_{k=1}^n a_k^2 \right) 52 | \left( \sum_{k=1}^n b_k^2 \right) 53 | $$ 54 | 55 | -------------------------------------------------------------------------------- /test_flexdashboard.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "My first flexdashboard document" 3 | author: "Jerzy Pawlowski, NYU Tandon School of Engineering" 4 | email: jp3900@nyu.edu 5 | affiliation: NYU Tandon School of Engineering 6 | abstract: My first flexdashboard document 7 | date: '`r format(Sys.time(), "%m/%d/%Y")`' 8 | output: 9 | flexdashboard::flex_dashboard: 10 | orientation: columns 11 | vertical_layout: fill 12 | source_code: embed 13 | --- 14 | 15 | ```{r setup, include=FALSE} 16 | # This is an R setup chunk, containing default options applied to all other chunks 17 | library(flexdashboard) 18 | ``` 19 | 20 | Page 1 21 | ===================================== 22 | 23 | Column {data-width=500} 24 | ----------------------------------------------------------------------- 25 | 26 | ### This is the first page 27 | 28 | This is a very simple example of a flexdashboard document, with text on the left, and *R* code chunks and plots on the right. 29 | 30 | 31 | Column {data-width=500} 32 | ----------------------------------------------------------------------- 33 | 34 | ### The data frame *mtcars* 35 | 36 | ```{r, eval=TRUE, echo=TRUE} 37 | head(mtcars) 38 | ``` 39 | 40 | 41 | ### Plot of data frame *cars* 42 | 43 | ```{r, eval=TRUE, echo=TRUE} 44 | plot(cars) 45 | ``` 46 | 47 | 48 | Page 2 49 | ===================================== 50 | 51 | Column {data-width=500} 52 | ----------------------------------------------------------------------- 53 | 54 | ### This is the second page 55 | 56 | The data frame *nhtemp* contains New Haven temperatures 57 | 58 | ```{r, eval=TRUE, echo=TRUE} 59 | head(mtcars) 60 | ``` 61 | 62 | Column {data-width=500} 63 | ----------------------------------------------------------------------- 64 | 65 | ### dygraph plot of data frame *nhtemp* containing New Haven temperatures 66 | 67 | ```{r, eval=TRUE, echo=TRUE} 68 | library(dygraphs) 69 | dygraph(nhtemp, main = "New Haven Temperatures") %>% 70 | dyRangeSelector(dateWindow = c("1920-01-01", "1960-01-01")) 71 | ``` 72 | 73 | -------------------------------------------------------------------------------- /test_fun.cpp: -------------------------------------------------------------------------------- 1 | //////////////////////////// 2 | // Rcpp functions needed for shiny apps 3 | //////////////////////////// 4 | 5 | // Compile this file in R by running this command: 6 | // Rcpp::sourceCpp(file="/Users/jerzy/Develop/Presentations/test_fun.cpp") 7 | 8 | // [[Rcpp::depends(RcppArmadillo)]] 9 | #include 10 | #include 11 | using namespace arma; 12 | // Use STL 13 | using namespace std; 14 | 15 | 16 | // This is an old version of run_reg() from 2022-02-09 17 | // Used in app_runreg_daily_strat.R 18 | // [[Rcpp::export]] 19 | arma::mat run_reg_20220209(const arma::mat& response, 20 | const arma::mat& predictor, 21 | double lambda, 22 | std::string method = "none") { 23 | 24 | arma::uword num_rows = predictor.n_rows; 25 | arma::uword num_cols = predictor.n_cols; 26 | arma::mat means_resp = arma::zeros(num_rows, 1); 27 | arma::mat means_pred = arma::zeros(num_rows, num_cols); 28 | arma::mat vars = arma::square(predictor); 29 | arma::mat covars = arma::zeros(num_rows, num_cols); 30 | arma::mat betas = arma::zeros(num_rows, num_cols); 31 | arma::mat alphas = arma::zeros(num_rows, 1); 32 | arma::mat resids = arma::zeros(num_rows, 1); 33 | arma::mat varz = arma::ones(num_rows, 1); 34 | arma::mat meanz = arma::zeros(num_rows, 1); 35 | double lambda1 = 1-lambda; 36 | 37 | // Perform loop over the rows 38 | means_resp.row(0) = response.row(0); 39 | means_pred.row(0) = predictor.row(0); 40 | for (arma::uword it = 1; it < num_rows; it++) { 41 | // Calculate the mean as the weighted sum 42 | means_resp.row(it) = lambda1*response.row(it) + lambda*means_resp.row(it-1); 43 | means_pred.row(it) = lambda1*predictor.row(it) + lambda*means_pred.row(it-1); 44 | // cout << "Calculating vars: " << it << endl; 45 | vars.row(it) = lambda1*arma::square(predictor.row(it)-means_pred.row(it)) + lambda*vars.row(it-1); 46 | // cout << "Calculating covars: " << it << endl; 47 | covars.row(it) = lambda1*((response.row(it)-means_resp.row(it))*(predictor.row(it)-means_pred.row(it))) + lambda*covars.row(it-1); 48 | // cout << "Calculating betas: " << it << endl; 49 | // Calculate the alphas and betas. 50 | betas.row(it) = lambda1*covars.row(it)/vars.row(it) + lambda*betas.row(it-1); 51 | alphas.row(it) = lambda1*(means_resp.row(it) - arma::dot(betas.row(it), means_pred.row(it))) + lambda*alphas.row(it-1); 52 | // cout << "Calculating resids: " << it << endl; 53 | // Calculate the residuals. 54 | resids.row(it) = lambda1*(response.row(it) - arma::dot(betas.row(it), predictor.row(it))) + lambda*resids.row(it-1); 55 | // Calculate the mean and variance of the residuals. 56 | meanz.row(it) = lambda1*resids.row(it) + lambda*meanz.row(it-1); 57 | varz.row(it) = lambda1*arma::square(resids.row(it) - meanz.row(it)) + lambda*varz.row(it-1); 58 | } // end for 59 | 60 | if (method == "scale") { 61 | // Divide the residuals by their volatility 62 | resids = resids/sqrt(varz); 63 | } else if (method == "standardize") { 64 | // De-mean the residuals and divide them by their volatility 65 | resids = (resids - meanz)/sqrt(varz); 66 | } // end if 67 | 68 | return join_rows(resids, alphas, betas); 69 | 70 | } // end run_reg_20220209 71 | 72 | 73 | -------------------------------------------------------------------------------- /trend_following.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algoquant/presentations/2a32cfa3ea4bcdd5db741e475e1482ab72b183ad/trend_following.png --------------------------------------------------------------------------------