-
Notifications
You must be signed in to change notification settings - Fork 7.6k
feat(tools): add OptionsAhoyTool for equity-compensation tax calculations #6148
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
Open
AlvisoOculus
wants to merge
4
commits into
crewAIInc:main
Choose a base branch
from
AlvisoOculus:feat/optionsahoy-tool
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+456
−0
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
d46b5a9
feat(tools): add OptionsAhoyTool for equity-compensation tax calculat…
AlvisoOculus c4e00e2
optionsahoy tool: treat None-valued required fields as missing (coder…
AlvisoOculus 67e8014
optionsahoy tool: test None-valued required field is rejected
AlvisoOculus 48766e3
Merge branch 'main' into feat/optionsahoy-tool
AlvisoOculus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
75 changes: 75 additions & 0 deletions
75
lib/crewai-tools/src/crewai_tools/tools/optionsahoy_tool/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| # OptionsAhoyTool | ||
|
|
||
| ## Description | ||
|
|
||
| `OptionsAhoyTool` computes the tax outcome of common equity-compensation decisions | ||
| using the [OptionsAhoy](https://optionsahoy.com) public REST API. The API is keyless | ||
| and runs each calculation against the federal tax code and all fifty states plus the | ||
| District of Columbia. | ||
|
|
||
| A single tool exposes seven calculators through a `calculator` selector and an | ||
| `inputs` object: | ||
|
|
||
| | `calculator` | What it computes | | ||
| | ------------------ | ---------------- | | ||
| | `amt-iso` | Optimizes a multi-year incentive stock option (ISO) exercise schedule under the alternative minimum tax (AMT). | | ||
| | `nso` | Tax and after-tax proceeds of exercising non-qualified stock options (NSOs), holding versus selling. | | ||
| | `rsu-sell-vs-hold` | Selling vested restricted stock units (RSUs) at vest versus holding them, on an after-tax, risk-adjusted basis. | | ||
| | `concentration` | Analyzes a concentrated single-stock position and the after-tax cost of diversifying it. | | ||
| | `protective-put` | Prices a protective put hedge at a given downside protection level and tenor. | | ||
| | `qsbs` | Checks qualified small business stock (QSBS) eligibility and the resulting capital-gains exclusion. | | ||
| | `equity-funding` | Plans which equity lots to sell, and when, to fund a cash goal by a target date at the least after-tax cost. | | ||
|
|
||
| No API key is read, stored, or sent. Field names in `inputs` match the published | ||
| schema at `https://optionsahoy.com/openapi.json` exactly. | ||
|
|
||
| ## Installation | ||
|
|
||
| The tool ships with `crewai-tools` and uses `requests`, which is already a core | ||
| dependency. No extra install is required. | ||
|
|
||
| ```shell | ||
| pip install crewai[tools] | ||
| ``` | ||
|
|
||
| ## Example | ||
|
|
||
| ```python | ||
| from crewai_tools import OptionsAhoyTool | ||
|
|
||
| tool = OptionsAhoyTool() | ||
|
|
||
| result = tool.run( | ||
| calculator="qsbs", | ||
| inputs={ | ||
| "acquisitionDate": "2018-01-01", | ||
| "saleDate": "2026-02-01", | ||
| "entityType": "us-c-corp", | ||
| "acquisitionMethod": "original-issuance", | ||
| "assetCategory": "under-50m", | ||
| "industry": "tech-software", | ||
| "activeBusiness": "yes", | ||
| "adjustedBasis": 10000, | ||
| "expectedGain": 2000000, | ||
| "stateCode": "CA", | ||
| "ordinaryIncome": 250000, | ||
| "filingStatus": "single", | ||
| }, | ||
| ) | ||
| ``` | ||
|
|
||
| The tool returns the calculator's result as a JSON string. | ||
|
|
||
| ## Arguments | ||
|
|
||
| - `calculator` (required): one of `amt-iso`, `nso`, `rsu-sell-vs-hold`, | ||
| `concentration`, `protective-put`, `qsbs`, `equity-funding`. | ||
| - `inputs` (required): a JSON object of inputs for the chosen calculator. Money values | ||
| are plain numbers, dates are ISO strings (`YYYY-MM-DD`), and US state codes are two | ||
| letters. | ||
|
|
||
| The tool can be constructed with a custom `base_url` or `timeout` if needed: | ||
|
|
||
| ```python | ||
| tool = OptionsAhoyTool(timeout=60) | ||
| ``` |
Empty file.
223 changes: 223 additions & 0 deletions
223
lib/crewai-tools/src/crewai_tools/tools/optionsahoy_tool/optionsahoy_tool.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,223 @@ | ||
| import json | ||
| from typing import Any, Literal | ||
|
|
||
| from crewai.tools import BaseTool | ||
| from pydantic import BaseModel, Field | ||
| import requests | ||
|
|
||
|
|
||
| CalculatorName = Literal[ | ||
| "amt-iso", | ||
| "nso", | ||
| "rsu-sell-vs-hold", | ||
| "concentration", | ||
| "protective-put", | ||
| "qsbs", | ||
| "equity-funding", | ||
| ] | ||
|
|
||
| # Required input fields per calculator, mirroring the published OpenAPI schema at | ||
| # https://optionsahoy.com/openapi.json. These are used for a friendly pre-flight | ||
| # check; the API remains the source of truth for validation. | ||
| REQUIRED_FIELDS: dict[str, tuple[str, ...]] = { | ||
| "amt-iso": ( | ||
| "shares", | ||
| "strike", | ||
| "fmv", | ||
| "filingStatus", | ||
| "ordinaryIncome", | ||
| "stateCode", | ||
| "carryforwardCredit", | ||
| "horizon", | ||
| "cashReturnRate", | ||
| "grantDate", | ||
| "hasLeftCompany", | ||
| "terminationDate", | ||
| ), | ||
| "nso": ( | ||
| "shares", | ||
| "strike", | ||
| "currentPrice", | ||
| "ordinaryIncome", | ||
| "filingStatus", | ||
| "stateCode", | ||
| "stillEmployed", | ||
| "holdYears", | ||
| "holdFunding", | ||
| ), | ||
| "rsu-sell-vs-hold": ( | ||
| "shares", | ||
| "currentPrice", | ||
| "ordinaryIncome", | ||
| "filingStatus", | ||
| "stateCode", | ||
| "stillEmployed", | ||
| "holdYears", | ||
| ), | ||
| "concentration": ( | ||
| "positionValue", | ||
| "costBasis", | ||
| "acquisitionDate", | ||
| "sector", | ||
| "stateCode", | ||
| "filingStatus", | ||
| "ordinaryIncome", | ||
| "totalAssets", | ||
| ), | ||
| "protective-put": ( | ||
| "positionValue", | ||
| "sector", | ||
| "protectionLevel", | ||
| "tenorYears", | ||
| ), | ||
| "qsbs": ( | ||
| "acquisitionDate", | ||
| "saleDate", | ||
| "entityType", | ||
| "acquisitionMethod", | ||
| "assetCategory", | ||
| "industry", | ||
| "activeBusiness", | ||
| "adjustedBasis", | ||
| "expectedGain", | ||
| "stateCode", | ||
| "ordinaryIncome", | ||
| "filingStatus", | ||
| ), | ||
| "equity-funding": ( | ||
| "targetAfterTax", | ||
| "targetDate", | ||
| "ordinaryIncome", | ||
| "filingStatus", | ||
| "stateCode", | ||
| ), | ||
| } | ||
|
|
||
| # ``terminationDate`` is meaningful when null (it encodes "no termination") so it | ||
| # must be sent even when the caller leaves it unset. | ||
| _KEEP_NULL = {"terminationDate"} | ||
|
|
||
|
|
||
| class OptionsAhoyToolSchema(BaseModel): | ||
| """Input for OptionsAhoyTool.""" | ||
|
|
||
| calculator: CalculatorName = Field( | ||
| ..., | ||
| description=( | ||
| "Which equity-compensation calculator to run. One of: " | ||
| "'amt-iso' (optimize a multi-year incentive stock option (ISO) exercise " | ||
| "schedule under the alternative minimum tax (AMT)); " | ||
| "'nso' (tax and after-tax proceeds of exercising non-qualified stock " | ||
| "options (NSOs), holding versus selling); " | ||
| "'rsu-sell-vs-hold' (sell vested restricted stock units (RSUs) at vest " | ||
| "versus hold, on an after-tax, risk-adjusted basis); " | ||
| "'concentration' (analyze a concentrated single-stock position and the " | ||
| "after-tax cost of diversifying it); " | ||
| "'protective-put' (price a protective put hedge at a given downside " | ||
| "protection level and tenor); " | ||
| "'qsbs' (check qualified small business stock (QSBS) eligibility and the " | ||
| "resulting capital-gains exclusion); " | ||
| "'equity-funding' (plan which equity lots to sell, and when, to fund a " | ||
| "cash goal by a target date at the least after-tax cost)." | ||
| ), | ||
| ) | ||
| inputs: dict[str, Any] = Field( | ||
| ..., | ||
| description=( | ||
| "The calculator inputs as a JSON object. Field names match the OptionsAhoy " | ||
| "public schema exactly (for example: shares, strike, fmv, filingStatus, " | ||
| "ordinaryIncome, stateCode, grantDate). Money values are plain numbers, " | ||
| "dates are ISO strings (YYYY-MM-DD), and US state codes are two letters." | ||
| ), | ||
| ) | ||
|
|
||
|
|
||
| class OptionsAhoyTool(BaseTool): | ||
| """Run an OptionsAhoy equity-compensation tax calculator. | ||
|
|
||
| OptionsAhoy is a keyless public REST API that computes the tax outcome of common | ||
| equity-compensation decisions against the federal tax code and all fifty states | ||
| plus the District of Columbia. This tool wraps the seven calculators behind a | ||
| single ``calculator`` selector plus an ``inputs`` object. No API key is read, | ||
| stored, or sent. | ||
| """ | ||
|
|
||
| name: str = "OptionsAhoy Equity Compensation Tax Calculator" | ||
| description: str = ( | ||
| "Computes the tax outcome of equity-compensation decisions using the " | ||
| "OptionsAhoy public API. Choose a 'calculator' and pass its 'inputs': " | ||
| "incentive stock option (ISO) exercise under the alternative minimum tax " | ||
| "(AMT), non-qualified stock option (NSO) exercise, restricted stock unit " | ||
| "(RSU) sell-versus-hold, single-stock concentration, protective put pricing, " | ||
| "qualified small business stock (QSBS) eligibility, and funding a cash goal " | ||
| "from equity lots. Returns the calculator's JSON result. No API key required." | ||
| ) | ||
| args_schema: type[BaseModel] = OptionsAhoyToolSchema | ||
| base_url: str = "https://optionsahoy.com" | ||
| timeout: int = 30 | ||
|
|
||
| def _check_required(self, calculator: str, inputs: dict[str, Any]) -> None: | ||
| required = REQUIRED_FIELDS.get(calculator, ()) | ||
| missing = [ | ||
| field | ||
| for field in required | ||
| if field not in inputs | ||
| or (inputs[field] is None and field not in _KEEP_NULL) | ||
| ] | ||
| if missing: | ||
| raise ValueError( | ||
| f"OptionsAhoy '{calculator}' is missing required input field(s): " | ||
| f"{', '.join(missing)}" | ||
| ) | ||
|
|
||
| def _build_payload(self, inputs: dict[str, Any]) -> dict[str, Any]: | ||
| return { | ||
| key: value | ||
| for key, value in inputs.items() | ||
| if value is not None or key in _KEEP_NULL | ||
| } | ||
|
|
||
| def _run(self, calculator: str, inputs: dict[str, Any]) -> str: | ||
| """Call the selected OptionsAhoy calculator and return its JSON result. | ||
|
|
||
| Args: | ||
| calculator: The calculator endpoint to run. | ||
| inputs: The calculator inputs, matching the OptionsAhoy public schema. | ||
|
|
||
| Returns: | ||
| A JSON string with the calculator result, or a JSON error object when the | ||
| request fails. | ||
| """ | ||
| self._check_required(calculator, inputs) | ||
| url = f"{self.base_url.rstrip('/')}/api/v1/{calculator}" | ||
| payload = self._build_payload(inputs) | ||
|
|
||
| try: | ||
| response = requests.post(url, json=payload, timeout=self.timeout) | ||
| response.raise_for_status() | ||
| except requests.exceptions.HTTPError as exc: | ||
| detail: Any | ||
| try: | ||
| detail = exc.response.json() | ||
| except ValueError: | ||
| detail = exc.response.text | ||
| message = ( | ||
| f"OptionsAhoy '{calculator}' request failed " | ||
| f"({exc.response.status_code})" | ||
| ) | ||
| if isinstance(detail, dict) and detail.get("error"): | ||
| message = f"{message}: {detail['error']}" | ||
| return json.dumps({"error": message, "detail": detail}) | ||
| except requests.exceptions.RequestException as exc: | ||
| return json.dumps( | ||
| {"error": f"OptionsAhoy '{calculator}' request failed: {exc}"} | ||
| ) | ||
|
|
||
| try: | ||
| result = response.json() | ||
| except ValueError: | ||
| return json.dumps( | ||
| {"error": (f"OptionsAhoy '{calculator}' returned a non-JSON response")} | ||
| ) | ||
|
|
||
| return json.dumps(result, indent=2) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.