Crypto backtesting
Loading...
Searching...
No Matches
summary.cxx
Go to the documentation of this file.
1#include "summary.h"
2#include "utils.h"
3#include <algorithm>
4#include <cassert>
5#include <format>
6
7/// Convert summary of trades to CSV string
8std::string to_csv(std::span<const trade_t> summary) {
9
10 std::string out{};
11
12 // Calculate average profit over all trades
13 const auto average_profit =
14 std::empty(summary)
15 ? 0.0
16 : std::ranges::fold_left(summary, 0.0,
17 [](const auto acc, const auto trade) {
18 return acc + std::get<4>(trade);
19 }) /
20 std::size(summary);
21
22 // Header row
23 out += std::format(
24 "Time,Token,Open,Close,Hours,Profit ({:.2f}% avg, {} trades)\n",
25 average_profit, std::size(summary));
26
27 // Output each trade as a row
28 for (const auto &s : summary) {
29 auto [file, entry_time, entry, exit, profit, duration] = s;
30 const auto utc = epoch_to_utc(entry_time);
31 out += std::format("{},{},{:.2f},{:.2f},{},{:.1f}\n", utc, file, entry,
32 exit, duration / 3600, profit);
33 }
34
35 return out;
36}
37
38/// Convert summary of trades to markdown string
39std::string to_markdown(std::span<const trade_t> summary) {
40
41 auto out = std::string{};
42
43 // Print summary of all trades
44 if (not std::empty(summary)) {
45
46 // Calculate average profit
47 const auto average_profit =
48 std::empty(summary)
49 ? 0.0
50 : std::ranges::fold_left(summary, 0.0,
51 [](const auto acc, auto &&trade) {
52 auto [file, entry_time, entry, exit,
53 profit, duration] = trade;
54
55 return acc + profit;
56 }) /
57 std::size(summary);
58
59 out += std::format("{:.2f}% average profit over {} trades.\n\n",
60 average_profit, std::size(summary));
61
62 // Table heading
63 out += std::format("|Time|Token|Open|Close|Hours|Profit|\n");
64 out += std::format("|---|---|---|---|---|---|\n");
65
66 // Table contents
67 for (const auto &trade : summary) {
68 auto [file, entry_time, entry, exit, profit, duration] = trade;
69 const auto utc = epoch_to_utc(entry_time);
70 out += std::format("|{}|{}|{:.2f}|{:.2f}|{}|{:.1f}%|\n", utc, file, entry,
71 exit, duration / 3600, profit);
72 }
73 }
74
75 return out;
76}
std::string to_csv(std::span< const trade_t > summary)
Convert summary of trades to CSV string.
Definition summary.cxx:8
std::string to_markdown(std::span< const trade_t > summary)
Convert summary of trades to markdown string.
Definition summary.cxx:39
std::string epoch_to_utc(const size_t epoch)
Routine to convert epoch seconds to a UTC time string.
Definition time.cxx:7