Skip to content

Commit

Permalink
CI Integration, Readme and Licensing
Browse files Browse the repository at this point in the history
  • Loading branch information
markovejnovic committed Dec 4, 2023
1 parent 2805583 commit 9bff8ea
Show file tree
Hide file tree
Showing 18 changed files with 357 additions and 111 deletions.
1 change: 1 addition & 0 deletions .github/res/badges/code-style.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions .github/res/badges/python-version.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
39 changes: 25 additions & 14 deletions .github/workflows/lint-test.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: lint-and-test
run-name: Lint and Test
name: ci-regressions
run-name: Run CI Regressions
on:
pull_request:
branches:
Expand All @@ -9,25 +9,36 @@ on:
- main

jobs:
lint:
name: Build Lint and Test Code
regressions:
name: CI Regression Tests
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4

- name: Install Dependencies
run: |
sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get install -y poetry
poetry install
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.12'
cache: 'pip'

- name: Build Lint and Test
run: |
make ci-build-lint-test
- name: Grab Tox and Poetry
run: pip install tox poetry

- name: Lint and Test
run: tox
env:
MARKETSTACK_TOKEN_TEST: "${{ secrets.MarketstackFreeTestToken }}"
MARKETSTACK_TOKEN_TEST: "${{ secrets.MARKETSTACK_TOKEN_TEST }}"

- name: Run a Build
run: poetry build

- name: Create a build-artifacts tarball
run: |
tar -czf \
build-artifacts.tar.gz \
test-artifacts-* \
dist
- name: Upload Artifacts
uses: actions/upload-artifact@v3
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -160,4 +160,5 @@ cython_debug/
#.idea/

# Build Artifact ignores
build-artifacts
build-artifacts*/
build-artifacts.tar.gz
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Marko Vejnovic <markovejnovic@plocca.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
28 changes: 0 additions & 28 deletions Makefile

This file was deleted.

140 changes: 136 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,149 @@
# aiomarketstack

