Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
negative_cycles_market_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
48# include <gtest/gtest.h>
49# include <gmp.h>
50
51# include <algorithm>
52# include <cmath>
53# include <cstddef>
54# include <functional>
55# include <limits>
56# include <set>
57# include <string>
58# include <vector>
59
61# include <Min_Mean_Cycle.H>
62# include <Negative_Cycles.H>
63# include <tpl_graph.H>
64
66
67using namespace Aleph;
68using namespace Negative_Cycles_Market_Data;
69
70namespace
71{
74 constexpr int A = asset_count;
75
78 constexpr long long max_age_ms = 1000;
79
81 constexpr double clear_margin = 1e-9;
82
83 struct Fee
84 {
85 const char * name;
86 long num;
87 long den; // the fee is num / den per leg
88 };
89
90 const Fee fees[] = {{"0", 0, 1}, {"1bp", 1, 10000}, {"0.075%", 75, 100000}, {"0.1%", 1, 1000}};
91 constexpr size_t fee_075 = 2;
92 constexpr size_t fee_10 = 3;
93
94 // ------------------------------------------------------------------------
95 // Exact rationals over the GMP C interface.
96 // ------------------------------------------------------------------------
97 class Rational
98 {
99 mpq_t q_;
100
101 public:
102 Rational() { mpq_init(q_); }
103 explicit Rational(const double x) { mpq_init(q_); mpq_set_d(q_, x); } // exact
104 Rational(const Rational & other) { mpq_init(q_); mpq_set(q_, other.q_); }
105 Rational & operator=(const Rational & other) { mpq_set(q_, other.q_); return *this; }
106 ~Rational() { mpq_clear(q_); }
107
108 Rational & operator+=(const Rational & other) { mpq_add(q_, q_, other.q_); return *this; }
109
110 friend Rational operator-(const Rational & a, const Rational & b)
111 {
112 Rational r;
113 mpq_sub(r.q_, a.q_, b.q_);
114 return r;
115 }
116
117 Rational times(const size_t factor) const
118 {
119 Rational f;
120 mpq_set_ui(f.q_, static_cast<unsigned long>(factor), 1);
121 Rational r;
122 mpq_mul(r.q_, q_, f.q_);
123 return r;
124 }
125
126 Rational divided_by(const size_t divisor) const
127 {
128 Rational d;
129 mpq_set_ui(d.q_, static_cast<unsigned long>(divisor), 1);
130 Rational r;
131 mpq_div(r.q_, q_, d.q_);
132 return r;
133 }
134
135 friend int compare(const Rational & a, const Rational & b) { return mpq_cmp(a.q_, b.q_); }
136 int sign() const { return mpq_sgn(q_); }
137 double to_double() const { return mpq_get_d(q_); }
138 };
139
140 // a / la < b / lb, with positive lengths.
141 bool mean_less(const Rational & a, const size_t la, const Rational & b, const size_t lb)
142 {
143 return compare(a.times(lb), b.times(la)) < 0;
144 }
145
146 bool mean_equal(const Rational & a, const size_t la, const Rational & b, const size_t lb)
147 {
148 return compare(a.times(lb), b.times(la)) == 0;
149 }
150
151 // True if `computed` is within one unit in the last place of `exact`, with
152 // the same sign (zero only for zero).
153 bool within_one_ulp(const double computed, const Rational & exact)
154 {
155 if (computed == 0.0)
156 return exact.sign() == 0;
157 if ((computed < 0.0 ? -1 : 1) != exact.sign())
158 return false;
159 const double up = std::nextafter(computed, std::numeric_limits<double>::infinity());
160 const double down = std::nextafter(computed, -std::numeric_limits<double>::infinity());
161 return compare(Rational(down), exact) <= 0 and compare(exact, Rational(up)) <= 0;
162 }
163
164 // ------------------------------------------------------------------------
165 // The market of one snapshot, as a digraph.
166 // ------------------------------------------------------------------------
167 struct Hide_Set
168 {
169 const std::set<Graph::Arc *> * hidden = nullptr;
170
171 bool operator()(Graph::Arc * arc) const
172 {
173 return hidden == nullptr or hidden->count(arc) == 0;
174 }
175 };
176
177 struct Market
178 {
179 Graph g;
180 Graph::Node * node[A] = {};
181 Graph::Arc * arc[A][A] = {};
182 double weight[A][A] = {};
183 Rational exact[A][A]; // the weights, as exact rationals
184 bool visible[A][A] = {};
185 const Market_Quote * quote[A][A] = {}; // the quote that prices each arc
186 std::set<Graph::Arc *> hidden;
187
190 Market(const Market_Snapshot & snapshot, const Fee & fee, const bool fresh_only)
191 {
192 for (int i = 0; i < A; ++i)
193 node[i] = g.insert_node(i);
194
195 const double fee_term = -std::log1p(-static_cast<double>(fee.num) / static_cast<double>(fee.den));
196 const double ln10 = std::log(10.0);
197 for (const auto & q : snapshot.quotes)
198 {
199 // Selling the base takes the bid, buying it takes the ask.
200 weight[q.base][q.quote] = -(std::log(static_cast<double>(q.bid)) - q.exponent * ln10) + fee_term;
201 weight[q.quote][q.base] = -(q.exponent * ln10 - std::log(static_cast<double>(q.ask))) + fee_term;
202 const bool shown = not fresh_only or (q.age_ms <= max_age_ms and q.observed != 0);
203 visible[q.base][q.quote] = visible[q.quote][q.base] = shown;
204 quote[q.base][q.quote] = quote[q.quote][q.base] = &q;
205 }
206
207 for (int u = 0; u < A; ++u)
208 for (int v = 0; v < A; ++v)
209 if (u != v)
210 {
211 arc[u][v] = g.insert_arc(node[u], node[v], weight[u][v]);
212 exact[u][v] = Rational(weight[u][v]);
213 if (not visible[u][v])
214 hidden.insert(arc[u][v]);
215 }
216 }
217 };
218
219 // ------------------------------------------------------------------------
220 // Exhaustive oracle over the simple cycles of the visible arcs.
221 // ------------------------------------------------------------------------
222 struct Oracle
223 {
224 size_t cycles = 0; // simple cycles of the visible arcs
225 size_t by_length[A + 1] = {}; // ... of each length
226 bool any_within[A + 1] = {}; // a cycle of at most L arcs exists
227 Rational best_total[A + 1]; // minimum total among cycles of at most L arcs
228 size_t best_length[A + 1] = {}; // fewest arcs among the minimizers
229 std::vector<int> best_nodes; // a minimizer over every length
230 bool any = false;
231 Rational mean_total; // the minimum mean is mean_total / mean_length
232 size_t mean_length = 1;
233 };
234
235 Oracle enumerate(const Market & m)
236 {
237 Oracle o;
238 std::vector<int> path;
239 bool on_path[A] = {};
240
241 const auto record = [&](const Rational & total)
242 {
243 const size_t len = path.size(); // a cycle has as many arcs as nodes
244 ++o.cycles;
245 ++o.by_length[len];
246 for (size_t bound = len; bound <= A; ++bound)
247 if (not o.any_within[bound] or compare(total, o.best_total[bound]) < 0
248 or (compare(total, o.best_total[bound]) == 0 and len < o.best_length[bound]))
249 {
250 o.any_within[bound] = true;
251 o.best_total[bound] = total;
252 o.best_length[bound] = len;
253 if (bound == A)
254 o.best_nodes = path;
255 }
256 if (not o.any or mean_less(total, len, o.mean_total, o.mean_length))
257 {
258 o.any = true;
259 o.mean_total = total;
260 o.mean_length = len;
261 }
262 };
263
264 std::function<void(int, int, const Rational &)> dfs =
265 [&](const int start, const int u, const Rational & total)
266 {
267 for (int v = 0; v < A; ++v)
268 {
269 if (v == u or not m.visible[u][v])
270 continue;
271 Rational t = total;
272 t += m.exact[u][v];
273 if (v == start)
274 {
275 record(t);
276 continue;
277 }
278 if (v < start or on_path[v])
279 continue;
280 on_path[v] = true;
281 path.push_back(v);
282 dfs(start, v, t);
283 path.pop_back();
284 on_path[v] = false;
285 }
286 };
287
288 for (int s = 0; s < A; ++s)
289 {
290 on_path[s] = true;
291 path.assign(1, s);
292 dfs(s, s, Rational());
293 on_path[s] = false;
294 }
295 return o;
296 }
297
298 // The exact total of a witness given as a list of arcs, which must be
299 // consecutive, visible, simple and closed.
300 bool exact_cycle(const Market & m, const DynList<Graph::Arc *> & arcs, Rational & total,
301 size_t & length)
302 {
303 std::set<Graph::Node *> seen;
304 Graph::Node * first = nullptr;
305 Graph::Node * current = nullptr;
306 length = 0;
307 total = Rational();
308 for (auto it = arcs.get_it(); it.has_curr(); it.next_ne())
309 {
310 auto * arc = it.get_curr();
311 if (m.hidden.count(arc) != 0)
312 return false;
313 auto * src = m.g.get_src_node(arc);
314 if (first == nullptr)
315 first = current = src;
316 if (src != current or not seen.insert(src).second)
317 return false;
318 current = m.g.get_tgt_node(arc);
319 total += Rational(arc->get_info());
320 ++length;
321 }
322 return length > 0 and current == first;
323 }
324
325 // Sign of the profit of going around `nodes` at the quoted prices with `fee`
326 // charged on every leg, in integers: 1 if the money grows, -1 if it shrinks.
327 // Selling the base takes the bid; buying it takes the ask.
328 int exact_profit_sign(const Market & m, const std::vector<int> & nodes, const Fee & fee)
329 {
330 mpz_t num, den, scale;
331 mpz_inits(num, den, scale, nullptr);
332 mpz_set_ui(num, 1);
333 mpz_set_ui(den, 1);
334 for (size_t i = 0; i < nodes.size(); ++i)
335 {
336 const int u = nodes[i];
337 const int v = nodes[(i + 1) % nodes.size()];
338 const Market_Quote & q = *m.quote[u][v];
339 mpz_ui_pow_ui(scale, 10, static_cast<unsigned long>(q.exponent));
340 if (u == q.base)
341 {
342 mpz_mul_si(num, num, q.bid);
343 mpz_mul(den, den, scale);
344 }
345 else
346 {
347 mpz_mul(num, num, scale);
348 mpz_mul_si(den, den, q.ask);
349 }
350 mpz_mul_si(num, num, fee.den - fee.num);
351 mpz_mul_si(den, den, fee.den);
352 }
353 const int order = mpz_cmp(num, den);
354 mpz_clears(num, den, scale, nullptr);
355 return order > 0 ? 1 : order < 0 ? -1 : 0;
356 }
357
358 std::string describe(const Market_Snapshot & s, const Fee & fee, const bool fresh_only)
359 {
360 return std::string("snapshot=") + s.label + " fee=" + fee.name + (fresh_only ? " fresh quotes only" : " every quote");
361 }
362
363 const Market_Snapshot & find_snapshot(const char * label)
364 {
365 for (const auto & s : snapshots)
366 if (std::string(s.label) == label)
367 return s;
368 ADD_FAILURE() << "no snapshot labelled " << label;
369 return snapshots[0];
370 }
371
374 void check_short(const Market & m, const Oracle & o)
375 {
376 for (size_t bound = 1; bound <= 3; ++bound)
377 {
378 SCOPED_TRACE(::testing::Message() << "up_to_3 bound=" << bound);
379 const auto r = most_negative_cycle_up_to_3<Graph, Distance, Hide_Set>(
380 m.g, bound, Distance(), Hide_Set{&m.hidden});
381 ASSERT_EQ(r.has_cycle, o.any_within[bound]);
382 if (not r.has_cycle)
383 continue;
384 Rational total;
385 size_t length = 0;
386 ASSERT_TRUE(exact_cycle(m, r.cycle_arcs, total, length));
387 ASSERT_EQ(length, r.length);
388 ASSERT_EQ(length, o.best_length[bound]);
389 ASSERT_EQ(compare(total, o.best_total[bound]), 0);
390 ASSERT_TRUE(within_one_ulp(r.total_cost, total));
391 ASSERT_EQ(r.is_negative(), total.sign() < 0);
392 }
393 }
394
399 void check_bounded(const Market & m, const Oracle & o)
400 {
401 for (const size_t bound : {size_t(3), size_t(4), size_t(6)})
402 {
403 SCOPED_TRACE(::testing::Message() << "bounded L=" << bound);
404 const auto r = most_negative_cycle_bounded<Graph, Distance, Hide_Set>(
405 m.g, bound, Distance(), Hide_Set{&m.hidden});
406 ASSERT_EQ(r.has_cycle, o.any_within[bound]);
407 if (not r.has_cycle)
408 continue;
409 Rational total;
410 size_t length = 0;
411 ASSERT_TRUE(exact_cycle(m, r.cycle_arcs, total, length));
412 ASSERT_EQ(length, r.length);
413 ASSERT_LE(length, bound);
414 ASSERT_TRUE(within_one_ulp(r.total_cost, total));
415 ASSERT_EQ(r.is_negative(), total.sign() < 0);
416 ASSERT_GE(compare(total, o.best_total[bound]), 0); // no cycle beats the optimum
417
418 // The gap is rigorous: the optimum is no cheaper than total - gap.
419 ASSERT_GE(r.optimality_gap, 0.0);
420 ASSERT_LE(compare(total - o.best_total[bound], Rational(r.optimality_gap)), 0);
421 if (r.is_exact)
422 {
423 ASSERT_EQ(compare(total, o.best_total[bound]), 0);
424 }
425 if (o.best_total[bound].to_double() < -clear_margin)
426 {
427 ASSERT_TRUE(r.is_negative());
428 }
429 }
430 }
431
434 void check_disjoint(const Market & m, const Oracle & o)
435 {
436 for (const size_t wanted : {size_t(1), size_t(3)})
437 {
438 SCOPED_TRACE(::testing::Message() << "find_disjoint wanted=" << wanted);
439 const auto cycles = find_disjoint_negative_cycles<Graph, Distance, Hide_Set>(
440 m.g, wanted, Negative_Cycle_Exclusion::All_Arcs, Distance(), Hide_Set{&m.hidden});
441 ASSERT_LE(cycles.size(), wanted);
442 std::set<Graph::Arc *> used;
443 for (auto it = cycles.get_it(); it.has_curr(); it.next_ne())
444 {
445 const auto & item = it.get_curr();
446 const auto arcs = item.cycle.arcs(); // a list by value: keep it alive while iterating
447 Rational total;
448 size_t length = 0;
449 ASSERT_TRUE(exact_cycle(m, arcs, total, length));
450 ASSERT_EQ(length, item.length);
451 ASSERT_LT(total.sign(), 0); // exactly negative
452 ASSERT_TRUE(within_one_ulp(item.total_cost, total));
453 for (auto ai = arcs.get_it(); ai.has_curr(); ai.next_ne())
454 ASSERT_TRUE(used.insert(ai.get_curr()).second);
455 }
456 if (not o.any_within[A])
457 {
458 ASSERT_TRUE(cycles.is_empty());
459 continue;
460 }
461 const double best = o.best_total[A].to_double();
462 if (best < -clear_margin)
463 {
464 ASSERT_FALSE(cycles.is_empty());
465 }
466 else if (best > clear_margin)
467 {
468 ASSERT_TRUE(cycles.is_empty());
469 }
470 }
471 }
472
474 void check_means(const Market & m, const Oracle & o)
475 {
476 const auto h = howard_minimum_mean_cycle<Graph, Distance, Hide_Set>(
477 m.g, Distance(), Hide_Set{&m.hidden});
478 const auto k = karp_minimum_mean_cycle<Graph, Distance, Hide_Set>(
479 m.g, Distance(), Hide_Set{&m.hidden});
480 ASSERT_EQ(h.has_cycle, o.any);
481 ASSERT_EQ(k.has_cycle, o.any);
482 if (not o.any)
483 return;
484
485 const double mean = o.mean_total.divided_by(o.mean_length).to_double();
486 Rational total;
487 size_t length = 0;
488 ASSERT_TRUE(exact_cycle(m, h.cycle_arcs, total, length)) << "Howard";
489 ASSERT_EQ(length, h.cycle_length);
490 ASSERT_TRUE(within_one_ulp(h.cycle_total_cost, total));
491 if (not h.used_karp and h.numeric_quality == Cycle_Numeric_Quality::Exact)
492 {
493 ASSERT_TRUE(mean_equal(total, length, o.mean_total, o.mean_length)) << "Howard is not exact";
494 }
495 if (std::fabs(mean) > clear_margin)
496 {
497 ASSERT_EQ(h.minimum_mean < 0, mean < 0) << "Howard sign";
498 }
499
500 ASSERT_TRUE(exact_cycle(m, k.cycle_arcs, total, length)) << "Karp";
501 ASSERT_EQ(length, k.cycle_length);
502 ASSERT_LE(std::fabs(static_cast<double>(k.minimum_mean) - mean), 1e-12) << "Karp mean";
503 if (std::fabs(mean) > clear_margin)
504 {
505 ASSERT_EQ(k.minimum_mean < 0, mean < 0) << "Karp sign";
506 }
507 }
508
511 void check_money(const Market & m, const Oracle & o, const Fee & fee)
512 {
513 if (not o.any_within[A])
514 return;
515 const double best = o.best_total[A].to_double();
516 const int profit = exact_profit_sign(m, o.best_nodes, fee);
517 if (best < -clear_margin)
518 {
519 ASSERT_EQ(profit, 1) << "a negative total must be a profit";
520 }
521 else if (best > clear_margin)
522 {
523 ASSERT_EQ(profit, -1) << "a positive total must be a loss";
524 }
525 }
526
528 void check_market(const Market_Snapshot & s, const Fee & fee, const bool fresh_only)
529 {
530 SCOPED_TRACE(describe(s, fee, fresh_only));
531 const Market m(s, fee, fresh_only);
532 const Oracle o = enumerate(m);
533 check_short(m, o);
534 if (::testing::Test::HasFatalFailure())
535 return;
536 check_bounded(m, o);
537 if (::testing::Test::HasFatalFailure())
538 return;
539 check_disjoint(m, o);
540 if (::testing::Test::HasFatalFailure())
541 return;
542 check_means(m, o);
543 if (::testing::Test::HasFatalFailure())
544 return;
545 check_money(m, o, fee);
546 }
547} // namespace
548
549
550TEST(NegativeCyclesMarketTest, TheOracleCountsEveryCycleOfTheCompleteMarket)
551{
552 // 15 pairs of nodes, 20 triples with 2 orientations, 15 quadruples with 6
553 // cyclic orders, 6 quintuples with 24 and 1 sextuple with 120: 409 cycles.
554 const Market m(snapshots[0], fees[0], false);
555 const Oracle o = enumerate(m);
556 EXPECT_EQ(o.cycles, 409u);
557 EXPECT_EQ(o.by_length[1], 0u);
558 EXPECT_EQ(o.by_length[2], 15u);
559 EXPECT_EQ(o.by_length[3], 40u);
560 EXPECT_EQ(o.by_length[4], 90u);
561 EXPECT_EQ(o.by_length[5], 144u);
562 EXPECT_EQ(o.by_length[6], 120u);
563}
564
565
566TEST(NegativeCyclesMarketTest, RealQuotesAgreeWithTheExhaustiveOracle)
567{
568 // Every snapshot, four fees, with every quote and with the stale or
569 // unobserved ones hidden through the arc filter: 144 markets, some of them
570 // without a single visible arc.
571 for (const auto & s : snapshots)
572 for (const auto & fee : fees)
573 for (const bool fresh_only : {false, true})
574 {
575 check_market(s, fee, fresh_only);
576 if (::testing::Test::HasFatalFailure())
577 return;
578 }
579}
580
581
582TEST(NegativeCyclesMarketTest, ARaisedFeeNeverImprovesTheBestCycle)
583{
584 // Every arc weighs more with a higher fee, and rounding is monotone, so the
585 // exact optimum of every bound can only rise.
586 for (const auto & s : snapshots)
587 for (const bool fresh_only : {false, true})
588 {
589 SCOPED_TRACE(std::string("snapshot=") + s.label + (fresh_only ? " fresh" : " all"));
590 Rational previous[4];
591 bool had[4] = {};
592 for (const auto & fee : fees)
593 {
594 const Market m(s, fee, fresh_only);
595 for (size_t bound = 2; bound <= 3; ++bound)
596 {
597 const auto r = most_negative_cycle_up_to_3<Graph, Distance, Hide_Set>(
598 m.g, bound, Distance(), Hide_Set{&m.hidden});
599 if (not r.has_cycle)
600 continue;
601 Rational total;
602 size_t length = 0;
603 ASSERT_TRUE(exact_cycle(m, r.cycle_arcs, total, length));
604 if (had[bound])
605 {
606 ASSERT_GE(compare(total, previous[bound]), 0) << "bound " << bound << " fee " << fee.name;
607 }
608 previous[bound] = total;
609 had[bound] = true;
610 }
611 }
612 }
613}
614
615
616TEST(NegativeCyclesMarketTest, QuietStatesOnlyOfferTheRoundTripThatCostsTwoFees)
617{
618 // Away from the burst nothing is profitable after fees: the cheapest cycle
619 // is going back and forth on the tightest pair, which costs the fee twice.
620 for (const auto & s : snapshots)
621 {
622 const std::string label = s.label;
623 const bool quiet = label.rfind("typical-", 0) == 0 or label == "first" or label == "len3"
624 or label == "len5" or label == "len6";
625 if (not quiet)
626 continue;
627 for (const size_t f : {fee_075, fee_10})
628 {
629 SCOPED_TRACE(describe(s, fees[f], false));
630 const Market m(s, fees[f], false);
631 const Oracle o = enumerate(m);
632 const double two_fees = 2 * -std::log1p(-static_cast<double>(fees[f].num) / fees[f].den);
633 ASSERT_TRUE(o.any_within[A]);
634 EXPECT_EQ(o.best_length[A], 2u);
635 const double best = o.best_total[A].to_double();
636 EXPECT_GE(best, two_fees - 1e-12);
637 EXPECT_LE(best, two_fees + 1e-4); // the spread of the tightest pair
638
639 const auto r = most_negative_cycle_bounded<Graph, Distance, Hide_Set>(
640 m.g, A, Distance(), Hide_Set{&m.hidden});
641 EXPECT_FALSE(r.is_negative());
642 const auto reported = find_disjoint_negative_cycles<Graph, Distance, Hide_Set>(
643 m.g, 1, Negative_Cycle_Exclusion::All_Arcs, Distance(), Hide_Set{&m.hidden});
644 EXPECT_TRUE(reported.is_empty());
645 }
646 }
647}
648
649
650TEST(NegativeCyclesMarketTest, TheFreshBurstReproducesTheEpisodesOfTheDay)
651{
652 // The three episodes of the capture in which every leg was at most one
653 // second old and its coverage observed. With a fee of 0.075 % they gain 22.67,
654 // 23.77 and 45.15 basis points; with 0.1 %, 15.17, 16.27 and 35.14.
655 struct Expected
656 {
657 const char * label;
658 size_t fee;
659 size_t legs;
660 double total;
661 };
662 const Expected expected[] = {
663 {"burst-1", fee_075, 3, -22.6732e-4}, {"burst-1", fee_10, 3, -15.1667e-4},
664 {"burst-2", fee_075, 3, -23.7742e-4}, {"burst-2", fee_10, 3, -16.2677e-4},
665 {"burst-3", fee_075, 4, -45.1460e-4}, {"burst-3", fee_10, 4, -35.1372e-4},
666 };
667 for (const auto & e : expected)
668 {
669 SCOPED_TRACE(describe(find_snapshot(e.label), fees[e.fee], true));
670 const Market m(find_snapshot(e.label), fees[e.fee], true);
671 const Oracle o = enumerate(m);
672 ASSERT_TRUE(o.any_within[A]);
673 EXPECT_EQ(o.best_length[A], e.legs);
674 EXPECT_NEAR(o.best_total[A].to_double(), e.total, 1e-7);
675
676 const auto found = find_disjoint_negative_cycles<Graph, Distance, Hide_Set>(
677 m.g, 1, Negative_Cycle_Exclusion::All_Arcs, Distance(), Hide_Set{&m.hidden});
678 EXPECT_FALSE(found.is_empty());
679 }
680}
681
682
683TEST(NegativeCyclesMarketTest, TrianglesUnderestimateTheFourLegOpportunityOfTheBurst)
684{
685 // The best fresh cycle of the last episode has four legs and gains 45.15 bp;
686 // the best triangle gains 23.79. The bounded search with L = 4 finds it and
687 // certifies it with a gap of rounding size, while L = 6 cannot certify
688 // anything on this market (its gap is 2.28 bp).
689 const Market m(find_snapshot("burst-3"), fees[fee_075], true);
690 const Oracle o = enumerate(m);
691 ASSERT_TRUE(o.any_within[A]);
692 ASSERT_EQ(o.best_length[A], 4u);
693
694 const auto triangle = most_negative_cycle_up_to_3<Graph, Distance, Hide_Set>(
695 m.g, 3, Distance(), Hide_Set{&m.hidden});
696 ASSERT_TRUE(triangle.has_cycle);
697 EXPECT_EQ(triangle.length, 3u);
698 EXPECT_TRUE(triangle.is_negative());
699 EXPECT_NEAR(triangle.total_cost, -23.7934e-4, 1e-7);
700 EXPECT_GT(triangle.total_cost, o.best_total[A].to_double() + 1e-3); // 21 bp worse
701
702 const auto four = most_negative_cycle_bounded<Graph, Distance, Hide_Set>(
703 m.g, 4, Distance(), Hide_Set{&m.hidden});
704 ASSERT_TRUE(four.has_cycle);
705 EXPECT_EQ(four.length, 4u);
706 Rational total;
707 size_t length = 0;
708 ASSERT_TRUE(exact_cycle(m, four.cycle_arcs, total, length));
709 EXPECT_EQ(compare(total, o.best_total[A]), 0);
710 EXPECT_LT(four.optimality_gap, 1e-12);
711
712 const auto six = most_negative_cycle_bounded<Graph, Distance, Hide_Set>(
713 m.g, 6, Distance(), Hide_Set{&m.hidden});
714 EXPECT_FALSE(six.is_exact);
715 EXPECT_GT(six.optimality_gap, 1e-4);
716}
717
718
719TEST(NegativeCyclesMarketTest, StaleQuotesOverstateTheBurstAndFakeTheBiggestProfitOfTheDay)
720{
721 // Without the freshness filter the last episode looks like a five-leg cycle
722 // of 56.65 bp, 11 bp better than the real one, which uses quotes up to 21
723 // seconds old. The largest profit of the day, 135 bp, is made only of stale
724 // or unobserved quotes: it vanishes once they are hidden.
725 {
726 const Market all(find_snapshot("burst-3"), fees[fee_075], false);
727 const Market fresh(find_snapshot("burst-3"), fees[fee_075], true);
728 const Oracle o_all = enumerate(all);
729 const Oracle o_fresh = enumerate(fresh);
730 ASSERT_TRUE(o_all.any_within[A]);
731 ASSERT_TRUE(o_fresh.any_within[A]);
732 EXPECT_EQ(o_all.best_length[A], 5u);
733 EXPECT_NEAR(o_all.best_total[A].to_double(), -56.6517e-4, 1e-7);
734 EXPECT_LT(compare(o_all.best_total[A], o_fresh.best_total[A]), 0);
735
736 bool uses_stale_quote = false;
737 for (size_t i = 0; i < o_all.best_nodes.size(); ++i)
738 {
739 const int u = o_all.best_nodes[i];
740 const int v = o_all.best_nodes[(i + 1) % o_all.best_nodes.size()];
741 uses_stale_quote = uses_stale_quote or not fresh.visible[u][v];
742 }
743 EXPECT_TRUE(uses_stale_quote);
744 }
745
746 const Market all(find_snapshot("raw-peak"), fees[fee_075], false);
747 const Market fresh(find_snapshot("raw-peak"), fees[fee_075], true);
748 const Oracle o_all = enumerate(all);
749 ASSERT_TRUE(o_all.any_within[A]);
750 EXPECT_EQ(o_all.best_length[A], 5u);
751 EXPECT_NEAR(o_all.best_total[A].to_double(), -135.175e-4, 1e-6);
752 EXPECT_EQ(exact_profit_sign(all, o_all.best_nodes, fees[fee_075]), 1); // real at those prices
753
754 EXPECT_FALSE(enumerate(fresh).any);
755 const auto found = find_disjoint_negative_cycles<Graph, Distance, Hide_Set>(
756 fresh.g, 1, Negative_Cycle_Exclusion::All_Arcs, Distance(), Hide_Set{&fresh.hidden});
757 EXPECT_TRUE(found.is_empty());
758}
759
760
761TEST(NegativeCyclesMarketTest, TheRelaxedBoundLeavesAGapOnARealState)
762{
763 // A state where the best cycle of at most six legs has six (-6.25 bp) and the
764 // bounded search with L = 6, a relaxed problem, returns a triangle of -5.82
765 // bp instead. Its gap, 5.17 bp, covers the 0.43 bp it leaves on the table, and
766 // `most_negative_cycle_up_to_3()` agrees with it on the triangle.
767 const Market m(find_snapshot("bounded-miss"), fees[fee_075], false);
768 const Oracle o = enumerate(m);
769 ASSERT_TRUE(o.any_within[A]);
770 EXPECT_EQ(o.best_length[A], 6u);
771 EXPECT_NEAR(o.best_total[A].to_double(), -6.2466e-4, 1e-7);
772
773 const auto r = most_negative_cycle_bounded<Graph, Distance, Hide_Set>(
774 m.g, 6, Distance(), Hide_Set{&m.hidden});
775 ASSERT_TRUE(r.has_cycle);
776 EXPECT_TRUE(r.is_negative());
777 EXPECT_FALSE(r.is_exact);
778 Rational total;
779 size_t length = 0;
780 ASSERT_TRUE(exact_cycle(m, r.cycle_arcs, total, length));
781 EXPECT_GT(compare(total, o.best_total[A]), 0); // not the optimum
782 EXPECT_GE(r.optimality_gap, (total - o.best_total[A]).to_double());
783
784 const auto triangle = most_negative_cycle_up_to_3<Graph, Distance, Hide_Set>(
785 m.g, 3, Distance(), Hide_Set{&m.hidden});
786 ASSERT_TRUE(triangle.has_cycle);
787 EXPECT_NEAR(triangle.total_cost, -5.81819e-4, 1e-7);
788}
789
790
791TEST(NegativeCyclesMarketTest, TheNearBreakEvenStateIsAnUnprofitableTriangle)
792{
793 // A state whose best cycle with a fee of 0.1 % is a triangle that loses
794 // 0.0034 bp, so no search reports a profit and the integer arithmetic on the
795 // prices agrees. With a fee of 0.075 % the same state gains 7.5 bp.
796 const Market m(find_snapshot("near-zero"), fees[fee_10], false);
797 const Oracle o = enumerate(m);
798 ASSERT_TRUE(o.any_within[A]);
799 EXPECT_EQ(o.best_length[A], 3u);
800 EXPECT_GT(o.best_total[A].to_double(), 0.0);
801 EXPECT_LT(o.best_total[A].to_double(), 1e-6);
802 EXPECT_EQ(exact_profit_sign(m, o.best_nodes, fees[fee_10]), -1);
803
804 const auto r = most_negative_cycle_bounded<Graph, Distance, Hide_Set>(
805 m.g, 4, Distance(), Hide_Set{&m.hidden});
806 EXPECT_FALSE(r.is_negative());
807 const auto found = find_disjoint_negative_cycles<Graph, Distance, Hide_Set>(
808 m.g, 1, Negative_Cycle_Exclusion::All_Arcs, Distance(), Hide_Set{&m.hidden});
809 EXPECT_TRUE(found.is_empty());
810
811 const Market cheaper(find_snapshot("near-zero"), fees[fee_075], false);
812 const auto gain = most_negative_cycle_up_to_3<Graph, Distance, Hide_Set>(
813 cheaper.g, 3, Distance(), Hide_Set{&cheaper.hidden});
814 EXPECT_TRUE(gain.is_negative());
815 EXPECT_NEAR(gain.total_cost, -7.50313e-4, 1e-7);
816}
Minimum mean cycle by Howard's policy iteration.
Minimum mean cycle in directed graphs (Karp algorithm).
Enumeration of negative cycles and bounded-length most negative cycle in directed graphs.
long double h
Definition btreepic.C:154
Default distance accessor for arc weights.
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Node Node
The graph type.
Definition tpl_graph.H:443
Arc Arc
The node class type.
Definition tpl_graph.H:444
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Minimal std::expected-style result type for C++20.
#define TEST(name)
double to_double(const Geom_Number &n)
Convert Geom_Number to double.
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
std::string quote(const std::string &s)
Definition ca-dot.H:92
decltype(auto) current(It &it) noexcept(current_is_noexcept< It >)
Current item of an iterator that is positioned on one.
Definition ah-dry.H:233
DFSResult< typename Domain::Distance > dfs(Domain &domain, typename Domain::State &state, SearchPath< typename Domain::Move > &path, const typename Domain::Distance g, const typename Domain::Distance threshold, const size_t depth, IDAStarResult< Solution, typename Domain::Distance > &result, OnSolution &on_solution)
Core recursive DFS used by IDA* for a single threshold pass.
bool mean_less(const Acc c1, const size_t l1, const Acc c2, const size_t l2)
Whether the mean c1 / l1 is smaller than c2 / l2.
Main namespace for Aleph-w library functions.
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
auto enumerate(const Container &c)
Return pairs of (element, index).
Gen_MultiPolynomial< C, M > operator-(const C &s, const Gen_MultiPolynomial< C, M > &p)
Scalar - polynomial.
and
Check uniqueness with explicit hash + equality functors.
auto mean(const Container &data) -> std::decay_t< decltype(*std::begin(data))>
Compute the arithmetic mean.
Definition stat_utils.H:190
const Market_Snapshot snapshots[]
The snapshots, in chronological order.
constexpr int asset_count
Number of assets of the market: BTC, ETH, SOL, BNB, USDT and USDC.
Snapshot snapshot(const Aleph::Adaptive_Huffman_Encoder &encoder)
Reconstruct and validate the tree using public encoder operations.
constexpr bool shown(unsigned long hidden, int i) noexcept
Whether the arc number i is shown by the mask hidden.
int num(Node *p)
The number of a node of a built graph.
STL namespace.
Top-of-book quotes of real Binance spot markets, as a fixture for the cycle searches of Negative_Cycl...
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Distance accessor.
Best bid and ask of one pair, with the price scale of both.
long long bid
Best bid, in units of 10^-exponent.
long long ask
Best ask, in units of 10^-exponent.
int base
Index of the base asset: what the bid buys and the ask sells.
const char * label
Why it was chosen (see the file documentation).
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static int * k
Gsl_Compatible_Rng r
Generic graph and digraph implementations.