Exemple #1
0
def struct_to_dict(s, as_namedtuple=True):
    if as_namedtuple:
        if s.dtype.names:
            nt = namedtuple('db', s.dtype.names)
            d = {}
            for x in s.dtype.names:
                try:
                    if x in ['Parameters', 'marginalt', 'DCCfit']:
                        d[x] = struct_to_dict(s[x])
                    elif isinstance(s[x], np.ndarray):
                        if x == 'sig2':
                            d[x] = s[x][0]
                        else:
                            d[x] = s[x]
                    else:
                        d[x] = np.atleast_1d(s[x]).flatten()[0]
                except:
                    d[x] = None
            nt = nt(**d)
            return nt
    else:
        if s.dtype.names:
            return {x: np.atleast_1d(s[x]).flatten()[0] for x in s.dtype.names}
i_ = 25  # number of stocks
t_ = 100  # len of time series
j_ = 500  # number of simulated time series for each k-th DGP [low for speed increase for accuracy]
k_ = 5  # number of perturbed DGP's [low for speed]
h = 0  # DGP whose loss is plotted
# -

# ## Upload databases

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_StocksS_P'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_StocksS_P'), squeeze_me=True)

Data = struct_to_dict(db['Data'])

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_VIX'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_VIX'), squeeze_me=True)

VIX = struct_to_dict(db['VIX'], as_namedtuple=False)
# -

# ## Compute the stocks' log-returns

# +
dates_x = Data.Dates
x = Data.Prices
Exemple #3
0
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_PricingScenarioBased'),
                 squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_PricingScenarioBased'),
                 squeeze_me=True)

# ## Compute the holdings corresponding to the following portfolio, fully invested in the n_=15 instruments
# ## $50k are invested in the stocks, such that the stocks are equally weighted
# ## The holdings in each bond are h=5000 (i.e. each bond has $5000 notional)
# ## The call options (same expiry, increasing strikes) have respective
# ## holdings equal to [1 -2, 1] (long butterfly strategy)

# +
Stocks = struct_to_dict(db['Stocks'], as_namedtuple=False)
Bonds = struct_to_dict(db['Bonds'], as_namedtuple=False)
Options = struct_to_dict(db['Options'], as_namedtuple=False)
v_tnow = db['v_tnow'].reshape(-1, 1)
Pi = db['Pi']
t_ = db['t_']

v0_stocks = 50000
w_stocks = ones((Stocks['n_'], 1)) / Stocks['n_']
Stocks['h'] = round((w_stocks * v0_stocks) / Stocks['v_tnow'].reshape(-1, 1))
Bonds['h'] = 5000 * ones((Bonds['n_'], 1))
Options['h'] = array([[1], [-2], [1]])

h = r_[Stocks['h'], Bonds['h'], Options['h']]  # ## holdings
cash = 0
# -
from autocorrelation import autocorrelation
from TradeQuoteProcessing import TradeQuoteProcessing
from InvarianceTestEllipsoid import InvarianceTestEllipsoid
# -

# ## Upload the database

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_US_10yr_Future_quotes_and_trades'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_US_10yr_Future_quotes_and_trades'), squeeze_me=True)

# ## Process the time series, refining the raw data coming from the database

# +
quotes = struct_to_dict(db['quotes'])
trades = struct_to_dict(db['trades'])

dates_quotes = quotes.time_names  #
t = quotes.time  # time vector of quotes
p_bid = quotes.bid  # bid prices
p_ask = quotes.ask  # ask prices
q_bid = quotes.bsiz  # bid volumes
q_ask = quotes.asiz  # ask volumes

dates_trades = trades.time_names  #
t_k = trades.time  # time vector of trades
p_last = trades.price  # last transaction prices
delta_q = trades.siz  # flow of traded contracts' volumes
delta_sgn = trades.aggress  # trade sign flow
match = trades.mtch  # match events: - the "1" value indicates the "start of a match event" while zeros indicates the "continuation of a match event"
from CONFIG import GLOBAL_DB, TEMPORARY_DB
from ARPM_utils import save_plot, struct_to_dict, date_mtop
from FitStochasticVolatilityModel import FitStochasticVolatilityModel
from FilterStochasticVolatility import FilterStochasticVolatility
from PlotTwoDimEllipsoid import PlotTwoDimEllipsoid
# -

