In [104]:
#!/Tsan/bin/python
# -*- coding: utf-8 -*-

In [105]:
# Libraries To Use
from __future__ import division 
from CloudQuant import MiniSimulator 
import numpy as np
import pandas as pd
import statsmodels.api as sm
import scipy.stats
import os
from sklearn import linear_model
from datetime import datetime,time,date
import matplotlib.pyplot as plt
import seaborn as sns
import time

In [106]:
# Import My own library for factor testing
from SingleFactorTest import factorFilterFunctions as ff
#from config import *

In [107]:
%matplotlib inline

In [108]:
# make sure that matplotib and seaborn can show Chinese
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['font.serif'] = ['SimHei']
sns.set_style("darkgrid",{"font.sans-serif":['simhei', 'Arial']})

In [109]:
path_name = 'D:/cStrategy/BackTestResult/8bf8cdf8380d4030b26df2c9a46a88d1/'
path = ff.data_path

In [110]:
filename = 'dealList.csv'
filenameHS300 = 'LZ_GPA_INDXQUOTE_CLOSE.csv'

In [111]:
benchMarkIndex = '000905.SH'
HS300Index ='000300.SH' # HS300 index code
ZZ500Index = '000905.SH' #   ZZ500 index code

In [112]:
benchMarkData = pd.read_csv(path+filenameHS300,infer_datetime_format=True,parse_dates=[0],index_col=0)[benchMarkIndex]

In [113]:
benchMarkMonthly = benchMarkData.resample('M').last()

In [114]:
inforDF = pd.read_csv(path_name+filename,infer_datetime_format=True,parse_dates=[0])
inforDF['TRADE_TIME'] = inforDF['TRADE_TIME'].apply(lambda x: str(x)[:8])
inforDF['TRADE_TIME'] = pd.to_datetime(inforDF['TRADE_TIME'], format='%Y%m%d', errors='ignore')

In [115]:
inforDFBuy = inforDF[inforDF['TRADE_TYPE'] == 1]

In [116]:
BuySeries = inforDFBuy.set_index('TRADE_TIME').resample('M').size()

In [117]:
compareDF = pd.concat([benchMarkMonthly, BuySeries], axis=1, join='inner')
compareDF.rename(columns = {0:'Buy_count'},inplace=True)
#compareDF['Buy_count']

In [118]:
compareDF .head()


Out[118]:
000905.SH Buy_count
LZ_GPA_INDXQUOTE_CLOSE-d
2012-01-31 3294.494 108
2012-02-29 3696.144 109
2012-03-31 3416.856 127
2012-04-30 3664.638 102
2012-05-31 3753.593 0

In [119]:
compareDF['Buy_count'].corr(compareDF[benchMarkIndex],method='spearman')


Out[119]:
-0.60120640531769254

In [120]:
# Plot bar and line in same figure
fig = plt.figure(figsize=(22,18))
ax = compareDF['Buy_count'].plot(kind="bar")
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(),compareDF[benchMarkIndex],marker='o',color ='r')


Out[120]:
[<matplotlib.lines.Line2D at 0x3f0ac978>]

In [ ]:


In [121]:
import pandas as pd
import matplotlib.pyplot as plt

left_2013 = pd.DataFrame(
    {'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
               'oct', 'nov', 'dec'],
     '2013_val': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 6]})

right_2014 = pd.DataFrame({'month': ['jan', 'feb'], '2014_val': [4, 5]})

right_2014_target = pd.DataFrame(
    {'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
               'oct', 'nov', 'dec'],
     '2014_target_val': [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]})

df_13_14 = pd.merge(left_2013, right_2014, how='outer')
df_13_14_target = pd.merge(df_13_14, right_2014_target, how='outer')

ax = df_13_14_target[['month', '2014_target_val']].plot(
    x='month', linestyle='-', marker='o')
df_13_14_target[['month', '2013_val', '2014_val']].plot(x='month', kind='bar',
                                                        ax=ax)

plt.show()



In [122]:
inforDF.set_index('TRADE_TIME').resample('M').last()


