用上证50做蒙特卡洛模拟分析有效前沿
出现了如下错误:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
C:\Users\ADMINI~1\AppData\Local\Temp/ipykernel_8100/1740976838.py in <module>
----> 1 PORT_WEIGHTS,PORT_RETURNS,PORT_SIGMAS,PORT_SR = montecarlo_portfolios(SH50_CODE_LIST,PORT_NUM,START_DATE,END_DATE,RF)
C:\Users\ADMINI~1\AppData\Local\Temp/ipykernel_8100/2484461405.py in montecarlo_portfolios(stock_list, number, start_date, end_date, risk_free, trade_days)
10 weights_i_array = np.random.random(len(stock_list))
11 weights_i_array /=np.sum(weights_i_array)
---> 12 port_i_year_return,port_i_year_sigma,port_i_year_sr = get_return_risk(weights_i_array,his_prices_df,risk_free)
13 port_weights_list.append(weights_i_array)
14 port_returns_list.append(port_i_year_return)
C:\Users\ADMINI~1\AppData\Local\Temp/ipykernel_8100/3548710514.py in get_return_risk(port_i_weights_array, his_prices_df, risk_free, trade_days)
1 def get_return_risk(port_i_weights_array,his_prices_df,risk_free,trade_days=250):
2 his_day_returns = np.log(his_prices_df/his_prices_df.shift(-1))
----> 3 port_i_year_return = np.sum(his_day_returns.mean()*trade_days*port_i_weights_array)
4 port_i_year_sigma = np.sqrt(np.dot(port_i_weights_array,np.dot(his_day_returns.cov()*trade_days,port_i_weights_array.T)))
5 port_i_year_sr=(port_i_year_return-risk_free)/port_i_year_sigma
D:\p\lib\site-packages\pandas\core\ops\common.py in new_method(self, other)
67 other = item_from_zerodim(other)
68
---> 69 return method(self, other)
70
71 return new_method
D:\p\lib\site-packages\pandas\core\arraylike.py in __mul__(self, other)
106 @unpack_zerodim_and_defer("__mul__")
107 def __mul__(self, other):
--> 108 return self._arith_method(other, operator.mul)
109
110 @unpack_zerodim_and_defer("__rmul__")
D:\p\lib\site-packages\pandas\core\series.py in _arith_method(self, other, op)
5526 result = ops.arithmetic_op(lvalues, rvalues, op)
5527
-> 5528 return self._construct_result(result, name=res_name)
5529
5530
D:\p\lib\site-packages\pandas\core\series.py in _construct_result(self, result, name)
2943 # We do not pass dtype to ensure that the Series constructor
2944 # does inference in the case where `result` has object-dtype.
-> 2945 out = self._constructor(result, index=self.index)
2946 out = out.__finalize__(self)
2947
D:\p\lib\site-packages\pandas\core\series.py in __init__(self, data, index, dtype, name, copy, fastpath)
428 index = ibase.default_index(len(data))
429 elif is_list_like(data):
--> 430 com.require_length_match(data, index)
431
432 # create/copy the manager
D:\p\lib\site-packages\pandas\core\common.py in require_length_match(data, index)
529 """
530 if len(data) != len(index):
--> 531 raise ValueError(
532 "Length of values "
533 f"({len(data)}) "
ValueError: Length of values (50) does not match length of index (1)