### Run Shiny Applications from GitHub Source: https://context7.com/englianhu/binary.com-interview-question/llms.txt Provides commands to directly run various Shiny applications from GitHub without local code download. Each command launches a specific interactive application. ```R # 1. 主应用:Lasso/Ridge/Elastic Net 模型精度比较(含面试题全部解答) shiny::runGitHub('englianhu/binary.com-interview-question') ``` ```R # 2. Q1App:自动采集汇价 → 建模预测 → 绘制K线+预测图 shiny::runGitHub('englianhu/binary.com-interview-question', subdir = 'Q1') # 用户选择货币对和预测日期后,系统自动拟合 glmnet 模型并以 highcharter 绘图 ``` ```R # 3. testRealTimeTransc:实时交易系统(采集→预测→自动下单→结算→盈亏展示) shiny::runGitHub('englianhu/binary.com-interview-question', subdir = '实验室/testRealTimeTransc') # 使用 TFX 包获取 TrueFX 实时汇价,cronR 定时触发 GARCH 预测与下单 ``` ```R # 4. Q1App2:庄家(Banker)与赌徒(Punter)双角色金融投注模拟 shiny::runGitHub('englianhu/binary.com-interview-question', subdir = '实验室/Q1App2') ``` ```R # 5. Q2App:双变量泊松模型排队论(运筹学)模拟 shiny::runGitHub('englianhu/binary.com-interview-question', subdir = 'Q2') ``` -------------------------------- ### Monte Carlo Simulation: Kelly vs. Optimal f Distribution Source: https://context7.com/englianhu/binary.com-interview-question/llms.txt Compares the Kelly criterion with the optimal f distribution using Monte Carlo simulations. Requires functions optKelly and opt.f to be defined elsewhere. ```R compare <- data.frame(kelly = numeric(5000), opt.f = numeric(5000)) for (i in 1:5000) { compare$kelly[i] <- optKelly(2, -0.5, 0.55, 500, 1)$opt.kelly compare$opt.f[i] <- opt.f(2, -0.5, 0.55, 500, 1)$opt.f } ggplot(compare) + stat_density(aes(x = kelly, colour = 'Kelly'), adjust = 2, fill = NA, geom = 'line') + stat_density(aes(x = opt.f, colour = 'Opt.f'), adjust = 2, fill = NA, geom = 'line') + labs(title = '凯利标准 vs 最优 f 分布比较', x = '最优仓位比例', colour = '方法') ``` -------------------------------- ### optKelly() / opt.f() — Kelly Criterion and Optimal f Bet Sizing Source: https://context7.com/englianhu/binary.com-interview-question/llms.txt Implements the Kelly Criterion and Optimal f (Ralph Vince) capital management algorithms. Calculates the cumulative log-equity across different bet sizes (f ∈ [0, lev]) using Monte Carlo simulation. Returns the optimal position size and a complete results matrix, which can be used with ggplot2 to plot distribution graphs for comparison. ```APIDOC ## optKelly() / opt.f() — 凯利标准与最优 f 投注比例 实现凯利标准(Kelly Criterion)和最优 f(Ralph Vince)两种资金管理算法,通过蒙特卡洛模拟在不同投注比例 f ∈ [0, lev] 上计算累积对数盈亏,返回最优仓位比例及完整结果矩阵,可用 ggplot2 绘制分布图比较两者差异。 ```r source('函数/kelly.opt.R') library(ggplot2) # 参数:盈利倍率=2,亏损=-0.5,胜率=0.55,模拟500次,最大杠杆=1 result_kelly <- optKelly(win = 2, loss = -0.5, p = 0.55, obs = 500, lev = 1) cat('最优凯利比例:', result_kelly$opt.kelly, '\n') # 最优凯利比例: 0.366 result_optf <- opt.f(win = 2, loss = -0.5, p = 0.55, obs = 500, lev = 1) cat('最优 f 比例:', result_optf$opt.f, '\n') # 最优 f 比例: 0.340 ``` ``` -------------------------------- ### simGarch() — Univariate GARCH Model Rolling Forecast Simulation Source: https://context7.com/englianhu/binary.com-interview-question/llms.txt Performs a day-by-day rolling fit of GARCH-class models (supporting sGARCH, fGARCH, gjrGARCH, iGARCH, csGARCH, realGARCH, etc.) on OHLC data for a specified currency pair. Outputs daily one-step-ahead forecast values compared against actual values as an xts time series. ARMA orders are automatically selected by `armaSearch()`. Supports bootstrap confidence intervals and parallel computation. ```APIDOC ## simGarch() — 单变量 GARCH 模型滚动预测模拟 对指定货币对的 OHLC 数据,逐日滚动拟合 GARCH 类模型(支持 sGARCH、fGARCH、gjrGARCH、iGARCH、csGARCH、realGARCH 等),并输出每日一步超前预测值与实际值的对比 xts 时间序列。ARMA 阶数由 `armaSearch()` 自动选取,支持自助法(bootstrap)置信区间与并行计算。 ```r library(rugarch); library(lubridate); library(xts); library(quantmod) source('函数/simGarch.R') # 准备 xts 格式 OHLCV 数据(美日汇率) getSymbols('JPY=X', from = '2014-01-01', to = '2017-08-31', auto.assign = TRUE) mbase <- `JPY=X` %>% na.omit # 使用 sGARCH(1,1) + 正态分布,预测日均价(Hi+Lo)/2) result <- simGarch( mbase, .solver = 'hybrid', .prCat = 'Mn', # 预测 (Hi+Lo)/2 均价 .baseDate = ymd('2016-01-01'), .maPeriod = 'years', .unit = 1, .variance.model = list(model = 'sGARCH', garchOrder = c(1,1), submodel = NULL, external.regressors = NULL, variance.targeting = FALSE), .mean.model = list(armaOrder = c(1,1), include.mean = TRUE), .dist.model = 'norm' ) # result 为 xts:含 Point.Forecast(预测)和实际 OHLCV 列 tail(result[, c('Point.Forecast', 'USDJPY.Mn')], 5) # Point.Forecast USDJPY.Mn # 2017-08-25 109.21 109.48 # 2017-08-28 109.35 109.52 # 2017-08-29 109.18 109.17 # 2017-08-30 109.44 109.88 # 2017-08-31 109.60 110.02 ``` ``` -------------------------------- ### Calculate Kelly Bet Staking based on GARCH Predictions Source: https://context7.com/englianhu/binary.com-interview-question/llms.txt Calculates optimal bet staking using the Kelly formula based on GARCH model predictions for high/low prices. Filters out trades with negative expected value. Requires the kellyBet.R script. ```R library(dplyr); library(data.table); library(magrittr) source('函数/kellyBet.R') # pred.data 为 simGarch 输出后整理的预测数据框,含以下必要列: # LatestDate.GMT, Lst.High, Lst.Low, ForecastDate.GMT, Fct.High, Fct.Low, EMprob, COMOdds pred.data <- data.frame( LatestDate.GMT = as.Date('2017-06-27'), Lst.High = 112.399, Lst.Low = 111.863, ForecastDate.GMT = 'T+1', Fct.High = 112.547, Fct.Low = 111.766, EMprob = 0.828, COMOdds = 1.95 ) result <- kellyBet(pred.data, initialFundSize = 10000) # result 含 ProbB, ProbS, Adv (优势值), Staking (最优投注比例) # Adv = (EMprob * COMOdds) + ((1-EMprob) * -1) # Staking = Adv / COMOdds,负值截断为 0 ``` -------------------------------- ### armaSearch() — Automatic ARMA Order Search Source: https://context7.com/englianhu/binary.com-interview-question/llms.txt Automatically searches through all combinations of ARMA(p,1,q) orders (p,q ∈ 0..5) to select the optimal order based on the AIC information criterion. Supports 'CSS-ML', 'ML', and 'CSS' fitting methods and includes automatic fallback retries. Returns a complete data frame of AIC comparisons. ```APIDOC ## armaSearch() — ARMA 阶数自动搜索 遍历 ARIMA(p,1,q)(p,q ∈ 0..5)的所有组合,以 AIC 信息准则选出最优阶数,支持 `CSS-ML`、`ML`、`CSS` 三种拟合方法,并在方法失败时自动降级重试,返回完整的 AIC 比较数据框。 ```r library(magrittr) source('函数/armaSearch.R') # 使用 quantmod 下载美日汇率日线数据 library(quantmod) getSymbols('JPY=X', from = '2016-01-01', to = '2017-12-31', auto.assign = TRUE) cl_data <- Cl(`JPY=X`) %>% na.omit # 自动搜索最优 ARMA(p,q) 阶数 result <- armaSearch(cl_data, .method = 'CSS-ML') # 输出示例:method = 'CSS-ML', the min AIC = -2345.12, p = 1, q = 1 # 查看所有 AIC 比较表 head(result[order(result$AIC), ]) # p q AIC # 7 1 1 -2345.12 # 8 1 2 -2343.87 # 2 0 1 -2341.05 ``` ``` -------------------------------- ### simETS() — Exponential Smoothing (ETS) Rolling Forecast Simulation Source: https://context7.com/englianhu/binary.com-interview-question/llms.txt Performs rolling one-step-ahead forecasts on currency pair OHLC data using the exponential smoothing state-space model from `forecast::ets()`. The model type can be specified (e.g., 'ZZZ' for automatic selection, or specific types like 'ANN', 'MAM'). Supports simulation paths and bootstrap confidence intervals. ```APIDOC ## simETS() — 指数平滑(ETS)滚动预测模拟 基于 `forecast::ets()` 的指数平滑状态空间模型,对货币对 OHLC 数据进行滚动单步预测,模型类型可指定(`ZZZ` 自动选择,或指定如 `ANN`、`MAM` 等),支持模拟路径与自助法置信区间。 ```r library(forecast); library(lubridate); library(xts); library(quantmod) source('函数/simETS.R') getSymbols('JPY=X', from = '2014-01-01', to = '2017-08-31', auto.assign = TRUE) mbase <- `JPY=X` %>% na.omit # 自动选择 ETS 模型,预测日最高价 result_hi <- simETS( mbase, .model = 'ZZZ', # 自动选择误差/趋势/季节性类型 .damped = NULL, .prCat = 'Hi', # 预测日最高价 .baseDate = ymd('2016-01-01'), .maPeriod = 'years', .unit = 1, .simulate = FALSE, .bootstrap = FALSE ) # 对比预测值与实际最高价 tail(result_hi[, c('Point.Forecast', 'JPY.X.High')], 3) # Point.Forecast JPY.X.High # 2017-08-29 109.60 109.72 # 2017-08-30 110.01 110.15 # 2017-08-31 110.22 110.38 ``` ``` -------------------------------- ### Simulate GARCH Model Rolling Forecast Source: https://context7.com/englianhu/binary.com-interview-question/llms.txt Performs daily rolling fitting of GARCH-class models (sGARCH, fGARCH, gjrGARCH, etc.) on OHLC data for a specified currency pair. Outputs daily one-step-ahead forecast values against actuals as an xts time series. ARMA order is automatically selected by `armaSearch()`, supporting bootstrap confidence intervals and parallel computation. ```r library(rugarch); library(lubridate); library(xts); library(quantmod) source('函数/simGarch.R') # 准备 xts 格式 OHLCV 数据(美日汇率) getSymbols('JPY=X', from = '2014-01-01', to = '2017-08-31', auto.assign = TRUE) mbase <- `JPY=X` %>% na.omit # 使用 sGARCH(1,1) + 正态分布,预测日均价(Hi+Lo)/2) result <- simGarch( mbase, .solver = 'hybrid', .prCat = 'Mn', # 预测 (Hi+Lo)/2 均价 .baseDate = ymd('2016-01-01'), .maPeriod = 'years', .unit = 1, .variance.model = list(model = 'sGARCH', garchOrder = c(1,1), submodel = NULL, external.regressors = NULL, variance.targeting = FALSE), .mean.model = list(armaOrder = c(1,1), include.mean = TRUE), .dist.model = 'norm' ) # result 为 xts:含 Point.Forecast(预测)和实际 OHLCV 列 tail(result[, c('Point.Forecast', 'USDJPY.Mn')], 5) # Point.Forecast USDJPY.Mn # 2017-08-25 109.21 109.48 # 2017-08-28 109.35 109.52 # 2017-08-29 109.18 109.17 # 2017-08-30 109.44 109.88 # 2017-08-31 109.60 110.02 ``` -------------------------------- ### Kelly Criterion and Optimal f Bet Sizing Source: https://context7.com/englianhu/binary.com-interview-question/llms.txt Implements the Kelly Criterion and Optimal f (Ralph Vince) capital management algorithms. It calculates cumulative log returns across different bet sizes (f ∈ [0, lev]) using Monte Carlo simulation, returning the optimal position size and a complete results matrix. Useful for plotting distribution differences with ggplot2. ```r source('函数/kelly.opt.R') library(ggplot2) # 参数:盈利倍率=2,亏损=-0.5,胜率=0.55,模拟500次,最大杠杆=1 result_kelly <- optKelly(win = 2, loss = -0.5, p = 0.55, obs = 500, lev = 1) cat('最优凯利比例:', result_kelly$opt.kelly, '\n') # 最优凯利比例: 0.366 result_optf <- opt.f(win = 2, loss = -0.5, p = 0.55, obs = 500, lev = 1) cat('最优 f 比例:', result_optf$opt.f, '\n') # 最优 f 比例: 0.340 ``` -------------------------------- ### filterFX() — Forex Data Filtering and Standardization Source: https://context7.com/englianhu/binary.com-interview-question/llms.txt Filters and standardizes column names of raw xts forex objects downloaded by `quantmod::getSymbols()`, based on currency code and price type (Open/High/Low/Close/Adjusted). Removes missing values and returns a clean, single-column xts series. Supports seven major currency pairs: AUDUSD, EURUSD, GBPUSD, USDCHF, USDCAD, USDCNY, USDJPY. ```APIDOC ## filterFX() — 外汇数据过滤与标准化 将 `quantmod::getSymbols()` 下载的原始 xts 外汇对象,按货币代码和价格类型(开/高/低/收/调整)进行过滤与列名标准化,去除缺失值并返回干净的单列 xts 序列。支持七种主要货币对:AUDUSD、EURUSD、GBPUSD、USDCHF、USDCAD、USDCNY、USDJPY。 ```r library(quantmod); library(magrittr); library(stringr) source('函数/filterFX.R') # 下载美日汇率 getSymbols('JPY=X', from = '2015-01-01', to = '2017-12-31', auto.assign = TRUE) mbase <- `JPY=X` # 提取日收盘价并标准化列名 usdjpy_cl <- filterFX(mbase, currency = 'JPY=X', price = 'Cl') # 列名自动规范为 'USDJPY',NA 已去除 head(usdjpy_cl) # USDJPY # 2015-01-02 119.63 # 2015-01-05 119.17 # 提取日最高价 usdjpy_hi <- filterFX(mbase, currency = 'JPY=X', price = 'Hi') head(usdjpy_hi) # USDJPY # 2015-01-02 120.11 # 2015-01-05 119.80 ``` ``` -------------------------------- ### Auto-search ARMA Order using AIC Source: https://context7.com/englianhu/binary.com-interview-question/llms.txt Automatically searches through ARIMA(p,1,q) combinations (p,q ∈ 0..5) to find the optimal order based on the AIC information criterion. Supports CSS-ML, ML, and CSS fitting methods, with automatic fallback retries on failure. Returns a complete AIC comparison data frame. ```r library(magrittr) source('函数/armaSearch.R') # 使用 quantmod 下载美日汇率日线数据 library(quantmod) getSymbols('JPY=X', from = '2016-01-01', to = '2017-12-31', auto.assign = TRUE) cl_data <- Cl(`JPY=X`) %>% na.omit # 自动搜索最优 ARMA(p,q) 阶数 result <- armaSearch(cl_data, .method = 'CSS-ML') # 输出示例:method = 'CSS-ML', the min AIC = -2345.12, p = 1, q = 1 # 查看所有 AIC 比较表 head(result[order(result$AIC), ]) # p q AIC # 7 1 1 -2345.12 # 8 1 2 -2343.87 # 2 0 1 -2341.05 ``` -------------------------------- ### Elastic Net Forex Price Prediction using glmnet Source: https://context7.com/englianhu/binary.com-interview-question/llms.txt Predicts forex closing prices using Elastic Net regression (alpha=0.8) with the glmnet package. The h() function creates feature matrices, and glmPrice() handles model fitting and prediction. Requires sourced R scripts for helper functions. ```R library(glmnet); library(magrittr); library(dplyr) source('实验室/shinyFunction/h.R') source('实验室/shinyFunction/glmPrice.R') source('实验室/shinyFunction/filterLAD.R') source('实验室/shinyFunction/loadLAD.R') # 载入数据 datam <- loadLAD() fundDT <- filterLAD(startDate = Sys.Date() - 365, endDate = Sys.Date())$fundDT # 构造特征矩阵(使用 h2 矩阵方案,预测 daily.mean2) xy <- h(fundDT, family = 'gaussian', xy.matrix = 'h2', setform = 'l4', yv = 'daily.mean2') # 使用预训练模型(alpha=0.8, lambda.1se)进行预测 fitgaum16.alpha08 <- readRDS('./shinyData/fitgaum16.alpha08.rds') pd <- predict(fitgaum16.alpha08, newx = xy$x, s = fitgaum16.alpha08$lambda.1se, pred.type = 'class') %>% as.data.frame() %>% rename(Pred = 1) # 合并预测值与原始数据 result <- fundDT %>% mutate(HL.Mean = (LAD.High + LAD.Low) / 2) %>% bind_cols(pd) tail(result[, c('Date', 'HL.Mean', 'Pred')], 3) ``` -------------------------------- ### Filter and Standardize FX Data Source: https://context7.com/englianhu/binary.com-interview-question/llms.txt Filters and standardizes raw xts Forex objects downloaded by `quantmod::getSymbols()`. It selects data by currency code and price type (Open/High/Low/Close/Adjusted), removes NA values, and returns a clean single-column xts series. Supports seven major currency pairs: AUDUSD, EURUSD, GBPUSD, USDCHF, USDCAD, USDCNY, USDJPY. ```r library(quantmod); library(magrittr); library(stringr) source('函数/filterFX.R') # 下载美日汇率 getSymbols('JPY=X', from = '2015-01-01', to = '2017-12-31', auto.assign = TRUE) mbase <- `JPY=X` # 提取日收盘价并标准化列名 usdjpy_cl <- filterFX(mbase, currency = 'JPY=X', price = 'Cl') # 列名自动规范为 'USDJPY',NA 已去除 head(usdjpy_cl) # USDJPY # 2015-01-02 119.63 # 2015-01-05 119.17 # 提取日最高价 usdjpy_hi <- filterFX(mbase, currency = 'JPY=X', price = 'Hi') head(usdjpy_hi) # USDJPY # 2015-01-02 120.11 # 2015-01-05 119.80 ``` -------------------------------- ### Simulate ETS Model Rolling Forecast Source: https://context7.com/englianhu/binary.com-interview-question/llms.txt Performs rolling one-step-ahead predictions using exponential smoothing state space models from `forecast::ets()`. Model types can be specified or automatically selected (`ZZZ`). Supports simulation paths and bootstrap confidence intervals. ```r library(forecast); library(lubridate); library(xts); library(quantmod) source('函数/simETS.R') getSymbols('JPY=X', from = '2014-01-01', to = '2017-08-31', auto.assign = TRUE) mbase <- `JPY=X` %>% na.omit # 自动选择 ETS 模型,预测日最高价 result_hi <- simETS( mbase, .model = 'ZZZ', # 自动选择误差/趋势/季节性类型 .damped = NULL, .prCat = 'Hi', # 预测日最高价 .baseDate = ymd('2016-01-01'), .maPeriod = 'years', .unit = 1, .simulate = FALSE, .bootstrap = FALSE ) # 对比预测值与实际最高价 tail(result_hi[, c('Point.Forecast', 'JPY.X.High')], 3) # Point.Forecast JPY.X.High # 2017-08-29 109.60 109.72 # 2017-08-30 110.01 110.15 # 2017-08-31 110.22 110.38 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.