WICHTIG: Der Betrieb von goMatlab.de wird privat finanziert fortgesetzt. - Mehr Infos...

Mein MATLAB Forum - goMatlab.de

Mein MATLAB Forum

 
Gast > Registrieren       Autologin?   

Partner:




Forum
      Option
[Erweitert]
  • Diese Seite per Mail weiterempfehlen
     


Gehe zu:  
Neues Thema eröffnen Neue Antwort erstellen

Fehler: Unary operator '-' is not supported for operand

 

jpauls
Forum-Newbie

Forum-Newbie


Beiträge: 3
Anmeldedatum: 29.04.20
Wohnort: ---
Version: ---
     Beitrag Verfasst am: 29.04.2020, 18:19     Titel: Fehler: Unary operator '-' is not supported for operand
  Antworten mit Zitat      
Hallo zusammen,

ich versuche im Zuge meiner Masterarbeit ein Expected Shortfall Estimation and Backtesting durchzuführen. Das folgende Skript habe ich über die offizielle Mathwork Website bezogen. Ich habe dieses jediglich um meine Finanzwerte ergänzt. Leider bekomme ich bei dem Coding immer die gleichen Fehler.

Sobald ich den markierten Bereich ausführe bekomme ich entweder den Fehler:

Unary operator '-' is not supported for operand of type 'cell'.[/code]

Error in ExpectedShortfallBacktestingExample2>hHistoricalVaRES (line 238)
 Sample = -Sample;

oder
Error using sum
Invalid data type. First argument must be numeric or logical.

Error in ExpectedShortfallBacktestingExample2>hHistoricalVaRES (line 248)
 ES = ((k - N*VaRLevel)*z{k} + sum(z(k+1:N)))/(N*(1 - VaRLevel));

die entsprechenden Lines habe ich auch markiert.
Ich wäre sehr über jegliche Hilfe dankbar.

Code:
%
H = readtable('CAPM2');
symbol = {'PBIT'};
nAsset = numel(symbol);
Convert prices to returns
Returns = (H{:,symbol});
Select assets into portfolio
symbol2 = {'Datum'};
Datum = H{:,symbol2};
DateReturns = Datum(1:end);
SampleSize = length(Returns);

TestWindowStart = find(year(DateReturns)==2015,1);
TestWindowEnd = find(year(DateReturns)==2019,1,'last');
TestWindow = TestWindowStart:TestWindowEnd;
EstimationWindowSize = 250;

DatesTest = DateReturns(TestWindow);
ReturnsTest = Returns(TestWindow);

VaRLevel = 0.975;

VaR_Hist = zeros(length(TestWindow),1);
ES_Hist = zeros(length(TestWindow),1);

[b]for t = TestWindow
   
   i = t - TestWindowStart + 1;
   EstimationWindow = t:EstimationWindowSize-t+1;
   
   [VaR_Hist(i),ES_Hist(i)] = hHistoricalVaRES(Returns(EstimationWindow),VaRLevel);
   
end[/b]


   
   
   


The following plot shows the daily returns, and the VaR and ES estimated with the historical method.
figure;
plot(DatesTest,ReturnsTest,DatesTest,-VaR_Hist,DatesTest,-ES_Hist)
legend('Returns','VaR','ES','Location','southeast')
title('Historical VaR and ES')
grid on



for t = TestWindow
   
   i = t - TestWindowStart + 1;
   EstimationWindow = t:EstimationWindowSize-t+1;
   
   Volatility(i) = std(Returns(EstimationWindow));
   
end

% Mu=0 in this example
Mu = 0;

% Sigma (standard deviation parameter) for normal distribution = Volatility
SigmaNormal = Volatility;
% Sigma (scale parameter) for t distribution = Volatility * sqrt((DoF-2)/DoF)
SigmaT10 = Volatility*sqrt((10-2)/10);
SigmaT5 = Volatility*sqrt((5-2)/5);

% Estimate VaR and ES, normal
[VaR_Normal,ES_Normal] = hNormalVaRES(Mu,SigmaNormal,VaRLevel);
% Estimate VaR and ES, t with 10 and 5 degrees of freedom
[VaR_T10,ES_T10] = hTVaRES(10,Mu,SigmaT10,VaRLevel);
[VaR_T5,ES_T5] = hTVaRES(5,Mu,SigmaT5,VaRLevel);


The following plot shows the daily returns, and the VaR and ES estimated with the normal method.
figure;
plot(DatesTest,ReturnsTest,DatesTest,-VaR_Normal,DatesTest,-ES_Normal)
legend('Returns','VaR','ES','Location','southeast')
title('Normal VaR and ES')
grid on


