第三期 金融數據處理
51.使用絕對路徑讀取本地Excel數據
#請將下面的路徑替換為你存儲數據的路徑
data = pd.read_excel('/Users/Desktop/600000.SH.xls')
WARNING *** OLE2 inconsistency: SSCS size is 0 but SSAT size is non-zero
52.查看數據前三行

53.查看每列數據缺失值情況

54.提取日期列含有空值的行
data[data['日期'].isnull()]

55.輸出每列缺失值具體行數
for columname in data.columns:
if data[columname].count() != len(data):
loc = data[columname][data[columname].isnull().values==True].index.tolist()
print('列名:"{}", 第{}行位置有缺失值'.format(columname,loc))

56.刪除所有存在缺失值的行
'''
備注
axis:0-行操作(默認),1-列操作
how:any-只要有空值就刪除(默認),all-全部為空值才刪除
inplace:False-返回新的數據集(默認),True-在原數據集上操作
'''
data.dropna(axis=0, how='any', inplace=True)
57.繪制收盤價的折線圖
import matplotlib.pyplot as plt
plt.style.use('seaborn-darkgrid') # 設置畫圖的風格
plt.rc('font', size=6) #設置圖中字體和大小
plt.rc('figure', figsize=(4,3), dpi=150) # 設置圖的大小
data['收盤價(元)'].plot()
# 等價於
import matplotlib.pyplot as plt
plt.plot(df['收盤價(元)'])

58.同時繪制開盤價與收盤價
data[['收盤價(元)','開盤價(元)']].plot()

59.繪制漲跌幅的直方圖
plt.hist(df['漲跌幅(%)'])
# 等價於
df['漲跌幅(%)'].hist()

60.讓直方圖更細致
data['漲跌幅(%)'].hist(bins = 30)

61.以data的列名創建一個dataframe
temp = pd.DataFrame(columns = data.columns.to_list())
62.打印所有換手率不是數字的行
for i in range(len(data)):
if type(data.iloc[i,13]) != float:
temp = temp.append(data.loc[i])
temp

63.打印所有換手率為--的行
data[data['換手率(%)'].isin(['--'])]

64.重置data的行號
data = data.reset_index()
65.刪除所有換手率為非數字的行
k =[]
for i in range(len(data)):
if type(data.iloc[i,13]) != float:
k.append(i)
data.drop(labels=k,inplace=True)
66.繪制換手率的密度曲線
data['換手率(%)'].plot(kind='kde')

67.計算前一天與后一天收盤價的差值

68.計算前一天與后一天收盤價變化率
data['收盤價(元)'].pct_change()

69.設置日期為索引
data = data.set_index('日期')
70.以5個數據作為一個數據滑動窗口,在這個5個數據上取均值(收盤價)
data['收盤價(元)'].rolling(5).mean()

71.以5個數據作為一個數據滑動窗口,計算這五個數據總和(收盤價)
data['收盤價(元)'].rolling(5).sum()

72.將收盤價5日均線、20日均線與原始數據繪制在同一個圖上
data['收盤價(元)'].plot()
data['收盤價(元)'].rolling(5).mean().plot()
data['收盤價(元)'].rolling(20).mean().plot()

73.按周為采樣規則,取一周收盤價最大值
data['收盤價(元)'].resample('W').max()

74.繪制重采樣數據與原始數據
data['收盤價(元)'].plot()
data['收盤價(元)'].resample('7D').max().plot()

75.將數據往后移動5天

76.將數據向前移動5天

77.使用expending函數計算開盤價的移動窗口均值
data['開盤價(元)'].expanding(min_periods=1).mean()

78.繪制上一題的移動均值與原始數據折線圖
data['expanding Open mean']=data['開盤價(元)'].expanding(min_periods=1).mean()
data[['開盤價(元)', 'expanding Open mean']].plot(figsize=(16, 6))

79.計算布林指標
data['former 30 days rolling Close mean']=data['收盤價(元)'].rolling(20).mean()
data['upper bound']=data['former 30 days rolling Close mean']+2*data['收盤價(元)'].rolling(20).std()#在這里我們取20天內的標准差
data['lower bound']=data['former 30 days rolling Close mean']-2*data['收盤價(元)'].rolling(20).std()
80.計算布林線並繪制
data[['收盤價(元)', 'former 30 days rolling Close mean','upper bound','lower bound' ]].plot(figsize=(16, 6))
