# 11. Timeserie tools

## The toolbox

`tse_timeserie.h` exports the engine's own CSV reader and writer as first-class handles, plus the timeserie utilities the engine uses internally — head/tail subranges, duration-based and count-based splitting, the seven joins of two scalar series, timestamp parsing, printing and decomposition, and the scalar transforms diff, lag and log. Everything operates over flat, caller-owned arrays: the same `TseTickOHLCV`, `TseTickBidAsk` and `TseTickTrade` arrays you feed into the market adapter, the `TseRetained` arrays you extract from results, the `TseBookMessage` arrays of a book serie, and parallel timestamp/value arrays for scalar series.

The toolbox lives next to the engine rather than in it for one reason: preparing data before a run and slicing data after it are the two chores that surround every backtest, and doing them with the engine's own parser and its own monetary arithmetic guarantees that what you inspect is exactly what the engine saw. The header is distinct from the specialized tick loaders of `tse_dataplane.h` (`tse_load_ohlcv_csv`, `tse_load_ohlcv_csv_ex`, `tse_load_bidask_csv`, `tse_load_trade_csv`): those parse straight into tick structs, while the reader here is a general-purpose handle for arbitrary columnar files. Both share the `TseCsvOptions` struct, which is declared in `tse_dataplane.h`.

The reader and the writer each carry a per-handle error text (`tse_csv_reader_error`, `tse_csv_writer_error`). The utility functions carry no handle at all and fail with a bare `tse_error` status, mirroring the silent refusals of the engine's own utilities. Any borrowed `char const*` returned by a handle stays valid until the next read on the same handle or its destruction.

## The two-phase protocol

Every extraction call in this header follows the count-then-buffer protocol shared with the rest of the library. The call is made twice. On the first call the output buffer is `NULL` and the capacity is zero: the call touches nothing, and writes into the final out-parameter the number of elements the extraction would produce. The caller then obtains storage for that many elements, by whatever means its language provides, and calls a second time with the buffer and its capacity; this time the call fills the buffer and writes the number of elements actually written. Nothing is allocated by the library and nothing has to be released to it: every buffer the engine writes into is the caller's own, for its whole lifetime. The two wrappers perform both calls internally and hand back a container, so the protocol is visible only at the C surface — the CSV reader section below shows it end to end on a real column.

Two refinements apply throughout:

- On a short buffer a truncated count is written. Matrix extraction truncates whole rows only, so the written count stays a multiple of the requested column count; table extraction truncates whole columns only, so its written count stays a multiple of the row count.
- Timestamps at the boundary are always `int64_t` nanoseconds since the epoch, in every direction: the reader's index columns come out as nanoseconds, the writer accepts nanoseconds, and the splitting functions take their `fromNs` and `stepNs` arguments in nanoseconds. The one exception is the pair `tse_csv_reader_read_index_in_duration_by_name` / `_by_index`, which names its unit in its own argument and returns the count of that unit instead.

The cell accessors are the one variation: cells are stored unterminated inside the reader, so the text is copied out. A `NULL` output stores the cell length (without terminator) into `length`; otherwise up to `capacity - 1` bytes plus a NUL terminator are written and `length` receives the copied byte count.

Borrowing works in two directions, and both are confined to the CSV reader. In one direction the reader lends: `tse_csv_reader_read_cells_by_name` / `_by_index` and `tse_csv_reader_read_table_by_columns` return `TseText` pairs of a pointer and a byte count that point into the reader's own parse buffer, so a whole column costs no allocation and one boundary crossing instead of two per cell. Those pointers follow the handle's borrowing rule and go stale on the next read or on destruction. In the other direction the caller lends: `tse_csv_reader_set_cell_by_name` / `_by_index` does not copy the text it is given, so the caller guarantees that text outlives the reader. That pair is the only place on the whole boundary where the obligation runs that way.

The reader trims every cell before any parsing: leading and trailing bytes that are neither letters nor digits are dropped, a leading minus sign excepted. A cell written `" 1"`, `"1 "` or `"+1"` therefore reaches the numeric parsers as `1`, and a cell written `"'7'"` reaches them as `7`. What survives the trim must then parse whole or the cell is refused. A row that ends with the separator carries an empty last cell rather than one field too few: the row is read with that cell empty, and neither the row nor the file is refused for it.

