File size: 2,101 Bytes
c4af433
 
 
 
96143f5
c4af433
 
 
96143f5
 
 
c4af433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96143f5
c4af433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96143f5
f6289e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import json
from pathlib import Path

import pandas as pd
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse


app = FastAPI()

origins = [
    "https://pro.openbb.dev",
    "https://pro.openbb.co",
    "https://excel.openbb.co",
    "https://excel.openbb.dev",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


ROOT_PATH = Path(__file__).parent.resolve()

@app.get("/")
def read_root():
    return {"Info": "Full example for OpenBB Custom Backend"}


@app.get("/csv-data")
def csv_data():
    """Read mock csv data and return it as a table to your widget"""
    # Specify the path to your CSV file
    csv_file_path = "mock_data.csv"

    try:
        # Convert the DataFrame to a dictionary and return the data
        return pd.read_csv((ROOT_PATH / csv_file_path).open()).to_dict(orient="records")
    except Exception as e:
        # Handle error cases here
        error_message = f"Error reading the CSV file: {str(e)}"
        return JSONResponse(content={"error": error_message}, status_code=500)


from pydantic import BaseModel
import random
import time


# Define a Pydantic model for stock data
class StockData(BaseModel):
    ticker: str
    price: float
    volume: int
    timestamp: float

# Create a mock function to simulate fetching stock data
def generate_mock_stock_data(ticker: str):
    return {
        "ticker": ticker,
        "price": round(random.uniform(100, 500), 2),  # Generate a random stock price
        "volume": random.randint(1000, 10000),  # Random trading volume
        "timestamp": time.time()  # Current timestamp
    }

# Define the /api/stocks endpoint
@app.get("/api/stocks", response_model=StockData)
async def get_stock_data(ticker: str):
    """
    Fetches stock data for a given ticker symbol.
    The data includes price, volume, and timestamp.
    """
    # Generate mock data for the given ticker
    stock_data = generate_mock_stock_data(ticker)
    return stock_data