Python Forum
x and y must have same first dimension, but have shapes (1,) and (50,)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
x and y must have same first dimension, but have shapes (1,) and (50,)
#3
The error message is the following:
ValueError                                Traceback (most recent call last)
<ipython-input-182-1237a1515f04> in <module>
      5 plt.colorbar(label='sharpe ratio')
      6 plt.scatter(expectedVolatility[maxIndex],expectedReturn[maxIndex],c='red')
----> 7 plt.plot(volatility_opt,returns, '--')
      8 plt.show()

C:\Anaconda3\lib\site-packages\matplotlib\pyplot.py in plot(scalex, scaley, data, *args, **kwargs)
   2838 @_copy_docstring_and_deprecators(Axes.plot)
   2839 def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
-> 2840     return gca().plot(
   2841         *args, scalex=scalex, scaley=scaley,
   2842         **({"data": data} if data is not None else {}), **kwargs)

C:\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, data, *args, **kwargs)
   1741         """
   1742         kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1743         lines = [*self._get_lines(*args, data=data, **kwargs)]
   1744         for line in lines:
   1745             self.add_line(line)

C:\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in __call__(self, data, *args, **kwargs)
    271                 this += args[0],
    272                 args = args[1:]
--> 273             yield from self._plot_args(this, kwargs)
    274 
    275     def get_next_color(self):

C:\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs)
    397 
    398         if x.shape[0] != y.shape[0]:
--> 399             raise ValueError(f"x and y must have same first dimension, but "
    400                              f"have shapes {x.shape} and {y.shape}")
    401         if x.ndim > 2 or y.ndim > 2:

ValueError: x and y must have same first dimension, but have shapes (1,) and (50,)
For what concerns volatility_opt:
def negativeSR(w):
    w = np.array(w)
    R = np.sum(meanlogReturns*w)
    V = np.sqrt(np.dot(w.T, np.dot(Sigma,w)))
    SR = R/V
    return -1*SR
def b(w):
    return np.sum(w)-1

w0 = [0.25, 0.25, 0.25, 0.25] 
bounds = ((0,1), (0,1), (0,1), (0,1))
constraints = ({'type': 'eq', 'fun': b})
w_opt = minimize(negativeSR, w0, method='SLSQP', bounds=bounds, constraints=constraints)
w_opt
returns = np.linspace(0, 1.50, num= 50, endpoint=True, retstep=False, dtype=None, axis=0)
volatility_opt = []

def GR(w):
    w = np.array(w)
    R = np.sum(meanlogReturns*w)
    return R

def minimizeMyvolatility(w):
    w =np.array(w)
    V = np.sqrt(np.dot(w.T, np.dot(Sigma, w)))
    return V

for R in returns:
    constraints = ({'type': 'eq', 'fun': b},
                   {'type': 'eq', 'fun': lambda w: GR(w) - R})
    opt = minimize(minimizeMyvolatility, w0, method = 'SLSQP', bounds = bounds, constraints = constraints)

volatility_opt.append(opt['fun'])
with b as :
def b(w):
    return np.sum(w)-1
and Sigma and w as :
weight = np.zeros((a, 4))
expectedReturn = np.zeros(a)
expectedVolatility = np.zeros(a)
sharpeRatio = np.zeros(a)

meanlogReturns = logReturns.mean()
Sigma = logReturns.cov()
for k in range(a):
    w = np.array(np.random.random(4))
    w = w / np.sum(w)
    weight[k,:] = w
Returns of 4 tickers from yahoo lib with their closing price from 4/01/22 to 4/01/22 (or 01/4/22 to 10/4/22). LogReturns is just the log function of returns multiplied by 250 days.
In fact, till the Sharpe Ratio and the frontier's plot everything was running smoothly.
Reply


Messages In This Thread
RE: x and y must have same first dimension, but have shapes (1,) and (50,) - by asja2010 - Jan-12-2023, 01:38 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I design shapes on a curve in python? mervea 2 949 Sep-14-2023, 01:04 PM
Last Post: Pedroski55
  Array dimension don't match asja2010 0 1,231 Feb-23-2023, 04:22 PM
Last Post: asja2010
  Shapes in Video finndude 0 790 Oct-07-2022, 03:30 PM
Last Post: finndude
  Shapes over video in tkinter finndude 1 1,051 Oct-04-2022, 06:14 PM
Last Post: deanhystad
  operands could not be broadcast together with shapes (337,451) (225,301) kevinabbot 0 1,665 Dec-14-2021, 04:02 PM
Last Post: kevinabbot
  Strange error ValueError: dimension mismatch Anldra12 0 2,074 Aug-17-2021, 07:54 AM
Last Post: Anldra12
  ValueError: dimension mismatch Anldra12 0 3,547 Jul-17-2021, 04:46 PM
Last Post: Anldra12
  ValueError: x and y must have same first dimension, but have shapes (11,) and (15406, hobbyist 17 153,391 Mar-22-2021, 10:27 AM
Last Post: hobbyist
  Error When Plotting ValueError: x and y must have same first dimension JoeDainton123 1 9,276 Oct-04-2020, 12:58 PM
Last Post: scidam
  Wrong dimension for my plot Jemeronimo 1 2,098 Apr-25-2019, 06:19 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020