Con el siguiente script intento calcular, dentro de una clase, el VaR Histórico y el Teórico obtenidos a través de la distribución normal,
import yfinance as yf
import numpy as np
from scipy import stats
from scipy.stats import norm
def get_quotes(ticker, start_day, end_day):
yfObj = yf.Ticker(ticker)
name = yfObj.info['shortName']
df = yf.download(ticker, start= start_day, end = end_day)
df.rename(columns={'Adj Close': name }, inplace=True)
data = df.drop(['Close','High', 'Low', 'Open', 'Volume'], axis=1 )
return data, name
ticker_val = 'SPY'
start_day = "1993-1-1"
end_day = "2019-11-1"
# Import Market quotes
df_aux, name = get_quotes(ticker_val, start_day, end_day)
df_aux['returns'] = df_aux[name].pct_change()
df_aux.dropna( )
class CalculadorIndicadoresRiesgo:
def __init__(self, df):
self.df = df
# VaR Teórico obtenido a través de la distribución normal al 95% y 99% de confianza.
def theoretical_var (self) :
print ('\nAdjusted parameters of the normal distribution used by SNS')
(mu, sigma) = stats.norm.fit(df_aux[name])
print (f"\t>VaR Gaussian model NC-95% : {norm.ppf(0.05, mu, sigma)*100:.2f}%")
print (f"\t>VaR Gaussian model NC-99% : {norm.ppf(0.01, mu, sigma)*100:.2f}%")
print (f"\t>VaR Gaussian model NC-99.7% : {norm.ppf(0.003, mu, sigma)*100:.2f}%")
# VaR histórico al 95% y 99% de confianza.
def historical_var (self) :
print ('\nVaR Thistórico al 95% y 99% de confianza.')
(mu, sigma) = stats.norm.fit(df_aux['returns'])
print (f"\t> VaR Gaussian model NC-95% : {np.percentile(self.df_aux['returns']*100, 5):.2f}%")
print (f"\t> VaR Gaussian model NC-95% : {np.percentile(self.df_aux['returns']*100, 1):.2f}%")
print (f"\t> VaR Gaussian model NC-95% : {np.percentile(self.df_aux['returns']*100, .3):.2f}%")
print (80*'=')
indicadores_riesgo = CalculadorIndicadoresRiesgo( df_aux)
indicadores_riesgo.theoretical_var()
indicadores_riesgo.historical_var ()
Me devuelve:
Adjusted parameters of the normal distribution used by SNS
>VaR Gaussian model NC-95% : 229.39%
>VaR Gaussian model NC-99% : -4164.49%
>VaR Gaussian model NC-99.7% : -6881.64%
VaR Thistórico al 95% y 99% de confianza.
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
/tmp/ipykernel_9457/4260036454.py in <module>
22 indicadores_riesgo = CalculadorIndicadoresRiesgo( df_aux)
23 indicadores_riesgo.theoretical_var()
---> 24 indicadores_riesgo.historical_var ()
/tmp/ipykernel_9457/4260036454.py in historical_var(self)
14 def historical_var (self) :
15 print ('\nVaR Thistórico al 95% y 99% de confianza.')
---> 16 (mu, sigma) = stats.norm.fit(df_aux['returns'])
17 print (f"\t> VaR Gaussian model NC-95% : {np.percentile(self.df_aux['returns']*100, 5):.2f}%")
18 print (f"\t> VaR Gaussian model NC-95% : {np.percentile(self.df_aux['returns']*100, 1):.2f}%")
~/anaconda3/envs/yfinance/lib/python3.9/site-packages/scipy/stats/_continuous_distns.py in wrapper(self, *args, **kwds)
60 return super(type(self), self).fit(*args, **kwds)
61 else:
---> 62 return fun(self, *args, **kwds)
63 return wrapper
64
~/anaconda3/envs/yfinance/lib/python3.9/site-packages/scipy/stats/_continuous_distns.py in fit(self, data, **kwds)
361
362 if not np.isfinite(data).all():
--> 363 raise RuntimeError("The data contains non-finite values.")
364
365 if floc is None:
RuntimeError: The data contains non-finite values.
Gracias de antemano por vuestra ayuda.
He comprobado que el error se devuelve en la sentencia
(mu, sigma) = stats.norm.fit(df['returns'])
mu, sigma
RuntimeError Traceback (most recent call last) /tmp/ipykernel_7998/4268868510.py in ----> 1 (mu, sigma) = stats.norm.fit(df['returns']) 2 3 mu, sigma
~/anaconda3/envs/yfinance/lib/python3.9/site-packages/scipy/stats/_continuous_distns.py in wrapper(self, *args, **kwds)
60 return super(type(self), self).fit(*args, **kwds)
61 else:
---> 62 return fun(self, *args, **kwds)
63 return wrapper
64
~/anaconda3/envs/yfinance/lib/python3.9/site-packages/scipy/stats/_continuous_distns.py in fit(self, data, **kwds)
361
362 if not np.isfinite(data).all():
--> 363 raise RuntimeError("The data contains non-finite values.")
364
365 if floc is None:
RuntimeError: The data contains non-finite values.
¿Podría ser debido a que la columna 'returns' tiene valores muy pequeños? [![Columna returns][1]][1]
He comprobado si en la columna hay non-finete values, haciendo
~np.isfinite(df['returns'])
Me devuelve
[![ivalores non finite][2]][2] valores non-finite Es evidente que en la primera línea tengo un nan. Elimino esta línea con el métdo df.dropna() y el problema se resuelve, [1]: https://i.sstatic.net/VThKG.png [2]: https://i.sstatic.net/jLhNI.png