# ## Upload database

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_Stocks'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_Stocks'), squeeze_me=True)

SPX = struct_to_dict(db['SPX'])

# daily prices and log-prices
price = SPX.Price_close
date = SPX.Date
logprice = log(price)
# -

# ## Compute weekly prices, returns and the log-square volatility
# ##pick weekly data

# +
w = arange(0, len(logprice), 5)
date = array([date_mtop(i) for i in SPX.Date[w]])

# prices
plt.style.use('seaborn')
# -

# ## Upload data from db_ImpliedVol_FX

# +
from CONFIG import GLOBAL_DB, TEMPORARY_DB
from ARPM_utils import save_plot, struct_to_dict
from intersect_matlab import intersect

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_ImpliedVol_FX'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_ImpliedVol_Fx'), squeeze_me=True)

db_ImpliedVol_FX = struct_to_dict(db['db_ImpliedVol_FX'])

# implied volatility surface for GBPUSD rate (in percentage format)

tau = db_ImpliedVol_FX.TimesToMaturity
delta =  db_ImpliedVol_FX.Delta
sigma_delta  =  db_ImpliedVol_FX.Sigma
t_ = sigma_delta.shape[2]
n_ = len(delta)
# -

# ## Plot the implied volatility surface and the evolution of implied volatility for the desired values of delta-moneyness and times to maturity

# +
_,tauIndex,_ = intersect(tau,1) # select 1 year of maturity
meanIndex_delta = int(ceil((n_)/2))-1
from ARPM_utils import save_plot, struct_to_dict
from TestKolSmirn import TestKolSmirn
from InvarianceTestKolSmirn import InvarianceTestKolSmirn
# -

# ## Upload the database
# ## Upload daily stock prices from db_Stocks

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_Stocks'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_Stocks'), squeeze_me=True)

StocksSPX = struct_to_dict(db['StocksSPX'])
# -

# ## Compute the dividend adjusted prices of one stock

stock_index = 0
v = StocksSPX.Prices[[stock_index], :]
date = StocksSPX.Date
div = StocksSPX.Dividends[stock_index][0]
# if not div:
#     v,_=Price2AdjustedPrice(date,v,div)

# ## Compute the time series for each variable

x = v[[0], 1:] / v[[0], :-1]
y = v[[0], 1:] - v[[0], :-1]
Exemple #8
0
from HistogramFP import HistogramFP
from ColorCodedFP import ColorCodedFP
from IterGenMetMomFP import IterGenMetMomFP
from binningHFseries import binningHFseries
from BlowSpinFP import BlowSpinFP
# -

# ## Upload database

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_US_10yr_Future_quotes_and_trades'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_US_10yr_Future_quotes_and_trades'), squeeze_me=True)

trades = struct_to_dict(db['trades'])
# -

# ## Comupte the invariants: eps= dn = number of trades in 1-second time intervals

# +
flag_dt = '1second'
trade = unique(trades.time)  # trade time
dk, k,*_ = binningHFseries(trade, flag_dt)
time = array([date_mtop(i) for i in arange(trade[0], trade[-1], 1.1574e-05)])
# time = cellstr((time))
time = time[1:]

epsi = dk
t_ = epsi.shape[1]
# -
Exemple #9
0
from Delta2MoneynessImplVol import Delta2MoneynessImplVol
from FitVAR1 import FitVAR1
from ExponentialDecayProb import ExponentialDecayProb
from InverseCallTransformation import InverseCallTransformation
# -

# ## Upload databases and match the time series of interest to work with synchronous observations

# +
#load
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_Stocks'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_Stocks'), squeeze_me=True)

StocksSPX = struct_to_dict(db['StocksSPX'], as_namedtuple=False)

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_SwapCurve'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_SwapCurve'), squeeze_me=True)

