Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
robertopucp
GitHub Repository: robertopucp/1eco35_2022_2
Path: blob/main/Lab2/Lab2_spyder.py
2710 views
1
# -*- coding: utf-8 -*-
2
"""
3
Created on Wed Aug 24 22:17:21 2022
4
5
@author: Roberto
6
"""
7
8
#%% Intro
9
10
#### Itntro 2.0
11
12
#%% If statement
13
14
"""
15
If statement
16
17
"""
18
19
import random
20
import numpy as np
21
import math
22
23
y = np.random.randint(-10, 10, 10)
24
25
if np.mean(y) >0 :
26
27
dummy = 1 #tab arriba del botom mayuscula
28
29
else :
30
dummy = 0
31
32
print(dummy)
33
34
"""
35
Nested If statement
36
37
"""
38
39
v = 2 # Ctrl 1
40
41
# v = np.nan # missing
42
# v = "String"
43
# v = False
44
45
46
if isinstance( v, int ):
47
print(v, " es numero entero (no missing)")
48
elif math.isnan(v):
49
print(v, " es un missing")
50
elif isinstance( v, str ):
51
print(v, " es un string")
52
elif isinstance( v, bool ):
53
print(v, " es un logical")
54
else:
55
print("Sin resultado")
56
57
58
#%% While Loop
59
60
### If I have my savings today of S/.1,000.00. How much will my savings be worth
61
### in 10 years at an interest rate of 2.5%?
62
63
" S_{y+1} =S_{y}(1+i) "
64
65
# sasve
66
S = 1000
67
68
# Periods
69
n = 10
70
71
# interes rate
72
i = 0.025
73
74
75
year = 1
76
77
while year < n:
78
S = S * (1+i)
79
year += 1 # sumo un unidad
80
print( year, S)
81
82
83
84
85
86
#%% Class
87
88
#### While + If statement
89
90
w = 10
91
92
while (w > 7 & w <= 15) :
93
coin = round( np.random.uniform(0,1) ) # numero aleatorio entre 0 y 1
94
95
if coin == 1:
96
w = w + 2
97
else :
98
w = w - 10
99
100
print(w)
101
102
#### For Loop
103
104
ages = np.array([21, 23, 25, 24, 20])
105
106
for age in ages:
107
108
print(age+10 )
109
110
#### For and Next, break
111
112
# Example 1
113
for i in range(50):
114
if i in range(15,21) :
115
None
116
else :
117
print("Ejecutanto",i,"\n")
118
119
120
# Example 2
121
122
for j in range(101):
123
print(j)
124
125
if j > 20:
126
break
127
128
#### While + break
129
130
w = 10
131
132
while True :
133
coin = round( np.random.uniform(0,1) ) # redondear al entero más cercano
134
if coin == 1 :
135
break
136
else:
137
w = w + 10
138
print(w)
139
140
141
#%% Function
142
143
def calculator(x,y,z):
144
result = x*y*z
145
146
return result
147
148
print( calculator( 158, 38, 10 ) )
149
150
calculator( 158, 38,15)
151
152
153
## return multiple
154
155
def calculator_square( x, y ):
156
157
x2 = x * x
158
y2 = y * y
159
160
result = x2 * y2
161
162
return result, x2, f"La multiplicación del cuadrado es: {result}"
163
164
calculator_square(3, 4)
165
166
print( calculator_square(3, 4)[1] )
167
calculator_square(3, 4)[2]
168
169
170
#### IF statement and return
171
def calculator_square_2( x, y ):
172
173
x2 = x * x
174
y2 = y * y
175
176
result = x2 * y2
177
178
if result <= 200:
179
return f"Large number. Get only the result variable {result}"
180
else:
181
return print( "Too large number. Do not return variables!")
182
183
184
185
calculator_square_2(300, 4)
186
187
## Función y tipo de variables
188
def calculator_base_5( x , y = 5 ):
189
190
result = x * y
191
192
return result
193
194
195
calculator_base_5( 7 )
196
197
198
199
def calculator_base_5( x : int, y : float ) -> float:
200
201
if not isinstance( x , int ):
202
raise TypeError( "X variable is not int type.")
203
204
if not isinstance( y, float ):
205
raise TypeError( "Y variable is not float type.")
206
207
result = x * y
208
209
210
return result
211
212
calculator_base_5( 8.358, 3 )
213
214
calculator_base_5( np.nan, 3.0)
215
216
#### Function y valore predeterminados de parámetros
217
218
def transpose(M, est = True, z = None):
219
220
if not isinstance( M , np.ndarray ) :
221
raise TypeError( "x must be a n-array")
222
223
224
elif (est and (z is None) ) :
225
226
M = M.T
227
Z = np.zeros((M.shape[0], M.shape[1]))
228
for i in range(M.shape[1]):
229
230
a = np.mean(M[:,i])
231
b = np.std(M[:,i])
232
Z[:,i] = (M[:,i]-a)/b
233
234
return Z
235
236
elif not z is None:
237
238
M = M*z
239
return M
240
241
242
243
A = np.array([np.arange(0,10), np.arange(10,20), np.arange(30,40), np.arange(-20,-10), np.arange(2,21,2)])
244
245
print(transpose(A))
246
247
print(transpose(A, est = False, z = 2))
248
249
#### Try and Exception
250
251
a = "2"
252
253
try:
254
255
print(a/7) # No corre el código si detecta un error
256
257
except TypeError:
258
print("El argumento deberia ser un número")
259
260
# caso 2
261
262
try:
263
264
print(a/7)
265
266
except Exception:
267
a = np.nan
268
print(a)
269
270
# caso 3
271
try:
272
273
print(a/7)
274
275
except Exception:
276
a = np.nan
277
print(a)
278
279
finally:
280
281
print("Siempre se ejecuta")
282
283
#%% *args
284
285
"""
286
The special syntax *args in function definitions in python is used to pass a variable number
287
of arguments to a function. The object *args is a tuple that contains all the arguments.
288
When you build your code, you should consider *args as a tuple.
289
"""
290
291
def calculator( *args ):
292
293
print( f"args is a {type( args )}" )
294
# Get the first value
295
result = args[ 0 ]
296
297
# Keep the rest of values
298
args1 = args[ 1: ]
299
300
# multiply all elements
301
for element in args1:
302
result = result * element
303
304
return result
305
306
calculator( 8, 9, 50, 40, 10, 1)
307
308
def calculator( *list_vars ):
309
310
print( f"args is a { type( list_vars ) }" )
311
# Get the first value
312
result = list_vars[ 0 ]
313
314
# Keep the rest of values
315
list_vars1 = list_vars[ 1: ]
316
317
# multiply all elements
318
for element in list_vars1:
319
result = result * element
320
321
return result
322
323
324
#### *Kwargs
325
326
def calculator( *list_vars, **kwargs):
327
328
print( type( list_vars ) )
329
print( type( kwargs ) )
330
331
if ( kwargs[ 'function' ] == "media" ) :
332
333
# Get the first value
334
result = np.mean( list_vars )
335
336
elif ( kwargs[ 'function' ] == "adicion" ) :
337
338
result = sum(list_vars)
339
else:
340
raise ValueError( f"The function argument {kwargs[ 'function' ]} is not supported." )
341
342
return result
343
344
345
calculator( 4, 5, 6, 7, 8, function = "adicion" )
346
347
calculator( 4, 5, 6, 7, 8, function = "media" )
348
349
calculator( 4, 5, 6, 7, 8, function = "inversa" )
350
351
#### Class
352
353
class class_name:
354
355
def __init__(self, parameter1, parameter2):
356
None
357
358
## Atributos
359
360
import numpy as np
361
362
A = np.arange( 8, 25 )
363
364
print(A.size)
365
A.shape
366
A.mean()
367
368
dir(A) # list de atributos
369
370
"""
371
Method
372
A function which is defined inside a class body.
373
If called as an attribute of an instance of that class,
374
the method will get the instance object as its first argument (which is usually called self).
375
See function and nested scope.
376
"""
377
378
from sklearn import linear_model
379
print(dir(linear_model))
380
381
382
#### __init__
383
384
class MyFirstClass:
385
386
def __init__( self, name, age ):
387
self.name = name
388
self.age = age
389
390
# best way to define a method
391
def print_name_1( self ):
392
print( f'I am { self.name }.' )
393
394
# wrong way to define a method
395
def print_name_2():
396
print( f'This is my { name }.' )
397
398
399
# the worst way to call a parameter
400
# we need to define them as attributes
401
def print_name_3( self ):
402
print( f'This is my { name }.' )
403
404
405
class MyFirstClass:
406
407
def __init__( self, name, age, school ):
408
self.name = name
409
self.age = age
410
self.school = school
411
412
# how to define a method
413
def print_name_1( self ):
414
print( f'I am { self.name }.' )
415
416
# other method
417
def person_age( self ):
418
print( f' I am { self.name } , I am { self.age } old. ' )
419
420
# method
421
def person_school( self ):
422
print( f' I am {self.name} , I study at {self.school}. ' )
423
424
# wrong way to define a method
425
def print_name_2():
426
print( f'This is my { name }.' )
427
428
# the worst way to call a parameter
429
# we need to define them as attributes
430
def print_name_3( self ):
431
print( f'This is my { name }.' )
432
433
434
student = MyFirstClass( name = "Jose" , age = 22, school = "Saco Oliveros" )
435
436
print(student.age)
437
print(student.school)
438
student.age
439
student.person_age()
440
student.print_name_1()
441
442
#%% Loop Replacement using list
443
444
vector = list(np.arange(100))
445
446
vector = np.arange(100)
447
448
list( map( lambda x: x**2 , vector) )
449
450
# time
451
452
from tqdm import tqdm
453
454
for i in tqdm( range(100000) ):
455
print(i)
456
457
458
459
# apply
460
461
import pandas as pd
462
463
# list of name, degree, score
464
var1 = np.random.rand(50000)
465
var2 = np.arange(0,50000)
466
var3 = np.random.rand(50000)
467
468
# dictionary of lists
469
dict = {'v1': var1, 'v2': var2, 'v3': var3}
470
471
df = pd.DataFrame(dict)
472
473
df.apply(np.sum, axis = 0) # columna por columna
474
df.apply(np.sum, axis = 1) # fila por fila
475
476
df['nueva_var'] = df['v2'].apply(lambda x : x**99)
477
478
479
# !pip install swifter
480
481
import swifter
482
483
df['nueva_var'] = df['v2'].swifter.apply(lambda x : x**99) # parallel procesing
484
485
486
#%% OLS
487
488
from scipy.stats import t # t - student
489
import pandas as pd
490
491
np.random.seed(175)
492
493
x1 = np.random.rand(500) # uniform distribution [0,1]
494
x2 = np.random.rand(500) # uniform distribution [0,1]
495
x3 = np.random.rand(500) # uniform distribution [0,1]
496
x4 = np.random.rand(500) # uniform distribution [0,1]
497
e = np.random.normal(0,1,500) # normal distribution mean = 0 and sd = 1
498
z = np.random.rand(500)
499
# Poblacional regression (Data Generating Process GDP)
500
501
502
Y = 1 + 0.8*x1 + 1.2*x2 + 0.5*x3 + 1.5*x4 + e
503
504
X = np.column_stack((np.ones(500),x1,x2,x3,x4))
505
506
def ols(M,Y, standar = True, Pvalue = True , instrumento = None, index = None):
507
508
if standar and Pvalue and (instrumento is None) and (index is None) :
509
510
beta = np.linalg.inv(X.T @ X) @ ((X.T) @ Y )
511
512
y_est = X @ beta
513
n = X.shape[0]
514
k = X.shape[1] - 1
515
nk = n - k
516
sigma = sum(list( map( lambda x: x**2 , Y - y_est) )) / nk
517
Var = sigma*np.linalg.inv(X.T @ X)
518
sd = np.sqrt( np.diag(Var) )
519
t_est = np.absolute(beta/sd)
520
pvalue = (1 - t.cdf(t_est, df=nk) ) * 2
521
df = pd.DataFrame( {"OLS": beta , "sd" : sd, "Pvalue":pvalue})
522
523
524
elif (not instrumento is None) and (not index is None) :
525
526
beta = np.linalg.inv(X.T @ X) @ ((X.T) @ Y )
527
528
index = index - 1
529
Z = X
530
Z[:,index] = z
531
beta_x = np.linalg.inv(Z.T @ Z) @ ((Z.T) @ X[:,index] )
532
x_est = Z @ beta_x
533
X[:,index] = x_est
534
beta_iv = np.linalg.inv(X.T @ X) @ ((X.T) @ Y )
535
df = pd.DataFrame( {"OLS": beta , "OLS_IV" : beta_iv})
536
537
return df
538
539
540
541
ols(X,Y)
542
543
ols(X,Y,instrumento = z, index = 2)
544
545
546
547
548
549
550
551