Spaces:
Paused
Paused
Tonic commited on
adds descriptive docstrings for mcp
Browse files- src/app.py +0 -117
- src/data/stock_data.py +0 -62
src/app.py
DELETED
|
@@ -1,117 +0,0 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException
|
| 2 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
-
import yfinance as yf
|
| 4 |
-
import pandas as pd
|
| 5 |
-
from datetime import datetime, timedelta
|
| 6 |
-
import logging
|
| 7 |
-
from typing import Optional
|
| 8 |
-
|
| 9 |
-
# Configure logging
|
| 10 |
-
logging.basicConfig(level=logging.INFO)
|
| 11 |
-
logger = logging.getLogger(__name__)
|
| 12 |
-
|
| 13 |
-
app = FastAPI()
|
| 14 |
-
|
| 15 |
-
# Configure CORS
|
| 16 |
-
app.add_middleware(
|
| 17 |
-
CORSMiddleware,
|
| 18 |
-
allow_origins=["*"], # Allows all origins
|
| 19 |
-
allow_credentials=True,
|
| 20 |
-
allow_methods=["*"], # Allows all methods
|
| 21 |
-
allow_headers=["*"], # Allows all headers
|
| 22 |
-
)
|
| 23 |
-
|
| 24 |
-
def fetch_stock_data(symbol: str, period: str = "1y") -> pd.DataFrame:
|
| 25 |
-
"""
|
| 26 |
-
Fetch historical stock data for a given symbol using yfinance with authentication.
|
| 27 |
-
|
| 28 |
-
Args:
|
| 29 |
-
symbol (str): Stock symbol (e.g., 'AAPL')
|
| 30 |
-
period (str): Time period to fetch (default: '1y')
|
| 31 |
-
|
| 32 |
-
Returns:
|
| 33 |
-
pd.DataFrame: DataFrame containing historical stock data
|
| 34 |
-
"""
|
| 35 |
-
try:
|
| 36 |
-
# Create a Ticker object with authentication
|
| 37 |
-
ticker = yf.Ticker(symbol)
|
| 38 |
-
|
| 39 |
-
# Set authentication credentials
|
| 40 |
-
ticker._session.headers.update({
|
| 41 |
-
'User-Agent': 'Mozilla/5.0',
|
| 42 |
-
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
|
| 43 |
-
'Accept-Language': 'en-US,en;q=0.5',
|
| 44 |
-
'Connection': 'keep-alive',
|
| 45 |
-
'Upgrade-Insecure-Requests': '1',
|
| 46 |
-
})
|
| 47 |
-
|
| 48 |
-
# Fetch historical data
|
| 49 |
-
df = ticker.history(period=period)
|
| 50 |
-
|
| 51 |
-
if df.empty:
|
| 52 |
-
logger.warning(f"No data found for symbol {symbol}")
|
| 53 |
-
return pd.DataFrame()
|
| 54 |
-
|
| 55 |
-
# Reset index to make Date a column
|
| 56 |
-
df = df.reset_index()
|
| 57 |
-
|
| 58 |
-
# Rename columns to match expected format
|
| 59 |
-
df = df.rename(columns={
|
| 60 |
-
'Date': 'date',
|
| 61 |
-
'Open': 'open',
|
| 62 |
-
'High': 'high',
|
| 63 |
-
'Low': 'low',
|
| 64 |
-
'Close': 'close',
|
| 65 |
-
'Volume': 'volume'
|
| 66 |
-
})
|
| 67 |
-
|
| 68 |
-
# Convert date to string format
|
| 69 |
-
df['date'] = df['date'].dt.strftime('%Y-%m-%d')
|
| 70 |
-
|
| 71 |
-
logger.info(f"Successfully fetched data for {symbol}")
|
| 72 |
-
return df
|
| 73 |
-
|
| 74 |
-
except Exception as e:
|
| 75 |
-
logger.error(f"Error fetching data for {symbol}: {str(e)}")
|
| 76 |
-
return pd.DataFrame()
|
| 77 |
-
|
| 78 |
-
@app.get("/")
|
| 79 |
-
async def root():
|
| 80 |
-
return {"message": "Stock Prediction API"}
|
| 81 |
-
|
| 82 |
-
@app.get("/api/stock/{symbol}")
|
| 83 |
-
async def get_stock_data(symbol: str, period: Optional[str] = "1y"):
|
| 84 |
-
"""
|
| 85 |
-
Get historical stock data for a given symbol.
|
| 86 |
-
|
| 87 |
-
Args:
|
| 88 |
-
symbol (str): Stock symbol (e.g., 'AAPL')
|
| 89 |
-
period (str, optional): Time period to fetch. Defaults to "1y".
|
| 90 |
-
Valid periods: 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max
|
| 91 |
-
|
| 92 |
-
Returns:
|
| 93 |
-
dict: Dictionary containing stock data and metadata
|
| 94 |
-
"""
|
| 95 |
-
try:
|
| 96 |
-
df = fetch_stock_data(symbol, period)
|
| 97 |
-
|
| 98 |
-
if df.empty:
|
| 99 |
-
raise HTTPException(status_code=404, detail=f"No data found for symbol {symbol}")
|
| 100 |
-
|
| 101 |
-
# Convert DataFrame to dictionary format
|
| 102 |
-
data = df.to_dict(orient='records')
|
| 103 |
-
|
| 104 |
-
return {
|
| 105 |
-
"symbol": symbol,
|
| 106 |
-
"period": period,
|
| 107 |
-
"data": data,
|
| 108 |
-
"count": len(data)
|
| 109 |
-
}
|
| 110 |
-
|
| 111 |
-
except Exception as e:
|
| 112 |
-
logger.error(f"Error processing request for {symbol}: {str(e)}")
|
| 113 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 114 |
-
|
| 115 |
-
if __name__ == "__main__":
|
| 116 |
-
import uvicorn
|
| 117 |
-
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/data/stock_data.py
DELETED
|
@@ -1,62 +0,0 @@
|
|
| 1 |
-
import yfinance as yf
|
| 2 |
-
import pandas as pd
|
| 3 |
-
from datetime import datetime, timedelta
|
| 4 |
-
import logging
|
| 5 |
-
|
| 6 |
-
# Configure logging
|
| 7 |
-
logging.basicConfig(level=logging.INFO)
|
| 8 |
-
logger = logging.getLogger(__name__)
|
| 9 |
-
|
| 10 |
-
def fetch_stock_data(symbol: str, period: str = "1y") -> pd.DataFrame:
|
| 11 |
-
"""
|
| 12 |
-
Fetch historical stock data for a given symbol using yfinance with authentication.
|
| 13 |
-
|
| 14 |
-
Args:
|
| 15 |
-
symbol (str): Stock symbol (e.g., 'AAPL')
|
| 16 |
-
period (str): Time period to fetch (default: '1y')
|
| 17 |
-
|
| 18 |
-
Returns:
|
| 19 |
-
pd.DataFrame: DataFrame containing historical stock data
|
| 20 |
-
"""
|
| 21 |
-
try:
|
| 22 |
-
# Create a Ticker object with authentication
|
| 23 |
-
ticker = yf.Ticker(symbol)
|
| 24 |
-
|
| 25 |
-
# Set authentication credentials
|
| 26 |
-
ticker._session.headers.update({
|
| 27 |
-
'User-Agent': 'Mozilla/5.0',
|
| 28 |
-
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
|
| 29 |
-
'Accept-Language': 'en-US,en;q=0.5',
|
| 30 |
-
'Connection': 'keep-alive',
|
| 31 |
-
'Upgrade-Insecure-Requests': '1',
|
| 32 |
-
})
|
| 33 |
-
|
| 34 |
-
# Fetch historical data
|
| 35 |
-
df = ticker.history(period=period)
|
| 36 |
-
|
| 37 |
-
if df.empty:
|
| 38 |
-
logger.warning(f"No data found for symbol {symbol}")
|
| 39 |
-
return pd.DataFrame()
|
| 40 |
-
|
| 41 |
-
# Reset index to make Date a column
|
| 42 |
-
df = df.reset_index()
|
| 43 |
-
|
| 44 |
-
# Rename columns to match expected format
|
| 45 |
-
df = df.rename(columns={
|
| 46 |
-
'Date': 'date',
|
| 47 |
-
'Open': 'open',
|
| 48 |
-
'High': 'high',
|
| 49 |
-
'Low': 'low',
|
| 50 |
-
'Close': 'close',
|
| 51 |
-
'Volume': 'volume'
|
| 52 |
-
})
|
| 53 |
-
|
| 54 |
-
# Convert date to string format
|
| 55 |
-
df['date'] = df['date'].dt.strftime('%Y-%m-%d')
|
| 56 |
-
|
| 57 |
-
logger.info(f"Successfully fetched data for {symbol}")
|
| 58 |
-
return df
|
| 59 |
-
|
| 60 |
-
except Exception as e:
|
| 61 |
-
logger.error(f"Error fetching data for {symbol}: {str(e)}")
|
| 62 |
-
return pd.DataFrame()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|