Пример #1
0
plt.title("Exponential Growth Effect ")
plt.xlabel("Time (number of years)")
plt.scatter(x, y, s=s)
plt.show()

#####
# Shows the negative relationship between discount rate and npv for
# fixed cash flows in a project
import scipy as sp
import numpy as np
import matplotlib.pyplot as plt
cashflows = [-120, 50, 60, 70]
rate = np.arange(0.001, 0.5, 0.002)
x = (0, max(rate))
y = (0, 0)
npvs = [sp.npv(r, cashflows) for r in rate]
plt.title("Rate - NPV() relationship")
plt.xlabel("Discount Rate")
plt.ylabel("NPV - Net Present Value")
plt.plot(rate, npvs)
plt.plot(x, y)
plt.show()

######
#converting price to returns in numpy and scipy
import numpy as np
price = np.array([10, 10.2, 10.1, 10.22, 9])
returns = (price[1:] - price[:-1]) / price[:-1]

######
import scipy as sp
"""
  Name     : 4375OS_06_03_npv_f_scipy.py
  Book     : Python for Finance
  Publisher: Packt Publishing Ltd. 
  Author   : Yuxing Yan
  Date     : 12/26/2013
  email    : [email protected]
             [email protected]
"""

import scipy as sp
cashflows = [50, 40, 20, 10, 50]
npv = sp.npv(0.1, cashflows)  #estimate NPV
print round(npv, 2)
Пример #3
0
#-*-coding:utf-8-*-
# 20200607
#21:00
import scipy as sp
from matplotlib.pyplot import *
cashflows = [-200, 80, 90, 100]
rate = []
npv = []
x = (0, 0.7)
y = (0, 0)

for i in range(1, 70):
    rate.append(0.01 * i)
    npv.append(sp.npv(0.01 * i, cashflows))

    plot(rate, npv)
    plot(x, y)
    show()
#
npv = []
for i in sp.arange(nSimulation):
    units = sp.ones(n) * units0[i]
    price = price0[i]
    R = R0[i]
    sales = units * price
    sales[0] = 0  # sales for 1st year is zero
    cost1 = costRawMaterials * sales
    cost2 = sp.ones(n) * otherCost
    cost3 = sp.ones(n) * sellingCost
    cost4 = sp.zeros(n)
    cost4[0] = costEquipment
    RD = sp.zeros(n)
    RD[0] = R_and_D  # assume R&D at time zero
    D = sp.ones(n) * costEquipment / nYear  # straight line depreciation
    D[0] = 0  # no depreciation at time 0
    EBIT = sales - cost1 - cost2 - cost3 - cost4 - RD - D
    NI = EBIT * (1 - tax)
    FCF = NI + D  # add back depreciation
    npvProject = sp.npv(R, FCF) / million  # estimate NPV
    npv.append(npvProject)

print("mean NPV of project=", round(sp.mean(npv), 0))
print("min  NPV of project=", round(min(npv), 0))
print("max  NPV of project=", round(max(npv), 0))
plt.title("NPV of the project: 3 uncertainties")
plt.xlabel("NPV (in million)")
plt.hist(npv, 50, range=[-3, 6], facecolor='blue', align='mid')
plt.show()
Пример #5
0
"""
  Name     : 4375OS_07_09_NPV_profile.py
  Book     : Python for Finance
  Publisher: Packt Publishing Ltd. 
  Author   : Yuxing Yan
  Date     : 12/26/2013
  email    : [email protected]
             [email protected]
"""

import scipy as sp
import matplotlib.pyplot as plt
cashflows = [504, -432, -432, -432, 832]
rate = []
npv = []
x = [0, 0.3]
y = [0, 0]
for i in range(1, 30):
    rate.append(0.01 * i)
    npv.append(sp.npv(0.01 * i, cashflows[1:]) + cashflows[0])
plt.plot(x, y), plt.plot(rate, npv)
plt.show()
Пример #6
0
'''
The  np.npv() function estimates the present values for a given set of future cash
flows. The first input value is the discount rate, and the second input is an array of
future cash flows. This  np.npv() function mimics Excel's  NPV function. Like Excel,
np.npv() is not a true  NPV function. It is actually a  PV function. It estimates the
present value of future cash flows by assuming the first cash flow happens at the
end of the first period.
'''
import scipy as sp
cashflows=[50,40,20,10,50]
npv=sp.npv(0.1,cashflows) #estimate NPV
npvrounded = round(npv,2)

