algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
example-analytics-offline.cpp
1// The analytics layer end to end, with no network and no credentials.
2//
3// Bars are built in code rather than fetched, so this runs anywhere and its output is
4// the same every time -- which is what makes it useful as a worked example of the
5// conventions rather than as a demonstration that a broker replied.
6//
7// It walks the whole path a strategy takes:
8//
9// BarSeries -> SeriesFrame -> your own computation -> a metric -> back to a Decimal64 price
10//
11// and prints the absent values explicitly, because "a missing value stays missing, and is
12// never a zero" is the single most important thing to understand about this layer.
13//
14// Run it as:
15//
16// example-analytics-offline
17
18#include <algotradelib/analytics>
19#include <algotradelib/core>
20#include <algotradelib/krx>
21
22#include <chrono>
23#include <cmath>
24#include <cstddef>
25#include <iomanip>
26#include <iostream>
27#include <sstream>
28#include <string>
29#include <vector>
30
31namespace {
32
43
44namespace analytics = algotradelib::analytics;
45namespace math = algotradelib::math;
46
47using analytics::observed;
48using analytics::Scalar;
49
51std::string cell(Scalar value) {
52 if (!observed(value)) {
53 return " --";
54 }
55 std::ostringstream text;
56 text << std::fixed << std::setprecision(2) << std::setw(7) << value;
57 return text.str();
58}
59
67math::Vector period_returns(math::SeriesView prices) {
68 math::Vector result = math::Vector::Constant(prices.size(), analytics::missing());
69 for (math::Index row = 1; row < prices.size(); ++row) {
70 if (observed(prices[row]) && observed(prices[row - 1]) && prices[row - 1] > 0) {
71 result[row] = prices[row] / prices[row - 1] - 1;
72 }
73 }
74 return result;
75}
76
78struct Moments {
80 Scalar mean_{analytics::missing()};
82 Scalar deviation_{analytics::missing()};
83};
84
86Moments moments(math::SeriesView values) {
87 Moments result;
88 Scalar sum = 0;
89 Scalar count = 0;
90 for (math::Index row = 0; row < values.size(); ++row) {
91 if (observed(values[row])) {
92 sum += values[row];
93 ++count;
94 }
95 }
96 if (count < 1) {
97 return result;
98 }
99 result.mean_ = sum / count;
100 if (count < 2) {
101 return result;
102 }
103 Scalar squares = 0;
104 for (math::Index row = 0; row < values.size(); ++row) {
105 if (observed(values[row])) {
106 squares += (values[row] - result.mean_) * (values[row] - result.mean_);
107 }
108 }
109 result.deviation_ = std::sqrt(squares / (count - 1));
110 return result;
111}
112
120BarSeries fixture() {
121 // Written as the strings a broker actually sends, so the conversion boundary is
122 // exercised on real decimal text rather than on doubles dressed up as decimals.
123 static constexpr const char* closes[] = {
124 "70000",
125 "70800",
126 "70200",
127 "71500",
128 "72300",
129 "71900",
130 "73100",
131 "74000",
132 "73400",
133 "72600",
134 "71800",
135 "72500",
136 "73900",
137 "75200",
138 "74800",
139 "76100",
140 "77000",
141 "76200",
142 "75400",
143 "74100",
144 };
145 static constexpr const char* highs[] = {
146 "70500",
147 "71300",
148 "70700",
149 "72000",
150 "72800",
151 "72400",
152 "73600",
153 "74500",
154 "73900",
155 "73100",
156 "72300",
157 "73000",
158 "74400",
159 "75700",
160 "75300",
161 "76600",
162 "77500",
163 "76700",
164 "75900",
165 "74600",
166 };
167 static constexpr const char* lows[] = {
168 "69400",
169 "70200",
170 "69600",
171 "70900",
172 "71700",
173 "71300",
174 "72500",
175 "73400",
176 "72800",
177 "72000",
178 "71200",
179 "71900",
180 "73300",
181 "74600",
182 "74200",
183 "75500",
184 "76400",
185 "75600",
186 "74800",
187 "73500",
188 };
189
190 BarSeries series;
191 series.instrument_ = InstrumentId{Country::KR, Venue::COMBINED, "005930"};
192 series.interval_ = BarInterval::ONE_DAY;
193 series.currency_ = Currency{"KRW"};
194 series.received_at_ = std::chrono::system_clock::now();
195
196 const auto start = std::chrono::system_clock::time_point{} + std::chrono::hours(24 * 20000);
197 for (std::size_t day = 0; day < std::size(closes); ++day) {
198 Bar bar;
199 bar.timestamp_ = start + std::chrono::hours(24 * static_cast<int>(day));
200 // The fourth day has no open, which is what a session with no trade at the auction
201 // looks like. It stays unobserved through the frame and every computation masks it.
202 if (day != 3) {
203 bar.open_ = Decimal64::parse(closes[day]);
204 }
205 bar.high_ = Decimal64::parse(highs[day]);
206 bar.low_ = Decimal64::parse(lows[day]);
207 bar.close_ = Decimal64::parse(closes[day]);
208 bar.volume_ = Decimal64::parse("1200000");
209 series.bars_.push_back(bar);
210 }
211 return series;
212}
213
214} // namespace
215
216int main() {
217 const BarSeries bars = fixture();
218
219 // The one place exact decimals become scalars. Everything below computes in `Scalar`
220 // and nothing below it sees a `Decimal64` again until the very last step.
221 const analytics::SeriesFrame frame = analytics::from_bars(bars);
222
223 // Views into the frame's own storage, not copies: a column of a column-major frame is
224 // contiguous, which is what `SeriesView` is for.
225 const math::SeriesView close = frame.close();
226 const math::SeriesView open = frame.open();
227 const math::Vector returns = period_returns(close);
228
229 std::cout << bars.instrument_.symbol_ << ", " << bars.bars_.size() << " daily bars, no network\n\n";
230 std::cout << "row close open return\n";
231 for (math::Index row = 0; row < close.size(); ++row) {
232 std::cout
233 << std::setw(3) << row << " " << cell(close[row]) << " " << cell(open[row]) << " " << cell(returns[row] * 100.0)
234 << "\n";
235 }
236
237 // Row 3 has no open. Notice it is a dash above rather than a zero, and that the close
238 // column and its returns are unaffected by it.
239 std::cout << "\nThe dashes are the point. Row 0 has no return, and row 3 has no open at all.\n";
240
241 const auto daily = moments(returns);
242 std::cout
243 << "\nOver the whole series:\n"
244 << " mean daily return " << std::fixed << std::setprecision(4) << daily.mean_ * 100.0 << " %\n"
245 << " daily volatility " << daily.deviation_ * 100.0 << " %\n"
246 << " per-period Sharpe " << analytics::sharpe(returns) << "\n"
247 << " annualized Sharpe " << analytics::annualize_ratio(analytics::sharpe(returns), 245.0) << "\n"
248 << " worst drawdown " << analytics::max_drawdown(close).magnitude_ * 100.0 << " %\n";
249
250 // The one sanctioned route back to something a broker will accept. Two deviations above the
251 // average of the last five closes is a computed scalar; an order needs an exact decimal on the
252 // instrument's own tick grid.
253 const auto recent = moments(close.tail(5));
254 const auto rule = algotradelib::krx::equity_price_rule();
255 const auto limit = analytics::round_scalar_to_tick(recent.mean_ + 2.0 * recent.deviation_, rule, OrderSide::SELL);
256 std::cout
257 << "\nA sell limit two deviations above the last five closes' average, rounded onto the KRX tick grid: "
258 << (limit ? limit->str() : std::string("refused")) << "\n";
259
260 return 0;
261}
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:374
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
Series buffers and frames, the conversions to and from exact decimals, and performance metrics.
PriceRule equity_price_rule()
Returns the KRX stock tick table (January 2023 revision).
Definition krx.hpp:12
The numeric vocabulary: Scalar, missing(), and the matrix and vector types.
Definition eigen.hpp:10
double Scalar
The floating-point type the analytics and math layers compute in (double).
Definition scalar.hpp:18
bool observed(Scalar value)
Tests whether a value is an observation.
Definition scalar.hpp:38
void start(S &strategy, Ctx &context)
Calls strategy.on_start(context) if the strategy declares on_start; otherwise does nothing.
Definition concept.hpp:240
void bar(S &strategy, Ctx &context, const BarEvent &event)
Calls strategy.on_bar(context, event) if the strategy declares on_bar; otherwise does nothing.
Definition concept.hpp:282
void bars(S &strategy, Ctx &context, const BarSlice &slice)
Calls strategy.on_bars(context, slice) if the strategy declares on_bars; otherwise does nothing.
Definition concept.hpp:309
SecurityType
What kind of security an instrument is.
Country
A country (market) the library supports.
Definition types.hpp:32
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
BarInterval
The period one bar covers.
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
The bars of one instrument and interval, oldest first.
One bar: the prices and volume of one period, as exact decimals.
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85