Skip to content

Commit c240794

Browse files
authored
fix yield spread, add test (#9)
1 parent 975fcb8 commit c240794

File tree

2 files changed

+78
-2
lines changed

2 files changed

+78
-2
lines changed

liquidity/compute/utils/yields.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,5 @@ def compute_dividend_yield(prices: pd.DataFrame, dividends: pd.DataFrame) -> pd.
1717
def yield_formula(row: pd.Series[np.float64]) -> np.float64:
1818
return ((row[Fields.TTM_Dividend] or 0.0) / row[OHLCV.Close]) * 100.0
1919

20-
df[Fields.Yield] = df.apply(yield_formula, axis=1)
21-
return df[[Fields.Yield]]
20+
df[Fields.Yield.value] = df.apply(yield_formula, axis=1)
21+
return df[[Fields.Yield.value]]
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import pandas as pd
2+
import pytest
3+
4+
from liquidity.models.yield_spread import YieldSpread
5+
from liquidity.compute.utils.yields import compute_dividend_yield
6+
from liquidity.data.metadata.entities import AssetMetadata, AssetTypes
7+
8+
9+
class MockTicker:
10+
def __init__(self, symbol, prices, dividends):
11+
self.symbol = symbol
12+
self._prices = prices
13+
self._dividends = dividends
14+
self.metadata = AssetMetadata(
15+
ticker=symbol,
16+
name=symbol,
17+
type=AssetTypes.ETF,
18+
subtype="Bonds",
19+
currency="USD",
20+
distributing=True,
21+
distribution_frequency=12,
22+
)
23+
24+
@property
25+
def prices(self):
26+
return self._prices
27+
28+
@property
29+
def dividends(self):
30+
return self._dividends
31+
32+
@property
33+
def yields(self):
34+
return compute_dividend_yield(self.prices, self.dividends)
35+
36+
@staticmethod
37+
def for_symbol(symbol: str):
38+
idx = pd.date_range("2023-01-01", periods=3)
39+
data = {
40+
"HYG": {
41+
"prices": pd.DataFrame({"Close": [100, 100, 100]}, index=idx),
42+
"dividends": pd.DataFrame({"TTM_Dividend": [5.5, 5.48, 5.51]}, index=idx)
43+
},
44+
"LQD": {
45+
"prices": pd.DataFrame({"Close": [100, 100, 100]}, index=idx),
46+
"dividends": pd.DataFrame({"TTM_Dividend": [3.2, 3.25, 3.19]}, index=idx)
47+
}
48+
}
49+
return MockTicker(
50+
symbol,
51+
prices=data[symbol]["prices"],
52+
dividends=data[symbol]["dividends"],
53+
)
54+
55+
56+
@pytest.fixture
57+
def mock_tickers(monkeypatch):
58+
monkeypatch.setattr("liquidity.models.yield_spread.Ticker", MockTicker)
59+
60+
61+
class TestYieldSpread:
62+
def test_calculation(self, mock_tickers):
63+
spread = YieldSpread("HYG", "LQD")
64+
expected = pd.DataFrame(
65+
{
66+
"YieldHYG": [5.5, 5.48, 5.51],
67+
"YieldLQD": [3.2, 3.25, 3.19],
68+
"Spread": [
69+
5.5 - 3.2,
70+
5.48 - 3.25,
71+
5.51 - 3.19,
72+
],
73+
},
74+
index=pd.date_range("2023-01-01", periods=3),
75+
)
76+
pd.testing.assert_frame_equal(spread.df, expected)

0 commit comments

Comments
 (0)