Question: Fast Permutation Compiled C


I have this Maple code that calculates the Sharpe ration= Expected return portfolio / Standard deviation return portfolio
for a pair of stocks by using permuations [ stock[i], stock[i] ]. Each stock shows up the permuation list twice first in
[ here, not here ]  and  [ not here, here ] so I just itterate over such permuation list and take a long position in the
first stock ( +1*return) and a short position in the second stock (-1*return). So I get the Sharpe ration for all
long/short cominations. Now I sometime have a Matrix with 500 stocks and I want to make this process
as fast as possible. I have tried to make the below code as fast as possible but it is still quite slow.
How can I make it very very fast (preferably compiled to c ie option=autocompile) ?


restart:
with(Statistics):
with(LinearAlgebra):
with(combinat):

nstock := 50:
StockReturn := Transpose(Matrix(`<,>`(seq(Sample(RandomVariable(Normal(0, 1)), 100), i = 1 .. nstock)))):

T := table():
per := permute(nstock, 2):

for i to nops(per) do

SH[i] := evalf(add(StockReturn[r, per[i][1]]-StockReturn[r, per[i][2]], r = 1 .. 100)/StandardDeviation([seq(StockReturn[r, per[i][1]]-StockReturn[r, per[i][2]], r = 1 .. 100)]), 5);

if SH[i] > 0 then T[i] := [per[i][1], -per[i][2], SH[i]] else next end if :

end do:

data1 := Matrix(sort(convert(T, list), proc (a, b) options operator, arrow; b[3] < a[3] end proc)):

data1[1 .. 10];
 

Please Wait...