Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interactive Web API for PorQua GSoC 25' Approach #22

Open
ARYPROGRAMMER opened this issue Mar 1, 2025 · 0 comments
Open

Interactive Web API for PorQua GSoC 25' Approach #22

ARYPROGRAMMER opened this issue Mar 1, 2025 · 0 comments

Comments

@ARYPROGRAMMER
Copy link

A General Idea for implementing the functionality. It is pretty simple to go with fastapi for quicker development but flask/django can be a better optimisation option that we can consider. MVT is any day robust.

The approach with fastapi can be described as :

  1. REST API Core Functionality - The main endpoint that handles portfolio optimization:
@app.post("/api/v1/optimize")
async def optimize_portfolio(data: UploadFile = File(...), params: OptimizationRequest = None):
    # Read uploaded financial data

    df = pd.read_csv(data.file)
    
    # Configure optimization with user parameters

    constraints = Constraints(selection=df.columns)

    if params.constraints["budget"]:
        constraints.add_budget()
    if params.constraints["long_only"]:
        constraints.add_box(box_type='LongOnly', upper=params.constraints["upper_bound"])
        
    # Run optimization using PorQua
    optimization = LeastSquares(solver_name='highs', sparse=True)
    optimization.constraints = constraints
    result = optimization.solve()
    
    return {
        "weights": dict(zip(df.columns, result.x)),
        "metrics": {
            "objective_value": result.objective_value,
            "tracking_error": np.sqrt(result.objective_value)
        }
    }

# CSV / JSON both can be given as request if needed -> a convertor might be used. CSV makes more sense

Core components Integration:

LeastSquares
OptimizationData
Constraints
Portfolio

  1. Interactive UI Components - Key widgets for user interaction:
# File upload and parameter controls
file_upload = widgets.FileUpload(
    description='Upload Data',
    accept='.csv',
    multiple=False
)

optimization_type = widgets.Dropdown(
    options=['Least Squares', 'Minimum Variance'],
    value='Least Squares',
    description='Method:'
)

max_weight = widgets.FloatSlider(
    value=0.1,
    min=0.0,
    max=1.0,
    step=0.01,
    description='Max Weight:'
)
  1. Visualization of Results - Shows the optimized portfolio:
def plot_weights(weights):
    fig = go.Figure(data=[
        go.Bar(x=list(weights.keys()), y=list(weights.values()))
    ])
    fig.update_layout(
        title='Portfolio Weights',
        xaxis_title='Assets',
        yaxis_title='Weight'
    )
    fig.show()

Ultimate Acheivements:

  1. Making PorQua Accessible:

    • Converts PorQua's Python library functionality into a web service
    • Provides both API and UI interfaces for different user needs, can be converted to a b2b or b2c solution if need be.
  2. User-Friendly Interface:

    • Drag and drop file upload
    • Interactive parameter adjustment
    • Real time visualization of results
  3. Flexible Implementation:

    • RESTful API allows for programmatic access
    • Jupyter interface for interactive use
    • Docker support for easy deployment

Users can optimize portfolios by either:

  • Making API calls programmatically
  • Using the interactive Jupyter notebook interface
  • Uploading data files and adjusting parameters through the web UI

Potential usage of these packages:

fastapi
uvicorn
pandas
numpy
python-multipart
pydantic
plotly
ipywidgets
requests

Deployment via a Dockerfile like:

FROM python:3.9-slim
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

For deployment, the solution can be containerized with all PorQua dependencies and run as a web service, while still maintaining the option to use the interactive Jupyter interface for more detailed analysis.

What IT Does:

  1. RESTful endpoints for data upload and processing
  2. Interactive Jupyter widgets for parameter configuration
  3. Real-time visualization of optimization results
  4. Error handling and validation layers
  5. Integration with PorQua's native optimization engines

I have tried to implement PorQua's core optimization capabilities while making them accessible to a broader audience through modern web interfaces. This is free and open for discussion. Still just an idea

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant