openapi: 3.1.0
info:
  title: API Documentation
  description: >
    # Financial Analytics API


    ## Overview


    The Financial Analytics API provides comprehensive data analysis and
    insights for ISA investments and trading behavior. This powerful platform
    enables financial institutions, advisors, and analysts to access detailed
    metrics, trends, and recommendations through a simple, consistent REST API.


    ## Key Capabilities


    ### ISA Analytics

    Access detailed analytics on Individual Savings Accounts (ISAs) including:

    - Provider market share and performance metrics

    - Customer demographic analysis across age groups and income brackets

    - Behavioral patterns and investment preferences

    - Term duration and risk profile analysis

    - Personalized provider recommendations


    ### Trading Analytics

    Comprehensive trading data analysis including:

    - Market trends and sentiment indicators

    - Trading pair popularity and directional bias

    - Trader behavior patterns and preferences

    - Broker performance metrics and comparison

    - Predictive signals and anomaly detection


    ## Authentication


    All API requests require authentication using an API key which should be
    passed as a query parameter:


    ```

    GET /isa/summary?api_key=your_api_key

    ```


    Contact our team to obtain your API key and access credentials.


    ## Rate Limits


    Our API offers different tiers of access:

    - Standard: 60 requests per minute

    - Premium: 300 requests per minute

    - Enterprise: Custom limits available


    ## Response Format


    All responses are returned in JSON format and follow a consistent structure:


    ```json

    {
      "timestamp": "2024-03-20T12:00:00Z",
      "data": {
        // Response data specific to the endpoint
      }
    }

    ```


    ## Error Handling


    The API uses standard HTTP status codes to indicate the success or failure
    of requests:


    - 200: Success

    - 400: Bad request (invalid parameters)

    - 401: Unauthorized (invalid API key)

    - 404: Resource not found

    - 422: Validation error

    - 429: Rate limit exceeded

    - 500: Server error


    Error responses include detailed information to help troubleshoot the issue:


    ```json

    {
      "timestamp": "2024-03-20T12:00:00Z",
      "error": "Validation Error",
      "detail": "Invalid parameter: start_date must be in DD-MM-YY format"
    }

    ```


    ## Versioning


    The API uses a semantic versioning system (Major.Minor.Patch). The current
    version is 2.1.3.


    ## Getting Started


    1. Sign up for an API key at our developer portal

    2. Explore the available endpoints in this documentation

    3. Make your first request to the API

    4. Implement the insights into your application or analysis
  version: 2.1.3
