by Dr. Yves J. Hilpisch, Visixion GmbH, http://www.visixion.com
This simple example illustrates how to analyze financial problems with Python.
First we import the scientific stack.
from pylab import *
Some parameter values for the stimulation.
S0 = 100 # intial value
vol = 0.2 # volatility
T = 10. # savings period in years
r = 0.025 # short rate
M = 20 # time steps
dt = T / M # time interval
Simulate the Base Investment and plot the simulated path.
S = zeros((M + 1)) # vector for index level
S[0] = S0 # intialization
for t in range(1, M + 1): # simulation loop
S[t] = S[t-1] * exp((r - vol ** 2 / 2) * dt + vol * sqrt(dt) * standard_normal())
# geometric Brownian motion
plot(S) # show the random development
grid(True)
S
array([ 100. , 131.86180161, 115.41549563, 109.09797105, 125.853692 , 107.21403887, 89.94434985, 90.32156587, 102.93154117, 87.42385132, 82.38829348, 96.36388625, 95.38434112, 76.52822176, 75.9340541 , 63.35431946, 75.21530176, 67.66162694, 75.43002615, 77.21285179, 89.97773932])
Simulate the savings plan.
sparPA = 100.0 # money invested per year
sparEUR = sparPA / M # money invested per time interval
sparANT = zeros_like(S)
sparVAL = zeros_like(S)
for t in range(0, M):
sparANT[t] = sparEUR / S[t]
sparVAL = cumsum(sparANT) * S # valuation of portfolio
perfS = S[-1] / S0 - 1 # performance of base investment in percent
perfV = sparVAL[-1] / (M * sparEUR) - 1 # performance of savings plan
print "Performance of Base Investment %4.3f" % perfS
print "Performance of Savings Plan %4.3f" % perfV
Performance of Base Investment -0.100 Performance of Savings Plan 0.014
Show the evolution of the savings plan
plot(sparVAL)
grid(True)
sparVAL
array([ 5. , 11.59309008, 15.14715574, 19.31804239, 27.28498783, 28.24392474, 28.69448511, 33.81482641, 43.53578227, 41.97667122, 44.55884185, 57.11739418, 61.53679218, 54.37184891, 58.94970407, 54.18370852, 69.32779993, 67.36539143, 80.0997791 , 86.99297664, 101.37472187])
Plot the net value of the savings plan.
sparSUM = array(array([sparEUR,] * M + [0.0])) # vector with investments
plot(sparVAL - sparSUM.cumsum()) # net value position (portfolio value - investments)
grid(True)