the npv caculated here is not consistent to execel
need to be found why.
print(npvrounded)
"""
  Name     : 4375OS_07_09_NPV_profile.py
  Book     : Python for Finance
  Publisher: Packt Publishing Ltd. 
  Author   : Yuxing Yan
  Date     : 12/26/2013
  email    : [email protected]
             [email protected]
"""

import scipy as sp
import matplotlib.pyplot as plt
cashflows=[504,-432,-432,-432,832]
rate=[]
npv=[]
x=[0,0.3]
y=[0,0]
for i in range(1,30):
    rate.append(0.01*i)
    npv.append(sp.npv(0.01*i,cashflows[1:])+cashflows[0])
plt.plot(x,y),plt.plot(rate,npv)
plt.show()
Пример #8
0
def npv(*args):
    discount_rate, cashflow = args[0], args[1]
    return scipy.npv(discount_rate, cashflow)
Пример #9
0
np.size(x, axis=0) ##2 rows
np.size(x, axis=1) ##3 cols
### manipulate matrix col and row
np.std(x, axis=1) ##std by col
x.sum()
x.sum(axis=0) ##sum by row
### simulation
ret = np.array(range(1, 100), float)/100 ##create a grid of return pct
rand_50 = np.random.rand(50) ##50 rand num btw 0 and 1
rnorm_100 = np.random.normal(size=100)


## 2. Scipy ------------
### Compute the NPV of a Cashflow
cf = [-100, 50, 40, 20, 10, 50]
sp.npv(rate=0.1, values=cf)
### Monthly payment: APR = 0.045, compounded monthly, mortgage = 250k, T=30yrs
sp.pmt(rate=0.045/12, nper=12*30, pv=250000)
### PV of one future cf
sp.pv(rate=0.1,nper=5,pmt=0,fv=100)
### PV of Annuity (series of payments)
sp.pv(rate=0.1, nper=5, pmt=100)
### Geometric mean returns
def geoMeanreturn(ret):
    return pow(sp.prod(ret+1), 1./len(ret)) - 1
ret = np.array([0.1, 0.05, -0.02])
geoMeanreturn(ret)
### other fundamental stuff
sp.unique([1,1,2,3,4,1,1,1])
sp.median([1,1,2,3,4,1,1,1])
Пример #10
0
#!/usr/bin/env python3
"""     p. 146
NPV:    Net Present Value

Definition:
    A measurement of profit calculated by subtracting the present values(PV)
    of cash outflows (including initial cost) from the present values of cash
    inflows over a period of time

Rules:
    NPV > 0     : Invest
    NPV < 0     : Not Invest
"""
import scipy as sp
import matplotlib.pyplot as pyplot

rate = 0.112
cashflows = [-100, 50, 60, 70, 100, 20]
print(sp.npv(rate, cashflows))

rate = []
npv = []
for i in range(1, 100):
    rate.append(0.01 * i)
    npv.append(sp.npv(0.01 * i, cashflows))
pyplot.plot(rate, npv)
pyplot.show()
import scipy as sp
nYear = 5  # number of years
costEquipment = 5e6  # 5 million
n = nYear + 1  # add year zero
price = 28  # price of the product
units = 100000  # estimate number of units sold
otherCost = 100000  # other costs
sellingCost = 1500  # selling and administration cost
R_and_D = 200000  # Research and development
costRawMaterials = 0.3  # percentage cost of raw materials
R = 0.15  # discount rate
tax = 0.38  # corporate tax rate
#
sales = sp.ones(n) * price * units
sales[0] = 0  # sales for 1st year is zero
cost1 = costRawMaterials * sales
cost2 = sp.ones(n) * otherCost
cost3 = sp.ones(n) * sellingCost
cost4 = sp.zeros(n)
cost4[0] = costEquipment
RD = sp.zeros(n)
RD[0] = R_and_D  # assume R&D at time zero
D = sp.ones(n) * costEquipment / nYear  # straight line depreciation
D[0] = 0  # no depreciation at time 0
EBIT = sales - cost1 - cost2 - cost3 - cost4 - RD - D
NI = EBIT * (1 - tax)
FCF = NI + D  # add back depreciation
npvProject = sp.npv(R, FCF)  # estimate NPV
print("NPV of project=", round(npvProject, 0))
import scipy as sp
from matplotlib.pyplot import *
cashflows=[-100, 50, 60, 70]
rate=[]
npv=[]
x=(0, 0.7)
y=(0, 0)
for i in range(1,70):
    rate.append(0.01*i)
    npv.append(sp.npv(0.01*i,cashflows))
    #npv.append(sp.npv(0.01*i,cashflows[1:])+cashflows[0])
