-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbacktest.cpp
282 lines (224 loc) · 7.86 KB
/
backtest.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double backtest_cpp_gpt(NumericVector returns, NumericVector indicator, double threshold) {
int n = indicator.size();
NumericVector sides(n, 1.0); // Initialize with 1s
for(int z = 1; z < n; ++z) { // Start from 1 since we look back one period
if(!NumericVector::is_na(indicator[z-1]) && indicator[z-1] > threshold) {
sides[z] = 0;
}
}
double cum_returns = 1.0; // Start cumulative returns at 1
for(int z = 0; z < n; ++z) {
cum_returns *= (1 + returns[z] * sides[z]);
}
return cum_returns - 1; // Adjust for initial value
}
// [[Rcpp::export]]
double backtest_sell_below_threshold(NumericVector returns, NumericVector indicator, double threshold) {
int n = indicator.size();
NumericVector sides(n, 1.0); // Initialize with 1s
for(int z = 1; z < n; ++z) { // Start from 1 since we look back one period
if(!NumericVector::is_na(indicator[z-1]) && indicator[z-1] < threshold) {
sides[z] = 0;
}
}
double cum_returns = 1.0; // Start cumulative returns at 1
for(int z = 0; z < n; ++z) {
cum_returns *= (1 + returns[z] * sides[z]);
}
return cum_returns - 1; // Adjust for initial value
}
DataFrame cbind_scalar_and_df(double x, DataFrame df) {
// Get the number of rows in the DataFrame
int n = df.nrows();
// Create a numeric vector that repeats 'x', one for each row
NumericVector new_col(n, x); // 'n' repetitions of 'x'
// Prepare a list to construct the new DataFrame
List new_df(df.size() + 1);
// Add the new column to the list
new_df[0] = new_col;
// Add the original DataFrame columns to the list
CharacterVector df_names = df.names();
for(int i = 0; i < df.size(); i++) {
new_df[i + 1] = df[i];
}
// Set names for the new DataFrame
CharacterVector new_names(df.size() + 1);
new_names[0] = "x"; // Name for the new column
for(int i = 0; i < df.size(); i++) {
new_names[i + 1] = df_names[i];
}
new_df.attr("names") = new_names;
new_df.attr("class") = "data.frame";
new_df.attr("row.names") = df.attr("row.names");
return DataFrame(new_df);
}
DataFrame bind_scalar_and_vector_to_df(double x, NumericVector vec) {
int n = vec.size();
// Create a numeric vector filled with the scalar value 'x', one for each element of vec
NumericVector scalar_vec(n, x);
// Create a DataFrame with two columns
DataFrame result = DataFrame::create(Named("Scalar") = scalar_vec, Named("Vector") = vec);
return result;
}
DataFrame sliceDataFrameColumnWise(DataFrame df, int start, int end) {
int n = df.size(); // Number of columns
List sliced(n); // List to store each sliced column
for(int i = 0; i < n; i++) {
// Check if the column can be converted
if (TYPEOF(df[i]) == REALSXP) {
NumericVector col = as<NumericVector>(df[i]);
sliced[i] = col[Range(start, end)];
} else {
Rcpp::Rcout << "Non-numeric column encountered at index: " << i << std::endl;
}
}
// Recreate the DataFrame with the new columns
DataFrame result(sliced);
result.attr("names") = df.attr("names");
result.attr("row.names") = df.attr("row.names");
return result;
}
// [[Rcpp::export]]
NumericVector opt(DataFrame df, DataFrame params) {
// Define help variables
int n_params = params.nrow();
NumericVector returns = df["returns"];
CharacterVector indicators = params["variable"];
NumericVector thresholds = params["thresholds"];
// return 1;
// Loop through all params rows and calculate the backtest results
NumericVector results(n_params);
for(int i = 0; i < n_params; ++i) {
String ind_ = indicators[i];
NumericVector indicator_ = df[ind_];
results[i] = backtest_cpp_gpt(returns, indicator_, thresholds[i]);
}
return results;
}
// [[Rcpp::export]]
NumericVector calculate_sma(NumericVector x, int n) {
int size = x.size();
NumericVector sma(size);
double sum = 0.0;
for(int i = 0; i < size; i++) {
sum += x[i];
if (i >= n) {
sum -= x[i - n];
}
if (i >= n - 1) {
sma[i] = sum / n;
} else {
sma[i] = NA_REAL; // Not enough data points to calculate SMA
}
}
return sma;
}
// [[Rcpp::export]]
NumericVector opt_with_sma(DataFrame df, DataFrame params) {
// Define help variables
int n_params = params.nrow();
NumericVector returns = df["returns"];
CharacterVector indicators = params["variable"];
NumericVector thresholds = params["thresholds"];
NumericVector sma_n = params["sma_n"];
// return 1;
// Loop through all params rows and calculate the backtest results
NumericVector results(n_params);
for(int i = 0; i < n_params; ++i) {
String ind_ = indicators[i];
NumericVector indicator_ = df[ind_];
int sma_n_ = sma_n[i];
// Calculate SMA for the current indicator
NumericVector sma_indicator_ = calculate_sma(indicator_, sma_n_);
results[i] = backtest_sell_below_threshold(returns, sma_indicator_, thresholds[i]);
}
return results;
}
// [[Rcpp::export]]
List wfo(DataFrame df,
DataFrame params,
int window,
std::string window_type = "rolling") {
// Define help variables
int n = df.nrow();
NumericVector time = df["time"];
NumericVector returns = df["returns"];
CharacterVector indicators = params["variable"];
NumericVector thresholds = params["thresholds"];
// Check if window size is valid relative to data size
if (window > n) {
stop("Window size exceeds available data.");
}
List results;
if (window_type == "expanding") {
results = List(n - window + 1); // Start at the minimum window size
} else {
results = List(n - window + 1);
}
// Loop over data
for(int i = 0; i < results.size(); ++i) {
DataFrame df_window;
// Before processing each window, ensure the indices are valid
if (i + window - 1 < df.nrow()) {
if (window_type == "expanding") {
df_window = sliceDataFrameColumnWise(df, 0, i + window - 1);
} else { // "rolling"
df_window = sliceDataFrameColumnWise(df, i, i + window - 1);
}
} else {
Rcpp::Rcout << "Skipping window " << i << " due to index out of range." << std::endl;
continue;
}
NumericVector sr = opt(df_window, params);
// Bind time and results
int time_index = (window_type == "expanding") ? i + window - 1 : i + window - 1;
results[i] = bind_scalar_and_vector_to_df(time[time_index], sr);
}
return results;
}
// [[Rcpp::export]]
List wfo_with_sma(DataFrame df,
DataFrame params,
int window,
std::string window_type = "rolling") {
// Define help variables
int n = df.nrow();
NumericVector time = df["time"];
// NumericVector returns = df["returns"];
// CharacterVector indicators = params["variable"];
// NumericVector thresholds = params["thresholds"];
// NumericVector sma_n = params["sma_n"];
// Check if window size is valid relative to data size
if (window > n) {
stop("Window size exceeds available data.");
}
List results;
if (window_type == "expanding") {
results = List(n - window + 1); // Start at the minimum window size
} else {
results = List(n - window + 1);
}
// Loop over data
for(int i = 0; i < results.size(); ++i) {
DataFrame df_window;
// Before processing each window, ensure the indices are valid
if (i + window - 1 < df.nrow()) {
if (window_type == "expanding") {
df_window = sliceDataFrameColumnWise(df, 0, i + window - 1);
} else { // "rolling"
df_window = sliceDataFrameColumnWise(df, i, i + window - 1);
}
} else {
Rcpp::Rcout << "Skipping window " << i << " due to index out of range." << std::endl;
continue;
}
NumericVector sr = opt_with_sma(df_window, params);
// Bind time and results
int time_index = (window_type == "expanding") ? i + window - 1 : i + window - 1;
results[i] = bind_scalar_and_vector_to_df(time[time_index], sr);
}
return results;
}