|
| 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