AssayingAnomalies 0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of AssayingAnomalies might be problematic. Click here for more details.

Files changed (54) hide show
  1. AssayingAnomalies/EP_2013.py +102 -0
  2. AssayingAnomalies/Functions/Gibbs.py +370 -0
  3. AssayingAnomalies/Functions/__init__.py +41 -0
  4. AssayingAnomalies/Functions/assignToPtf.py +49 -0
  5. AssayingAnomalies/Functions/calcPtfRets.py +146 -0
  6. AssayingAnomalies/Functions/calcTcosts.py +109 -0
  7. AssayingAnomalies/Functions/estFactorRegs.py +206 -0
  8. AssayingAnomalies/Functions/fill_months.py +36 -0
  9. AssayingAnomalies/Functions/getCRSPDailyData.py +0 -0
  10. AssayingAnomalies/Functions/getCRSPData.py +75 -0
  11. AssayingAnomalies/Functions/getCompustatData.py +81 -0
  12. AssayingAnomalies/Functions/getFFDailyFactors.py +162 -0
  13. AssayingAnomalies/Functions/getFFFactors.py +170 -0
  14. AssayingAnomalies/Functions/getFredData.py +80 -0
  15. AssayingAnomalies/Functions/grs_test_p.py +83 -0
  16. AssayingAnomalies/Functions/makeAbdiRanaldi.py +92 -0
  17. AssayingAnomalies/Functions/makeBetas.py +117 -0
  18. AssayingAnomalies/Functions/makeBivSortInd.py +140 -0
  19. AssayingAnomalies/Functions/makeCOMPUSTATDerivedVariables.py +430 -0
  20. AssayingAnomalies/Functions/makeCOMPUSTATVariables.py +95 -0
  21. AssayingAnomalies/Functions/makeCRSPDailyData.py +73 -0
  22. AssayingAnomalies/Functions/makeCRSPDailyDerivedVariables.py +495 -0
  23. AssayingAnomalies/Functions/makeCRSPDerivedVariables.py +206 -0
  24. AssayingAnomalies/Functions/makeCRSPMonthlyData.py +101 -0
  25. AssayingAnomalies/Functions/makeCorwinSchultz.py +158 -0
  26. AssayingAnomalies/Functions/makeFF10Indus.py +108 -0
  27. AssayingAnomalies/Functions/makeFF17Indus.py +279 -0
  28. AssayingAnomalies/Functions/makeFF49Indus.py +346 -0
  29. AssayingAnomalies/Functions/makeGibbs.py +80 -0
  30. AssayingAnomalies/Functions/makeIndustryClassifications.py +33 -0
  31. AssayingAnomalies/Functions/makeIndustryReturns.py +62 -0
  32. AssayingAnomalies/Functions/makeKyleObizhaeva.py +112 -0
  33. AssayingAnomalies/Functions/makeNovyMarxVelikovAnomalies.py +369 -0
  34. AssayingAnomalies/Functions/makePastPerformance.py +110 -0
  35. AssayingAnomalies/Functions/makeTradingCosts.py +69 -0
  36. AssayingAnomalies/Functions/makeUnivSortInd.py +105 -0
  37. AssayingAnomalies/Functions/makeUniverses.py +147 -0
  38. AssayingAnomalies/Functions/mergeCRSPCOMP.py +190 -0
  39. AssayingAnomalies/Functions/prt_sort_results.py +91 -0
  40. AssayingAnomalies/Functions/rank_data.py +149 -0
  41. AssayingAnomalies/Functions/rank_with_nan.py +25 -0
  42. AssayingAnomalies/Functions/remote_get_compustat_data.py +138 -0
  43. AssayingAnomalies/Functions/remote_get_crsp_data.py +125 -0
  44. AssayingAnomalies/Functions/remote_get_daily_crsp.py +90 -0
  45. AssayingAnomalies/Functions/runBivSort.py +146 -0
  46. AssayingAnomalies/Functions/runUnivSort.py +168 -0
  47. AssayingAnomalies/__init__.py +2 -0
  48. AssayingAnomalies/config.py +57 -0
  49. AssayingAnomalies/wrds_utilities/__init__.py +1 -0
  50. AssayingAnomalies/wrds_utilities/utilities.py +122 -0
  51. AssayingAnomalies-0.1.dist-info/METADATA +7 -0
  52. AssayingAnomalies-0.1.dist-info/RECORD +54 -0
  53. AssayingAnomalies-0.1.dist-info/WHEEL +5 -0
  54. AssayingAnomalies-0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,102 @@