DF_Rolling = struct_to_dict(db['DF_Rolling'], as_namedtuple=False)

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_ImpliedVol_SPX'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_ImpliedVol_SPX'),
                 squeeze_me=True)

db_ImpliedVol_SPX = struct_to_dict(db['db_ImpliedVol_SPX'],
Exemple #10
0
                 squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_SPX_zcb_Invariants'),
                 squeeze_me=True)

dates = db['dates']
epsi_SPX = db['epsi_SPX']

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_VIX'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_VIX'), squeeze_me=True)

from ARPM_utils import struct_to_dict

VIX = struct_to_dict(db['VIX'])
# -

# ## Recover the time series of realized invariants

# VIX's compounded returns
c_VIX = diff(log(VIX.value))

# ## Compute the time series of the conditioning variable by applying sequentially smoothing and scoring filters to the time series of VIX's compounded returns

# +
t_vix = len(c_VIX)
times = arange(t_vix)

# smoothing
z_vix = zeros((1, t_vix))
from TradeQuoteProcessing import TradeQuoteProcessing
# -

# ## Upload the database

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB,
                              'db_US_10yr_Future_quotes_and_trades'),
                 squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB,
                              'db_US_10yr_Future_quotes_and_trades'),
                 squeeze_me=True)

quotes = struct_to_dict(db['quotes'], as_namedtuple=False)
trades = struct_to_dict(db['trades'], as_namedtuple=False)
# -

# ## Process the time series, refining the raw data coming from the database

# +
dates_quotes = quotes['time_names']  #
t = quotes['time']  # time vector of quotes
p_bid = quotes['bid']  # bid prices
p_ask = quotes['ask']  # ask prices
q_bid = quotes['bsiz']  # bid volumes
q_ask = quotes['asiz']  # ask volumes

dates_trades = trades['time_names']  #
t_k = trades['time']  # time vector of trades
Exemple #12
0
# -

# ## Upload the implied-volatility and the underlying value data from db_ImpliedVol_SPX
# and the realized time series of the rolling values contained in db_SwapCurve.

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_ImpliedVol_SPX'))
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_ImpliedVol_SPX'))
try:
    db_swap = loadmat(os.path.join(GLOBAL_DB, 'db_SwapCurve'))
except FileNotFoundError:
    db_swap = loadmat(os.path.join(TEMPORARY_DB, 'db_SwapCurve'))

db_ImpliedVol_SPX = struct_to_dict(db['db_ImpliedVol_SPX'])
DF_Rolling = struct_to_dict(db_swap['DF_Rolling'])

# ## run S_PricingCallOptionValue which computes the call option exact pricing

from S_PricingCallOptionValue import *

# call option price at time t=0
d1_0 = (log(S_u[0, 0] / k) / sqrt(expiry / 252) + sqrt(expiry / 252) *
        (Y[0, 0] + 0.5 * exp(LogSigma_interp[0, 0])**2)) / exp(
            LogSigma_interp[0, 0])
d2_0 = d1_0 - exp(LogSigma_interp[0, 0]) * sqrt(expiry / 252)
Vcall_0 = S_u[0, 0] * (norm.cdf(d1_0) - exp(-(
    (log(S_u[0, 0] / k) / sqrt(expiry / 252)) * sqrt(expiry / 252) +
    Y[0, 0] * expiry / 252)) * norm.cdf(d2_0))
from FPmeancov import FPmeancov
from intersect_matlab import intersect
from HistogramFP import HistogramFP
from SimulateBrownMot import SimulateBrownMot
# -

# ## Load the historical series of the S&P 500 from StocksS_P
# ## and the historical series of hte daily exchange rate from db_FX.

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_StocksS_P'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_StocksS_P'), squeeze_me=True)

Data = struct_to_dict(db['Data'])

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_FX'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_FX'), squeeze_me=True)

USD_GBP = struct_to_dict(db['USD_GBP'])
# -

