Back to Community
Getting error "Markowitz portfolio optimization in Python"

Hello Quantopians.. Does anyone have idea about this error? Please advise.

Traceback (most recent call last):
File "C:/Users/jayesh/Desktop/pth/Optimazation work/m2.py", line 128, in
results = algo.run(data)
File "C:\Python34\lib\site-packages\zipline\algorithm.py", line 423, in run
for perf in self.gen:
File "C:\Python34\lib\site-packages\zipline\gens\tradesimulation.py", line 127, in transform
self.algo.instant_fill,
File "C:\Python34\lib\site-packages\zipline\gens\tradesimulation.py", line 214, in process_snapshot
new_orders = self._call_handle_data()
File "C:\Python34\lib\site-packages\zipline\gens\tradesimulation.py", line 236, in call_handle_data
self.algo.handle_data(self.current_data)
File "C:\Python34\lib\site-packages\zipline\algorithm.py", line 226, in handle_data
self._handle_data(self, data)
File "C:/Users/jayesh/Desktop/pth/Optimazation work/m2.py", line 118, in handle
data
order_target_percent(stock, weight)
File "C:\Python34\lib\site-packages\zipline\utils\api_support.py", line 60, in wrapped
return getattr(get_algo_instance(), f.
_name__)(*args, **kwargs)
File "C:\Python34\lib\site-packages\zipline\algorithm.py", line 785, in order_target_percent
style=style)
File "C:\Python34\lib\site-packages\zipline\algorithm.py", line 767, in order_target_value
style=style)
File "C:\Python34\lib\site-packages\zipline\algorithm.py", line 744, in order_target
style=style)
File "C:\Python34\lib\site-packages\zipline\algorithm.py", line 511, in order
amount = int(round_if_near_integer(amount))
File "C:\Python34\lib\site-packages\zipline\algorithm.py", line 503, in round_if_near_integer
if abs(a - round(a)) <= epsilon:
TypeError: type numpy.ndarray doesn't define round method

3 responses

it would help if you published your script along with it...
but I'm going to guess your variable a is a numpy.ndarray and not just a number... so when you call round(a) it is trying to round an nump.ndarray?

Shooting from the hip

I just

Thanks for the prompt responsI just copy pasted same code as mentioned below:

import numpy as np
import matplotlib.pyplot as plt
import cvxopt as opt
from cvxopt import blas, solvers
import pandas as pd

from zipline.utils.factory import load_bars_from_yahoo
end = pd.Timestamp.utcnow()
start = end - 250 * pd.tseries.offsets.BDay()

print (start)

data = load_bars_from_yahoo(stocks=['IBM', 'GLD', 'XOM', 'AAPL',
'MSFT'],
start=start, end=end)
data.loc[:, :, 'price'].plot(figsize=(8,5))
plt.ylabel('price in $')

plt.show()

import zipline
from zipline.api import (add_history,
history,
set_slippage,
slippage,
set_commission,
commission,
order_target_percent)

from zipline import TradingAlgorithm

def initialize(context):

# Register history container to keep a window of the last 100 prices.  
add_history(100, '1d', 'price')  
# Turn off the slippage model  
set_slippage(slippage.FixedSlippage(spread=0.0))  
# Set the commission model (Interactive Brokers Commission)  
set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.0))  
context.tick = 0

def optimal_portfolio(returns):
n = len(returns)
returns = np.asmatrix(returns)

N = 100  
mus = [10**(5.0 * t/N - 1.0) for t in range(N)]  

# Convert to cvxopt matrices  
S = opt.matrix(np.cov(returns))  
pbar = opt.matrix(np.mean(returns, axis=1))  

# Create constraint matrices  
G = -opt.matrix(np.eye(n))   # negative n x n identity matrix  
h = opt.matrix(0.0, (n ,1))  
A = opt.matrix(1.0, (1, n))  
b = opt.matrix(1.0)  

# Calculate efficient frontier weights using quadratic programming  
portfolios = [solvers.qp(mu*S, -pbar, G, h, A, b)['x']  
              for mu in mus]  
## CALCULATE RISKS AND RETURNS FOR FRONTIER  
returns = [blas.dot(pbar, x) for x in portfolios]  
risks = [np.sqrt(blas.dot(x, S*x)) for x in portfolios]  
## CALCULATE THE 2ND DEGREE POLYNOMIAL OF THE FRONTIER CURVE  
m1 = np.polyfit(returns, risks, 2)  
x1 = np.sqrt(m1[2] / m1[0])  
# CALCULATE THE OPTIMAL PORTFOLIO  
wt = solvers.qp(opt.matrix(x1 * S), -pbar, G, h, A, b)['x']  
return np.asarray(wt), returns, risks  

def handle_data(context, data):
# Allow history to accumulate 100 days of prices before trading
# and rebalance every day thereafter.
context.tick += 1
if context.tick < 100:
return
# Get rolling window of past prices and compute returns
prices = history(100, '1d', 'price').dropna()
returns = prices.pct_change().dropna()
try:
# Perform Markowitz-style portfolio optimization
weights, _, _ = optimal_portfolio(returns.T)
# Rebalance portfolio accordingly
for stock, weight in zip(prices.columns, weights):
order_target_percent(stock, weight)
except ValueError as e:
# Sometimes this error is thrown
# ValueError: Rank(A) < p or Rank([P; A; G]) < n
pass

Instantinate algorithm

algo = TradingAlgorithm(initialize=initialize,
handle_data=handle_data)

Run algorithm

results = algo.run(data)
results.portfolio_value.plot()

Hello Jayesh,
Seems there's a problem with zipline/algorithm.py.
Replacing the method round by np.around (suitable for np.ndarray types) worked for me.
Cheers,
Marc