### Install stocksTUI Source: https://github.com/andriy-git/stockstui/blob/main/README.md Install the application using pipx. ```bash pipx install stocksTUI ``` -------------------------------- ### Install from Source Source: https://context7.com/andriy-git/stockstui/llms.txt Clone the repository and install dependencies for development purposes. ```bash # Clone the repository git clone https://github.com/andriy-git/stocksTUI.git cd stocksTUI # Run the install script (creates venv and installs globally) ./install.sh # Or manually with pip python -m pip install -e ".[dev]" ``` -------------------------------- ### Install stocksTUI from Source Source: https://github.com/andriy-git/stockstui/blob/main/README.md Clone the repository, navigate to the directory, and run the install script. This sets up a virtual environment and a global command. ```bash git clone https://github.com/andriy-git/stocksTUI.git cd stocksTUI ./install.sh ``` -------------------------------- ### Command-Line Examples Source: https://github.com/andriy-git/stockstui/blob/main/README.md Examples of using CLI flags to open specific views or filter data directly from the terminal. ```bash stockstui --history TSLA ``` ```bash stockstui --news "NVDA,AMD" ``` ```bash stockstui --options AAPL ``` ```bash stockstui --session-list "EV Stocks=TSLA,RIVN,LCID" ``` ```bash stockstui --history TSLA --period 5d --chart ``` ```bash stockstui --fred UNRATE ``` ```bash stockstui -o stocks --tags tech ``` -------------------------------- ### Install pipx Source: https://github.com/andriy-git/stockstui/blob/main/README.md Commands to install the pipx package manager on various operating systems. ```bash # Debian/Ubuntu sudo apt install pipx # Arch Linux sudo pacman -S python-pipx # macOS brew install pipx # Or fallback to pip python3 -m pip install --user pipx python3 -m pipx ensurepath ``` -------------------------------- ### Manage Option Positions Source: https://context7.com/andriy-git/stockstui/llms.txt Provides examples for saving, retrieving, and deleting option positions from the database. ```python db.save_option_position( symbol="AAPL240119C00180000", ticker="AAPL", quantity=5, avg_cost=3.50 ) position = db.get_option_position("AAPL240119C00180000") all_positions = db.get_all_option_positions() db.delete_option_position("AAPL240119C00180000") ``` -------------------------------- ### Populate and Get Cache State Source: https://context7.com/andriy-git/stockstui/llms.txt Populates the market provider's price cache from an external source and retrieves the current cache state for persistence. ```python initial_cache = { "AAPL": { "expiry": datetime.now(timezone.utc) + timedelta(hours=1), "data": {"symbol": "AAPL", "price": 178.50, "description": "Apple Inc."} } } market_provider.populate_price_cache(initial_cache) # Get current cache state for persistence cache_state = market_provider.get_price_cache_state() ``` -------------------------------- ### Get Comprehensive FRED Series Summary Source: https://context7.com/andriy-git/stockstui/llms.txt Retrieves a summary of economic series including computed metrics like YoY change and Z-scores. ```python from stockstui.data_providers import fred_provider api_key = "your_fred_api_key" # Get comprehensive summary with computed metrics series_ids = ["UNRATE", "CPIAUCSL", "GDP", "FEDFUNDS"] for series_id in series_ids: summary = fred_provider.get_series_summary(series_id, api_key) print(f"\n{summary['title']} ({series_id})") print(f" Current: {summary['current']:.2f} ({summary['date']})") print(f" Units: {summary['units_short']}") if summary['yoy_pct'] is not None: print(f" YoY Change: {summary['yoy_pct']:+.1f}%") if summary['z_10y'] is not None: z = summary['z_10y'] trend = "HIGH" if z > 2 else "LOW" if z < -2 else "NORMAL" print(f" Z-Score (10Y): {z:+.2f} ({trend})") if summary['pct_of_range'] is not None: print(f" Percentile in 10Y Range: {summary['pct_of_range']:.0f}%") ``` -------------------------------- ### Get Market Status Source: https://context7.com/andriy-git/stockstui/llms.txt Retrieves the current market status for a specified exchange. The status includes whether the market is open, pre-market, or post-market, along with relevant times. ```python from stockstui.data_providers import market_provider # Get current market status for an exchange status = market_provider.get_market_status("NYSE") # Returns: # { # 'status': 'open' | 'closed' | 'pre' | 'post' | 'unknown', # 'is_open': True | False, # 'calendar': 'NYSE', # 'next_open': datetime(...), # 'next_close': datetime(...), # 'reason': None | 'weekend' | 'holiday', # 'holiday': 'Independence Day' | None, # 'premarket_open': datetime(...), # 'premarket_close': datetime(...), # 'postmarket_open': datetime(...), # 'postmarket_close': datetime(...) # } if status['is_open']: print(f"Market is OPEN until {status['next_close']}") elif status['status'] == 'pre': print("Pre-market trading active") elif status['status'] == 'post': print("After-hours trading active") else: print(f"Market CLOSED - Opens {status['next_open']}") ``` -------------------------------- ### Basic CLI Usage Source: https://context7.com/andriy-git/stockstui/llms.txt Common commands for launching the application and accessing help documentation. ```bash # Launch the TUI stockstui # Show help stockstui -h # Show full manual stockstui --man # Show version stockstui --version ``` -------------------------------- ### Run stocksTUI Source: https://github.com/andriy-git/stockstui/blob/main/README.md Basic commands to launch the application or view help documentation. ```bash stockstui ``` ```bash stockstui -h # Short help stockstui --man # Full user manual ``` -------------------------------- ### Manage Application Configuration Source: https://context7.com/andriy-git/stockstui/llms.txt Demonstrates loading, modifying, and saving application settings and watchlists. ```python from pathlib import Path from stockstui.config_manager import ConfigManager # Initialize with app root path app_root = Path(__file__).resolve().parent config = ConfigManager(app_root) # Access settings theme = config.get_setting("theme", "gruvbox_soft_dark") auto_refresh = config.get_setting("auto_refresh", False) refresh_interval = config.get_setting("refresh_interval", 300.0) market_calendar = config.get_setting("market_calendar", "NYSE") # Modify settings config.settings["theme"] = "tokyo_night" config.settings["auto_refresh"] = True config.settings["refresh_interval"] = 60.0 config.save_settings() # Access watchlists for list_name, tickers in config.lists.items(): print(f"{list_name}:") for item in tickers: print(f" {item['ticker']}: {item.get('alias', '')} [{item.get('tags', '')}]") # Modify watchlists config.lists["tech"] = [ {"ticker": "AAPL", "alias": "Apple", "note": "", "tags": "mega-cap, dividend"}, {"ticker": "MSFT", "alias": "Microsoft", "note": "", "tags": "mega-cap, cloud"}, {"ticker": "GOOG", "alias": "Google", "note": "", "tags": "mega-cap, ai"}, ] config.save_lists() # Access themes for theme_name, theme_data in config.themes.items(): dark_mode = theme_data.get("dark", False) print(f"{theme_name}: {'Dark' if dark_mode else 'Light'} theme") ``` -------------------------------- ### Launch stocksTUI with Custom Options Source: https://context7.com/andriy-git/stockstui/llms.txt Demonstrates launching the stocksTUI application programmatically with custom configuration overrides or running it in CLI output mode. Requires importing `StocksTUI` and `run_cli_output` from `stockstui.main`, and `create_arg_parser` from `stockstui.parser`. ```python from stockstui.main import StocksTUI, run_cli_output from stockstui.parser import create_arg_parser # Launch TUI with custom overrides cli_overrides = { 'tab': 'stocks', 'session_list': {'custom': ['AAPL', 'MSFT', 'GOOG']}, 'period': '1mo' } app = StocksTUI(cli_overrides=cli_overrides) app.run() # Or use CLI output mode parser = create_arg_parser() args = parser.parse_args(['-o', 'stocks', '--tags', 'tech']) run_cli_output(args) ``` -------------------------------- ### Configure View Selection Source: https://context7.com/andriy-git/stockstui/llms.txt Launch the application directly into specific tabs or views. ```bash # Start on a specific watchlist tab stockstui --tab stocks stockstui --tab crypto # Start on the History tab with optional ticker stockstui --history stockstui --history TSLA # Start on the News tab with comma-separated tickers stockstui --news stockstui --news "NVDA,AMD,INTC" # Start on the Options tab stockstui --options stockstui --options AAPL # Start on the FRED economic data tab stockstui --fred # Start on the Debug tab stockstui --debug # Start on the Configs tab stockstui --configs ``` -------------------------------- ### Create Temporary Session Watchlists Source: https://context7.com/andriy-git/stockstui/llms.txt Define custom watchlists for the current session using the --session-list flag. ```bash # Create a single session list stockstui --session-list "EV Stocks=TSLA,RIVN,LCID,NIO" # Create multiple session lists stockstui --session-list "Tech=AAPL,MSFT,GOOG" "Banks=JPM,BAC,GS" # Combine with other options stockstui --session-list "Watchlist=SPY,QQQ,IWM" --tab "watchlist" ``` -------------------------------- ### Configuration Manager Source: https://context7.com/andriy-git/stockstui/llms.txt This section explains how to use the ConfigManager to load, access, modify, and save application settings, watchlists, and themes. ```APIDOC ## Configuration Manager ### Loading and Saving Configuration This module provides functionality to manage application configuration, including user settings, watchlists, and theme preferences. ### Method Initialization: Constructor Access/Modify Settings: Direct attribute access or `get_setting` method Save: `save_settings()`, `save_lists()` ### Endpoint N/A (Local file-based configuration) ### Parameters #### Initialization - **app_root** (Path) - Required - The root path of the application. #### Accessing Settings - **setting_name** (string) - The name of the setting to retrieve. - **default_value** - Optional - The value to return if the setting is not found. ### Request Example ```python from pathlib import Path from stockstui.config_manager import ConfigManager app_root = Path(__file__).resolve().parent config = ConfigManager(app_root) # Access settings theme = config.get_setting("theme", "gruvbox_soft_dark") auto_refresh = config.get_setting("auto_refresh", False) # Modify settings config.settings["theme"] = "tokyo_night" config.save_settings() # Access watchlists for list_name, tickers in config.lists.items(): print(f"{list_name}:") for item in tickers: print(f" {item['ticker']}") # Modify watchlists config.lists["tech"] = [ {"ticker": "AAPL", "alias": "Apple"} ] config.save_lists() ``` ### Response #### Success Response (N/A) Configuration is loaded into memory and saved to disk. #### Response Example (Accessing Settings) `theme` might return "gruvbox_soft_dark" or "tokyo_night". `auto_refresh` might return `False` or `True`. #### Response Example (Accessing Watchlists) { "tech": [ {"ticker": "AAPL", "alias": "Apple", "note": "", "tags": "mega-cap, dividend"}, {"ticker": "MSFT", "alias": "Microsoft", "note": "", "tags": "mega-cap, cloud"} ] } #### Response Example (Accessing Themes) { "gruvbox_soft_dark": {"dark": true, "colors": {...}}, "tokyo_night": {"dark": true, "colors": {...}} } ``` -------------------------------- ### Save and Load Ticker Info Cache Source: https://context7.com/andriy-git/stockstui/llms.txt Demonstrates saving and loading ticker information cache to and from the database. ```python info_cache = { "AAPL": {"exchange": "NMS", "shortName": "Apple Inc.", "longName": "Apple Inc."}, "MSFT": {"exchange": "NMS", "shortName": "Microsoft", "longName": "Microsoft Corporation"} } db.save_info_cache_to_db(info_cache) loaded_info = db.load_info_cache_from_db() ``` -------------------------------- ### Fetch Options Expirations and Chains Source: https://context7.com/andriy-git/stockstui/llms.txt Retrieves available option expiration dates for a given ticker and then fetches the options chain (calls and puts) for a specific expiration date. Includes underlying price and details for the first 5 call strikes. Also shows how to clear the options cache. ```python from stockstui.data_providers import options_provider # Get available expiration dates for a ticker ticker = "AAPL" expirations = options_provider.get_available_expirations(ticker) print(f"Available expirations for {ticker}:") for exp in expirations[:5]: print(f" {exp}") # Fetch the options chain for a specific expiration expiration_date = expirations[0] # e.g., "2024-01-19" chain = options_provider.get_options_chain(ticker, expiration_date) if chain: calls_df = chain['calls'] puts_df = chain['puts'] underlying = chain['underlying'] print(f"\nUnderlying price: ${underlying['regularMarketPrice']:.2f}") print(f"\nCalls (first 5 strikes):") print(calls_df[['strike', 'lastPrice', 'bid', 'ask', 'volume', 'openInterest', 'delta', 'gamma', 'theta', 'vega']].head()) # Clear cache for specific ticker or all options_provider.clear_options_cache("AAPL") # Clear AAPL only options_provider.clear_options_cache() # Clear all ``` -------------------------------- ### Close Database Connection Source: https://context7.com/andriy-git/stockstui/llms.txt Shows how to properly close the database connection. ```python db.close() ``` -------------------------------- ### Parse and Format Tags Source: https://context7.com/andriy-git/stockstui/llms.txt Demonstrates parsing tags from various string formats and formatting them back into a comma-separated string. Requires importing `parse_tags`, `match_tags`, and `format_tags` from `stockstui.utils`. ```python from stockstui.utils import parse_tags, match_tags, format_tags # Parse tags from various input formats tags1 = parse_tags("tech, growth, dividend") tags2 = parse_tags("tech growth dividend") tags3 = parse_tags("tech;growth;dividend") # All return: ['tech', 'growth', 'dividend'] # Format tags back to string formatted = format_tags(['tech', 'growth']) # Returns: "tech, growth" # Filter items by tags item_tags = ['tech', 'growth', 'large-cap'] filter_tags = ['tech', 'value'] if match_tags(item_tags, filter_tags): print("Item matches filter") # True - 'tech' matches ``` -------------------------------- ### Manage Persistent Cache with DbManager Source: https://context7.com/andriy-git/stockstui/llms.txt Initializes the database manager and performs save/load operations for price cache data. ```python from pathlib import Path from stockstui.database.db_manager import DbManager # Initialize database db_path = Path("~/.cache/stockstui/app_cache.db").expanduser() db = DbManager(db_path) # Save price cache to database price_cache = { "AAPL": { "expiry": datetime.now(timezone.utc) + timedelta(hours=1), "data": {"symbol": "AAPL", "price": 178.50, "description": "Apple Inc."} }, "MSFT": { "expiry": datetime.now(timezone.utc) + timedelta(hours=1), "data": {"symbol": "MSFT", "price": 378.25, "description": "Microsoft Corporation"} } } db.save_price_cache_to_db(price_cache) # Load price cache on startup loaded_cache = db.load_price_cache_from_db() print(f"Loaded {len(loaded_cache)} items from cache") ``` -------------------------------- ### History View Options Source: https://context7.com/andriy-git/stockstui/llms.txt Customize historical data display with specific periods and chart rendering. ```bash # View 5-day history for Tesla stockstui --history TSLA --period 5d # View 1-year history with chart enabled stockstui --history AAPL --period 1y --chart # Available periods: 1d, 5d, 1mo, 6mo, ytd, 1y, 5y, max stockstui --history MSFT --period max --chart ``` -------------------------------- ### Fetch Market Price Data Source: https://context7.com/andriy-git/stockstui/llms.txt Retrieve financial data programmatically using the market_provider module. ```python from stockstui.data_providers import market_provider # Fetch price data for multiple tickers tickers = ["AAPL", "MSFT", "GOOG", "TSLA"] data = market_provider.get_market_price_data(tickers, force_refresh=False) # Each item in data contains: # { # 'symbol': 'AAPL', # 'description': 'Apple Inc.', # 'price': 178.50, # 'previous_close': 176.25, # 'day_low': 177.10, # 'day_high': 179.80, # 'volume': 52345678, # 'open': 177.50, # 'fifty_two_week_low': 124.17, # 'fifty_two_week_high': 199.62, # 'pe_ratio': 28.5, # 'market_cap': 2800000000000, # 'dividend_yield': 0.005, # 'eps': 6.27, # 'beta': 1.28, # 'all_time_high': 199.62 # } for item in data: symbol = item['symbol'] price = item['price'] change = price - item['previous_close'] if price and item['previous_close'] else None print(f"{symbol}: ${price:.2f} ({change:+.2f})" if change else f"{symbol}: ${price:.2f}") ``` -------------------------------- ### Format Price Data for Table Display Source: https://context7.com/andriy-git/stockstui/llms.txt Formats raw market data into a structure suitable for table display, including price, change, and day range. It also handles user-defined aliases and detects price changes for flash highlighting. Requires importing `format_price_data_for_table` from `stockstui.presentation.formatter`. ```python from stockstui.presentation.formatter import format_price_data_for_table # Raw data from market provider data = [ { 'symbol': 'AAPL', 'description': 'Apple Inc.', 'price': 178.50, 'previous_close': 176.25, 'day_low': 177.10, 'day_high': 179.80, 'volume': 52345678, 'open': 177.50, 'fifty_two_week_low': 124.17, 'fifty_two_week_high': 199.62, 'all_time_high': 199.62 } ] # Previous prices for flash detection old_prices = {'AAPL': 176.25} # User-defined aliases alias_map = {'AAPL': 'Apple'} # Format for table display rows = format_price_data_for_table(data, old_prices, alias_map) for row in rows: print(f"Ticker: {row['Ticker']}") print(f"Description: {row['Description']}") print(f"Price: ${row['Price']:.2f}") print(f"Change: {row['Change']:+.2f}") print(f"% Change: {row['% Change']:.2%}") print(f"Day Range: {row['Day\'s Range']}") print(f"Flash: {row['_change_direction']}") # 'up', 'down', or None ``` -------------------------------- ### Extract Text from Rich Objects and Slugify Source: https://context7.com/andriy-git/stockstui/llms.txt Illustrates extracting plain text from Rich Text objects and converting strings into snake_case identifiers. Requires importing `extract_cell_text` and `slugify` from `stockstui.utils`. ```python from stockstui.utils import extract_cell_text, slugify from rich.text import Text # Extract plain text from Rich Text objects rich_text = Text("$178.50", style="bold green") plain = extract_cell_text(rich_text) # Returns: "$178.50" # Convert names to snake_case identifiers category_name = "My Stock List" slug = slugify(category_name) # Returns: "my_stock_list" ``` -------------------------------- ### Fetch Stock News Source: https://context7.com/andriy-git/stockstui/llms.txt Fetches news articles for a single ticker or a list of tickers. For multiple tickers, news is deduplicated and sorted by date. Displays the first 5 articles with source, title, publisher, publish time, and link. ```python from stockstui.data_providers import market_provider # Fetch news for a single ticker news = market_provider.get_news_data("AAPL") # Fetch combined news for multiple tickers (deduped, sorted by date) tickers = ["NVDA", "AMD", "INTC"] combined_news = market_provider.get_news_for_tickers(tickers) if combined_news: for article in combined_news[:5]: print(f"[{article['source_ticker']}] {article['title']}") print(f" Publisher: {article['publisher']}") print(f" Time: {article['publish_time']}") print(f" Link: {article['link']}") print() # News item structure: # { # 'source_ticker': 'AAPL', # 'title': 'Apple Announces New Product...', # 'summary': 'Apple Inc. today announced...', # 'publisher': 'Reuters', # 'link': 'https://...', # 'publish_time': '2024-01-15 14:30 EST', # 'publish_datetime_utc': datetime(...) # } ``` -------------------------------- ### Non-Interactive CLI Output Source: https://context7.com/andriy-git/stockstui/llms.txt Print market data directly to the terminal without launching the TUI interface. ```bash # Output all watchlist data to terminal (no TUI) stockstui -o # Output specific watchlists stockstui -o stocks stockstui -o "stocks,crypto" # Filter by tags stockstui -o stocks --tags tech stockstui -o stocks --tags "growth,dividend" ``` -------------------------------- ### Fetch FRED Series Data Source: https://context7.com/andriy-git/stockstui/llms.txt Retrieves metadata and raw observations for a specific FRED economic series. ```python from stockstui.data_providers import fred_provider api_key = "your_fred_api_key" # Get from https://fred.stlouisfed.org # Fetch series metadata series_id = "UNRATE" # Unemployment Rate info = fred_provider.get_series_info(series_id, api_key) print(f"Series: {info['title']}") print(f"Units: {info['units']}") print(f"Frequency: {info['frequency']}") print(f"Seasonal Adjustment: {info['seasonal_adjustment']}") # Fetch raw observations (newest first) observations = fred_provider.get_series_observations(series_id, api_key, limit=24) print(f"\nRecent {series_id} values:") for obs in observations[:5]: print(f" {obs['date']}: {obs['value']}") ``` -------------------------------- ### FRED Economic Data Provider API Source: https://context7.com/andriy-git/stockstui/llms.txt This section details how to interact with the FRED (Federal Reserve Economic Data) API using the stockstui library to fetch economic series data, summaries, and search for series. ```APIDOC ## FRED Economic Data Provider API ### Fetching FRED Series Data This endpoint allows you to fetch metadata and raw observations for a given FRED series. ### Method GET ### Endpoint /fred/series_info /fred/series_observations ### Parameters #### Query Parameters - **series_id** (string) - Required - The ID of the FRED series (e.g., "UNRATE"). - **api_key** (string) - Required - Your FRED API key. - **limit** (integer) - Optional - The maximum number of observations to retrieve. ### Request Example ```python from stockstui.data_providers import fred_provider api_key = "your_fred_api_key" series_id = "UNRATE" # Fetch series metadata info = fred_provider.get_series_info(series_id, api_key) print(f"Series: {info['title']}") # Fetch raw observations observations = fred_provider.get_series_observations(series_id, api_key, limit=24) print(f"\nRecent {series_id} values:") for obs in observations[:5]: print(f" {obs['date']}: {obs['value']}") ``` ### Response #### Success Response (200) - **info**: Dictionary containing series metadata (title, units, frequency, etc.). - **observations**: List of dictionaries, each containing 'date' and 'value' for the series. #### Response Example (info) { "title": "Unemployment Rate", "units": "Percent", "frequency": "Monthly", "seasonal_adjustment": "Seasonally Adjusted" } #### Response Example (observations) [ {"date": "2023-10-01", "value": "3.8"}, {"date": "2023-09-01", "value": "3.8"} ] ### Getting Comprehensive Series Summary with Metrics This endpoint retrieves a detailed summary of a FRED series, including computed metrics like year-over-year change and z-scores. ### Method GET ### Endpoint /fred/series_summary ### Parameters #### Query Parameters - **series_id** (string) - Required - The ID of the FRED series. - **api_key** (string) - Required - Your FRED API key. ### Request Example ```python from stockstui.data_providers import fred_provider api_key = "your_fred_api_key" series_ids = ["UNRATE", "CPIAUCSL", "GDP", "FEDFUNDS"] for series_id in series_ids: summary = fred_provider.get_series_summary(series_id, api_key) print(f"\n{summary['title']} ({series_id})") print(f" Current: {summary['current']:.2f} ({summary['date']})") if summary['yoy_pct'] is not None: print(f" YoY Change: {summary['yoy_pct']:+.1f}%") ``` ### Response #### Success Response (200) - **summary**: Dictionary containing comprehensive series data including title, current value, date, units, and various computed metrics (yoy_pct, z_10y, pct_of_range, etc.). #### Response Example { "id": "UNRATE", "title": "Unemployment Rate", "date": "2023-11-01", "value": 3.7, "value_formatted": "3.7", "units": "Percent", "units_short": "%", "frequency": "Monthly", "frequency_short": "m", "relative_start_date": "1948-01-01", "sort_order": 1, "observation_start": "1948-01-01", "observation_end": "2023-11-01", "popularity": 85, "link": "https://fred.stlouisfed.org/series/UNRATE", "current": 3.7, "yoy_pct": -0.5, "z_10y": -1.5, "pct_of_range": 25.0 } ### Searching FRED Series This endpoint allows you to search for FRED series based on keywords. ### Method GET ### Endpoint /fred/search_series ### Parameters #### Query Parameters - **query** (string) - Required - The keyword(s) to search for. - **api_key** (string) - Required - Your FRED API key. ### Request Example ```python from stockstui.data_providers import fred_provider api_key = "your_fred_api_key" results = fred_provider.search_series("unemployment rate", api_key) print("Search results for 'unemployment rate':") for series in results[:5]: print(f" {series['id']}: {series['title']}") ``` ### Response #### Success Response (200) - **results**: A list of dictionaries, where each dictionary represents a found series and contains its id, title, frequency, and last updated date. #### Response Example [ { "id": "UNRATE", "title": "Unemployment Rate", "frequency": "Monthly", "last_updated": "2023-12-08T08:00:01-06:00" } ] ``` -------------------------------- ### Options Provider API Source: https://context7.com/andriy-git/stockstui/llms.txt APIs for fetching options data, including expirations and chains, and managing cache. ```APIDOC ## Fetching Option Expirations and Chains ### Description Retrieves available option expiration dates for a ticker and fetches the options chain for a specific expiration. ### Method `GET` (implied by function calls) ### Endpoint Not directly exposed as an HTTP endpoint, accessed via `options_provider.get_available_expirations` and `options_provider.get_options_chain`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from stockstui.data_providers import options_provider ticker = "AAPL" expirations = options_provider.get_available_expirations(ticker) expiration_date = expirations[0] # e.g., "2024-01-19" chain = options_provider.get_options_chain(ticker, expiration_date) ``` ### Response #### Success Response (200) `get_available_expirations` returns a list of strings representing expiration dates. `get_options_chain` returns a dictionary containing 'calls', 'puts' (both pandas DataFrames), and 'underlying' (a dictionary). #### Response Example ```json { "calls": [ { "strike": 150.0, "lastPrice": 5.0, "bid": 4.9, "ask": 5.1, "volume": 1000, "openInterest": 5000, "delta": 0.6, "gamma": 0.1, "theta": -0.05, "vega": 0.02 } // ... more call options ], "puts": [ { "strike": 150.0, "lastPrice": 2.0, "bid": 1.9, "ask": 2.1, "volume": 800, "openInterest": 4000, "delta": -0.4, "gamma": 0.08, "theta": -0.03, "vega": 0.015 } // ... more put options ], "underlying": { "symbol": "AAPL", "regularMarketPrice": 152.50 // ... more underlying details } } ``` ## Clearing Options Cache ### Description Clears the cache for options data, either for a specific ticker or for all tickers. ### Method `DELETE` (implied by function call) ### Endpoint Not directly exposed as an HTTP endpoint, accessed via `options_provider.clear_options_cache`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from stockstui.data_providers import options_provider # Clear cache for a specific ticker options_provider.clear_options_cache("AAPL") # Clear cache for all tickers options_provider.clear_options_cache() ``` ### Response #### Success Response (200) No explicit response body is detailed, operation is confirmed by successful execution. #### Response Example None ``` -------------------------------- ### Calculate Black-Scholes Option Greeks Source: https://context7.com/andriy-git/stockstui/llms.txt Calculates the Greeks (Delta, Gamma, Theta, Vega, Rho) for a given option using the Black-Scholes model. Requires parameters like underlying price, strike price, time to expiration, risk-free rate, implied volatility, and dividend yield. ```python from stockstui.utils.black_scholes import calculate_greeks # Calculate option Greeks greeks = calculate_greeks( flag='c', # 'c' for Call, 'p' for Put S=150.0, # Underlying price K=155.0, # Strike price T=0.25, # Time to expiration in years (e.g., 3 months = 0.25) r=0.045, # Risk-free rate (4.5%) sigma=0.30, # Implied volatility (30%) q=0.01 # Dividend yield (1%) ) print(f"Call Option Greeks:") print(f" Delta: {greeks['delta']:.4f}") # Price sensitivity print(f" Gamma: {greeks['gamma']:.6f}") # Delta sensitivity print(f" Theta: {greeks['theta']:.4f}") # Time decay (daily) print(f" Vega: {greeks['vega']:.4f}") # Volatility sensitivity (1% change) print(f" Rho: {greeks['rho']:.4f}") # Interest rate sensitivity ``` -------------------------------- ### Format Market Status Source: https://context7.com/andriy-git/stockstui/llms.txt Formats market status information, including open/closed status, calendar, and next closing time, into a displayable string with styled parts. Requires importing `format_market_status` from `stockstui.presentation.formatter`. ```python from stockstui.presentation.formatter import format_market_status from datetime import datetime, timezone status = { 'status': 'open', 'is_open': True, 'calendar': 'NYSE', 'next_close': datetime(2024, 1, 15, 16, 0, tzinfo=timezone.utc), 'reason': None } result = format_market_status(status) if result: text, parts = result print(f"Base: {text}") # "NYSE: " for content, style in parts: print(f" [{style}] {content}") # Output: # Base: NYSE: # [status-open] Open # [text-muted] (Closes 16:00) ``` -------------------------------- ### Black-Scholes Greeks Calculator Source: https://context7.com/andriy-git/stockstui/llms.txt Utility function to calculate option Greeks using the Black-Scholes model. ```APIDOC ## Black-Scholes Greeks Calculator ### Description Calculates the Greeks (Delta, Gamma, Theta, Vega, Rho) for a given option using the Black-Scholes model. ### Method `POST` (implied by function call) ### Endpoint Not directly exposed as an HTTP endpoint, accessed via `calculate_greeks`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from stockstui.utils.black_scholes import calculate_greeks greeks = calculate_greeks( flag='c', # 'c' for Call, 'p' for Put S=150.0, # Underlying price K=155.0, # Strike price T=0.25, # Time to expiration in years (e.g., 3 months = 0.25) r=0.045, # Risk-free rate (4.5%) sigma=0.30, # Implied volatility (30%) q=0.01 # Dividend yield (1%) ) ``` ### Response #### Success Response (200) A dictionary containing the calculated Greeks. #### Response Example ```json { "delta": 0.4567, "gamma": 0.089123, "theta": -0.0234, "vega": 0.0156, "rho": 0.0089 } ``` ``` -------------------------------- ### Market Data Provider API Source: https://context7.com/andriy-git/stockstui/llms.txt APIs for fetching market data, including historical prices, market status, and news. ```APIDOC ## Fetching Historical Data ### Description Fetches historical Open, High, Low, Close, and Volume (OHLCV) data for a given ticker. ### Method `GET` (implied by function call) ### Endpoint Not directly exposed as an HTTP endpoint, accessed via `market_provider.get_historical_data`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from stockstui.data_providers import market_provider ticker = "TSLA" period = "1mo" # e.g., "1d", "5d", "1mo", "6mo", "ytd", "1y", "5y", "max" interval = "1d" # e.g., "1m", "5m", "15m", "1h", "1d", "1wk", "1mo" df = market_provider.get_historical_data(ticker, period, interval) ``` ### Response #### Success Response (200) A pandas DataFrame containing historical OHLCV data. The DataFrame index is the datetime. #### Response Example ``` Open High Low Close Volume Date 2024-01-02 248.42 251.25 244.41 248.42 112117500 2024-01-03 246.42 249.13 244.03 248.48 79444300 ``` ## Getting Market Status ### Description Retrieves the current market status for a specified exchange. ### Method `GET` (implied by function call) ### Endpoint Not directly exposed as an HTTP endpoint, accessed via `market_provider.get_market_status`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from stockstui.data_providers import market_provider status = market_provider.get_market_status("NYSE") ``` ### Response #### Success Response (200) A dictionary containing market status details. #### Response Example ```json { "status": "open" | "closed" | "pre" | "post" | "unknown", "is_open": True | False, "calendar": "NYSE", "next_open": "datetime(...)", "next_close": "datetime(...)", "reason": null | "weekend" | "holiday", "holiday": "Independence Day" | null, "premarket_open": "datetime(...)", "premarket_close": "datetime(...)", "postmarket_open": "datetime(...)", "postmarket_close": "datetime(...)" } ``` ## Fetching News Data ### Description Fetches news articles for a single ticker or a combined list of tickers. ### Method `GET` (implied by function calls) ### Endpoint Not directly exposed as an HTTP endpoint, accessed via `market_provider.get_news_data` and `market_provider.get_news_for_tickers`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from stockstui.data_providers import market_provider # Fetch news for a single ticker news = market_provider.get_news_data("AAPL") # Fetch combined news for multiple tickers tickers = ["NVDA", "AMD", "INTC"] combined_news = market_provider.get_news_for_tickers(tickers) ``` ### Response #### Success Response (200) A list of news items, where each item is a dictionary. #### Response Example ```json { "source_ticker": "AAPL", "title": "Apple Announces New Product...", "summary": "Apple Inc. today announced...", "publisher": "Reuters", "link": "https://...", "publish_time": "2024-01-15 14:30 EST", "publish_datetime_utc": "datetime(...)" } ``` ``` -------------------------------- ### Database Manager for Persistent Caching Source: https://context7.com/andriy-git/stockstui/llms.txt This section describes the DbManager for managing a persistent cache using a SQLite database, including saving and loading price data. ```APIDOC ## Database Manager for Persistent Caching ### Managing Cache with DbManager This module provides a `DbManager` class to handle persistent caching of data, specifically designed for price data, using a SQLite database. ### Method Initialization: Constructor Save Cache: `save_price_cache_to_db()` Load Cache: `load_price_cache_from_db()` ### Endpoint N/A (Local file-based database) ### Parameters #### Initialization - **db_path** (Path) - Required - The path to the SQLite database file. ### Request Example ```python from pathlib import Path from datetime import datetime, timedelta, timezone from stockstui.database.db_manager import DbManager db_path = Path("~/.cache/stockstui/app_cache.db").expanduser() db = DbManager(db_path) # Save price cache to database price_cache = { "AAPL": { "expiry": datetime.now(timezone.utc) + timedelta(hours=1), "data": {"symbol": "AAPL", "price": 178.50, "description": "Apple Inc."} } } db.save_price_cache_to_db(price_cache) # Load price cache on startup loaded_cache = db.load_price_cache_from_db() print(f"Loaded {len(loaded_cache)} items from cache") ``` ### Response #### Success Response (N/A) Data is saved to or loaded from the specified SQLite database file. #### Response Example (Loading Cache) ```json { "AAPL": { "expiry": "2023-12-15T10:30:00+00:00", "data": {"symbol": "AAPL", "price": 178.50, "description": "Apple Inc."} } } ``` ``` -------------------------------- ### Search FRED Series Source: https://context7.com/andriy-git/stockstui/llms.txt Searches for economic series by keyword using the FRED provider. ```python from stockstui.data_providers import fred_provider api_key = "your_fred_api_key" # Search for series by keyword results = fred_provider.search_series("unemployment rate", api_key) print("Search results for 'unemployment rate':") for series in results[:5]: print(f" {series['id']}: {series['title']}") print(f" Frequency: {series['frequency']}") print(f" Updated: {series['last_updated']}") print() ``` -------------------------------- ### Check Cache Status Source: https://context7.com/andriy-git/stockstui/llms.txt Verify if data is available in the local cache before performing an API request. ```python from stockstui.data_providers import market_provider # Check if ticker is in cache if market_provider.is_cached("AAPL"): # Get cached data without API call cached = market_provider.get_cached_price("AAPL") print(f"Cached price: ${cached['price']:.2f}") ``` -------------------------------- ### Calculate Put Option Greeks Source: https://context7.com/andriy-git/stockstui/llms.txt Calculates and prints the delta for a put option using the calculate_greeks function. ```python put_greeks = calculate_greeks('p', S=150.0, K=155.0, T=0.25, r=0.045, sigma=0.30) print(f"\nPut Delta: {put_greeks['delta']:.4f}") # Negative for puts ``` -------------------------------- ### Fetch Historical Stock Data Source: https://context7.com/andriy-git/stockstui/llms.txt Fetches historical Open, High, Low, Close, and Volume (OHLCV) data for a given ticker and period. Returns a pandas DataFrame. Ensure the DataFrame is not empty before processing. ```python from stockstui.data_providers import market_provider # Fetch historical OHLCV data # Returns a pandas DataFrame with index as datetime ticker = "TSLA" period = "1mo" # 1d, 5d, 1mo, 6mo, ytd, 1y, 5y, max interval = "1d" # 1m, 5m, 15m, 1h, 1d, 1wk, 1mo df = market_provider.get_historical_data(ticker, period, interval) if not df.empty: print(f"Historical data for {df.attrs.get('symbol', ticker)}") print(df.head()) # Output: # Open High Low Close Volume # Date # 2024-01-02 248.42 251.25 244.41 248.42 112117500 # 2024-01-03 246.42 249.13 244.03 248.48 79444300 else: error = df.attrs.get('error', 'Unknown error') print(f"Error: {error}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.