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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
"""Tests for the portfolio loading and processing functionality.

This module tests the functionality in src/folio/portfolio.py for loading and processing
portfolio data from CSV files.
"""

import os

import pandas as pd

from src.folio.data_model import (
    ExposureBreakdown,
    OptionPosition,
    PortfolioGroup,
    PortfolioSummary,
    StockPosition,
)
from src.folio.portfolio import calculate_beta_adjusted_net_exposure


class TestPortfolioLoading:
    """Tests for portfolio loading functionality."""

    def test_load_sample_portfolio(self):
        """Test loading the sample portfolio data from CSV file."""
        # Use the sample portfolio file for testing
        sample_file_path = os.path.join(
            "src", "folio", "assets", "sample-portfolio.csv"
        )

        # Ensure the file exists
        assert os.path.exists(sample_file_path), (
            f"Sample file not found: {sample_file_path}"
        )

        # Load the portfolio data using pandas directly
        portfolio_data = pd.read_csv(sample_file_path)

        # Verify the data was loaded correctly
        assert portfolio_data is not None
        assert len(portfolio_data) > 0

        # Check for expected columns
        expected_columns = [
            "Symbol",
            "Description",
            "Quantity",
            "Last Price",
            "Current Value",
            "Percent Of Account",
            "Type",
        ]
        for column in expected_columns:
            assert column in portfolio_data.columns, (
                f"Column {column} not found in portfolio data"
            )

        # Check for specific entries from the sample file
        assert "AAPL" in portfolio_data["Symbol"].values
        assert "SPAXX**" in portfolio_data["Symbol"].values

        # Check for option entries
        option_entries = portfolio_data[portfolio_data["Symbol"].str.contains("-")]
        assert len(option_entries) > 0, "No option entries found in portfolio data"

        # Check for cash entries
        cash_entries = portfolio_data[portfolio_data["Type"] == "Cash"]
        assert len(cash_entries) > 0, "No cash entries found in portfolio data"

    def test_process_portfolio_data_with_mocks(self):
        """Test processing portfolio data into position objects using mocks."""
        # Since we can't easily mock the process_portfolio_data function due to its complexity,
        # we'll test it indirectly by verifying we can create the objects it would create

        # Create a stock position
        stock_position = StockPosition(
            ticker="AAPL",
            quantity=1500,
            beta=1.2,
            market_exposure=33825.0,
            beta_adjusted_exposure=40590.0,
        )

        # Create an option position
        option_position = OptionPosition(
            ticker="AAPL",
            position_type="option",
            quantity=-15,
            beta=1.2,
            market_exposure=-1100.0,
            beta_adjusted_exposure=-1320.0,
            strike=220.0,
            expiry="2025-04-17",
            option_type="CALL",
            delta=0.7,
            delta_exposure=-1155.0,  # -15 * 0.7 * 110 (notional per contract)
            notional_value=49500.0,  # -15 * 100 * 220 (strike)
            underlying_beta=1.2,
        )

        # Create a portfolio group
        portfolio_group = PortfolioGroup(
            ticker="AAPL",
            stock_position=stock_position,
            option_positions=[option_position],
            net_exposure=32670.0,  # 33825 - 1155
            beta=1.2,
            beta_adjusted_exposure=39270.0,  # 40590 - 1320
            total_delta_exposure=-1155.0,
            options_delta_exposure=-1155.0,
        )

        # Create a cash position
        cash_position = StockPosition(
            ticker="SPAXX**",
            quantity=1,
            beta=0.0,
            market_exposure=12345670.0,
            beta_adjusted_exposure=0.0,
        )

        # Verify the objects were created correctly
        assert portfolio_group.ticker == "AAPL"
        assert portfolio_group.stock_position is not None
        assert portfolio_group.stock_position.quantity == 1500
        assert portfolio_group.stock_position.market_exposure == 33825.0

        # Check the option position
        assert len(portfolio_group.option_positions) == 1
        option = portfolio_group.option_positions[0]
        assert option.ticker == "AAPL"
        assert option.quantity == -15
        assert option.strike == 220.0
        assert option.option_type == "CALL"
        assert option.expiry == "2025-04-17"

        # Check the cash position
        assert cash_position.ticker == "SPAXX**"
        assert cash_position.market_exposure == 12345670.0

    def test_calculate_portfolio_summary_with_mocks(self):
        """Test calculating portfolio summary from position data using mocks."""
        # Create empty exposure breakdowns for testing
        empty_exposure = ExposureBreakdown(
            stock_exposure=0.0,
            stock_beta_adjusted=0.0,
            option_delta_exposure=0.0,
            option_beta_adjusted=0.0,
            total_exposure=0.0,
            total_beta_adjusted=0.0,
            description="Empty exposure",
            formula="N/A",
            components={},
        )

        # Create a portfolio summary directly
        summary = PortfolioSummary(
            net_market_exposure=32670.0,
            portfolio_beta=1.2,
            long_exposure=empty_exposure,
            short_exposure=empty_exposure,
            options_exposure=empty_exposure,
            short_percentage=3.4,
            cash_like_positions=[],
            cash_like_value=12345670.0,
            cash_like_count=1,
            cash_percentage=97.4,
            portfolio_estimate_value=12378340.0,  # 32670 + 12345670
        )

        # Verify the summary was created correctly
        assert isinstance(summary, PortfolioSummary)
        assert summary.net_market_exposure == 32670.0
        assert summary.portfolio_beta == 1.2
        assert summary.cash_like_value == 12345670.0
        assert summary.cash_like_count == 1
        assert summary.portfolio_estimate_value == 12378340.0
        assert summary.cash_percentage == 97.4
        assert summary.short_percentage == 3.4

        # Check the exposure breakdowns
        assert isinstance(summary.long_exposure, ExposureBreakdown)
        assert summary.long_exposure.stock_exposure == 0.0
        assert summary.long_exposure.total_exposure == 0.0

        assert isinstance(summary.short_exposure, ExposureBreakdown)
        assert summary.short_exposure.option_delta_exposure == 0.0
        assert summary.short_exposure.total_exposure == 0.0

        assert isinstance(summary.options_exposure, ExposureBreakdown)
        assert summary.options_exposure.option_delta_exposure == 0.0
        assert summary.options_exposure.total_exposure == 0.0

    def test_empty_portfolio_summary(self):
        """Test creating an empty portfolio summary."""
        # Create empty exposure breakdowns for testing
        empty_exposure = ExposureBreakdown(
            stock_exposure=0.0,
            stock_beta_adjusted=0.0,
            option_delta_exposure=0.0,
            option_beta_adjusted=0.0,
            total_exposure=0.0,
            total_beta_adjusted=0.0,
            description="Empty exposure",
            formula="N/A",
            components={},
        )

        # Create an empty portfolio summary directly
        summary = PortfolioSummary(
            net_market_exposure=0.0,
            portfolio_beta=0.0,
            long_exposure=empty_exposure,
            short_exposure=empty_exposure,
            options_exposure=empty_exposure,
            short_percentage=0.0,
            cash_like_positions=[],
            cash_like_value=0.0,
            cash_like_count=0,
            cash_percentage=0.0,
            portfolio_estimate_value=0.0,
        )

        # Verify the summary for empty portfolio
        assert summary.net_market_exposure == 0.0
        assert summary.portfolio_beta == 0.0
        assert summary.cash_like_value == 0.0
        assert summary.cash_like_count == 0
        assert summary.portfolio_estimate_value == 0.0
        assert summary.cash_percentage == 0.0
        assert summary.short_percentage == 0.0