1
+ import AssayingAnomalies.Functions as aa
2
+ from AssayingAnomalies.Functions import estFactorRegs
3
+ import numpy as np
4
+ import pandas as pd
5
+ import matplotlib.pyplot as plt
6
+ import scipy.io
7
+ import os
8
+ from AssayingAnomalies import Config
9
+
10
+
11
+ params = Config()
12
+ params.prompt_user()
13
+ params.make_folders()
14
+ path = r"C:\Users\josh\OneDrive - University at Buffalo\Desktop\Spring_2023\AssayingAnomalies-main\AssayingAnomalies-main\Data" + os.sep
15
+
16
+
17
+ raw_data = pd.read_csv(r'C:\Users\josh\Downloads\OK_portfolios.csv', index_col=0)
18
+ plt.close()
19
+ fig, ax = plt.subplots(1, 1)
20
+ ax.plot(raw_data.index, raw_data.OMK)
21
+ ax.set(ylabel='OMK', xlabel='Date')
22
+
23
+ # estimate factor regs of OMK portfolios on the FF5 factors
24
+ ff = pd.read_csv(r'C:\Users\josh\OneDrive - University at Buffalo\Desktop\Spring_2023\AA_Test_Data\AA_Data\CRSP\ff.csv', index_col=0)
25
+
26
+ dates = np.array(raw_data.index)
27
+ test = aa.estFactorRegs(params=params, pret=np.array(raw_data), dates=dates, factorModel=5, addLongShort=0)
28
+ test['w'] = 'v'
29
+ test['hperiod'] = 1
30
+ aa.prt_sort_results(test)
31
+
32
+ # Test against RMW without CMA (investment)
33
+ factors = ff[['mkt', 'smb', 'hml', 'rmw']]
34
+ factors.index = ff.dates
35
+ test2 = estFactorRegs(params, np.array(raw_data), dates, factorModel=factors, addLongShort=0)
36
+ test2['w'] = 'v'
37
+ test2['hperiod'] = 1
38
+ aa.prt_sort_results(test2)
39
+
40
+ def to_latex_table(text):
41
+ lines = text.split('\n')
42
+ headers = [''] + lines[4].split()[1:]
43
+ latex_table = []
44
+
45
+ latex_table.append('\\begin{table}[ht]')
46
+ latex_table.append('\\centering')
47
+ latex_table.append('\\begin{tabular}{|l|' + 'r|' * len(headers) + '}')
48
+
49
+ # Header row
50
+ latex_table.append('\\hline')
51
+ header_row = ' & '.join(headers) + ' \\\\'
52
+ latex_table.append(header_row)
53
+ latex_table.append('\\hline')
54
+
55
+ # Content rows
56
+ for i in range(5, len(lines) - 2, 2):
57
+ row_data = lines[i].split()
58
+ row_values = ' & '.join(row_data) + ' \\\\'
59
+ latex_table.append(row_values)
60
+
61
+ if i + 1 < len(lines) - 2: # Check if there are significance values
62
+ sig_values = lines[i + 1].split()
63
+ sig_row = ' & '.join([''] + sig_values) + ' \\\\'
64
+ latex_table.append(sig_row)
65
+
66
+ latex_table.append('\\hline')
67
+ latex_table.append('\\end{tabular}')
68
+ latex_table.append('\\caption{Value-weighted portfolio sort, 1-month holding period: Excess returns, alphas, and loadings on the Fama and French 5-factor model.}')
69
+ latex_table.append('\\label{tab:my_label}')
70
+ latex_table.append('\\end{table}')
71
+
72
+ return '\n'.join(latex_table)
73
+
74
+ testing = to_latex_table(text)
75
+
76
+ # Test against Roberts profitability
77
+ factors = ff[['mkt', 'smb', 'hml', 'roberts']]
78
+
79
+
80
+ # from AssayingAnomalies.Functions.makeBivSortInd import makeBivSortInd
81
+ #
82
+ xsga = scipy.io.loadmat(path + 'COMPUSTAT' + os.sep + 'XSGA.mat')['XSGA']
83
+ assets = scipy.io.loadmat(path + 'COMPUSTAT' + os.sep + 'AT.mat')['AT']
84
+ dates = scipy.io.loadmat(path + os.sep + 'CRSP' + os.sep + 'dates.mat')['dates']
85
+ dates = dates.flatten()
86
+
87
+ # initialize O_0 = SGA_0/(0.10 + 0.15)
88
+ O_0 =
89
+
90
+ R = scipy.io.loadmat(path + 'R.mat')['R']
91
+ # # R = pd.read_csv(path + 'R.csv', index_col=0)
92
+ # me = scipy.io.loadmat(path + 'me.mat')['me']
93
+ # NYSE = scipy.io.loadmat(path + 'NYSE.mat')['NYSE']
94
+ # ind1 = makeBivSortInd(me, 5, R, 5)
95
+ # ret = scipy.io.loadmat(path + 'ret.mat')['ret']
96
+ # test_res1, test_cond_res1 = runBivSort(params=params, ret=ret, ind=ind1, nptf1=5, nptf2=5, dates=dates, mcap=me)
97
+ #
98
+ # ind2 = makeBivSortInd(me, 2, R, [30, 70])
99
+ # test_res2, test_cond_res2 = runBivSort(params=params, ret=ret, ind=ind2, nptf1=3, nptf2=2, dates=dates, mcap=me)
100
+ #
101
+ # ind3 = makeBivSortInd(me, 5, R, 5, sort_type='conditional')
102
+ # test_res3, test_cond_res3 = runBivSort(params=params, ret=ret, ind=ind3, nptf1=5, nptf2=5, dates=dates, mcap=me)
@@ -0,0 +1,370 @@
1
+ import numpy as np
2
+ from scipy.stats import truncnorm, multivariate_normal
3
+ from scipy.linalg import sqrtm
4
+
5
+ def q_draw(p, q, c, varu, print_level):
6
+ # Check if the lengths of p and q are equal. If not, raise an error.
7
+ if len(p) != len(q):
8
+ raise ValueError("p and q are of different lengths.")
9
+
10
+ # Check if c and varu are scalar values. If not, raise an error.
11
+ if not np.isscalar(c) or not np.isscalar(varu):
12
+ raise ValueError("c and varu should be scalars.")
13
+
14
+ # Create a boolean array where True indicates non-zero elements in q.
15
+ q_nonzero = q != 0
16
+
17
+ # Duplicate each element in p and q to create p2 and q_double, both are 2D arrays.
18
+ p2 = np.tile(p, (2, 1)).T
19
+ q_double = np.tile(q, (2, 1)).T
20
+
21
+ # Define a constant to determine how many elements to skip in the loop.
22
+ n_skip = 2
23
+
24
+ # Create an array where each element is the remainder of division by n_skip.
25
+ mod_p = np.mod(np.arange(len(p)), n_skip)
26
+
27
+ # Calculate u for all pairs in q_double:
28
+ # cq is the product of cost parameter c and q_double.
29
+ # v is the difference between each pair of prices in p2 and cq.
30
+ # u is the difference between consecutive elements in v.
31
+ cq = c * q_double
32
+ v = p2 - cq
33
+ u = v[1:] - v[:-1]
34
+
35
+ # Compute s for each time step:
36
+ # s is the squared elements of u divided by twice the variance varu.
37
+ s = (u ** 2) / (2 * varu)
38
+
39
+ # Extend s to have the same length as p:
40
+ # Append zeros to the bottom of s to match the length of p2.
41
+ s_extended = np.vstack([s, np.zeros((len(p2) - len(s), 2))])
42
+
43
+ # Calculate s_sum_all:
44
+ # This involves a complex reshaping and addition of s_extended to itself.
45
+ s_sum_all = np.vstack((s_extended[:, 0], np.zeros(len(p2)))).T + np.vstack((np.zeros(len(p2)), s_extended[:, 1])).T
46
+
47
+ # Iterate over each skip interval (0 and 1 in this case).
48
+ for i_start in range(n_skip):
49
+ if print_level > 0:
50
+ # Print the current skip interval for debugging.
51
+ print(f"qDraw. iStart: {i_start}")
52
+
53
+ # k is a boolean array where True corresponds to elements in mod_p equal to i_start.
54
+ # jnz contains indices where both k is True and q is non-zero.
55
+ k = mod_p == i_start
56
+ jnz = np.where(k & q_nonzero)[0]
57
+
58
+ if len(jnz) > 0:
59
+ # Select relevant rows from s_sum_all:
60
+ # For each index in jnz, select the corresponding row in s_sum_all.
61
+ s_sum = s_sum_all[jnz, :]
62
+
63
+ # Calculate log odds:
64
+ # log_odds is the difference between the second and first column of s_sum.
65
+ log_odds = s_sum[:, 1] - s_sum[:, 0]
66
+
67
+ # Adjust log odds to avoid overflow in the exp function.
68
+ log_okay = log_odds < 500
69
+ odds = np.exp(log_odds * log_okay)
70
+
71
+ # Calculate the probability of buying (p_buy):
72
+ # It is the odds divided by the sum of odds and 1, adjusted by log_okay.
73
+ p_buy = odds / (1 + odds)
74
+ p_buy = p_buy * log_okay
75
+
76
+ # Generate random uniform values and calculate qknz:
77
+ # qknz is an updated value of q based on whether the random value is greater than p_buy.
78
+ ru = np.random.uniform(size=len(p_buy))
79
+ qknz = 1 - 2 * (ru > p_buy)
80
+
81
+ # Update the elements of q at indices jnz with qknz.
82
+ q[jnz] = qknz
83
+
84
+ # Return the updated q array.
85
+ return q
86
+
87
+
88
+ def q_draw_vec(p, q, c, varu, print_level):
89
+ # Validate the lengths of the input arrays
90
+ if len(p) != len(q):
91
+ raise ValueError("p and q are of different lengths.")
92
+
93
+ # Check that c and varu are either scalars or arrays of appropriate lengths
94
+ if not (np.isscalar(c) or len(c) == len(p)) or not (np.isscalar(varu) or len(varu) == len(p) - 1):
95
+ raise ValueError("Invalid dimensions for c or varu.")
96
+
97
+ # Create a boolean array indicating where q is not zero
98
+ q_nonzero = q != 0
99
+
100
+ # Duplicate the price array p and the trade direction array q
101
+ p2 = np.tile(p, (2, 1)).T
102
+ q_double = np.tile(q, (2, 1)).T
103
+
104
+ # Define a constant for the number of elements to skip in the loop
105
+ n_skip = 2
106
+
107
+ # Create an array for modulo calculations to determine the update pattern
108
+ mod_p = np.mod(np.arange(len(p)), n_skip)
109
+
110
+ for i_start in range(n_skip):
111
+ # Print the current iteration for debugging if print_level is greater than 0
112
+ if print_level > 0:
113
+ print(f"qDrawVec. iStart: {i_start}")
114
+
115
+ # Calculate indices for updating q based on the current iteration and nonzero elements in q
116
+ k = mod_p == i_start
117
+ jnz = np.where(k & q_nonzero)[0]
118
+
119
+ if len(jnz) > 0:
120
+ # Update the elements of q_double to be alternately 1 and -1 for the indices in jnz
121
+ q_double[jnz, 0] = 1
122
+ q_double[jnz, 1] = -1
123
+
124
+ # Calculate cq based on whether c is a scalar or a vector
125
+ if np.isscalar(c):
126
+ cq = c * q_double
127
+ else:
128
+ c2 = np.vstack((c, c)).T
129
+ cq = c2 * q_double
130
+
131
+ # Compute the difference between doubled prices and cq
132
+ v = p2 - cq
133
+ u = v[1:] - v[:-1]
134
+
135
+ # Calculate s based on whether varu is a scalar or a vector
136
+ if np.isscalar(varu):
137
+ s = (u ** 2) / (2 * varu)
138
+ else:
139
+ varu2 = 2 * np.vstack((varu, varu)).T
140
+ s = (u ** 2) / varu2
141
+
142
+ # Extend s to have the same length as p
143
+ s_extended = np.vstack([s, np.zeros((len(p2) - len(s), 2))])
144
+
145
+ # Calculate s_sum_all by combining s_extended with itself
146
+ s_sum_all = np.vstack((s_extended[:, 0], np.zeros(len(p2)))).T + np.vstack(
147
+ (np.zeros(len(p2)), s_extended[:, 1])).T
148
+
149
+ # Select the relevant rows from s_sum_all
150
+ s_sum = s_sum_all[jnz, :]
151
+ log_odds = s_sum[:, 1] - s_sum[:, 0]
152
+
153
+ # Adjust log odds to avoid overflow and calculate the odds
154
+ log_okay = log_odds < 500
155
+ odds = np.exp(log_odds * log_okay)
156
+
157
+ # Calculate the probability of buying and adjust it based on log_okay
158
+ p_buy = odds / (1 + odds)
159
+ p_buy = p_buy * log_okay
160
+
161
+ # Generate random uniform values and calculate qknz
162
+ ru = np.random.uniform(size=len(p_buy))
163
+ qknz = 1 - 2 * (ru > p_buy)
164
+
165
+ # Update q at the indices specified in jnz
166
+ q[jnz] = qknz
167
+
168
+ # Return the updated q array
169
+ return q
170
+
171
+
172
+ def bayes_regression_update(prior_mu, prior_cov, y, X, d_var):
173
+ if prior_mu.shape[1] != 1:
174
+ raise ValueError("priorMu should be a column vector")
175
+ if X.shape[0] < X.shape[1]:
176
+ raise ValueError("X has fewer rows than columns")
177
+ if X.shape[0] != y.shape[0] or y.shape[1] != 1:
178
+ raise ValueError("Dimensions of X and y are not compatible")
179
+ if prior_mu.shape[0] != X.shape[1]:
180
+ raise ValueError("priorMu and X are not conformable")
181
+ if prior_cov.shape[0] != prior_cov.shape[1] or prior_cov.shape[0] != prior_mu.shape[0]:
182
+ raise ValueError("Dimensions of priorCov are not compatible with priorMu")
183
+
184
+ cov_inv = np.linalg.inv(prior_cov)
185
+ Di = (1 / d_var) * np.dot(X.T, X) + cov_inv
186
+ D = np.linalg.inv(Di)
187
+ dd = (1 / d_var) * np.dot(X.T, y) + np.dot(cov_inv, prior_mu)
188
+ post_mu = np.dot(D, dd)
189
+ post_cov = D
190
+
191
+ return post_mu, post_cov
192
+
193
+
194
+ def bayes_variance_update(prior_alpha, prior_beta, u):
195
+ """
196
+ Updates the posterior alpha and beta parameters for an inverted gamma distribution.
197
+
198
+ Parameters:
199
+ prior_alpha (float): The prior alpha parameter of the inverted gamma distribution.
200
+ prior_beta (float): The prior beta parameter of the inverted gamma distribution.
201
+ u (numpy.ndarray): Vector of estimated disturbances.
202
+
203
+ Returns:
204
+ post_alpha (float): Updated posterior alpha parameter.
205
+ post_beta (float): Updated posterior beta parameter.
206
+ """
207
+
208
+ # Update the posterior alpha parameter
209
+ post_alpha = prior_alpha + len(u) / 2
210
+
211
+ # Update the posterior beta parameter
212
+ post_beta = prior_beta + np.sum(u ** 2) / 2
213
+
214
+ return post_alpha, post_beta
215
+
216
+
217
+ def rand_std_norm_t(zlow, zhigh):
218
+ PROBNLIMIT = 6
219
+ eps = 1e-30 # A small epsilon value
220
+
221
+ if zlow == float('-inf') and zhigh == float('inf'):
222
+ return np.random.normal()
223
+ if zlow > PROBNLIMIT and (zhigh == float('inf') or zhigh > PROBNLIMIT):
224
+ return zlow + 100 * eps
225
+ if zhigh < -PROBNLIMIT and (zlow == float('-inf') or zlow < -PROBNLIMIT):
226
+ return zhigh - 100 * eps
227
+
228
+ a, b = zlow, zhigh
229
+ if zlow == float('-inf'):
230
+ a = -np.inf
231
+ if zhigh == float('inf'):
232
+ b = np.inf
233
+
234
+ return truncnorm.rvs(a, b, loc=0, scale=1)
235
+
236
+
237
+ def mvnrnd_t(mu, cov, v_lower, v_upper):
238
+ f = sqrtm(cov)
239
+ n = np.prod(mu.shape)
240
+ eta = np.zeros(n)
241
+
242
+ for k in range(n):
243
+ etasum = np.dot(f[k, :k], eta[:k])
244
+ low = (v_lower[k] - mu[k] - etasum) / f[k, k]
245
+ high = (v_upper[k] - mu[k] - etasum) / f[k, k]
246
+ eta[k] = rand_std_norm_t(low, high)
247
+
248
+ return mu + np.dot(f, eta)
249
+
250
+
251
+ def roll_gibbs_beta(p, pm, q, n_sweeps, reg_draw, varu_draw, q_draw_bool, varu_start, c_start, beta_start, print_level):
252
+ """
253
+ Perform Gibbs sampling to estimate parameters in the Roll model.
254
+
255
+ Parameters:
256
+ p (numpy.ndarray): Vector of trade prices.
257
+ pm (numpy.ndarray): Vector of mid prices.
258
+ q (numpy.ndarray): Vector of trade directions.
259
+ n_sweeps (int): Number of Gibbs sampling iterations.
260
+ reg_draw (bool): Flag to perform regression draw.
261
+ varu_draw (bool): Flag to perform variance draw.
262
+ q_draw_bool (bool): Flag to perform q draw.
263
+ varu_start (float): Initial value of variance.
264
+ c_start (float): Initial value of cost parameter c.
265
+ beta_start (float): Initial value of beta.
266
+ print_level (int): Verbosity level for printing diagnostics.
267
+
268
+ Returns:
269
+ numpy.ndarray: Output matrix with parameters from each sweep. Columns are c, beta, and varu.
270
+ """
271
+ n_obs = len(p)
272
+
273
+ # Check for length mismatch
274
+ if len(q) != n_obs or len(pm) != n_obs:
275
+ print('RollGibbsBeta length mismatch')
276
+ return None
277
+
278
+ # Calculate price change
279
+ dp = p[1:] - p[:-1]
280
+
281
+ # Initialize q based on price sign changes if required
282
+ if q_draw_bool:
283
+ q_initial = np.sign(dp)
284
+ q_initial = np.append(q_initial, 1) # Extend to match length of q
285
+ q = np.where(q != 0, q_initial, q)
286
+
287
+ # Initialize variance, cost, and beta parameters
288
+ varu = max(varu_start, 0.001)
289
+ c = max(c_start, 0.01)
290
+ beta = max(beta_start, 1)
291
+
292
+ # Output matrix initialization
293
+ parm_out = np.zeros((n_sweeps, 3))
294
+
295
+ for sweep in range(n_sweeps):
296
+ # Calculate changes in trade directions and mid prices
297
+ dq = q[1:] - q[:-1]
298
+ dpm = pm[1:] - pm[:-1]
299
+
300
+ # Perform regression draw if enabled
301
+ if reg_draw:
302
+ prior_mu = np.array([[0], [1]]) # Prior mean
303
+ prior_cov = np.diag([1, 2]) # Prior covariance
304
+ X = np.column_stack((dq, dpm)) # Design matrix
305
+ post_mu, post_cov = bayes_regression_update(prior_mu, prior_cov, dp.reshape(-1, 1), X, varu)
306
+ coeff_lower = np.array([0, float('-inf')])
307
+ coeff_upper = np.array([float('inf'), float('inf')])
308
+ coeff_draw = mvnrnd_t(post_mu.flatten(), post_cov, coeff_lower, coeff_upper)
309
+ c, beta = coeff_draw[0], coeff_draw[1] # Extract c and beta
310
+
311
+ # Perform variance draw if enabled
312
+ if varu_draw:
313
+ u = dp - c * dq[:len(dp)] - beta * dpm[:len(dp)] # Calculate disturbances
314
+ prior_alpha = 1e-12
315
+ prior_beta = 1e-12
316
+ post_alpha, post_beta = bayes_variance_update(prior_alpha, prior_beta, u)
317
+ varu = 1 / np.random.gamma(post_alpha, 1 / post_beta)
318
+
319
+ # Update q if required
320
+ if q_draw_bool:
321
+ p2 = p - beta * pm
322
+ q = q_draw(p2, q, c, varu, 0)
323
+
324
+ # Store parameters in output array
325
+ parm_out[sweep, :] = [c, beta, varu]
326
+
327
+ return parm_out
328
+
329
+ #
330
+ # "Testing bayes_regression_update and roll_gibbs_beta"
331
+ # # Example test data
332
+ # np.random.seed(0) # for reproducibility
333
+ # n_samples = 100
334
+ # n_features = 2
335
+ #
336
+ # X_test = np.random.randn(n_samples, n_features) # Design matrix
337
+ # y_test = np.random.randn(n_samples, 1) * 0.5 # Dependent variable with some noise
338
+ #
339
+ # prior_mu_test = np.zeros((n_features, 1)) # Prior mean (zero)
340
+ # prior_cov_test = np.eye(n_features) # Prior covariance (identity matrix)
341
+ # d_var_test = 0.5 # Variance of error
342
+ #
343
+ # # Run bayes_regression_update
344
+ # post_mu, post_cov = bayes_regression_update(prior_mu_test, prior_cov_test, y_test, X_test, d_var_test)
345
+ #
346
+ # # Print or inspect the results
347
+ # print("Posterior Mean (post_mu):", post_mu)
348
+ # print("Posterior Covariance (post_cov):", post_cov)
349
+ #
350
+ # # Example test data for roll_gibbs_beta
351
+ # p_test = np.random.normal(size=100)
352
+ # pm_test = np.random.normal(size=100)
353
+ # q_test = np.random.choice([-1, 1], size=100)
354
+ #
355
+ # # Parameters for the Gibbs sampler
356
+ # n_sweeps_test = 1000
357
+ # reg_draw_test = True
358
+ # varu_draw_test = True
359
+ # q_draw_test = True
360
+ # varu_start_test = 0.001
361
+ # c_start_test = 0.01
362
+ # beta_start_test = 1
363
+ # print_level_test = 1
364
+ #
365
+ # # Run roll_gibbs_beta
366
+ # results = roll_gibbs_beta(p_test, pm_test, q_test, n_sweeps_test, reg_draw_test, varu_draw_test, q_draw_test, varu_start_test, c_start_test, beta_start_test, print_level_test)
367
+ #
368
+ # # Inspect results
369
+ # print("Results from RollGibbsBeta:", results)
370
+ #
@@ -0,0 +1,41 @@
1
+ from .assignToPtf import assignToPtf
2
+ from .calcPtfRets import calcPtfRets
3
+ from .calcTcosts import calcTcosts
4
+ # from .create_pgpass_file import create_pgpass_file
5
+ from .estFactorRegs import estFactorRegs
6
+ from .fill_months import fill_months
7
+ from .getCompustatData import getCOMPUSTATData
8
+ from .getCRSPData import getCRSPData
9
+ from .getFFDailyFactors import getFFDailyFactors
10
+ from .getFFFactors import getFFFactors
11
+ from .getFredData import getFredData
12
+ from .Gibbs import *
13
+ from .grs_test_p import grs_test_p
14
+ from .makeAbdiRanaldi import makeAbdiRanaldi
15
+ from .makeBetas import makeBetas
16
+ from .makeCOMPUSTATDerivedVariables import makeCOMPUSTATDerivedVariables
17
+ from .makeCOMPUSTATVariables import makeCOMPUSTATVariables
18
+ from .makeCorwinSchultz import makeCorwinSchultz
19
+ from .makeCRSPDailyData import makeCRSPDailyData
20
+ from .makeCRSPDailyDerivedVariables import makeCRSPDailyDerivedVariables
21
+ from .makeCRSPDerivedVariables import makeCRSPDerivedVariables
22
+ from .makeCRSPMonthlyData import makeCRSPMonthlyData
23
+ from .makeFF10Indus import makeFF10Indus
24
+ from .makeFF17Indus import makeFF17Indus
25
+ from .makeFF49Indus import makeFF49Indus
26
+ from .makeGibbs import makeGibbs
27
+ from .makeIndustryReturns import makeIndustryReturns
28
+ from .makeIndustryClassifications import makeIndustryClassifications
29
+ from .makeKyleObizhaeva import makeKyleObizhaeva
30
+ from .makePastPerformance import makePastPerformance
31
+ from .makeUniverses import makeUniverses
32
+ from .makeUnivSortInd import makeUnivSortInd
33
+ from .makeBivSortInd import makeBivSortInd
34
+ from .mergeCRSPCOMP import mergeCRSPCOMP
35
+ from .prt_sort_results import prt_sort_results
36
+ from .rank_with_nan import rank_with_nan
37
+ from .remote_get_compustat_data import remote_get_compustat_data
38
+ from .remote_get_crsp_data import remote_get_crsp_data
39
+ from .remote_get_daily_crsp import remote_get_daily_crsp
40
+ from .runUnivSort import runUnivSort
41
+ from .runBivSort import runBivSort
@@ -0,0 +1,49 @@
1
+ import numpy as np
2
+
3
+
4
+ def assignToPtf(x, bPtsMat):
5
+ """
6
+ Function that assigns each firm-month to the bin it belongs to in the
7
+ particular month. It assigns a zero if a firm-month is not held in any
8
+ portfolio.
9
+
10
+ Parameters
11
+ ----------
12
+ x : numpy array or pandas DataFrame
13
+ Matrix based on which we want to assign the bins.
14
+ bPtsMat : numpy array
15
+ A matrix with the breakpoints (values) for each time period.
16
+ e.g. np.nanpercentile(me, np.linspace(0, 100, 5), axis=1).T
17
+
18
+ Returns
19
+ -------
20
+ ind : numpy array
21
+ A matrix that indicates the bin each stock-time is in.
22
+ """
23
+
24
+ # Store several dimensions
25
+ nStocks = x.shape[1]
26
+ nPeriods = x.shape[0]
27
+ nBPoints = bPtsMat.shape[1]
28
+
29
+ # Create a matrix with the same dimensions as x
30
+ ind = np.zeros((nPeriods, nStocks))
31
+
32
+ # Assign the indicator for the first portfolio
33
+ bPtsPtfOne = bPtsMat[:, 0]
34
+ rptdBPtsPtfOne = np.repeat(bPtsPtfOne[:, np.newaxis], nStocks, axis=1)
35
+ ind[x < rptdBPtsPtfOne] = 1
36
+
37
+ # Repeat the same for all the other breakpoints
38
+ for j in range(1, nBPoints + 1):
39
+ bPtsPtfJ = bPtsMat[:, j - 1]
40
+ rptdBPtsPtfJ = np.repeat(bPtsPtfJ[:, np.newaxis], nStocks, axis=1)
41
+ ind[x >= rptdBPtsPtfJ] = j + 1
42
+
43
+ return ind
44
+
45
+
46
+ # saveFolder = r'/home/jlaws13/PycharmProjects/AssayingAnomalies_root/Data/CRSP/'
47
+ # me = pd.read_csv(saveFolder + 'me.csv', index_col=0).astype(float)
48
+ # test_bpts = np.nanpercentile(me, np.linspace(0, 100, 5), axis=1).T
49
+ # test_ind = assignToPtf(me, test_bpts)