> ## Documentation Index
> Fetch the complete documentation index at: https://finance.chiefpriest.design/llms.txt
> Use this file to discover all available pages before exploring further.

# Stock Price History

> Get historical stock price data and trading volume

## Overview

Retrieve comprehensive historical stock price data including open, high, low, close prices, and trading volume. This endpoint provides daily time series data essential for technical analysis, backtesting strategies, and understanding price trends.

<Info>
  Historical price data is fundamental for technical analysis, pattern recognition, and quantitative trading strategies. The data includes adjusted prices for dividends and stock splits.
</Info>

## Parameters

<ParamField path="symbol" type="string" required>
  Stock ticker symbol (e.g., AAPL, MSFT, GOOGL, TSLA)
</ParamField>

<ParamField query="outputsize" type="string" default="compact">
  Data range: "compact" (latest 100 data points) or "full" (up to 20 years)
</ParamField>

<ParamField query="from" type="string">
  Start date in YYYY-MM-DD format (optional, for custom date range)
</ParamField>

<ParamField query="to" type="string">
  End date in YYYY-MM-DD format (optional, for custom date range)
</ParamField>

## Response

<ResponseField name="symbol" type="string">
  The stock ticker symbol
</ResponseField>

<ResponseField name="historical" type="array">
  Array of historical price data (most recent first)

  <Expandable title="Historical Data Object">
    <ResponseField name="date" type="string">
      Trading date in YYYY-MM-DD format
    </ResponseField>

    <ResponseField name="open" type="number">
      Opening price
    </ResponseField>

    <ResponseField name="high" type="number">
      Highest price during the day
    </ResponseField>

    <ResponseField name="low" type="number">
      Lowest price during the day
    </ResponseField>

    <ResponseField name="close" type="number">
      Closing price
    </ResponseField>

    <ResponseField name="adjClose" type="number">
      Adjusted closing price (accounts for dividends/splits)
    </ResponseField>

    <ResponseField name="volume" type="number">
      Trading volume (number of shares)
    </ResponseField>

    <ResponseField name="unadjustedVolume" type="number">
      Unadjusted trading volume
    </ResponseField>

    <ResponseField name="change" type="number">
      Daily price change (close - open)
    </ResponseField>

    <ResponseField name="changePercent" type="number">
      Daily percentage change
    </ResponseField>

    <ResponseField name="vwap" type="number">
      Volume Weighted Average Price
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="outputsize" type="string">
  Data range returned
</ResponseField>

<ResponseField name="source" type="string">
  Data source identifier ("YFinance" or "FMP")
</ResponseField>

<ResponseField name="timestamp" type="string">
  ISO timestamp of the response
</ResponseField>

