Skip to content
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

get option expirations #11

Merged
merged 2 commits into from
Jun 6, 2024
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
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,15 @@ schwab_client.get_tokens_manually()
# now you should have access token & refresh token downloaded to your device

#----------------
ticker = '$SPX'
# get option expirations:
expiration_list = await schwab_client.get_option_expirations_async(underlying_symbol = ticker)

# download SPX option chains
from_date = 2024-07-01
to_date = 2024-07-01
ticker = '$SPX'
asyncio.run(opt_chain_result = schwab_client.download_option_chain(ticker, from_date, to_date))

opt_chain_result = await schwab_client.download_option_chain_async(ticker, from_date, to_date)

# get call-put dataframe pairs by expiration
opt_df_pairs = opt_chain_result.to_dataframe_pairs_by_expiration()
Expand Down
27 changes: 25 additions & 2 deletions cschwabpy/SchwabAsyncClient.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
from cschwabpy.models.token import Tokens, ITokenStore, LocalTokenStore
from cschwabpy.models import OptionChainQueryFilter, OptionContractType, OptionChain
from cschwabpy.models import (
OptionChainQueryFilter,
OptionContractType,
OptionChain,
OptionExpiration,
OptionExpirationChainResponse,
)
from typing import Optional, List, Mapping
from cschwabpy.costants import (
SCHWAB_API_BASE_URL,
Expand Down Expand Up @@ -94,7 +100,24 @@ def __auth_header(self) -> Mapping[str, str]:
"Accept": "application/json",
}

async def download_option_chain(
async def get_option_expirations_async(
self, underlying_symbol: str
) -> List[OptionExpiration]:
await self._ensure_valid_access_token()
target_url = f"{SCHWAB_MARKET_DATA_API_BASE_URL}/expirationchain?symbol={underlying_symbol}"
client = httpx.AsyncClient() if self.__client is None else self.__client
try:
response = await client.get(
url=target_url, params={}, headers=self.__auth_header()
)
json_res = response.json()
expiration_resp = OptionExpirationChainResponse(**json_res)
return expiration_resp.expirationList
finally:
if not self.__keep_client_alive:
await client.aclose()

async def download_option_chain_async(
self,
underlying_symbol: str,
from_date: str,
Expand Down
11 changes: 11 additions & 0 deletions cschwabpy/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,17 @@ def to_query_params(self, ignore_fields: List[str] = []) -> str:
return "&".join([f"{k}={v}" for k, v in query_dict.items() if v is not None])


class OptionExpiration(JSONSerializableBaseModel):
expirationDate: str
daysToExpiration: Optional[int] = None
expirationType: Optional[str] = None
standard: Optional[bool] = None


class OptionExpirationChainResponse(JSONSerializableBaseModel):
expirationList: List[OptionExpiration] = []


class OptionContractType(str, Enum):
"""Option contract type."""

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "cschwabpy"
version = "0.0.4"
version = "0.0.5"
description = ""
authors = ["Tony Wang <[email protected]>"]
readme = "README.md"
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setup(
name="CSchwabPy",
version="0.1.0",
version="0.0.5",
description="Charles Schwab Stock & Option Trade API Client for Python.",
long_description=long_description,
long_description_content_type="text/markdown",
Expand Down
57 changes: 57 additions & 0 deletions tests/data/mock_schwab_api_resp.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,61 @@
{
"option_expirations_list": {
"expirationList": [
{
"expirationDate": "2022-01-07",
"daysToExpiration": 2,
"expirationType": "W",
"standard": true
},
{
"expirationDate": "2022-01-14",
"daysToExpiration": 9,
"expirationType": "W",
"standard": true
},
{
"expirationDate": "2022-01-21",
"daysToExpiration": 16,
"expirationType": "S",
"standard": true
},
{
"expirationDate": "2022-01-28",
"daysToExpiration": 23,
"expirationType": "W",
"standard": true
},
{
"expirationDate": "2022-02-04",
"daysToExpiration": 30,
"expirationType": "W",
"standard": true
},
{
"expirationDate": "2022-02-11",
"daysToExpiration": 37,
"expirationType": "W",
"standard": true
},
{
"expirationDate": "2022-02-18",
"daysToExpiration": 44,
"expirationType": "S",
"standard": true
},
{
"expirationDate": "2022-03-18",
"daysToExpiration": 72,
"expirationType": "S",
"standard": true
},
{
"expirationDate": "2022-04-14",
"daysToExpiration": 99,
"expirationType": "S",
"standard": true
}]
},
"option_chain_resp": {
"symbol":"$SPX",
"status":"SUCCESS",
Expand Down
35 changes: 34 additions & 1 deletion tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ async def test_download_option_chain(httpx_mock: HTTPXMock):
tokens=mocked_token,
http_client=client,
)
opt_chain_result = await cschwab_client.download_option_chain(
opt_chain_result = await cschwab_client.download_option_chain_async(
underlying_symbol=symbol, from_date="2025-01-03", to_date="2025-01-03"
)
assert opt_chain_result is not None
Expand All @@ -88,3 +88,36 @@ async def test_download_option_chain(httpx_mock: HTTPXMock):
print(f"put dataframe size: {df.put_df.shape}. expiration: {df.expiration}")
print(df.call_df.head(5))
print(df.put_df.head(5))


@pytest.mark.asyncio
async def test_get_option_expirations(httpx_mock: HTTPXMock):
mock_option_chain_resp = get_mock_response()
mocked_token = mock_tokens()
token_store = LocalTokenStore()
if os.path.exists(Path(token_store.token_output_path)):
os.remove(token_store.token_output_path) # clean up before test

mock_response = {
**mock_option_chain_resp["option_expirations_list"],
**(mocked_token.to_json()),
}
symbol = "$SPX"
httpx_mock.add_response(json=mock_response)
async with httpx.AsyncClient() as client:
cschwab_client = SchwabAsyncClient(
app_client_id="fake_id",
app_secret="fake_secret",
token_store=token_store,
tokens=mocked_token,
http_client=client,
)
opt_expirations_list = await cschwab_client.get_option_expirations_async(
underlying_symbol=symbol
)
assert opt_expirations_list is not None
assert len(opt_expirations_list) > 0
assert opt_expirations_list[0].expirationDate == "2022-01-07"
assert opt_expirations_list[0].daysToExpiration == 2
assert opt_expirations_list[0].expirationType == "W"
assert opt_expirations_list[0].standard