`aiomarketstack` is a thin-and-light, Python-only `asyncio`-based
[marketsack](https://marketstack.com/) client.
![Python 3.8-3.11](.github/res/badges/python-version.svg)
![Code Style](.github/res/badges/code-style.svg)

## Getting Started
_`aiomarketstack` is an unofficial Python-only `asyncio`-based
[Marketstack](https://marketstack.com/) client._

This library aims to be extremely observable and, therefore, comes with
`structlog` (which I adore ❤️) support out of the box. I am also currently
working on `OpenTelemetry` metrics as well.

## Installing

To get started, grab yourself a copy of `aiomarketstack`:

```bash
pip install aiomarketstack
```

## Getting Started

The easiest way to use client is via the `HttpMarketstackClient`. The following
example illustrates the most powerful utilities in `aiomarketstack`.

```python
from __future__ import annotations

import asyncio

from datetime import date
import matplotlib.pyplot as plt

from aiomarketstack import HttpMarketstackClient, MarketstackPlan
from aiomarketstack.exceptions import ResponseError
from aiomarketstack.types import Eod


async def main():
date_range = (date(2023, 1, 1), date(2023, 1, 31))

async with HttpMarketstackClient(
"your-token-here",
MarketstackPlan.FREE
) as client:
try:
eod_values: tuple[Eod, ...] = (
await client.get_eod_range(("AMZN", ), date_range)
)
except ResponseError as resp_err:
print(f"Uh-oh, a response error ocurred: {resp_err}")
raise

# Note that there will be missing data (if the market was closed).
plt_xaxis = [eod["date"] for eod in eod_values]
plt_yaxes = {
key: [eod[key] for eod in eod_values]
for key in {"open", "high", "low", "close"}
}

for label, data in plt_yaxes.items():
plt.plot(plt_xaxis, data, label=label.capitalize())
plt.legend()
plt.grid()
plt.title("End-of-day prices for AMZN for January 2023")
plt.xlabel("Date in January")
plt.ylabel("Price in $")
plt.show()


asyncio.run(main())
```

Run this example to get a pretty output:

![Matplotlib Example Output](docs/res/example_matplotlib_plot.png)

## Documentation

In progress!

### Why not [marketstack-python](https://github.com/mreiche/marketstack-python)?

The main reason this library exists is because I found the great
[marketstack-python](https://github.com/mreiche/marketstack-python) to be
unwieldy for my needs.

The three main advantages of `aiomarketstack` are:

* OpenTelemetry Metrics (Currently In Progress)
* [structlog](https://www.structlog.org/en/stable/)-style Logging.
* Much more flexible API

The main disadvantage of this library, compared with
[marketstack-python](https://github.com/mreiche/marketstack-python) is that it
does not and **will not** cache your queries. This is not and will not be the
goal of this library.

## Development

To manually build `aiomarketstack` for development, we use `poetry`. Get
started with:

```bash
git clone https://github.com/markovejnovic/aiomarketstack.git
cd aiomarketstack
poetry install && poetry build
```

### Unit Tests

You can test your code against test suite via `tox`.

```bash
MARKETSTACK_TOKEN_TEST=<Your-Marketstack-Free-Token> tox
```

> [!CAUTION]
> This will consume about 30 API requests.
## Contributing

In progress! Feel free to open a issue if you spot something!

## License

## Dependencies
```
MIT License
Copyright (c) 2023 Marko Vejnovic <markovejnovic@plocca.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
15 changes: 12 additions & 3 deletions aiomarketstack/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,23 @@
from __future__ import annotations

import warnings
from datetime import date, datetime
from datetime import date, datetime, timezone
from enum import IntEnum
from typing import (
TYPE_CHECKING,
AsyncGenerator,
Callable,
Collection,
Literal,
Self,
)

import aiohttp
import structlog
from aiohttp import ClientResponse, ClientSession

if TYPE_CHECKING:
from typing_extensions import Self

from aiomarketstack.exceptions import (
ForbiddenError,
FunctionAccessRestrictedError,
Expand Down Expand Up @@ -306,9 +308,16 @@ def _deserialize_eod(raw_eod: RawEod) -> Eod:
"dividend": raw_eod["dividend"],
"symbol": raw_eod["symbol"],
"exchange": raw_eod["exchange"],
"date": datetime.fromisoformat(raw_eod["date"]).date(),
"date": _MarketstackClient._parse_marketstack_date(raw_eod["date"]),
}

@staticmethod
def _parse_marketstack_date(date_str: str) -> date:
# Necessary because python < 3.11's fromisoformat didn't support IS8601.
marketstack_date_format = "%Y-%m-%dT%H:%M:%S%z"
return datetime.strptime(date_str, marketstack_date_format) \
.replace(tzinfo=timezone.utc).date()


class HttpMarketstackClient(_MarketstackClient):
"""The main marketstack client.
Expand Down
2 changes: 1 addition & 1 deletion aiomarketstack/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Marketstack Error Response Errors."""

from typing import Self

from aiohttp.client import ClientResponse
from typing_extensions import Self


class ResponseError(Exception):
Expand Down
4 changes: 3 additions & 1 deletion aiomarketstack/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

from __future__ import annotations

from typing import TYPE_CHECKING, NotRequired, Required, Sequence, TypedDict
from typing import TYPE_CHECKING, Sequence, TypedDict

if TYPE_CHECKING:
from datetime import date

from typing_extensions import NotRequired, Required


class Eod(TypedDict):
"""Represents an end-of-day marketstack return type."""
Expand Down
45 changes: 45 additions & 0 deletions docs/examples/matplotlib_plot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from __future__ import annotations

import asyncio

from datetime import date
import matplotlib.pyplot as plt

from aiomarketstack import HttpMarketstackClient, MarketstackPlan
from aiomarketstack.exceptions import ResponseError
from aiomarketstack.types import Eod


async def main():
date_range = (date(2023, 1, 1), date(2023, 1, 31))

async with HttpMarketstackClient(
"your-token-here",
MarketstackPlan.FREE
) as client:
try:
eod_values: tuple[Eod, ...] = (
await client.get_eod_range(("AMZN", ), date_range)
)
except ResponseError as resp_err:
print(f"Uh-oh, a response error ocurred: {resp_err}")
raise

# Note that there will be missing data (if the market was closed).
plt_xaxis = [eod["date"] for eod in eod_values]
plt_yaxes = {
key: [eod[key] for eod in eod_values]
for key in {"open", "high", "low", "close"}
}

for label, data in plt_yaxes.items():
plt.plot(plt_xaxis, data, label=label)
plt.legend()
plt.grid()
plt.title("End-of-day prices for AMZN for January 2023")
plt.xlabel("Date in January")
plt.ylabel("Price in $")
plt.show()


asyncio.run(main())
Binary file added docs/res/example_matplotlib_plot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 9bff8ea

Please sign in to comment.