Out[122]:
CODE VOLUME PRICE TRADE_TYPE POSITION_AVG_PRICE COMMISSION
TRADE_TIME
2012-01-31 600408 114600 4.25 1 4.256375 0.0
2012-02-29 002110 63100 8.15 1 8.162225 0.0
2012-03-31 600475 100 11.85 1 11.900000 0.0
2012-04-30 002011 49000 10.30 1 10.315450 0.0
2012-05-31 601126 32000 15.42 -1 15.483190 0.0
2012-06-30 002011 49100 10.43 1 10.445645 0.0
2012-07-31 000656 49400 10.17 1 10.185255 0.0
2012-08-31 600963 700 3.65 1 3.657143 0.0
2012-09-30 000861 38600 14.28 1 14.301420 0.0
2012-10-31 600121 78600 7.27 1 7.280905 0.0
2012-11-30 000417 105200 5.31 1 5.317965 0.0
2012-12-31 000826 26100 22.50 1 22.538278 0.0
2013-01-31 600038 34800 22.10 -1 17.586340 0.0
2013-02-28 600765 5000 16.43 1 16.454645 0.0
2013-03-31 002238 55500 11.59 1 11.607385 0.0
2013-04-30 600197 55700 11.20 1 11.216800 0.0
2013-05-31 600635 4300 4.69 1 4.386039 0.0
2013-06-30 000652 191400 3.26 1 3.264890 0.0
2013-07-31 000006 166800 4.08 1 4.086120 0.0
2013-08-31 600780 115900 6.01 1 6.019015 0.0
2013-09-30 600584 2400 6.34 1 6.349510 0.0
2013-10-31 002167 1900 10.82 1 10.836230 0.0
2013-11-30 002191 55600 14.18 1 14.201270 0.0
2013-12-31 601616 182400 3.95 1 3.955925 0.0
2014-01-31 600575 223300 3.21 1 3.214815 0.0
2014-02-28 600088 3500 14.80 1 16.677921 0.0
2014-03-31 600110 18100 5.05 1 5.057575 0.0
2014-04-30 600056 3000 20.69 1 22.289687 0.0
2014-05-31 600125 100 4.93 1 4.980000 0.0
2014-06-30 600220 254300 2.95 1 2.954425 0.0
2014-07-31 601369 132800 6.05 -1 5.568340 0.0
2014-08-31 000616 199400 3.82 1 3.825730 0.0
2014-09-30 600582 74900 11.06 1 11.076590 0.0
2014-10-31 600636 55300 14.61 1 14.631915 0.0
2014-11-30 600724 154600 5.62 1 5.628430 0.0
2014-12-31 600337 87300 9.31 1 9.323965 0.0
2015-01-31 000735 112100 8.06 1 8.072090 0.0
2015-02-28 601099 34900 12.45 1 12.468675 0.0
2015-03-31 600874 100 13.87 1 13.920000 0.0
2015-04-30 600511 30000 38.25 1 38.307375 0.0
2015-05-31 600584 66700 27.03 -1 15.079001 0.0
2015-06-30 600510 70100 13.80 1 13.808619 0.0
2015-07-31 600337 68200 15.50 1 15.523250 0.0
2015-08-31 600580 102900 11.85 1 11.867775 0.0
2015-09-30 600175 234400 4.70 1 4.707050 0.0
2015-10-31 000422 160000 7.22 1 7.230830 0.0
2015-11-30 600280 98400 10.95 1 10.966425 0.0
2015-12-31 000582 3500 22.95 1 22.984425 0.0
2016-01-31 000566 55600 20.16 1 20.190240 0.0
2016-02-29 000550 48400 26.05 1 26.089075 0.0
2016-03-31 600967 118900 10.50 1 10.515750 0.0
2016-04-30 600872 98200 12.26 1 12.278390 0.0
2016-05-31 600664 146500 8.01 1 8.022015 0.0
2016-06-30 000900 175000 6.80 1 6.810200 0.0
2016-07-31 002311 80000 15.16 1 15.182740 0.0
2016-08-31 601168 163600 7.54 1 7.551310 0.0
2016-09-30 002589 36600 32.46 1 32.508690 0.0
2016-10-31 600812 185900 6.63 1 6.639945 0.0
2016-11-30 002508 32300 38.45 1 38.507675 0.0
2016-12-31 000786 200 10.33 1 10.355000 0.0

In [ ]:


In [ ]:


In [123]:
filenamePositionList = 'positionlist.csv'
filenameAsset = 'asset.csv'
filenameClose = 'LZ_GPA_QUOTE_TCLOSE.csv'
filenameZXIndustry = 'LZ_GPA_INDU_ZX.csv'
filenameZXExplanation = 'LZ_GPA_TMP_INDU_ZX.csv'


filenameValue =  'LZ_GPA_VAL_PB.csv' # 市净率
filenameAdjPrice = 'Own_Factor_AdjustedPriceForward-1d.csv'  # 通过 calAdjustedPrice()函数获得

In [124]:
#
initialAsset = 10000000
# Constants
startTime =  datetime.strptime('20100101', '%Y%m%d')
endTime = datetime.strptime('20170228', '%Y%m%d')

In [125]:
# 必要的数据 股票收盘价格
closeDF = pd.read_csv(path+filenameClose,infer_datetime_format=True,parse_dates=[0],index_col=0)
closeDF.columns = map(lambda x : x.split('.')[0],closeDF.columns)

In [126]:
# 估值因子
factorValue = pd.read_csv(path+filenameValue,infer_datetime_format=True,parse_dates=[0],index_col=0)
factorValue.columns = map(lambda x : x.split('.')[0],factorValue.columns)

In [127]:
# 复权后收盘价
priceADJ = pd.read_csv(path+filenameAdjPrice,infer_datetime_format=True,parse_dates=[0],index_col=0)
priceADJ.columns = map(lambda x : x.split('.')[0],priceADJ.columns)

In [128]:
# 读取仓位信息
positionDF = pd.read_csv(path+filenamePositionList,infer_datetime_format=True,parse_dates=[0],index_col=0)
positionDF['CODE'] = positionDF['CODE'].apply(lambda x :(6-len(str(x)))*'0' + str(x))
assetDF = pd.read_csv(path+filenameAsset,infer_datetime_format=True,parse_dates=[0],index_col=0)
assetDF.is_copy = False
assetDF = assetDF[['STOCK_MARKET','STOCK_BALANCE']]
assetDF['TOTAL'] = assetDF['STOCK_MARKET'] + assetDF['STOCK_BALANCE']

In [129]:
positionDF


Out[129]:
CODE OPT_POSITION ORDER_TYPE TOTAL_COST TODAY_POSITION
DATE
2012-02-10 600853 29700 1 100783.683 0
2012-02-10 002314 10200 1 101080.980 0
2012-02-10 600810 12500 1 100850.750 0
2012-02-10 600777 26500 1 101065.965 0
2012-02-10 600019 19900 1 100993.893 0
2012-02-10 300157 4400 1 98922.824 0
2012-02-10 601988 33200 1 101028.928 0
2012-02-10 600219 13800 1 100564.464 0
2012-02-10 000898 21200 1 100800.700 0
2012-02-10 000698 16800 1 100732.632 0
2012-02-10 300117 13300 1 100914.814 0
2012-02-10 000615 23700 1 100825.725 0
2012-02-10 600819 10800 1 100324.224 0
2012-02-10 000415 10700 1 100680.580 0
2012-02-10 000619 17200 1 100548.448 0
2012-02-10 000859 22100 1 101097.997 0
2012-02-10 601390 37900 1 100914.814 0
2012-02-10 300041 5400 1 99351.252 0
2012-02-10 002043 15100 1 100666.566 0
2012-02-10 300163 6200 1 99547.448 0
2012-02-10 601398 22900 1 100860.760 0
2012-02-10 002088 9700 1 100107.007 0
2012-02-10 600782 20000 1 100900.800 0
2012-02-10 002082 10500 1 101005.905 0
2012-02-10 600423 15800 1 100746.646 0
2012-02-10 601898 10300 1 100216.116 0
2012-02-10 000761 21100 1 100747.647 0
2012-02-10 600249 20200 1 100898.798 0
2012-02-10 600569 36200 1 101098.998 0
2012-02-10 000881 12400 1 100664.564 0
... ... ... ... ... ...
2016-12-06 000010 27400 1 216950.734 0
2016-12-06 600039 48100 1 216184.969 0
2016-12-06 002699 6300 1 216306.090 0
2016-12-06 002574 16500 1 216366.150 0
2016-12-06 600839 48500 1 217011.795 0
2016-12-06 601808 16100 1 215955.740 0
2016-12-06 600284 18600 1 216161.946 0
2016-12-06 002060 26600 1 215675.460 0
2016-12-06 002062 29600 1 216888.672 0
2016-12-06 000040 16900 1 216874.658 0
2016-12-06 600028 42200 1 217124.908 0
2016-12-06 600545 17100 1 216702.486 0
2016-12-06 601117 33400 1 215979.764 0
2016-12-06 000541 20700 1 216738.522 0
2016-12-06 600823 27300 1 216432.216 0
2016-12-06 002563 19400 1 205845.640 0
2016-12-06 000667 53900 1 216894.678 0
2016-12-06 600827 16300 1 215864.649 0
2016-12-06 600790 31500 1 216621.405 0
2016-12-06 600278 11200 1 216488.272 0
2016-12-07 600175 39800 1 217126.910 0
2016-12-08 600175 39800 1 217126.910 0
2016-12-09 600175 39800 1 217126.910 0
2016-12-12 600175 39800 1 217126.910 0
2016-12-13 600175 39800 1 217126.910 0
2016-12-14 600175 39800 1 217126.910 0
2016-12-15 600175 39800 1 217126.910 0
2016-12-16 600175 39800 1 217126.910 0
2016-12-19 600175 39800 1 217126.910 0
2016-12-20 600175 39800 1 217126.910 0

29922 rows × 5 columns


In [130]:
positionDF1 = positionDF[['CODE','OPT_POSITION']]
positionDF1


Out[130]:
CODE OPT_POSITION
DATE
2012-02-10 600853 29700
2012-02-10 002314 10200
2012-02-10 600810 12500
2012-02-10 600777 26500
2012-02-10 600019 19900
2012-02-10 300157 4400
2012-02-10 601988 33200
2012-02-10 600219 13800
2012-02-10 000898 21200
2012-02-10 000698 16800
2012-02-10 300117 13300
2012-02-10 000615 23700
2012-02-10 600819 10800
2012-02-10 000415 10700
2012-02-10 000619 17200
2012-02-10 000859 22100
2012-02-10 601390 37900
2012-02-10 300041 5400
2012-02-10 002043 15100
2012-02-10 300163 6200
2012-02-10 601398 22900
2012-02-10 002088 9700
2012-02-10 600782 20000
2012-02-10 002082 10500
2012-02-10 600423 15800
2012-02-10 601898 10300
2012-02-10 000761 21100
2012-02-10 600249 20200
2012-02-10 600569 36200
2012-02-10 000881 12400
... ... ...
2016-12-06 000010 27400
2016-12-06 600039 48100
2016-12-06 002699 6300
2016-12-06 002574 16500
2016-12-06 600839 48500
2016-12-06 601808 16100
2016-12-06 600284 18600
2016-12-06 002060 26600
2016-12-06 002062 29600
2016-12-06 000040 16900
2016-12-06 600028 42200
2016-12-06 600545 17100
2016-12-06 601117 33400
2016-12-06 000541 20700
2016-12-06 600823 27300
2016-12-06 002563 19400
2016-12-06 000667 53900
2016-12-06 600827 16300
2016-12-06 600790 31500
2016-12-06 600278 11200
2016-12-07 600175 39800
2016-12-08 600175 39800
2016-12-09 600175 39800
2016-12-12 600175 39800
2016-12-13 600175 39800
2016-12-14 600175 39800
2016-12-15 600175 39800
2016-12-16 600175 39800
2016-12-19 600175 39800
2016-12-20 600175 39800

29922 rows × 2 columns


In [131]:
# pivot表格
positionDF1 = positionDF[['CODE','OPT_POSITION']]
positionPivot = pd.pivot_table(positionDF1,index =positionDF1.index,values='OPT_POSITION',columns = ['CODE'])
positionPivot


