markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
2. ¿Qué es la volatilidad implícita? **Volatilidad:** desviación estándar de los rendimientos.- ¿Cómo se calcula?- ¿Para qué calcular la volatilidad? - **Para valuar derivados**, por ejemplo **opciones**.- Método de valuación de riesgo neutral (se supone que el precio del activo $S_t$ no se ve afectado por el riesgo d...
# para los call de la fecha 1 ax = call06_f1.set_index('Strike').loc[:, 'IV'].plot(figsize=(8,6)) ax.axvline(call06_f1.Underlying_Price.iloc[0], color='g'); # para los call de la fecha 2 ax = call06_f2.set_index('Strike').loc[:, 'IV'].plot(figsize=(8,6)) ax.axvline(call06_f2.Underlying_Price.iloc[0], color='g');
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Analicemos ahora datos de los `put`
put06_f1 = aapl_opt.loc[(aapl_opt.Expiry==fecha1) & (aapl_opt.Type=='put')] put06_f1
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Para los `put` de la `fecha 1`
ax = put06_f1.set_index('Strike').loc[:, 'IV'].plot(figsize=(8,6)) ax.axvline(put06_f1.Underlying_Price.iloc[0], color='g')
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Con lo que hemos aprendido, deberíamos ser capaces de crear una función que nos devuelva un `DataFrame` de `pandas` con los precios de cierre ajustados de ciertas compañías en ciertas fechas:- Escribir la función a continuación
# Función para descargar precios de cierre ajustados: def get_adj_closes(tickers, start_date=None, end_date=None): # Fecha inicio por defecto (start_date='2010-01-01') y fecha fin por defecto (end_date=today) # Descargamos DataFrame con todos los datos closes = web.DataReader(name=tickers, data_source='yaho...
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
- Obtener como ejemplo los precios de cierre de Apple del año pasado hasta la fecha. Graficar...
ticker = ['AAPL'] start_date = '2017-01-01' closes_aapl = get_adj_closes(ticker, start_date) closes_aapl.plot(figsize=(8,5)); plt.legend(ticker);
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
- Escribir una función que pasándole el histórico de precios devuelva los rendimientos logarítmicos:
def calc_daily_ret(closes): return np.log(closes/closes.shift(1)).iloc[1:]
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
- Graficar...
ret_aapl = calc_daily_ret(closes_aapl) ret_aapl.plot(figsize=(8,6));
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
También, descargar datos de opciones de Apple:
aapl = web.YahooOptions('AAPL') aapl_opt = aapl.get_all_data().reset_index() aapl_opt.set_index('Expiry').sort_index() aapl_opt.Underlying_Price[0] K = 135 # strike price indice_opt = aapl_opt.loc[(aapl_opt.Type=='call') & (aapl_opt.Strike==K) & (aapl_opt.Expiry=='2023-06-16')] indice_opt i_opt= indice_opt.index opcion...
Precio del activo subyacente actual = 133.5
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Simulación de precios usando rendimiento simple y logarítmico * Comenzaremos por suponer que los rendimientos son un p.e. estacionario que distribuyen $\mathcal{N}(\mu,\sigma)$. Rendimiento Simple
# Obtenemos el rendimiento simple Ri = closes_aapl.pct_change(1).iloc[1:] # Obtenemos su media y desviación estándar de los rendimientos mu_R = Ri.mean()[0] sigma_R = Ri.std()[0] Ri today = pd.to_datetime(date.today()) # Obtener fecha de cierre de la opción a valuar expiry = opcion_valuar.Expiry len(pd.date_range(tod...
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Mostrar como simular precios usando los rendimientos 1. Usando rendimiento simple
# Simular los rendimientos # Rendimiento diario dt = 1 # Z ~ N(0,1) normal estándar (ndays, nscen) Z = np.random.randn(ndays, nscen) # Simulación normal de los rendimientos Ri_dt = pd.DataFrame(Z * sigma_R * np.sqrt(dt) + mu_R * dt, index=dates) Ri_dt
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
**Simulación de precios usando el rendimiento simple**: Como demostramos en clases pasadas la fórmula de simular precios usando el rendimiento simple es la siguiente:$$S_T = S_0 \prod_{i=0}^{T-1} (R_i + 1)$$
S0 = opcion_valuar.Underlying_Price S_T = S0*(Ri_dt + 1).cumprod() # Simulación del precio S_0 = opcion_valuar.Underlying_Price S_T = S_0*(1+Ri_dt).cumprod() S_T.iloc[0,:] = S_0 # Se muestran los precios simulados con los precios descargados pd.concat([closes_aapl, S_T.iloc[:, :10]]).plot(figsize=(8,6)); plt.title('Si...
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
2. Rendimiento Logarítmico **Simulación de precios usando el rendimiento logarítmico**: Como demostramos en clases pasadas la fórmula de simular precios usando el rendimiento simple es la siguiente:$$S_T = S_0 \cdot e^{\sum_{i=1}^{T} r_i }$$
Z.shape, len(dates) # Calcular rendimiento logarítmico ri = calc_daily_ret(closes_aapl) # Usando la media y desviación estándar de los rendimientos logarítmicos mu_r = ri.mean()[0] sigma_r = ri.std()[0] # Simulación del rendimiento dt = 1 Z = np.random.randn(ndays, nscen) sim_ret_ri = pd.DataFrame(mu_r * dt + Z * sig...
Las std usando rendimientos logarítmicos y simples son similares
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Con los precios simulados debemos de encontrar el valor de la opción según la función de pago correspondiente. Para este caso es:$$max(S_T - K,0)$$
opcion_valuar['JSON']
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Valuación usando el modelo de Black and ScholesLos supuestos que hicieron Black y Scholes cuando dedujeron su fórmula para la valoración de opciones fueron los siguientes:1. El comportamiento del precio de la acción corresponde al modelo logarítmico normal, con $\mu$ y $\sigma$constantes.2. No hay costos de transición...
mu = ret_aapl.mean()[0] sigma = ret_aapl.std()[0] mu, sigma
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
No se toma la media sino la tasa libre de riesgo> Referencia: https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yield
# Tasa de bonos de 1 yr de fecha 21/04/2021 -> 7% r = 0.007/360 # Tasa diaria
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
- Simularemos el tiempo de contrato desde `HOY` hasta la fecha de `Expiry`, 10 escenarios: - Generar fechas
from datetime import date today = pd.Timestamp(date.today()) expiry = opcion_valuar.Expiry dates = pd.date_range(start=today, end=expiry, freq='B') ndays = len(dates) nscen = 10 dates
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
- Generamos 10 escenarios de rendimientos simulados y guardamos en un dataframe
sim_ret = pd.DataFrame(sigma*np.random.randn(ndays,nscen)+r, index=dates) sim_ret.cumsum() # Las columnas son los escenarios y las filas son las días de contrato
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
- Con los rendimientos simulados, calcular los escenarios de precios respectivos:
S0 = closes_aapl.iloc[-1,0] # Condición inicial del precio a simular sim_closes = S0*np.exp(sim_ret.cumsum()) sim_closes.iloc[0, :] = S0 sim_closes
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
- Graficar:
sim_closes.plot(figsize=(8,6)); # Se muestran los precios simulados con los precios descargados pd.concat([closes_aapl,sim_closes]).plot(figsize=(8,6)); opcion_valuar['JSON'] opcion_valuar from datetime import date Hoy = date.today() # strike price de la opción K = opcion_valuar['JSON']['strike'] # Fechas a simular...
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
La valuación de la opción es:
call.iloc[-1]
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Intervalo de confianza del 99%
confianza = 0.99 sigma_est = sim_closes.iloc[-1].sem() mean_est = call.iloc[-1].Prima i2 = st.norm.interval(confianza, loc=mean_est, scale=sigma_est) print(i2) opcion_valuar['JSON']
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Precios simulados usando técnicas de reducción de varianza
# Usando muestreo estratificado----> #estratros = nscen U = (np.arange(0,nscen)+np.random.rand(ndays,nscen))/nscen Z = st.norm.ppf(U) sim_ret2 = pd.DataFrame(sigma*Z+r,index=dates) sim_closes2 = S0*np.exp(sim_ret.cumsum()) # Función de pago strike = pd.DataFrame(K*np.ones([ndays,nscen]), index=dates) call = pd.DataFr...
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
La valuación de la opción es:
call.iloc[-1]
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Intervalo de confianza del 99%
confianza = 0.99 sigma_est = sim_closes2.iloc[-1].sem() mean_est = call.iloc[-1].Prima i2 = st.norm.interval(confianza, loc=mean_est, scale=sigma_est) print(i2)
(34.383953470513504, 35.621289698015715)
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Análisis de la distribución de los rendimientos Ajustando norm
ren = calc_daily_ret(closes_aapl) # rendimientos y,x,_ = plt.hist(ren['AAPL'],bins=50,density=True,label='Histograma rendimientos') mu_fit,sd_fit = st.norm.fit(ren) # Se ajustan los parámetros de una normal # Valores máximo y mínimo de los rendiemientos a generar ren_max = max(x);ren_min = min(x) # Vector de rendimie...
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Ajustando t
# rendimientos ren = calc_daily_ret(closes_aapl) # Histograma de los rendimientos y, x, _ = plt.hist(ren['AAPL'], bins=50, density=True, label='Histograma rendimientos') # Se ajustan los parámetros de una distribución dist = 't' params = getattr(st, dist).fit(ren.values) # Generación de la pdf de la distribución ...
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
3. Valuación usando simulación: uso del histograma de rendimientosTodo el análisis anterior se mantiene. Solo cambia la forma de generar los números aleatorios para la simulación montecarlo.Ahora, generemos un histograma de los rendimientos diarios para generar valores aleatorios de los rendimientos simulados. - Prime...
ndays = len(dates) nscen = 10
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
- Del histograma anterior, ya conocemos las probabilidades de ocurrencia, lo que se llamó como variable `y`
prob prob = y/np.sum(y) values = x[1:] prob.sum()
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
- Con esto, generamos los números aleatorios correspondientes a los rendimientos (tantos como días por número de escenarios).
# Rendimientos simulados ret = np.random.choice(values, ndays*nscen, p=prob) # Fechas dates = pd.date_range(start=Hoy,periods=ndays) # Rendimien en Data Frame sim_ret_hist = pd.DataFrame(ret.reshape((ndays,nscen)),index=dates) sim_ret_hist sim_closes_hist = (closes_aapl.iloc[-1,0])*np.exp(sim_ret_hist.cumsum()) sim_clo...
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Intervalo de confianza del 95%
confianza = 0.95 sigma_est = sim_closes_hist.iloc[-1].sem() mean_est = call_hist.iloc[-1].Prima i1 = st.t.interval(confianza,nscen-1, loc=mean_est, scale=sigma_est) i2 = st.norm.interval(confianza, loc=mean_est, scale=sigma_est) print(i1) print(i1)
(38.04373480098675, 39.00930377235172) (38.04373480098675, 39.00930377235172)
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
List and Dictionary ComprehensionsComprehension is a different way to construct lists and dictionaries. Up to now, every time that we have built up a list or dictionary, we began by initializing it. We then took advantage of their mutability inherent to build them up one element or key-value pair at a time. However, t...
my_list = [1, 5, 9, 33] my_squares = [] for num in my_list: my_squares.append(num ** 2) print(my_squares)
[1, 25, 81, 1089]
MIT
uebung_python1/5_Comprehension.ipynb
AlexaZiRo/share
Now, `my_squares` will hold the list `[1, 25, 81, 1089]`. To get this, we were simply specifying a bunch of stuff that we wanted to add on to the end of the `my_squares` list, with a starting point at `my_list`. So, from a high level, we can write the framework of creating a list in code as:```pythonlist_were_building ...
my_squares2 = [num ** 2 for num in my_list] print(my_squares2)
[1, 25, 81, 1089]
MIT
uebung_python1/5_Comprehension.ipynb
AlexaZiRo/share
But wait! There's more! Remember in all the examples where we were getting evens, we had a condition to decide when to append a value to a list? We can also use conditions to determine what "transformed things" get added in a list comprehension! Let's look at the evens list builder to hammer this home.```python Old way...
# Standard way. squares_dict = {} for num in range(1, 6): squares_dict[num] = num ** 2 print(squares_dict) # Dictionary Comprehension way. squares_dict2 = {num: num ** 2 for num in range(1, 6)} print(squares_dict2)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
MIT
uebung_python1/5_Comprehension.ipynb
AlexaZiRo/share
We can see that in both cases, we're going through the numbers 1 - 5 with `range(1, 6)` and those `num`s are being assigned as keys. The values assigned to those keys are the squares of the keys, assigned with `squares_dict[num] = num ** 2` and `num: num ** 2`, respectively. Just as with list comprehensions, dictionary...
from random import randint animals_list = ['cow', 'chicken', 'horse', 'moose'] animals_dict = {animal: randint(1, 10) for animal in animals_list} print(animals_dict)
{'cow': 5, 'chicken': 8, 'horse': 5, 'moose': 8}
MIT
uebung_python1/5_Comprehension.ipynb
AlexaZiRo/share
Other ComprehensionsYou can actually use the syntax from the list comprehensions to construct a tuple in what seems like a dynamic way. Take the example.
my_tuple = tuple(num for num in range(10) if num % 2 == 0) print(my_tuple)
(0, 2, 4, 6, 8)
MIT
uebung_python1/5_Comprehension.ipynb
AlexaZiRo/share
All we are doing here is passing `num for num in range(10) if num % 2 == 0` to the tuple constructor, `()`. Since the tuple constructor takes any iterable, which that statement produces, it makes a tuple out of the contents. Note that it would be impossible to make a tuple with statements like this the "old way", since...
odds = [num for num in range(10) if num % 2 != 0] odds cubes = {num: num **3 for num in range(1,6)} cubes
_____no_output_____
MIT
uebung_python1/5_Comprehension.ipynb
AlexaZiRo/share
LOGISTIC REGRESSION MODEL
#import dependencies import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression # Train the Logistic Regression model on the unscaled data and print the model score classifier = LogisticRegression() # Fit our model using the training data classifier.fit(x_train, y_train) print(f"Training Data ...
Training Data Score: 0.6564860426929392 Testing Data Score: 0.5199914929817099
ADSL
Credit Risk Evaluator.ipynb
memeguerrini/supervised-learning-challenge
RandomForest Classifier Model
#import dependencies from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report, roc_curve # Train a Random Forest Classifier model and print the model score rf_clf = RandomForestClassifier(random_state=1) rf_clf.fit(x_train, y_train) #classification reports y_pred = rf_clf.pr...
Training Data Score: 1.0 Testing Data Score: 0.6671629094002552
ADSL
Credit Risk Evaluator.ipynb
memeguerrini/supervised-learning-challenge
Scaling the Data
#import dependencies from sklearn.preprocessing import StandardScaler # Scale the data and all features scaler = StandardScaler().fit(x_train) x_train_scaled = scaler.transform(x_train) x_test_scaled = scaler.transform(x_test) # Train the Logistic Regression model on the scaled data and print the model score # Create...
Training Data Score: 1.0 Testing Data Score: 0.6546150574223735
ADSL
Credit Risk Evaluator.ipynb
memeguerrini/supervised-learning-challenge
Denoising Autoencoder on MNIST dataset* This notebook will give you a very good understanding abou denoising autoencoders* For more information: visit [here](https://lilianweng.github.io/lil-log/2018/08/12/from-autoencoder-to-beta-vae.html)* The entire notebook is in PyTorch
# Importing packages that will be necessary for the project import numpy as np from keras.datasets import mnist import matplotlib.pyplot as plt from tqdm import tqdm from torchvision import transforms import torch.nn as nn from torch.utils.data import DataLoader,Dataset import torch import torch.optim as optim from tor...
_____no_output_____
Apache-2.0
ML_AI/PyTorch/Denoising_Autoencoder_MNIST.ipynb
PranavHegde99/OpenOctober
Cleaning the data to build the prototype for crwa This data cleans the original sql output and performs cleaning tasks. Also checking validity of the results against original report found at https://www.crwa.org/uploads/1/2/6/7/126781580/crwa_ecoli_web_2017_updated.xlsx
import pandas as pd pd.options.display.max_rows = 999 import numpy as np import matplotlib.pyplot as plt df = pd.read_csv("data_for_prototype.csv") # There are 2 rows with Date = Null so droping those rows df = df.dropna(subset=['Date_Collected']) df.isna().sum() # There are following types of invalids in Site_ID inv...
_____no_output_____
MIT
projects/crwa/data/sampling_datasets/bhushan-prototype.ipynb
TylerTsang/safe-water
Linear Regression
model1 = sm.ols('y~age',data=diab) fit1_lm = model1.fit() pred1 = fit1_lm.predict(xpred) prediction_output = fit1_lm.get_prediction(xpred).summary_frame() ax1 = diab.plot.scatter(x='age',y='y',c='Red',title="Diabetes data with least-squares linear fit") ax1.set_xlabel("Age at Diagnosis") ax1.set_ylabel("Log C-Peptide C...
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
`vander` is for Vandermonde. It's a matrix where the first column is $x^0$, the second is $x^1$, the third is $x^2$ and so on.` np.vander([6,3,5], 4, increasing=True) = array([[ 1, 6, 36, 216], ...
fit2_lm = sm.ols(formula="y ~ np.vander(age, 4, increasing=True) -1",data=diab).fit() fit2_lm = sm.ols(formula="y ~ age + np.power(age, 2) + np.power(age, 3)",data=diab).fit() poly_predictions = fit2_lm.get_prediction(xpred).summary_frame() poly_predictions.head() ax2 = diab.plot.scatter(x='age',y='y',c='Red',title="D...
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
Logistic Regression
diab['y_bin'] = 1*(diab['y'] > 4) # multiply by 1 because statsmodels wants 1s and 0s instead of true and false logit_model = sm.logit("y_bin ~ age ", data = diab).fit() logit_prediction = logit_model.predict(xpred) from scipy.special import expit import re def get_logit_prediction_intervals(model, new_data_df): if...
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
Lo(w)ess
from statsmodels.nonparametric.smoothers_lowess import lowess as lowess lowess_models = {} for cur_frac in [.15,.25,.7, 1]: lowess_models[cur_frac] = lowess(diab['y'],diab['age'],frac=cur_frac)
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
**Note** Python's lowess implementation does not have any tool to predict on new data; it only returns the fitted function's value at the training points. We're making up for that by drawing a straight line between consecutive fitted values. (There are other more sophisticated interpolation techniques, but the ideal ap...
from scipy.interpolate import interp1d for cur_frac, cur_model in lowess_models.items(): ax = diab.plot.scatter(x='age',y='y',c='Red',title="Lowess Fit, Fraction = {}".format(cur_frac)) ax.set_xlabel("Age at Diagnosis") ax.set_ylabel("Log C-Peptide Concentration") lowess_interpolation = interp1d(cur_mod...
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
Splines (via knots) Define a Relu/Truncated cubic function
def h(x, knot, exponent): output = np.power(x-knot, exponent) output[x<=knot] = 0 return output
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
Transforming the x values [0,10] with a knot at 4, power 1
xvals = np.arange(0,10.1,0.1) plt.plot(xvals, h(xvals,4,1), color="red") plt.title("Truncated linear basis function with knot at x=4") plt.xlabel("$x$") plt.ylabel("$(x-4)_+$") #note the use of TeX in the label plt.show()
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
Transforming the x values [0,10] with a knot at 4, power 3
plt.plot(xvals,h(xvals,4,3),color="red") plt.title("Truncated cubic basis function with knot at x=4") plt.xlabel("$x$") plt.ylabel("$(x-4)_+^3$") plt.show()
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
The sum of three RELUs with different knots and different coeffecients
plt.plot(xvals, 3*h(xvals,2,1) - 4*h(xvals,5,1) + 0.5*h(xvals,8,1), color="red") plt.title("Piecewise linear spline with knots at x=2, 5, and 8") plt.xlabel("$x$") plt.ylabel("$y$") plt.show()
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
Above, but with a starting slope and intercept
plt.plot(xvals, 2 + xvals + 3*h(xvals,2,1) - 4*h(xvals,5,1) + 0.5*h(xvals,8,1), color="red") plt.title("Piecewise linear spline with knots at x=2, 5, and 8\n plus a starting slope and intercept") plt.xlabel("$x$") plt.ylabel("$y$") plt.show()
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
Using OLS, we can find optimal coeffecients for RELUs with pre-specified knots, just like we can find optimal coeffecients for $x^2$ and $x^3$
# generate some fake data to fit x = np.arange(0.1,10,9.9/100) from scipy.stats import norm y = norm.ppf(x/10) + np.random.normal(0,0.4,100) fitted_spline_model = sm.ols('y~x+h(x,2,1)+h(x,5,1)+h(x,8,1)',data={'x':x,'y':y}).fit() plt.scatter(x,y,facecolors='none', edgecolors='black') plt.title("3 knots") plt.xlabel("...
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
More knots
fitted_spline_model = sm.ols('y~x+h(x,1,1)+h(x,2,1)+h(x,3.5,1)+h(x,5,1)+h(x,6.5,1)+h(x,8,1)',data={'x':x,'y':y}).fit() plt.scatter(x,y,facecolors='none', edgecolors='black') plt.title("6 knots") plt.xlabel("$x$") plt.ylabel("$y$") plt.plot(x, fitted_spline_model.predict(),color="darkblue", label="Linear Spline with kn...
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
More knots
fitted_spline_model = sm.ols('y~x+h(x,1,1)+h(x,2,1)+h(x,3,1)+h(x,4,1)+h(x,5,1)+h(x,6,1)+h(x,7,1)+h(x,8,1)+h(x,9,1)', data={'x':x,'y':y}).fit() plt.scatter(x,y,facecolors='none', edgecolors='black') plt.title("9 knots") plt.xlabel("$x$") plt.ylabel("$y$") plt.plot(x, fitted_spline_model.pre...
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
Using code to write out the formula this time
n_knots = 25 components = ['h(x,{},1)'.format(x) for x in np.linspace(0,10,n_knots)] formula = ' + '.join(components) final_formula = 'y ~ x + ' + formula final_formula fitted_spline_model = sm.ols(final_formula,data={'x':x,'y':y}).fit() plt.scatter(x,y,facecolors='none', edgecolors='black') plt.title("25 knots") plt...
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
Cubic splines, instead of linear. Still using code to write the formula
components = ['h(x,{},3)'.format(x) for x in [2,5,8]] formula = ' + '.join(components) final_formula = 'y~x + np.power(x,2) + np.power(x,3) + ' + formula fitted_spline_model = sm.ols(final_formula,data={'x':x,'y':y}).fit() plt.scatter(x,y,facecolors='none', edgecolors='black') plt.title("3 knots") plt.xlabel("$x$") p...
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
Smoothing splines
from scipy.interpolate import UnivariateSpline
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
This method won't allow tied values, and wants its values in sorted order. Add a tiny bit of noise to the x values and sort them.
diab['noisy_age'] = diab['age'] + np.random.normal(0,.001, len(diab)) sorted_noisy_diab = diab.sort_values(["noisy_age"]) smoothing_spline_dict = {} for cur_smoothing in [0, 5, 10, 20, np.inf]: cur_spline = UnivariateSpline(sorted_noisy_diab['noisy_age'],sorted_noisy_diab['y'], s=cur_smoothing) ax = diab.p...
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
Even when we request infinite smoothness, we don't end up with a horizontal line (no derivatives at all)- we end up with a single cubic curve. That's because we chose a cubic spline.In general, this implementation's smoothness regularization penalizes any derivatives _beyond_ what our basic spline needs. So with k=3, a...
from sklearn.model_selection import KFold from sklearn.metrics import r2_score candidate_smoothings = [0, 5, 10, 20, 200] kf = KFold(n_splits=5, random_state=47, shuffle=True) scores = np.zeros((5,len(candidate_smoothings))) for i, (train_index, test_index) in enumerate(kf.split(sorted_noisy_diab)): train_df = s...
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
Get quartiles
quarts = GAGurine['Age'].quantile([0.25, 0.5, 0.75]).values.reshape(-1)
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
Build a Bspline model. Call `splrep` (spline representation) to find the knots and coeffecients that smooth the given data, then call BSpline to build something that can predict on given values.
from scipy.interpolate import splrep from scipy.interpolate import BSpline t,c,k = splrep(GAGurine['Age'].values, GAGurine['GAG'].values, t=quarts) b_spline_model = BSpline(t,c,k) b_spline_model(7)
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
`LSQUnivariateSpline` fits splines to data, using user-specified knots
from scipy.interpolate import LSQUnivariateSpline natural_spline_model = LSQUnivariateSpline(GAGurine['Age'].values, GAGurine['GAG'].values, quarts) ax = GAGurine.plot.scatter(x='Age',y='GAG',c='grey',title="GAG in urine of children") ax.plot(GAGurine['Age'], b_spline_model(GAGurine['Age']), label="B-spline, knots at ...
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
GAMs
kyphosis = pd.read_csv("../data/kyphosis.csv") kyphosis["outcome"] = 1*(kyphosis["Kyphosis"] == "present") kyphosis.describe() from pygam import LogisticGAM, s X = kyphosis[["Age","Number","Start"]] y = kyphosis["outcome"] kyph_gam = LogisticGAM(s(0)+s(1)+s(2)).fit(X,y)
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
GAMs provide plots of the effect of increasing each variable (conditional on / adjusted for the other variables)
res = kyph_gam.deviance_residuals(X,y) for i, term in enumerate(kyph_gam.terms): if term.isintercept: continue XX = kyph_gam.generate_X_grid(term=i) pdep, confi = kyph_gam.partial_dependence(term=i, X=XX, width=0.95) pdep2, _ = kyph_gam.partial_dependence(term=i, X=X, width=0.95) plt.figure...
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
AIC is a measure of model quality, estimating performance on a test set (without actually needing a test set). It can be used to compare and select two models.
kyph_gam.summary() X = kyphosis[["Age","Number","Start"]] y = kyphosis["outcome"] small_kyph_gam = LogisticGAM(s(0)+s(2)).fit(X,y) res = small_kyph_gam.deviance_residuals(X,y) for i, term in enumerate(small_kyph_gam.terms): if term.isintercept: continue XX = small_kyph_gam.generate_X_grid(term=i) ...
_____no_output_____
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
The original model's AIC was lower, so we prefer that model- it is expected to do better on out-of-sample data.
small_kyph_gam.summary()
LogisticGAM =============================================== ========================================================== Distribution: BinomialDist Effective DoF: 10.478...
MIT
content/lectures/lecture01/notebook/cs109b_smoothing.ipynb
wfseaton/2020-CS109B
MATH 4100: Temporal data analysis and applications to stock analysis*Curtis Miller* IntroductionThis is a lecture for [MATH 4100/CS 5160: Introduction to Data Science](http://datasciencecourse.net/), offered at the University of Utah, introducing time series data analysis applied to finance.Advanced mathematics and st...
import pandas as pd import quandl import datetime # We will look at stock prices over the past year, starting at January 1, 2016 start = datetime.datetime(2016,1,1) end = datetime.date.today() # Let's get Apple stock data; Apple's ticker symbol is AAPL # First argument is the series we want, second is the source ("ya...
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
Let's briefly discuss this. **Open** is the price of the stock at the beginning of the trading day (it need not be the closing price of the previous trading day), **high** is the highest price of the stock on that trading day, **low** the lowest price of the stock on that trading day, and **close** the price of the sto...
import matplotlib.pyplot as plt # Import matplotlib # This line is necessary for the plot to appear in a Jupyter notebook %matplotlib inline # Control the default size of figures in this Jupyter notebook %pylab inline pylab.rcParams['figure.figsize'] = (15, 9) # Change the size of plots apple["Adj. Close"].plot(gr...
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
A linechart is fine, but there are at least four variables involved for each date (open, high, low, and close), and we would like to have some visual way to see all four variables that does not require plotting four separate lines. Financial data is often plotted with a **Japanese candlestick plot**, so named because i...
from matplotlib.dates import DateFormatter, WeekdayLocator,\ DayLocator, MONDAY from matplotlib.finance import candlestick_ohlc def pandas_candlestick_ohlc(dat, stick = "day", adj = False, otherseries = None): """ :param dat: pandas DataFrame object with datetime64 index, and float columns "Open", "High", ...
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
With a candlestick chart, a black candlestick indicates a day where the closing price was higher than the open (a gain), while a red candlestick indicates a day where the open was higher than the close (a loss). The wicks indicate the high and the low, and the body the open and close (hue is used to determine which end...
microsoft, google = (quandl.get("WIKI/" + s, start_date=start, end_date=end) for s in ["MSFT", "GOOG"]) # Below I create a DataFrame consisting of the adjusted closing price of these stocks, first by making a list of these objects and using the join method stocks = pd.DataFrame({"AAPL": apple["Adj. Close"], ...
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
What's wrong with this chart? While absolute price is important (pricy stocks are difficult to purchase, which affects not only their volatility but *your* ability to trade that stock), when trading, we are more concerned about the relative change of an asset rather than its absolute price. Google's stocks are much mor...
stocks.plot(secondary_y = ["AAPL", "MSFT"], grid = True)
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
A "better" solution, though, would be to plot the information we actually want: the stock's returns. This involves transforming the data into something more useful for our purposes. There are multiple transformations we could apply.One transformation would be to consider the stock's return since the beginning of the pe...
# df.apply(arg) will apply the function arg to each column in df, and return a DataFrame with the result # Recall that lambda x is an anonymous function accepting parameter x; in this case, x will be a pandas Series object stock_return = stocks.apply(lambda x: x / x[0]) stock_return.head() stock_return.plot(grid = True...
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
This is a much more useful plot. We can now see how profitable each stock was since the beginning of the period. Furthermore, we see that these stocks are highly correlated; they generally move in the same direction, a fact that was difficult to see in the other charts.Alternatively, we could plot the change of each st...
# Let's use NumPy's log function, though math's log function would work just as well import numpy as np stock_change = stocks.apply(lambda x: np.log(x) - np.log(x.shift(1))) # shift moves dates back by 1. stock_change.head() stock_change.plot(grid = True).axhline(y = 0, color = "black", lw = 2)
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
Which transformation do you prefer? Looking at returns since the beginning of the period make the overall trend of the securities in question much more apparent. Changes between days, though, are what more advanced methods actually consider when modelling the behavior of a stock. so they should not be ignored.We often ...
#import pandas_datareader.data as web # Going to get SPY from Yahoo! (I know I said you shouldn't but I didn't have a choice) #spyder = web.DataReader("SPY", "yahoo", start, end) # Didn't work #spyder = web.DataReader("SPY", "google", start, end) # Didn't work either # If all else fails, read from a file, obta...
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
Classical Risk MetricsFrom what we have so far we can already compute informative metrics for our stocks, which can be considered some measure of risk.First, we will want to **annualize** our returns, thus computing the **annual percentage rate (APR)**. This helps us keep returns on a common time scale.
stock_change_apr = stock_change * 252 * 100 # There are 252 trading days in a year; the 100 converts to percentages stock_change_apr.tail()
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
Some of these numbers look initially like nonsense, but that's okay for now.The metrics I want are:* The average return* Volatility (the standard deviation of returns)* $\alpha$ and $\beta$* The Sharpe ratioThe first two metrics are largely self-explanatory, but the latter two need explaining.First, the **risk-free rat...
tbill = quandl.get("FRED/TB3MS", start_date=start, end_date=end) tbill.tail() tbill.plot() rrf = tbill.iloc[-1, 0] # Get the most recent Treasury Bill rate rrf
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
Now, a **linear regression model** is a model of the following form:$$y_i = \alpha + \beta x_i + \epsilon_i$$$\epsilon_i$ is an error process. Another way to think of this process model is:$$\hat{y}_i = \alpha + \beta x_i$$$\hat{y}_i$ is the **predicted value** of $y_i$ given $x_i$. In other words, a linear regression ...
smcorr = stock_change_apr.drop("SPY", 1).corrwith(stock_change_apr.SPY) # Since RRF is constant it doesn't change the # correlation so we can ignore it in our # calcul...
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
Then I compute $\alpha$ and $\beta$.
sy = stock_change_apr.drop("SPY", 1).std() sx = stock_change_apr.SPY.std() sy sx ybar = stock_change_apr.drop("SPY", 1).mean() - rrf xbar = stock_change_apr.SPY.mean() - rrf ybar xbar beta = smcorr * sy / sx alpha = ybar - beta * xbar beta alpha
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
The **Sharpe ratio** is another popular risk metric, defined below:$$\text{Sharpe ratio} = \frac{\bar{R_t} - r_{RF}}{s}$$Here $s$ is the volatility of the stock. We want the sharpe ratio to be large. A large Sharpe ratio indicates that the stock's excess returns are large relative to the stock's volatilitly. Additional...
# Your code here
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
Moving AveragesCharts are very useful. In fact, some traders base their strategies almost entirely off charts (these are the "technicians", since trading strategies based off finding patterns in charts is a part of the trading doctrine known as **technical analysis**). Let's now consider how we can find trends in stoc...
apple["20d"] = np.round(apple["Adj. Close"].rolling(window = 20, center = False).mean(), 2) pandas_candlestick_ohlc(apple.loc['2016-01-04':'2016-12-31',:], otherseries = "20d", adj=True)
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
Notice how late the rolling average begins. It cannot be computed until 20 days have passed. This limitation becomes more severe for longer moving averages. Because I would like to be able to compute 200-day moving averages, I'm going to extend out how much AAPL data we have. That said, we will still largely focus on 2...
start = datetime.datetime(2010,1,1) apple = quandl.get("WIKI/AAPL", start_date=start, end_date=end) apple["20d"] = np.round(apple["Adj. Close"].rolling(window = 20, center = False).mean(), 2) pandas_candlestick_ohlc(apple.loc['2016-01-04':'2016-12-31',:], otherseries = "20d", adj=True)
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
You will notice that a moving average is much smoother than the actua stock data. Additionally, it's a stubborn indicator; a stock needs to be above or below the moving average line in order for the line to change direction. Thus, crossing a moving average signals a possible change in trend, and should draw attention.T...
apple["50d"] = np.round(apple["Adj. Close"].rolling(window = 50, center = False).mean(), 2) apple["200d"] = np.round(apple["Adj. Close"].rolling(window = 200, center = False).mean(), 2) pandas_candlestick_ohlc(apple.loc['2016-01-04':'2016-12-31',:], otherseries = ["20d", "50d", "200d"], adj=True)
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
The 20-day moving average is the most sensitive to local changes, and the 200-day moving average the least. Here, the 200-day moving average indicates an overall **bearish** trend: the stock is trending downward over time. The 20-day moving average is at times bearish and at other times **bullish**, where a positive sw...
apple['20d-50d'] = apple['20d'] - apple['50d'] apple.tail()
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
We will refer to the sign of this difference as the **regime**; that is, if the fast moving average is above the slow moving average, this is a bullish regime (the bulls rule), and a bearish regime (the bears rule) holds when the fast moving average is below the slow moving average. I identify regimes with the followin...
# np.where() is a vectorized if-else function, where a condition is checked for each component of a vector, and the first argument passed is used when the condition holds, and the other passed if it does not apple["Regime"] = np.where(apple['20d-50d'] > 0, 1, 0) # We have 1's for bullish regimes and 0's for everything ...
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
The last line above indicates that for 1005 days the market was bearish on Apple, while for 600 days the market was bullish, and it was neutral for 54 days.Trading signals appear at regime changes. When a bullish regime begins, a buy signal is triggered, and when it ends, a sell signal is triggered. Likewise, when a be...
# To ensure that all trades close out, I temporarily change the regime of the last row to 0 regime_orig = apple.loc[:, "Regime"].iloc[-1] apple.loc[:, "Regime"].iloc[-1] = 0 apple["Signal"] = np.sign(apple["Regime"] - apple["Regime"].shift(1)) # Restore original regime data apple.loc[:, "Regime"].iloc[-1] = regime_orig...
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
We would buy Apple stock 23 times and sell Apple stock 23 times. If we only go long on Apple stock, only 23 trades will be engaged in over the 6-year period, while if we pivot from a long to a short position every time a long position is terminated, we would engage in 23 trades total. (Bear in mind that trading more fr...
apple.loc[apple["Signal"] == 1, "Close"] apple.loc[apple["Signal"] == -1, "Close"] # Create a DataFrame with trades, including the price at the trade and the regime under which the trade is made. apple_signals = pd.concat([ pd.DataFrame({"Price": apple.loc[apple["Signal"] == 1, "Adj. Close"], ...
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
Let's now create a simulated portfolio of $1,000,000, and see how it would behave, according to the rules we have established. This includes:* Investing only 10% of the portfolio in any trade* Exiting the position if losses exceed 20% of the value of the trade.When simulating, bear in mind that:* Trades are done in bat...
# We need to get the low of the price during each trade. tradeperiods = pd.DataFrame({"Start": apple_long_profits.index, "End": apple_long_profits["End Date"]}) apple_long_profits["Low"] = tradeperiods.apply(lambda x: min(apple.loc[x["Start"]:x["End"], "Adj. Low"]), axis = 1) apple_long_prof...
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
Our portfolio's value grew by 13% in about six years. Considering that only 10% of the portfolio was ever involved in any single trade, this is not bad performance.Notice that this strategy never lead to our rule of never allowing losses to exceed 20% of the trade's value being invoked. For the sake of simplicity, we w...
def ma_crossover_orders(stocks, fast, slow): """ :param stocks: A list of tuples, the first argument in each tuple being a string containing the ticker symbol of each stock (or however you want the stock represented, so long as it's unique), and the second being a pandas DataFrame containing the stocks, with a ...
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
A more realistic portfolio that can invest in any in a list of twelve (tech) stocks has a final growth of about 100%. How good is this? While on the surface not bad, we will see we could have done better. BenchmarkingBacktesting is only part of evaluating the efficacy of a trading strategy. We would like to **benchmark...
#spyder = web.DataReader("SPY", "yahoo", start, end) spyder = spyderdat.loc[start:end] spyder.iloc[[0,-1],:] batches = 1000000 // np.ceil(100 * spyder.loc[:,"Adj Close"].iloc[0]) # Maximum number of batches of stocks invested in trade_val = batches * batch * spyder.loc[:,"Adj Close"].iloc[0] # How much money is used to...
_____no_output_____
MIT
07-time-series/07-time-series.ipynb
uwsd/2018-datascience-lectures
Вебинар 6. Консультация по курсовому проекту. Задание для курсового проектаМетрика:R2 - коэффициент детерминации (sklearn.metrics.r2_score)Сдача проекта:1. Прислать в раздел Задания Урока 10 ("Вебинар. Консультация по итоговому проекту")ссылку на программу в github (программа должна содержаться в файле Jupyter Noteboo...
import numpy as np import pandas as pd import random from sklearn.model_selection import train_test_split, cross_val_score from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import r2_score as r2 from sklearn.model_selection import KFo...
_____no_output_____
MIT
Web06.ipynb
gera09/Numpy_Matplotlib_Scikit-learn
**Пути к директориям и файлам**
TRAIN_DATASET_PATH = 'datasets/project_task/train.csv' TEST_DATASET_PATH = 'datasets/project_task/test.csv'
_____no_output_____
MIT
Web06.ipynb
gera09/Numpy_Matplotlib_Scikit-learn
Загрузка данных **Описание датасета*** **Id** - идентификационный номер квартиры* **DistrictId** - идентификационный номер района* **Rooms** - количество комнат* **Square** - площадь* **LifeSquare** - жилая площадь* **KitchenSquare** - площадь кухни* **Floor** - этаж* **HouseFloor** - количество этажей в доме* **House...
train_df = pd.read_csv('train.csv') display(train_df.tail()) print(train_df.shape) # train_df = train_df.set_index('Id') # train_df.head() test_df = pd.read_csv('test.csv') display(test_df.tail()) print(test_df.shape) # test_df = test_df.set_index('Id') train_df.shape[1]-1 == test_df.shape[1]
_____no_output_____
MIT
Web06.ipynb
gera09/Numpy_Matplotlib_Scikit-learn
Приведение типов
train_df.dtypes train_df['Id'] = train_df['Id'].astype(str) train_df['DistrictId'] = train_df['DistrictId'].astype(str)
_____no_output_____
MIT
Web06.ipynb
gera09/Numpy_Matplotlib_Scikit-learn
Обзор данных **Целевая переменная**
plt.figure(figsize = (16, 8)) train_df['Price'].hist(bins=30) plt.ylabel('Count') plt.xlabel('Price') plt.title('Target distribution') plt.show()
_____no_output_____
MIT
Web06.ipynb
gera09/Numpy_Matplotlib_Scikit-learn
**Количественные переменные**
train_df.describe().T
_____no_output_____
MIT
Web06.ipynb
gera09/Numpy_Matplotlib_Scikit-learn
**Категориальные переменные**
cat_colnames = train_df.select_dtypes(include='object').columns.tolist() cat_colnames for cat_colname in cat_colnames[2:]: print(str(cat_colname) + '\n\n' + str(train_df[cat_colname].value_counts()) + '\n' + '*' * 100 + '\n')
Ecology_2 B 9903 A 97 Name: Ecology_2, dtype: int64 **************************************************************************************************** Ecology_3 B 9725 A 275 Name: Ecology_3, dtype: int64 ************************************************************************************************...
MIT
Web06.ipynb
gera09/Numpy_Matplotlib_Scikit-learn
Обработка выбросов **Rooms**
train_df['Rooms'].value_counts() train_df.loc[train_df['Rooms'].isin([0, 10, 19]), 'Rooms'] = train_df['Rooms'].median()
_____no_output_____
MIT
Web06.ipynb
gera09/Numpy_Matplotlib_Scikit-learn
**Square, LifeSquare, KitchenSquare**
train_df.describe() steps = [] scores = [] # <- записываем финальный score # steps.append('обработка пропусков, выбросов var1') train_df = train_df[train_df['Square'].isnull() | (train_df['Square'] < train_df['Square'].quantile(.99)) & (train_df['Square'] > train_df['Square'].qu...
_____no_output_____
MIT
Web06.ipynb
gera09/Numpy_Matplotlib_Scikit-learn
**HouseFloor, Floor**
train_df['HouseFloor'].sort_values().unique() train_df['Floor'].sort_values().unique() train_df.loc[train_df['HouseFloor'] == 0, 'HouseFloor'] = train_df['HouseFloor'].median() floor_outliers = train_df[train_df['Floor'] > train_df['HouseFloor']].index train_df.loc[floor_outliers, 'Floor'] = train_df.loc[floor_outlier...
_____no_output_____
MIT
Web06.ipynb
gera09/Numpy_Matplotlib_Scikit-learn
**HouseYear**
train_df['HouseYear'].sort_values().unique() train_df.loc[train_df['HouseYear'] > 2020, 'HouseYear'] = 2020
_____no_output_____
MIT
Web06.ipynb
gera09/Numpy_Matplotlib_Scikit-learn