## CSV reader

A reader is created from `TseCsvOptions` and destroyed explicitly. Passing `NULL` options falls back to the engine reader's own defaults: `dateFormat` `"%m/%d/%Y %H:%M"`, separator `','`, no header row, parse errors not ignored, engine-chosen buffer size. Of the options struct, only `dateFormat`, `separator`, `hasHeader`, `ignoreParseErrors` and `bufferSize` (zero means the engine default) matter here — the role-column fields exist for the tick loaders of `tse_dataplane.h` and play no part in the general reader.

`tse_csv_reader_read_file` parses a file from disk; `tse_csv_reader_read_buffer` parses an in-memory buffer through the same machinery. After a successful read the shape is available through `tse_csv_reader_column_count` and `tse_csv_reader_row_count`, and — when the file has a header row — `tse_csv_reader_header_count` and `tse_csv_reader_header_name` enumerate the header names.

Column addressing comes in two families: by header name, which requires a header row, and by zero-based column index, which works either way. Each extraction exists in both forms:

- `tse_csv_reader_read_index_by_name` / `tse_csv_reader_read_index_by_index` — parse a column as timestamps using the configured `dateFormat` and return `int64_t` nanoseconds.
- `tse_csv_reader_read_index_in_duration_by_name` / `tse_csv_reader_read_index_in_duration_by_index` — the same column read in a `TseDuration` of your choosing, returning the count of that unit since the epoch. The text is parsed by the same `dateFormat`; only the unit of the answer changes, and a coarser unit truncates towards the epoch rather than rounding. A unit outside `TseDuration` refuses the read and names itself in the error text. This pair exists because a moment of the current decade counted in nanoseconds exceeds the 2^53 a `double` holds without loss, while the same moment counted in seconds sits far inside it.
- `tse_csv_reader_read_doubles_by_name` / `tse_csv_reader_read_doubles_by_index` — parse a column as doubles.
- `tse_csv_reader_read_integers_by_name` / `tse_csv_reader_read_integers_by_index` and `tse_csv_reader_read_unsigned_integers_by_name` / `tse_csv_reader_read_unsigned_integers_by_index` — parse a column as 64-bit whole numbers, signed and unsigned, with no `double` in between. A cell must parse whole once trimmed, so `1.0`, `1e3`, `0x10`, `1_000` and `12 34` are all refused, and so is a value outside the 64-bit range; the unsigned family also refuses a leading minus, `-0` included. A cell that does not parse obeys `ignoreParseErrors` exactly as the double and price columns do: with the option off the whole read is refused and the error text quotes the cell and names its row, with the option on that cell is skipped and the written count comes back smaller than the row count.
- `tse_csv_reader_read_prices_by_name` / `tse_csv_reader_read_prices_by_index` — parse a column as `TsePrice` pairs, exactly from the text and with no double in between; a cell that is not a decimal number refuses the whole read, and the error text quotes that cell and names its row. A cell that carries more than six decimals is accepted: the engine keeps six decimals, so the digits past the sixth are dropped and a price smaller than one millionth reads as zero.
- `tse_csv_reader_read_matrix_by_name` / `tse_csv_reader_read_matrix_by_index` — extract several columns at once as a row-major flat double matrix; capacity and the written count are in double elements, and truncation drops whole rows only.
- `tse_csv_reader_cell_by_name` / `tse_csv_reader_cell_by_index` — copy out the raw text of a single cell, with the copy semantics described above.
- `tse_csv_reader_read_cells_by_name` / `tse_csv_reader_read_cells_by_index` — borrow a whole column of raw text as `TseText` pairs, with no copy and no allocation. Capacity and the written count are in `TseText` elements.
- `tse_csv_reader_read_table_by_columns` — borrow the whole parsed table in one call, column after column. The order is the engine reader's own, which is why the name says so: matrix extraction over the same handle is row-major, and the two differ on purpose.

Two further calls change what the reader holds rather than extract from it. `tse_csv_reader_set_header_name` renames one column; the name is copied in, a file read afterwards discards the rename along with the rest of the parse, and a file read without a header row has no names to rename. `tse_csv_reader_set_cell_by_name` / `_by_index` replaces the text of one cell without copying it, under the caller-guarantees rule stated above; a re-read discards the substitution.