Out[131]:
CODE 000002 000005 000010 000016 000019 000021 000027 000029 000030 000031 ... 603017 603020 603123 603167 603308 603333 603366 603766 603979 603993
DATE
2012-02-10 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-02-13 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-02-14 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-02-15 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-02-16 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-02-17 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-02-20 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-02-21 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-02-22 NaN NaN NaN 31000.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-02-23 NaN NaN NaN 31000.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-02-24 NaN NaN NaN 31000.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-02-27 NaN NaN NaN 31000.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-02-28 NaN NaN NaN 31000.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-02-29 NaN NaN NaN 31000.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-03-01 NaN NaN NaN 31000.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-03-02 NaN NaN NaN 31000.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-03-05 NaN NaN NaN 31000.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-03-06 NaN NaN NaN 31000.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-03-07 NaN NaN NaN 31000.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-03-08 NaN NaN NaN 31000.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-03-09 NaN NaN NaN 31000.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-03-12 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-03-13 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-03-14 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-03-15 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-04-25 NaN 25800.0 NaN NaN NaN NaN NaN NaN NaN 23700.0 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-04-26 NaN 25800.0 NaN NaN NaN NaN NaN NaN NaN 23700.0 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-04-27 NaN 25800.0 NaN NaN NaN NaN NaN NaN NaN 23700.0 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-05-02 NaN 25800.0 NaN NaN NaN NaN NaN NaN NaN 23700.0 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2012-05-03 NaN 25800.0 NaN NaN NaN NaN NaN NaN NaN 23700.0 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
2016-11-09 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN 9300.0 NaN NaN NaN NaN NaN NaN NaN NaN
2016-11-10 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN 9300.0 NaN NaN NaN NaN NaN NaN NaN NaN
2016-11-11 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN 9300.0 NaN NaN NaN NaN NaN NaN NaN NaN
2016-11-14 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN 9300.0 NaN NaN NaN NaN NaN NaN NaN NaN
2016-11-15 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN 10800.0 49600.0
2016-11-16 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN 10800.0 49600.0
2016-11-17 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN 10800.0 49600.0
2016-11-18 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN 10800.0 49600.0
2016-11-21 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN 10800.0 49600.0
2016-11-22 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN 10800.0 49600.0
2016-11-23 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN 10800.0 49600.0
2016-11-24 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN 10800.0 49600.0
2016-11-25 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN 10800.0 49600.0
2016-11-28 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN 10800.0 49600.0
2016-11-29 NaN NaN 27400.0 NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN 21100.0 NaN NaN NaN
2016-11-30 NaN NaN 27400.0 NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN 21100.0 NaN NaN NaN
2016-12-01 NaN NaN 27400.0 NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN 21100.0 NaN NaN NaN
2016-12-02 NaN NaN 27400.0 NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN 21100.0 NaN NaN NaN
2016-12-05 NaN NaN 27400.0 NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN 21100.0 NaN NaN NaN
2016-12-06 NaN NaN 27400.0 NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN 21100.0 NaN NaN NaN
2016-12-07 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2016-12-08 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2016-12-09 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2016-12-12 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2016-12-13 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2016-12-14 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2016-12-15 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2016-12-16 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2016-12-19 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2016-12-20 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

557 rows × 1122 columns


In [132]:
# 生成风险因子暴露dataframe
factorValue = factorValue.loc[positionPivot.index]
factorValueNorm = ((factorValue.T - factorValue.T.mean()) / factorValue.T.std()).T
exposureDF = ((factorValueNorm[positionPivot.columns] * positionPivot).T / positionPivot.sum(axis=1)).T

In [133]:
#  按每天相加在平均后得到平均的risk exposure
exposureDF.sum(axis=1).mean()


Out[133]:
-0.10675693591855419

In [134]:
# 市值数据
priceADJ = priceADJ.loc[positionPivot.index][positionPivot.columns]
profit = priceADJ * positionPivot

In [135]:
profit.pct_change().sum().sum()


Out[135]:
475.34576532090705

In [136]:
# 读取行业信息
indusDF = pd.read_csv(path+filenameZXIndustry,infer_datetime_format=True,parse_dates=[0],index_col=0).loc[startTime:endTime]
indusDF.columns = map(lambda x : x.split('.')[0],indusDF.columns)
induExplanation = pd.read_csv(path+filenameZXExplanation,infer_datetime_format=True,parse_dates=[0],encoding='gb2312')

In [137]:
# 市值变化
marketValuePercent = assetDF['STOCK_MARKET'] / assetDF['TOTAL']

#  Visualization
fig = plt.figure(figsize=(16,10))
# Add a subplot
ax = fig.add_subplot(111)
marketValuePercent.plot.area(ax = ax, fontsize =13,title =u'账户股票市值变化',alpha =0.8)
ax.set_title(ax.get_title(),alpha=0.7, fontsize=25)


Out[137]:
<matplotlib.text.Text at 0x3b604160>

In [138]:
indusDF


