README.md 7.33 KB
Newer Older
1
2
TSHISTORY
===========
Aurélien Campéas's avatar
Aurélien Campéas committed
3
4
5
6

This is a library to store/retrieve pandas timeseries to/from a
postgres database, tracking their successive versions.

7
8
[TOC]

9
# Introduction
Aurélien Campéas's avatar
Aurélien Campéas committed
10

11
## Purpose
12

13
14
15
16
17
18
19
20
21
`tshistory` is targetted at applications using time series where
[backtesting][backtesting] and [cross-validation][cross-validation]
are an essential feature.

It provides exhaustivity and efficiency of the storage, with a simple
Python api.

It can be used as a building block for machine learning, model
optimization and validation, both for inputs and outputs.
22
23


24
## Principles
Aurélien Campéas's avatar
Aurélien Campéas committed
25
26
27
28
29
30

There are many ways to represent timeseries in a relational database,
and `tshistory` provides two things:

* a base python API which abstracts away the underlying storage

31
* a postgres model, which emphasizes the compact storage of successive
Aurélien Campéas's avatar
Aurélien Campéas committed
32
  states of series
Aurélien Campéas's avatar
Aurélien Campéas committed
33
34
35
36
37
38

The core idea of tshistory is to handle successive versions of
timeseries as they grow in time, allowing to get older states of any
series.


39
40
41
# Basic usage

## Starting with a fresh database
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

You need a postgresql database. You can create one like this:

```shell
 createdb mydb
```

Then, initialize the `tshistory` tables, like this:

```python
 tsh init-db postgresql://me:password@localhost/mydb
```

From this you're ready to go !


58
## Creating a series
Aurélien Campéas's avatar
Aurélien Campéas committed
59

60
However here's a simple example:
Aurélien Campéas's avatar
Aurélien Campéas committed
61
62

```python
Aurélien Campéas's avatar
Aurélien Campéas committed
63
64
65
66
67
68
69
70
71
72
 >>> from sqlalchemy import create_engine
 >>> import pandas as pd
 >>> from tshistory.tsio import TimeSerie
 >>>
 >>> engine = create_engine('postgres://me:password@localhost/mydb')
 >>> tsh = TimeSerie()
 >>>
 >>> series = pd.Series([1, 2, 3],
 ...                    pd.date_range(start=pd.Timestamp(2017, 1, 1),
 ...                                  freq='D', periods=3))
Aurélien Campéas's avatar
Aurélien Campéas committed
73
 # db insertion
74
75
76
 >>> with engine.begin() as cn:
 >>>     tsh.insert(cn, series, 'my_series', 'babar@pythonian.fr')
 ...
Aurélien Campéas's avatar
Aurélien Campéas committed
77
78
79
80
81
82
83
84
85
 2017-01-01    1.0
 2017-01-02    2.0
 2017-01-03    3.0
 Freq: D, Name: my_series, dtype: float64

 # note how our integers got turned into floats
 # (there are no provisions to handle integer series as of today)

 # retrieval
86
87
88
 >>> with engine.begin() as cn:
 >>>     tsh.get(cn, 'my_series')
 ...
Aurélien Campéas's avatar
Aurélien Campéas committed
89
90
91
92
 2017-01-01    1.0
 2017-01-02    2.0
 2017-01-03    3.0
 Name: my_series, dtype: float64
Aurélien Campéas's avatar
Aurélien Campéas committed
93
94
```

Aurélien Campéas's avatar
Aurélien Campéas committed
95
## Updating a series
96

Aurélien Campéas's avatar
Aurélien Campéas committed
97
This is good. Now, let's insert more:
Aurélien Campéas's avatar
Aurélien Campéas committed
98
99

```python
Aurélien Campéas's avatar
Aurélien Campéas committed
100
101
102
 >>> series = pd.Series([2, 7, 8, 9],
 ...                    pd.date_range(start=pd.Timestamp(2017, 1, 2),
 ...                                  freq='D', periods=4))
Aurélien Campéas's avatar
Aurélien Campéas committed
103
 # db insertion
104
105
106
 >>> with engine.begin() as cn:
 >>>     tsh.insert(cn, series, 'my_series', 'babar@pythonian.fr')
 ...
Aurélien Campéas's avatar
Aurélien Campéas committed
107
108
109
110
111
112
113
114
 2017-01-03    7.0
 2017-01-04    8.0
 2017-01-05    9.0
 Name: my_series, dtype: float64

 # you get back the *new information* you put inside
 # and this is why the `2` doesn't appear (it was already put
 # there in the first step)
Aurélien Campéas's avatar
Aurélien Campéas committed
115
116

 # db retrieval
117
118
119
 >>> with engine.begin() as cn:
 >>>     tsh.get(engine, 'my_series')
 ...
Aurélien Campéas's avatar
Aurélien Campéas committed
120
121
122
123
124
125
2017-01-01    1.0
2017-01-02    2.0
2017-01-03    7.0
2017-01-04    8.0
2017-01-05    9.0
Name: my_series, dtype: float64
Aurélien Campéas's avatar
Aurélien Campéas committed
126
127
```

