from dx import *
from pylab import plt
plt.style.use('seaborn')

"""
Explanation: <img src="http://hilpisch.com/tpq_logo.png" alt="The Python Quants" width="45%" align="right" border="4">
Mean-Variance Portfolio Class
Without doubt, the Markowitz (1952) mean-variance portfolio theory is a cornerstone of modern financial theory. This section illustrates the use of the mean_variance_portfolio class to implement this approach.
End of explanation
"""


ma = market_environment('ma', dt.date(2010, 1, 1))
ma.add_list('symbols', ['AAPL.O', 'INTC.O', 'MSFT.O', 'GS.N'])
ma.add_constant('source', 'google')
ma.add_constant('final date', dt.date(2014, 3, 1))

"""
Explanation: Market Environment and Portfolio Object
We start by instantiating a market environment object which in particular contains a list of ticker symbols in which we are interested in.
End of explanation
"""


%%time
port = mean_variance_portfolio('am_tech_stocks', ma)
  # instantiates the portfolio class
  # and retrieves all the time series data needed

port.get_available_symbols()

"""
Explanation: Using pandas under the hood, the class retrieves historial stock price data from either Yahoo! Finance of Google.
End of explanation
"""


port.get_weights()
  # defaults to equal weights

"""
Explanation: Basic Statistics
Since no portfolio weights have been provided, the class defaults to equal weights.
End of explanation
"""


port.get_portfolio_return()
  # expected (= historical mean) return

"""
Explanation: Given these weights you can calculate the portfolio return via the method get_portfolio_return.
End of explanation
"""


port.get_portfolio_variance()
  # expected (= historical) variance

"""
Explanation: Analogously, you can call get_portfolio_variance to get the historical portfolio variance.
End of explanation
"""


print(port)
  # ret. con. is "return contribution"
  # given the mean return and the weight
  # of the security

"""
Explanation: The class also has a neatly printable string representation.
End of explanation
"""


port.set_weights([0.6, 0.2, 0.1, 0.1])

print(port)

"""
Explanation: Setting Weights
Via the method set_weights the weights of the single portfolio components can be adjusted.
End of explanation
"""


port.test_weights([0.6, 0.2, 0.1, 0.1])
    # returns av. return + vol + Sharp ratio
    # without setting new weights

"""
Explanation: You cal also easily check results for different weights with changing the attribute values of an object.
End of explanation
"""


# Monte Carlo simulation of portfolio compositions
rets = []
vols = []

for w in range(500):
    weights = np.random.random(4)
    weights /= sum(weights)
    r, v, sr = port.test_weights(weights)
    rets.append(r)
    vols.append(v)

rets = np.array(rets)
vols = np.array(vols)

"""
Explanation: Let us implement a Monte Carlo simulation over potential portfolio weights.
End of explanation
"""


import matplotlib.pyplot as plt
%matplotlib inline
plt.figure(figsize=(10, 6))
plt.scatter(vols, rets, c=rets / vols, marker='o', cmap='coolwarm')
plt.xlabel('expected volatility')
plt.ylabel('expected return')
plt.colorbar(label='Sharpe ratio');

"""
Explanation: And the simulation results visualized.
End of explanation
"""


port.optimize('Return')
  # maximizes expected return of portfolio
  # no volatility constraint

print(port)

"""
Explanation: Optimizing Portfolio Composition
One of the major application areas of the mean-variance portfolio theory and therewith of this DX Analytics class it the optimization of the portfolio composition. Different target functions can be used to this end.
Return
The first target function might be the portfolio return.
End of explanation
"""


port.optimize('Return', constraint=0.225, constraint_type='Exact')
  # interpretes volatility constraint as equality

print(port)

"""
Explanation: Instead of maximizing the portfolio return without any constraints, you can also set a (sensible/possible) maximum target volatility level as a constraint. Both, in an exact sense ("equality constraint") ...
End of explanation
"""


port.optimize('Return', constraint=0.4, constraint_type='Bound')
  # interpretes volatility constraint as inequality (upper bound)

print(port)

"""
Explanation: ... or just a an upper bound ("inequality constraint").
End of explanation
"""


port.optimize('Vol')
  # minimizes expected volatility of portfolio
  # no return constraint

print(port)

"""
Explanation: Risk
The class also allows you to minimize portfolio risk.
End of explanation
"""


port.optimize('Vol', constraint=0.175, constraint_type='Exact')
  # interpretes return constraint as equality

