-
Notifications
You must be signed in to change notification settings - Fork 0
/
lmts.py
278 lines (208 loc) · 6.52 KB
/
lmts.py
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/usr/bin/env python
# coding: utf-8
import os
import subprocess
import inspect
from typing import Union, List
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
import plotly.express as px
import plotly.offline as offline
import plotly.graph_objects as go
def create_appdata():
"""
Data dizini altında app klasörü oluşturur.
app klasöründe uygulama verileri saklanır.
"""
try:
os.mkdir('data/app')
except FileExistsError:
pass
def retrieve_name(var):
"""
Getting the name of a variable as a string"""
callers_local_vars = inspect.currentframe().f_back.f_locals.items()
return [var_name for var_name, var_val in callers_local_vars if var_val is var][0]
def ln(data: Union[List[pd.DataFrame], pd.DataFrame]) -> Union[List[pd.DataFrame], pd.DataFrame]:
"""
Doğal logaritmayı hesaplar.
Args:
data (Dataframe or list)
Returns:
Dataframe or List
"""
if isinstance(data, list):
ln_list = []
for _df in data:
ln_list.append(np.log(_df))
return ln_list
return np.log(data)
def diff(df: pd.DataFrame, subtrahend: str, drop: bool = False) -> Union[pd.DataFrame, list]:
"""
Verinin subtrahend ile belirtilen sütundan farkını alın.
Args:
df : Dataframe or List
subtrahend : Çıkarılacak sütun adı. Ortalama için 'mean' ayarlanmalı.
drop: subtrahend ile belirtilen sütun dataframe'den çıkarılsın mı?
Returns:
Union[pd.DataFrame, list]
"""
if isinstance(df, list):
diff_list = []
for _df in df:
if subtrahend == 'mean':
diff_value = _df.mean(axis=1)
else:
diff_value = _df[subtrahend]
diff = _df.sub(diff_value, axis=0)
if drop:
diff = diff.drop(subtrahend, axis=1)
diff_list.append(diff)
return diff_list
if subtrahend == 'mean':
diff_value = df.mean(axis=1)
else:
diff_value = df[subtrahend]
diff = df.sub(diff_value, axis=0)
if drop:
diff = diff.drop(subtrahend, axis=1)
return diff
def constrain(data: pd.DataFrame, n: int) -> pd.DataFrame:
"""
Belirtilen sayıdan az veri içeren sütunları DataFrame'den kaldırır.
Args:
data: Kısıta göre yeniden düzenlenecek veri.
n: kısıt sayısı
Returns:
pd.DataFrame
"""
data = data[data.columns[data.count() >= n]]
return data
def get_d_values(df: pd.DataFrame):
"""
Run the R script and get the results.
R'ın LongMemoryTS paketini kullanarak d'leri hesaplar.
Rscript çalıştırır ve sonuçları döndürür.
Args:
df : Date x Country
Returns: 'elw_m', 'elw_n', 'elw2s_v0', 'elw2s_v1', 'elw2s_h0', 'elw2s_h1', 'gph',
'hou_perron', 'local_w' verileri içeren Dataframe
"""
file = 'data/app/lndiff.csv'
df.to_csv('data/app/lndiff.csv')
if os.name == 'posix':
command = 'Rscript dvals.R {}'.format(file)
os.system(command)
else:
command = 'C:/Program Files/R/R-4.0.3/bin/x64/Rscript dvals.R {}'.format(file)
subprocess.call(command)
try:
d = pd.read_csv('data/app/d_values.csv', index_col=0)
except FileNotFoundError:
raise Exception("Please update your R path.")
return d
def mean(data: Union[List[pd.DataFrame], pd.DataFrame]):
"""
Aritmetik ortalamayı hesaplar.
Returns: DataFrame or List of DataFrame
"""
if isinstance(data, list):
return list(map(lambda x: x.mean(), data))
return data.mean()
def intersection(x: list, y:pd.Series):
"""
Ülkelerin kesişimini alın.
Args:
x: (list of series) : Regresyonda kullanılacak x değerlerinin listesi.
y: pd.Series
Returns: new x and y
"""
x = pd.concat(x, axis=1).dropna()
countries = y.index.intersection(x.index)
x = x.loc[countries]
y = y[countries]
return x, y
def country_intersection(merged_X):
interlist = list(merged_X.groupby(level='date'))
x = interlist[0][1]
x = x.index.get_level_values(1)
for i in range(1, len(interlist)):
y = interlist[i][1]
y = y.index.get_level_values(1)
x = x.intersection(y)
return x
def initial_values(data):
x = data.unstack(0)
x.iloc[:, 0]
for col in x.columns:
x[col] = x.iloc[:, 0]
return x
def growth(data):
x = data.unstack(1)
return x.diff() / x
def test_data(x):
"""
Eğitim verilerinden kullanarak test verisi oluştur.
Args:
x: (pd.DataFrame) : Training data
Returns:
Test Data
"""
test = x.copy()
average = x.mean()[1:]
for i in average.index:
test[i] = average[i]
test = test.sort_values(0)
return test
class Model:
"""
En küçük kareler yöntemini kullanan Doğrusal Regresyon işlemlerini gerçekleştirin.
Args:
training_data: (Dataframe): Kullanılacak X'leri içermelidir.
target_values: (Series): Kullanılacak d_values.
test_values: test verileri.
"""
__model = LinearRegression()
def __init__(self, training_data, target_values, test_values):
self.training_data = training_data
self.target_values = target_values
self.test_values = test_values
self.__fit()
def __fit(self):
self.__model.fit(self.training_data, self.target_values)
def predict(self):
return self.__model.predict(self.test_values)
@property
def intercept(self):
"""
y ekseni kesim noktası
"""
return self.__model.intercept_
@property
def countries(self):
"""
Regresyonda kullanılan ülkeler
"""
return self.training_data.index.values
@property
def r_square(self):
# TODO: r2 hesaplanacak
pass
@property
def cofficients(self):
"""
tahmini katsayılar
"""
return self.__model.coef_
def plot(self) -> go.Figure:
"""
Regresyon grafiğini çizer ve data/app dizininde regression.html olarak kaydeder.
"""
fig = px.scatter(x=self.training_data[0], y=self.target_values, text=self.countries)
fig.add_traces(go.Scatter(x=self.test_values[0], y=self.predict(), name='Regression Fit'))
offline.plot(fig, filename='data/app/regression.html')
if __name__ == 'lmts':
# data/app klasörünü oluşturur.
create_appdata()