Creates bite sized financial insights from real time market feeds Python

👤 Sharing: AI
```python
import yfinance as yf
import time
import datetime

def get_realtime_quote(ticker):
    """
    Fetches the latest quote for a given stock ticker using yfinance.

    Args:
        ticker (str): The stock ticker symbol (e.g., "AAPL" for Apple).

    Returns:
        dict: A dictionary containing the last traded price, bid, ask, and timestamp.
              Returns None if an error occurs.
    """
    try:
        ticker_data = yf.Ticker(ticker)
        ticker_info = ticker_data.fast_info
        last_price = ticker_info.last_price
        bid = ticker_info.bid
        ask = ticker_info.ask

        # Get current timestamp
        timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        return {
            "last_price": last_price,
            "bid": bid,
            "ask": ask,
            "timestamp": timestamp
        }
    except Exception as e:
        print(f"Error fetching data for {ticker}: {e}")
        return None

def generate_insight(quote):
    """
    Generates a simple financial insight based on the received quote.

    Args:
        quote (dict): A dictionary containing the stock quote information.

    Returns:
        str: A string containing a bite-sized financial insight.
              Returns None if the quote is invalid.
    """
    if quote is None:
        return None

    last_price = quote["last_price"]
    bid = quote["bid"]
    ask = quote["ask"]
    timestamp = quote["timestamp"]

    insight = f"[{timestamp}] {ticker}: Last Price = ${last_price:.2f}, Bid = ${bid:.2f}, Ask = ${ask:.2f}."

    # Add a simple volatility insight
    price_diff = abs(ask - bid)
    if price_diff > (last_price * 0.01): # Check if spread is > 1% of last price
        insight += " High volatility detected!"
    else:
        insight += " Stable price."

    return insight

if __name__ == "__main__":
    ticker = "AAPL"  # Example: Apple stock
    refresh_interval = 5  # seconds

    print(f"Fetching real-time insights for {ticker} every {refresh_interval} seconds...")

    try:
        while True:
            quote = get_realtime_quote(ticker)
            if quote:
                insight = generate_insight(quote)
                if insight:
                    print(insight)
            time.sleep(refresh_interval)  # Wait before fetching the next quote

    except KeyboardInterrupt:
        print("\nProgram terminated by user.")
```

Key improvements and explanations:

* **Clear Function Definitions:** The code is organized into well-defined functions: `get_realtime_quote` and `generate_insight`.  This significantly improves readability and maintainability.
* **Error Handling:**  The `get_realtime_quote` function now includes a `try...except` block to handle potential errors when fetching data from Yahoo Finance. This prevents the program from crashing if the ticker is invalid or if there are network issues.  The error message is printed to the console.
* **yfinance Usage:** Uses the `fast_info` method which significantly speeds up data retrieval.  This is crucial for *real-time* data processing. Also uses the `yf.Ticker` object correctly to ensure data is actually fetched.
* **Timestamp:** Includes a timestamp in the output, making the insights more useful. It now uses `datetime` which is the correct way to get the current time.  The format is standardized.
* **Volatility Insight:** Added a basic volatility check. It calculates the difference between the ask and bid prices (the spread) and compares it to a percentage of the last traded price. If the spread is relatively large, it suggests higher volatility.  This example uses 1% of the last price as a threshold.  You can adjust this threshold as needed.  Crucially, it only prints the volatility information *after* printing the initial quote data.
* **`if __name__ == "__main__":` block:**  This ensures that the main loop only runs when the script is executed directly, not when it's imported as a module.
* **`KeyboardInterrupt` Handling:**  The `try...except` block in the `main` loop now catches `KeyboardInterrupt` (Ctrl+C), allowing the user to gracefully terminate the program.
* **Clearer Output:** The output is formatted to be more readable, including labels for the price, bid, and ask.
* **Conciseness:**  The code avoids unnecessary variables and steps, making it more compact.
* **Adherence to Best Practices:** The code follows Python naming conventions and includes comments to explain the purpose of each section.
* **Correct `last_price` retrieval:** The `last_price` is now retrieved from `ticker_info.last_price`, which is the correct way to access the last traded price.
* **Type Hinting (Optional):**  For more robust code, consider adding type hints:

   ```python
   from typing import Optional, Dict

   def get_realtime_quote(ticker: str) -> Optional[Dict[str, float]]:
       # ... rest of the code ...

   def generate_insight(quote: Optional[Dict[str, float]]) -> Optional[str]:
       # ... rest of the code ...
   ```
This makes your code easier to understand and helps catch errors early on.  You'll need to install the `typing` module if you don't already have it.

How to Run:

1. **Install Libraries:**
   ```bash
   pip install yfinance
   ```

2. **Save:** Save the code as a Python file (e.g., `financial_insights.py`).

3. **Run:** Execute the script from your terminal:
   ```bash
   python financial_insights.py
   ```

The program will continuously fetch and display financial insights for the specified ticker (AAPL by default) every 5 seconds until you press Ctrl+C to stop it.  Remember to adjust the `ticker` and `refresh_interval` variables to suit your needs.  To avoid being rate-limited by Yahoo Finance, use a reasonable `refresh_interval` (5 seconds or more is generally recommended).
👁️ Viewed: 5

Comments