|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +import os |
| 3 | +from datetime import date |
| 4 | +from typing import List |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +import pandas as pd |
| 8 | +from fastapi import FastAPI, HTTPException |
| 9 | +from pydantic import BaseModel, Field |
| 10 | + |
| 11 | +prices = pd.read_csv( |
| 12 | + os.path.join(os.path.dirname(__file__), "prices.csv"), |
| 13 | + index_col=0, |
| 14 | + parse_dates=True, |
| 15 | +) |
| 16 | + |
| 17 | + |
| 18 | +def validate_ticker(ticker): |
| 19 | + if ticker not in prices["ticker"].unique(): |
| 20 | + raise HTTPException(status_code=404, detail="Ticker not found") |
| 21 | + |
| 22 | + |
| 23 | +class Tickers(BaseModel): |
| 24 | + tickers: list = Field(title="All available stock tickers") |
| 25 | + |
| 26 | + |
| 27 | +class Stock(BaseModel): |
| 28 | + ticker: str = Field(..., title="Ticker of the stock") |
| 29 | + price: float = Field(..., title="Latest price of the stock") |
| 30 | + volatility: float = Field(..., title="Latest volatility of the stock price") |
| 31 | + |
| 32 | + |
| 33 | +class Price(BaseModel): |
| 34 | + date: date |
| 35 | + high: float = Field(..., title="High price for this date") |
| 36 | + low: float = Field(..., title="Low price for this date") |
| 37 | + close: float = Field(..., title="Closing price for this date") |
| 38 | + volume: int = Field(..., title="Daily volume for this date") |
| 39 | + adjusted: float = Field(..., title="Split-adjusted price for this date") |
| 40 | + |
| 41 | + |
| 42 | +app = FastAPI( |
| 43 | + title="Stocks API", |
| 44 | + description="The Stocks API provides pricing and volatility data for a " |
| 45 | + "limited number of US equities from 2010-2018", |
| 46 | +) |
| 47 | + |
| 48 | + |
| 49 | +@app.get("/stocks", response_model=Tickers) |
| 50 | +async def tickers(): |
| 51 | + tickers = prices["ticker"].unique().tolist() |
| 52 | + return {"tickers": tickers} |
| 53 | + |
| 54 | + |
| 55 | +@app.get("/stocks/{ticker}", response_model=Stock) |
| 56 | +async def ticker(ticker: str): |
| 57 | + validate_ticker(ticker) |
| 58 | + |
| 59 | + latest = prices.last_valid_index() |
| 60 | + ticker_prices = prices[prices["ticker"] == ticker] |
| 61 | + current_price = ticker_prices["close"][latest:].iloc[0].round(2) |
| 62 | + current_volatility = np.log( |
| 63 | + ticker_prices["adjusted"] / ticker_prices["adjusted"].shift(1) |
| 64 | + ).var() |
| 65 | + |
| 66 | + return { |
| 67 | + "ticker": ticker, |
| 68 | + "price": current_price, |
| 69 | + "volatility": current_volatility, |
| 70 | + } |
| 71 | + |
| 72 | + |
| 73 | +@app.get("/stocks/{ticker}/history", response_model=List[Price]) |
| 74 | +async def history(ticker: str): |
| 75 | + validate_ticker(ticker) |
| 76 | + |
| 77 | + ticker_prices = prices[prices["ticker"] == ticker] |
| 78 | + ticker_prices.loc[:, "date"] = ticker_prices.index.to_numpy() |
| 79 | + return ticker_prices.to_dict("records") |
0 commit comments