Out[138]:
000005 600601 600602 600651 600652 600653 600654 600656 000004 000002 ... 603200 300658 300660 603042 002877 002878 300661 603496 300662 300663
LZ_GPA_INDU_ZX-t
2010-01-04 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-05 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-06 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-07 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-08 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-11 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-12 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-13 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-14 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-15 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-18 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-19 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-20 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-21 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-22 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-25 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-26 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-27 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-28 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-01-29 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-02-01 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-02-02 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-02-03 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-02-04 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-02-05 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-02-08 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-02-09 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-02-10 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-02-11 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2010-02-12 23 25 25 16 2 13 25 10 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
2017-01-11 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-01-12 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-01-13 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-01-16 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-01-17 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-01-18 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-01-19 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-01-20 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-01-23 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-01-24 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-01-25 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-01-26 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-03 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-06 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-07 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-08 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-09 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-10 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-13 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-14 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-15 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-16 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-17 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-20 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-21 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-22 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-23 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-24 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-27 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2017-02-28 23 27 25 16 28 13 25 13 18 23 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

1736 rows × 3348 columns


In [139]:
induExplanation


Out[139]:
LZ_GPA_TMP_INDU_ZX-t
0 石油石化
1 煤炭
2 有色金属
3 电力及公用事业
4 钢铁
5 基础化工
6 建筑
7 建材
8 轻工制造
9 机械
10 电力设备
11 国防军工
12 汽车
13 商贸零售
14 餐饮旅游
15 家电
16 纺织服装
17 医药
18 食品饮料
19 农林牧渔
20 银行
21 非银行金融
22 房地产
23 交通运输
24 电子元器件
25 通信
26 计算机
27 传媒
28 综合

In [140]:
# 日期序列
dateList = sorted(set(positionDF.index))

sample = positionDF[positionDF.index ==dateList[0]]
sample.set_index('CODE',inplace=True)

In [141]:
sampledate = dateList[0]

sample.is_copy = False

sample['PRICE'] = closeDF.loc[dateList[0]]
sample['MARKET_VALUE'] =  sample['OPT_POSITION'] * sample['PRICE']

In [142]:
totalPosPerc = ((sample['OPT_POSITION'] * sample['PRICE']).sum() ) / assetDF.loc[sampledate]

In [143]:
# 收益比例
sample['PNL'] = ((sample['OPT_POSITION'] * sample['PRICE']) - sample['TOTAL_COST']) / sample['TOTAL_COST']

In [144]:
# 行业占比
sample['INDUSTRY'] =  indusDF.loc[dateList[0]]
sample['INDUSTRY'] =  sample['INDUSTRY'].apply(lambda x: int(x)-1)

In [145]:
len(indusDF.loc[dateList[0]])


Out[145]:
3348

In [146]:
# 风险因子/标准化
factorValueSlice = factorValue.loc[dateList[0]]
factorValueSlice = (factorValueSlice - factorValueSlice.mean()) / factorValueSlice.std()

In [147]:
# 当天的估值因子暴露
sample['PB'] = factorValueSlice 
exposure = (sample['PB'] * sample['OPT_POSITION']).sum() / sample['OPT_POSITION'].sum()
exposure


Out[147]:
-0.21432552069089492

In [148]:
# 当日各行业市值占比
indusProp = sample.groupby('INDUSTRY')['MARKET_VALUE'].sum()/ assetDF.loc[sampledate]['STOCK_MARKET']
indusProp


Out[148]:
INDUSTRY
0     0.084691
1     0.063305
2     0.147618
4     0.106502
5     0.225185
6     0.095592
7     0.160053
20    0.031621
28    0.085433
Name: MARKET_VALUE, dtype: float64

In [149]:
# 可视化
induInfo = induExplanation.copy()
induInfo['PROPORTION'] = indusProp

#  Visualization
fig = plt.figure(figsize=(18,12))
# Add a subplot
ax = fig.add_subplot(111)
induInfo.set_index('LZ_GPA_TMP_INDU_ZX-t').plot(kind='bar',ax = ax, fontsize =13,title =u'各行业配置占比',alpha =0.8)
for i, v in enumerate(induInfo['PROPORTION'].values):
    if ~np.isnan(v):
        ax.text(i-0.35,v+0.002, str(round(v,4)*100)+'%', color='red', fontweight='bold')
ax.set_title(ax.get_title(),alpha=0.7, fontsize=25)


Out[149]:
<matplotlib.text.Text at 0x4d5ca1d0>

In [150]:
# 每天重仓股票(持仓最大的十只股票) 占当天整个持仓的比重
topNum = 10 if sample.shape[0] > 10 else sample.shape[0]
top10Stocks = (sample.sort_values('MARKET_VALUE',ascending = False).iloc[:topNum]['MARKET_VALUE'] / assetDF.loc[sampledate]['STOCK_MARKET'])
top10Stocks.sum()


Out[150]:
0.11009252553009169

In [151]:
industryID = 20
industryProChange = pd.DataFrame(index = dateList,columns = [induExplanation.iloc[industryID].values],dtype = float)
endOfWeekList = sorted(list(set(industryProChange.iloc[industryProChange.resample('W').size().cumsum().sub(1)].index)))