# ## Select the daily price of the Priceline.com Inc equity (S&P 500 dataset with n= 279)
# ## and the USD/GBP daily exchange rate (USD_GBP.FX from db_FX), and compute the risk drivers,
# ## that are the log-value for the equity and the log-rate for the spot exchange rate.

# +
t_end = 240
nu = 4  # degrees of freedom of the t copula we want to fit
nu_vec = arange(2, 31)
nu_ = len(nu_vec)
j_ = 2000  # number of scenarios
k_ = 1  # factors for correlation shrinkage
# -

# ## Upload databases

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_Stocks'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_Stocks'), squeeze_me=True)

SPX = struct_to_dict(db['SPX'])

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_CorporateBonds'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_CorporateBonds'),
                 squeeze_me=True)

GE = struct_to_dict(db['GE'])

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_VIX'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_VIX'), squeeze_me=True)

VIX = struct_to_dict(db['VIX'])
from ARPM_utils import save_plot, struct_to_dict
from autocorrelation import autocorrelation
from FitFractionalIntegration import FitFractionalIntegration
from InvarianceTestEllipsoid import InvarianceTestEllipsoid
# -

# ## Upload database

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_StocksHighFreq'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_StocksHighFreq'),
                 squeeze_me=True)

MSFT = struct_to_dict(db['MSFT'])

price = MSFT.trade_price
ask = MSFT.ask
bid = MSFT.bid
# -

# ## Compute the realizations of the variable "sign" (dz_k: difference in cumulative trade sign in tick time)
# ##take data with (ask > bid) and (price = bid or price = ask) and (bid different form ask)

scale = 5
index = ((bid != ask) & (price == bid)) | ((price == ask) & (ask > bid))
frac = (price[index] - bid[index]) / (ask[index] - bid[index])
dz_k = erf(scale * (2 * frac - 1))

# ## Fit the fractional integration process
Exemple #16
0
plt.style.use('seaborn')

from CONFIG import GLOBAL_DB, TEMPORARY_DB
from ARPM_utils import save_plot, struct_to_dict, date_mtop
from intersect_matlab import intersect
# -

# ## Upload database

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_Stocks'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_Stocks'), squeeze_me=True)

SPX = struct_to_dict(db['SPX'])
KOSPI = struct_to_dict(db['KOSPI'])
# -

# ## Compute the log-prices and log-returns of the two indexes

# +
# S&P 500 (US)
NSprice = SPX.Price_close
x1 = log(NSprice)
NSdate = SPX.Date

# KOSPI (Korea)
KSprice = KOSPI.Price_close
x2 = log(KSprice)
KSdate = KOSPI.Date
Exemple #17
0
par_start.theta1 = 0.05  # starting values
par_start.theta2 = 0.05
par_start.theta3 = 0.05
par_start.theta4_squared = 0.05
tau = array([0.0833, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30])  # select time to maturities
# -

# ## Upload the rolling values from db_SwapCurve and compute the corresponding yields to maturity using function RollPrices2YieldToMat

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_SwapCurve'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_SwapCurve'), squeeze_me=True)

DF_Rolling = struct_to_dict(db['DF_Rolling'])

# reference yields from rolling prices
y_ref,_ = RollPrices2YieldToMat(DF_Rolling.TimeToMat, DF_Rolling.Prices)
# -

# ## Upload JPM bond prices from db_CorporateBonds and restrict the yields to available dates

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_CorporateBonds'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_CorporateBonds'), squeeze_me=True)

JPM = struct_to_dict(db['JPM'])
Exemple #18
0
# ##Load the transition matrix

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_FitCreditTransitions'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_FitCreditTransitions'), squeeze_me=True)

p_EP = db['p_EP']

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_Ratings'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_Ratings'), squeeze_me=True)

db_Ratings = struct_to_dict(db['db_Ratings'])

Transitions = namedtuple('Transition', 'p ratings p_tau_step p_default')
Transitions.p = p_EP
Transitions.ratings = db_Ratings.ratings