class TestPortfolioUtilityFunctions:
    """Tests for utility functions in the portfolio module."""

    def test_calculate_beta_adjusted_net_exposure(self):
        """Test the calculate_beta_adjusted_net_exposure function.

        This function tests that the beta-adjusted net exposure is correctly calculated
        by adding the long and short beta-adjusted exposures, where short is represented
        as a negative value.
        """
        # Test with positive long and negative short values
        long_beta_adjusted = 14400.0
        short_beta_adjusted = -7200.0  # Negative value for short exposure
        expected_net = 7200.0

        result = calculate_beta_adjusted_net_exposure(
            long_beta_adjusted, short_beta_adjusted
        )
        assert result == expected_net

        # Test with zero values
        assert calculate_beta_adjusted_net_exposure(0.0, 0.0) == 0.0

        # Test with negative long value and negative short value
        assert calculate_beta_adjusted_net_exposure(-1000.0, -500.0) == -1500.0

        # Test with large values
        large_long = 1_000_000.0
        large_short = -500_000.0  # Negative value for short exposure
        assert (
            calculate_beta_adjusted_net_exposure(large_long, large_short) == 500_000.0
        )


class TestOptionMarketValue:
    """Tests for option market value calculation."""

    def test_option_market_value_calculation(self):
        """Test that option market value is calculated correctly with 100x multiplier."""
        # Create an option position
        option_position = OptionPosition(
            ticker="SPY",
            position_type="option",
            quantity=10,
            beta=1.0,
            beta_adjusted_exposure=1000.0,
            market_exposure=1000.0,
            strike=450.0,
            expiry="2025-06-20",
            option_type="CALL",
            delta=0.5,
            delta_exposure=1000.0,
            notional_value=450000.0,  # 10 contracts * 100 shares * $450 strike
            underlying_beta=1.0,
            price=5.0,  # $5 per share
        )

        # Verify the market value is calculated with 100x multiplier
        # Market value should be: quantity * price * 100
        expected_market_value = (
            10 * 5.0 * 100
        )  # 10 contracts * $5 * 100 shares per contract
        assert option_position.market_value == expected_market_value
        assert option_position.market_value == 5000.0

        # Test with negative quantity (short position)
        short_option = OptionPosition(
            ticker="SPY",
            position_type="option",
            quantity=-5,
            beta=1.0,
            beta_adjusted_exposure=-500.0,
            market_exposure=-500.0,
            strike=450.0,
            expiry="2025-06-20",
            option_type="PUT",
            delta=-0.5,
            delta_exposure=-500.0,
            notional_value=225000.0,  # 5 contracts * 100 shares * $450 strike
            underlying_beta=1.0,
            price=2.0,  # $2 per share
        )

        # Verify the market value for short position
        expected_short_value = (
            -5 * 2.0 * 100
        )  # -5 contracts * $2 * 100 shares per contract
        assert short_option.market_value == expected_short_value
        assert short_option.market_value == -1000.0