The reader itself extracts by column; slicing an extracted serie by time window is the job of the splitting utilities below, which return index ranges over the arrays you have already pulled out.

```c
TseCsvReaderHandle tse_csv_reader_create(TseCsvOptions const* options);
void tse_csv_reader_destroy(TseCsvReaderHandle reader);
char const* tse_csv_reader_error(TseCsvReaderHandle reader);
TseStatus tse_csv_reader_read_file(TseCsvReaderHandle reader, char const* filePath);
TseStatus tse_csv_reader_read_buffer(TseCsvReaderHandle reader, char const* data, size_t length);
```

```c
TseStatus tse_csv_reader_read_index_by_name(TseCsvReaderHandle reader, char const* column, int64_t* out, size_t capacity, size_t* written);
TseStatus tse_csv_reader_read_index_in_duration_by_name(TseCsvReaderHandle reader, char const* column, TseDuration duration, int64_t* out, size_t capacity, size_t* written);
TseStatus tse_csv_reader_read_integers_by_name(TseCsvReaderHandle reader, char const* column, int64_t* out, size_t capacity, size_t* written);
TseStatus tse_csv_reader_read_unsigned_integers_by_index(TseCsvReaderHandle reader, size_t column, uint64_t* out, size_t capacity, size_t* written);
TseStatus tse_csv_reader_read_prices_by_name(TseCsvReaderHandle reader, char const* column, TsePrice* out, size_t capacity, size_t* written);
TseStatus tse_csv_reader_read_matrix_by_index(TseCsvReaderHandle reader, size_t const* columns, size_t columnCount, double* out, size_t capacity, size_t* written);
TseStatus tse_csv_reader_cell_by_name(TseCsvReaderHandle reader, char const* column, size_t row, char* out, size_t capacity, size_t* length);
TseStatus tse_csv_reader_read_cells_by_name(TseCsvReaderHandle reader, char const* column, TseText* out, size_t capacity, size_t* written);
TseStatus tse_csv_reader_read_table_by_columns(TseCsvReaderHandle reader, TseText* out, size_t capacity, size_t* written);
TseStatus tse_csv_reader_set_header_name(TseCsvReaderHandle reader, size_t index, char const* name);
TseStatus tse_csv_reader_set_cell_by_index(TseCsvReaderHandle reader, size_t column, size_t row, char const* text, size_t length);
```

A borrowed cell is a pointer and a byte count, never a terminated string, so the count is what delimits it.

```c
typedef struct TseText {
	char const* data;
	size_t      length;
} TseText;
```

Put together, one column comes out of a file like this — the first call sizes the array, the second fills it, and both the reader and the storage are released by the caller that made them.

```c
TseCsvOptions options = {0};
options.structSize = sizeof(TseCsvOptions);
options.separator = ',';
options.hasHeader = 1;

TseCsvReaderHandle reader = tse_csv_reader_create(&options);
tse_csv_reader_read_file(reader, "prices.csv");

size_t needed = 0;
tse_csv_reader_read_prices_by_name(reader, "close", NULL, 0, &needed);

TsePrice* closes = calloc(needed, sizeof(TsePrice));
size_t written = 0;
tse_csv_reader_read_prices_by_name(reader, "close", closes, needed, &written);

free(closes);
tse_csv_reader_destroy(reader);
```

A borrowed column needs no sizing call and no storage of its own: the row count is already known, and the reader lends what it already holds.

```c
size_t rows = tse_csv_reader_row_count(reader);
TseText* cells = calloc(rows, sizeof(TseText));
size_t lent = 0;
tse_csv_reader_read_cells_by_name(reader, "symbol", cells, rows, &lent);

for (size_t i = 0; i < lent; ++i) {
	printf("%.*s\n", (int)cells[i].length, cells[i].data);
}

free(cells);
```

```cpp
tse::CsvReader reader {tse::CsvOptions {}};
reader.readFile("prices.csv");
std::vector<tse::Price> const closes {reader.readPrices("close")};
```

```python
reader = tse.CsvReader(has_header=True)
reader.read_file("prices.csv")
closes = reader.read_prices_by_name("close")
```

## CSV writer

A writer is created from `TseCsvWriterOptions` and writes one file per call. `NULL` options mean separator `','` and raw nanosecond timestamps.

