import os import pandas as pd stock_data = pd.read_csv('stock data/sh600898.csv',parse_dates=[1]) #設定轉換周期period_type 轉換為周是'W',月'M',季度線'Q',五分鍾'5min',12天'12D' period_type = 'W' #將[date]設定為 index inplace是原地修改,不要創建一個新對象 stock_data.set_index('date',inplace=True) #進行轉換,周線的每個變量都等於那一周中最后一個交易日的變量值 period_stock_data = stock_data.resample(period_type,how='last') #周線的change等於那一周中每日change的連續相乘 period_stock_data['change'] = stock_data['change'].resample(period_type,how=lambda x:(x+1.0).prod()-1.0) #周線的open等於那一周中第一個交易日的open period_stock_data['open'] = stock_data['open'].resample(period_type,how='first') #周線的high等於那一周中的high的最大值 period_stock_data['high'] = stock_data['high'].resample(period_type,how='max') #周線的low等於那一周中的low的最大值 period_stock_data['low'] = stock_data['low'].resample(period_type,how='min') #周線的volume和money等於那一周中volume和money各自的和 period_stock_data['volume'] = stock_data['volume'].resample(period_type,how='sum') period_stock_data['money'] = stock_data['money'].resample(period_type,how='sum') #計算周線turnover period_stock_data['turnover'] = period_stock_data['volume']/\ (period_stock_data['traded_market_value']/period_stock_data['close']) #股票在有些周一天都沒有交易,將這些周去除 period_stock_data = period_stock_data[period_stock_data['code'].notnull()] period_stock_data.reset_index(inplace=True) #導出數據 period_stock_data.to_csv('week_stock_data.csv',index=False)