point = round(sp.irr(cashflows), 2)
print(point)
plot(rate,npv)
plot(x,y)
plot(point, 0, 'ro' )
figtext(point,0.2,str(point))
show()
Пример #13
0
    for i in np.arange(0, 10):
        fv = 50*(1+r)**i
        Fv_v  = Fv_v + fv
    face_value_f = face_value*(1+r)**num
    return Fv_v + face_value_f

Future_value = FV(1000, 50, 10,0.06)
print ('终值为%.2f元' % Future_value )

#==============================================================================
# 6.3 变化现金流计算
#==============================================================================
# NPV
import scipy as sp
cashflows=[-10000,3000,3500,7000,8000,2000]
sp.npv(0.112,cashflows)
if sp.npv(0.112,cashflows) > 0:
    print ('投资可以接受')
else:
    print('投资不可行')

# IRR
# 计算IRR
cashflows = [-6000,2500,1500,3000,1000,2000]
IRR = np.irr(cashflows)
print('内部收益率为: %.4f%%' % (100*IRR))

#使用函数
def IRR_rate(initial_invest,cash_flow,R):
    cash_total = 0
    for i in range(0,len(cash_flow)):
#!/usr/bin/env python3
"""     p. 149
IRR:    Internal Rate of Return

Definition:
    The interest rate at which the net present value of all the
    cash flows (both positive and negative) from a project or
    investment equal zero.

Rules:
    IRR > Rc    : Invest
    IRR < Rc    : Not Invest
"""
import scipy as sp


cashflows = [-100, 30, 40, 40, 50]
print(sp.irr(cashflows))

r = sp.irr(cashflows)
print(sp.npv(r, cashflows))
units0 = sp.random.uniform(low=lowUnit, high=highUnit, size=n2)
#
npv = []
for i in sp.arange(nSimulation):
    units = sp.ones(n) * units0[i]
    price = price0[i]
    sales = units * price
    sales[0] = 0
    cost1 = costRawMaterials * sales
    cost2 = sp.ones(n) * otherCost
    cost3 = sp.ones(n) * sellingCost
    cost4 = sp.zeros(n)
    cost4[0] = costEquipment
    RD = sp.zeros(n)
    RD[0] = R_and_D  #시각0의 R&D
    D = sp.ones(n) * costEquipment / nYear  #정액법
    D[0] = 0
    EBIT = sales - cost1 - cost2 - cost3 - cost4 - RD - D
    NI = EBIT * (1 - tax)
    FCF = NI + D
    npvProject = sp.npv(R, FCF) / million  # NPV
    npv.append(npvProject)
#표시
print("mean NPV of project=", round(sp.mean(npv), 0))
print("min NPV of project", round(min(npv), 0))
print("max NPV of project", round(max(npv), 0))
plt.title("NPV of the project : 3 uncertaintties")
plt.xlabel("NPV (in million)")
plt.hist(npv, 50, range=[-3, 6], facecolor='blue', align='mid')
plt.show()
Пример #16
0
#!/usr/bin/env python
#
# Classes and functions given as examples from Chapter 5
# in the book.
#
# Stock valuation using the dividend discount model
#

import scipy as sp

if __name__ == "__main__":
    """
    Go go super awesome stock valutation DDM
    """
    """
    Present Value demo:
    Given R=12%; D=1; and FV=50, where
        R is appropriate cost of equity
        D is the dividend
        and FV is the future value
    """
    sp.pv(0.12, 1, 1 + 50)
    """
    Grammatical growth demo:
    """
    dividends = [1.80, 2.07, 2.48193, 2.680, 2.7877]
    R = 0.182
    g = 0.03

    print(float(sp.npv(R, dividends[:-1]) * (1 + R)))