| Field | Meaning |
| --- | --- |
| `structSize` | Set to `sizeof(TseCsvWriterOptions)` for forward compatibility. |
| `separator` | The column separator character. |
| `formatTimestamps` | Zero writes timestamps as raw `int64_t` nanoseconds; non-zero formats them by `dateFormat`. |
| `dateFormat` | strftime-like chrono conversion specifiers, the same dialect the reader parses; required non-empty when `formatTimestamps` is non-zero. |

`tse_csv_writer_write_bidask` and `tse_csv_writer_write_trade` complete the family with the same shape as the OHLCV form. A `NULL` `headers` (or zero `headerCount`) writes no header row; otherwise `headerCount` must equal the file's column count or the call refuses with the reason in the error text. Column order equals the tick layout, and the trade side is written as its textual name, the exact mirror of `tse_side_to_string`. A price field is printed as decimal text from its pair, with no trailing representation error, so a file the writer produced reads back through the price readers unchanged.

| Form | Columns | Header count |
| --- | --- | --- |
| OHLCV | ts, open, high, low, close, volume | 6 |
| Bid/ask | ts, bid, bidVolume, ask, askVolume, last | 6 |
| Trade | ts, price, volume, side | 4 |
| Scalar | ts, value | 2 |
| Matrix | ts plus one per value column | 1 + `columns` |

Doubles are written in the shortest representation that round-trips back to the same value, so a write–read cycle is lossless.

```c
TseCsvWriterHandle tse_csv_writer_create(TseCsvWriterOptions const* options);
void tse_csv_writer_destroy(TseCsvWriterHandle writer);
char const* tse_csv_writer_error(TseCsvWriterHandle writer);
TseStatus tse_csv_writer_write_ohlcv(TseCsvWriterHandle writer, char const* filePath, char const* const* headers, size_t headerCount, TseTickOHLCV const* ticks, size_t count);
TseStatus tse_csv_writer_write_scalar(TseCsvWriterHandle writer, char const* filePath, char const* const* headers, size_t headerCount, int64_t const* ts, double const* values, size_t count);
TseStatus tse_csv_writer_write_matrix(TseCsvWriterHandle writer, char const* filePath, char const* const* headers, size_t headerCount, int64_t const* ts, double const* values, size_t rows, size_t columns);
```

## Slicing and transforms

The utilities come one family per element kind: `_ohlcv`, `_bidask`, `_trade`, `_executed` (over `TseRetained`) and `_book` (over `TseBookMessage`) run on the respective tick arrays, and `_scalar` runs on parallel timestamp/value arrays. All slicing results are expressed through `TseSlice`:

| Field | Type |
| --- | --- |
| begin | `size_t` |
| length | `size_t` |

The head and tail functions yield the first or last `n` elements of the caller's array as an offset plus a length and copy nothing — the result is a view into memory you already own.

`tse_timeserie_split_by_duration_*` mirrors the engine's own splitting: the timestamps must be sorted, the sign of `stepNs` sets the direction, buckets align to the `|stepNs|` grid, `fromNs` clamps the start, and a zero step yields zero segments. Segments arrive as `TseSlice` pairs under the count-then-buffer protocol.

The scalar transforms run on the engine's monetary arithmetic of the given currency, so their rounding matches the engine's bookkeeping exactly. `out` receives exactly `count` values whose first `offset` (or `lag`) positions are zero — the engine's own convention. An offset or lag below one, or a serie not longer than it, is refused.

`diff` produces the arithmetic change over `offset` positions, `log` the logarithmic return over `offset` positions, and `lag` shifts the serie forward by `lag` positions.

```c
TseStatus tse_timeserie_head_ohlcv(TseTickOHLCV const* ticks, size_t count, size_t n, size_t* outOffset, size_t* outLength);
TseStatus tse_timeserie_tail_scalar(int64_t const* ts, double const* values, size_t count, size_t n, size_t* outOffset, size_t* outLength);
```

```c
TseStatus tse_timeserie_split_by_duration_scalar(int64_t const* ts, double const* values, size_t count, int64_t fromNs, int64_t stepNs, TseSlice* out, size_t capacity, size_t* written);
```

```c
TseStatus tse_timeserie_diff_scalar(int64_t const* ts, double const* values, size_t count, char const* currency, int offset, double* out);
TseStatus tse_timeserie_lag_scalar(int64_t const* ts, double const* values, size_t count, char const* currency, int lag, double* out);
TseStatus tse_timeserie_log_scalar(int64_t const* ts, double const* values, size_t count, char const* currency, int offset, double* out);
```

