Hello, I encounter a problem when trying to convert these(Python) to Julia:
delta_TRC = [sum((i - TRC)**2) for i in TRC]
return sum(delta_TRC)
I found that the syntax of sum function provided by JuMP is very similar to these, but it is possible to implement only with the standard function ( whose syntax: sum(f, itr; [init]) )?
I am new to both Python and Julia, so I would appreciate if you explain the issue in detail…
Thank you.
The following is for reference, if needed:
from scipy.optimize import minimize
class Portfolio:
def __init__(self,port_a,port_b,port_c,port_d):
self.port_a=port_a
self.port_b=port_b
self.port_c=port_c
self.port_d=port_d
self.df=data[["Date",port_a,port_b,port_c,port_d]].dropna().reset_index(drop=True)
ret=self.df[[port_a,port_b,port_c,port_d]]
self.Rcov=ret.cov()
self.cov=np.array(ret.cov())
def risk_budget_objective(self,weights,cov):
weights = np.array(weights) #one-dimension array
sigma = np.sqrt(np.dot(weights, np.dot(cov, weights)))
MRC = np.dot(cov,weights)/sigma
TRC = weights * MRC
delta_TRC = [sum((i - TRC)**2) for i in TRC]
return sum(delta_TRC)
In short, the answer is: yes, you can do the same thing in base Julia than what Python+Numpy allows, with almost the same syntax.
The only syntactic difference lies in sum((TRC - i)**2). In this expression, i is a number (a scalar), TRC is an array of such numbers, and in this context the computation is supposed to mean:
tmp1 = TRC - i build the array obtained by subtracting the number i to every element of TRC
tmp2 = tmp1**2 build the array obtained by squaring tmp1 elementwise
sum(tmp2) compute the sum of all elements in tmp2
You see here that the arithmetic operations used to build tmp1 and tmp2 above are to be understood as elementwise operations; they are not simple operations between scalar numbers. This is where languages differ:
plain python lists do not allow this
[1,2,3] - 1 is an error
for numpy arrays, arithmetic operations are implicitly considered to be elementwise