class TestPriceUpdates:
    """Tests for portfolio price update functionality."""

    def test_update_portfolio_prices(self, mocker):
        """Test updating prices for portfolio positions."""
        # Create mock data fetcher
        mock_data_fetcher = mocker.MagicMock()
        mock_df = pd.DataFrame({"Close": [150.0]})
        mock_data_fetcher.fetch_data.return_value = mock_df

        # Create test portfolio groups
        stock_position = StockPosition(
            ticker="AAPL",
            quantity=100,
            beta=1.2,
            market_exposure=14000.0,  # Old price: $140
            beta_adjusted_exposure=16800.0,
            price=140.0,
        )

        option_position = OptionPosition(
            ticker="AAPL",
            position_type="option",
            quantity=1,
            beta=1.2,
            market_exposure=500.0,
            beta_adjusted_exposure=600.0,
            strike=150.0,
            expiry="2025-01-17",
            option_type="CALL",
            delta=0.5,
            delta_exposure=50.0,
            notional_value=15000.0,
            underlying_beta=1.2,
            price=5.0,  # Old price
        )

        portfolio_group = PortfolioGroup(
            ticker="AAPL",
            stock_position=stock_position,
            option_positions=[option_position],
            net_exposure=14500.0,
            beta=1.2,
            beta_adjusted_exposure=17400.0,
            total_delta_exposure=50.0,
            options_delta_exposure=50.0,
        )

        # Update prices
        from src.folio.portfolio import update_portfolio_prices

        timestamp = update_portfolio_prices([portfolio_group], mock_data_fetcher)

        # Verify the timestamp is returned
        assert timestamp is not None
        assert isinstance(timestamp, str)

        # Verify the prices were updated
        assert stock_position.price == 150.0
        assert option_position.price == 150.0

        # Verify market exposure was updated for stock position
        assert stock_position.market_exposure == 15000.0  # 100 shares * $150
        assert stock_position.beta_adjusted_exposure == 18000.0  # $15000 * 1.2

        # Verify the data fetcher was called correctly
        mock_data_fetcher.fetch_data.assert_called_with("AAPL", period="1d")

    def test_update_portfolio_summary_with_prices(self, mocker):
        """Test updating the portfolio summary with the latest prices."""
        # Mock the update_portfolio_prices function
        mock_update_prices = mocker.patch(
            "src.folio.portfolio.update_portfolio_prices",
            return_value="2025-04-08T12:34:56.789012",
        )

        # Mock the calculate_portfolio_summary function
        mock_summary = PortfolioSummary(
            net_market_exposure=10000.0,
            portfolio_beta=1.2,
            long_exposure=ExposureBreakdown(
                stock_exposure=10000.0,
                stock_beta_adjusted=12000.0,
                option_delta_exposure=0.0,
                option_beta_adjusted=0.0,
                total_exposure=10000.0,
                total_beta_adjusted=12000.0,
                description="Long Exposure",
                formula="",
                components={},
            ),
            short_exposure=ExposureBreakdown(
                stock_exposure=0.0,
                stock_beta_adjusted=0.0,
                option_delta_exposure=0.0,
                option_beta_adjusted=0.0,
                total_exposure=0.0,
                total_beta_adjusted=0.0,
                description="Short Exposure",
                formula="",
                components={},
            ),
            options_exposure=ExposureBreakdown(
                stock_exposure=0.0,
                stock_beta_adjusted=0.0,
                option_delta_exposure=0.0,
                option_beta_adjusted=0.0,
                total_exposure=0.0,
                total_beta_adjusted=0.0,
                description="Options Exposure",
                formula="",
                components={},
            ),
            short_percentage=0.0,
            cash_like_positions=[],
            cash_like_value=0.0,
            cash_like_count=0,
            cash_percentage=0.0,
            portfolio_estimate_value=10000.0,
        )
        mocker.patch(
            "src.folio.portfolio.calculate_portfolio_summary",
            return_value=mock_summary,
        )

        # Create test portfolio groups
        portfolio_groups = [mocker.MagicMock()]
        current_summary = mocker.MagicMock()

        # Update the portfolio summary with prices
        from src.folio.portfolio import update_portfolio_summary_with_prices

        updated_summary = update_portfolio_summary_with_prices(
            portfolio_groups, current_summary
        )

        # Verify the price_updated_at timestamp was set
        assert updated_summary.price_updated_at == "2025-04-08T12:34:56.789012"

        # Verify the update_portfolio_prices function was called
        mock_update_prices.assert_called_once_with(portfolio_groups, None)

    def test_process_orphaned_options(self):
        """Test that options without a matching stock position are properly processed.

        This test verifies that the portfolio processing logic correctly handles
        options without a matching stock position (like SPY options without a SPY stock position).
        """
        # Create a test DataFrame with only option positions (no matching stock)
        data = {
            "Symbol": ["-SPY250620C580", "-SPY250620P470", "-SPY250620P525"],
            "Description": [
                "SPY JUN 20 2025 $580 CALL",
                "SPY JUN 20 2025 $470 PUT",
                "SPY JUN 20 2025 $525 PUT",
            ],
            "Quantity": [-30, -30, 30],
            "Last Price": [5.37, 7.29, 17.76],
            "Current Value": [-16110.00, -21870.00, 53280.00],
            "Percent Of Account": [-0.60, -0.81, 1.98],
            "Type": ["Margin", "Margin", "Margin"],
        }
        df = pd.DataFrame(data)

        # Import the function directly in the test to avoid circular imports
        from src.folio.portfolio import process_portfolio_data

        # Process the portfolio data
        groups, summary, cash_like = process_portfolio_data(df)

        # Verify that a group was created for the SPY options
        assert len(groups) > 0, "No portfolio groups were created"

        # Find the SPY group
        spy_group = None
        for group in groups:
            if group.ticker == "SPY":
                spy_group = group
                break

        # Verify that the SPY group exists
        assert spy_group is not None, "SPY group was not created"

        # Verify that the SPY group has options but no stock position
        assert len(spy_group.option_positions) == 3, (
            "SPY group should have 3 option positions"
        )

        # Verify the option positions
        assert spy_group.option_positions[0].ticker == "SPY"
        assert spy_group.option_positions[1].ticker == "SPY"
        assert spy_group.option_positions[2].ticker == "SPY"

        # Verify the option types
        call_count = sum(
            1 for opt in spy_group.option_positions if opt.option_type == "CALL"
        )
        put_count = sum(
            1 for opt in spy_group.option_positions if opt.option_type == "PUT"
        )
        assert call_count == 1, "Should have 1 CALL option"
        assert put_count == 2, "Should have 2 PUT options"

        # Verify the quantities
        assert spy_group.option_positions[0].quantity == -30
        assert spy_group.option_positions[1].quantity == -30
        assert spy_group.option_positions[2].quantity == 30