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

Tutorial code snippet cannot be run by itself? #60

Open
Realife-Brahmin opened this issue Mar 17, 2025 · 1 comment
Open

Tutorial code snippet cannot be run by itself? #60

Realife-Brahmin opened this issue Mar 17, 2025 · 1 comment

Comments

@Realife-Brahmin
Copy link

Realife-Brahmin commented Mar 17, 2025

So I cannot run this:

# Minimal example:
from amplpy import AMPL
import pandas as pd
ampl = AMPL()
ampl.eval(r"""
    set A ordered;
    param S{A, A};
    param lb default 0;
    param ub default 1;
    var w{A} >= lb <= ub;
    minimize portfolio_variance:
        sum {i in A, j in A} w[i] * S[i, j] * w[j];
    s.t. portfolio_weights:
        sum {i in A} w[i] = 1;
""")
tickers, cov_matrix = # ... pre-process data in Python
ampl.set["A"] = tickers
ampl.param["S"] = pd.DataFrame(cov_matrix, index=tickers, columns=tickers)
ampl.solve(solver="gurobi", gurobi_options="outlev=1")
assert ampl.solve_result == "solved"
sigma = ampl.get_value("sqrt(sum {i in A, j in A} w[i] * S[i, j] * w[j])")
print(f"Volatility: {sigma*100:.1f}%")
# ... post-process solution in Python

as I get an error on tickers, cov_matrix not being defined variables?

Only when I instantiate the variables, something like this:

# Additional loc(s) to make the above Minimal Example a 'Working' one:
# Pre-process data in Python
tickers = ['AAPL', 'GOOGL', 'MSFT']  # Example tickers
cov_matrix = [
    [0.1, 0.01, 0.02],
    [0.01, 0.2, 0.03],
    [0.02, 0.03, 0.15]
]  # Example covariance matrix

can I get it to actually run.

Surely my additional loc(s) shouldn't be necessary, and that the amplpy tutorial code snippet is supposed to work by itself? (Sorry I'm certain this must be a pretty trivial question.)

@fdabrandao
Copy link
Member

Hi @Realife-Brahmin,

Thank you for bringing this up. Yes, the same does not include everything necessary to run the example to keep is short. You can find the complete example at https://ampl.com/colab/notebooks/financial-portfolio-optimization-with-amplpy.html. However, it is a good idea to include some sample data like the one you used to just make it runnable. I will updated the example.

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

2 participants