In [152]:
# 计算某行业市值变化
def IndusMarketValueChange(industryID,dateList):
    '''
    计算行业市值变化,注意此函数含有已定义过的变量,请调用此函数前初始化这些变量
    Input:
    industryID: int, 行业ID,即induExplanation的index
    dateList: List, 需要回放的时间序列,其中每个元素是datetime格式
    Output:
    industryProChange:dataframe, 行业市值数据
    industryPNL:dataframe,行业pnl数据'''
    industryProChange = pd.DataFrame(index = dateList,columns = [induExplanation.iloc[industryID].values],dtype = float)
    industryPNL = pd.DataFrame(index = dateList,columns = [induExplanation.iloc[industryID].values],dtype = float)
    # 计算某行业的股票持仓随时间的变化
    for date in endOfWeekList:
        try:
            # 切片
            #print date
            positionSlice = positionDF[positionDF.index == date]
            positionSlice.is_copy = False
            positionSlice.set_index('CODE',inplace=True)


            positionSlice['INDUSTRY'] =  indusDF.loc[date]

            positionSlice['INDUSTRY'] =  positionSlice['INDUSTRY'].apply(lambda x: int(x)-1 if ~np.isnan(x) else x)

            if industryID in positionSlice['INDUSTRY'].values:
                positionSlice = positionSlice[positionSlice['INDUSTRY'] == industryID]      
                positionSlice['PRICE'] = closeDF.loc[date]
                positionSlice['MARKET_VALUE'] =  positionSlice['OPT_POSITION'] * positionSlice['PRICE']
                industryProChange.loc[date] = positionSlice['MARKET_VALUE'].sum()/ assetDF.loc[sampledate]['STOCK_MARKET']
                #print industryProChange.loc[date]
                industryPNL.loc[date] = ((positionSlice['OPT_POSITION'] * positionSlice['PRICE']).sum() - positionSlice['TOTAL_COST'].sum()) / positionSlice['TOTAL_COST'].sum()

            else:
                print 'Industry ID '+str(industryID)+' is not in the slice of position dataframe on ' + date.strftime("%Y-%m-%d")
                industryProChange.loc[date] = 0
                industryPNL.loc[date] = 0
        except:
            industryProChange.loc[date] = 0
            industryPNL.loc[date] = 0
    return industryProChange,industryPNL

In [153]:
a,b = IndusMarketValueChange(industryID,endOfWeekList)


Industry ID 20 is not in the slice of position dataframe on 2012-03-15
Industry ID 20 is not in the slice of position dataframe on 2012-05-17
Industry ID 20 is not in the slice of position dataframe on 2013-01-25
Industry ID 20 is not in the slice of position dataframe on 2013-01-30
Industry ID 20 is not in the slice of position dataframe on 2013-06-14
Industry ID 20 is not in the slice of position dataframe on 2013-06-17
Industry ID 20 is not in the slice of position dataframe on 2013-09-30
Industry ID 20 is not in the slice of position dataframe on 2013-10-11
Industry ID 20 is not in the slice of position dataframe on 2013-10-18
Industry ID 20 is not in the slice of position dataframe on 2013-10-25
Industry ID 20 is not in the slice of position dataframe on 2013-11-01
Industry ID 20 is not in the slice of position dataframe on 2013-11-08
Industry ID 20 is not in the slice of position dataframe on 2013-11-15
Industry ID 20 is not in the slice of position dataframe on 2013-11-22
Industry ID 20 is not in the slice of position dataframe on 2013-12-20
Industry ID 20 is not in the slice of position dataframe on 2013-12-27
Industry ID 20 is not in the slice of position dataframe on 2014-01-03
Industry ID 20 is not in the slice of position dataframe on 2014-01-10
Industry ID 20 is not in the slice of position dataframe on 2014-01-17
Industry ID 20 is not in the slice of position dataframe on 2014-04-25
Industry ID 20 is not in the slice of position dataframe on 2014-07-04
Industry ID 20 is not in the slice of position dataframe on 2014-07-25
Industry ID 20 is not in the slice of position dataframe on 2014-08-01
Industry ID 20 is not in the slice of position dataframe on 2014-08-08
Industry ID 20 is not in the slice of position dataframe on 2014-08-22
Industry ID 20 is not in the slice of position dataframe on 2014-08-29
Industry ID 20 is not in the slice of position dataframe on 2014-09-03
Industry ID 20 is not in the slice of position dataframe on 2014-09-23
Industry ID 20 is not in the slice of position dataframe on 2015-01-16
Industry ID 20 is not in the slice of position dataframe on 2015-01-23
Industry ID 20 is not in the slice of position dataframe on 2015-01-30
Industry ID 20 is not in the slice of position dataframe on 2015-02-06
Industry ID 20 is not in the slice of position dataframe on 2015-02-13
Industry ID 20 is not in the slice of position dataframe on 2015-02-17
Industry ID 20 is not in the slice of position dataframe on 2015-02-27
Industry ID 20 is not in the slice of position dataframe on 2015-03-06
Industry ID 20 is not in the slice of position dataframe on 2015-03-13
Industry ID 20 is not in the slice of position dataframe on 2015-03-20
Industry ID 20 is not in the slice of position dataframe on 2015-05-08
Industry ID 20 is not in the slice of position dataframe on 2015-05-15
Industry ID 20 is not in the slice of position dataframe on 2015-05-22
Industry ID 20 is not in the slice of position dataframe on 2015-06-19
Industry ID 20 is not in the slice of position dataframe on 2015-06-26
Industry ID 20 is not in the slice of position dataframe on 2015-07-03
Industry ID 20 is not in the slice of position dataframe on 2015-07-10
Industry ID 20 is not in the slice of position dataframe on 2015-07-17
Industry ID 20 is not in the slice of position dataframe on 2015-07-22
Industry ID 20 is not in the slice of position dataframe on 2015-11-25
Industry ID 20 is not in the slice of position dataframe on 2016-04-22
Industry ID 20 is not in the slice of position dataframe on 2016-12-09
Industry ID 20 is not in the slice of position dataframe on 2016-12-16
Industry ID 20 is not in the slice of position dataframe on 2016-12-20

