- Notifications
You must be signed in to change notification settings - Fork25
all functions and scripts of the lazy trade educational project on udemy
License
Unknown, MIT licenses found
Licenses found
vzhomeexperiments/lazytrade
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
The goal of lazytrade is to keep all functions and scripts of thelazytrade educational project onUDEMY.Functions are providing an opportunity to learn Computer and DataScience using example of Algorithmic Trading. Please kindly not thatthis project was created for Educational Purposes only!
You can install the released version of lazytrade fromCRAN with:
install.packages("lazytrade")And the development version fromGitHub with:
# install.packages("devtools")devtools::install_github("vzhomeexperiments/lazytrade")
- Data manipulation and analysis of performed trades results
- Reinforcement Learning for Automated Trading Risk Management
- Data manipulation and preparation for Machine Learning (transposing,aggregation, lagging, etc)
- Using Deep Learning for prediction of Market Types (Classification)
- Using Deep Learning for prediction of future price change (Regression)
- Strategy Tests simulations
- Utility functions to generate passwords, initialization files,encryption of passwords, etc
- Explored idea of building a model using random structures combinedwith an automated functional (strategy) test to improve modelperformance
- Overall, all functions have working examples with relevant documentedsample data included in the package
This is a basic example which shows you how to solve a common problem:
library(lazytrade)library(magrittr,warn.conflicts=FALSE)## basic example code# Convert a time series vector to matrix with 64 columnsmacd_m<- seq(1:1000) %>% as.data.frame() %>% to_m(20)head(macd_m,2)#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]#> [1,] 1 2 3 4 5 6 7 8 9 10 11 12 13 14#> [2,] 21 22 23 24 25 26 27 28 29 30 31 32 33 34#> [,15] [,16] [,17] [,18] [,19] [,20]#> [1,] 15 16 17 18 19 20#> [2,] 35 36 37 38 39 40
Why is it useful? It is possible to convert time-series data into matrixdata to do make modeling
Multiple log files could be joined into one data object
library(lazytrade)library(readr)library(dplyr)#>#> Attaching package: 'dplyr'#> The following objects are masked from 'package:stats':#>#> filter, lag#> The following objects are masked from 'package:base':#>#> intersect, setdiff, setequal, unionlibrary(magrittr)library(lubridate)#>#> Attaching package: 'lubridate'#> The following objects are masked from 'package:base':#>#> date, intersect, setdiff, union# files are located in the sample foldersDFOLDER<- system.file("extdata/RES",package="lazytrade")DFR<- opt_aggregate_results(path_data=DFOLDER)
This data object can be visualized
library(ggplot2)opt_create_graphs(x=DFR,outp_path=dir,graph_type='bars')
Or just visualize results with time-series plot
opt_create_graphs(x=DFR,outp_path=dir,graph_type='ts')
Example below would generate RL policy based on the trade resultsachieved so far
library(dplyr)library(ReinforcementLearning)library(magrittr)data(data_trades)states<- c("tradewin","tradeloss")actions<- c("ON","OFF")control<-list(alpha=0.7,gamma=0.3,epsilon=0.1)rl_generate_policy(data_trades,states,actions,control)#> TradeState Policy#> tradeloss tradeloss ON#> tradewin tradewin OFF
Multiple trading accounts require passwords, package contains functionthat may easily generate random passwords:
library(lazytrade)library(stringr)library(magrittr)library(openssl)library(readr)#generate 8digit password for trading platformutil_generate_password(salt='random text')#> .#> 1 ac5cE049
Facilitate generation of initialisation files:
library(lazytrade)dir<- normalizePath(tempdir(),winslash="/")# test file to launch MT4 terminal with parameterswrite_ini_file(mt4_Profile="Default",mt4_Login="12345678",mt4_Password="password",mt4_Server="BrokerServerName",dss_inifilepath=dir,dss_inifilename="prod_T1.ini",dss_mode="prod")
What is special about usingREADME.Rmd instead of justREADME.md?You can include R chunks like so:
summary(cars)#> speed dist#> Min. : 4.0 Min. : 2.00#> 1st Qu.:12.0 1st Qu.: 26.00#> Median :15.0 Median : 36.00#> Mean :15.4 Mean : 42.98#> 3rd Qu.:19.0 3rd Qu.: 56.00#> Max. :25.0 Max. :120.00
You’ll still need to renderREADME.Rmd regularly, to keepREADME.mdup-to-date.
taken fromhttps://r-pkgs.org/
taken fromhttps://lifecycle.r-lib.org/articles/communicate.html
Run Once:
usethis::use_lifecycle()
To insert badge:
Add badges in documentation topics by inserting one of:
#’ #’ #’
Create right title case for the title of the package By running thiscommand…tools::toTitleCase("Learn computer and data science using algorithmic trading")the Title will become: “Learn Computer and Data Science usingAlgorithmic Trading”
Run this code to re-generate documentationdevtools::document()
Run this code to fix license:usethis::use_mit_license(name = "Vladimir Zhbanko")
Run this code to add data to the folderdata/x <- sample(1000)usethis::use_data(x)
To update this data:x <- sample(2000)usethis::use_data(x, overwrite = T)
To convert character into time:mutate(across('X1', ~ as.POSIXct(.x, format = "%Y.%m.%d %H:%M:%S")))
Note: use option ’LazyLoad` to make data available only when user wantsit always include LazyData: true in your DESCRIPTION. Note: to documentdataset seehttps://stackoverflow.com/questions/2310409/how-can-i-document-data-sets-with-roxygen
Document dataset using the R scriptR/datasets.R
Use data in the function withdata(x)
Place data like small files to the folder:inst/extdata
Run this command to setup tests ‘usethis::use_testthat()’
This will create a folder with the nametests
Inside this folder there will be another foldertestthat.
@examples …
code to execute during package checks
@examples
/donttest{
code to NOT execute during package checks
}
Run this command to create a new script with the test skeleton:
usethis::use_test("profit_factor.R")
Details:
- add libraries used for test
- add function
context("profit_factor") - add function test_that(“test description”, {test process})
- load data using function
data(named_data_object)
Example:
library(testthat)#>#> Attaching package: 'testthat'#> The following object is masked from 'package:dplyr':#>#> matches#> The following objects are masked from 'package:readr':#>#> edition_get, local_edition#> The following objects are masked from 'package:magrittr':#>#> equals, is_less_than, notlibrary(dplyr)library(magrittr)context("profit_factor")test_that("test value of the calculation", { data(profit_factor_data)DF_Stats<-profit_factor_data %>% group_by(X1) %>% summarise(PnL= sum(X5),NumTrades= n(),PrFact= util_profit_factor(X5)) %>% select(PrFact) %>% head(1) %>% pull(PrFact) %>% round(3) expect_equal(DF_Stats,0.68)})#> Test passed 🎊
Test coverage shows you what you’ve testeddevtools::test_coverage_file()
devtools::test_coverage_file()
This will add automatic test coverage badge to the readme file on githubusethis::use_coverage()
Step 1.devtools::document() Step 2.devtools::run_examples() Step3. Menu ‘Build’Clean and Rebuild Step 4. ‘Check’devtools::check()
This is now a default option
Whenever examples construct is used author of the package must insurethat those examples are running. Such examples are those that wouldrequire longer test execution. To perform this test package needs to bechecked with the following command:
devtools::check(run_dont_test = TRUE)
whenever a quick check is required:
devtools::check(run_dont_test = FALSE) ???
In case functions are writing files there are few considerations to takeinto account:
- examples section must contain working example of code that writesfiles
- example code must write to the temporary directory defined by
tempdir()function - after package check performed with
devtools::check()there shouldnothing remain in the ‘tmp/’ directory
File names defined by functiontempdir() would look like this:
# > tempdir()# [1] "/tmp/RtmpkaFStZ"
File names defined by functiontempfile() would look like this:
# > tempfile()# [1] "/tmp/RtmpkaFStZ/file7a33be992b4"
This is example of how functionwrite_csv example works:
tmp<- tempfile()write_csv(mtcars,tmp)
results of this code are correctly stored to the temporary file
however this example fromreadr package functionwrite_csv isshowing that file will be written to the ‘/tmp/’ directory
dir<- tempdir()write_tsv(mtcars, file.path(dir,"mtcars.tsv.gz"))
We use functionunlink() to do this:
unlink("/tmp/*.csv",recursive=TRUE,force=TRUE)
and we check that there is nothing more remained:
dir("/tmp/*.csv")To remove function from the package we can use:
- Delete function from the folder (careful not to break other functions)
- Build -> More -> Document
- Build -> More -> Clean and Rebuild
- Build -> Check
seehttps://stackoverflow.com/questions/9439256/how-can-i-handle-r-cmd-check-no-visible-binding-for-global-variable-notes-whenseehttps://github.com/HughParsonage/grattan/blob/master/R/zzz.R
After first submission there are some notes on specific R flavors
This question was addressed here but yet it’s not answered:https://stackoverflow.com/questions/48487541/r-cmd-check-note-namespace-in-imports-field-not-imported
To search for specific function in the scripts one can do the following:
list_of_functions<- c("drop_na","fill","extract","gather","nest","separate")for (FNinlist_of_functions) {if(!exists("res")){res<-BurStMisc::scriptSearch(FN) }else {res2<-BurStMisc::scriptSearch(FN)res<- mapply(c,res,res2,SIMPLIFY=FALSE)}}
It’s important to avoid that function write to the directory other thentempdir() Construct file name must be done usingfile.name()function as follow:
# use plane temp directorydir_name<- normalizePath(tempdir(),winslash="/")file_name<- paste0('my_file',1,'.csv')# this needs to be used in the functionfull_path<- file.path(dir_name,file_name)# when using sub-directorysub_dir<- file.path(dir_name,"_SUB")if(!dir.exists(sub_dir)){dir.create(sub_dir)}
https://r-pkgs.org/description.html#version
..
Clone package from GitHub and test check it in Docker Container
- started docker container vladdsm/docker-r-studio
- new project package
- clone from vzhomeexperiments/lazytrade.git
- use check button to pass the test
devtools::build()
usethis::use_readme_rmd()
usethis::use_github_action()
To be elaborated
Setup the new version of the package:
usethis::use_release_issue()
Follow checklist before upload to CRAN:
devtools::release_checks()
then:
devtools::release()
spellingdevtools::spell_check()
See?rhubv2
devtools::check_win_release()
devtools::check_win_devel()
devtools::check_win_oldrelease()
- use docker image with R Studio,
- clone repo, build, check package…
Explain the changes
About
all functions and scripts of the lazy trade educational project on udemy
Topics
Resources
License
Unknown, MIT licenses found
Licenses found
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.

