# Guide 2: Historical Price Analysis for Backtesting

**What you'll build:** A script that retrieves historical daily prices for a stock over a custom date range, calculates basic performance metrics (total return, average daily return, volatility), and identifies the best and worst trading days — the foundation for any backtesting engine.

**Endpoints used:**

-   `GET /v2/tickers/{symbol}/eod` — Get historical EOD data for a single ticker with date filters
    
-   `GET /v2/tickers/{symbol}/splits` — Check for stock splits that might affect raw price analysis
    

**Scenario:** You want to analyze AAPL's performance over the past year to evaluate whether it would have been a good investment.

**Step 1 — Retrieve one year of daily price data:**

`GET https://api.marketstack.com/v2/tickers/AAPL/eod?access_key=YOUR_API_KEY&date_from=2025-01-01&date_to=2025-12-31&sort=ASC&limit=1000`

Using `sort=ASC` returns data in chronological order (oldest first), which makes time-series analysis straightforward. Setting `limit=1000` ensures you get all ~252 trading days in one call.

**Step 2 — Check for splits in the same period:**

`GET https://api.marketstack.com/v2/tickers/AAPL/splits?access_key=YOUR_API_KEY&date_from=2025-01-01&date_to=2025-12-31`

If splits occurred, use `adj_close` instead of `close` for all calculations — otherwise raw prices will show a misleading drop on the split date.

**Step 3 — Calculate performance metrics:**

**Python example:**

python

```python
import requests

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.marketstack.com/v2"
ticker = "AAPL"
date_from = "2025-01-01"
date_to = "2025-12-31"
# Step 1: Get historical EOD data
response = requests.get(f"{BASE_URL}/tickers/{ticker}/eod", params={
    "access_key": API_KEY,
    "date_from": date_from,
    "date_to": date_to,
    "sort": "ASC",
    "limit": 1000
})
data = response.json()
if "error" in data:
    print(f"API Error: {data['error']['message']}")
    exit()
records = data["data"]
print(f"Retrieved {len(records)} trading days for {ticker}")
print(f"Period: {date_from} to {date_to}\n")
# Step 2: Check for splits
splits_resp = requests.get(f"{BASE_URL}/tickers/{ticker}/splits", params={
    "access_key": API_KEY,
    "date_from": date_from,
    "date_to": date_to
})
splits = splits_resp.json().get("data", [])
use_adjusted = len(splits) > 0
price_field = "adj_close" if use_adjusted else "close"
if use_adjusted:
    print(f"⚠ {len(splits)} stock split(s) detected — using adjusted prices\n")
# Step 3: Calculate metrics
prices = [r[price_field] for r in records]
# Daily returns
daily_returns = []
for i in range(1, len(prices)):
    daily_return = (prices[i] - prices[i - 1]) / prices[i - 1]
    daily_returns.append(daily_return)
# Total return
total_return = (prices[-1] - prices[0]) / prices[0] * 100
# Average daily return
avg_daily_return = sum(daily_returns) / len(daily_returns) * 100
# Volatility (standard deviation of daily returns)
mean = sum(daily_returns) / len(daily_returns)
variance = sum((r - mean) ** 2 for r in daily_returns) / len(daily_returns)
volatility = (variance ** 0.5) * 100
# Best and worst days
best_idx = daily_returns.index(max(daily_returns))
worst_idx = daily_returns.index(min(daily_returns))
print(f"--- {ticker} Performance Summary ---")
print(f"Start price:        ${prices[0]:.2f}")
print(f"End price:          ${prices[-1]:.2f}")
print(f"Total return:       {total_return:+.2f}%")
print(f"Avg daily return:   {avg_daily_return:+.4f}%")
print(f"Daily volatility:   {volatility:.4f}%")
print(f"Annualized vol:     {volatility * (252 ** 0.5):.2f}%")
print(f"")
print(f"Best day:  {records[best_idx + 1]['date'][:10]}  {max(daily_returns) * 100:+.2f}%")
print(f"Worst day: {records[worst_idx + 1]['date'][:10]}  {min(daily_returns) * 100:+.2f}%")
```

**Example output:**

```text
Retrieved 251 trading days for AAPL
Period: 2025-01-01 to 2025-12-31
--- AAPL Performance Summary ---
Start price:        $221.34
End price:          $237.45
Total return:       +7.28%
Avg daily return:   +0.0290%
Daily volatility:   1.4235%
Annualized vol:     22.60%
Best day:  2025-07-14  +4.82%
Worst day: 2025-03-09  -3.67%
```

**Tips:**

-   Always use `adj_close` for multi-month or multi-year analysis — unadjusted prices create false signals around split dates
    
-   Set `limit=1000` to avoid pagination for a single year (there are ~252 trading days per year)
    
-   For multi-year analysis, paginate using `offset`: first call `offset=0&limit=1000`, next call `offset=1000&limit=1000`
    
-   To compare multiple stocks, run the same analysis in a loop and compare total returns and volatility side by side
    
-   Weekends and market holidays have no data — don't assume 365 records per year