## Splitting by count, joins and timestamps

Three further families complete the toolbox: cutting a serie into segments of a fixed length, aligning two scalar series on their timestamps, and converting a timestamp between nanoseconds, text and calendar components.

`tse_timeserie_split_by_count_*` cuts the serie into consecutive segments of `segmentSize` elements each; the last segment holds the remainder and may be shorter. A segment size of zero cuts nothing and writes zero segments, as does an empty serie. The six families cover the same element kinds as the duration-based split — `ohlcv`, `bidask`, `trade`, `executed`, `book` and `scalar` — and segments arrive as `TseSlice` pairs under the count-then-buffer protocol. The difference from the duration split is what the segments mean: here they are of equal population, there of equal elapsed time.

`tse_timeserie_join_scalar` aligns two scalar series on their timestamps and carries **each side independently**, because the engine's joins return the two sides with their own lengths. Both sides therefore have their own output buffers, their own capacity and their own written count. The join kind is a `TseJoinKind`:

| Kind | What each side receives |
| --- | --- |
| `tse_join_outer_full` | each serie whole, unchanged |
| `tse_join_outer_excluding` | per side, only the timestamps absent from the other serie |
| `tse_join_inner` | per side, only the timestamps present in both |
| `tse_join_left_outer` | the left serie whole; the right reduced to the timestamps the left also carries |
| `tse_join_right_outer` | the mirror image |
| `tse_join_left_excluding` | the left timestamps absent from the right — **in the left buffers**, the right side left empty |
| `tse_join_right_excluding` | the right timestamps absent from the left — again **in the left buffers**, the right side left empty |

The two excluding kinds are the one asymmetry of the call: the engine's join returns a single serie for them, and that serie is served through the left buffers while the right written count is set to zero. `tse_join_undefined`, and any value outside the enumeration, is refused — this is the one place in the library where the `undefined` guard of an enumeration is not resolved to a conventional form, because no conventional join exists.

The timestamp trio is independent of any serie. `tse_timestamp_parse` turns text into nanoseconds using the same format dialect the CSV reader parses, and refuses text it cannot consume as a whole. The `length` it is given is the whole extent it may read: a field of the format that would reach past that length is refused instead of read beyond it, so `%Y` needs four digits inside the length and `%m`, `%d`, `%H` and `%M` need two each. `tse_timestamp_format` prints nanoseconds through the same dialect under the count-then-buffer protocol with the cell copy semantics described above: a `NULL` output stores the length, otherwise up to `capacity - 1` bytes plus a terminator are written. An empty format is refused by both. `tse_timestamp_components` decomposes nanoseconds into the calendar:

| Field | Type |
| --- | --- |
| structSize | `size_t` |
| years | `int32_t` |
| months | `int32_t` |
| days | `int32_t` |
| hours | `int32_t` |
| minutes | `int32_t` |
| seconds | `int32_t` |
| nanoseconds | `int32_t` |
| offsetMinutes | `int32_t` |

```c
TseStatus tse_timeserie_split_by_count_ohlcv(TseTickOHLCV const* ticks, size_t count, size_t segmentSize, TseSlice* out, size_t capacity, size_t* written);
TseStatus tse_timeserie_split_by_count_scalar(int64_t const* ts, double const* values, size_t count, size_t segmentSize, TseSlice* out, size_t capacity, size_t* written);
```

```c
TseStatus tse_timeserie_join_scalar
(
	TseJoinKind    kind,
	int64_t const* tsA, double const* valuesA, size_t countA,
	int64_t const* tsB, double const* valuesB, size_t countB,
	int64_t* outTsA, double* outValuesA, size_t capacityA, size_t* writtenA,
	int64_t* outTsB, double* outValuesB, size_t capacityB, size_t* writtenB
);
```

```c
TseStatus tse_timestamp_parse(char const* format, char const* text, size_t length, int64_t* outNs);
TseStatus tse_timestamp_format(int64_t ns, char const* format, char* out, size_t capacity, size_t* length);
TseStatus tse_timestamp_components(int64_t ns, TseTimestampComponents* out);
```

## C++ and Python

### C++