In [ ]:


In [154]:
# 从 0 -28 中选
start =time.time()
industryID = 20 # 银行
industryProChange = pd.DataFrame(index = dateList,columns = [induExplanation.iloc[industryID].values],dtype = float)
industryPNL = pd.DataFrame(index = dateList,columns = [induExplanation.iloc[industryID].values],dtype = float)
# 计算某行业的股票持仓随时间的变化
for date in endOfWeekList:
    try:
        # 切片
        #print date
        positionSlice = positionDF[positionDF.index == date]
        positionSlice.is_copy = False
        positionSlice.set_index('CODE',inplace=True)
        

        positionSlice['INDUSTRY'] =  indusDF.loc[date]

        positionSlice['INDUSTRY'] =  positionSlice['INDUSTRY'].apply(lambda x: int(x)-1 if ~np.isnan(x) else x)
        
        if industryID in positionSlice['INDUSTRY'].values:
            positionSlice = positionSlice[positionSlice['INDUSTRY'] == industryID]      
            positionSlice['PRICE'] = closeDF.loc[date]
            positionSlice['MARKET_VALUE'] =  positionSlice['OPT_POSITION'] * positionSlice['PRICE']
            industryProChange.loc[date] = positionSlice['MARKET_VALUE'].sum()/ assetDF.loc[sampledate]['STOCK_MARKET']
            #print industryProChange.loc[date]
            industryPNL.loc[date] = ((positionSlice['OPT_POSITION'] * positionSlice['PRICE']).sum() - positionSlice['TOTAL_COST'].sum()) / positionSlice['TOTAL_COST'].sum()
             
        else:
            print 'Industry ID '+str(industryID)+' is not in the slice of position dataframe on ' + date.strftime("%Y-%m-%d")
            industryProChange.loc[date] = 0
            industryPNL.loc[date] = 0
    except:
        industryProChange.loc[date] = 0
        industryPNL.loc[date] = 0
print time.time() - start


Industry ID 20 is not in the slice of position dataframe on 2012-03-15
Industry ID 20 is not in the slice of position dataframe on 2012-05-17
Industry ID 20 is not in the slice of position dataframe on 2013-01-25
Industry ID 20 is not in the slice of position dataframe on 2013-01-30
Industry ID 20 is not in the slice of position dataframe on 2013-06-14
Industry ID 20 is not in the slice of position dataframe on 2013-06-17
Industry ID 20 is not in the slice of position dataframe on 2013-09-30
Industry ID 20 is not in the slice of position dataframe on 2013-10-11
Industry ID 20 is not in the slice of position dataframe on 2013-10-18
Industry ID 20 is not in the slice of position dataframe on 2013-10-25
Industry ID 20 is not in the slice of position dataframe on 2013-11-01
Industry ID 20 is not in the slice of position dataframe on 2013-11-08
Industry ID 20 is not in the slice of position dataframe on 2013-11-15
Industry ID 20 is not in the slice of position dataframe on 2013-11-22
Industry ID 20 is not in the slice of position dataframe on 2013-12-20
Industry ID 20 is not in the slice of position dataframe on 2013-12-27
Industry ID 20 is not in the slice of position dataframe on 2014-01-03
Industry ID 20 is not in the slice of position dataframe on 2014-01-10
Industry ID 20 is not in the slice of position dataframe on 2014-01-17
Industry ID 20 is not in the slice of position dataframe on 2014-04-25
Industry ID 20 is not in the slice of position dataframe on 2014-07-04
Industry ID 20 is not in the slice of position dataframe on 2014-07-25
Industry ID 20 is not in the slice of position dataframe on 2014-08-01
Industry ID 20 is not in the slice of position dataframe on 2014-08-08
Industry ID 20 is not in the slice of position dataframe on 2014-08-22
Industry ID 20 is not in the slice of position dataframe on 2014-08-29
Industry ID 20 is not in the slice of position dataframe on 2014-09-03
Industry ID 20 is not in the slice of position dataframe on 2014-09-23
Industry ID 20 is not in the slice of position dataframe on 2015-01-16
Industry ID 20 is not in the slice of position dataframe on 2015-01-23
Industry ID 20 is not in the slice of position dataframe on 2015-01-30
Industry ID 20 is not in the slice of position dataframe on 2015-02-06
Industry ID 20 is not in the slice of position dataframe on 2015-02-13
Industry ID 20 is not in the slice of position dataframe on 2015-02-17
Industry ID 20 is not in the slice of position dataframe on 2015-02-27
Industry ID 20 is not in the slice of position dataframe on 2015-03-06
Industry ID 20 is not in the slice of position dataframe on 2015-03-13
Industry ID 20 is not in the slice of position dataframe on 2015-03-20
Industry ID 20 is not in the slice of position dataframe on 2015-05-08
Industry ID 20 is not in the slice of position dataframe on 2015-05-15
Industry ID 20 is not in the slice of position dataframe on 2015-05-22
Industry ID 20 is not in the slice of position dataframe on 2015-06-19
Industry ID 20 is not in the slice of position dataframe on 2015-06-26
Industry ID 20 is not in the slice of position dataframe on 2015-07-03
Industry ID 20 is not in the slice of position dataframe on 2015-07-10
Industry ID 20 is not in the slice of position dataframe on 2015-07-17
Industry ID 20 is not in the slice of position dataframe on 2015-07-22
Industry ID 20 is not in the slice of position dataframe on 2015-11-25
Industry ID 20 is not in the slice of position dataframe on 2016-04-22
Industry ID 20 is not in the slice of position dataframe on 2016-12-09
Industry ID 20 is not in the slice of position dataframe on 2016-12-16
Industry ID 20 is not in the slice of position dataframe on 2016-12-20
11.7640001774