# Inject the transition matrix
Transitions.p_tau_step = ProjectTransitionMatrix(Transitions.p, 1 / 252)
Transitions.p_default = Transitions.p_tau_step[:,-1]

# Compute threshold matrix
u_tau = r_['-1', zeros((Transitions.p_tau_step.shape[0], 1)), cumsum(Transitions.p_tau_step, 1)]
# -

# ## Compute the log-returns (invariants) of the 5 obligor's stocks
Exemple #19
0
# inputs
j_ = 1000  # number of simulations
nb = round(5 * log(j_))

nu = 3  # degree of freedom
r = 0.95  # panic correlation
c = 0.07  # threshold

# Load daily observations of the stocks in S&P 500
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_StocksS_P'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_StocksS_P'), squeeze_me=True)

Data = struct_to_dict(db['Data'])

V = Data.Prices
pair = [0, 1]  # stocks to spot

# Set the calm correlation matrix as sample correlation matrix of compounded returns
C = diff(log(V), 1, 1)
C = C[pair, :]
varrho2 = corrcoef(C)

# Compute panic distribution
X, p_ = PanicTDistribution(varrho2, r, c, nu, j_)

# Extract the simulations of the panic copula
x, u, U = CopMargSep(X, p_)
# -
Exemple #20
0
from CONFIG import GLOBAL_DB, TEMPORARY_DB
from ARPM_utils import save_plot, struct_to_dict
from intersect_matlab import intersect
from PlotTwoDimEllipsoid import PlotTwoDimEllipsoid
from RollPrices2YieldToMat import RollPrices2YieldToMat
# -

# ## Upload the database

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_SwapCurve'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_SwapCurve'), squeeze_me=True)

DF_Rolling = struct_to_dict(db['DF_Rolling'])
# -

# ## Compute yields, select observations and compute increments

# +
tau = [1, 5, 21]
nu = array([[2],[10]])  # times to maturity of interest (years)
y = {}

_, index, *_ = intersect(DF_Rolling.TimeToMat,nu)
# yields from rolling prices
y[0],_= RollPrices2YieldToMat(DF_Rolling.TimeToMat[index], DF_Rolling.Prices[index,:])  # yield daily observations
# extract weekly and monthly observations
for k in range(len(tau)):
    y[k] = y[0][:, ::tau[k]]  # computing increments
Exemple #21
0
from VAR1toMVOU import VAR1toMVOU
from FitVAR1 import FitVAR1
from ShiftedVGMoments import ShiftedVGMoments
from FitCIR_FP import FitCIR_FP
from InverseCallTransformation import InverseCallTransformation
# -

# ## Upload the databases and match the time series of interest to work with synchronous observations

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_Stocks'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_Stocks'), squeeze_me=True)

SPX = struct_to_dict(db['SPX'], as_namedtuple=False)

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_SwapCurve'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_SwapCurve'), squeeze_me=True)

DF_Rolling = struct_to_dict(db['DF_Rolling'], as_namedtuple=False)

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_OptionStrategy'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_OptionStrategy'),
                 squeeze_me=True)

OptionStrategy = struct_to_dict(db['OptionStrategy'], as_namedtuple=False)
Exemple #22
0
from SortBySector import SortBySector
from HomCl import HomCl

# inputs
index = [96, 97, 128, 132, 138]  # entries of interest
# -

# ## Upload database

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_StocksS_P'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_StocksS_P'), squeeze_me=True)

Data = struct_to_dict(db['Data'])
# -

# ## Compute the correlation matrix from the log-returns

# +
prices = Data.Prices

i_ = prices.shape[0]
t_ = prices.shape[1]

epsi = log(prices[:, 1:t_] / prices[:, :t_ - 1])
c2 = corrcoef(epsi)  # sample correlation matrix
# -

# ## Sort the correlation matrix by sectors
# parameters
tau = 6  # projection horizon
# -

# ## Upload databases db_ImpliedVol_SPX, db_SwapCurve and db_VIX, and where the common daily observations

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_ImpliedVol_SPX'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(
        os.path.join(TEMPORARY_DB, 'db_ImpliedVol_SPX'), squeeze_me=True
    )  # underlying values and implied volatility surface for S&P 500

db_ImpliedVol_SPX = struct_to_dict(db['db_ImpliedVol_SPX'], False)

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_SwapCurve'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(
        os.path.join(TEMPORARY_DB, 'db_SwapCurve'),
        squeeze_me=True)  # rolling values used to computed the short rate

DF_Rolling = struct_to_dict(db['DF_Rolling'], False)

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_VIX'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_VIX'),
                 squeeze_me=True)  # Vix index values
from RollPrices2YieldToMat import RollPrices2YieldToMat
from EffectiveScenarios import EffectiveScenarios
from ConditionalFP import ConditionalFP
from Stats import Stats
from ColorCodedFP import ColorCodedFP
# -

# ## Upload data

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_Stocks'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_Stocks'), squeeze_me=True)

SPX = struct_to_dict(db['SPX'])
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_VIX'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_VIX'), squeeze_me=True)

VIX = struct_to_dict(db['VIX'])

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_SwapCurve'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_SwapCurve'), squeeze_me=True)

DF_Rolling = struct_to_dict(db['DF_Rolling'])
# -
from CONFIG import GLOBAL_DB, TEMPORARY_DB
from ARPM_utils import save_plot, struct_to_dict, date_mtop
from FPmeancov import FPmeancov
from PlotTwoDimEllipsoid import PlotTwoDimEllipsoid
# -

# ## Upload data from db_ImpliedVol_SPX

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_ImpliedVol_SPX'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_ImpliedVol_SPX'),
                 squeeze_me=True)  # implied volatility surface for SP500

db_ImpliedVol_SPX = struct_to_dict(db['db_ImpliedVol_SPX'])

tau = db_ImpliedVol_SPX.TimeToMaturity
delta = db_ImpliedVol_SPX.Delta  # delta-moneyness
sigma_delta = db_ImpliedVol_SPX.Sigma

implied_vol = sigma_delta[0, delta == 0.5,
                          1:]  # at the money option expiring in tau[0] years
prices = db_ImpliedVol_SPX.Underlying
logrets = diff(log(prices))
dates = db_ImpliedVol_SPX.Dates[1:]
dates = array([date_mtop(i) for i in dates])

t_ = len(dates)

lam = log(2) / 90  # exp decay probs, half life 3 months
Exemple #26
0
from MMFP import MMFP
from VGpdf import VGpdf
from ParamChangeVG import ParamChangeVG
from ShiftedVGMoments import ShiftedVGMoments
from VG import VG
# -

# ## Upload databases

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_OptionStrategy'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_OptionStrategy'), squeeze_me=True)

OptionStrategy = struct_to_dict(db['OptionStrategy'])

try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_VIX'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_VIX'), squeeze_me=True)

VIX = struct_to_dict(db['VIX'])

# invariants (daily P&L)
pnl = OptionStrategy.cumPL
epsi = diff(pnl)
dates_x = array([datenum(i) for i in OptionStrategy.Dates])
dates_x = dates_x[1:]

# conditioning variable (VIX)
Exemple #27
0
plt.style.use('seaborn')

from CONFIG import GLOBAL_DB, TEMPORARY_DB
from ARPM_utils import save_plot, struct_to_dict
from ProjDFFT import ProjDFFT
# -

# ## Upload databases db_Uniform

# +
try:
    db = loadmat(os.path.join(GLOBAL_DB, 'db_Uniform'), squeeze_me=True)
except FileNotFoundError:
    db = loadmat(os.path.join(TEMPORARY_DB, 'db_Uniform'), squeeze_me=True)

UniformStrategy = struct_to_dict(db['UniformStrategy'])
# -

# ## Select the time series of cumulative P&L and set an horizon tau = 20

# +
x = UniformStrategy.cumPL

t_ = 4  #
tau = 20  # investment horizon expressed in days
k_ = 2**11  # coarseness level for projection
# -

# ## Set the parameters of the one-step uniform distribution

mu = 1 / 2  # mean