The C++ wrapper exposes the reader and writer as the RAII classes `tse::CsvReader` and `tse::CsvWriter`. Both hide the count-then-buffer protocol behind vector returns, and failures throw `tse::Error` carrying the handle's error text. `CsvReader` is constructed from `tse::CsvOptions` — note that the C++ struct defaults `hasHeader` to `true`, unlike the C `NULL`-options default of no header row — and offers name/index overloads in place of the `_by_name`/`_by_index` pairs.

`CsvReader` additionally offers `readBuffer`, `readStream`, `columnCount`, `rowCount`, `headers` and `setHeaderName`. Its extractions are `readIndex`, `readDoubles`, `readIntegers`, `readUnsignedIntegers`, `readPrices`, `readMatrix`, `cell`, `readCells` and `readTableByColumns`, and `setCell` substitutes the text of one cell. `readIndex` carries a second overload pair taking a `TseDuration`, so `readIndex("Date", tse_duration_seconds)` answers in seconds where the one-argument form answers in nanoseconds. `readCells` returns `std::vector<std::string_view>` and `readTableByColumns` returns `std::vector<std::vector<std::string_view>>`; both borrow from the reader's parse buffer, so the views die with the next read or with the reader, and `setCell` borrows the other way, taking a `std::string_view` the caller must keep alive. `readStream` drains a `std::istream` and parses what it drained, and refuses a stream that is not in a good state. `CsvWriter` offers `writeOhlcv`, `writeBidAsk`, `writeTrade`, `writeScalar` and `writeMatrix`, each taking an optional headers vector that defaults to empty (no header row); `writeScalar` takes its values as `std::vector<double>`, so a price column read with `readPrices` is not what it wants. The free functions mirror the utilities for every element kind — `tse::head` and `tse::tail` are overloaded for `OhlcvTick`, `BidAskTick`, `TradeTick`, `Retained`, `BookMessage` and scalar vectors, defaulting `n` to `5`; `tse::splitByDuration` carries the same overload set and returns `std::vector<TseSlice>`; `tse::diff`, `tse::lag` and `tse::log` default their offset or lag to `1` and the currency to `"USD"`.

```cpp
tse::CsvReader reader {options};
reader.readFile("quotes.csv");
std::vector<std::int64_t> ts {reader.readIndex("Date")};
std::vector<std::int64_t> seconds {reader.readIndex("Date", tse_duration_seconds)};
std::vector<std::int64_t> sessionStarts {reader.readIntegers("session_start_ns")};
std::vector<tse::Price> closes {reader.readPrices("close")};
std::vector<double> values {reader.readDoubles("close")};
std::vector<double> matrix {reader.readMatrix(std::vector<std::string> {"open", "close"})};
std::string cellText {reader.cell("close", 0)};
std::vector<std::string_view> symbols {reader.readCells("symbol")};
std::vector<std::vector<std::string_view>> table {reader.readTableByColumns()};

tse::CsvWriter writer {tse::CsvWriterOptions {}};
writer.writeScalar("out.csv", ts, values);
```

```cpp
std::pair<std::size_t, std::size_t> firstFive {tse::head(ticks)};
std::vector<TseSlice> days {tse::splitByDuration(ts, values, fromNs, stepNs)};
std::vector<double> returns {tse::log(ts, values)};
```

`tse::splitByCount` carries the same overload set as `tse::splitByDuration` and returns `std::vector<TseSlice>`. `tse::join` takes a `tse::JoinKind` and the two series and returns a `JoinResult` holding two `JoinSide` values, each with its own `ts` and `values` vectors — so the independent lengths of the two sides survive into C++, and the two excluding kinds come back with an empty right side. `tse::parseTimestamp` returns `std::optional<std::int64_t>` and yields `std::nullopt` on text it cannot parse rather than throwing; `tse::formatTimestamp` returns the printed string and throws on a refused format; `tse::timestampParts` returns a `TimestampParts` aggregate mirroring the C structure.

```cpp
std::vector<TseSlice> const weeks {tse::splitByCount(ts, values, 5u)};

tse::JoinResult const aligned {tse::join(tse::JoinKind::inner, tsA, valuesA, tsB, valuesB)};
double const firstPair {aligned.left.values.front() - aligned.right.values.front()};

std::optional<std::int64_t> const stamp {tse::parseTimestamp("%m/%d/%Y %H:%M", "01/02/1970 03:04")};
std::string const printed {tse::formatTimestamp(stamp.value(), "%Y-%m-%d")};
tse::TimestampParts const parts {tse::timestampParts(stamp.value())};
```