In [155]:
industryPNL.head(10)


Out[155]:
银行
2012-02-10 -0.003241
2012-02-13 NaN
2012-02-14 NaN
2012-02-15 NaN
2012-02-16 NaN
2012-02-17 -0.009150
2012-02-20 NaN
2012-02-21 NaN
2012-02-22 NaN
2012-02-23 NaN

In [156]:
industryProChange.head(10)


Out[156]:
银行
2012-02-10 0.031621
2012-02-13 NaN
2012-02-14 NaN
2012-02-15 NaN
2012-02-16 NaN
2012-02-17 0.031433
2012-02-20 NaN
2012-02-21 NaN
2012-02-22 NaN
2012-02-23 NaN

In [157]:
#

In [158]:
#  Visualization
fig = plt.figure(figsize=(16,10))
# Add a subplot
ax = fig.add_subplot(111)
industryProChange.plot.area(ax = ax, fontsize =13,title =u'行业占比',alpha =0.8)
ax.set_title(ax.get_title(),alpha=0.7, fontsize=25)


Out[158]:
<matplotlib.text.Text at 0x3a1fb128>

In [ ]:


In [159]:
filename = 'C:/Users/LZJF_02/Desktop/ru888_1min.csv'
savename = 'C:/Users/LZJF_02/Desktop/ru888_1min_modi.csv'

In [160]:
ru888 = pd.read_csv(filename,infer_datetime_format=True,header=None,names = ['Open', 'High', 'Low', 'Close','TotalVolume','Position'])


---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-160-0412e896f237> in <module>()
----> 1 ru888 = pd.read_csv(filename,infer_datetime_format=True,header=None,names = ['Open', 'High', 'Low', 'Close','TotalVolume','Position'])

c:\python27\lib\site-packages\pandas\io\parsers.pyc in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
    644                     skip_blank_lines=skip_blank_lines)
    645 
--> 646         return _read(filepath_or_buffer, kwds)
    647 
    648     parser_f.__name__ = name

c:\python27\lib\site-packages\pandas\io\parsers.pyc in _read(filepath_or_buffer, kwds)
    387 
    388     # Create the parser.
--> 389     parser = TextFileReader(filepath_or_buffer, **kwds)
    390 
    391     if (nrows is not None) and (chunksize is not None):

c:\python27\lib\site-packages\pandas\io\parsers.pyc in __init__(self, f, engine, **kwds)
    728             self.options['has_index_names'] = kwds['has_index_names']
    729 
--> 730         self._make_engine(self.engine)
    731 
    732     def close(self):

c:\python27\lib\site-packages\pandas\io\parsers.pyc in _make_engine(self, engine)
    921     def _make_engine(self, engine='c'):
    922         if engine == 'c':
--> 923             self._engine = CParserWrapper(self.f, **self.options)
    924         else:
    925             if engine == 'python':

c:\python27\lib\site-packages\pandas\io\parsers.pyc in __init__(self, src, **kwds)
   1388         kwds['allow_leading_cols'] = self.index_col is not False
   1389 
-> 1390         self._reader = _parser.TextReader(src, **kwds)
   1391 
   1392         # XXX

pandas\parser.pyx in pandas.parser.TextReader.__cinit__ (pandas\parser.c:4184)()

pandas\parser.pyx in pandas.parser.TextReader._setup_parser_source (pandas\parser.c:8449)()

IOError: File C:/Users/LZJF_02/Desktop/ru888_1min.csv does not exist

In [ ]:
ru888.index = ru888.index.map(lambda x : pd.to_datetime(x))

ru888['Time'] = ru888.index.map(lambda x : x.time)

ru888.index = ru888.index.map(lambda x : x.date)

ru888.index.name = 'Date'

ru888.drop('Position',axis=1,inplace = True)

In [ ]:
ru888.to_csv(savename,na_rep='NaN',date_format='%Y%m%d')

In [ ]:
ru888

In [ ]:
def tbDataToVnpy(filePath,fileName,savePath,newName):
    '''Adjust format of data downloaded from TradeBlazer to Vnpy data format.
    Input: 
    filePath: String.Old path for original csv data.
    fileName: String.Old file name for original csv data.
    savePath: String.new path for adjusted csv data.
    newName: String.new Name for adjusted csv data.'''
    data = pd.read_csv(filePath+fileName,infer_datetime_format=True,header=None,names = ['Open', 'High', 'Low', 'Close','TotalVolume','Position'])
    data.index = data.index.map(lambda x : pd.to_datetime(x))
    data['Time'] = data.index.map(lambda x : x.time)
    data.index = data.index.map(lambda x : x.date)
    data.index.name = 'Date'
    data.drop('Position',axis=1,inplace = True)
    data.to_csv(savePath+newName,na_rep='NaN',date_format='%Y%m%d')
    return data

In [ ]:
old_path = 'C:/Users/LZJF_02/Desktop/original_data/'
new_path = 'C:/Users/LZJF_02/Desktop/modified_data/'
filename = 'ru000_1min.csv'
newname = 'ru000_1min_modi.csv'

In [ ]:
#c = tbDataToVnpy(old_path,filename,new_path,newname)

In [ ]: