def a(x1, x2, L): d = [] x1 = int(x1) x2 = int(x2) for i in range(x1, x2): if (i not in date2): continue d.append(i) start1 = datetime.strptime(start, "%Y-%m-%d") t1 = str(start1 + timedelta(x1 - datestr2num(start)))[0:10] t2 = str(start1 + timedelta(x2 - datestr2num(start)))[0:10] ti = str(start1 + timedelta(i - datestr2num(start)))[0:10] d.append( culDistence(x1, closePrice[t1], x2, closePrice[t2], i, closePrice[ti])) # index=d.index(max(d)) if len(d) == 0: return d1 = [d[i] for i in range(1, len(d), 2)] #不包含索引的list maxD = max(d1) if maxD < L: return else: index = d[d.index(maxD) - 1] result.append(index) a(x1, index, L) a(index, x2, L)
def setUp(self): n=1000 # slows down significantly! constraint is percentile test x = sc.randn(n)*100. # generate dummy data self.D = Data(None, None) d=np.ones((n, 1, 1)) self.D.data = d self.D.data[:,0,0]=x self.D.data = np.ma.array(self.D.data, mask=self.D.data != self.D.data) self.D.verbose = True self.D.unit = 'myunit' self.D.label = 'testlabel' self.D.filename = 'testinputfilename.nc' self.D.varname = 'testvarname' self.D.long_name = 'This is the longname' self.D.time = np.arange(n) + pl.datestr2num('2001-01-01') self.D.time_str = "days since 0001-01-01 00:00:00" self.D.calendar = 'gregorian' self.D.oldtime=False # generate dummy Model object data_dir = './test/' varmethods = {'albedo':'get_albedo()', 'sis': 'get_sis()'} self.model = models.Model(data_dir, varmethods, name='testmodel', intervals='monthly') sis = self.D.copy() sis.mulc(5., copy=False) sis.label='sisdummy' alb = self.D.copy() alb.label='albedodummy' # add some dummy data variable self.model.variables = {'albedo':alb, 'sis':sis}
def setUp(self): self.map_plot = mapping.MapPlotGeneric() # data for testing n=1000 # slows down significantly! constraint is percentile test x = sc.randn(n)*100. # generate dummy data self.D = Data(None, None) ny=10 nx=20 d=np.ones((n, ny, nx)) self.D.data = d for i in xrange(ny): for j in xrange(nx): self.D.data[:, i, j] = x[:] self.D.data = np.ma.array(self.D.data, mask=self.D.data != self.D.data) self.D.verbose = True self.D.unit = 'myunit' self.D.label = 'testlabel' self.D.filename = 'testinputfilename.nc' self.D.varname = 'testvarname' self.D.long_name = 'This is the longname' self.D.time = np.arange(n) + pl.datestr2num('2001-01-01') self.D.time_str = "days since 0001-01-01 00:00:00" self.D.calendar = 'gregorian' self.D.cell_area = np.ones((ny, nx)) self.D.lon = np.random.random((ny,nx))*10. self.D.lat = np.random.random((ny,nx))*20. self._tmpdir = tempfile.mkdtemp()
def get_stock_plot(code, start, end, session_id=''): # get history res_table = ts.get_hist_data(code, start, end) sh_res_table = ts.get_hist_data('sh', start, end) print(res_table) # string to date print(res_table.index.values) x_date = [datestr2num(i) for i in res_table.index.values] # draw fig = plt.figure(figsize=(10, 5)) # matplotlib doesn't support chinese plt.title(u"percentage - date") plt.xlabel(u"date") plt.ylabel(u"percentage") plt.plot_date(x_date, res_table['p_change'], '-', label="change percentage") plt.plot_date(x_date, sh_res_table['p_change'], '-', label="change percentage") # plt.legend() plt.grid(True) # fig.savefig('test.png', format='png') # plt.show() sio = BytesIO() fig.savefig(sio, format='png') data = base64.encodebytes(sio.getvalue()).decode() return data
def fun(x1, x2, L): global result result = [] a(x1, x2, L) result = [date2[0]] + sorted(result) + [date2[-1]] # 画图部分 start1 = datetime.strptime(start, "%Y-%m-%d") profitRate = 1 for i in range(0, len(result) - 1): ii = str(start1 + timedelta(result[i] - datestr2num(start)))[0:10] #数字转化为日期 ii1 = str(start1 + timedelta(result[i + 1] - datestr2num(start)))[0:10] p0 = closePrice[ii] p1 = closePrice[ii1] plt.plot_date([result[i], result[i + 1]], [p0, p1], 'r-') if p1 > p0: profitRate *= 1 + ((1 - Fee) * p1 - (1 + Fee) * p0) / ((1 + Fee) * p0) print(profitRate)
def setUp(self): #init Data object for testing n=4 #slows down significantly! constraint is percentile test x = sc.randn(n)*100. #generate dummy data self.D = Data(None,None) d=np.ones((n,1,2)) self.D.data = d self.D.data[:,0,0]=x self.D.data = np.ma.array(self.D.data,mask=self.D.data != self.D.data) self.D.verbose = True self.D.unit = 'myunit' self.D.time = np.arange(n) + pl.datestr2num('2001-01-01') - 1
def fun(x1, x2, L): global result result = [] a(x1, x2, L) # fileHeader = ["start", "end","duration","slope"] datacsv = open("data.csv", "w", newline="") csvwriter = csv.writer(datacsv, dialect=("excel")) result = [date2[0]] + sorted(result) + [date2[-1]] # 画图部分 start1 = datetime.strptime(start, "%Y-%m-%d") for i in range(0, len(result) - 1): ii = str(start1 + timedelta(result[i] - datestr2num(start)))[0:10] #数字转化为日期 ii1 = str(start1 + timedelta(result[i + 1] - datestr2num(start)))[0:10] p0 = closePrice[ii] p1 = closePrice[ii1] plt.plot_date([result[i], result[i + 1]], [p0, p1], 'r-') #保存为csv格式 csvwriter.writerow([ ii, ii1, date2.index(result[i + 1]) - date2.index(result[i]), (p1 - p0) / (result[i + 1] - result[i]) ])
def sort_MMSI(traj): ##############筛选特定海域的,以及满足各种特定限制范围的正常数据#################### traj = traj[(traj['YCoord'] <= 43.2) & (traj['YCoord'] >= 29.7)] #海域范围北纬29.7-43.2之间 traj = traj[(traj['STATUS'] <= 8)] #正常航行或者停泊状态 traj = traj[(traj['HEADING'] < 360)] #船头朝向范围[0,360) traj = traj[(traj['SOG'] <= 50)] #速度小于50节 traj = traj[~((traj['SOG'] == 0) & (traj['STATUS'] == 0))] #船速为0,但是状态却为航行的错误数据 ###################按照MMSI和时间顺序,排列出每条轨迹############################ a = traj['BASEDATETIME'] traj['BASEDATETIME'] = datestr2num(a) traj = traj.sort_values(by=['MMSI', 'BASEDATETIME']) traj = traj.reset_index(drop=True) return traj
def generate_monthly_timeseries(t, sday='01'): """ generate a vector monthly timeseries t: time (numeric) """ tn = [] d = pl.num2date(t) for i in range(len(t)): y = str(d[i].year).zfill(4) m = str(d[i].month).zfill(2) s = y + '-' + m + '-' + sday tn.append(pl.datestr2num(s)) return tn
def setUp(self): # init Data object for testing n=100 # slows down significantly! constraint is percentile test x = sc.randn(n)*100. # generate dummy data self.D = Data(None, None) d=np.ones((n, 1, 1)) self.D.data = d self.D.data[:,0,0]=x self.D.data = np.ma.array(self.D.data, mask=self.D.data != self.D.data) self.D.verbose = True self.D.unit = 'myunit' self.D.label = 'testlabel' self.D.filename = 'testinputfilename.nc' self.D.varname = 'testvarname' self.D.long_name = 'This is the longname' self.D.time = np.arange(n) + pl.datestr2num('2001-01-01') - 1 self.D.time_str = "days since 0001-01-01 00:00:00" self.D.calendar = 'gregorian' self.D.cell_area = np.ones_like(self.D.data[0,:,:])
def setUp(self): # init Data object for testing n = 100 # slows down significantly! constraint is percentile test x = sc.randn(n) * 100. # generate dummy data self.D = Data(None, None) d = np.ones((n, 1, 1)) self.D.data = d self.D.data[:, 0, 0] = x self.D.data = np.ma.array(self.D.data, mask=self.D.data != self.D.data) self.D.verbose = True self.D.unit = 'myunit' self.D.label = 'testlabel' self.D.filename = 'testinputfilename.nc' self.D.varname = 'testvarname' self.D.long_name = 'This is the longname' self.D.time = np.arange(n) + pl.datestr2num('2001-01-01') - 1 self.D.time_str = "days since 0001-01-01 00:00:00" self.D.calendar = 'gregorian' self.D.cell_area = np.ones_like(self.D.data[0, :, :])
def mainPieceWise(L, path): #分段主函数 files = os.listdir(path) #得到文件夹下的所有文件名称 for code in files: #遍历文件夹 closePrice = [] #收盘价 date = [] #字符串日期 filePath = path + "/" + code + "/" + code + ".csv" #csv文件名 with open(filePath) as f: f_csv = csv.reader(f) headers = next(f_csv) # 略过第一行列名 for row in f_csv: closePrice.append(row[3]) date.append(row[0]) os.chdir(path + "/" + code) #更改当前文件夹,进行文件的保存 closePrice = [float(i) for i in closePrice][::-1] date = [str(i)[:10] for i in date][::-1] #字符串日期 dateToNum = [datestr2num(i) for i in date] #将日期转为数字进行坐标表示 #画原始数据图 plt.gcf().set_size_inches(12, 4) plt.plot_date(dateToNum, closePrice, 'b-') #调用线性分段函数 pieceWise(dateToNum, L, closePrice, code)
def get_bond_stocks_pe_infos(): addr = host_address + '/stock/get_stocks_bonds_pe' r = requests.get(addr) if r.status_code == 200: result = json.loads(r.text) pe_history = json.loads(result['pe_history']) data = pd.DataFrame(pe_history) data['bond_yield'] = 100 / data['bond_pe'] data['stock_yield'] = 100 / data['stocks_pe'] x = range(len(data)) x_date = [datestr2num(i) for i in data['trade_date']] plt.style.use('ggplot') plt.figure(figsize=(14, 4)) plt.title("10年期国债收益率与全市场股票收益率(%)") plt.xticks(rotation=45) plt.ylabel("收益率") plt.plot_date(x_date, data['bond_yield'], '-', label="10年期国债收益率") plt.plot_date(x_date, data['stock_yield'], '-', label="全市场股票收益率") plt.legend() plt.grid(True) pic_path = sys.path[0] + '\\bond_stocks_yield.png' if os.path.exists(pic_path): os.remove(pic_path) print('删除历史文件bond_stocks_yield.png') print('生成图片:' + pic_path) plt.savefig(pic_path) # 保存图片 with open(pic_path, "rb") as f: base64_data = base64.b64encode(f.read()) global pic_base64 pic_base64 = pic_base64 + str(base64_data)[2:-1] print('将图片转化为base64') print(pic_base64) else: raise Exception('更新每日数据接口【get_bond_stocks_pe_infos】调用失败')
def test_gleckler_index(self): """ test Reichler index/Gleckler plot """ # generate sample data # sample data tmp = np.zeros((5, 3, 1)) tmp[:, 0, 0] = np.ones(5) * 1. tmp[:, 1, 0] = np.ones(5) * 2. tmp[:, 2, 0] = np.ones(5) * 5. # The data is like ... #| 1 | 2 | 5 | #| 1 | 2 | 5 | #| 1 | 2 | 5 | #| 1 | 2 | 5 | #| 1 | 2 | 5 | x = self.D.copy() x._temporal_subsetting(0, 4) x.data = np.ma.array(tmp, mask=tmp != tmp) x.std = np.ones(x.data.shape) x.time[0] = pl.datestr2num('2000-02-15') x.time[1] = pl.datestr2num('2000-03-15') x.time[2] = pl.datestr2num('2000-04-15') x.time[3] = pl.datestr2num('2000-05-15') x.time[4] = pl.datestr2num('2000-06-15') y = self.D.copy() y._temporal_subsetting(0, 4) tmp = np.ones(x.data.shape) # sample data 2 y.data = np.ma.array(tmp, mask=tmp != tmp) y.time[0] = pl.datestr2num('2000-02-15') y.time[1] = pl.datestr2num('2000-03-15') y.time[2] = pl.datestr2num('2000-04-15') y.time[3] = pl.datestr2num('2000-05-15') y.time[4] = pl.datestr2num('2000-06-15') # Case 1: same area weights # cell area tmp = np.ones((3, 1)) x.cell_area = tmp * 1. #| 1-1 | 2-1 | 5-1 | #| 1-1 | 2-1 | 5-1 | #| 1-1 | 2-1 | 5-1 | #| 1-1 | 2-1 | 5-1 | #| 1-1 | 2-1 | 5-1 | #=================== #| 0 | 5 | 5*4**2=5*16. = 80 | #==> E2 = sqrt(85./(15.)) D = GlecklerPlot() r = D.calc_index(x, y, 'a', 'b', time_weighting=False) wt = np.ones(5) / 5. ref = np.sqrt(((85. / 15.) * wt).sum()) t = np.abs(1. - r / ref) self.assertLess(t, 0.000001) # relative error D = GlecklerPlot() r = D.calc_index(x, y, 'a', 'b') wt = np.asarray([29., 31., 30., 31., 30.]) wt = wt / wt.sum() ref = np.sqrt(((85. / 15.) * wt).sum()) t = np.abs(1. - r / ref) self.assertLess(t, 0.000001) # relative error # Case 2: Different area weights # cell area tmp = np.ones((3, 1)) tmp[1, 0] = 2. x.cell_area = tmp * 1. #| 1-1=0 | 2-1=1 | 5-1=16 | #| 1-1=0 | 2-1=1 | 5-1=16 | #| 1-1=0 | 2-1=1 | 5-1=16 | #| 1-1=0 | 2-1=1 | 5-1=16 | #| 1-1=0 | 2-1=1 | 5-1=16 | #-------------------------- # w = 0.25 w = 0.5 w=0.25| #-------------------------- # 0.25*0 + 0.5 * 1 + 0.25 * 16 = 0 + 0.5 + 4 = 4.5 # the mean of that is 4.5 for each timestep # mean because the overall weights are calculated as such that # they give a total weight if 1 # diagnostic D = GlecklerPlot() r = D.calc_index(x, y, 'a', 'b', time_weighting=False) wt = np.ones(5) / 5. ref = np.sqrt((4.5 * wt).sum()) t = np.abs(1. - r / ref) self.assertLess(t, 0.000001) # relative error wt = np.asarray([29., 31., 30., 31., 30.]) wt = wt / wt.sum() ref = np.sqrt((4.5 * wt).sum()) t = np.abs(1. - r / ref) self.assertLess(t, 0.000001) # relative error # Case 3: use different std x.std = np.ones(x.data.shape) x.std[:, 2, 0] = 0.5 #| 1-1=0 | 2-1=1 | 5-1=16 / 0.5 | #| 1-1=0 | 2-1=1 | 5-1=16 / 0.5 | #| 1-1=0 | 2-1=1 | 5-1=16 / 0.5 | #| 1-1=0 | 2-1=1 | 5-1=16 / 0.5 | #| 1-1=0 | 2-1=1 | 5-1=16 / 0.5 | #-------------------------------- # w = 0.25 w = 0.5 w=0.25| # 0 + 0.5 + 0.25*32 = 0.5 + 8 = 8.5 D = GlecklerPlot() r = D.calc_index(x, y, 'a', 'b', time_weighting=False) wt = np.ones(5) / 5. ref = np.sqrt((8.5 * wt).sum()) t = np.abs(1. - r / ref) self.assertLess(t, 0.000001) # relative error wt = np.asarray([29., 31., 30., 31., 30.]) wt = wt / wt.sum() ref = np.sqrt((8.5 * wt).sum()) t = np.abs(1. - r / ref) self.assertLess(t, 0.000001) # relative error
DM = '000002' global csvInput csvInput = [] sns.set_style("whitegrid") end = datetime.today() #开始时间结束时间,选取最近一年的数据 start = datetime(end.year, end.month - 3, end.day) end = str(end)[0:10] start = str(start)[0:10] getData = ts.get_hist_data(DM, start, end) closePrice = getData.close #收盘价 closePrice = closePrice[::-1] #按日期从低到高 date1 = getData.index #日期 date1 = date1[::-1] #按日期从低到高 date2 = [datestr2num(i) for i in date1] #将日期转为数字进行坐标表示 plt.gcf().set_size_inches(12, 4) plt.plot_date(date2, closePrice, 'b-') #买卖的的判断画图 chiyou = [] #预计持有日期 uptrend = [] #预计上升日期 downtrend = [] #预计下跌日期 chiyouPrice = [] #持有价钱 uptrendPrice = [] #上升价钱 downtrendPrice = [] #下跌价钱 for i in date1: cul, count1 = culKDJ.cul_KDJ(DM, i, 9) count += count1 if cul == 0:
import numpy as np import matplotlib.pyplot as plt import matplotlib.pylab as pylab import matplotlib.mlab as mlab from scipy.interpolate import UnivariateSpline as spline from glob import glob files = sorted(glob("grand-island-test-wenzel-*.csv")) # pumping start and end times t0 = pylab.datestr2num('07/29/1931 06:05:00') t1 = pylab.datestr2num('07/31/1931 06:04:00') print 'test length in seconds:', (t1 - t0) * 1440 * 60 tlen = (t1 - t0) * 1440 # column 0: date # column 1: time # column 2: drawdown (ft) individualplots = True computesplinederiv = True drawdowncheck = True mapcheckplot = True saveMetricDecimalData = True # apply uniform min/max derivatives to all data ydmin, ydmax = (-0.2, 1.0) if drawdowncheck:
def test_gleckler_index(self): """ test Reichler index/Gleckler plot """ # generate sample data # sample data tmp = np.zeros((5, 3, 1)) tmp[:,0,0] = np.ones(5)*1. tmp[:,1,0] = np.ones(5)*2. tmp[:,2,0] = np.ones(5)*5. # The data is like ... #| 1 | 2 | 5 | #| 1 | 2 | 5 | #| 1 | 2 | 5 | #| 1 | 2 | 5 | #| 1 | 2 | 5 | x = self.D.copy() x._temporal_subsetting(0, 4) x.data = np.ma.array(tmp, mask=tmp!=tmp) x.std = np.ones(x.data.shape) x.time[0] = pl.datestr2num('2000-02-15') x.time[1] = pl.datestr2num('2000-03-15') x.time[2] = pl.datestr2num('2000-04-15') x.time[3] = pl.datestr2num('2000-05-15') x.time[4] = pl.datestr2num('2000-06-15') y = self.D.copy() y._temporal_subsetting(0, 4) tmp = np.ones(x.data.shape) # sample data 2 y.data = np.ma.array(tmp, mask=tmp!=tmp) y.time[0] = pl.datestr2num('2000-02-15') y.time[1] = pl.datestr2num('2000-03-15') y.time[2] = pl.datestr2num('2000-04-15') y.time[3] = pl.datestr2num('2000-05-15') y.time[4] = pl.datestr2num('2000-06-15') # Case 1: same area weights # cell area tmp = np.ones((3, 1)) x.cell_area = tmp*1. #| 1-1 | 2-1 | 5-1 | #| 1-1 | 2-1 | 5-1 | #| 1-1 | 2-1 | 5-1 | #| 1-1 | 2-1 | 5-1 | #| 1-1 | 2-1 | 5-1 | #=================== #| 0 | 5 | 5*4**2=5*16. = 80 | #==> E2 = sqrt(85./(15.)) D = GlecklerPlot() r = D.calc_index(x, y, 'a', 'b', time_weighting=False) wt = np.ones(5) / 5. ref = np.sqrt(((85./15.) * wt).sum()) t = np.abs(1. - r / ref) self.assertLess(t, 0.000001) # relative error D = GlecklerPlot() r = D.calc_index(x, y, 'a', 'b') wt = np.asarray([29., 31., 30., 31., 30.]) wt = wt / wt.sum() ref = np.sqrt(((85./15.) * wt).sum()) t = np.abs(1. - r / ref) self.assertLess(t, 0.000001) # relative error # Case 2: Different area weights # cell area tmp = np.ones((3, 1)) tmp[1, 0] = 2. x.cell_area = tmp*1. #| 1-1=0 | 2-1=1 | 5-1=16 | #| 1-1=0 | 2-1=1 | 5-1=16 | #| 1-1=0 | 2-1=1 | 5-1=16 | #| 1-1=0 | 2-1=1 | 5-1=16 | #| 1-1=0 | 2-1=1 | 5-1=16 | #-------------------------- # w = 0.25 w = 0.5 w=0.25| #-------------------------- # 0.25*0 + 0.5 * 1 + 0.25 * 16 = 0 + 0.5 + 4 = 4.5 # the mean of that is 4.5 for each timestep # mean because the overall weights are calculated as such that # they give a total weight if 1 # diagnostic D = GlecklerPlot() r = D.calc_index(x, y, 'a', 'b', time_weighting=False) wt = np.ones(5) / 5. ref = np.sqrt((4.5 * wt).sum()) t = np.abs(1. - r / ref) self.assertLess(t, 0.000001) # relative error wt = np.asarray([29., 31., 30., 31., 30.]) wt = wt / wt.sum() ref = np.sqrt((4.5 * wt).sum()) t = np.abs(1. - r / ref) self.assertLess(t, 0.000001) # relative error # Case 3: use different std x.std = np.ones(x.data.shape) x.std[:, 2, 0] = 0.5 #| 1-1=0 | 2-1=1 | 5-1=16 / 0.5 | #| 1-1=0 | 2-1=1 | 5-1=16 / 0.5 | #| 1-1=0 | 2-1=1 | 5-1=16 / 0.5 | #| 1-1=0 | 2-1=1 | 5-1=16 / 0.5 | #| 1-1=0 | 2-1=1 | 5-1=16 / 0.5 | #-------------------------------- # w = 0.25 w = 0.5 w=0.25| # 0 + 0.5 + 0.25*32 = 0.5 + 8 = 8.5 D = GlecklerPlot() r = D.calc_index(x, y, 'a', 'b', time_weighting=False) wt = np.ones(5) / 5. ref = np.sqrt((8.5 * wt).sum()) t = np.abs(1. - r / ref) self.assertLess(t, 0.000001) # relative error wt = np.asarray([29., 31., 30., 31., 30.]) wt = wt / wt.sum() ref = np.sqrt((8.5 * wt).sum()) t = np.abs(1. - r / ref) self.assertLess(t, 0.000001) # relative error
import numpy as np import matplotlib.pyplot as plt import matplotlib.pylab as pylab import matplotlib.mlab as mlab from scipy.interpolate import UnivariateSpline as spline from glob import glob files = sorted(glob("grand-island-test-wenzel-*.csv")) # pumping start and end times t0 = pylab.datestr2num("07/29/1931 06:05:00") t1 = pylab.datestr2num("07/31/1931 06:04:00") print "test length in seconds:", (t1 - t0) * 1440 * 60 tlen = (t1 - t0) * 1440 # column 0: date # column 1: time # column 2: drawdown (ft) individualplots = True computesplinederiv = True drawdowncheck = True mapcheckplot = True saveMetricDecimalData = True # apply uniform min/max derivatives to all data ydmin, ydmax = (-0.2, 1.0) if drawdowncheck:
def main(): funds = [ # # 股票基金 {"code": "004851", "name": "广发医疗保健股票"}, {"code": "000913", "name": "农银医疗保健股票"}, {"code": "000960", "name": "招商医药健康产业股票"}, # # 债券基金 {"code": "005461", "name": "南方希元转债"}, {"code": "000080", "name": "天治可转债增强债券A"}, {"code": "004993", "name": "中欧可转债债券A"}, # # # 混合基金 {"code": "050026", "name": "博时医疗保健行业混合A"}, {"code": "003096", "name": "中欧医疗健康混合C"}, {"code": "005689", "name": "中银医疗保健混合"}, # # # 大盘指数基金 {"code": "070039", "name": "嘉实中证500ETF联接C"}, {"code": "002987", "name": "广发沪深300ETF联接C"}, # # 行业指数基金 {"code": "161035", "name": "富国中证医药主题指数增强"}, {"code": "161122", "name": "易方达生物分级"}, {"code": "161726", "name": "招商国证生物医药指数分级"}, ] if USE_ALL_FUNDS: print("拉取全部基金列表") funds = [] allFunds = AllFundDownloader() for fund in allFunds.funds: funds.append({ "code": fund.code, "name": fund.name, }) # 下载每日净值图 if FETCH_FUNDS_GUZHI: guzhi_images_dir = "guzhi_images" print("下载每日净值图到{}".format(guzhi_images_dir)) # 创建结果目录 shutil.rmtree(guzhi_images_dir, True) pathlib.Path(guzhi_images_dir).mkdir(parents=True, exist_ok=True) for idx, fund in enumerate(funds): chartDownloader = FundGuzhiChartDownloader(fund["code"], fund["name"], guzhi_images_dir) res = "" if chartDownloader.save_to_local(): res = "成功" else: res = "失败" print("[{}/{}] 下载{}-{}成功, url={}".format(idx + 1, len(funds), chartDownloader.code, chartDownloader.name, chartDownloader.url)) # 合并为一个图 print("合并为单个图") images_to_merge = [] for filename in os.listdir(guzhi_images_dir): filepath = os.path.join(guzhi_images_dir, filename) if filename.endswith(".png"): images_to_merge.append(filepath) merge_images_vertically_and_display(images_to_merge) peroids = [ 7, 14, 30, ] now = datetime.datetime.now().strftime("%Y-%m-%d") lastMonth = (datetime.datetime.now() - datetime.timedelta(days=int(365 / 12 * 1))).strftime("%Y-%m-%d") lastTwoMonth = (datetime.datetime.now() - datetime.timedelta(days=int(365 / 12 * 2))).strftime("%Y-%m-%d") lastSeason = (datetime.datetime.now() - datetime.timedelta(days=int(365 / 12 * 3))).strftime("%Y-%m-%d") lastFourMonth = (datetime.datetime.now() - datetime.timedelta(days=int(365 / 12 * 4))).strftime("%Y-%m-%d") lastFiveMonth = (datetime.datetime.now() - datetime.timedelta(days=int(365 / 12 * 5))).strftime("%Y-%m-%d") lastHalfYear = (datetime.datetime.now() - datetime.timedelta(days=int(365 / 12 * 6))).strftime("%Y-%m-%d") lastYear = (datetime.datetime.now() - datetime.timedelta(days=int(365))).strftime("%Y-%m-%d") times = [ {"start": "2016-01-01", "end": "2017-01-01"}, # 2016年 {"start": "2017-01-01", "end": "2018-01-01"}, # 2017年 {"start": "2018-01-01", "end": "2019-01-01"}, # 2018年 {"start": "2016-01-01", "end": now}, # 2016年至今 {"start": "2017-01-01", "end": now}, # 2017年至今 {"start": "2018-01-01", "end": now}, # 2018年至今 {"start": "2019-01-01", "end": now}, # 2019年至今 {"start": lastMonth, "end": now}, # 上个月 {"start": lastTwoMonth, "end": now}, # 前两个月 {"start": lastSeason, "end": now}, # 上个季度 {"start": lastFourMonth, "end": now}, # 前四个月 {"start": lastFiveMonth, "end": now}, # 前五个月 {"start": lastHalfYear, "end": now}, # 前半年 {"start": lastYear, "end": now}, # 前年 ] fund_deal_map = {} for idx, fund in enumerate(funds): # 获取基金数据 print("[%d/%d] Loading data for %s" % (idx + 1, len(funds), fund["name"])) fund_deal_map[fund["name"]] = BackTrackingDeal(fund["code"], fund["name"], DingtouStrategy(days=1)) if DRAW_PLOTS: # 绘走势图 # plt.style.use('ggplot') plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 # plt.title(u'基金走势图') fig, axs = plt.subplots(len(fund_deal_map), figsize=(10, 5 * len(fund_deal_map))) idx = 0 start_dingtou_time = "2019-10-15" for name, fund in fund_deal_map.items(): data = fund.get_range_data(start_dingtou_time, now) # data = fund.fund.data x = range(len(data)) x_date = [datestr2num(i.time) for i in data] y_data = [i.unit_net_value for i in data] fund.strategy = DingtouStrategy(days=30) profit = fund.run(start_dingtou_time, now) total_change_rate = (data[-1].unit_net_value - data[0].unit_net_value) / data[0].unit_net_value * 100 axs[idx].plot_date(x_date, y_data, '-', label=u"%s-%s-[%f%%]-[%s]" % (fund.fund_code, fund.fund_name, total_change_rate, profit["profit_rate"])) for day in get_dingtou_days(): axs[idx].axvline(datestr2num(day), ymin=0.0, ymax=1.0, color="gray") axs[idx].legend() axs[idx].grid(True) idx += 1 plt.xlabel(u'时间') plt.ylabel(u'单位净值') # plt.show() plt.savefig("profit.png") webbrowser.get("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s").open("profit.png") # 清空结果目录 shutil.rmtree("result") print("output directory cleared") for t in times: start = t["start"] end = t["end"] duration = (datetime.datetime.strptime(end, "%Y-%m-%d") - datetime.datetime.strptime(start, "%Y-%m-%d")).days file_name = "result/%s_%s.csv" % (start, end) if not os.path.exists(os.path.dirname(file_name)): os.makedirs(os.path.dirname(file_name)) summary = {} for peroid in peroids: summary[peroid] = { "fund_name": "平均", "duration": duration, "strategy": "%d天" % peroid, "invest_money": 0.001, "profit": 0.0, "profit_rate": "0%", "annualized_profit_rate": "0%", } outputs = [] for fund in funds: fund_deal = fund_deal_map[fund["name"]] for peroid in peroids: # 尝试不同策略 strategy = DingtouStrategy(days=peroid) fund_deal.strategy = strategy profit = fund_deal.run(start, end) if len(profit) != 0: outputs.append({ "fund_name": fund["name"], "duration": duration, "strategy": strategy.name(), "invest_money": profit["invest_money"], "profit": profit["profit"], "profit_rate": profit["profit_rate"], "annualized_profit_rate": profit["annualized_profit_rate"], }) # show status line = "%s,%s天,%s,%s,%s,%s,%s" % ( fund["name"], duration, strategy.name(), profit["invest_money"], profit["profit"], profit["profit_rate"], profit["annualized_profit_rate"]) print(line) summary[peroid]["invest_money"] += profit["invest_money"] summary[peroid]["profit"] += profit["profit"] outputs.sort(key=lambda x: x["profit"], reverse=True) for k, v in summary.items(): v["profit_rate"] = "%.4f%%" % (100 * v["profit"] / v["invest_money"]) v["annualized_profit_rate"] = "%.4f%%" % (100 * v["profit"] / v["invest_money"] * 365 / duration) outputs.append(v) with open(file_name, "w+") as ouput_file: print("名称,时长,定投周期,总投入,总盈利,总盈利率,年化利率", file=ouput_file) for output in outputs: line = "%s,%s天,%s,%s,%s,%s,%s" % ( output["fund_name"], output["duration"], output["strategy"], output["invest_money"], output["profit"], output["profit_rate"], output["annualized_profit_rate"]) print(line, file=ouput_file)
return positions #%% positions = trading() strategy_positions = pd.DataFrame(positions) return_strategy = (strategy_positions / strategy_positions.shift()) - 1 return_strategy = return_strategy.cumsum() hsa_closeIndex = pd.DataFrame(hsa.closeIndex) return_hsa = (hsa_closeIndex / hsa_closeIndex.shift()) - 1 return_hsa = return_hsa.cumsum() matplotlib.use('qt4agg') myfont = FontProperties(fname='C:\Windows\Fonts\simhei.ttf') matplotlib.rcParams['axes.unicode_minus'] = False plt.figure(figsize=(10, 5)) plt.title(u"累计收益率", fontproperties=myfont) x_date = [datestr2num(i) for i in hsa.tradeDate] plt.plot_date(x_date, return_hsa, '-') plt.plot_date(x_date, return_strategy, '-', color='r') plt.legend(['恒生指数', '策略累计收益率'], prop=myfont) #date = pd.to_datetime(hsa.tradeDate) #hsa_hist = pd.DataFrame({'closeIndex':hsa.closeIndex},index=hsa.tradeDate) #plt.plot(hsa_hist) #plt.show()