### Python

The Python module offers the same surface as the classes `tse.CsvReader` and `tse.CsvWriter` plus the module-level functions `head`, `tail`, `split_by_duration`, `diff`, `lag` and `log`. Failures raise `tse.TseError` with the handle's error text. The Python reader constructor exposes exactly the options that matter to the general reader — `date_format`, `separator` (default `","`), `has_header` (default `False`, matching the C default), `ignore_parse_errors` (default `False`) and `buffer_size` (default `0`, the engine default). The extraction methods keep the explicit `_by_name`/`_by_index` naming of the C API and return lists. Beside the index, double, price, matrix and cell families there are `read_integers_by_*`, `read_unsigned_integers_by_*`, `read_index_in_duration_by_*` (taking a `tse.Duration`), `read_cells_by_*`, `read_table_by_columns`, `set_header_name`, `set_cell_by_*` and `read_stream`, which drains any object with a `read` method. The cell and table borrowings come back as read-only `memoryview` objects over the reader's own buffer rather than as copies: they carry bytes, not text, and they die with the next read or with `close()`. `set_cell_by_*` hands the library a pointer it does not copy, so the reader keeps the substituted bytes alive itself until the next read or until it closes.

The Python timeserie functions cover the scalar family: they take parallel `timestamps` and `values` sequences, `head` and `tail` default `n=5` and return an `(offset, length)` tuple, `split_by_duration` returns a list of `(begin, length)` tuples, and `diff`, `lag` and `log` default their offset or lag to `1` and the currency to `"USD"`, returning a list of exactly `len(values)` floats. Both `CsvReader` and `CsvWriter` release their handle in `close()`, which is also invoked on garbage collection.

```python
reader = tse.CsvReader(date_format="%Y-%m-%d %H:%M:%S", has_header=True)
reader.read_file("quotes.csv")
ts = reader.read_index_by_name("Date")
seconds = reader.read_index_in_duration_by_name("Date", tse.Duration.Seconds)
session_starts = reader.read_integers_by_name("session_start_ns")
closes = reader.read_prices_by_name("close")
values = reader.read_doubles_by_name("close")
matrix = reader.read_matrix_by_index([1, 4])
text = reader.cell_by_name("close", 0)
symbols = [bytes(view).decode() for view in reader.read_cells_by_name("symbol")]
table = reader.read_table_by_columns()

writer = tse.CsvWriter(separator=",", format_timestamps=False)
writer.write_scalar("out.csv", ts, values)
```

```python
offset, length = tse.tail(ts, values, n=10)
segments = tse.split_by_duration(ts, values, from_ns, step_ns)
returns = tse.log(ts, values)
```

The count-based split comes in two Python functions rather than six: `tse.split_by_count(ticks, kind, segment_size)` takes the kind as one of the strings `"ohlcv"`, `"bidask"`, `"trade"`, `"executed"` and `"book"`, and `tse.split_by_count_scalar(ts, values, segment_size)` serves the scalar family. Both return a list of `(begin, length)` tuples. `tse.join_scalar(kind, ts_left, values_left, ts_right, values_right)` returns a pair of `(timestamps, values)` pairs — left side first — where the timestamps are always a plain list and the values follow the module's array policy. `tse.timestamp_parse` returns `None` on text it cannot parse, `tse.timestamp_format` returns a string and raises on a refused format, and `tse.timestamp_components` returns the mirrored structure with the fields `years`, `months`, `days`, `hours`, `minutes`, `seconds`, `nanoseconds` and `offsetMinutes`.

```python
weeks = tse.split_by_count_scalar(ts, values, 5)
bars = tse.split_by_count(ticks, "ohlcv", 5)

(ts_left, values_left), (ts_right, values_right) = tse.join_scalar(
    tse.JoinKind.INNER, ts_a, values_a, ts_b, values_b
)

stamp = tse.timestamp_parse("%m/%d/%Y %H:%M", "01/02/1970 03:04")
printed = tse.timestamp_format(stamp, "%Y-%m-%d")
parts = tse.timestamp_components(stamp)
```
