ML for trading -cs7646-02

来源:互联网 发布:威露士滴露哪个好 知乎 编辑:程序博客网 时间:2024/05/22 00:01
环境python 2.71.移动平均线moving average 2.布林带bollinger band 3.日回报daily returns 4.累计回报cumulative returns 
import pandas as pdimport tushare as tsimport matplotlib.pyplot as plt
df = ts.get_k_data('002233','2015-01-01','2017-01-01')print df[:3]df.to_csv('002233.csv',columns=['date','open','close','high','low','volume'])          #保存到本地
         date   open  close   high    low    volume    code0  2015-01-05  9.552  9.712  9.843  9.458  249837.0  0022331  2015-01-06  9.609  9.515  9.684  9.421  182603.0  0022332  2015-01-07  9.421  9.393  9.562  9.308  126189.0  002233
df = pd.read_csv('002233.csv',delimiter=',',usecols=['date','close'],index_col='date',parse_dates=True)
def compute_ma(df,window):    return df.rolling(window).mean()     #计算滑动窗口的移动平均收盘价格def compute_mstd(df,window):    return df.rolling(window).std()       #计算滑动窗口的移动标准差def compute_bband(rm, rstd):              #布林带    upper = rm + 2*rstd    lowwer = rm - 2*rstd    return upper,lowwerdef plot_data(df,title):    ax = df['close'].plot(title=title)    ax.set_xlabel('date')    ax.set_ylabel('price')    ax.legend(loc='upper left')    plt.show()
#10日移动平均线rm = compute_ma(df,10)plot_data(rm,'moving average',)

png]![10日移动平均线

#布林带rstd = compute_mstd(df,10)upper, lowwer = compute_bband(rm, rstd)ax = df.plot(title='bollinger band',figsize=(11,7))rm.plot(ax=ax)upper.plot(ax=ax)lowwer.plot(ax=ax)ax.set_xlabel=('date')ax.set_ylabel=('price')ax.legend(['%s' %s for s in ['close','mov_average','upper','lowwer']])plt.show()

png布林带

def compute_dr(df):                                       # 日回报    daily_return = df.copy()    daily_return[1:] = (df[1:]/df[:-1].values) -1         # 两个DateFrame对象进行运算是,会尽量根据index对每一行元素进行匹配    daily_return.iloc[0,:]=0                              # 如果不使用values属性,前面的切片操作可能不起作用    return daily_return                                   
daily_return = compute_dr(df)daily_return.plot(title='Daily returns',figsize=(15,5))plt.show()

pngDaily returns

#累计回报def compute_cr(df):    cumulative_returns= df.copy()                              # 2015-1-1的收盘价格    cumulative_returns = (df/df.iloc[0].values)-1    return cumulative_returns
cumulative_returns = compute_cr(df)cumulative_returns.plot(title='Cumulative returns',figsize=(15,5))plt.grid()plt.show()

pngcumulative returns

原创粉丝点击