def sample_531_1(): """ 5.3.1_1 绘制股票的收益,及收益波动情况 demo list :return: """ # 示例序列 demo_list = np.array([2, 4, 16, 20]) # 以三天为周期计算波动 demo_window = 3 # pd.rolling_std * np.sqrt print('pd.rolling_std(demo_list, window=demo_window, center=False) * np.sqrt(demo_window):\n', pd_rolling_std(demo_list, window=demo_window, center=False) * np.sqrt(demo_window)) print('pd.Series([2, 4, 16]).std() * np.sqrt(demo_window):', pd.Series([2, 4, 16]).std() * np.sqrt(demo_window)) print('pd.Series([4, 16, 20]).std() * np.sqrt(demo_window):', pd.Series([4, 16, 20]).std() * np.sqrt(demo_window)) print('np.sqrt(pd.Series([2, 4, 16]).var() * demo_window):', np.sqrt(pd.Series([2, 4, 16]).var() * demo_window))
def sample_531_1(): """ 5.3.1_1 绘制股票的收益,及收益波动情况 demo list :return: """ # 示例序列 demo_list = np.array([2, 4, 16, 20]) # 以三天为周期计算波动 demo_window = 3 # pd.rolling_std * np.sqrt print('pd.rolling_std(demo_list, window=demo_window, center=False) * np.sqrt(demo_window):\n', pd_rolling_std(demo_list, window=demo_window, center=False) * np.sqrt(demo_window)) print('pd.Series([2, 4, 16]).std() * np.sqrt(demo_window):', pd.Series([2, 4, 16]).std() * np.sqrt(demo_window)) print('pd.Series([4, 16, 20]).std() * np.sqrt(demo_window):', pd.Series([4, 16, 20]).std() * np.sqrt(demo_window)) print('np.sqrt(pd.Series([2, 4, 16]).var() * demo_window):', np.sqrt(pd.Series([2, 4, 16]).var() * demo_window))
def sample_531_2(): """ 5.3.1_2 绘制股票的收益,及收益波动情况 :return: """ tsla_df_copy = tsla_df.copy() # 投资回报 tsla_df_copy['return'] = np.log(tsla_df['close'] / tsla_df['close'].shift(1)) # 移动收益标准差 tsla_df_copy['mov_std'] = pd_rolling_std(tsla_df_copy['return'], window=20, center=False) * np.sqrt(20) # 加权移动收益标准差,与移动收益标准差基本相同,只不过根据时间权重计算std tsla_df_copy['std_ewm'] = pd_ewm_std(tsla_df_copy['return'], span=20, min_periods=20, adjust=True) * np.sqrt(20) tsla_df_copy[['close', 'mov_std', 'std_ewm', 'return']].plot(subplots=True, grid=True) plt.show()
def sample_531_2(): """ 5.3.1_2 绘制股票的收益,及收益波动情况 :return: """ tsla_df_copy = tsla_df.copy() # 投资回报 tsla_df_copy['return'] = np.log(tsla_df['close'] / tsla_df['close'].shift(1)) # 移动收益标准差 tsla_df_copy['mov_std'] = pd_rolling_std(tsla_df_copy['return'], window=20, center=False) * np.sqrt(20) # 加权移动收益标准差,与移动收益标准差基本相同,只不过根据时间权重计算std tsla_df_copy['std_ewm'] = pd_ewm_std(tsla_df_copy['return'], span=20, min_periods=20, adjust=True) * np.sqrt(20) tsla_df_copy[['close', 'mov_std', 'std_ewm', 'return']].plot(subplots=True, grid=True) plt.show()