-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbactest_gpt.cpp
48 lines (40 loc) · 1.34 KB
/
bactest_gpt.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::plugins("cpp11")]]
// [[Rcpp::export]]
double backtest_cpp_gpt(NumericVector returns, NumericVector indicator, double threshold) {
int n = indicator.size();
NumericVector sides(n, 1.0);
for(int i = 1; i < n; ++i) {
if(!NumericVector::is_na(indicator[i-1]) && indicator[i-1] > threshold) {
sides[i] = 0;
}
}
double cum_returns = 1.0;
for(int i = 0; i < n; ++i) {
cum_returns *= (1 + returns[i] * sides[i]);
}
return cum_returns - 1;
}
// [[Rcpp::export]]
List combined_walk_forward_opt(NumericVector returns,
List indicators,
NumericVector thresholds,
int window) {
int n = returns.size();
if (window > n) {
stop("Window size exceeds available data.");
}
int nWindows = n - window + 1;
List results(nWindows);
NumericVector sr(thresholds.size()); // Moved outside the loop
for(int i = 0; i < nWindows; ++i) {
NumericVector returns_window = returns[Range(i, i + window - 1)];
for(int j = 0; j < thresholds.size(); ++j) {
NumericVector indicator_ = as<NumericVector>(indicators[j]);
sr[j] = backtest_cpp_gpt(returns_window, indicator_, thresholds[j]);
}
results[i] = clone(sr); // Clone the vector to save the result
}
return results;
}