简体   繁体   中英

Function doesn't work anymore if run by more than one time in Python 3.7

I'm dealing with some simulations in Python and I have the following code:

import numpy as np
import matplotlib.pyplot as plt
from statsmodels.sandbox.distributions import multivariate as mt
# Simulation parameters

n = 100    # number of assets
T = 360    # time-series size
p = 100    # number of controls
b = 4      # number of relevant controls

# Risk price of newly proposed factor
lambdag1 = 0.5

# Other risk prices
lambdah1 = 0.5 * np.random.multivariate_normal(np.zeros(b), cov = 0.1 * np.identity(b)).reshape((b, 1))

# Zero-beta rate
gamma_0 = 0.5

# Simulating moments (covariances, expected returns and betas)

# Computing cross-sectional residuals (nx1)
Ce1 = 0.5 * np.random.multivariate_normal(mean = np.zeros(n), cov = np.identity(n)).reshape((n,1))

# Computing Ch1 (nxb)
Ch1 = 0.1 * np.transpose(np.random.multivariate_normal(mean = np.zeros(n), cov = np.identity(n), size = b))

# Computing Cg1 (nx1)
xi1 = 0.5 * np.random.normal()
chi1 = 0.5 * np.random.multivariate_normal(mean = np.zeros((b)), cov = np.identity(b)).reshape((1, b))
Cg1 = np.ones((n,1))*np.transpose(xi1) + Ch1.dot(np.transpose(chi1)) + Ce1

# Computing Cz1
eta1 = np.random.multivariate_normal(np.zeros(b), cov = np.identity(b)).reshape((1,b))
Cz1 = Cg1 - Ch1.dot(np.transpose(eta1))

# Computing the cross-section of expected returns
Er = np.ones((n,1)) * gamma_0 + Cg1.dot(lambdag1) + Ch1.dot(lambdah1)

# Computing the betas

# Computing the correlation structure for shocks z1
rhoz1 = 0.5

# Defines the covariance matrix for the important controls. Some correlation is desired to challenge the LASSO.
# Too much "independence" would be unreal. Using a non-random co-variance matrix

rhoh1 = 0.5
Sigmah1 = np.zeros((b, b))
for i in range(0, b):
  for j in range(0, b):
    Sigmah1[i, j] = 0.5 * rhoh1**(np.abs(i - j))

# Use orthogonality conditions to derive the betas
# betag1 = Cz1 * 1/Sigmaz1[0,0]
betag1 = Cz1 * 1/rhoz1
betah1 = Ch1.dot(np.linalg.inv(Sigmah1)) - betag1.dot(eta1)

# Creating Sigmau
rhou = 0.5
Sigmau = np.zeros((n,n))
for i in range(0, n):
  for j in range(0, n):
    Sigmau[i, j] = rhou**(np.abs(i - j))


# Defining covariances for h2
theta0 = np.zeros((1, p -b))
red_fac = int(np.floor(0.5*(p-b)))  # indices of redundant factors in h2  

theta1 = 0.5 * np.hstack((np.transpose(np.random.multivariate_normal(mean = np.zeros(b + 1), 
                                                               cov = np.identity(b+1), 
                                                               size = red_fac)), 
                    np.zeros((b+1, p - b - red_fac))))

Cepsilon = np.random.multivariate_normal(mean = np.zeros(p-b), cov = 0.5 * np.identity(p-b), size = n)

# The factor shrinking covariances is a way magnitudes agree. This is important for LASSO
Ch2 = 0.1 * (np.ones((n,1)).dot(theta0) + np.hstack((Cg1, Ch1)).dot(theta1) + Cepsilon)

# Implied covariance matrix for returns
Sigmar = (Cz1 * 1/rhoz1).dot(np.transpose(Cz1)) + Ch1.dot(np.linalg.inv(Sigmah1)).dot(np.transpose(Ch1)) + Sigmau
phi = np.linalg.inv(Sigmar).dot(Ch2)

After that, I define the following function:

def gen_data(n, p, T, b):
  """This function simulates one sample dataset of returns and factors from previously computed covariances and betas.
  Outputs:

  R (n x T): matrix of returns for n assets and T periods
  H (p X T): matrix of p factors and T periods
  G (1 X T): matrix of the evolution of the newly proposed factor (T periods) 

  """

  # Computing the important controls
  H1 = np.transpose(np.random.multivariate_normal(mean = np.zeros(b), cov = Sigmah1, size = T))

  # Computing the shocks z1t and the factor g_t stacked in G
  Z1 = np.random.multivariate_normal(mean = np.zeros(T), cov = np.identity(T)).reshape(1, T)
  G = eta1.dot(H1) + Z1

  # Simulating the shocks
  # Reference for multivariate Student-t: https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/distributions/multivariate.py
  U = mt.multivariate_t_rvs(m = np.zeros(n), S = Sigmau, df = 5, n = T).T

  # Finally simulating the returns
  R = Er.dot(np.ones((1, T))) + betag1.dot(G) + betah1.dot(H1) + U

  # Simulating other factors
  H2 = Ch2.T.dot(np.linalg.inv(Sigmar)).dot(R - Er.dot(np.ones((1,T)))) + np.random.multivariate_normal(mean = np.zeros(p-b), cov = np.identity(p-b), size = T).T
  H = np.vstack((H1, H2))

  # Outputs
  return(R, G, H)

And now I call it just to check everything is ok

a, b, c = gen_data(n, p, T, b)

So far, so good. Everything has the desired dimensions and so on. The bug starts to appear when I run the above call once more. If I do so, I will have the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-cb3db1328026> in <module>()
----> 1 a, b, c = gen_data(n, p, T, b)
      2 #print(time.time() - tic)

<ipython-input-10-6f0fd2e2ab70> in gen_data(n, p, T, b)
     10 
     11   # Computing the important controls
---> 12   H1 = np.transpose(np.random.multivariate_normal(mean = np.zeros(b), cov = Sigmah1, size = T))
     13 
     14   # Computing the shocks z1t and the factor g_t stacked in G

TypeError: only integer scalar arrays can be converted to a scalar index

First, I cannot understand the error message. Second, I cannot understand how it runs fine the first time and does not run in the second time. It does not make sense to me. Sorry if this is silly, I am new to Python. Any ideas on this? Thanks a lot in advance!

a, b, c = gen_data(n, p, T, b)

After running that line of code, b loses its original value of 4, because you're assigning it to the middle return value from the function (ie G ).

So, presumably the problem is that b is an inappropriate value when the function runs a second time. (I don't know anything about numpy, so I can't address the error message specifically.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM