%matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt #stock_data df_1 = pd.read_csv('stock_data.csv') df_1 #篩選出2021年度數據 df_1=df_1[df_1['TIME']>='2021-02-01'] df_1.reset_index(drop=True, inplace=True) df_1 #計算stock_data日報酬 df_1['日報酬'] = '' for i in range(1,len(df_1)): df_1['日報酬'][i] = df_1['CLOSE'][i]/df_1['CLOSE'][i-1]-1 df_1['1+日報酬'] = '' for i in range(1,len(df_1)): df_1['1+日報酬'][i] = df_1['日報酬'][i]+1 df_1['相乘'] = '' a = 1 for i in range(1,len(df_1)): a *= df_1['1+日報酬'][i] df_1['相乘'][i] = a def time(df): df['TIME'] = pd.to_datetime(df['TIME']) df=df.set_index(df.TIME) return df df_1=time(df_1) #相乘 累積報酬,畫圖畫出曲線變化 df_1 #匯入RL訓練出來的結果 rl_1 =pd.read_csv('1.csv') rl_1 rl_2 = df_1.copy() rl_2 #計算stock_data日報酬 rl_2['rl_reward'] = '' for i in range(224): rl_2['rl_reward'][i] = rl_1.reward[i] rl_2 rl_2['1+rl日報酬'] = '' for i in range(0,len(rl_2)): rl_2['1+rl日報酬'][i] = rl_2['rl_reward'][i]+1 rl_2['rl相乘'] = '' a = 1 for i in range(0,len(rl_2)): a *= rl_2['1+rl日報酬'][i] rl_2['rl相乘'][i] = a rl_2 import matplotlib.gridspec as gridspec #某列更換成數值類型_使用pd.to_numeric df_1['相乘']=pd.to_numeric(df_1['相乘']) rl_2['rl相乘']=pd.to_numeric(rl_2['rl相乘']) plt.figure(figsize = (10,6)) plt.title('', fontsize = 16) df_1.相乘.plot(color = 'blue', linewidth = 1) rl_2.rl相乘.plot(color = 'green', linewidth = 1) plt.grid() plt.xlabel('time', fontsize = 13) # X座標名稱 plt.ylabel('return(%)', fontsize = 14) # Y座標名稱 plt.legend(['buy&hold','RL_model'], bbox_to_anchor=(1, 1)); plt.savefig('績效圖.png') # 儲存圖片;