Aurélien Campéas's avatar
Aurélien Campéas committed
128
129
130
131
132
133
It is important to note that the third value was *replaced*, and the two
last values were just *appended*.

As noted the point at `2017-1-2` wasn't a new information so it was
just ignored.

Aurélien Campéas's avatar
Aurélien Campéas committed
134

135
136
## Retrieving history

137
138
139
We can access the whole history (or parts of it) in one call:

```python
140
141
142
 >>> with engine.begin() as cn:
 >>>     history = tsh.get_history(engine, 'my_series')
 ...
Aurélien Campéas's avatar
Aurélien Campéas committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
 >>>
 >>> for idate, series in history.items(): # it's a dict
 ...     print('insertion date:', idate)
 ...     print(series)
 ...
 insertion date: 2018-09-26 17:10:36.988920+02:00
 2017-01-01    1.0
 2017-01-02    2.0
 2017-01-03    3.0
 Name: my_series, dtype: float64
 insertion date: 2018-09-26 17:12:54.508252+02:00
 2017-01-01    1.0
 2017-01-02    2.0
 2017-01-03    7.0
 2017-01-04    8.0
 2017-01-05    9.0
 Name: my_series, dtype: float64
160
161
```

Aurélien Campéas's avatar
Aurélien Campéas committed
162
163
164
165
Note how this shows the full serie state for each insertion date.
Also the insertion date is timzeone aware.

It is possible to show the differences only:
166
167

```python
168
169
170
 >>> with engine.begin() as cn:
 >>>     diffs = tsh.get_history(engine, 'my_series', diffmode=True)
 ...
Aurélien Campéas's avatar
Aurélien Campéas committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184
 >>> for idate, series in tsh.get_history(engine, 'ts', diffmode=True).items():
 ...   print('insertion date:', idate)
 ...   print(series)
 ...
 insertion date: 2018-09-26 17:10:36.988920+02:00
 2017-01-01    1.0
 2017-01-02    2.0
 2017-01-03    3.0
 Name: my_series, dtype: float64
 insertion date: 2018-09-26 17:12:54.508252+02:00
 2017-01-03    7.0
 2017-01-04    8.0
 2017-01-05    9.0
 Name: my_series, dtype: float64
185
```
186

Aurélien Campéas's avatar
Aurélien Campéas committed
187
188
189
190
191
192
193
194
195
196
You can see a series metadata:

```python
 >>> tsh.metadata(engine, 'my_series')
 {'tzaware': False, 'index_type': 'datetime64[ns]', 'value_type': 'float64',
 'index_dtype': '<M8[ns]', 'index_names': [], 'value_dtype': '<f8'}
```

We built a series with naive time stamps, but timezone-aware
timestamps work well (and it is advised to use them !).
197
198


Aurélien Campéas's avatar
Aurélien Campéas committed
199
200
# Command line

201
202
## Basic operations

203
204
205
206
A command line tool is provided, called `tsh`. It provides its usage
guidelines:

```shell
207
 $ tsh
208
209
210
211
212
 Usage: tsh [OPTIONS] COMMAND [ARGS]...

 Options:
   --help  Show this message and exit.

213
Commands:
Aurélien Campéas's avatar
Aurélien Campéas committed
214
  check    coherence checks of the db
215
216
217
218
219
220
  get      show a serie in its current state
  history  show a serie full history
  info     show global statistics of the repository
  init-db  initialize an new db.
  log      show revision history of entire repository or...
  view     visualize time series through the web
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
```

`Info` provides an overview of the time series repository (number of
committed changes, number and series and their names).

```shell
 $ tsh info postgres://babar:babarpassword@dataserver:5432/banana_studies
 changeset count: 209
 series count:    144
 series names:    banana_spot_price, banana_trades, banana_turnover
```

`Log` provides the full history of editions to time series in the
repository.

```shell
 $ tsh log postgres://babar:babar@dataserver:5432/banana_studies --limit 3
 revision: 206
 author:   BABAR
 date:     2017-06-06 15:32:51.502507
 series:   banana_spot_price

 revision: 207
 author:   BABAR
 date:     2017-06-06 15:32:51.676507
 series:   banana_trades

 revision: 209
 author:   CELESTE
 date:     2017-06-06 15:32:51.977507
 series:   banana_turnover
```

All options of all commands can be obtained by using the `--help`
switch:

```shell
 $ tsh log --help
 Usage: tsh log [OPTIONS] DB_URI

 Options:
   -l, --limit TEXT
   --show-diff
   -s, --serie TEXT
   --from-rev TEXT
   --to-rev TEXT
   --help            Show this message and exit.
```
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289


## Extensions

It is possible to augment the `tsh` command with new subcommands (or
augment, modify existing commands).

Any program doing so must define a new command and declare a setup
tools entry point named `tshistory:subcommand` as in e.g.:

```python

    entry_points={'tshistory.subcommands': [
        'view=tsview.command:view'
    ]}
```

For instance, the [tsview][tsview] python package provides such a
`view` subcommand for generic time series visualisation.

[tsview]: https://bitbucket.org/pythonian/tsview
290
[backtesting]: https://en.wikipedia.org/wiki/Backtesting
291
[cross-validation]: https://en.wikipedia.org/wiki/Cross-validation_(statistics)