ebt = esbacktest(ReturnsTest,[VaR_Hist VaR_Normal VaR_T10 VaR_T5],...
   [ES_Hist ES_Normal ES_T10 ES_T5],'PortfolioID',"S&P, 1995-2002",...
   'VaRID',["Historical" "Normal","T 10","T 5"],'VaRLevel',VaRLevel);
disp(ebt)

Start the analysis by running the summary function.
s = summary(ebt);
disp(s)

subplot(2,1,1)
bar(categorical(s.VaRID),[s.ExpectedSeverity,s.ObservedSeverity])
ylim([1 1.5])
legend('Expected','Observed','Location','southeast')
title('Average Severity Ratio')

subplot(2,1,2)
bar(categorical(s.VaRID),[s.Expected,s.Failures])
ylim([40 70])
legend('Expected','Observed','Location','southeast')
title('Number of VaR Failures')

t = runtests(ebt);
disp(t)


t = unconditionalNormal(ebt);
disp(t)


t = unconditionalT(ebt);
disp(t)


t = runtests(ebt);
TLValue = (t.UnconditionalNormal=='reject')+(t.UnconditionalT=='reject');
t.TrafficLight = categorical(TLValue,0:2,{'green','yellow','red'},'Ordinal',true);
disp(t)


t95 = runtests(ebt); % 95% is the default test level value
t99 = runtests(ebt,'TestLevel',0.99);
TLValue = (t95.UnconditionalNormal=='reject')+(t99.UnconditionalNormal=='reject');
tRolling = t95(:,1:3);
tRolling.UnconditionalNormal95 = t95.UnconditionalNormal;
tRolling.UnconditionalNormal99 = t99.UnconditionalNormal;
tRolling.TrafficLight = categorical(TLValue,0:2,{'green','yellow','red'},'Ordinal',true);
disp(tRolling)

sRolling = table;
tRolling = table;
for Year = 2015:2019
   Ind = year(DatesTest)==Year;
   PortID = ['S&P, ' num2str(Year)];
   PortfolioData = ReturnsTest(Ind);
   VaRData = [VaR_Hist(Ind) VaR_Normal(Ind) VaR_T10(Ind) VaR_T5(Ind)];
   ESData = [ES_Hist(Ind) ES_Normal(Ind) ES_T10(Ind) ES_T5(Ind)];
   ebt = esbacktest(PortfolioData,VaRData,ESData,...
      'PortfolioID',PortID,'VaRID',["Historical" "Normal" "T 10" "T 5"],...
      'VaRLevel',VaRLevel);
   if Year == 1995
      sRolling = summary(ebt);
      tRolling = runtests(ebt);
   else
      sRolling = [sRolling;summary(ebt)];
      tRolling = [tRolling;runtests(ebt)];
   end
end

% Optional: Add the first user-defined traffic light test described above
TLValue = (tRolling.UnconditionalNormal=='reject')+(tRolling.UnconditionalT=='reject');
tRolling.TrafficLight = categorical(TLValue,0:2,{'green','yellow','red'},'Ordinal',true);

Display the results, one model at a time. The "T 5" model has the best performance in these tests (two "yellow"), and the "Normal" model the worst (three "red" and one "yellow").
disp(tRolling(tRolling.VaRID=="Historical",:))
disp(tRolling(tRolling.VaRID=="Normal",:))
disp(tRolling(tRolling.VaRID=="T 10",:))
disp(tRolling(tRolling.VaRID=="T 5",:))

T
sH = sRolling(sRolling.VaRID=="Historical",:);

figure;

subplot(2,1,1)
FailureInd = ReturnsTest<-VaR_Hist;
plot(DatesTest,ReturnsTest,DatesTest,-VaR_Hist,DatesTest,-ES_Hist)
hold on
plot(DatesTest(FailureInd),ReturnsTest(FailureInd),'.')
hold off
legend('Returns','VaR','ES','Location','best')
title('Historical VaR and ES')
grid on

subplot(2,1,2)
bar(1995:2002,[sH.ExpectedSeverity,sH.ObservedSeverity])
ylim([1 1.8])
legend('Expected','Observed','Location','best')
title('Yearly Average Severity Ratio, Historical VaR')



subplot(2,1,1)
plot(DatesTest,ReturnsTest,DatesTest,-VaR_Hist,DatesTest,-ES_Hist)
hold on
plot(DatesTest(FailureInd),ReturnsTest(FailureInd),'.')
hold off
legend('Returns','VaR','ES','Location','best')
title('Historical VaR and ES')
grid on

subplot(2,1,2)
bar(1995:2002,[sH.Expected,sH.Failures])
legend('Expected','Observed','Location','best')
title('Yearly VaR Failures, Historical VaR')


s = summary(ebts);
disp(s)

The runtests function shows the final accept or reject result.
t = runtests(ebts);
disp(t)

Additional details on the test results are obtained by calling the individual test functions.
[t,s] = conditional(ebts);
disp(t)



The following figure is a visualization of the significance of the tests. The histogram shows the distribution of simulated test statistics, and the asterisk shows the value of the test statistic for the actual portfolio returns.
For the conditional test, this is a visualization of the standalone conditional test (ConditionalOnly result in the table above). The final conditional test result (Conditional column) depends also on a preliminary VaR backtest (VaRTestResult column).
figure;
histogram(s);
hold on;
plot(t.TestStatistic,0,'*');
hold off;
Title = sprintf('Conditional: %s, p-value: %4.3f',t.VaRID,t.PValue);
title(Title)


[t,s] = unconditional(ebts);
disp(t)

figure;
histogram(s);
hold on;
plot(t.TestStatistic,0,'*');
hold off;
Title = sprintf('Unconditional: %s, p-value: %4.3f',t.VaRID,t.PValue);
title(Title)

Here are the results for the quantile test.
[t,s] = quantile(ebts);
disp(t)

figure;
histogram(s);
hold on;
plot(t.TestStatistic,0,'*');
hold off;
Title = sprintf('Quantile: %s, p-value: %4.3f',t.VaRID,t.PValue);
title(Title)


s = summary(ebtde);
disp(s)


t = runtests(ebtde);
disp(t)


t = conditionalDE(ebtde);
disp(t)




xLS = 0:0.05:30;
pdfLS = chi2pdf(xLS,t.NumLags);
histogram(s,'Normalization',"pdf")
hold on
plot(xLS,pdfLS)
hold off
ylim([0 0.1])
legend({'Simulation','Large-Sample'})
Title = sprintf('Conditional Test Distribution\nVaR Level: %g%%, Sample Size = %d',VaRLevel*100,t.Observations);
title(Title)




Local Functions
function [VaR,ES] = hHistoricalVaRES(Sample,VaRLevel)
    % Compute historical VaR and ES
    % See [5] for technical details

    % Convert to losses
[color=yellow]  [b]  Sample = -Sample;[/b][/color]
   
    N = length(Sample);
    k = ceil(N*VaRLevel);
   
    z = sort(Sample);
   
    VaR = z(k);
   
    if k < N
[color=green]     [size=18]  [b]ES = ((k - N*VaRLevel)*z{k} + sum(z(k+1:N)))/(N*(1 - VaRLevel));[/b][/size]
[/color]    else
       ES = z(k);
    end
end

function [VaR,ES] = hNormalVaRES(Mu,Sigma,VaRLevel)
    % Compute VaR and ES for normal distribution
    % See [4] for technical details
   
    VaR = -1*(Mu-Sigma*norminv(VaRLevel));
    ES = -1*(Mu-Sigma*normpdf(norminv(VaRLevel))./(1-VaRLevel));

end

function [VaR,ES] = hTVaRES(DoF,Mu,Sigma,VaRLevel)
    % Compute VaR and ES for t location-scale distribution
    % See [4] for technical details

    VaR = -1*(Mu-Sigma*tinv(VaRLevel,DoF));
    ES_StandardT = (tpdf(tinv(VaRLevel,DoF),DoF).*(DoF+tinv(VaRLevel,DoF).^2)./((1-VaRLevel).*(DoF-1)));
    ES = -1*(Mu-Sigma*ES_StandardT);

end
 
Private Nachricht senden Benutzer-Profile anzeigen


Harald
Forum-Meister

Forum-Meister


Beiträge: 24.448
Anmeldedatum: 26.03.09
Wohnort: Nähe München
Version: ab 2017b
     Beitrag Verfasst am: 29.04.2020, 20:32     Titel:
  Antworten mit Zitat      
Hallo,

die Fehlermeldung sagt ja recht klar, was das Problem ist. Schau dir doch mal im Debugger an, was Returns(EstimationWindow) ergibt. Es muss numerisch sein, ist aber ein Cell.

Grüße,
Harald
_________________

1.) Ask MATLAB Documentation
2.) Search gomatlab.de, google.de or MATLAB Answers
3.) Ask Technical Support of MathWorks
4.) Go mad, your problem is unsolvable ;)
Private Nachricht senden Benutzer-Profile anzeigen
 
jpauls
Themenstarter

Forum-Newbie

Forum-Newbie


Beiträge: 3
Anmeldedatum: 29.04.20
Wohnort: ---
Version: ---
     Beitrag Verfasst am: 29.04.2020, 20:51     Titel:
  Antworten mit Zitat      
ja das stimmt, danke schon einmal dafür!! Sorry aber ich gucke seit mehreren Wochen auf diese Codings etc...

laut google funktioniert die Umwandlung wie folgt:
H = readtable('CAPM2');
symbol = {'PBIT'};
nAsset = numel(symbol);
Convert prices to returns
ret = (H{:,symbol});
Returns = str2double(ret)

leider bekomme ich dann folgenden Fehler ( dazu sei gesagt, dass mit der Änderung ein anderes Coding jetzt funktioniert Laughing )

Code:
VaR_Hist = zeros(length(TestWindow),1);
ES_Hist = zeros(length(TestWindow),1);

for t = TestWindow
   
   i = t - TestWindowStart + 1;
   EstimationWindow = t:EstimationWindowSize-t+1;
   
   [VaR_Hist(i),ES_Hist(i)] = hHistoricalVaRES(Returns(EstimationWindow),VaRLevel);
   
end
Array indices must be positive integers or logical values.
Error in ExpectedShortfallBacktestingExample2>hHistoricalVaRES (line 246)
    VaR = z(k);


Bitte entschuldige meine wahrscheinlich dummen Fragen aber ich bin komplett neu in der Welt.
Private Nachricht senden Benutzer-Profile anzeigen
 
Harald
Forum-Meister

Forum-Meister


Beiträge: 24.448
Anmeldedatum: 26.03.09
Wohnort: Nähe München
Version: ab 2017b
     Beitrag Verfasst am: 29.04.2020, 20:54     Titel:
  Antworten mit Zitat      
Hallo,

nächster Schritt: Haltepunkt in die Zeile setzen und schauen, was mit k ist. Ich kann dir dabei leider nicht helfen, da ich den Code ja nicht laufen lassen kann.

Grüße,
Harald
_________________

1.) Ask MATLAB Documentation
2.) Search gomatlab.de, google.de or MATLAB Answers
3.) Ask Technical Support of MathWorks
4.) Go mad, your problem is unsolvable ;)
Private Nachricht senden Benutzer-Profile anzeigen
 
jpauls
Themenstarter

Forum-Newbie

Forum-Newbie


Beiträge: 3
Anmeldedatum: 29.04.20
Wohnort: ---
Version: ---
     Beitrag Verfasst am: 29.04.2020, 21:09     Titel:
  Antworten mit Zitat      
Danke Harald,

nach dem Stop wird mir k als 1x1double angezeigt mit value 1
Private Nachricht senden Benutzer-Profile anzeigen
 
Harald
Forum-Meister

Forum-Meister


Beiträge: 24.448
Anmeldedatum: 26.03.09
Wohnort: Nähe München
Version: ab 2017b
     Beitrag Verfasst am: 29.04.2020, 21:20     Titel:
  Antworten mit Zitat      
Hallo,

das erklärt den Fehler nicht.
Du hast ja eine for-Schleife. Möglicherweise schaust du in eine Iteration und der Fehler passiert in einer anderen. Also immer "Continue", bis das problematische k kommt.

Grüße,
Harald
_________________

1.) Ask MATLAB Documentation
2.) Search gomatlab.de, google.de or MATLAB Answers
3.) Ask Technical Support of MathWorks
4.) Go mad, your problem is unsolvable ;)
Private Nachricht senden Benutzer-Profile anzeigen
 
Neues Thema eröffnen Neue Antwort erstellen



Einstellungen und Berechtigungen
Beiträge der letzten Zeit anzeigen:

Du kannst Beiträge in dieses Forum schreiben.
Du kannst auf Beiträge in diesem Forum antworten.
Du kannst deine Beiträge in diesem Forum nicht bearbeiten.
Du kannst deine Beiträge in diesem Forum nicht löschen.
Du kannst an Umfragen in diesem Forum nicht mitmachen.
Du kannst Dateien in diesem Forum posten
Du kannst Dateien in diesem Forum herunterladen
.





 Impressum  | Nutzungsbedingungen  | Datenschutz | FAQ | goMatlab RSS Button RSS

Hosted by:


Copyright © 2007 - 2024 goMatlab.de | Dies ist keine offizielle Website der Firma The Mathworks

MATLAB, Simulink, Stateflow, Handle Graphics, Real-Time Workshop, SimBiology, SimHydraulics, SimEvents, and xPC TargetBox are registered trademarks and The MathWorks, the L-shaped membrane logo, and Embedded MATLAB are trademarks of The MathWorks, Inc.