print(port)

port.optimize('Vol', constraint=0.20, constraint_type='Bound')
  # interpretes return constraint as inequality (upper bound)

print(port)

"""
Explanation: And, as before, to set constraints (in this case) for the target return level.
End of explanation
"""


port.optimize('Sharpe')
  # maximize Sharpe ratio

print(port)

"""
Explanation: Sharpe Ratio
Often, the target of the portfolio optimization efforts is the so called Sharpe ratio. The mean_variance_portfolio class of DX Analytics assumes a risk-free rate of zero in this context.
End of explanation
"""


%%time
evols, erets = port.get_efficient_frontier(100)
  # 100 points of the effient frontier

"""
Explanation: Efficient Frontier
Another application area is to derive the efficient frontier in the mean-variance space. These are all these portfolios for which there is no portfolio with both lower risk and higher return. The method get_efficient_frontier yields the desired results.
End of explanation
"""


plt.figure(figsize=(10, 6))
plt.scatter(vols, rets, c=rets / vols, marker='o')
plt.scatter(evols, erets, c=erets / evols, marker='o', cmap='coolwarm')
plt.xlabel('expected volatility')
plt.ylabel('expected return')
plt.colorbar(label='Sharpe ratio')

"""
Explanation: The plot with the random and efficient portfolios.
End of explanation
"""


%%time
cml, optv, optr = port.get_capital_market_line(riskless_asset=0.05)
  # capital market line for effiecient frontier and risk-less short rate

cml  # lambda function for capital market line

"""
Explanation: Capital Market Line
The capital market line is another key element of the mean-variance portfolio approach representing all those risk-return combinations (in mean-variance space) that are possible to form from a risk-less money market account and the market portfolio (or another appropriate substitute efficient portfolio).
End of explanation
"""


plt.figure(figsize=(10, 6))
plt.plot(evols, erets, lw=2.0, label='efficient frontier')
plt.plot((0, 0.4), (cml(0), cml(0.4)), lw=2.0, label='capital market line')
plt.plot(optv, optr, 'r*', markersize=10, label='optimal portfolio')
plt.legend(loc=0)
plt.ylim(0)
plt.xlabel('expected volatility')
plt.ylabel('expected return')

"""
Explanation: The following plot illustrates that the capital market line has an ordinate value equal to the risk-free rate (the safe return of the money market account) and is tangent to the efficient frontier.
End of explanation
"""


optr

optv

"""
Explanation: Portfolio return and risk of the efficient portfolio used are:
End of explanation
"""


port.optimize('Vol', constraint=optr, constraint_type='Exact')

print(port)

"""
Explanation: The portfolio composition can be derived as follows.
End of explanation
"""


port.optimize('Return', constraint=optv, constraint_type='Exact')

print(port)

"""
Explanation: Or also in this way.
End of explanation
"""


symbols = list(port.get_available_symbols())[:7]
symbols

ma = market_environment('ma', dt.date(2010, 1, 1))
ma.add_list('symbols', symbols)
ma.add_constant('source', 'google')
ma.add_constant('final date', dt.date(2014, 3, 1))

"""
Explanation: More Assets
As a larger, more realistic example, consider a larger set of assets.
End of explanation
"""


%%time
djia = mean_variance_portfolio('djia', ma)
  # defining the portfolio and retrieving the data

%%time
djia.optimize('Vol')
print(djia.variance, djia.variance ** 0.5)
  # minimium variance & volatility in decimals

"""
Explanation: Data retrieval in this case takes a bit.
End of explanation
"""


%%time
evols, erets = djia.get_efficient_frontier(25)
  # efficient frontier of DJIA

"""
Explanation: Given the larger data set now used, efficient frontier ...
End of explanation
"""


%%time
cml, optv, optr = djia.get_capital_market_line(riskless_asset=0.01)
  # capital market line and optimal (tangent) portfolio

plt.figure(figsize=(10, 6))
plt.plot(evols, erets, lw=2.0, label='efficient frontier')
plt.plot((0, 0.4), (cml(0), cml(0.4)), lw=2.0, label='capital market line')
plt.plot(optv, optr, 'r*', markersize=10, label='optimal portfolio')
plt.legend(loc=0)
plt.ylim(0)
plt.xlabel('expected volatility')
plt.ylabel('expected return')

"""
Explanation: ... and capital market line derivations take also longer.
End of explanation
"""


