Skip to content

Add fiscal data #28

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

Merged
merged 4 commits into from
May 31, 2025
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions notebooks/_config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
# Learn more at https://jupyterbook.org/customize/config.html

title: Quantflow library
author: Quantmind Team
copyright: "2024"
author: <a href="https://quantmind.com">quantmind</a>
copyright: "2014-2025"
logo: assets/quantflow-light.svg

# Force re-execution of notebooks on each build.
Expand Down
31 changes: 31 additions & 0 deletions notebooks/data/fiscal_data.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
jupytext:
text_representation:
extension: .md
format_name: myst
format_version: 0.13
jupytext_version: 1.16.6
kernelspec:
display_name: Python 3 (ipykernel)
language: python
name: python3
---

# Fiscal Data

```{code-cell} ipython3
from quantflow.data.fiscal_data import FiscalData
```

```{code-cell} ipython3
fd = FiscalData()
```

```{code-cell} ipython3
data = await fd.securities()
data
```

```{code-cell} ipython3

```
22 changes: 21 additions & 1 deletion notebooks/data/fmp.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,25 @@ The library provides a python client for the [Financial Modelling Prep API](http

```{code-cell} ipython3
from quantflow.data.fmp import FMP
import pandas as pd
cli = FMP()
cli.url
```

## Get path

```{code-cell} ipython3
d = await cli.get_path("stock-list")
pd.DataFrame(d)
```

## Search

```{code-cell} ipython3
d = await cli.search("electric")
pd.DataFrame(d)
```

```{code-cell} ipython3
stock = "KNOS.L"
```
Expand All @@ -41,7 +56,7 @@ c
## Executive trading

```{code-cell} ipython3
stock = "KNOS.L"
stock = "AAPL"
```

```{code-cell} ipython3
Expand All @@ -58,3 +73,8 @@ await cli.insider_trading(stock)
c = await cli.news(stock)
c
```

```{code-cell} ipython3
p = await cli.market_risk_premium()
pd.DataFrame(p)
```
2,989 changes: 1,532 additions & 1,457 deletions poetry.lock

Large diffs are not rendered by default.

24 changes: 11 additions & 13 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "quantflow"
version = "0.3.2"
version = "0.3.3"
description = "quantitative analysis"
authors = ["Luca <[email protected]>"]
license = "BSD-3-Clause"
Expand All @@ -17,21 +17,21 @@ scipy = "^1.14.1"
pydantic = "^2.0.2"
ccy = { version = "^1.7.1" }
python-dotenv = "^1.0.1"
polars = {version = "^1.11.0", extras=["pandas", "pyarrow"]}
polars = { version = "^1.11.0", extras = ["pandas", "pyarrow"] }
asciichartpy = { version = "^1.5.25", optional = true }
prompt-toolkit = { version = "^3.0.43", optional = true }
aio-fluid = {version = "^1.2.1", extras=["http"], optional = true}
rich = {version = "^13.9.4", optional = true}
click = {version = "^8.1.7", optional = true}
holidays = {version = "^0.63", optional = true}
async-cache = {version = "^1.1.1", optional = true}
aio-fluid = { version = "^1.2.1", extras = ["http"], optional = true }
rich = { version = "^13.9.4", optional = true }
click = { version = "^8.1.7", optional = true }
holidays = { version = "^0.63", optional = true }
async-cache = { version = "^1.1.1", optional = true }

[tool.poetry.group.dev.dependencies]
black = "^25.1.0"
pytest-cov = "^6.0.0"
mypy = "^1.14.1"
ghp-import = "^2.0.2"
ruff = "^0.11.2"
ruff = "^0.11.12"
pytest-asyncio = "^0.26.0"
isort = "^6.0.1"

Expand All @@ -44,7 +44,7 @@ cli = [
"prompt-toolkit",
"rich",
"click",
"holidays"
"holidays",
]

[tool.poetry.group.book]
Expand Down Expand Up @@ -74,9 +74,7 @@ formats = "ipynb,myst"

[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = [
"quantflow_tests"
]
testpaths = ["quantflow_tests"]

[tool.isort]
profile = "black"
Expand All @@ -102,7 +100,7 @@ module = [
"IPython.*",
"pandas.*",
"plotly.*",
"scipy.*"
"scipy.*",
]
ignore_missing_imports = true
disallow_untyped_defs = false
2 changes: 1 addition & 1 deletion quantflow/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""Quantitative analysis and pricing"""

__version__ = "0.3.2"
__version__ = "0.3.3"
34 changes: 31 additions & 3 deletions quantflow/cli/commands/crypto.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from cache import AsyncTTL
from ccy.cli.console import df_to_rich

from quantflow.data.deribit import Deribit
from quantflow.data.deribit import Deribit, InstrumentKind
from quantflow.options.surface import VolSurface
from quantflow.utils.numbers import round_to_step

Expand All @@ -24,13 +24,34 @@ def crypto() -> None:
ctx.set_as_section()


@crypto.command()
@click.argument("currency")
@click.option(
"-k",
"--kind",
type=click.Choice(list(InstrumentKind)),
default=InstrumentKind.spot.value,
)
def instruments(currency: str, kind: str) -> None:
"""Provides information about instruments

Instruments for given cryptocurrency from Deribit API"""
ctx = QuantContext.current()
data = asyncio.run(get_instruments(ctx, currency, kind))
df = pd.DataFrame(data)
ctx.qf.print(df_to_rich(df))


@crypto.command()
@click.argument("currency")
@options.length
@options.height
@options.chart
def volatility(currency: str, length: int, height: int, chart: bool) -> None:
"""Provides information about historical volatility for given cryptocurrency"""
"""Provides information about historical volatility

Historical volatility for given cryptocurrency from Deribit API
"""
ctx = QuantContext.current()
df = asyncio.run(get_volatility(ctx, currency))
df["volatility"] = df["volatility"].map(lambda p: round_to_step(p, "0.01"))
Expand Down Expand Up @@ -109,9 +130,16 @@ def prices(symbol: str, height: int, length: int, chart: bool, frequency: str) -
)


async def get_instruments(ctx: QuantContext, currency: str, kind: str) -> list[dict]:
async with Deribit() as client:
return await client.get_instruments(
currency=currency, kind=InstrumentKind(kind)
)


async def get_volatility(ctx: QuantContext, currency: str) -> pd.DataFrame:
async with Deribit() as client:
return await client.get_volatility(params=dict(currency=currency))
return await client.get_volatility(currency)


@AsyncTTL(time_to_live=10)
Expand Down
14 changes: 14 additions & 0 deletions quantflow/cli/commands/stocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ def stocks() -> None:
ctx.set_as_section()


@stocks.command()
def indices() -> None:
"""Search companies"""
ctx = QuantContext.current()
data = asyncio.run(get_indices(ctx))
df = pd.DataFrame(data)
ctx.qf.print(df_to_rich(df))


@stocks.command()
@click.argument("symbol")
def profile(symbol: str) -> None:
Expand Down Expand Up @@ -78,6 +87,11 @@ def sectors(period: str) -> None:
ctx.qf.print(df_to_rich(df))


async def get_indices(ctx: QuantContext) -> list[dict]:
async with ctx.fmp() as cli:
return await cli.indices()


async def get_prices(ctx: QuantContext, symbol: str, frequency: str) -> pd.DataFrame:
async with ctx.fmp() as cli:
return await cli.prices(symbol, frequency)
Expand Down
61 changes: 48 additions & 13 deletions quantflow/data/deribit.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import enum
from dataclasses import dataclass
from datetime import datetime, timezone
from decimal import Decimal
from typing import Any, cast

import pandas as pd
from dateutil.parser import parse
from fluid.utils.data import compact_dict
from fluid.utils.http_client import AioHttpClient, HttpResponse, HttpResponseError

from quantflow.options.surface import VolSecurityType, VolSurfaceLoader
Expand All @@ -14,47 +17,79 @@ def parse_maturity(v: str) -> datetime:
return parse(v).replace(tzinfo=timezone.utc, hour=8)


class InstrumentKind(enum.StrEnum):
"""Instrument kind for Deribit API."""

future = enum.auto()
option = enum.auto()
spot = enum.auto()
future_combo = enum.auto()
option_combo = enum.auto()


@dataclass
class Deribit(AioHttpClient):
"""Deribit API client

Fetch market and static data from `Deribit`_.
Fetch market and static data from `Deribit`_ API.

.. _Deribit: https://docs.deribit.com/
"""

url = "https://www.deribit.com/api/v2"
url: str = "https://www.deribit.com/api/v2"

async def get_book_summary_by_instrument(self, **kw: Any) -> list[dict]:
kw.update(callback=self.to_result)
async def get_book_summary_by_instrument(
self,
instrument_name: str,
**kw: Any,
) -> list[dict]:
"""Get the book summary for a given instrument."""
kw.update(params=dict(instrument_name=instrument_name), callback=self.to_result)
return cast(
list[dict],
await self.get_path("public/get_book_summary_by_instrument", **kw),
)

async def get_book_summary_by_currency(self, **kw: Any) -> list[dict]:
kw.update(callback=self.to_result)
async def get_book_summary_by_currency(
self, currency: str, kind: InstrumentKind | None = None, **kw: Any
) -> list[dict]:
"""Get the book summary for a given currency."""
kw.update(
params=compact_dict(currency=currency, kind=kind), callback=self.to_result
)
return cast(
list[dict], await self.get_path("public/get_book_summary_by_currency", **kw)
)

async def get_instruments(self, **kw: Any) -> list[dict]:
kw.update(callback=self.to_result)
async def get_instruments(
self,
currency: str,
kind: InstrumentKind | None = None,
expired: bool | None = None,
**kw: Any,
) -> list[dict]:
"""Get the list of instruments for a given currency."""
kw.update(
params=compact_dict(currency=currency, kind=kind, expired=expired),
callback=self.to_result,
)
return cast(list[dict], await self.get_path("public/get_instruments", **kw))

async def get_volatility(self, **kw: Any) -> pd.DataFrame:
kw.update(callback=self.to_df)
async def get_volatility(self, currency: str, **kw: Any) -> pd.DataFrame:
"""Provides information about historical volatility for given cryptocurrency"""
kw.update(params=dict(currency=currency), callback=self.to_df)
return await self.get_path("public/get_historical_volatility", **kw)

async def volatility_surface_loader(self, currency: str) -> VolSurfaceLoader:
"""Create a :class:`.VolSurfaceLoader` for a given crypto-currency"""
loader = VolSurfaceLoader()
futures = await self.get_book_summary_by_currency(
params=dict(currency=currency, kind="future")
currency=currency, kind=InstrumentKind.future
)
options = await self.get_book_summary_by_currency(
params=dict(currency=currency, kind="option")
currency=currency, kind=InstrumentKind.option
)
instruments = await self.get_instruments(params=dict(currency=currency))
instruments = await self.get_instruments(currency=currency)
instrument_map = {i["instrument_name"]: i for i in instruments}
min_tick_size = Decimal("inf")
for future in futures:
Expand Down
11 changes: 3 additions & 8 deletions quantflow/data/fed.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,7 @@
import pandas as pd
from fluid.utils.http_client import AioHttpClient

URL = (
"https://www.federalreserve.gov/datadownload/Output.aspx?"
"rel=H15&series=bf17364827e38702b42a58cf8eaa3f78&lastobs=&"
)

maturities = [
MATURITIES = (
"month_1",
"month_3",
"month_6",
Expand All @@ -23,7 +18,7 @@
"year_10",
"year_20",
"year_30",
]
)


@dataclass
Expand Down Expand Up @@ -52,7 +47,7 @@ async def yield_curves(self, **params: Any) -> pd.DataFrame:
params.update(series="bf17364827e38702b42a58cf8eaa3f78", rel="H15")
data = await self._get_text(params)
df = pd.read_csv(data, header=5, index_col=None, parse_dates=True)
df.columns = ["date"] + maturities # type: ignore
df.columns = list(("date",) + MATURITIES) # type: ignore
df = df.set_index("date").replace("ND", np.nan)
return df.dropna(axis=0, how="all").reset_index()

Expand Down
Loading