Skip to content

Commit

Permalink
Merge pull request #528 from JWCook/backtesting-example
Browse files Browse the repository at this point in the history
Add documentation example for backtesting with time-machine
  • Loading branch information
JWCook committed Feb 15, 2022
2 parents c2baccd + 1b2ba6c commit 2b88d91
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
14 changes: 14 additions & 0 deletions docs/examples.md
Expand Up @@ -133,3 +133,17 @@ The following scripts can also be found in the
:lines: 1,17-
```
:::


### Backtesting with time-machine
```{include} ../examples/time_machine_backtesting.py
:start-line: 2
:end-line: 4
```

:::{admonition} Example: custom_request_matcher.py
:class: toggle
```{literalinclude} ../examples/time_machine_backtesting.py
:lines: 1,6-
```
:::
38 changes: 38 additions & 0 deletions examples/time_machine_backtesting.py
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""
An example of using the [time-machine](https://github.com/adamchainz/time-machine) library for backtesting,
e.g., testing with cached responses that were available at an arbitrary time in the past.
"""
from datetime import datetime

import requests
import time_machine
from requests_cache import CachedSession, set_response_defaults


class BacktestCachedSession(CachedSession):
def request(self, method: str, url: str, **kwargs):
response = super().request(method, url, **kwargs)

# Response was cached after the (simulated) current time, so ignore it and send a new request
if response.created_at and response.created_at > datetime.utcnow():
new_response = requests.request(method, url, **kwargs)
return set_response_defaults(new_response)
else:
return response


def demo():
session = BacktestCachedSession()
response = session.get('https://httpbin.org/get')
response = session.get('https://httpbin.org/get')
assert response.from_cache is True

# Response was not cached yet at this point, so we should get a fresh one
with time_machine.travel(datetime(2020, 1, 1)):
response = session.get('https://httpbin.org/get')
assert response.from_cache is False


if __name__ == '__main__':
demo()

0 comments on commit 2b88d91

Please sign in to comment.