Question: # Load financial data financial_data = pd.read_csv('OPTProject_Financial.csv') # Calculate expected return and risk for each stock financial_data['ExpectedReturn'] = financial_data['price'] * financial_data['ret_mean'] * 20 financial_data['ExpectedRisk'] =
# Load financial data financial_data = pd.read_csv('OPTProject_Financial.csv')
# Calculate expected return and risk for each stock financial_data['ExpectedReturn'] = financial_data['price'] * financial_data['ret_mean'] * 20 financial_data['ExpectedRisk'] = financial_data['price'] * financial_data['ret_std'] * 20
# Define the optimization function for partial investments def optimize_partial_stocks(stocks, budget, risk_limit): c = -stocks['ExpectedReturn'].values # Negative return for maximization A = [stocks['price'].values, stocks['ExpectedRisk'].values] # Constraints b = [budget, risk_limit] bounds = [(0, price) for price in stocks['price'].values] # Fractional investment allowed
# Linear programming optimization result = linprog(c, A_ub=A, b_ub=b, bounds=bounds, method='highs')
if result.success: stocks['Investment'] = result.x total_money_spent = np.dot(stocks['price'].values, result.x) expected_return = np.dot(stocks['ExpectedReturn'].values, result.x) expected_risk = np.dot(stocks['ExpectedRisk'].values, result.x) num_stocks_bought = np.sum(result.x > 0) stocks_by_sector = stocks.loc[result.x > 0, 'Sector'].value_counts().to_dict() return num_stocks_bought, total_money_spent, expected_risk, expected_return, stocks_by_sector else: return None
# Run the optimization budget = 20000 risk_limit = 5000 result = optimize_partial_stocks(financial_data, budget, risk_limit) if result: num_stocks_bought, total_money_spent, expected_risk, expected_return, stocks_by_sector = result print(f"Partial Investment: Stocks Bought: {num_stocks_bought}, Total Money Spent: ${total_money_spent:.2f}, Expected Risk: ${expected_risk:.2f}, Expected Return: ${expected_return:.2f}") print(f"Stocks by Sector: {stocks_by_sector}") else: print("No feasible solution found.") --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[6], line 32 30 budget = 20000 31 risk_limit = 5000 ---> 32 result = optimize_partial_stocks(financial_data, budget, risk_limit) 33 if result: 34 num_stocks_bought, total_money_spent, expected_risk, expected_return, stocks_by_sector = result Cell In[6], line 16, in optimize_partial_stocks(stocks, budget, risk_limit) 13 bounds = [(0, price) for price in stocks['price'].values] # Fractional investment allowed 15 # Linear programming optimization ---> 16 result = linprog(c, A_ub=A, b_ub=b, bounds=bounds, method='highs') 18 if result.success: 19 stocks['Investment'] = result.x File /opt/anaconda3/lib/python3.11/site-packages/scipy/optimize/_linprog.py:628, in linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, method, callback, options, x0, integrality) 625 integrality = np.broadcast_to(integrality, np.shape(c)) 627 lp = _LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality) --> 628 lp, solver_options = _parse_linprog(lp, options, meth) 629 tol = solver_options.get('tol', 1e-9) 631 # Give unmodified problem to HiGHS File /opt/anaconda3/lib/python3.11/site-packages/scipy/optimize/_linprog_util.py:1026, in _parse_linprog(lp, options, meth) 1023 solver_options, A_ub, A_eq = _check_sparse_inputs(solver_options, meth, 1024 lp.A_ub, lp.A_eq) 1025 # Convert lists to numpy arrays, etc... -> 1026 lp = _clean_inputs(lp._replace(A_ub=A_ub, A_eq=A_eq)) 1027 return lp, solver_options File /opt/anaconda3/lib/python3.11/site-packages/scipy/optimize/_linprog_util.py:306, in _clean_inputs(lp) 302 raise ValueError( 303 "Invalid input for linprog: c must be a 1-D array and must " 304 "not have more than one non-singleton dimension") 305 if not np.isfinite(c).all(): --> 306 raise ValueError( 307 "Invalid input for linprog: c must not contain values " 308 "inf, nan, or None") 310 sparse_lhs = sps.issparse(A_eq) or sps.issparse(A_ub) 311 try: ValueError: Invalid input for linprog: c must not contain values inf, nan, or None
I am receiving this error on this code, and I don't know how to solve it. can you help?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