paths:
  /trading/trends/monthly:
    get:
      tags:
        - Market Analysis
      summary: Monthly Trends
      description: Get monthly trends with weighted scoring based on lot sizes and recency
      operationId: get_monthly_trends_trading_trends_monthly_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: end_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: End Date
        - name: days
          in: query
          required: false
          schema:
            type: integer
            maximum: 90
            minimum: 1
            default: 30
            title: Days
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TradingTrendsResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/trends/daily:
    get:
      tags:
        - Market Analysis
      summary: Daily Trends
      description: >-
        Get daily trading trends with weighted scoring based on lot sizes and
        recency
      operationId: get_daily_trends_trading_trends_daily_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: end_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: End Date
        - name: hours
          in: query
          required: false
          schema:
            type: integer
            maximum: 168
            minimum: 1
            default: 24
            title: Hours
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TradingTrendsResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/predictive-signals:
    get:
      tags:
        - Market Analysis
      summary: Predictive Signals
      description: Get predictive signals for trading patterns and trends
      operationId: get_predictive_signals_trading_predictive_signals_get
      parameters:
        - name: instrument
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Instrument
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: lookback_days
          in: query
          required: false
          schema:
            type: integer
            maximum: 180
            minimum: 1
            default: 30
            title: Lookback Days
        - name: min_trades
          in: query
          required: false
          schema:
            type: integer
            minimum: 5
            default: 10
            title: Min Trades
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/instrument-breakdown/{instrument}:
    get:
      tags:
        - Behavioral
      summary: Segment Correlation
      description: Get detailed trading metrics breakdown by experience level segments
      operationId: get_segment_correlation_trading_instrument_breakdown__instrument__get
      parameters:
        - name: instrument
          in: path
          required: true
          schema:
            type: string
            title: Instrument
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InstrumentBreakdownResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/position-size:
    get:
      tags:
        - Market Analysis
      summary: Position Size
      description: Get breakdown of total lots traded by instrument for buy/sell operations
      operationId: get_lotsize_positioning_trading_position_size_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PositionSizeResponse'
  /trading/trade-frequency/{instrument}/{start_date}:
    get:
      tags:
        - Market Analysis
      summary: Trade Frequency
      description: Get predictive signals for lot size patterns
      operationId: >-
        get_trade_frequency_trading_trade_frequency__instrument___start_date__get
      parameters:
        - name: instrument
          in: path
          required: true
          schema:
            type: string
            title: Instrument
        - name: start_date
          in: path
          required: true
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: lookback_days
          in: query
          required: false
          schema:
            type: integer
            maximum: 180
            minimum: 1
            default: 30
            title: Lookback Days
        - name: min_trades
          in: query
          required: false
          schema:
            type: integer
            minimum: 5
            default: 10
            title: Min Trades
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TradeFrequencyResponse'
              example:
                instrument: EURUSD
                total_trades: 2854
                frequency_analysis:
                  daily_statistics:
                    average_trades_per_day: 95.13
                    most_active_day: Wednesday
                    least_active_day: Sunday
                    day_distribution:
                      Monday: 15.2
                      Tuesday: 18.7
                      Wednesday: 22.5
                      Thursday: 19.8
                      Friday: 16.5
                      Saturday: 4.2
                      Sunday: 3.1
                  hourly_statistics:
                    most_active_hour: 14:00-15:00 UTC
                    least_active_hour: 03:00-04:00 UTC
                    peak_activity_period: London/New York overlap
                  trend_analysis:
                    frequency_trend: increasing
                    volume_correlation: 0.78
                    volatility_correlation: 0.65
                segments:
                  experience_breakdown:
                    beginner: 32.5
                    intermediate: 45.7
                    expert: 21.8
                  direction_breakdown:
                    buy: 52.3
                    sell: 47.7
                timestamp_utc: '2024-03-25T12:34:56.789Z'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/broker-comparison/{broker1}/{broker2}:
    get:
      tags:
        - Broker Insights
      summary: Broker Comparison
      description: Compare performance metrics between brokers
      operationId: get_broker_comparison_trading_broker_comparison__broker1___broker2__get
      parameters:
        - name: broker1
          in: path
          required: true
          schema:
            type: string
            title: Broker1
        - name: broker2
          in: path
          required: true
          schema:
            type: string
            title: Broker2
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: object
                properties:
                  brokers:
                    type: array
                    items:
                      type: string
                  comparison_metrics:
                    type: object
                    properties:
                      trader_count:
                        type: object
                        additionalProperties:
                          type: integer
                      average_trade_size:
                        type: object
                        additionalProperties:
                          type: number
                      win_rate:
                        type: object
                        additionalProperties:
                          type: number
                      popular_instruments:
                        type: object
                        additionalProperties:
                          type: string
                  timestamp_utc:
                    type: string
                    format: date-time
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/broker:
    get:
      tags:
        - Behavioral
      summary: Broker Data
      description: Get detailed trading data for a specific broker
      operationId: get_broker_data_trading_broker_get
      parameters:
        - name: broker
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Broker
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/broker-preferences:
    get:
      tags:
        - Broker Insights
      summary: Broker Preferences
      description: |-
        Get detailed analysis of broker preferences by trader experience level

        Returns:
            Detailed preferences analysis for each experience level
      operationId: get_broker_preferences_trading_broker_preferences_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BrokerPreferencesResponse'
  /trading/broker-breakdown:
    get:
      tags:
        - Broker Insights
      summary: Broker Breakdown
      description: Get comprehensive breakdown of broker statistics
      operationId: endpoint_broker_breakdown_trading_broker_breakdown_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BrokerBreakdownResponse'
  /trading/experience-breakdown:
    get:
      tags:
        - Trader Analytics
      summary: Experience Level Breakdown
      description: Get breakdown of trading data by experience level
      operationId: endpoint_experience_level_breakdown_trading_experience_breakdown_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExperienceBreakdownResponse'
  /trading/pair-breakdown:
    get:
      tags:
        - Behavioral
      summary: Pair Breakdown
      description: Get breakdown of trading data by trading pair
      operationId: endpoint_pair_breakdown_trading_pair_breakdown_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /trading/timeframe-breakdown:
    get:
      tags:
        - Trader Analytics
      summary: Time Frame Breakdown
      description: Get breakdown of trading data by time frame
      operationId: endpoint_time_frame_breakdown_trading_timeframe_breakdown_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TimeframeBreakdownResponse'
  /trading/direction-breakdown:
    get:
      tags:
        - Trader Analytics
      summary: Direction Breakdown
      description: Get breakdown of trading data by direction (buy/sell)
      operationId: endpoint_direction_breakdown_trading_direction_breakdown_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DirectionBreakdownResponse'
  /trading/summary:
    get:
      tags:
        - Summary Metrics
      summary: Trading Summary
      description: Get a comprehensive summary of trading data
      operationId: get_trading_summary_trading_summary_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /trading/trending-pairs:
    get:
      tags:
        - Behavioral
      summary: Trending Pairs
      description: Get trending trading pairs across all time or from a specific date
      operationId: endpoint_trending_pairs_trading_trending_pairs_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: days
          in: query
          required: false
          schema:
            type: integer
            maximum: 90
            minimum: 1
            default: 30
            title: Days
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/market-sentiment/{start_date}:
    get:
      tags:
        - Market Analysis
      summary: Market Sentiment
      description: Get market sentiment analysis based on trading activity
      operationId: endpoint_market_sentiment_trading_market_sentiment__start_date__get
      parameters:
        - name: start_date
          in: path
          required: true
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MarketSentimentResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/trends/weekly:
    get:
      tags:
        - Market Analysis
      summary: Weekly Trends
      description: >-
        Get weekly trading trends with weighted scoring based on lot sizes and
        recency
      operationId: get_weekly_trends_trading_trends_weekly_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: end_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: End Date
        - name: days
          in: query
          required: false
          schema:
            type: integer
            maximum: 14
            minimum: 1
            default: 7
            title: Days
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TradingTrendsResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/most-popular-trading-pair:
    get:
      tags:
        - Summary Metrics
      summary: Most Popular Trading Pair
      description: >-
        Get the most popular trading pair across all time or from a specific
        date
      operationId: endpoint_most_popular_trading_pair_trading_most_popular_trading_pair_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/most-popular-currency:
    get:
      tags:
        - Summary Metrics
      summary: Most Popular Currency
      description: >-
        Get the most popular selected currency across all time or from a
        specific date
      operationId: endpoint_most_popular_currency_trading_most_popular_currency_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/most-popular-broker:
    get:
      tags:
        - Summary Metrics
      summary: Most Popular Broker
      description: Get the most popular broker across all time or from a specific date
      operationId: endpoint_most_popular_broker_trading_most_popular_broker_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/most-popular-experience-level:
    get:
      tags:
        - Summary Metrics
      summary: Most Popular Experience Level
      description: >-
        Get the most popular experience level across all time or from a specific
        date
      operationId: >-
        endpoint_most_popular_experience_level_trading_most_popular_experience_level_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/most-popular-direction:
    get:
      tags:
        - Summary Metrics
      summary: Most Popular Direction
      description: >-
        Get the most popular trading direction across all time or from a
        specific date
      operationId: endpoint_most_popular_direction_trading_most_popular_direction_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/most-popular-timeframe:
    get:
      tags:
        - Summary Metrics
      summary: Most Popular Timeframe
      description: Get the most popular timeframe across all time or from a specific date
      operationId: endpoint_most_popular_timeframe_trading_most_popular_timeframe_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /trading/broker-opportunities:
    get:
      tags:
        - Broker Insights
      summary: Broker Opportunities
      description: >-
        Get broker opportunities by identifying high-value traders based on
        volatility, timeframe, and experience.


        High-value traders are those who:

        1. Trade predominantly on shorter timeframes (1h or lower)

        2. Trade volatile instruments (like XAUUSD, GBPJPY, exotic pairs,
        BTCUSD)

        3. Have low experience level (1-2 years or 3-4 years, with higher weight
        for less experienced)


        Returns:
            Ranked list of brokers with high-value trader potential and targeting recommendations
      operationId: endpoint_broker_opportunities_trading_broker_opportunities_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: object
                properties:
                  broker:
                    type: string
                  opportunities:
                    type: array
                    items:
                      type: object
                      properties:
                        segment:
                          type: string
                        potential:
                          type: number
                        description:
                          type: string
                        competitor_analysis:
                          type: object
                          additionalProperties:
                            type: number
                  timestamp_utc:
                    type: string
                    format: date-time
  /ISA/bank-breakdown:
    get:
      tags:
        - ISA Analytics/Provider
      summary: Bank Breakdown
      description: |-
        Get bank breakdown with metrics by provider

        Args:
            request: FastAPI request object
            provider: Optional provider name to filter by
            start_date: Optional start date in DD-MM-YY format
            end_date: Optional end date in DD-MM-YY format

        Returns:
            Bank breakdown information including provider statistics
      operationId: get_bank_breakdown_isa_bank_breakdown_get
      parameters:
        - name: provider
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Provider
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: end_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: End Date
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BankBreakdownResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /ISA/age-breakdown:
    get:
      tags:
        - ISA Analytics/Demographic
      summary: Age Breakdown
      description: |-
        Get age breakdown metrics

        Args:
            request: FastAPI request object
            provider: Optional provider name to filter by
            start_date: Optional start date in DD-MM-YY format
            end_date: Optional end date in DD-MM-YY format

        Returns:
            Age breakdown information including demographic statistics
      operationId: get_age_breakdown_isa_age_breakdown_get
      parameters:
        - name: provider
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Provider
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: end_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: End Date
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AgeBreakdownResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /ISA/summary:
    get:
      tags:
        - ISA Analytics/Summary
      summary: Isa Summary Endpoint
      description: |-
        Get summary of ISA statistics

        Args:
            request: FastAPI request object
            
        Returns:
            Summary of ISA statistics including averages, customer types, and popular metrics
      operationId: get_isa_summary_endpoint_isa_summary_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /ISA/trends:
    get:
      tags:
        - ISA Analytics/Behavioral
      summary: Trends
      description: |-
        Get ISA trends for the specified date range or default lookback period

        Args:
            request: FastAPI request object
            start_date: Optional start date in DD-MM-YY format
            end_date: Optional end date in DD-MM-YY format
            
        Returns:
            ISA trend information
      operationId: endpoint_trends_isa_trends_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: end_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: End Date
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /ISA/term-breakdown:
    get:
      tags:
        - ISA Analytics/Provider
      summary: Term Breakdown
      description: |-
        Get breakdown analysis by term length (years)

        Args:
            request: FastAPI request object
            provider: Filter by provider
            start_date: Optional start date in DD-MM-YY format
            end_date: Optional end date in DD-MM-YY format

        Returns:
            ISA statistics broken down by term length categories
      operationId: get_term_breakdown_isa_term_breakdown_get
      parameters:
        - name: provider
          in: query
          required: false
          schema:
            type: string
            description: Filter by provider
            title: Provider
          description: Filter by provider
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: end_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: End Date
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InflowBreakdownResponse'
              example:
                status: success
                message: Term breakdown retrieved successfully
                timestamp: '2023-06-01T12:00:00Z'
                data:
                  date_range: 01-01-24 to 01-02-24
                  term_categories:
                    - id: short_term
                      name: Short Term
                      description: ISA term length up to 1 year
                      percentage: 25
                      metrics:
                        average_initial_deposit: 3000
                        average_monthly_deposit: 200
                        average_interest_rate: 1.8
                      age_distribution:
                        18-24: 15
                        25-34: 35
                        35-44: 25
                      provider_distribution:
                        Bank A: 30
                        Bank B: 25
                        Bank C: 20
                      most_common_provider: Bank A
                      most_common_income: £30k-£40k
                      income_distribution:
                        £20k-£30k: 25
                        £30k-£40k: 40
                        £40k-£50k: 20
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /ISA/income-breakdown:
    get:
      tags:
        - ISA Analytics/Demographic
      summary: Income Breakdown
      description: |-
        Get breakdown analysis by income level

        Args:
            request: FastAPI request object
            provider: Filter by provider
            start_date: Optional start date in DD-MM-YY format
            end_date: Optional end date in DD-MM-YY format

        Returns:
            ISA statistics broken down by income categories
      operationId: get_income_breakdown_isa_income_breakdown_get
      parameters:
        - name: provider
          in: query
          required: false
          schema:
            type: string
            description: Filter by provider
            title: Provider
          description: Filter by provider
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: end_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: End Date
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InflowBreakdownResponse'
              example:
                status: success
                message: Income breakdown retrieved successfully
                timestamp: '2023-06-01T12:00:00Z'
                data:
                  date_range: 01-01-24 to 01-02-24
                  income_categories:
                    - id: 30k_to_40k
                      name: £30k-£40k
                      description: Annual income between £30,000-£40,000
                      percentage: 35
                      metrics:
                        average_initial_deposit: 4500
                        average_monthly_deposit: 250
                        average_interest_rate: 2.2
                      age_distribution:
                        25-34: 45
                        35-44: 35
                        45-54: 20
                      provider_distribution:
                        Bank A: 35
                        Bank B: 30
                        Bank C: 20
                      most_common_provider: Bank A
                      most_common_age: 25-34
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /ISA/isa-type:
    get:
      tags:
        - ISA Analytics/Behavioral
      summary: ISA Type
      description: |-
        Get breakdown of ISA data by calculator type

        Args:
            request: FastAPI request object
            provider: Filter by provider
            
        Returns:
            ISA calculator type breakdown information
      operationId: endpoint_isa_type_isa_isa_type_get
      parameters:
        - name: provider
          in: query
          required: false
          schema:
            type: string
            description: Filter by provider
            title: Provider
          description: Filter by provider
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InflowBreakdownResponse'
              example:
                status: success
                message: ISA type breakdown retrieved successfully
                timestamp: '2023-06-01T12:00:00Z'
                data:
                  date_range: 01-01-24 to 01-02-24
                  isa_type:
                    - id: cash_isa
                      name: Cash ISA
                      description: Cash ISA accounts
                      percentage_of_total: 45.5
                      metrics:
                        average_initial_deposit: 5000
                        average_monthly_deposit: 300
                        average_interest_rate: 2.5
                      age_distribution:
                        18-24: 10
                        25-34: 25
                        35-44: 30
                        45-54: 20
                        55+: 15
                      provider_distribution:
                        Bank A: 35
                        Bank B: 25
                        Bank C: 20
                        Other: 20
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /ISA/risk-breakdown:
    get:
      tags:
        - ISA Analytics/Provider
      summary: Risk Breakdown
      description: |-
        Get breakdown analysis by risk score

        Args:
            request: FastAPI request object
            provider: Filter by provider
            start_date: Optional start date in DD-MM-YY format
            end_date: Optional end date in DD-MM-YY format

        Returns:
            ISA statistics broken down by risk profile
      operationId: get_risk_breakdown_isa_risk_breakdown_get
      parameters:
        - name: provider
          in: query
          required: false
          schema:
            type: string
            description: Filter by provider
            title: Provider
          description: Filter by provider
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: end_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: End Date
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InflowBreakdownResponse'
              example:
                status: success
                message: Risk breakdown retrieved successfully
                timestamp: '2023-06-01T12:00:00Z'
                data:
                  date_range: 01-01-24 to 01-02-24
                  risk_categories:
                    - id: medium_risk
                      name: Medium Risk
                      description: Balanced investment strategy with moderate risk
                      percentage: 40
                      metrics:
                        average_initial_deposit: 5500
                        average_monthly_deposit: 350
                        average_interest_rate: 3.2
                      age_distribution:
                        25-34: 35
                        35-44: 40
                        45-54: 15
                      provider_distribution:
                        Bank A: 25
                        Bank B: 40
                        Bank C: 20
                      most_common_provider: Bank B
                      most_common_age: 35-44
                      most_common_income: £40k-£50k
                      income_distribution:
                        £30k-£40k: 30
                        £40k-£50k: 45
                        £50k-£75k: 25
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /ISA/inflow-breakdown:
    get:
      tags:
        - ISA Analytics/Provider
      summary: Inflow Breakdown
      description: >-
        Get breakdown analysis of ISA inflow patterns showing provider
        transitions

        from current_provider to new_provider with associated metrics.


        Args:
            request: FastAPI request object
            provider: Filter by provider (looks in both current_provider and new_provider)
            start_date: Optional start date in DD-MM-YY format
            end_date: Optional end date in DD-MM-YY format

        Returns:
            ISA statistics broken down by provider transitions
      operationId: get_inflow_breakdown_isa_inflow_breakdown_get
      parameters:
        - name: provider
          in: query
          required: false
          schema:
            type: string
            description: Filter by provider
            title: Provider
          description: Filter by provider
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: end_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: End Date
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InflowBreakdownResponse'
              example:
                status: success
                message: Inflow breakdown retrieved successfully
                timestamp: '2023-06-01T12:00:00Z'
                data:
                  date_range: 01-01-24 to 01-02-24
                  provider: all
                  provider_transitions:
                    - from_provider: Bank A
                      to_provider: Bank B
                      percentage: 35
                      metrics:
                        average_initial_deposit: 5000
                        average_monthly_deposit: 300
                        average_interest_rate: 2.5
                      most_common_age_group: 25-34
                      most_common_income: £30k-£40k
                      isa_type: Cash ISA
                      age_distribution:
                        18-24: 10
                        25-34: 25
                        35-44: 30
                        45-54: 20
                        55+: 15
                      provider_distribution:
                        Bank A: 35
                        Bank B: 25
                        Bank C: 20
                        Other: 20
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /ISA/average-final-amount:
    get:
      tags:
        - ISA Analytics/Behavioral
      summary: Average Final Amount
      description: Get the average final amount across all time
      operationId: endpoint_average_final_amount_isa_average_final_amount_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: period
          in: query
          required: false
          schema:
            type: string
            description: Optional time period filter (e.g., '7d', '30d', '90d', '1y')
            title: Period
          description: Optional time period filter (e.g., '7d', '30d', '90d', '1y')
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /ISA/average-growth-amount:
    get:
      tags:
        - ISA Analytics/Behavioral
      summary: Average Growth Amount
      description: Get the average growth amount across all time
      operationId: endpoint_average_growth_amount_isa_average_growth_amount_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: period
          in: query
          required: false
          schema:
            type: string
            description: Optional time period filter (e.g., '7d', '30d', '90d', '1y')
            title: Period
          description: Optional time period filter (e.g., '7d', '30d', '90d', '1y')
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /ISA/average-deposit-transfer/{start_date}:
    get:
      tags:
        - ISA Analytics/Behavioral
      summary: Average Deposit Transfer
      description: Get the average deposit for transfers
      operationId: >-
        endpoint_average_deposit_transfer_isa_average_deposit_transfer__start_date__get
      parameters:
        - name: start_date
          in: path
          required: true
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: period
          in: query
          required: false
          schema:
            type: string
            description: Optional time period filter (e.g., '7d', '30d', '90d', '1y')
            title: Period
          description: Optional time period filter (e.g., '7d', '30d', '90d', '1y')
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /ISA/average-final-amount-transfer/{start_date}:
    get:
      tags:
        - ISA Analytics/Behavioral
      summary: Average Final Amount Transfer
      description: Get the average final amount for transfers
      operationId: >-
        endpoint_average_final_amount_transfer_isa_average_final_amount_transfer__start_date__get
      parameters:
        - name: start_date
          in: path
          required: true
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: period
          in: query
          required: false
          schema:
            type: string
            description: Optional time period filter (e.g., '7d', '30d', '90d', '1y')
            title: Period
          description: Optional time period filter (e.g., '7d', '30d', '90d', '1y')
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /ISA/most-popular-years:
    get:
      tags:
        - ISA Analytics/Behavioral
      summary: Most Popular Years
      description: Get the most popular years for ISA investments
      operationId: endpoint_most_popular_years_isa_most_popular_years_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: period
          in: query
          required: false
          schema:
            type: string
            description: Optional time period filter (e.g., '7d', '30d', '90d', '1y')
            title: Period
          description: Optional time period filter (e.g., '7d', '30d', '90d', '1y')
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /ISA/average-years:
    get:
      tags:
        - ISA Analytics/Behavioral
      summary: Average Years
      description: Get the average years for ISA investments
      operationId: endpoint_average_years_isa_average_years_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: period
          in: query
          required: false
          schema:
            type: string
            description: Optional time period filter (e.g., '7d', '30d', '90d', '1y')
            title: Period
          description: Optional time period filter (e.g., '7d', '30d', '90d', '1y')
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /ISA/average-interest-rate:
    get:
      tags:
        - ISA Analytics/Behavioral
      summary: Average Interest Rate
      description: Get the average interest rate for ISA investments
      operationId: endpoint_average_interest_rate_isa_average_interest_rate_get
      parameters:
        - name: start_date
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Start Date
        - name: period
          in: query
          required: false
          schema:
            type: string
            description: Optional time period filter (e.g., '7d', '30d', '90d', '1y')
            title: Period
          description: Optional time period filter (e.g., '7d', '30d', '90d', '1y')
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
components:
  schemas:
    AgeBreakdownResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            date_range:
              type: string
              example: 25-02-24 to 25-03-24
            total_age_groups:
              type: integer
              example: 5
            age_statistics:
              type: array
              items:
                type: object
                properties:
                  age_group:
                    type: string
                    example: 25-34
                  percentage:
                    type: number
                    example: 38.7
                  average_initial_deposit:
                    type: number
                    example: 4250.5
                  average_monthly_deposit:
                    type: number
                    example: 325.75
                  average_interest_rate:
                    type: number
                    example: 4.25
                  average_annual_income:
                    type: number
                    example: 45000
                  most_common_provider:
                    type: string
                    example: Moneybox
                  most_common_isa_type:
                    type: string
                    example: Cash ISA
                  most_common_income:
                    type: string
                    example: £30k-£50k
                  provider_distribution:
                    type: object
                    additionalProperties:
                      type: number
                  income_distribution:
                    type: object
                    additionalProperties:
                      type: number
    ApiKeyResponse:
      properties:
        key_id:
          type: string
          title: Key Id
        client_id:
          type: string
          title: Client Id
        api_key:
          anyOf:
            - type: string
            - type: 'null'
          title: Api Key
        api_key_prefix:
          type: string
          title: Api Key Prefix
        created_at:
          type: string
          title: Created At
        expires_at:
          type: string
          title: Expires At
        revoked:
          type: boolean
          title: Revoked
        revoked_at:
          anyOf:
            - type: string
            - type: 'null'
          title: Revoked At
        last_used:
          anyOf:
            - type: string
            - type: 'null'
          title: Last Used
      type: object
      required:
        - key_id
        - client_id
        - api_key_prefix
        - created_at
        - expires_at
        - revoked
      title: ApiKeyResponse
      description: API key response model
    BankBreakdownResponse:
      type: object
      properties:
        status:
          type: string
          example: success
        message:
          type: string
          example: Bank breakdown retrieved successfully
        timestamp:
          type: string
          format: date-time
        total_providers:
          type: integer
          example: 15
        provider_statistics:
          type: array
          items:
            type: object
            properties:
              provider:
                type: string
                example: Moneybox
              customer_percentage:
                type: string
                example: '22.5'
              retention_rate:
                type: string
                example: '89.3'
              new_isa_acquisition_rate:
                type: string
                example: '68.7'
              transfer_acquisition_rate:
                type: string
                example: '31.3'
              average_initial_deposit:
                type: string
                example: '4850.75'
              average_monthly_deposit:
                type: integer
                example: 325
              average_interest_rate:
                type: string
                example: '4.25'
              average_stocks_isa_return:
                type: string
                example: '8.75'
              average_annual_income:
                type: string
                example: '45000.00'
              age_distribution:
                type: object
                additionalProperties:
                  type: number
              distribution:
                type: object
                additionalProperties:
                  type: number
              income_distribution:
                type: object
                additionalProperties:
                  type: number
              most_common_income:
                type: string
                example: £30k-£50k
        date_range:
          type: string
          example: 25-02-24 to 25-03-24
    Body_revoke_token_auth_revoke_post:
      properties:
        token:
          type: string
          title: Token
      type: object
      required:
        - token
      title: Body_revoke_token_auth_revoke_post
    BrokerPreferencesResponse:
      type: object
      properties:
        timestamp:
          type: string
          format: date-time
        data:
          type: object
        experience_levels:
          type: object
          properties:
            beginner:
              type: object
              properties:
                assets:
                  type: object
                  additionalProperties:
                    type: number
                platforms:
                  type: object
                  additionalProperties:
                    type: number
                customer_support_importance:
                  type: number
                education_importance:
                  type: number
                spreads_importance:
                  type: number
                automated_trading_importance:
                  type: number
                deposit_options_importance:
                  type: number
            intermediate:
              type: object
              properties:
                assets:
                  type: object
                  additionalProperties:
                    type: number
                platforms:
                  type: object
                  additionalProperties:
                    type: number
                customer_support_importance:
                  type: number
                education_importance:
                  type: number
                spreads_importance:
                  type: number
                automated_trading_importance:
                  type: number
                deposit_options_importance:
                  type: number
            advanced:
              type: object
              properties:
                assets:
                  type: object
                  additionalProperties:
                    type: number
                platforms:
                  type: object
                  additionalProperties:
                    type: number
                customer_support_importance:
                  type: number
                education_importance:
                  type: number
                spreads_importance:
                  type: number
                automated_trading_importance:
                  type: number
                deposit_options_importance:
                  type: number
    ClientResponse:
      properties:
        client_id:
          type: string
          title: Client Id
        name:
          type: string
          title: Name
        email:
          type: string
          title: Email
        contact_name:
          type: string
          title: Contact Name
        tier:
          type: string
          title: Tier
        rate_limit:
          type: integer
          title: Rate Limit
        active:
          type: boolean
          title: Active
        created_at:
          type: string
          title: Created At
        updated_at:
          type: string
          title: Updated At
        company:
          anyOf:
            - type: string
            - type: 'null'
          title: Company
        description:
          anyOf:
            - type: string
            - type: 'null'
          title: Description
      type: object
      required:
        - client_id
        - name
        - email
        - contact_name
        - tier
        - rate_limit
        - active
        - created_at
        - updated_at
      title: ClientResponse
      description: Client response model
    ClientWithKeysResponse:
      properties:
        client_id:
          type: string
          title: Client Id
        name:
          type: string
          title: Name
        email:
          type: string
          title: Email
        contact_name:
          type: string
          title: Contact Name
        tier:
          type: string
          title: Tier
        rate_limit:
          type: integer
          title: Rate Limit
        active:
          type: boolean
          title: Active
        created_at:
          type: string
          title: Created At
        updated_at:
          type: string
          title: Updated At
        company:
          anyOf:
            - type: string
            - type: 'null'
          title: Company
        description:
          anyOf:
            - type: string
            - type: 'null'
          title: Description
        api_keys:
          items:
            $ref: '#/components/schemas/ApiKeyResponse'
          type: array
          title: Api Keys
      type: object
      required:
        - client_id
        - name
        - email
        - contact_name
        - tier
        - rate_limit
        - active
        - created_at
        - updated_at
        - api_keys
      title: ClientWithKeysResponse
      description: Client response model with API keys
    CreateApiKeyRequest:
      properties:
        name:
          type: string
          title: Name
        description:
          anyOf:
            - type: string
            - type: 'null'
          title: Description
        permissions:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Permissions
      type: object
      required:
        - name
      title: CreateApiKeyRequest
      description: Request model for creating a new API key
    CreateClientRequest:
      properties:
        name:
          type: string
          title: Name
        email:
          type: string
          title: Email
        contact_name:
          type: string
          title: Contact Name
        tier:
          type: string
          title: Tier
          default: standard
        rate_limit:
          type: integer
          title: Rate Limit
          default: 120
        company:
          anyOf:
            - type: string
            - type: 'null'
          title: Company
        description:
          anyOf:
            - type: string
            - type: 'null'
          title: Description
      type: object
      required:
        - name
        - email
        - contact_name
      title: CreateClientRequest
      description: Client creation request model
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    InflowBreakdownResponse:
      type: object
      properties:
        data:
          type: array
          items:
            type: object
            properties:
              category:
                type: string
                example: 3 Years
              total_amount:
                type: number
                example: 12562500.5
              average_amount:
                type: number
                example: 4182.75
              count:
                type: integer
                example: 3004
              percentage:
                type: number
                example: 35.8
        status:
          type: string
          example: success
        timestamp:
          type: string
          format: date-time
        date_range:
          type: string
          example: 25-02-24 to 25-03-24
        provider:
          type: string
          example: All Providers
        breakdown_type:
          type: string
          example: Term
    ProviderRecommendationResponse:
      type: object
      properties:
        provider:
          type: string
          example: Moneybox
        recommendations:
          type: array
          items:
            type: object
            properties:
              provider:
                type: string
                example: Vanguard
              recommendation_score:
                type: number
                example: 92.5
              recommendation_reasons:
                type: array
                items:
                  type: string
                example:
                  - Higher average interest rate (+0.35%)
                  - Better customer satisfaction score (+7.5%)
                  - Lower account fees (-£15/year)
                  - Similar customer demographic profile
              comparison_metrics:
                type: object
                properties:
                  interest_rate_diff:
                    type: number
                    example: 0.35
                  fee_diff:
                    type: number
                    example: -15
                  customer_satisfaction_diff:
                    type: number
                    example: 7.5
        status:
          type: string
          example: success
        timestamp:
          type: string
          format: date-time
    TokenRequest:
      properties:
        api_key:
          type: string
          title: Api Key
      type: object
      required:
        - api_key
      title: TokenRequest
      description: Token request model
    TokenResponse:
      properties:
        access_token:
          type: string
          title: Access Token
        token_type:
          type: string
          title: Token Type
          default: bearer
        expires_in:
          type: integer
          title: Expires In
        client_id:
          type: string
          title: Client Id
        name:
          type: string
          title: Name
      type: object
      required:
        - access_token
        - expires_in
        - client_id
        - name
      title: TokenResponse
      description: Token response model
    TraderPreferences:
      properties:
        assets:
          additionalProperties:
            type: number
          type: object
          title: Assets
        platforms:
          additionalProperties:
            type: number
          type: object
          title: Platforms
        customer_support_importance:
          type: number
          title: Customer Support Importance
        education_importance:
          type: number
          title: Education Importance
        spreads_importance:
          type: number
          title: Spreads Importance
        automated_trading_importance:
          type: number
          title: Automated Trading Importance
        deposit_options_importance:
          type: number
          title: Deposit Options Importance
      type: object
      required:
        - assets
        - platforms
        - customer_support_importance
        - education_importance
        - spreads_importance
        - automated_trading_importance
        - deposit_options_importance
      title: TraderPreferences
    TrendsResponse:
      type: object
      properties:
        status:
          type: string
          example: success
        period:
          type: string
          example: 30d
        provider_trends:
          type: array
          items:
            type: object
            properties:
              provider:
                type: string
                example: Moneybox
              trend_stats:
                type: object
                properties:
                  market_share:
                    type: object
                    properties:
                      current:
                        type: number
                        example: 22.5
                      previous:
                        type: number
                        example: 20.2
                      trend:
                        type: number
                        example: 2.3
                  interest_rate:
                    type: object
                    properties:
                      current:
                        type: number
                        example: 4.25
                      previous:
                        type: number
                        example: 3.95
                      trend:
                        type: number
                        example: 0.3
                  average_deposit:
                    type: object
                    properties:
                      current:
                        type: number
                        example: 4850.75
                      previous:
                        type: number
                        example: 4650.25
                      trend:
                        type: number
                        example: 200.5
        segment_trends:
          type: object
          properties:
            age:
              type: array
              items:
                type: object
                properties:
                  segment:
                    type: string
                    example: 25-34
                  current:
                    type: number
                    example: 38.7
                  previous:
                    type: number
                    example: 37.2
                  trend:
                    type: number
                    example: 1.5
            income:
              type: array
              items:
                type: object
                properties:
                  segment:
                    type: string
                    example: £30k-£50k
                  current:
                    type: number
                    example: 42.1
                  previous:
                    type: number
                    example: 41.5
                  trend:
                    type: number
                    example: 0.6
        timestamp:
          type: string
          format: date-time
        date_range:
          type: string
          example: 2024-02-24 to 2024-03-24
    UpdateApiKeyRequest:
      properties:
        name:
          anyOf:
            - type: string
            - type: 'null'
          title: Name
        description:
          anyOf:
            - type: string
            - type: 'null'
          title: Description
        is_active:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Is Active
        permissions:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Permissions
      type: object
      title: UpdateApiKeyRequest
      description: Request model for updating an API key
    UpdateClientRequest:
      properties:
        name:
          anyOf:
            - type: string
            - type: 'null'
          title: Name
        email:
          anyOf:
            - type: string
            - type: 'null'
          title: Email
        contact_name:
          anyOf:
            - type: string
            - type: 'null'
          title: Contact Name
        tier:
          anyOf:
            - type: string
            - type: 'null'
          title: Tier
        rate_limit:
          anyOf:
            - type: integer
            - type: 'null'
          title: Rate Limit
        active:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Active
        company:
          anyOf:
            - type: string
            - type: 'null'
          title: Company
        description:
          anyOf:
            - type: string
            - type: 'null'
          title: Description
      type: object
      title: UpdateClientRequest
      description: Client update request model
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
    ISASummaryResponse:
      type: object
      properties:
        average_metrics:
          type: object
          properties:
            initial_deposit:
              type: number
              example: 4250.5
            monthly_deposit:
              type: number
              example: 325.75
            interest_rate:
              type: number
              example: 4.25
            age:
              type: number
              example: 34.5
            income:
              type: number
              example: 45000
            term:
              type: number
              example: 3.2
            risk_level:
              type: number
              example: 2.8
        customer_types:
          type: object
          properties:
            first_time:
              type: number
              example: 68.5
            transfer:
              type: number
              example: 31.5
        isa_types:
          type: object
          properties:
            cash_isa:
              type: number
              example: 65.2
            stocks_isa:
              type: number
              example: 34.8
        popular_metrics:
          type: object
          properties:
            most_popular_provider:
              type: string
              example: Moneybox
            most_popular_interest_rate:
              type: string
              example: 4.25%
            most_common_initial_deposit:
              type: string
              example: £4,000
            most_common_monthly_deposit:
              type: string
              example: £300
            most_popular_isa_type:
              type: string
              example: Cash ISA
            most_popular_age_group:
              type: string
              example: 25-34
            most_popular_income:
              type: string
              example: £30k-£50k
            most_popular_term:
              type: string
              example: 3 years
            biggest_gainer:
              type: string
              example: Moneybox (+2.3%)
            biggest_loser:
              type: string
              example: Halifax (-1.5%)
    TradingTrendsResponse:
      type: object
      properties:
        timeframe:
          type: object
          properties:
            start_time:
              type: string
              format: date-time
            end_time:
              type: string
              format: date-time
        total_instruments:
          type: integer
          example: 42
        trending_instruments:
          type: array
          items:
            type: object
            properties:
              instrument:
                type: string
                example: EURUSD
              trending_score:
                type: number
                example: 87.5
              avg_lot_size:
                type: number
                example: 0.85
              buy_percentage:
                type: number
                example: 58.3
              sell_percentage:
                type: number
                example: 41.7
              hours_since_last_trade:
                type: number
                example: 0.4
              volume_trend:
                type: number
                example: 15.2
              trending_status:
                type: string
                example: highly_trending
              score_components:
                type: object
                properties:
                  volume_score:
                    type: number
                    example: 36.4
                  recency_score:
                    type: number
                    example: 33.2
                  trend_score:
                    type: number
                    example: 17.9
        timestamp_utc:
          type: string
          format: date-time
    PredictiveSignalsResponse:
      type: object
      properties:
        instrument:
          type: string
          example: GBPUSD
        total_trades:
          type: integer
          example: 1238
        predictive_analysis:
          type: object
          properties:
            daily_trend:
              type: object
              properties:
                trend:
                  type: string
                  example: trending_upwards
                volume_trend:
                  type: string
                  example: trending_upwards
                momentum:
                  type: string
                  example: neutral
                direction:
                  type: string
                  example: trending_upwards
                direction_value:
                  type: number
                  example: 0.65
            weekly_trend:
              type: object
              properties:
                trend:
                  type: string
                  example: trending_upwards
                volume_trend:
                  type: string
                  example: neutral
                momentum:
                  type: string
                  example: trending_upwards
                direction:
                  type: string
                  example: trending_upwards
                direction_value:
                  type: number
                  example: 0.58
            monthly_trend:
              type: object
              properties:
                trend:
                  type: string
                  example: neutral
                volume_trend:
                  type: string
                  example: neutral
                momentum:
                  type: string
                  example: neutral
                direction:
                  type: string
                  example: neutral
                direction_value:
                  type: number
                  example: 0.12
            signal:
              type: string
              example: moderate_buy
            confidence:
              type: number
              example: 72.5
        timestamp_utc:
          type: string
          format: date-time
    TradeFrequencyResponse:
      type: object
      properties:
        instrument:
          type: string
          example: EURUSD
        lookback_days:
          type: integer
          example: 30
        current_signals:
          type: object
          properties:
            trend:
              type: string
              example: increasing
            volatility:
              type: string
              example: normal
            current_ma_5:
              type: number
              example: 0.7623
            current_ma_20:
              type: number
              example: 0.7245
        hourly_patterns:
          type: array
          items:
            type: object
            properties:
              hour:
                type: integer
                example: 14
              avg_lot_size:
                type: number
                example: 0.95
              lot_size_std:
                type: number
                example: 0.25
        daily_patterns:
          type: array
          items:
            type: object
            properties:
              day:
                type: string
                example: Monday
              avg_lot_size:
                type: number
                example: 0.75
              lot_size_std:
                type: number
                example: 0.18
        timeframe:
          type: object
          properties:
            start_time:
              type: string
              format: date-time
            end_time:
              type: string
              format: date-time
        timestamp_utc:
          type: string
          format: date-time
    BrokerOpportunitiesResponse:
      type: object
      properties:
        broker_rankings:
          type: array
          items:
            type: object
            properties:
              broker:
                type: string
                example: IG Markets
              high_volatility_percentage:
                type: number
                example: 42.5
              short_timeframe_percentage:
                type: number
                example: 68.3
              low_experience_percentage:
                type: number
                example: 35.7
              valuable_trader_score:
                type: number
                example: 76.5
              top_volatile_instruments:
                type: object
                additionalProperties:
                  type: number
                example:
                  XAUUSD: 32.5
                  GBPJPY: 28.7
              top_timeframes:
                type: object
                additionalProperties:
                  type: number
                example:
                  M5: 22.5
                  M15: 35.8
              targeting_opportunities:
                type: array
                items:
                  type: object
                  properties:
                    instrument:
                      type: string
                      example: XAUUSD
                    timeframe:
                      type: string
                      example: M15
                    low_experience_percentage:
                      type: number
                      example: 45.7
                    average_lot_size:
                      type: number
                      example: 0.85
                    opportunity_score:
                      type: number
                      example: 82.5
        top_recommendations:
          type: array
          items:
            type: object
            properties:
              broker:
                type: string
                example: IG Markets
              recommendation:
                type: string
                example: >-
                  Target traders trading XAUUSD on M15 timeframe as they have a
                  high propensity to become valuable traders for your broker.
              opportunity_score:
                type: number
                example: 82.5
              average_lot_size:
                type: number
                example: 0.85
        timestamp_utc:
          type: string
          format: date-time
    TrendingPairsResponse:
      type: object
      properties:
        timeframe:
          type: object
          properties:
            start_time:
              type: string
              format: date-time
            end_time:
              type: string
              format: date-time
        total_instruments:
          type: integer
          example: 8
        total_trades:
          type: integer
          example: 2354
        trending_instruments:
          type: array
          items:
            type: object
            properties:
              instrument:
                type: string
                example: EURUSD
              trending_score:
                type: number
                example: 78.5
              avg_lot_size:
                type: number
                example: 0.85
              buy_percentage:
                type: number
                example: 52.3
              sell_percentage:
                type: number
                example: 47.7
              hours_since_last_trade:
                type: number
                example: 0.28
              volume_trend:
                type: number
                example: 14.5
              trending_status:
                type: string
                example: highly_trending
              score_components:
                type: object
                properties:
                  volume_score:
                    type: number
                    example: 35.2
                  recency_score:
                    type: number
                    example: 32.8
                  trend_score:
                    type: number
                    example: 10.5
        timestamp_utc:
          type: string
          format: date-time
    PairBreakdownResponse:
      type: object
      properties:
        pair_stats:
          type: array
          items:
            type: object
            properties:
              pair:
                type: string
                example: EURUSD
              percentage:
                type: number
                example: 32.5
              average_lot_size:
                type: number
                example: 0.85
              buy_percentage:
                type: number
                example: 52.3
              sell_percentage:
                type: number
                example: 47.7
              experience_distribution:
                type: object
                additionalProperties:
                  type: number
              broker_distribution:
                type: object
                additionalProperties:
                  type: number
              timeframe_distribution:
                type: object
                additionalProperties:
                  type: number
        timestamp_utc:
          type: string
          format: date-time
    BrokerBreakdownResponse:
      type: object
      properties:
        data:
          type: array
          items:
            type: object
            properties:
              broker:
                type: string
                example: IG Markets
              percentage:
                type: number
                example: 22.5
              trader_count:
                type: integer
                example: 4850
              average_trade_size:
                type: number
                example: 0.85
              average_trades_per_trader:
                type: number
                example: 32.5
              buy_percentage:
                type: number
                example: 52.3
              sell_percentage:
                type: number
                example: 47.7
              most_traded_instrument:
                type: string
                example: EURUSD
              experience_distribution:
                type: object
                properties:
                  beginner:
                    type: number
                    example: 32.5
                  intermediate:
                    type: number
                    example: 45.7
                  expert:
                    type: number
                    example: 21.8
        status:
          type: string
          example: success
        timestamp:
          type: string
          format: date-time
    BrokerResponse:
      type: object
      properties:
        broker:
          type: string
          example: IG Markets
        overall_metrics:
          type: object
          properties:
            avg_lot_size:
              type: number
              example: 0.85
            total_volume:
              type: number
              example: 125.75
            buy_percentage:
              type: number
              example: 52.3
            sell_percentage:
              type: number
              example: 47.7
            avg_account_balance:
              type: number
              example: 10000
            avg_risk_input:
              type: number
              example: 2.5
            avg_stop_loss:
              type: number
              example: 50
            avg_take_profit:
              type: number
              example: 150
            risk_reward_ratio:
              type: number
              example: 3
        experience_distribution:
          type: array
          items:
            type: object
            properties:
              level:
                type: string
                example: beginner
              percentage:
                type: number
                example: 32.5
              trader_count:
                type: integer
                example: 350
              total_volume:
                type: number
                example: 42.5
        timeframe_distribution:
          type: array
          items:
            type: object
            properties:
              timeframe:
                type: string
                example: H1
              percentage:
                type: number
                example: 42.7
              trader_count:
                type: integer
                example: 450
              total_volume:
                type: number
                example: 65.8
        instrument_distribution:
          type: array
          items:
            type: object
            properties:
              instrument:
                type: string
                example: EURUSD
              percentage:
                type: number
                example: 32.5
              trader_count:
                type: integer
                example: 350
              total_volume:
                type: number
                example: 42.5
        timestamp_utc:
          type: string
          format: date-time
    AllBrokersResponse:
      type: object
      properties:
        all_brokers:
          type: boolean
          example: true
        total_brokers:
          type: integer
          example: 5
        brokers:
          type: array
          items:
            $ref: '#/components/schemas/BrokerResponse'
        timestamp_utc:
          type: string
          format: date-time
    BrokerComparisonResponse:
      type: object
      properties:
        broker1:
          type: object
          properties:
            name:
              type: string
              example: IG Markets
            metrics:
              type: object
              properties:
                total_trades:
                  type: integer
                  example: 1250
                buy_percentage:
                  type: number
                  example: 52.3
                sell_percentage:
                  type: number
                  example: 47.7
                average_lot_size:
                  type: number
                  example: 0.85
                average_stop_loss:
                  type: number
                  example: 50
                average_take_profit:
                  type: number
                  example: 150
                average_risk:
                  type: number
                  example: 2.5
                average_balance:
                  type: number
                  example: 10000
                risk_reward_ratio:
                  type: number
                  example: 3
                experience_distribution:
                  type: object
                  additionalProperties:
                    type: number
                preferred_pairs:
                  type: object
                  additionalProperties:
                    type: number
        broker2:
          type: object
          properties:
            name:
              type: string
              example: Pepperstone
            metrics:
              type: object
              properties:
                total_trades:
                  type: integer
                  example: 980
                buy_percentage:
                  type: number
                  example: 48.5
                sell_percentage:
                  type: number
                  example: 51.5
                average_lot_size:
                  type: number
                  example: 0.75
                average_stop_loss:
                  type: number
                  example: 45
                average_take_profit:
                  type: number
                  example: 135
                average_risk:
                  type: number
                  example: 2.3
                average_balance:
                  type: number
                  example: 9500
                risk_reward_ratio:
                  type: number
                  example: 3
                experience_distribution:
                  type: object
                  additionalProperties:
                    type: number
                preferred_pairs:
                  type: object
                  additionalProperties:
                    type: number
        relative_performance:
          type: object
          properties:
            trade_count_ratio:
              type: number
              example: 1.28
            lot_size_ratio:
              type: number
              example: 1.13
            risk_reward_ratio_difference:
              type: number
              example: 0
        timestamp_utc:
          type: string
          format: date-time
    MarketSentimentResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            overall_market_sentiment:
              type: string
              example: bullish
            sentiment_score:
              type: number
              example: 62.5
            sentiment_change:
              type: number
              example: 3.2
            instrument_sentiments:
              type: array
              items:
                type: object
                properties:
                  instrument:
                    type: string
                    example: EURUSD
                  sentiment:
                    type: string
                    example: bullish
                  sentiment_score:
                    type: number
                    example: 68.7
                  buy_percentage:
                    type: number
                    example: 58.3
                  sell_percentage:
                    type: number
                    example: 41.7
                  volume_trend:
                    type: string
                    example: increasing
                  sentiment_change:
                    type: number
                    example: 4.5
            experience_sentiments:
              type: object
              properties:
                beginner:
                  type: string
                  example: strongly_bullish
                intermediate:
                  type: string
                  example: bullish
                expert:
                  type: string
                  example: neutral
        status:
          type: string
          example: success
        timestamp:
          type: string
          format: date-time
        date_range:
          type: string
          example: 2024-02-24 to 2024-03-24
    PositionSizeResponse:
      type: object
      properties:
        total_instruments:
          type: integer
          example: 28
        market_metrics:
          type: object
          properties:
            average_lot_size:
              type: number
              example: 0.85
        instrument_positions:
          type: array
          items:
            type: object
            properties:
              instrument:
                type: string
                example: EURUSD
              volumes:
                type: object
                properties:
                  buy:
                    type: number
                    example: 2354.75
                  sell:
                    type: number
                    example: 1985.32
                  total:
                    type: number
                    example: 4340.07
              average_sizes:
                type: object
                properties:
                  buy:
                    type: number
                    example: 0.92
                  sell:
                    type: number
                    example: 0.78
                  overall:
                    type: number
                    example: 0.85
              market_metrics:
                type: object
                properties:
                  volume_percentage:
                    type: number
                    example: 24.5
                  direction_bias:
                    type: string
                    example: buy
                  size_trend:
                    type: string
                    example: increasing
        timestamp_utc:
          type: string
          format: date-time
    TimeframeBreakdownResponse:
      type: object
      properties:
        timeframe_distribution:
          type: array
          items:
            type: object
            properties:
              timeframe:
                type: string
                example: M5
              percentage:
                type: number
                example: 12.3
              success_rate:
                type: number
                example: 35.8
        experience_correlation:
          type: object
          properties:
            beginner:
              type: object
              properties:
                preferred:
                  type: string
                  example: M15
                success_rate:
                  type: number
                  example: 38.7
            intermediate:
              type: object
              properties:
                preferred:
                  type: string
                  example: H1
                success_rate:
                  type: number
                  example: 53.2
            expert:
              type: object
              properties:
                preferred:
                  type: string
                  example: H4
                success_rate:
                  type: number
                  example: 68.5
        timestamp_utc:
          type: string
          format: date-time
    DirectionBreakdownResponse:
      type: object
      properties:
        direction_distribution:
          type: object
          properties:
            buy:
              type: number
              example: 52.3
            sell:
              type: number
              example: 47.7
        instrument_breakdown:
          type: array
          items:
            type: object
            properties:
              instrument:
                type: string
                example: EURUSD
              buy_percentage:
                type: number
                example: 58.3
              sell_percentage:
                type: number
                example: 41.7
              success_rates:
                type: object
                properties:
                  buy:
                    type: number
                    example: 54.7
                  sell:
                    type: number
                    example: 48.2
        experience_correlation:
          type: object
          properties:
            beginner:
              type: object
              properties:
                buy_bias:
                  type: number
                  example: 62.5
                sell_bias:
                  type: number
                  example: 37.5
            intermediate:
              type: object
              properties:
                buy_bias:
                  type: number
                  example: 53.7
                sell_bias:
                  type: number
                  example: 46.3
            expert:
              type: object
              properties:
                buy_bias:
                  type: number
                  example: 48.2
                sell_bias:
                  type: number
                  example: 51.8
        timestamp_utc:
          type: string
          format: date-time
    InstrumentBreakdownResponse:
      type: object
      properties:
        instrument:
          type: string
          example: EURUSD
        segment_analysis:
          type: object
          properties:
            beginner:
              type: object
              properties:
                avg_lot_size:
                  type: number
                  example: 0.45
                success_rate:
                  type: number
                  example: 38.7
                avg_holding_time:
                  type: string
                  example: 2h 15m
                preferred_timeframes:
                  type: object
                  properties:
                    M5:
                      type: number
                      example: 42.5
                    M15:
                      type: number
                      example: 31.8
                    H1:
                      type: number
                      example: 18.3
                    H4:
                      type: number
                      example: 5.7
                    D1:
                      type: number
                      example: 1.7
            intermediate:
              type: object
              properties:
                avg_lot_size:
                  type: number
                  example: 0.75
                success_rate:
                  type: number
                  example: 52.3
                avg_holding_time:
                  type: string
                  example: 4h 32m
                preferred_timeframes:
                  type: object
                  properties:
                    M5:
                      type: number
                      example: 12.5
                    M15:
                      type: number
                      example: 28.7
                    H1:
                      type: number
                      example: 42.5
                    H4:
                      type: number
                      example: 12.8
                    D1:
                      type: number
                      example: 3.5
            expert:
              type: object
              properties:
                avg_lot_size:
                  type: number
                  example: 1.25
                success_rate:
                  type: number
                  example: 68.7
                avg_holding_time:
                  type: string
                  example: 9h 45m
                preferred_timeframes:
                  type: object
                  properties:
                    M5:
                      type: number
                      example: 5.3
                    M15:
                      type: number
                      example: 15.7
                    H1:
                      type: number
                      example: 38.5
                    H4:
                      type: number
                      example: 25.8
                    D1:
                      type: number
                      example: 14.7
        timestamp_utc:
          type: string
          format: date-time
    ExperienceBreakdownResponse:
      type: object
      properties:
        data:
          type: array
          items:
            type: object
            properties:
              experience_level:
                type: string
                example: beginner
              position_metrics:
                type: object
                properties:
                  buy_percentage:
                    type: number
                    example: 62.5
                  sell_percentage:
                    type: number
                    example: 37.5
              trading_metrics:
                type: object
                properties:
                  average_lot_size:
                    type: number
                    example: 0.45
                  average_stop_loss:
                    type: number
                    example: 25.3
                  average_take_profit:
                    type: number
                    example: 42.7
                  average_risk_input:
                    type: number
                    example: 2.5
                  risk_reward_ratio:
                    type: number
                    example: 1.68
              broker_distribution:
                type: object
                properties:
                  IG Markets:
                    type: number
                    example: 32.5
                  Pepperstone:
                    type: number
                    example: 28.7
                  XTB:
                    type: number
                    example: 18.5
        timestamp_utc:
          type: string
          format: date-time
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
    QueryApiKeyAuth:
      type: apiKey
      in: query
      name: api_key
