박하늘

Merge branch 'develop' of http://khuhub.khu.ac.kr/2017103989/stock_chatbot into develop

1 -def GMM(): 1 +import datetime
2 - pass 2 +import pandas as pd
3 +import numpy as np
4 +import FinanceDataReader as fdr
5 +from scipy.optimize import minimize
6 +import json
3 7
4 -def backtest():
5 - pass
...\ No newline at end of file ...\ No newline at end of file
8 +class c_Models:
9 + #Input 값으로, 자산 list, 사용자 포트폴리오 비중, 시작일, 마지막일
10 + def __init__(self, assets, assets_w, start, end):
11 + self.result = None
12 + self.graph = None
13 +
14 + data = pd.DataFrame()
15 + # 전체 자산 data들을 가지고 온 후, 정리함
16 + for asset in assets: #total_list:
17 + tmp = fdr.DataReader(asset,start,end).Close
18 + tmp.rename(columns={'Close': asset}, inplace=True)
19 + data = pd.concat([data, tmp], axis=1)
20 +
21 + if data.isnull().values.any() == True: #불러온 data에 오류가 있다면
22 + return "No Data",''
23 +
24 + else:
25 + data = data.resample('M').mean() #일별 데이터를 월별 데이터로 만들어줌
26 + data = data.pct_change() #월별 주가 데이터를 이용해 수익률 데이터로 변환
27 + data.dropna(inplace=True) #결측치 제외(첫 row)
28 +
29 + self.data = data
30 + self.assets_w = assets_w
31 + self.mu = data.mean() * 12
32 + self.cov = data.cov() * 12
33 +
34 + #GMV 최적화 : 제약 조건은 비중합=1, 공매도 불가능
35 + def gmv_opt(self):
36 + n_assets = len(self.data.columns)
37 + w0 = np.ones(n_assets) / n_assets
38 + fun = lambda w: np.dot(w.T, np.dot(self.cov, w))
39 + constraints = ({'type':'eq', 'fun':lambda x: np.sum(x)-1})
40 + bd = ((0,1),) * n_assets
41 + #cov = data.cov() * 12
42 +
43 + gmv = minimize(fun, w0, method = 'SLSQP', constraints=constraints, bounds=bd)
44 + return gmv.x
45 +
46 + #Max Sharp ratio : risk free rate은 0.8%로 지정했고,
47 + def ms_opt(self):
48 + n_assets = len(self.data.columns)
49 + w0 = np.ones(n_assets) / n_assets
50 + fun = lambda w: -(np.dot(w.T, self.mu) - 0.008) / np.sqrt(np.dot(w.T, np.dot(self.cov, w)))
51 + bd = ((0,1),) * n_assets
52 + constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
53 + maxsharp = minimize(fun, w0, method ='SLSQP', constraints=constraints, bounds=bd)
54 + return maxsharp.x
55 +
56 + def rp_opt(self):
57 + def RC(cov, w):
58 + pfo_std = np.sqrt(np.dot(w.T, np.dot(self.cov, w)))
59 + mrc = 1/pfo_std * (np.dot(self.cov, w))
60 + rc = mrc * w
61 + rc = rc / rc.sum()
62 + return rc
63 +
64 +
65 + def RP_objective(x):
66 + pfo_std = np.sqrt(np.dot(x.T, np.dot(self.cov, x)))
67 + mrc = 1/pfo_std * (np.dot(self.cov, x))
68 + rc = mrc * x
69 + rc = rc / rc.sum()
70 +
71 + a = np.reshape(rc, (len(rc),1))
72 + differs = a - a.T
73 + objective = np.sum(np.square(differs))
74 +
75 + return objective
76 +
77 + n_assets = len(self.data.columns)
78 + w0 = np.ones(n_assets) / n_assets
79 + constraints = [{'type':'eq', 'fun': lambda x: np.sum(x) -1}]
80 + bd = ((0,1),) * n_assets
81 +
82 + rp = minimize(RP_objective, w0, constraints=constraints, bounds = bd, method='SLSQP')
83 +
84 + return rp.x #, RC(self.cov, rp.x)
......