Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add documentation example for backtesting with time-machine #528

Merged
merged 1 commit into from Feb 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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()