servers:
  - url: https://api.tfe.ai
    description: Production server
tags:
  - name: ISA Analytics
    description: >-
      # ISA Analytics


      The ISA Analytics module provides tools for calculating and analyzing
      Individual Savings Account (ISA) data. This documentation covers the
      endpoints, parameters, and response formats for working with ISA data
      through the TFE API.


      ## Available Endpoints


      - [Summary & Diagnostics](#summary--diagnostics)

      - [Breakdown Analysis](#breakdown-analysis)

      - [Trends & Insights](#trends--insights)

      - [Recommendations](#recommendations)

      - [Summary Metrics](#/tag/ISA-Analytics%2FSummary)


      ## Key Features


      - Analyze ISA data across different providers and demographics

      - Compare performance metrics by age groups and income brackets

      - Track trends over different time periods

      - Generate provider recommendations

      - Evaluate transfer and deposit patterns


      ## Endpoint Details


      ### Summary & Diagnostics


      Get overall statistics and diagnostic information about ISA data.


      ```

      GET /isa/summary

      ```


      This endpoint provides a comprehensive summary of ISA data including most
      popular providers, calculator types, age groups, average deposits, and
      other key metrics.


      ### Breakdown Analysis


      Analyze ISA data across different segments and categories.


      ```

      # Provider Analysis

      GET /isa/bank-breakdown

      GET /isa/bank-breakdown/{start_date}/{end_date}

      GET /isa/term-breakdown

      GET /isa/term-breakdown/{start_date}/{end_date}

      GET /isa/inflow-breakdown

      GET /isa/inflow-breakdown/{start_date}/{end_date}


      # Demographic Analysis

      GET /isa/age-breakdown

      GET /isa/age-breakdown/{start_date}/{end_date}

      GET /isa/income-breakdown

      GET /isa/income-breakdown/{start_date}/{end_date}


      # Behavioral Analysis

      GET /isa/risk-breakdown

      GET /isa/risk-breakdown/{start_date}/{end_date}

      GET /isa/isa-type

      GET /isa/isa-type/{start_date}/{end_date}

      ```


      Key parameters:

      - provider: Filter by provider name

      - start_date: Custom start date in DD-MM-YY format

      - end_date: Custom end date in DD-MM-YY format


      ### Trends & Insights


      Analyze trends over time and get targeted insights.


      ```

      GET /isa/trends

      GET /isa/trends/{start_date}/{end_date}

      ```


      Key parameters:

      - start_date: Custom start date in DD-MM-YY format

      - end_date: Custom end date in DD-MM-YY format


      ### Recommendations


      Get personalized provider recommendations.


      ```

      GET /isa/recommendations/{provider}

      ```


      Key parameters:

      - provider: Provider name to get recommendations for


      ### Summary Metrics


      Endpoints for specific statistical metrics:


      ```

      GET /isa/average-final-amount

      GET /isa/average-final-amount/{start_date}

      GET /isa/average-growth-amount

      GET /isa/average-growth-amount/{start_date}

      GET /isa/average-deposit-transfer

      GET /isa/average-deposit-transfer/{start_date}

      GET /isa/average-final-amount-transfer

      GET /isa/average-final-amount-transfer/{start_date}

      GET /isa/most-popular-years

      GET /isa/most-popular-years/{start_date}

      GET /isa/average-years

      GET /isa/average-years/{start_date}

      GET /isa/average-interest-rate

      GET /isa/average-interest-rate/{start_date}

      ```


      Key parameters:

      - start_date: Custom start date in DD-MM-YY format

      - period: Optional time period filter (e.g., '7d', '30d', '90d', '1y')


      ## Data Analysis


      The ISA Analytics API processes data from BigQuery tables and provides
      statistical analysis including:


      - Most popular providers, age groups, calculator types

      - Average deposit and growth amounts

      - Transfer vs. non-transfer comparisons

      - Interest rate trends

      - Term duration analysis

      - Income bracket distributions


      ## Getting Started


      For a quick introduction to using the TFE API, see the [Quick Start
      Guide](#/tag/API-Documentation%2FQuick-Start-Guide).


      For details on authentication and security, see the [Security
      Documentation](#/tag/Authentication%2FSecurity).


      For frequently asked questions about the API, see the
      [FAQ](#/tag/API-Documentation%2FFAQ).


      ## Analytics Modules


      ### [Demographic Analysis](#/tag/ISA-Analytics%2FDemographic)


      Understand your ISA customer demographics with detailed breakdowns by:

      - Age groups

      - Income levels

      - Geographic distribution


      ### [Behavioral Analysis](#/tag/ISA-Analytics%2FBehavioral)


      Analyze customer investment behaviors:

      - Risk profiles

      - ISA types

      - Investment choices

      - Savings behavior


      ### [Provider Analysis](#/tag/ISA-Analytics%2FProvider)


      Compare providers and performance:

      - Provider market share

      - Performance metrics

      - Term preferences

      - Inflow patterns

      - Provider comparisons

      - Recommendation engine


      ### [Summary Metrics](#/tag/ISA-Analytics%2FSummary)


      Key metrics and statistics:

      - Average amounts and values

      - Most popular choices

      - Growth metrics

      - Performance indicators 
    x-displayName: ISA Analytics
  - name: Trading Analytics
    description: >-
      # Trading Analytics


      The Trading Analytics module provides tools for analyzing trading
      behavior, market trends, broker performance, and trader demographics. This
      documentation covers the endpoints, parameters, and response formats for
      working with trading data through the API.


      ## Available Endpoints


      - [Market Analysis](#market-analysis)

      - [Trader Analytics](#trader-analytics)

      - [Broker Insights](#broker-insights)

      - [Summary Metrics](#summary-metrics)


      ## Key Features


      - Analyze market trends and trading signals across instruments

      - Examine trader behavior patterns and preferences

      - Evaluate broker performance and competitive positioning

      - Access quick summary statistics on trading activity

      - Track sentiment and directional biases in the market


      ## Endpoint Details


      ### Market Analysis


      Analyze market trends, trading signals, and instrument popularity.


      ```

      # Trend Analysis

      GET /trading/trends/monthly

      GET /trading/trends/daily

      GET /trading/trends/weekly

      GET /trading/trending-pairs


      # Market Sentiment

      GET /trading/market-sentiment


      # Trading Signals

      GET /trading/predictive-signals

      GET /trading/{instrument}/real-time-anomalies

      GET /trading/position-size

      GET /trading/trade-frequency/{instrument}

      GET /trading/pair-breakdown

      ```


      ### Trader Analytics


      Understand trader behavior patterns and preferences.


      ```

      GET /trading/experience-breakdown

      GET /trading/timeframe-breakdown

      GET /trading/direction-breakdown

      ```


      ### Broker Insights


      Analyze broker performance, preferences, and opportunities.


      ```

      GET /trading/broker-breakdown

      GET /trading/broker/{broker}

      GET /trading/broker-comparison/{broker1}/{broker2}

      GET /trading/broker-preferences

      GET /trading/broker-opportunities

      ```


      ### Summary Metrics


      Quick access to key statistics and most popular metrics.


      ```

      GET /trading/summary

      GET /trading/most-popular-trading-pair

      GET /trading/most-popular-currency

      GET /trading/most-popular-broker

      GET /trading/most-popular-experience-level

      GET /trading/most-popular-direction

      GET /trading/most-popular-timeframe

      ```


      ## Data Analysis


      The Trading Analytics API processes data from BigQuery tables and provides
      statistical analysis including:


      - Market trends and sentiment indicators

      - Trader behavior patterns across demographics

      - Broker performance and competitive intelligence

      - Popularity metrics for instruments, timeframes, and directions

      - Predictive signals and trading opportunities


      ## Getting Started


      For a quick introduction to using the API, see the [Quick Start
      Guide](#/tag/API-Documentation%2FQuick-Start-Guide).


      For details on authentication and security, see the [Security
      Documentation](#/tag/Authentication%2FSecurity).


      For frequently asked questions about the API, see the
      [FAQ](#/tag/API-Documentation%2FFAQ).


      ## Analytics Modules


      ### [Market Analysis](#/tag/Market-Analysis)


      Analyze market trends and trading signals:

      - Trend analysis for trading instruments

      - Market sentiment indicators

      - Predictive trading signals

      - Real-time anomaly detection

      - Position size analytics


      ### [Trader Analytics](#/tag/Trader-Analytics)


      Understand trader behavior patterns:

      - Experience level breakdown

      - Timeframe preferences

      - Directional biases

      - Demographic correlations


      ### [Broker Insights](#/tag/Broker-Insights)


      Evaluate broker performance:

      - Broker statistics and demographics

      - Competitive comparisons

      - Trader preferences by broker

      - Targeting opportunities


      ### [Summary Metrics](#/tag/Summary-Metrics)


      Quick access to key statistics:

      - Most popular instruments and pairs

      - Preferred brokers and platforms

      - Common experience levels

      - Dominant directions and timeframes 
    x-displayName: Trading Analytics
  - name: ISA Analytics/Behavioral
    description: >-
      # ISA Analytics: Behavioral Module


      This module provides analysis of ISA customer behavior patterns,
      including:


      - ISA type preferences and trends

      - Trending patterns and behavioral insights

      - Account holder behaviors

      - Average metrics and growth analysis

      - Most popular analysis and customer preferences


      ## Endpoints


      The Behavioral module includes the following endpoints:


      GET /isa/isa-type

      GET /isa/trends

      GET /isa/average-final-amount

      GET /isa/average-growth-amount

      GET /isa/average-deposit-transfer

      GET /isa/average-final-amount-transfer

      GET /isa/most-popular-years

      GET /isa/average-years

      GET /isa/average-interest-rate

      ```


      ### Risk Breakdown Response

      ```json

      {
        "timestamp": "2024-03-20T12:00:00Z",
        "data": {
          "date_range": "2024-02-24 to 2024-03-24",
          "total_risk_profiles": 3,
          "risk_statistics": [
            {
              "risk_level": "low",
              "percentage": 35.5,
              "average_initial_deposit": 4000.0,
              "average_monthly_deposit": 200.0,
              "average_interest_rate": 3.85,
              "average_final_amount": 12500.0,
              "most_common_provider": "Halifax",
              "most_common_isa_type": "Cash ISA",
              "most_common_age_group": "45-54",
              "provider_distribution": {
                "Halifax": 40.5,
                "Moneybox": 25.3,
                "Nutmeg": 15.7,
                "Vanguard": 10.8,
                "Other": 7.7
              }
            }
          ]
        }
      }

      ```


      ### ISA Type Breakdown Response

      ```json

      {
        "timestamp": "2024-03-20T12:00:00Z",
        "data": {
          "date_range": "2024-02-24 to 2024-03-24",
          "total_isa_types": 2,
          "isa_type_statistics": [
            {
              "isa_type": "Cash ISA",
              "percentage": 65.5,
              "average_initial_deposit": 4200.0,
              "average_monthly_deposit": 225.0,
              "average_interest_rate": 3.95,
              "average_final_amount": 13500.0,
              "most_common_provider": "Halifax",
              "most_common_age_group": "45-54",
              "provider_distribution": {
                "Halifax": 38.5,
                "Moneybox": 27.3,
                "Nutmeg": 16.7,
                "Vanguard": 10.8,
                "Other": 6.7
              }
            },
            {
              "isa_type": "Stocks & Shares ISA",
              "percentage": 34.5,
              "average_initial_deposit": 5200.0,
              "average_monthly_deposit": 345.0,
              "average_interest_rate": 0,
              "average_final_amount": 16500.0,
              "most_common_provider": "Vanguard",
              "most_common_age_group": "35-44",
              "provider_distribution": {
                "Vanguard": 42.5,
                "Nutmeg": 32.3,
                "Moneybox": 18.7,
                "Halifax": 4.8,
                "Other": 1.7
              }
            }
          ]
        }
      }

      ```


      ### Trends Response

      ```json

      {
        "status": "success",
        "timestamp": "2024-03-20T12:00:00Z",
        "data": {
          "period": "30d",
          "total_records": 1000,
          "most_popular_provider": "Bank A",
          "fastest_growing_provider": "Bank C",
          "most_popular_age_group": "25-34",
          "average_initial_deposit": 5000.0,
          "average_monthly_deposit": 300.0,
          "average_interest_rate": 3.5,
          "provider_trends": [
            {
              "provider": "Bank A",
              "growth_rate": 5.2,
              "customer_count": 300,
              "market_share": 30.0
            }
          ]
        }
      }

      ```


      ## ISA Type Analysis


      The ISA Type endpoint provides insights into customer preferences for
      different ISA products:


      - Cash ISA vs. Stocks & Shares ISA distribution

      - Lifetime ISA and Innovative Finance ISA adoption

      - ISA type preferences by demographic

      - Trends in ISA type selection over time


      ## Trends Analysis


      The Trends endpoint provides insights into changing ISA behaviors over
      time:


      - Provider popularity and growth trends 

      - Customer demographic changes

      - Investment pattern shifts

      - Behavioral metric evolution


      ## Average Metrics Analysis


      These endpoints provide average metrics for various aspects of ISA
      investments:


      - Average final ISA amounts (average-final-amount)

      - Average growth amounts and patterns (average-growth-amount)

      - Average deposit and transfer metrics (average-deposit-transfer,
      average-final-amount-transfer)

      - Average duration of ISA investments (average-years)

      - Average interest rates and yield analytics (average-interest-rate)


      ## Most Popular Analysis


      The Most Popular analysis endpoints provide insights into customer
      preferences:


      - Most popular investment timeframes (most-popular-years)


      ## Data Analysis


      The Behavioral Analysis API processes ISA calculator data to identify:


      - Most popular ISA types

      - Shifts in preference between Cash ISAs and Stocks & Shares ISAs

      - Key demographic factors influencing ISA type selection

      - Seasonal patterns in ISA product popularity

      - Trending behaviors and preferences


      ## Getting Started


      For a quick introduction to using the API, see the [Quick Start
      Guide](#/tag/API-Documentation%2FQuick-Start-Guide).


      For details on authentication and security, see the [Security
      Documentation](#/tag/Authentication%2FSecurity).


      For frequently asked questions about the API, see the
      [FAQ](#/tag/API-Documentation%2FFAQ).


      ## Related Topics


      - [ISA Analytics Overview](#/tag/ISA-Analytics)

      - [Demographic Analysis](#/tag/ISA-Analytics%2FDemographic)

      - [Provider Analysis](#/tag/ISA-Analytics%2FProvider)

      - [Summary Analysis](#/tag/ISA-Analytics%2FSummary)

      - [API Security](#/tag/Authentication%2FSecurity)

      - [Error Handling](#/tag/API-Documentation%2FError-Handling) 
    x-displayName: Behavioral
    x-parent: ISA Analytics
  - name: ISA Analytics/Demographic
    description: >-
      # ISA Analytics: Demographic Module


      This module provides analysis of ISA customer demographics, enabling
      detailed understanding of how different demographic segments interact with
      ISA products.


      ## Endpoints


      The Demographic module includes the following endpoints:


      ```

      GET /isa/age-breakdown

      GET /isa/age-breakdown/{start_date}/{end_date}

      GET /isa/income-breakdown

      GET /isa/income-breakdown/{start_date}/{end_date}

      ```


      ## Age Breakdown Analysis


      The Age Breakdown endpoint provides insights into ISA usage across age
      groups:


      - Distribution of ISA customers by age bracket

      - Age-specific performance metrics

      - Provider preferences by age group

      - ISA type selection patterns by age

      - Investment behavior differences across age groups


      ## Income Breakdown Analysis


      The Income Breakdown endpoint analyzes ISA usage across income brackets:


      - Distribution of ISA customers by income level

      - Income-specific performance metrics

      - Provider preferences by income bracket

      - ISA type selection patterns by income

      - Investment behavior differences across income levels


      ## Data Analysis


      The Demographic Analysis API processes ISA calculator data to identify:


      - Key demographic trends in ISA adoption

      - Age and income patterns in investment behavior

      - Demographic-specific provider preferences

      - ISA type popularity across demographic segments

      - Investment amount variations by demographic


      ## Getting Started


      For a quick introduction to using the API, see the [Quick Start
      Guide](#/tag/API-Documentation%2FQuick-Start-Guide).


      For details on authentication and security, see the [Security
      Documentation](#/tag/Authentication%2FSecurity).


      For frequently asked questions about the API, see the
      [FAQ](#/tag/API-Documentation%2FFAQ).


      ## Related Topics


      - [ISA Analytics Overview](#/tag/ISA-Analytics)

      - [Behavioral Analysis](#/tag/ISA-Analytics%2FBehavioral)

      - [Provider Analysis](#/tag/ISA-Analytics%2FProvider)

      - [Summary Analysis](#/tag/ISA-Analytics%2FSummary)

      - [API Security](#/tag/Authentication%2FSecurity)

      - [Error Handling](#/tag/API-Documentation%2FError-Handling)


      ## Response Schemas


      ### Age Breakdown Response

      ```json

      {
        "timestamp": "2024-03-20T12:00:00Z",
        "data": {
          "date_range": "2024-02-24 to 2024-03-24",
          "total_age_groups": 5,
          "age_statistics": [
            {
              "age_group": "25-34",
              "percentage": 38.7,
              "average_initial_deposit": 4250.5,
              "average_monthly_deposit": 325.75,
              "average_interest_rate": 4.25,
              "average_annual_income": 45000,
              "most_common_provider": "Moneybox",
              "most_common_isa_type": "Cash ISA",
              "most_common_income": "£30k-£50k",
              "provider_distribution": {
                "Moneybox": 28.5,
                "Nutmeg": 22.3,
                "Vanguard": 19.7,
                "Halifax": 15.8,
                "Other": 13.7
              },
              "income_distribution": {
                "Under £20k": 8.5,
                "£20k-£30k": 32.3,
                "£30k-£50k": 43.1,
                "£50k-£75k": 12.6,
                "Over £75k": 3.5
              }
            }
          ]
        }
      }

      ```


      ### Income Breakdown Response

      ```json

      {
        "timestamp": "2024-03-20T12:00:00Z",
        "data": {
          "date_range": "2024-02-24 to 2024-03-24",
          "total_income_groups": 5,
          "income_statistics": [
            {
              "income_group": "£30k-£50k",
              "percentage": 42.3,
              "average_initial_deposit": 4500.0,
              "average_monthly_deposit": 250.0,
              "average_interest_rate": 4.15,
              "average_final_amount": 15750.0,
              "most_common_provider": "Moneybox",
              "most_common_isa_type": "Cash ISA",
              "most_common_age_group": "25-34",
              "provider_distribution": {
                "Moneybox": 30.5,
                "Nutmeg": 25.3,
                "Vanguard": 20.7,
                "Halifax": 13.8,
                "Other": 9.7
              }
            }
          ]
        }
      }

      ```


      ### Risk Breakdown Response

      ```json

      {
        "timestamp": "2024-03-20T12:00:00Z",
        "data": {
          "date_range": "2024-02-24 to 2024-03-24",
          "total_risk_profiles": 3,
          "risk_statistics": [
            {
              "risk_level": "low",
              "percentage": 35.5,
              "average_initial_deposit": 4000.0,
              "average_monthly_deposit": 200.0,
              "average_interest_rate": 3.85,
              "average_final_amount": 12500.0,
              "most_common_provider": "Halifax",
              "most_common_isa_type": "Cash ISA",
              "most_common_age_group": "45-54",
              "provider_distribution": {
                "Halifax": 40.5,
                "Moneybox": 25.3,
                "Nutmeg": 15.7,
                "Vanguard": 10.8,
                "Other": 7.7
              }
            }
          ]
        }
      }

      ```


      ## Notes


      1. All endpoints support optional query parameters:
         - `provider`: Filter by specific provider name
         - `start_date`: Start date for analysis (DD-MM-YY format, e.g., "01-03-24")
         - `end_date`: End date for analysis (DD-MM-YY format, e.g., "15-03-24")

      2. Age groups are predefined as:
         - 18-24
         - 25-34
         - 35-44
         - 45-54
         - 55+

      3. Income groups are defined as:
         - Under £20k
         - £20k-£30k
         - £30k-£50k
         - £50k-£75k
         - Over £75k

      4. Risk profiles are categorized as:
         - Low
         - Medium
         - High

      5. Data is sourced from BigQuery tables and updated regularly. 
    x-displayName: Demographic
    x-parent: ISA Analytics
  - name: ISA Analytics/Provider
    description: >-
      # ISA Analytics: Provider Module


      This module provides analysis and comparison of ISA providers, enabling
      detailed evaluation of market share, performance metrics, and customer
      preferences across different providers.


      ## Endpoints


      The Provider module includes the following endpoints:


      ```

      GET /isa/bank-breakdown

      GET /isa/bank-breakdown/{start_date}/{end_date}

      GET /isa/term-breakdown

      GET /isa/term-breakdown/{start_date}/{end_date}

      GET /isa/inflow-breakdown

      GET /isa/inflow-breakdown/{start_date}/{end_date}

      GET /isa/risk-breakdown

      GET /isa/risk-breakdown/{start_date}/{end_date}

      GET /isa/recommendations/{provider}

      ```


      ## Provider Analysis


      The Provider module offers comprehensive insights into ISA providers:


      - Market share and provider adoption rates

      - Provider metrics and performance comparison

      - Term duration distribution by provider

      - Inflow and transfer patterns between providers

      - Risk profile distribution across providers

      - Provider recommendations and personalized insights


      ## Key Features


      ### Bank Breakdown Analysis


      The Bank Breakdown endpoints provide detailed analysis of provider market
      share and metrics:


      - Provider distribution and market share

      - Performance metrics by provider

      - Customer demographics by provider

      - ISA type adoption rates by provider


      ### Term Analysis


      The Term Breakdown endpoints analyze term duration preferences across
      providers:


      - Term length distribution by provider

      - Performance metrics by term duration

      - Provider specialization by term length

      - Customer preferences for different durations


      ### Inflow Analysis


      The Inflow Breakdown endpoints track customer movement between providers:


      - Provider transition matrix

      - Retention and acquisition rates

      - Average value metrics for transfers

      - Market share change analysis


      ### Risk Analysis


      The Risk Breakdown endpoints measure risk profile distribution by
      provider:


      - Risk level distribution by provider

      - Performance metrics by risk level

      - Provider specialization by risk profile

      - Customer risk tolerance patterns


      ### Recommendations


      The Recommendations endpoint provides personalized provider suggestions:


      - Provider comparison with current provider

      - Performance metric improvement potential

      - Personalized provider matches by profile

      - Optimization recommendations


      ## Getting Started


      For a quick introduction to using the API, see the [Quick Start
      Guide](#/tag/API-Documentation%2FQuick-Start-Guide).


      For details on authentication and security, see the [Security
      Documentation](#/tag/Authentication%2FSecurity).


      For frequently asked questions about the API, see the
      [FAQ](#/tag/API-Documentation%2FFAQ).


      ## Related Topics


      - [ISA Analytics Overview](#/tag/ISA-Analytics)

      - [Demographic Analysis](#/tag/ISA-Analytics%2FDemographic)

      - [Behavioral Analysis](#/tag/ISA-Analytics%2FBehavioral)

      - [Summary Analysis](#/tag/ISA-Analytics%2FSummary)

      - [API Security](#/tag/Authentication%2FSecurity)

      - [Error Handling](#/tag/API-Documentation%2FError-Handling)


      ## Response Schemas


      ### Bank Breakdown Response

      ```json

      {
        "status": "success",
        "message": "Bank breakdown retrieved successfully",
        "timestamp": "2024-03-20T12:00:00Z",
        "total_providers": 5,
        "provider_statistics": [
          {
            "provider": "Bank A",
            "total_records": 300,
            "average_age": 35,
            "risk_profile": {
              "low": 0.3,
              "medium": 0.5,
              "high": 0.2
            }
          }
        ]
      }

      ```


      ### Term Breakdown Response

      ```json

      {
        "timestamp": "2024-03-20T12:00:00Z",
        "data": {
          "date_range": "2024-02-24 to 2024-03-24",
          "total_term_groups": 4,
          "term_statistics": [
            {
              "term_years": "5 years",
              "percentage": 42.3,
              "average_initial_deposit": 4500.0,
              "average_monthly_deposit": 250.0,
              "average_interest_rate": 4.15,
              "average_final_amount": 15750.0,
              "most_common_provider": "Moneybox",
              "most_common_age_group": "25-34",
              "provider_distribution": {
                "Moneybox": 30.5,
                "Nutmeg": 25.3,
                "Vanguard": 20.7,
                "Halifax": 13.8,
                "Other": 9.7
              }
            }
          ]
        }
      }

      ```


      ### Inflow Breakdown Response

      ```json

      {
        "timestamp": "2024-03-20T12:00:00Z",
        "data": {
          "date_range": "2024-02-24 to 2024-03-24",
          "total_providers": 5,
          "inflow_statistics": [
            {
              "provider": "Moneybox",
              "percentage": 30.5,
              "average_initial_deposit": 4500.0,
              "average_monthly_deposit": 250.0,
              "average_interest_rate": 4.15,
              "average_final_amount": 15750.0,
              "most_common_age_group": "25-34",
              "most_common_term": "5 years"
            }
          ]
        }
      }

      ```


      ### Recommendations Response

      ```json

      {
        "status": "success",
        "timestamp": "2024-03-20T12:00:00Z",
        "data": {
          "provider": "Bank A",
          "provider_metrics": {
            "average_initial_deposit": 5000.0,
            "average_monthly_deposit": 250.0,
            "average_interest_rate": 3.5,
            "customer_count": 500
          },
          "demographics_analysis": {
            "age_distribution": {
              "25-34": 0.35,
              "35-44": 0.30,
              "45-54": 0.25,
              "55-64": 0.10
            },
            "age_insights": [
              {
                "age_group": "25-34",
                "status": "strong",
                "insight": "You're attracting 7.5% more 25-34 customers than the market average."
              }
            ]
          }
        }
      }

      ```


      ## Notes


      1. All endpoints support optional query parameters:
         - `provider`: Filter by specific provider
         - `start_date`: Start date for analysis (DD-MM-YY format)
         - `end_date`: End date for analysis (DD-MM-YY format)

      2. Provider metrics include:
         - Market share
         - Customer demographics
         - Transfer patterns
         - Performance indicators

      3. Term breakdown provides:
         - Distribution of term lengths
         - Average deposits by term
         - Interest rate analysis by term
         - Provider preferences by term

      4. Inflow analysis provides:
         - New customer acquisition metrics
         - Deposit patterns
         - Customer demographics for new accounts
         - Provider performance comparison

      5. Data is updated daily with real-time statistics for active endpoints. 
    x-displayName: Provider
    x-parent: ISA Analytics
  - name: ISA Analytics/Summary
    description: >-
      # ISA Analytics - Summary Metrics


      This section provides key statistical metrics and summary data for ISA
      investments, including averages, popular choices, and growth metrics.


      ## Endpoints


      ### General Summary

      - `GET /isa/summary` - Get comprehensive summary of ISA statistics

      - `GET /isa/trends/{period}` - Get trend analysis for specified period

      - `GET /isa/isa-type` - Get breakdown of ISA data by calculator type

      - `GET
      /isa/horizontal-insight/{age_group}/{current_provider}/{new_provider}/{interest_rate}/{years}/{annual_income}/{calculator_type}`
      - Get horizontal insights with specified parameters


      ### Average Value Metrics

      - `GET /isa/average-final-amount` - Get average final amount for ISAs

      - `GET /isa/average-final-amount/{start_date}` - Get average final amount
      for a specific date range

      - `GET /isa/average-growth-amount` - Get average growth amount for ISAs

      - `GET /isa/average-growth-amount/{start_date}` - Get average growth
      amount for a specific date range

      - `GET /isa/average-deposit-transfer` - Get average deposit amount for
      transfers

      - `GET /isa/average-deposit-transfer/{start_date}` - Get average deposit
      amount for transfers in a specific date range

      - `GET /isa/average-final-amount-transfer` - Get average final amount for
      transfers

      - `GET /isa/average-final-amount-transfer/{start_date}` - Get average
      final amount for transfers in a specific date range

      - `GET /isa/average-years` - Get average term in years

      - `GET /isa/average-years/{start_date}` - Get average term in years for a
      specific date range

      - `GET /isa/average-interest-rate` - Get average interest rate

      - `GET /isa/average-interest-rate/{start_date}` - Get average interest
      rate for a specific date range


      ### Most Popular Metrics

      - `GET /isa/most-popular-years` - Get most popular term in years

      - `GET /isa/most-popular-years/{start_date}` - Get most popular term in
      years for a specific date range


      ## Response Schemas


      ### Average Final Amount Response

      ```json

      {
        "timestamp": "2024-03-20T12:00:00Z",
        "data": {
          "average_final_amount": 15750.25,
          "sample_size": 1250,
          "min_value": 5000.00,
          "max_value": 50000.00,
          "median_value": 14500.00,
          "by_provider": {
            "Moneybox": 16750.50,
            "Nutmeg": 18500.75,
            "Halifax": 14250.25
          },
          "by_age_group": {
            "25-34": 14500.00,
            "35-44": 17500.50,
            "45-54": 18750.75
          }
        }
      }

      ```


      ### Most Popular Years Response

      ```json

      {
        "timestamp": "2024-03-20T12:00:00Z",
        "data": {
          "most_popular_years": "5 years",
          "percentage": 42.5,
          "runner_up": "3 years",
          "runner_up_percentage": 28.7,
          "by_provider": {
            "Moneybox": "5 years",
            "Nutmeg": "5 years",
            "Halifax": "3 years"
          },
          "by_age_group": {
            "25-34": "5 years",
            "35-44": "5 years",
            "45-54": "3 years"
          }
        }
      }

      ```


      ### Summary Response

      ```json

      {
        "status": "success",
        "timestamp": "2024-03-20T12:00:00Z",
        "average_metrics": {
          "initial_deposit": 4250.50,
          "monthly_deposit": 325.75,
          "interest_rate": 4.25,
          "age": 34.5,
          "income": 45000.00,
          "term": 3.2,
          "risk_level": 2.8
        },
        "customer_types": {
          "first_time": 68.5,
          "transfer": 31.5
        },
        "isa_types": {
          "cash_isa": 65.2,
          "stocks_isa": 34.8
        },
        "popular_metrics": {
          "most_popular_provider": "Moneybox",
          "most_popular_interest_rate": "4.25%",
          "most_common_initial_deposit": "£4,000",
          "most_common_monthly_deposit": "£300",
          "most_popular_isa_type": "Cash ISA",
          "most_popular_age_group": "25-34",
          "most_popular_income": "£30k-£50k",
          "most_popular_term": "3 years",
          "biggest_gainer": "Moneybox (+2.3%)",
          "biggest_loser": "Halifax (-1.5%)"
        }
      }

      ```


      ## Notes


      1. All endpoints support optional query parameters:
         - `provider`: Filter by specific provider
         - `start_date`: Start date for analysis (DD-MM-YY format)
         - `period`: Optional time period filter (e.g., '7d', '30d', '90d', '1y')

      2. Average metrics include:
         - Statistical calculations (mean, median, min, max)
         - Provider-specific averages
         - Age group-specific averages
         - Demographic segmentation

      3. Most popular metrics include:
         - Top preference for each metric
         - Runner-up preferences
         - Provider-specific popularities
         - Age group-specific popularities

      4. Data is updated daily with real-time statistics for active endpoints.


      ## Overview


      Summary metrics provide critical insights into:


      - Average investment behavior across customer segments

      - Most popular choices for key investment parameters

      - Performance metrics across different providers

      - Trend analysis for key metrics over time


      Our summary metrics APIs can help financial institutions understand market
      patterns and optimize product offerings.


      ## Key Features


      ### Average Value Analytics


      Analyze average values across different metrics:


      - Initial and monthly deposit patterns

      - Final amount and growth expectations

      - Term preferences and trends

      - Interest rate comparisons

      - Transfer patterns and behaviors


      ### Popularity Metrics


      Analyze most popular choices for different parameters:


      - Term preferences

      - Provider popularity

      - ISA type preferences

      - Initial and monthly deposit patterns

      - Age group distribution


      ## Getting Started


      To begin using the summary metrics endpoints:


      1. Review the [Quick Start
      Guide](#/tag/API-Documentation%2FQuick-Start-Guide) for authentication
      setup

      2. Explore the example requests and responses in the API reference

      3. Consider combining summary metrics with other categories for richer
      insights


      ## Common Questions


      For frequently asked questions about summary metrics, see our
      [FAQ](#/tag/API-Documentation%2FFAQ).


      ## Related Topics


      - [ISA Analytics Overview](#/tag/ISA-Analytics)

      - [Demographic Analysis](#/tag/ISA-Analytics%2FDemographic)

      - [Behavioral Analysis](#/tag/ISA-Analytics%2FBehavioral)

      - [Provider Analysis](#/tag/ISA-Analytics%2FProvider)

      - [API Security](#/tag/Authentication%2FSecurity)

      - [Error Handling](#/tag/API-Documentation%2FError-Handling) 
    x-displayName: Summary
    x-parent: ISA Analytics
  - name: Market Analysis
    description: Analysis of market trends, instruments, and trading signals
    x-displayName: Market Analysis
    x-parent: Trading Analytics
  - name: Trader Analytics
    description: Analysis of trader behavior and demographics
    x-displayName: Trader Analytics
    x-parent: Trading Analytics
  - name: Broker Insights
    description: Broker analysis, comparison, and performance metrics
    x-displayName: Broker Insights
    x-parent: Trading Analytics
  - name: Summary Metrics
    description: Overview statistics and most popular metrics
    x-displayName: Summary Metrics
    x-parent: Trading Analytics
  - name: API Documentation
    description: Documentation and guides for using the API
    x-displayName: API Documentation
    x-tagGroup: main
  - name: API Documentation/FAQ
    description: >-
      # Frequently Asked Questions


      ## General Questions


      ### What is the TFE API?

      The TFE API provides financial analytics tools and data services with
      bank-grade security. It enables businesses to access trading analytics,
      ISA investment data, and financial insights through a secure RESTful
      interface.


      ### How do I get access to the API?

      Email [hello@tfe.ai](mailto:hello@tfe.ai) to request API access. You'll
      need to provide company information, use case, and expected request
      volume.


      ### What programming languages can I use with the API?

      The API can be used with any programming language that supports HTTP
      requests. We provide example code in Python, JavaScript, Java, and Go.


      ## Authentication & Security


      ### How do I authenticate API requests?

      You can use API key authentication via header or query parameter. The API
      key must be included in every request either as a header (`X-API-Key`) or
      as a query parameter (`api_key`). See the [Security
      Documentation](#/tag/Authentication%2FSecurity) for details.


      ### How long do JWT tokens last?

      JWT tokens are valid for 60 minutes by default. After expiration, you'll
      need to request a new token.


      ### What should I do if my API key is compromised?

      Contact [security@tfe.ai](mailto:security@tfe.ai) immediately. We'll
      revoke the compromised key and issue a new one.


      ### Is the API compliant with banking regulations?

      Yes, the API is designed to meet financial industry standards including
      appropriate security and data protection measures.


      ## Usage & Limits


      ### What are the rate limits?

      - Standard tier: 120 requests per minute

      - Premium tier: Custom limits based on requirements

      - Sensitive endpoints (auth, admin): 20 requests per minute


      ### Can I increase my rate limits?

      Yes, enterprise clients can request customized rate limits. Contact your
      account manager for details.


      ### How do I handle rate limit errors?

      When you receive a 429 status code, implement exponential backoff in your
      client. Headers in the response provide information about remaining
      requests and reset time.


      ### What endpoints are available?

      The API provides two main modules:

      - ISA Analytics: Endpoints for analyzing ISA investment data

      - Trading Analytics: Endpoints for analyzing trading behavior and market
      data


      See the [API Reference](#/) for a complete list of endpoints and their
      functionality.


      ## Data & Processing


      ### How current is the data?

      ISA and trading data is updated regularly from our BigQuery database. Most
      endpoints support date range filtering so you can analyze specific time
      periods.


      ### How is sensitive data handled?

      Sensitive data is encrypted at rest and in transit. We implement
      field-level encryption for PII and financial data.


      ### What data formats are supported?

      The API returns data in JSON format. Response structures are consistent
      across endpoints with timestamp information included.


      ### Can I filter data by specific parameters?

      Yes, most endpoints support filtering by:

      - Provider/broker

      - Date ranges (start_date/end_date)

      - Specific instruments/pairs

      - Experience levels

      - Other relevant parameters


      ## Support & Troubleshooting


      ### How do I report bugs?

      Email [support@tfe.ai](mailto:support@tfe.ai) with a description of the
      issue, steps to reproduce, and relevant request details.


      ### Is there a status page for the API?

      Yes, you can check service status at
      [status.tfe.ai](https://status.tfe.ai).


      ### How do I get implementation help?

      For technical assistance, email [support@tfe.ai](mailto:support@tfe.ai) or
      schedule a consultation call with our integration team.


      ### Where can I find more documentation?

      - [Quick Start Guide](#/tag/API-Documentation%2FQuick-Start-Guide)

      - [ISA Analytics Overview](#/tag/ISA-Analytics)

      - [Trading Analytics Overview](#/tag/Trading-Analytics)

      - [Security Documentation](#/tag/Authentication%2FSecurity)

      - [Error Handling Guide](#/tag/API-Documentation%2FError-Handling)

      - [API Reference](#/) 
    x-displayName: FAQ
    x-parent: API Documentation
  - name: Authentication/Security
    description: >
      # API Security Features for TFE API


      ### Authentication Methods


      The TFE API uses API key authentication to secure all endpoints.


      ## Data Protection


      ### Rate Limiting


      Rate limiting protects the API from abuse and ensures fair usage across
      all clients.
    x-displayName: Security
    x-parent: Authentication
  - name: API Documentation/Error Handling
    description: >
      # Error Handling Guide for TFE API


      This document provides comprehensive information about handling errors
      when integrating with the TFE API.


      ## Understanding Error Responses


      All API errors follow a consistent format:


      ```json

      {
        "timestamp": "2023-06-20T15:45:32.123Z",
        "error": "error_code",
        "detail": "Human-readable error message"
      }

      ```


      Where:

      - `timestamp`: When the error occurred (UTC)

      - `error`: A machine-readable error code

      - `detail`: A human-readable explanation of what went wrong


      For validation errors, additional fields may be included:


      ```json

      {
        "timestamp": "2023-06-20T15:45:32.123Z",
        "error": "validation_error",
        "detail": "One or more validation errors occurred",
        "errors": [
          {
            "field": "name_of_field",
            "message": "Specific validation error message"
          }
        ]
      }

      ```


      ## HTTP Status Codes


      The API uses standard HTTP status codes to indicate the success or failure
      of a request:


      | Status Code | Description |

      |-------------|-------------|

      | 200 OK | The request succeeded |

      | 400 Bad Request | The request was malformed or invalid |

      | 401 Unauthorized | Authentication failed (missing or invalid API key) |

      | 404 Not Found | The requested resource doesn't exist or no data found |

      | 422 Unprocessable Entity | The request was well-formed but couldn't be
      processed (e.g., validation failed) |

      | 429 Too Many Requests | Rate limit exceeded |

      | 500 Internal Server Error | An unexpected error occurred on the server |

      | 503 Service Unavailable | The service is temporarily unavailable |


      ## Common Error Types


      ## Best Practices for Error Handling


      When integrating with the TFE API, follow these best practices for error
      handling:


      1. **Always check the HTTP status code** first to determine the general
      category of error

      2. **Parse the error response** to extract the specific error code and
      message

      3. **Implement retry logic with exponential backoff** for 429 and 5xx
      errors

      4. **Log detailed error information** including timestamps for
      troubleshooting

      5. **Don't retry 4xx errors** (except 429) without fixing the underlying
      issue

      6. **Handle rate limiting gracefully** by respecting the retry time

      7. **Provide clear error messages to your users** that explain what went
      wrong

      8. **Monitor error rates** to detect problems early
    x-displayName: Error Handling
    x-parent: API Documentation
  - name: API Documentation/Quick Start Guide
    description: >-
      # TFE API Quick Start Guide


      This guide will help you get started with the TFE API, covering the basics
      from authentication to making your first requests.


      ## Table of Contents

      1. [Overview](#overview)

      2. [Getting Access](#getting-access)

      3. [Authentication](#authentication)

      4. [Making Your First Request](#making-your-first-request)

      5. [Sample Code](#sample-code)

      6. [Next Steps](#next-steps)


      ## Overview


      The TFE API provides comprehensive data and analytics for:


      - ISA (Individual Savings Account) data and insights 

      - Trading analytics and trends

      - Financial behavior patterns


      The API is designed for financial institutions, fintech companies, and
      wealth management platforms that need reliable, secure access to financial
      analytics data.


      ## Getting Access


      ### Requesting an API Key


      1. **Email us**: Send a request to [hello@tfe.ai](mailto:hello@tfe.ai)
      with the following information:
         - Your company name
         - Contact information
         - Description of your use case
         - Expected request volume

      2. **Complete the onboarding**: Our team will review your request and send
      you:
         - An onboarding form
         - Security requirements
         - Terms of service

      3. **Receive your credentials**: Once approved, you'll receive:
         - A unique API key
         - Documentation for getting started
         - Support contact information

      ## Authentication


      ### API Key Authentication


      The primary method for authenticating with the API is using your API key.
      You can include it in requests in one of two ways:


      #### Option 1: Via HTTP Header (Recommended)


      ```

      X-API-Key: your-api-key-here

      ```


      #### Option 2: Via Query Parameter


      ```

      https://api.tfe.ai/isa/summary?api_key=your-api-key-here

      ```


      ## Making Your First Request


      Let's make a simple request to test your API key. The `/isa/summary`
      endpoint provides a high-level overview of ISA data.


      ### Request


      ```http

      GET /isa/summary

      Host: api.tfe.ai

      X-API-Key: your-api-key-here

      ```


      ### Response


      ```json

      {
        "timestamp": "2024-03-20T15:45:32.123Z",
        "data": {
          "most_popular_provider": "Moneybox",
          "most_popular_age_group": "25-34",
          "most_popular_calculator_type": "Standard ISA",
          "most_popular_annual_income": "£30,000 - £49,999",
          "average_initial_deposit": 5000.0,
          "average_monthly_deposit": 300.0,
          "average_final_amount": 15750.0,
          "average_growth_amount": 2450.0
        }
      }

      ```


      For trading data, you can use the `/trading/summary` endpoint:


      ```http

      GET /trading/summary

      Host: api.tfe.ai

      X-API-Key: your-api-key-here

      ```


      Response:


      ```json

      {
        "average_metrics": {
          "account_balance": 10000.0,
          "risk_input": 2.5,
          "lot_size": 0.25,
          "stop_loss": 50.0,
          "take_profit": 150.0
        },
        "most_popular": {
          "pair": "EURUSD",
          "broker": "IG",
          "experience_level": "Intermediate",
          "direction": "buy",
          "time_frame": "1h",
          "risk_mode": "percentage"
        },
        "timestamp_utc": "2024-03-20T15:45:32.123Z"
      }

      ```


      ## Sample Code


      ### Python


      ```python

      import requests


      API_KEY = "your-api-key-here"

      BASE_URL = "https://api.tfe.ai"


      def get_isa_summary():
          headers = {
              "X-API-Key": API_KEY
          }
          
          response = requests.get(f"{BASE_URL}/isa/summary", headers=headers)
          
          if response.status_code == 200:
              return response.json()
          else:
              print(f"Error: {response.status_code}")
              print(response.json())
              return None

      def get_trading_trends(start_date=None, end_date=None):
          headers = {
              "X-API-Key": API_KEY
          }
          
          params = {}
          if start_date:
              params["start_date"] = start_date
          if end_date:
              params["end_date"] = end_date
          
          response = requests.get(f"{BASE_URL}/trading/trends/monthly", headers=headers, params=params)
          
          if response.status_code == 200:
              return response.json()
          else:
              print(f"Error: {response.status_code}")
              print(response.json())
              return None

      # Example usage

      summary = get_isa_summary()

      if summary:
          print(f"Most popular provider: {summary['data']['most_popular_provider']}")
          print(f"Average initial deposit: £{summary['data']['average_initial_deposit']}")

      # Get trading trends for a specific date range

      trends = get_trading_trends(start_date="01-03-24", end_date="15-03-24")

      if trends:
          instruments = trends.get("trending_instruments", [])
          if instruments:
              print(f"Top trending instrument: {instruments[0]['instrument']}")
              print(f"Trending score: {instruments[0]['trending_score']}")
      ```


      ### JavaScript


      ```javascript

      const API_KEY = "your-api-key-here";

      const BASE_URL = "https://api.tfe.ai";


      async function getIsaSummary() {
        try {
          const response = await fetch(`${BASE_URL}/isa/summary`, {
            headers: {
              "X-API-Key": API_KEY
            }
          });
          
          if (!response.ok) {
            const error = await response.json();
            throw new Error(`API error: ${error.detail}`);
          }
          
          return await response.json();
        } catch (error) {
          console.error("Error fetching ISA summary:", error);
          return null;
        }
      }


      async function getTradingTrends(startDate = null, endDate = null) {
        try {
          const params = new URLSearchParams();
          if (startDate) params.append("start_date", startDate);
          if (endDate) params.append("end_date", endDate);
          
          const url = `${BASE_URL}/trading/trends/monthly${params.toString() ? '?' + params.toString() : ''}`;
          
          const response = await fetch(url, {
            headers: {
              "X-API-Key": API_KEY
            }
          });
          
          if (!response.ok) {
            const error = await response.json();
            throw new Error(`API error: ${error.detail}`);
          }
          
          return await response.json();
        } catch (error) {
          console.error("Error fetching trading trends:", error);
          return null;
        }
      }


      // Example usage

      getIsaSummary().then(summary => {
        if (summary) {
          console.log(`Most popular provider: ${summary.data.most_popular_provider}`);
          console.log(`Average initial deposit: £${summary.data.average_initial_deposit}`);
        }
      });


      // Get trading trends for a specific date range

      getTradingTrends("01-03-24", "15-03-24").then(trends => {
        if (trends && trends.trending_instruments && trends.trending_instruments.length > 0) {
          console.log(`Top trending instrument: ${trends.trending_instruments[0].instrument}`);
          console.log(`Trending score: ${trends.trending_instruments[0].trending_score}`);
        }
      });

      ```


      ## Next Steps


      Now that you've made your first API request, here are some next steps:


      1. **Explore the API documentation**:
         - [ISA Analytics Documentation](#/tag/ISA-Analytics)
         - [Trading Analytics Documentation](#/tag/Trading-Analytics)
         - [Full API Reference](#/)

      2. **Implement proper error handling**:
         - Check out our [Error Handling Guide](#/tag/API-Documentation%2FError-Handling)
         - Implement retry logic for rate limiting and server errors

      3. **Learn about API security**:
         - Review our [Security Documentation](#/tag/Authentication%2FSecurity)
         - Follow best practices for API key management

      4. **Build advanced integrations**:
         - Use date ranges and filtering to target specific data
         - Combine multiple endpoints for comprehensive analysis
         - Implement caching to optimize performance

      For further assistance, contact our support team at
      [support@tfe.ai](mailto:support@tfe.ai). 
    x-displayName: Quick Start Guide
    x-parent: API Documentation
  - name: Authentication
    description: >-
      # API Security Features for TFE API


      ## Table of Contents

      1. [Security Overview](#security-overview)

      2. [API Authentication](#api-authentication)

      3. [Data Protection](#data-protection)

      4. [Network Security](#network-security)

      5. [Request Protection](#request-protection)

      6. [Compliance & Certifications](#compliance--certifications)

      7. [Incident Response](#incident-response)

      8. [Audit & Monitoring](#audit--monitoring)

      9. [Error Codes & Responses](#error-codes--responses)

      10. [Getting Started](#getting-started)

      11. [FAQ](#faq)


      ## Security Overview


      The TFE API is built with bank-grade security in mind, incorporating
      multiple layers of protection:


      * **Authentication**: Robust API key and JWT token-based authentication

      * **Encryption**: TLS 1.3 for all data in transit and field-level
      encryption for sensitive data

      * **Data Handling**: Strict policies for sensitive financial data with
      automatic encryption

      * **Monitoring**: Comprehensive audit logging and intrusion detection

      * **Compliance**: Designed to meet financial industry regulatory
      requirements


      ### Security Architecture


      Our API is deployed on Google Cloud Run, which provides:


      * **Fully managed infrastructure**: Google manages patching and
      infrastructure security

      * **Automatic scaling**: Dynamic resource allocation to handle traffic
      fluctuations

      * **Private networking**: Services can be exposed only to private VPC
      networks

      * **Binary Authorization**: Ensures only trusted container images are
      deployed

      * **Security scans**: Automatic vulnerability scanning

      * **Managed TLS certificates**: Automatic certificate provisioning and
      renewal


      Our application layer implements additional security controls:


      * **Input validation**: All parameters are validated using Pydantic models

      * **Output sanitization**: Standardized response formats prevent data
      leakage

      * **Rate limiting**: Protection against abuse and DoS attacks

      * **Security headers**: Protection against common web vulnerabilities

      * **Sensitive data handling**: Automatic encryption of sensitive fields

      * **Token management**: JWT token revocation and expiration controls


      ## API Authentication


      ### Authentication Methods


      The TFE API uses API key authentication to secure all endpoints.


      ### API Key Authentication


      API keys are used to identify and authenticate client applications. Each
      API key is tied to a specific client and has specific permissions.


      You can include your API key in requests in one of two ways:


      #### Option 1: Via HTTP Header (Recommended)


      ```

      X-API-Key: your-api-key-here

      ```


      Example in Python:

      ```python

      import requests


      headers = {
          "X-API-Key": "your-api-key-here"
      }


      response = requests.get("https://api.tfe.ai/trading/summary",
      headers=headers)

      ```


      #### Option 2: Via Query Parameter


      ```

      https://api.tfe.ai/trading/summary?api_key=your-api-key-here

      ```


      Example in Python:

      ```python

      import requests


      params = {
          "api_key": "your-api-key-here"
      }


      response = requests.get("https://api.tfe.ai/trading/summary",
      params=params)

      ```


      ### API Key Security Guidelines


      1. **Keep your API key secure** - Do not share your API key or commit it
      to public repositories

      2. **Store keys in environment variables** - Never hardcode API keys in
      your application code

      3. **Use backend servers** - Make API calls from your server, not directly
      from client-side code

      4. **Implement key rotation** - Request a new API key periodically for
      enhanced security

      5. **Restrict key usage** - Only use your API key in approved applications


      ## Data Protection


      ### Data Encryption


      The TFE API implements multiple layers of encryption:


      1. **Transport Layer Security (TLS)** - All API requests must use HTTPS
      protocol

      2. **Data encryption at rest** - All stored data is encrypted using
      industry-standard encryption

      3. **Field-level encryption** - Sensitive fields like account details have
      additional encryption


      ### Data Handling Practices


      1. **Data minimization** - API responses include only necessary data

      2. **No sensitive data in URLs** - Query parameters never include
      sensitive information

      3. **Data retention policies** - Data is retained only as long as
      necessary for legitimate business purposes

      4. **Secure data disposal** - Data is securely deleted when no longer
      needed


      ### Data Classification


      We classify data into the following categories:


      * **Public**: Information that can be freely disclosed

      * **Internal**: Information for authenticated users only

      * **Sensitive**: Information requiring additional protection

      * **Restricted**: Highly sensitive information subject to strict access
      controls


      ### Data Handling


      * Data minimization principles are applied (we collect only what's
      necessary)

      * Anonymization and pseudonymization are applied where possible

      * Sensitive data is never exposed in logs or error messages

      * Custom JSON encoders ensure numeric data is handled safely


      ### PII Handling


      * Personal Identifiable Information (PII) is identified and protected

      * Our `SensitiveData` model automatically encrypts designated fields

      * PII is encrypted both in transit and at rest

      * Sensitive fields are automatically redacted in logs and error messages

      * Encryption/decryption occurs at the application level


      ### Data Retention


      * Transaction data is retained according to financial regulations

      * API access logs are retained for auditing purposes

      * Authentication logs are securely stored

      * Data retention periods are configurable based on client requirements


      ### Data Residency


      * Our primary data centers are located in the UK

      * All data processing occurs within UK jurisdiction

      * We comply with UK and EU data protection regulations

      * Data is stored in Google BigQuery with appropriate security controls


      ## Network Security


      ### TLS Configuration


      * TLS 1.2+ enforced for all API connections

      * Strong cipher suites with perfect forward secrecy

      * TLS certificates managed and rotated automatically by Google Cloud Run

      * HSTS enabled with a 1-year duration


      ### DDoS Protection


      * Google Cloud Armor provides protection against DDoS attacks

      * Automatic scaling to handle traffic spikes

      * Rate limiting at application level

      * Graceful degradation during traffic surges


      ### Firewall Rules


      * API can be restricted to specific networks (contact support to set up)

      * Only necessary ports are exposed (HTTPS/443)

      * All inbound traffic is filtered and monitored

      * VPC Service Controls available for enterprise clients


      ## Request Protection


      ### Rate Limiting


      Rate limiting protects the API from abuse and ensures fair usage across
      all clients.


      ### Rate Limit Structure


      - **Standard tier**: 120 requests per minute

      - **Premium tier**: Custom limits based on requirements

      - **Sensitive endpoints**: 20 requests per minute


      ### Rate Limit Headers


      Rate limit information is included in response headers:


      - **X-RateLimit-Limit**: Maximum number of requests allowed in the current
      time window

      - **X-RateLimit-Remaining**: Number of requests remaining in the current
      time window

      - **X-RateLimit-Reset**: Seconds until the rate limit resets


      ### Handling Rate Limits


      When you exceed your rate limit, the API returns a 429 (Too Many Requests)
      status code. Implement exponential backoff retry logic to handle these
      cases gracefully.


      Example in Python:

      ```python

      import requests

      import time

      import random


      def make_api_request_with_backoff(url, api_key, max_retries=5):
          headers = {"X-API-Key": api_key}
          
          for attempt in range(max_retries):
              response = requests.get(url, headers=headers)
              
              if response.status_code == 200:
                  return response.json()
                  
              if response.status_code == 429:
                  if attempt == max_retries - 1:
                      raise Exception("Rate limit exceeded after maximum retries")
                      
                  # Get retry time from headers or use exponential backoff
                  retry_after = int(response.headers.get('X-RateLimit-Reset', 1))
                  # Add jitter to prevent thundering herd
                  sleep_time = retry_after + (random.random() * 0.5)
                  print(f"Rate limited. Retrying after {sleep_time:.2f} seconds")
                  time.sleep(sleep_time)
                  continue
                  
              # Handle other errors
              response.raise_for_status()
              
          raise Exception("Request failed after maximum retries")

      ## Compliance & Certifications


      The TFE API is designed with security best practices that align with the
      following standards:


      * **GDPR**: For handling personal data of EU residents

      * **PSD2**: For payment services directives (where applicable)

      * **ISO 27001**: Information security management principles

      * **Financial Conduct Authority (FCA)**: Adherence to UK financial
      regulations


      ### Security Assessment


      * Regular penetration testing by independent security firms

      * Vulnerability scanning is performed weekly

      * Security practices are continuously reviewed and updated

      * Compliance with banking industry security standards


      ## Incident Response


      ### Security Incident Process


      In the event of a security incident:


      1. We will identify and contain the incident

      2. We will notify affected clients within 24 hours

      3. We will investigate the root cause

      4. We will remediate vulnerabilities

      5. We will provide post-incident reports to affected clients


      ### Reporting Security Issues


      If you discover a security vulnerability, please report it to
      [security@tfe.ai](mailto:security@tfe.ai).


      ## Audit & Monitoring


      ### Request Auditing


      All API requests are logged with the following information:


      * Timestamp

      * Client ID

      * IP address

      * Requested endpoint

      * Response status code

      * Request ID (returned in the `X-Request-ID` header)

      * Request duration


      These logs are used for:


      * Security monitoring

      * Compliance auditing

      * Performance analysis

      * Troubleshooting

      * Threat detection


      ### Access Control Audit


      All authentication events are logged:


      * Successful and failed authentication attempts

      * API key usage

      * Token generation and usage

      * Access to sensitive endpoints

      * Administrative actions


      ### Monitoring System


      Our monitoring system provides:


      * Real-time alerting for suspicious activities

      * Detection of unusual request patterns

      * Continuous monitoring of security controls

      * Automated response to potential threats

      * Anomaly detection using machine learning


      ## Error Codes & Responses


      The API uses standard HTTP status codes and a consistent error response
      format:


      ### HTTP Status Codes


      * `200 OK`: Request successful

      * `400 Bad Request`: Invalid request parameters

      * `401 Unauthorized`: Authentication failed

      * `403 Forbidden`: Insufficient permissions

      * `404 Not Found`: Resource not found

      * `429 Too Many Requests`: Rate limit exceeded

      * `500 Internal Server Error`: Server-side error


      ### Error Response Format


      ```json

      {
        "timestamp": "2023-07-01T14:30:00Z",
        "error": "Error type",
        "detail": "Human-readable error message"
      }

      ```


      ## Getting Started


      ### Environments


      The API provides two environments:


      1. **Sandbox**: For development and testing
         * Less strict rate limits
         * Test data available
         * Uses test API keys

      2. **Production**: For live applications
         * Full security controls enforced
         * Real data access
         * Requires production API keys

      ### Testing the API


      To get started with the API:


      1. Request an API key from [hello@tfe.ai](mailto:hello@tfe.ai)

      2. Use the API base URL for all requests

      3. Test with a simple endpoint to verify connectivity

      4. Implement proper key management in your systems


      ### API Versioning


      We use a date-based versioning approach:


      * APIs are versioned as `/v{YYYY-MM-DD}/endpoint`

      * We guarantee backward compatibility 

      * At least 6 months' notice is provided before deprecating an API version


      ## FAQ


      **Q: How do I report a security issue?**

      A: Email [security@tfe.ai](mailto:security@tfe.ai) with details of the
      vulnerability.


      **Q: Can I customize rate limits?**

      A: Yes, enterprise clients can request custom rate limits based on their
      needs.


      **Q: What happens if my API key is compromised?**

      A: Contact us immediately at [security@tfe.ai](mailto:security@tfe.ai). We
      will revoke the compromised key and issue a new one.


      **Q: Do you support mutual TLS (mTLS)?**

      A: For banking clients requiring additional security, we offer mutual TLS
      authentication. Contact your account manager to set this up.


      **Q: What is your uptime target?**

      A: We aim for 99.95% uptime for our production API to meet bank-level
      availability requirements.


      **Q: How do you handle data residency requirements?**

      A: Our primary data centers are in the UK. For clients with specific
      residency requirements, we can discuss options for data localization.


      **Q: How do you handle regulatory reporting for banking clients?**

      A: We provide comprehensive audit logs that can be exported for regulatory
      reporting requirements. Contact us to discuss specific reporting needs.


      **Q: Do you support FIDO2/WebAuthn for authentication?**

      A: For admin interfaces, we support FIDO2/WebAuthn as a second factor.
      This is not available for API authentication.


      **Q: What encryption standards do you use for sensitive data?**

      A: We use AES-256 for encrypting sensitive data at rest, with PBKDF2 for
      key derivation.


      **Q: How do you ensure your security keeps up with banking standards?**

      A: We maintain regular security assessments, conduct penetration testing,
      and follow evolving security standards in the banking industry. Our
      security team monitors for emerging threats and vulnerabilities. 
    x-displayName: Authentication
    x-tagGroup: main
x-tagGroups:
  - name: ISA Analytics
    tags:
      - ISA Analytics/Behavioral
      - ISA Analytics/Demographic
      - ISA Analytics/Provider
      - ISA Analytics/Summary
  - name: Trading Analytics
    tags:
      - Market Analysis
      - Trader Analytics
      - Broker Insights
      - Summary Metrics
  - name: API Documentation
    tags:
      - API Documentation/FAQ
      - API Documentation/Error Handling
      - API Documentation/Quick Start Guide
  - name: Authentication
    tags:
      - Authentication
      - Authentication/Security
security:
  - ApiKeyAuth: []
  - QueryApiKeyAuth: []
