-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
32 lines (23 loc) · 1.01 KB
/
utils.py
File metadata and controls
32 lines (23 loc) · 1.01 KB
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
import numpy as np
def load_data(filename="sample.txt"):
"""Load expected returns and covariance matrix from file."""
with open(filename, "r") as file:
expected_returns = [float(num) for num in file.readline().split()]
cov_matrix = []
while True:
line = file.readline()
if not line:
break
cov_matrix.append([float(num) for num in line.split()])
return np.array(expected_returns), np.array(cov_matrix)
def portfolio_return(weights, expected_returns):
"""Calculate portfolio return."""
return np.dot(weights, expected_returns)
def portfolio_risk(weights, cov_matrix):
"""Calculate portfolio risk (standard deviation)."""
return np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
def fitness(weights, expected_returns, cov_matrix):
"""Fitness function: maximize return and minimize risk."""
ret = portfolio_return(weights, expected_returns)
risk = portfolio_risk(weights, cov_matrix)
return ret / risk