## Examples

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://stocks-dev.up.railway.app/api/v1/stock/AAPL/history?outputsize=compact"
  ```

  ```python Python theme={null}
  import requests
  import pandas as pd
  import matplotlib.pyplot as plt

  response = requests.get("https://stocks-dev.up.railway.app/api/v1/stock/AAPL/history")
  data = response.json()

  symbol = data['symbol']
  historical = data['historical']

  print(f"📈 Historical Data for {symbol} (Last {len(historical)} days)")
  print("=" * 60)

  # Convert to DataFrame for easy analysis
  df = pd.DataFrame(historical)
  df['date'] = pd.to_datetime(df['date'])
  df = df.sort_values('date')  # Sort chronologically

  # Recent performance
  recent = historical[:5]  # Last 5 days
  print("Recent Performance:")
  for day in recent:
      date = day['date']
      close = day['close']
      change_pct = day['changePercent']
      volume = day['volume']
      
      emoji = "🟢" if change_pct >= 0 else "🔴"
      vol_str = f"{volume/1e6:.1f}M" if volume >= 1e6 else f"{volume/1e3:.0f}K"
      
      print(f"  {date}: ${close:>7.2f} {emoji} {change_pct:>+5.2f}% | Vol: {vol_str}")

  # Calculate key statistics
  df['returns'] = df['adjClose'].pct_change()
  volatility = df['returns'].std() * (252 ** 0.5) * 100  # Annualized volatility
  avg_volume = df['volume'].mean()
  max_price = df['high'].max()
  min_price = df['low'].min()

  print(f"\n📊 Statistics (Last {len(historical)} days):")
  print(f"  Price Range: ${min_price:.2f} - ${max_price:.2f}")
  print(f"  Avg Volume: {avg_volume/1e6:.1f}M shares")
  print(f"  Volatility: {volatility:.1f}% (annualized)")

  # Simple moving averages
  if len(df) >= 20:
      df['sma_20'] = df['adjClose'].rolling(20).mean()
      current_price = df['adjClose'].iloc[-1]
      sma_20 = df['sma_20'].iloc[-1]
      
      print(f"  20-day SMA: ${sma_20:.2f}")
      print(f"  vs SMA: {((current_price - sma_20) / sma_20 * 100):+.1f}%")
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://stocks-dev.up.railway.app/api/v1/stock/AAPL/history');
  const data = await response.json();

  const symbol = data.symbol;
  const historical = data.historical;

  console.log(`📈 Historical Data for ${symbol} (Last ${historical.length} days)`);
  console.log("=".repeat(60));

  // Recent performance
  const recent = historical.slice(0, 5); // Last 5 days
  console.log("Recent Performance:");
  recent.forEach(day => {
      const date = day.date;
      const close = day.close;
      const changePct = day.changePercent;
      const volume = day.volume;
      
      const emoji = changePct >= 0 ? "🟢" : "🔴";
      const volStr = volume >= 1e6 ? `${(volume/1e6).toFixed(1)}M` : `${(volume/1e3).toFixed(0)}K`;
      
      console.log(`  ${date}: $${close.toFixed(2).padStart(7)} ${emoji} ${changePct >= 0 ? '+' : ''}${changePct.toFixed(2)}% | Vol: ${volStr}`);
  });

  // Calculate key statistics
  const prices = historical.map(d => d.adjClose);
  const volumes = historical.map(d => d.volume);
  const maxPrice = Math.max(...historical.map(d => d.high));
  const minPrice = Math.min(...historical.map(d => d.low));
  const avgVolume = volumes.reduce((a, b) => a + b, 0) / volumes.length;

  console.log(`\n📊 Statistics (Last ${historical.length} days):`);
  console.log(`  Price Range: $${minPrice.toFixed(2)} - $${maxPrice.toFixed(2)}`);
  console.log(`  Avg Volume: ${(avgVolume/1e6).toFixed(1)}M shares`);

  // Simple moving average
  if (historical.length >= 20) {
      const last20 = prices.slice(0, 20);
      const sma20 = last20.reduce((a, b) => a + b, 0) / last20.length;
      const currentPrice = prices[0];
      
      console.log(`  20-day SMA: $${sma20.toFixed(2)}`);
      console.log(`  vs SMA: ${((currentPrice - sma20) / sma20 * 100) >= 0 ? '+' : ''}${((currentPrice - sma20) / sma20 * 100).toFixed(1)}%`);
  }
  ```

  ```php PHP theme={null}
  <?php
  $response = file_get_contents('https://stocks-dev.up.railway.app/api/v1/stock/AAPL/history');
  $data = json_decode($response, true);

  $symbol = $data['symbol'];
  $historical = $data['historical'];

  echo "📈 Historical Data for $symbol (Last " . count($historical) . " days)\n";
  echo str_repeat("=", 60) . "\n";

  // Recent performance
  $recent = array_slice($historical, 0, 5); // Last 5 days
  echo "Recent Performance:\n";
  foreach ($recent as $day) {
      $date = $day['date'];
      $close = $day['close'];
      $change_pct = $day['changePercent'];
      $volume = $day['volume'];
      
      $emoji = $change_pct >= 0 ? "🟢" : "🔴";
      $vol_str = $volume >= 1e6 ? number_format($volume/1e6, 1) . "M" : number_format($volume/1e3, 0) . "K";
      
      echo sprintf("  %s: $%7.2f %s %+5.2f%% | Vol: %s\n", 
          $date, $close, $emoji, $change_pct, $vol_str);
  }

  // Calculate key statistics
  $prices = array_column($historical, 'adjClose');
  $volumes = array_column($historical, 'volume');
  $highs = array_column($historical, 'high');
  $lows = array_column($historical, 'low');

  $max_price = max($highs);
  $min_price = min($lows);
  $avg_volume = array_sum($volumes) / count($volumes);

  echo "\n📊 Statistics (Last " . count($historical) . " days):\n";
  echo "  Price Range: $" . number_format($min_price, 2) . " - $" . number_format($max_price, 2) . "\n";
  echo "  Avg Volume: " . number_format($avg_volume/1e6, 1) . "M shares\n";

  // Simple moving average
  if (count($historical) >= 20) {
      $last_20 = array_slice($prices, 0, 20);
      $sma_20 = array_sum($last_20) / count($last_20);
      $current_price = $prices[0];
      
      echo "  20-day SMA: $" . number_format($sma_20, 2) . "\n";
      echo "  vs SMA: " . sprintf("%+.1f", (($current_price - $sma_20) / $sma_20 * 100)) . "%\n";
  }
  ?>
  ```
</CodeGroup>

## Response Example

```json theme={null}
{
  "symbol": "AAPL",
  "historical": [
    {
      "date": "2025-06-28",
      "open": 199.50,
      "high": 202.15,
      "low": 198.80,
      "close": 201.08,
      "adjClose": 201.08,
      "volume": 52147890,
      "unadjustedVolume": 52147890,
      "change": 1.58,
      "changePercent": 0.79,
      "vwap": 200.45
    },
    {
      "date": "2025-06-27",
      "open": 201.20,
      "high": 203.45,
      "low": 199.10,
      "close": 199.50,
      "adjClose": 199.50,
      "volume": 48235671,
      "unadjustedVolume": 48235671,
      "change": -1.70,
      "changePercent": -0.85,
      "vwap": 201.12
    },
    {
      "date": "2025-06-26",
      "open": 198.75,
      "high": 201.90,
      "low": 198.25,
      "close": 201.20,
      "adjClose": 201.20,
      "volume": 55892134,
      "unadjustedVolume": 55892134,
      "change": 2.45,
      "changePercent": 1.23,
      "vwap": 200.15
    }
  ],
  "outputsize": "compact",
  "source": "YFinance",
  "timestamp": "2025-06-28T21:00:15.123456"
}
```

## Understanding Historical Data

<AccordionGroup>
  <Accordion title="Price Data Types">
    **OHLC Data Explained:**

    * **Open**: First traded price of the day
    * **High**: Highest price during trading session
    * **Low**: Lowest price during trading session
    * **Close**: Last traded price of the day
    * **Adjusted Close**: Price adjusted for dividends and stock splits
  </Accordion>

  <Accordion title="Volume Analysis">
    **Volume Metrics:**

    * **Volume**: Number of shares traded
    * **VWAP**: Volume Weighted Average Price
    * **Volume Patterns**: High volume often confirms price movements
    * **Relative Volume**: Compare to average daily volume
  </Accordion>

  <Accordion title="Data Adjustments">
    **Corporate Actions:**

    * **Stock Splits**: Prices adjusted to maintain continuity
    * **Dividends**: Ex-dividend adjustments in historical prices
    * **Spin-offs**: Complex adjustments for corporate restructuring
    * **Rights Issues**: Adjustments for new share issuances
  </Accordion>
</AccordionGroup>

## Use Cases

<CardGroup cols={2}>
  <Card title="Technical Analysis" icon="chart-line">
    **Chart Patterns**

    * Support/resistance levels
    * Moving averages
    * Trend analysis
    * Pattern recognition
  </Card>

  <Card title="Backtesting" icon="clock">
    **Strategy Testing**

    * Historical performance
    * Risk metrics calculation
    * Strategy optimization
    * Performance attribution
  </Card>

  <Card title="Risk Management" icon="shield">
    **Volatility Analysis**

    * Historical volatility
    * Value at Risk (VaR)
    * Drawdown analysis
    * Correlation studies
  </Card>

  <Card title="Quantitative Analysis" icon="calculator">
    **Statistical Models**

    * Return distributions
    * Momentum indicators
    * Mean reversion tests
    * Factor analysis
  </Card>
</CardGroup>

## Technical Indicators

<Info>
  **Common Calculations:**

  * **Simple Moving Average**: Average price over N periods
  * **Volatility**: Standard deviation of returns
  * **RSI**: Relative Strength Index for momentum
  * **Bollinger Bands**: Price bands based on standard deviation
</Info>

<Tip>
  **Analysis Tips:**

  * Use adjusted prices for accurate calculations
  * Consider volume confirmation for price moves
  * Look for patterns in volume and price together
  * Account for market holidays and gaps
</Tip>

<Warning>
  **Data Considerations:**

  * Historical data may have survivorship bias
  * Corporate actions can affect calculations
  * Market hours and timezone considerations
  * Data quality varies by source and symbol
</Warning>

## Error Responses

<AccordionGroup>
  <Accordion title="Invalid Symbol (404)">
    ```json theme={null}
    {
      "error": "404: Failed to fetch historical data for INVALID"
    }
    ```
  </Accordion>

  <Accordion title="Invalid Date Range (400)">
    ```json theme={null}
    {
      "error": "Invalid date range",
      "detail": "Start date must be before end date"
    }
    ```
  </Accordion>

  <Accordion title="No Data Available (404)">
    ```json theme={null}
    {
      "error": "No historical data available",
      "detail": "No trading data found for the specified period"
    }
    ```
  </Accordion>
</AccordionGroup>

## MCP Protocol Usage

For AI agents using the Model Context Protocol:

```json theme={null}
{
  "method": "tools/call",
  "params": {
    "name": "get_time_series_daily",
    "arguments": {
      "symbol": "AAPL",
      "outputsize": "compact"
    }
  }
}
```

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Stock Quote" icon="chart-line" href="/api-reference/stock/quote">
    Get current real-time stock price
  </Card>

  <Card title="Technical Indicators" icon="trending-up" href="/api-reference/fmp/technical-indicators">
    Get calculated technical indicators
  </Card>

  <Card title="Moving Averages" icon="chart-area" href="/api-reference/fmp/moving-averages">
    Get moving average calculations
  </Card>

  <Card title="Company Overview" icon="building" href="/api-reference/stock/overview">
    Get fundamental company data
  </Card>
</CardGroup>
