How to plot levels for Higher high and Lower low for last 100 bars - plot

I am trying to plot target levels for last lower low and last higher high, but not getting any solution for ploting my targets TU2 (Upper Targer on Lower low) and TD2 Lower target from Higher high.
//#version=5
indicator('Implied Volatility ', shorttitle='IV Raj', overlay = true)
spot = input(close, title='Source')
Expiry = input.int(10, title='Days until expiry', minval=0)
//VixFix Length Parameters
VIXFixLength = input.int(20, title='VixFix Length', minval=1)
dt=Expiry
x2 = 2
hv1 = VIXFixLength // Expiry
LogReturn = math.log(spot[0] / spot[1])
//Average = ta.sma(LogReturn, Expiry)
STDEV = ta.stdev(LogReturn, hv1)
v1 = STDEV * math.sqrt(365)
t = math.sqrt(dt/365)
//Time_Average = Expiry * Average
//Time_STDEV = STDEV * math.sqrt(Expiry)
b3 = math.exp(v1*t*x2)*spot[0] // 2nd Target is ... Future Price Above Close
b4 = math.exp(v1*t*-x2)*spot[0] // 2nd Target is... Future Price Below Close
// Target up //
TU2 = b3
// Target Down //
TD2 = b4
// Ploting Area
HH = ta.highest(high, 100)
LL = ta.lowest(low, 100)
plot(TU2,"TU2",color=color.blue, linewidth = 2)
plot(TD2,"TD2",color=color.red, linewidth = 2)
//---------------------------------------------------------------------
On Chart plot
Means at lower low will plot a line for TU2 upper tgt and for higher high will plot a line for TD2 lower levels. Getting confused in floting arrays, how they call for previous prices and plot on chart. Currently ploting for all bars.
My code with simple calculations with Impliedvolatility, but stucked in ploting them.
Please help me out , how to plot my levels on HH and LL levels only.

Related

magnitude squared coherence in matlab

I am tring to get magnitud squared coherence (MSC) and I am finding some problems.
In theory, the MSC is the result of the crospectra of two signals, devided by the autospectra of each signal.
Therefore, this is my code:
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sampling period
L = length(myData(1,:)); % length of segment
Hz = Fs*(0:(L/2))/L; % frequency vector
dat1 = fft(myData(1,:));
dat2 = fft(myData(2,:));
pow1 = dat1.*conj(dat1); % autospectra signal 1
pow2 = dat2.*conj(dat2); % autospectra signal 2
cpow = abs(dat1.*conj(dat2)).^2; % crosspectra
coh = cpow./(pow1.*pow2); % getting the coherence
coherence = coh(1:L/2+1);
coherence(2:end-1) = coherence(2:end-1); % adjusting length to Nyquest freq
figure;
plot(Hz,coherence)
but the result are only "1" and it does not make much seance, so there must be I mistake but I just can't find it.
Thanks for your help

What's wrong with my Euclidean Distance Calculation? (Julia)

I'm trying to compute the Perceptually Important Points by using three different methods.
Euclidean Distance;
Perpendicular Distance;
Vertical Distance.
Method 2 and 3 gives me the same Point, but Euclidean distance not. Can't find the mistake I made. Hope someone can help me.
pt = 7.6 #pt
_t = 1 #t
ptT = 10.7 #p(t+T)
_T = 253 #t+T
# Distances
dE = Float64[] #Euclidean Distances
dP = Float64[] #Perpendicular Distances
dV = Float64[] #Vertical Distances
xi = Float64[] #x values
for i in 2:length(stockdf[:Price])-1
_de = sqrt((_t - i)^2 + (pt - stockdf[:Price][i])^2) + sqrt((_T - i)^2 + (ptT - stockdf[:Price][i])^2)
push!(dE,_de)
_dP = abs(_s*i+_c-stockdf[:Price][i])/sqrt(_s^2+1)
push!(dP,_dP)
_dV = abs(_s*i+_c-stockdf[:Price][i])
push!(dV,_dV)
push!(xi,i)
end
Both method 2 and 3 give me the max point indexed at 153, but method 1 gives me a point, which is not the max point and is indexed at 230.
Formula for the 3rd PIP with Euclidean Distance is:
dE = sqrt((t-i)^2 + (pt-pi)^2) + sqrt((t+T-i)^2+(pt+T-pi)^2)
EDIT:
For a better understanding I reproduced the code with other variables which you can test for yourself.
xs = Array(1:10)
ys = rand(1:1:10,10)
dde = Float64[]
ddP = Float64[]
ddV = Float64[]
xxi = Float64[]
# Connecting Line of first 2 PIPs
_ss = (ys[end]-ys[1])/10
_cc = ys[1]-(1*(ys[end]-ys[1]))/10
_zz = Float64[]
for i in 1:length(dedf[:Price])
push!(_zz,_ss*i+_cc)
end
for i in 2:length(xs)-1
_dde = sqrt((1-i)^2+(ys[1]-ys[i])) + sqrt((10-i)^2 + (ys[end]- ys[i])^2)
push!(dde,_dde)
_ddP = abs(_ss*i+_cc-ys[i])/sqrt(_ss^2+1)
push!(ddP,_ddP)
_ddV = abs(_ss*i+_cc-ys[i])
push!(ddV,_ddV)
push!(xxi,i)
end
println(dde)
for i in 1:length(dde)
if ddV[i] == maximum(ddV)
println(i)
end
end
For Euclidean Distance I get index 7
for Perpendicular and Vertical Distance I get index 5. Look at the graphs
Euclidean Distance on graph
Perpendicular Distance on graph
EDIT:
I'm working through a book about pattern recognition in financial time series. Now I downloaded the same data, which the book used and the now the results are the same. All of the 3 methods gave me the same index. But with different data sets, method 1 differs from 2 and 3. I don't know why.

Flat top Pulse Amplitude Modulation

i want to plot flat-topped PAM of sinusoid. wave using matlab.
the sinusoidal signal has frequency = 10^4/(2*pi) HZ and sampling frequency = 8 kHZ. pulse duration T = 50 microseconds.
i wrote code for natural sampling, so how to do flat-top?
clear all;
close all;
Fs = 1e9;
t = 0:1/Fs:(0.2e-2);
fc = 8000; %sampling frequency
fm = 10^4/(2*pi); %message frequency
a = 1;
vm = a.*sin(2*pi*fm*t); %message
pulseperiods = [0:10]*1/fc;
pulsewidth = 50e-6;
vc = pulstran(t,pulseperiods,#rectpuls,pulsewidth);
y = vc.*vm;
figure
subplot(3,1,1);
plot(t,vm); % plot message
xlabel('Temps');
ylabel('Amplitude');
title('Message');
subplot(3,1,2);
plot(t,vc); % plot pulse
xlabel('Temps');
ylabel('Amplitude');
title('Switching waveform');
subplot(3,1,3);
plot(t,y); % plot PAM naturel
xlabel('Temps');
ylabel('Amplitude');
title('PAM naturel');
The flat-top PAM means the instantaneous sampling, i.e. the message signal is sampled only once per period, so modulated signal does not change its value until returning to zero and next sampling period. The sampling takes place at rising edge of carrier signal, so the solution is quite straightforward: by adding the for loop to your code:
for i = 2:length(t)
if vc(i) == 1 && vc(i-1) == 0 %if the rising edge is detected
y1(i) = vc(i) * vm(i); %sampling occurs
elseif vc(i) == 1 && vc(i-1) == 1 %and while the carrier signal is 1
y1(i) = y1(i-1); %the value of y1 remains constant
else
y1(i) = 0; %otherwise, y is zero
end
end
plot(t,y1); % flat-top PAM plot
xlabel('Temps');
ylabel('Amplitude');
title('PAM flat-top');
you get

Plotting evolution of 2D vector in 3D as a ribbon in MATLAB

I would like to plot how the amplitude and orientation of a 2D vector evolves over time. To do this I would like to create a graph reminiscent of the canonical E & B field graphs you may recall from an introductory electricity and magnetism class.
Specifically, I would like to connect my 2D vector points with a ribbon, so that they are easy to see. Is there a simple way to do this in MATLAB? quiver3 is pretty close, but it lacks the ribbon. Perhaps some sort of parametric surface?
You can use the plotting functions FILL3 and QUIVER3 to do something like this:
x = linspace(0,4*pi,30); %# Create some x data
y1 = sin(x); %# Create wave 1
y2 = sin(x-pi); %# Create wave 2
u = zeros(size(x)); %# Create a vector of zeroes
hRibbon1 = fill3(x,y1,u,'r'); %# Plot wave 1 and fill underneath with color
set(hRibbon1,'EdgeColor','r',... %# Change the edge color and
'FaceAlpha',0.5); %# make the colored patch transparent
hold on; %# Add to the existing plot
quiver3(x,u,u,u,y1,u,0,'r'); %# Plot the arrows
hRibbon2 = fill3(x,u,y2,'b'); %# Plot wave 2 and fill underneath with color
set(hRibbon2,'EdgeColor','b',... %# Change the edge color and
'FaceAlpha',0.5); %# make the colored patch transparent
quiver3(x,u,u,u,u,y2,0,'b'); %# Plot the arrows
axis equal; %# Use equal axis scaling
And here's the resulting plot:
here's a solution that draws a ribbon between any two lines in 3D space. you can plot your quiver over it & adjust the opacity using 'FaceAlpha' as in gnovice's solution
To make the function clearer, I am first posting it without error-checking and resizing functions (which make up most of the body of the function & aren't particularly interesting)
function h = filledRibbon (x,y,z,u,v,w,c, varargin)
%function filledRibbon (x,y,z,u,v,w,c, varargin)
%
%plots a ribbon spanning the area between the lines x,y,z and x+u,y+v,z+w
%in the color c
%varargin is passed directly to patch
%returns a handle to the patch graphic created
%make up a set of regions that span the space between the lines
xr = [x(1:end-1); x(1:end-1) + u(1:end-1); x(2:end) + u(2:end); x(2:end)];
yr = [y(1:end-1); y(1:end-1) + v(1:end-1); y(2:end) + v(2:end); y(2:end)];
zr = [z(1:end-1); z(1:end-1) + w(1:end-1); z(2:end) + w(2:end); z(2:end)];
%plot the regions with no edges
h = patch(xr,yr,zr,c, 'LineStyle','none', varargin{:});
use this error-checking version in your actual code:
function h = filledRibbon (x,y,z,u,v,w,c, varargin)
%function filledRibbon (x,y,z,u,v,w,c, varargin)
%
%plots a ribbon spanning the area between the lines x,y,z and x+u,y+v,z+w
%in the color c
%varargin is passed directly to patch
%returns a handle to the patch graphic created
if ~exist('w', 'var') || isempty(w)
w = 0;
end
if ~exist('u', 'var') || isempty(u)
u = 0;
end
if ~exist('v', 'var') || isempty(v)
v = 0;
end
if ~exist('c', 'var') || isempty(c)
c = 'b';
end
%make all vectors 1xN
x = reshape(x,1,[]);
y = reshape(y,1,[]);
z = reshape(z,1,[]);
%if any offsets are scalar, expand to a vector
if all(size(u) == 1)
u = repmat(u, size(x));
end
if all(size(v) == 1)
v = repmat(v, size(x));
end
if all(size(w) == 1)
w = repmat(w, size(x));
end
%make up a set of regions that span the space between the lines
xr = [x(1:end-1); x(1:end-1) + u(1:end-1); x(2:end) + u(2:end); x(2:end)];
yr = [y(1:end-1); y(1:end-1) + v(1:end-1); y(2:end) + v(2:end); y(2:end)];
zr = [z(1:end-1); z(1:end-1) + w(1:end-1); z(2:end) + w(2:end); z(2:end)];
%plot the regions with no edges
h = patch(xr,yr,zr,c, 'LineStyle','none', varargin{:});

How to generate a lower frequency version of a signal in Matlab?

With a sine input, I tried to modify it's frequency cutting some lower frequencies in the spectrum, shifting the main frequency towards zero. As the signal is not fftshifted I tried to do that by eliminating some samples at the begin and at the end of the fft vector:
interval = 1;
samplingFrequency = 44100;
signalFrequency = 440;
sampleDuration = 1 / samplingFrequency;
timespan = 1 : sampleDuration : (1 + interval);
original = sin(2 * pi * signalFrequency * timespan);
fourierTransform = fft(original);
frequencyCut = 10; %% Hertz
frequencyCut = floor(frequencyCut * (length(pattern) / samplingFrequency) / 4); %% Samples
maxFrequency = length(fourierTransform) - (2 * frequencyCut);
signal = ifft(fourierTransform(frequencyCut + 1:maxFrequency), 'symmetric');
But it didn't work as expected. I also tried to remove the center part of the spectrum, but it wielded a higher frequency sine wave too.
How to make it right?
#las3rjock:
its more like downsampling the signal itself, not the FFT..
Take a look at downsample.
Or you could create a timeseries object, and resample it using the resample method.
EDIT:
a similar example :)
% generate a signal
Fs = 200;
f = 5;
t = 0:1/Fs:1-1/Fs;
y = sin(2*pi * f * t) + sin(2*pi * 2*f * t) + 0.3*randn(size(t));
% downsample
n = 2;
yy = downsample([t' y'], n);
% plot
subplot(211), plot(t,y), axis([0 1 -2 2])
subplot(212), plot(yy(:,1), yy(:,2)), axis([0 1 -2 2])
A crude way to downsample your spectrum by a factor of n would be
% downsample by a factor of 2
n = 2; % downsampling factor
newSpectrum = fourierTransform(1:n:end);
For this to be a lower-frequency signal on your original time axis, you will need to zero-pad this vector up to the original length on both the positive and negative ends. This will be made much simpler using fftshift:
pad = length(fourierTransform);
fourierTransform = [zeros(1,pad/4) fftshift(newSpectrum) zeros(1,pad/4)];
To recover the downshifted signal, you fftshift back before applying the inverse transform:
signal = ifft(fftshift(fourierTransform));
EDIT: Here is a complete script which generates a plot comparing the original and downshifted signal:
% generate original signal
interval = 1;
samplingFrequency = 44100;
signalFrequency = 440;
sampleDuration = 1 / samplingFrequency;
timespan = 1 : sampleDuration : (1 + interval);
original = sin(2 * pi * signalFrequency * timespan);
% plot original signal
subplot(211)
plot(timespan(1:1000),original(1:1000))
title('Original signal')
fourierTransform = fft(original)/length(original);
% downsample spectrum by a factor of 2
n = 2; % downsampling factor
newSpectrum = fourierTransform(1:n:end);
% zero-pad the positive and negative ends of the spectrum
pad = floor(length(fourierTransform)/4);
fourierTransform = [zeros(1,pad) fftshift(newSpectrum) zeros(1,pad)];
% inverse transform
signal = ifft(length(original)*fftshift(fourierTransform),'symmetric');
% plot the downshifted signal
subplot(212)
plot(timespan(1:1000),signal(1:1000))
title('Shifted signal')
Plot of original and downshifted signals http://img5.imageshack.us/img5/5426/downshift.png

Resources