Skip to content

Commit e0e18b9

Browse files
TexasCodingclaude
andauthored
Fix test failures and improve Yahoo news fetching reliability (#64)
* update * Fix test failures and improve Yahoo news fetching reliability - Add CLAUDE.md with comprehensive development guidance - Fix test_close_a_order_by_id assertion for escaped quotes - Refactor Yahoo news fetching to avoid scraping issues: * Add scrape_content parameter (defaults to False) * Use metadata from yfinance API instead of scraping * Fall back to summaries when full content unavailable * Handle Yahoo's anti-scraping measures gracefully - Update tests to reflect new Yahoo news behavior 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]> * Update dependencies and code improvements - Lower Python requirement to >=3.10 for broader compatibility - Add GEMINI.md guidance file for Gemini AI assistance - Improve screener.py error handling with length check - Remove unused caching session from recommendations.py - Update uv.lock with dependency changes 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]> * update --------- Co-authored-by: Claude <[email protected]>
1 parent 0429b6f commit e0e18b9

File tree

12 files changed

+1463
-544
lines changed

12 files changed

+1463
-544
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,3 +163,5 @@ cython_debug/
163163
# and can be added to the global gitignore or merged into this file. For a more nuclear
164164
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
165165
#.idea/
166+
167+
# test.sh

CLAUDE.md

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
# CLAUDE.md
2+
3+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4+
5+
## Development Commands
6+
7+
### Package Management
8+
This project uses `uv` for dependency management (migrated from Poetry).
9+
10+
```bash
11+
# Install dependencies
12+
uv sync --all-extras --dev
13+
14+
# Add a new dependency
15+
uv add <package-name>
16+
17+
# Add a dev dependency
18+
uv add --dev <package-name>
19+
```
20+
21+
### Testing
22+
```bash
23+
# Run all tests
24+
uv run pytest tests
25+
26+
# Run tests quietly
27+
uv run pytest -q tests
28+
29+
# Run specific test file
30+
uv run pytest tests/test_trading/test_orders.py
31+
32+
# Run with test script (includes API keys)
33+
./test.sh
34+
35+
# Run specific tests with test script
36+
./test.sh tests/test_trading/test_orders.py
37+
```
38+
39+
### Code Quality
40+
```bash
41+
# Run linter
42+
uv run ruff check
43+
44+
# Run linter with auto-fix
45+
uv run ruff check --fix
46+
47+
# Format code
48+
uv run ruff format
49+
```
50+
51+
## Architecture Overview
52+
53+
### Core API Structure
54+
The repository implements a Python wrapper for the Alpaca Trading API with the following architecture:
55+
56+
1. **Main Entry Point**: `PyAlpacaAPI` class in `src/py_alpaca_api/__init__.py`
57+
- Initializes with API key, secret, and paper trading flag
58+
- Provides access to `trading` and `stock` modules
59+
60+
2. **Trading Module** (`src/py_alpaca_api/trading/`)
61+
- `account.py`: Account information, activities, and portfolio history
62+
- `orders.py`: Order management and execution
63+
- `positions.py`: Position tracking and management
64+
- `watchlists.py`: Watchlist CRUD operations
65+
- `market.py`: Market clock and calendar data
66+
- `news.py`: Financial news from Yahoo Finance and Benzinga
67+
- `recommendations.py`: Stock recommendations and sentiment analysis
68+
69+
3. **Stock Module** (`src/py_alpaca_api/stock/`)
70+
- `assets.py`: Asset information retrieval
71+
- `history.py`: Historical stock data
72+
- `screener.py`: Stock screening for gainers/losers
73+
- `predictor.py`: Prophet-based stock prediction
74+
- `latest_quote.py`: Real-time quote data
75+
76+
4. **Models** (`src/py_alpaca_api/models/`)
77+
- Dataclass models for all API entities
78+
- `model_utils.py`: Utility functions for data transformation
79+
- Consistent pattern: each model has a `from_dict()` function
80+
81+
5. **HTTP Layer** (`src/py_alpaca_api/http/`)
82+
- `requests.py`: Centralized HTTP request handling with retry logic
83+
- Configurable retry strategies for resilient API communication
84+
85+
### Key Design Patterns
86+
87+
1. **Modular Architecture**: Each domain (trading, stock, models) is self-contained
88+
2. **Dataclass Models**: All API responses are converted to typed dataclasses
89+
3. **Centralized HTTP**: Single point for API communication with built-in resilience
90+
4. **Factory Pattern**: `from_dict()` methods for model instantiation
91+
92+
### API Authentication
93+
- Requires `ALPACA_API_KEY` and `ALPACA_SECRET_KEY` environment variables
94+
- Supports both paper and live trading environments
95+
- Test script includes default paper trading credentials
96+
97+
### External Dependencies
98+
- **Data Processing**: pandas, numpy
99+
- **Time Handling**: pendulum
100+
- **Stock Prediction**: prophet
101+
- **Web Scraping**: beautifulsoup4
102+
- **Market Data**: yfinance
103+
- **HTTP**: requests with caching and rate limiting
104+
105+
## Testing Approach
106+
107+
Tests are organized by module:
108+
- `test_http/`: HTTP request handling tests
109+
- `test_models/`: Model creation and transformation tests
110+
- `test_stock/`: Stock module functionality tests
111+
- `test_trading/`: Trading operations tests
112+
113+
All tests require API credentials (can use paper trading credentials).

GEMINI.md

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
# GEMINI.md
2+
3+
This file provides guidance to Gemini (gemini.google.com) when working with code in this repository.
4+
5+
## Development Commands
6+
7+
### Package Management
8+
This project uses `uv` for dependency management (migrated from Poetry).
9+
10+
```bash
11+
# Install dependencies
12+
uv sync --all-extras --dev
13+
14+
# Add a new dependency
15+
uv add <package-name>
16+
17+
# Add a dev dependency
18+
uv add --dev <package-name>
19+
```
20+
21+
### Testing
22+
```bash
23+
# Run all tests
24+
uv run pytest tests
25+
26+
# Run tests quietly
27+
uv run pytest -q tests
28+
29+
# Run specific test file
30+
uv run pytest tests/test_trading/test_orders.py
31+
32+
# Run with test script (includes API keys)
33+
./test.sh
34+
35+
# Run specific tests with test script
36+
./test.sh tests/test_trading/test_orders.py
37+
```
38+
39+
### Code Quality
40+
```bash
41+
# Run linter
42+
uv run ruff check
43+
44+
# Run linter with auto-fix
45+
uv run ruff check --fix
46+
47+
# Format code
48+
uv run ruff format
49+
```
50+
51+
## Architecture Overview
52+
53+
### Core API Structure
54+
The repository implements a Python wrapper for the Alpaca Trading API with the following architecture:
55+
56+
1. **Main Entry Point**: `PyAlpacaAPI` class in `src/py_alpaca_api/__init__.py`
57+
- Initializes with API key, secret, and paper trading flag
58+
- Provides access to `trading` and `stock` modules
59+
60+
2. **Trading Module** (`src/py_alpaca_api/trading/`)
61+
- `account.py`: Account information, activities, and portfolio history
62+
- `orders.py`: Order management and execution
63+
- `positions.py`: Position tracking and management
64+
- `watchlists.py`: Watchlist CRUD operations
65+
- `market.py`: Market clock and calendar data
66+
- `news.py`: Financial news from Yahoo Finance and Benzinga
67+
- `recommendations.py`: Stock recommendations and sentiment analysis
68+
69+
3. **Stock Module** (`src/py_alpaca_api/stock/`)
70+
- `assets.py`: Asset information retrieval
71+
- `history.py`: Historical stock data
72+
- `screener.py`: Stock screening for gainers/losers
73+
- `predictor.py`: Prophet-based stock prediction
74+
- `latest_quote.py`: Real-time quote data
75+
76+
4. **Models** (`src/py_alpaca_api/models/`)
77+
- Dataclass models for all API entities
78+
- `model_utils.py`: Utility functions for data transformation
79+
- Consistent pattern: each model has a `from_dict()` function
80+
81+
5. **HTTP Layer** (`src/py_alpaca_api/http/`)
82+
- `requests.py`: Centralized HTTP request handling with retry logic
83+
- Configurable retry strategies for resilient API communication
84+
85+
### Key Design Patterns
86+
87+
1. **Modular Architecture**: Each domain (trading, stock, models) is self-contained
88+
2. **Dataclass Models**: All API responses are converted to typed dataclasses
89+
3. **Centralized HTTP**: Single point for API communication with built-in resilience
90+
4. **Factory Pattern**: `from_dict()` methods for model instantiation
91+
92+
### API Authentication
93+
- Requires `ALPACA_API_KEY` and `ALPACA_SECRET_KEY` environment variables
94+
- Supports both paper and live trading environments
95+
- Test script includes default paper trading credentials
96+
97+
### External Dependencies
98+
- **Data Processing**: pandas, numpy
99+
- **Time Handling**: pendulum
100+
- **Stock Prediction**: prophet
101+
- **Web Scraping**: beautifulsoup4
102+
- **Market Data**: yfinance
103+
- **HTTP**: requests with caching and rate limiting
104+
105+
## Testing Approach
106+
107+
Tests are organized by module:
108+
- `test_http/`: HTTP request handling tests
109+
- `test_models/`: Model creation and transformation tests
110+
- `test_stock/`: Stock module functionality tests
111+
- `test_trading/`: Trading operations tests
112+
113+
All tests require API credentials (can use paper trading credentials).

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ name = "py-alpaca-api"
33
version = "0.1.0"
44
description = "Add your description here"
55
readme = "README.md"
6-
requires-python = ">=3.12"
6+
requires-python = ">=3.10"
77
dependencies = [
88
"beautifulsoup4>=4.12.3",
99
"numpy>=2.1.1",

pytest.ini

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,5 @@ filterwarnings =
99
ignore::FutureWarning
1010
ignore::SyntaxWarning
1111
ignore::Warning
12-
ignore::pytest.PytestUnknownMarkWarning
13-
ignore::pytest.PytestUnhandledCoroutineWarning
14-
ignore::pytest.PytestCollectionWarning
12+
ignore::_pytest.warning_types.PytestUnknownMarkWarning
13+
ignore::_pytest.warning_types.PytestCollectionWarning

src/py_alpaca_api/stock/screener.py

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -215,21 +215,22 @@ def _get_percentages(
215215
sceener_df = pd.DataFrame()
216216
for symbol in symbols_data.items():
217217
try:
218-
sym = symbol[0]
219-
last_day = symbol[1][-1]
220-
prev_day = symbol[1][-2]
221-
222-
sym_data = {
223-
"symbol": sym,
224-
"change": round(
225-
((last_day["c"] - prev_day["c"]) / prev_day["c"]) * 100, 2
226-
),
227-
"price": last_day["c"],
228-
"volume": last_day["v"],
229-
"trades": last_day["n"],
230-
}
231-
sceener_df = pd.concat([sceener_df, pd.DataFrame([sym_data])])
232-
except TypeError or KeyError:
218+
if len(symbol[1]) > 1:
219+
sym = symbol[0]
220+
last_day = symbol[1][-1]
221+
prev_day = symbol[1][-2]
222+
223+
sym_data = {
224+
"symbol": sym,
225+
"change": round(
226+
((last_day["c"] - prev_day["c"]) / prev_day["c"]) * 100, 2
227+
),
228+
"price": last_day["c"],
229+
"volume": last_day["v"],
230+
"trades": last_day["n"],
231+
}
232+
sceener_df = pd.concat([sceener_df, pd.DataFrame([sym_data])])
233+
except (TypeError, KeyError, IndexError):
233234
pass
234235

235236
sceener_df.reset_index(drop=True, inplace=True)

0 commit comments

Comments
 (0)