Last active
December 29, 2017 03:52
-
-
Save TOSHISTATS/9811ba109150c3209d33f2c035c56821 to your computer and use it in GitHub Desktop.
Portfolio management by Genetic algorithm with mutation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 1.Import library | |
import time | |
import numpy as np | |
from numpy.random import * | |
seed(100) | |
# 2.Setting up the data | |
conv = np.array([(6,-5,4), (-5,17,-11),(4,-11,24)]) | |
mu=np.array([8,12,15]) | |
print(conv) | |
print(mu) | |
const=0.1 | |
n=len(mu) | |
popsize=8 | |
beta=2 | |
n | |
pwm=(1/n)*rand(n, popsize) | |
# 3. Evaluate and select genes | |
pwm1=pwm[: ,1] | |
# 3.1 Obtain the return of portfolio | |
preturn=np.dot(mu, pwm) | |
# 3.2.1 Obtain risk of portfolio for one gene | |
pvar=0.5*beta*(np.dot(np.dot(pwm1, conv), pwm1)) | |
# 3.2.2 Obtain risk of portfolio for all genes | |
pvar=list(range(popsize)) | |
for j in range(popsize): | |
pvar[j]=0.5*beta*(np.dot(np.dot(pwm[: , j], conv), pwm[: , j])) | |
print(len(pvar)) | |
print(type(pvar)) | |
print(pvar) | |
# 3.3 Select the best gene | |
pcriteria=preturn-pvar | |
print(type(pvar)) | |
print(pcriteria) | |
top=np.max(pcriteria) | |
topindex=np.argmax(pcriteria) | |
wtop=pwm[:, topindex] | |
print(top) | |
print(topindex) | |
# 4. Perfome GA operation and create next generations | |
nruns=10000 | |
t=time.time() | |
for k in range(nruns): | |
preturn=np.dot(mu, pwm) | |
pvar=list(range(popsize)) | |
for j in range(popsize): | |
pvar[j]=0.5*beta*(np.dot(np.dot(pwm[: , j], conv), pwm[: , j])) | |
pcriteria=preturn-pvar | |
top=np.max(pcriteria) | |
topindex=np.argmax(pcriteria) | |
wtop=pwm[:, topindex] | |
for i in range(popsize-1): | |
w1=wtop[0]+rand()*const | |
w2=wtop[1]+rand()*const | |
w3=wtop[2]+rand()*const | |
temp=w1+w2+w3 | |
w1=w1/temp | |
w2=w2/temp | |
w3=w3/temp | |
pwm[: , i]=[w1,w2,w3] | |
t2 = time.time() | |
print(round(t2-t, 5), 'Seconds to predict') | |
W=[w1,w2,w3] | |
Retern=np.dot(W, mu) | |
Risk=np.sqrt(np.dot(np.dot(W, conv), W)) | |
W,Retern,Risk | |
# This code is solely for educational purpose. The code cannot be used for investments in practive. TOSHI STATS SDN. BHD. and I do not accept any responsibility or liability for loss or damage occasioned to any person or property through using materials, instructions, methods, algorithm or ideas contained herein, or acting or refraining from acting as a result of such use. TOSHI STATS SDN. BHD. and I expressly disclaim all implied warranties, including merchantability or fitness for any particular purpose. There will be no duty on TOSHI STATS SDN. BHD. and me to correct any errors or defects in the codes and the software. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment