-
Notifications
You must be signed in to change notification settings - Fork 0
/
indicators.m
1475 lines (1239 loc) · 52.2 KB
/
indicators.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function vout = indicators(vin,mode,varargin)
%INDICATORS calculates various technical indicators
%
% Description
% INDICATORS is a technical analysis tool that calculates various
% technical indicators. Technical analysis is the forecasting of
% future financial price movements based on an examination of past
% price movements. Most technical indicators require at least 1
% variable argument. If these arguments are not supplied, default
% values are used.
%
% Syntax
% Momentum
% cci = indicators([hi,lo,cl] ,'cci' ,tp_per,md_per,const)
% roc = indicators(price ,'roc' ,period)
% rsi = indicators(price ,'rsi' ,period)
% [fpctk,fpctd] = indicators([hi,lo,cl] ,'fsto' ,k,d)
% [spctk,spctd] = indicators([hi,lo,cl] ,'ssto' ,k,d)
% [fpctk,fpctd,jline] = indicators([hi,lo,cl] ,'kdj' ,k,d)
% willr = indicators([hi,lo,cl] ,'william',period)
% [dn,up,os] = indicators([hi,lo] ,'aroon' ,period)
% tsi = indicators(cl ,'tsi' ,r,s)
% Trend
% sma = indicators(price ,'sma' ,period)
% ema = indicators(price ,'ema' ,period)
% [macd,signal,macdh] = indicators(cl ,'macd' ,short,long,signal)
% [pdi,mdi,adx] = indicators([hi,lo,cl] ,'adx' ,period)
% t3 = indicators(price ,'t3' ,period,volfact)
% Volume
% obv = indicators([cl,vo] ,'obv')
% cmf = indicators([hi,lo,cl,vo] ,'cmf' ,period)
% force = indicators([cl,vo] ,'force' ,period)
% mfi = indicators([hi,lo,cl,vo] ,'mfi' ,period)
% Volatility
% [middle,upper,lower] = indicators(price ,'boll' ,period,weight,nstd)
% [middle,upper,lower] = indicators([hi,lo,cl] ,'keltner',emaper,atrmul,atrper)
% atr = indicators([hi,lo,cl] ,'atr' ,period)
% vr = indicators([hi,lo,cl] ,'vr' ,period)
% hhll = indicators([hi,lo] ,'hhll' ,period)
% Other
% [index,value] = indicators(price ,'zigzag' ,moveper)
% change = indicators(price ,'compare')
% [pivot sprt res] = indicators([dt,op,hi,lo,cl],'pivot' ,type)
% sar = indicators([hi,lo] ,'sar' ,step,maximum)
%
% Arguments
% Outputs
% cci/roc/rsi/willr/tsi/sma/ema/t3/obv/cmf/force/mfi/atr/change/sar/vr/hhll
% - single output vector
% macd/signal/macdh
% - moving average convergence divergence vector/
% signal line/ macd histogram
% middle/upper/lower
% - middle/upper/lower band for bollinger bands or keltner
% channels
% fpctk/fpctd/spctk/spctd/jline
% - fast/slow percent k/d and the J Line
% index/value
% - index and value for each point in zigzag
% pivot/sprt/res
% - vectors for pivot point, support lines, resistance
% lines
% dn/up/os
% - aroon down/aroon up/aroon oscillator
% Inputs
% price - any price vector (e.g. open, high, ...)
% dt/op/hi/lo/cl/vo
% - matlab serial date, open/high/low/close price, and volume of data
% Mode
% Momentum
% cci - Commodity Channel Index
% roc - Rate of Change
% rsi - Relative Strength Index
% fsto - Fast Stochastic Oscillator
% ssto - Slow Stochastic Oscillator
% kdj - KDJ Indicator
% william - William's %R
% aroon - Aroon
% tsi - True Strength Index
% Trend
% sma - Simple Moving Average
% ema - Exponential Moving Average
% macd - Moving Average Convergence Divergence
% adx - Wildmer's DMI (ADX)
% t3 - Triple EMA (Not the same as EMA3)
% Volume
% obv - On-Balance Volume
% cmf - Chaikin Money Flow
% force - Force Index
% mfi - Money Flow Index
% Volatility
% boll - Bollinger Bands
% keltner - Keltner Channels
% atr - Average True Range
% vr - Volatility Ratio
% hhll - Highest High, Lowest Low
% Other
% zigzag - ZigZag
% compare - relative price compared to first input
% pivot - Pivot Points
% sar - Parabolic SAR (Stop And Reverse)
%
% Variable Arguments
% period - number of periods over which to make calculations
% short/long/signal
% - number of periods for short/long/signal for macd
% period/weight/nstd
% - number of periods/weight factor/number of standard
% deviations
% k/d/j - number of periods for %K/%D/JLine
% r/s - number of periods for momentum/smoothed momentum
% emaper/atrmul/atrper
% - number of periods for ema/atr multiplier/number of
% periods for atr for keltner
% tp_per/md_per/const
% - number of periods for true price/number of periods for
% mean deviation/constant for cci
% moveper - movement percent for zigzag
% type - string for pivot point method pick one of 's', 'f', 'd'
% which stand for 'standard', 'fibonacci', 'demark'
% step/maximum
% - value to add to acceleration factor at each increment
% maximum value acceleration factor can reach
% volfact - volume factor for t3
%
% Notes
% - there are no argument checks
% - all prices must be column oriented
% - the parabolic sar indicator is not completely correct
% - if there is a tie between price points, the aroon indicator uses
% the one farthest back
% - 2 methods are available to calculate the ema for the tsi
% indicator. Simply uncomment whichever one is desired.
% - the t3 indicator uses a different ema than ta-lib
% - 3 methods are available to calculate the kdj. Simply uncomment
% whichever one is desired.
%
% Example
% load disney.mat
% vout = indicators([dis_HIGH,dis_LOW,dis_CLOSE],'fsto',14,3);
% fpctk = vout(:,1);
% fpctd = vout(:,2);
% plot(1:length(fpctk),fpctk,'b',1:length(fpctd),fpctd,'g')
% title('Fast Stochastics for Disney')
%
% Further Information
% For an in depth analysis of how many of these technical indicators
% work, refer to one of the following websites or Google it.
% http://stockcharts.com/
% http://www.investopedia.com/
% http://www.ta-lib.org/
%
% Version : 1.1.3 (05/24/2013)
% Author : Nate Jensen
% Created : 10/10/2011
% History :
% - v1.0 10/25/2011 : initial release of 21 indicators
% - v1.1 03/04/2012 : 23 indicators, fixed date conversion issue
% - v1.1.1 03/25/2012 : 24 indicators
% - v1.1.2 03/21/2013 : 25 indicators
% - v1.1.3 05/24/2013 : 27 indicators, bug fixes
% To Do
% - add more indicators
%%% Main Function
% Initialize output vector
vout = [];
% Number of observations
observ = size(vin,1);
% Switch between the various modes
switch lower(mode)
%%% Momentum
%==========================================================================
case 'cci' % Commodity Channel Index
% Input Data
hi = vin(:,1);
lo = vin(:,2);
cl = vin(:,3);
% Variable Argument Input
if isempty(varargin)
tp_per = 20;
md_per = 20;
const = 0.015;
else
tp_per = varargin{1};
md_per = varargin{2};
const = varargin{3};
end
% Typical Price
tp = (hi+lo+cl)/3;
% Simple moving average of typical price
smatp = sma(tp,tp_per,observ);
% Sum of the mean absolute deviation
smad = nan(observ,1);
cci = smad; % preallocate cci
for i1 = md_per:observ
smad(i1) = sum(abs(smatp(i1)-tp(i1-md_per+1:i1)));
end
% Commodity Channel Index
i1 = md_per:observ;
cci(i1) = (tp(i1)-smatp(i1))./(const*smad(i1)/md_per);
% Format Output
vout = cci;
case 'roc' % Rate of Change
% Input Data
cl = vin;
% Variable Argument Input
if isempty(varargin)
period = 12;
else
period = varargin{1};
end
% Rate of Change
roc = nan(observ,1);
% calculate rate of change
roc(period+1:observ) = ((cl(period+1:observ)- ...
cl(1:observ-period))./cl(1:observ-period))*100;
% Format Output
vout = roc;
case 'rsi' % Relative Strength Index
% Input Data
cl = vin;
% Variable Argument Input
if isempty(varargin)
period = 14;
else
period = varargin{1};
end
% Determine how many nans are in the beginning
nanVals = isnan(cl);
firstVal = find(nanVals == 0, 1, 'first');
numLeadNans = firstVal - 1;
% Create vector of non-nan closing prices
nnanvin = cl(~isnan(cl));
% Take a diff of the non-nan closing prices
diffdata = diff(nnanvin);
priceChange = abs(diffdata);
% Create '+' Delta vectors and '-' Delta vectors
advances = priceChange;
declines = priceChange;
advances(diffdata < 0) = 0;
declines(diffdata >= 0) = 0;
% Calculate the RSI of the non-nan closing prices. Ignore first non-nan
% vin b/c it is a reference point. Take into account any leading nans
% that may exist in vin vector.
trsi = nan(size(diffdata, 1)-numLeadNans, 1);
for i1 = period:size(diffdata, 1)
% Gains/losses
totalGain = sum(advances((i1 - (period-1)):i1));
totalLoss = sum(declines((i1 - (period-1)):i1));
% Calculate RSI
rs = totalGain ./ totalLoss;
trsi(i1) = 100 - (100 / (1+rs));
end
% Pre allocate vector taking into account reference value and leading nans.
% length of vector = length(vin) - # of reference values - # of leading nans
rsi = nan(size(cl, 1)-1-numLeadNans, 1);
% Populate RSI
rsi(~isnan(cl(2+numLeadNans:end))) = trsi;
% Format Output
vout = [nan(numLeadNans+1, 1); rsi];
case 'fsto' % Fast Stochastic Oscillator
% Input Data
hi = vin(:,1);
lo = vin(:,2);
cl = vin(:,3);
% Variable Argument Input
if isempty(varargin)
kperiods = 14;
dperiods = 3;
else
kperiods = varargin{1};
dperiods = varargin{2};
end
% Fast %K
fpctk = nan(observ,1); % preallocate Fast %K
llv = zeros(observ,1); % preallocate lowest low
llv(1:kperiods) = min(lo(1:kperiods)); % lowest low of first kperiods
for i1 = kperiods:observ % cycle through rest of data
llv(i1) = min(lo(i1-kperiods+1:i1)); % lowest low of previous kperiods
end
hhv = zeros(observ,1); % preallocate highest high
hhv(1:kperiods) = max(hi(1:kperiods)); % highest high of first kperiods
for i1 = kperiods:observ % cycle through rest of data
hhv(i1) = max(hi(i1-kperiods+1:i1)); % highest high of previous kperiods
end
nzero = find((hhv-llv) ~= 0);
fpctk(nzero) = ((cl(nzero)-llv(nzero))./(hhv(nzero)-llv(nzero)))*100;
% Fast %D
fpctd = nan(size(cl));
fpctd(~isnan(fpctk)) = ema(fpctk(~isnan(fpctk)),dperiods, ...
length(fpctk(~isnan(fpctk))));
% Format Output
vout = [fpctk,fpctd];
case 'ssto' % Slow Stochastic Oscillator
% Input data
hi = vin(:,1);
lo = vin(:,2);
cl = vin(:,3);
% Variable Argument Input
if isempty(varargin)
kperiods = 14;
dperiods = 3;
else
kperiods = varargin{1};
dperiods = varargin{2};
end
% Fast %K
fpctk = nan(observ,1); % preallocate Fast %K
llv = zeros(observ,1); % preallocate lowest low
llv(1:kperiods) = min(lo(1:kperiods)); % lowest low of first kperiods
for i1 = kperiods:observ % cycle through rest of data
llv(i1) = min(lo(i1-kperiods+1:i1)); % lowest low of previous kperiods
end
hhv = zeros(observ,1); % preallocate highest high
hhv(1:kperiods) = max(hi(1:kperiods)); % highest high of first kperiods
for i1 = kperiods:observ % cycle through rest of data
hhv(i1) = max(hi(i1-kperiods+1:i1)); % highest high of previous kperiods
end
nzero = find((hhv-llv) ~= 0);
fpctk(nzero) = ((cl(nzero)-llv(nzero))./(hhv(nzero)-llv(nzero)))*100;
% Fast %D
fpctd = nan(size(cl));
fpctd(~isnan(fpctk)) = ema(fpctk(~isnan(fpctk)),dperiods, ...
length(fpctk(~isnan(fpctk))));
% Slow %K
spctk = fpctd;
% Slow %D
spctd = nan(size(cl));
spctd(~isnan(spctk)) = ema(spctk(~isnan(spctk)),dperiods, ...
length(spctk(~isnan(spctk))));
% Format Output
vout = [spctk,spctd];
case 'kdj' % KDJ Indicator
% Input Data
hi = vin(:,1);
lo = vin(:,2);
cl = vin(:,3);
% Variable Argument Input
if isempty(varargin)
kperiods = 14;
dperiods = 3;
% jperiods = 5;
else
kperiods = varargin{1};
dperiods = varargin{2};
% jperiods = varargin{3};
end
% Fast %K
fpctk = nan(observ,1); % preallocate Fast %K
llv = zeros(observ,1); % preallocate lowest low
llv(1:kperiods) = min(lo(1:kperiods)); % lowest low of first kperiods
for i1 = kperiods:observ % cycle through rest of data
llv(i1) = min(lo(i1-kperiods+1:i1)); % lowest low of previous kperiods
end
hhv = zeros(observ,1); % preallocate highest high
hhv(1:kperiods) = max(hi(1:kperiods)); % highest high of first kperiods
for i1 = kperiods:observ % cycle through rest of data
hhv(i1) = max(hi(i1-kperiods+1:i1)); % highest high of previous kperiods
end
nzero = find((hhv-llv) ~= 0);
fpctk(nzero) = ((cl(nzero)-llv(nzero))./(hhv(nzero)-llv(nzero)))*100;
% Fast %D
fpctd = nan(size(cl));
fpctd(~isnan(fpctk)) = ema(fpctk(~isnan(fpctk)),dperiods,observ);
% Method # 1:
jline = 3*fpctk-2*fpctd;
% Method # 2:
% jline = nan(size(cl));
% jline(~isnan(fpctk)) = ema(fpctk(~isnan(fpctk)),jperiods,observ);
% Method # 3:
% Slow %K
% spctk = fpctd;
% Slow %D
% spctd = nan(size(cl));
% spctd(~isnan(spctk)) = ema(spctk(~isnan(spctk)),dperiods,observ-dperiods+1);
% J Line
% jline = 3*spctk-2*spctd;
% Format Output
% vout = [spctk,spctd,jline];
% Format Output
vout = [fpctk,fpctd,jline];
case 'william' % William's %R
% Input Data
hi = vin(:,1);
lo = vin(:,2);
cl = vin(:,3);
% Variable Argument Input
if isempty(varargin)
period = 14;
else
period = varargin{1};
end
% Highest High and Lowest Low
llv = zeros(observ,1); % preallocate lowest low
llv(1:period) = min(lo(1:period)); % lowest low of first kperiods
for i1 = period:observ % cycle through rest of data
llv(i1) = min(lo(i1-period+1:i1)); % lowest low of previous kperiods
end
hhv = zeros(observ,1); % preallocate highest high
hhv(1:period) = max(hi(1:period)); % highest high of first kperiods
for i1 = period:observ % cycle through rest of data
hhv(i1) = max(hi(i1-period+1:i1)); % highest high of previous kperiods
end
% Williams %R
wpctr = nan(observ,1);
nzero = find((hhv-llv) ~= 0);
wpctr(nzero) = ((hhv(nzero)-cl(nzero))./(hhv(nzero)-llv(nzero))) * -100;
% Format output
vout = wpctr;
case 'aroon' % Aroon
% Input Data
hi = vin(:,1);
lo = vin(:,2);
% Variable Argument Input
if isempty(varargin)
period = 25;
else
period = varargin{1};
end
% Cumulative sum of end indices
% Output looks like:
% [1 16 31 46 61 76 91 ... ]
temp_var1 = cumsum([1;(period+1:observ)'-(1:observ-period)'+1]);
% Vector of moving indices
% Output looks like:
% [1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 ... ]
temp_var2 = ones(temp_var1(observ-period+1)-1,1);
temp_var2(temp_var1(1:observ-period)) = 1-period;
temp_var2(1) = 1;
temp_var2 = cumsum(temp_var2);
% Days since last n periods high/low
[~,min_idx] = min(lo(reshape(temp_var2,period+1,observ-period)),[],1);
[~,max_idx] = max(hi(reshape(temp_var2,period+1,observ-period)),[],1);
% Aroon Down/Up/Oscillator
aroon_dn = [nan(period,1); ((period-(period+1-min_idx'))/period)*100];
aroon_up = [nan(period,1); ((period-(period+1-max_idx'))/period)*100];
aroon_os = aroon_up-aroon_dn;
% Format Output
vout = [aroon_dn,aroon_up,aroon_os];
case 'tsi' % True Strength Index
% Input Data
cl = vin(:,1);
% Variable Argument Input
if isempty(varargin)
slow = 25;
fast = 13;
else
slow = varargin{1};
fast = varargin{2};
end
% If the lag is greater than or equal to the number of observations
if slow >= observ || fast >= observ
return
end
% Momentum
mtm = [0; (cl(2:end,1)) - cl(1:end-1,1)];
absmtm = abs(mtm);
% Calculate the exponential percentage
k1 = 2/(slow+1);
k2 = 2/(fast+1);
% Wikipedia method for calculating ema
% Preallocate
ema1 = zeros(observ,1);
ema2 = ema1;
ema3 = ema1;
ema4 = ema1;
% EMA's
for i1 = 2:observ
ema1(i1) = k1 * (mtm(i1)-ema1(i1-1)) + ema1(i1-1);
ema2(i1) = k2 * (ema1(i1)-ema2(i1-1)) + ema2(i1-1);
ema3(i1) = k1 * (absmtm(i1)-ema3(i1-1)) + ema3(i1-1);
ema4(i1) = k2 * (ema3(i1)-ema4(i1-1)) + ema4(i1-1);
end
% True Strength Index
tsi = 100*ema2./ema4;
% % Matlab method for calculating ema
% % Preallocate EMA's
% ema1 = nan(observ,1);
% ema2 = ema1;
% ema3 = ema1;
% ema4 = ema1;
%
% % Calculate the simple moving average for the first 'exp mov avg' value.
% ema1(slow) = sum(mtm(1:slow))/slow;
% ema3(slow) = sum(absmtm(1:slow))/slow;
%
% % K*vin; 1-k
% kvin1 = mtm(slow:observ) * k1;
% oneK1 = 1-k1;
% kvin3 = absmtm(slow:observ) * k1;
% oneK2 = 1-k2;
%
% % First period calculation
% ema1(slow) = kvin1(1) + (ema1(slow) * oneK1);
% ema3(slow) = kvin3(1) + (ema3(slow) * oneK1);
%
% % Remaining periods calculation
% for i1 = slow+1:observ
% ema1(i1) = kvin1(i1-slow+1) + (ema1(i1-1) * oneK1);
% ema3(i1) = kvin3(i1-slow+1) + (ema3(i1-1) * oneK1);
% end
%
% % Calculate the simple moving average for the first 'exp mov avg' value.
% ema2(slow+fast-1) = sum(ema1(slow:slow+fast-1))/fast;
% ema4(slow+fast-1) = sum(ema3(slow:slow+fast-1))/fast;
%
% % K*vin; 1-k
% kvin2 = ema1(slow+fast-1:observ) * k2;
% kvin4 = ema3(slow+fast-1:observ) * k2;
%
% % First period calculation
% ema2(slow+fast-1) = kvin2(1) + (ema2(slow+fast-1) * oneK2);
% ema4(slow+fast-1) = kvin4(1) + (ema4(slow+fast-1) * oneK2);
%
% % Remaining periods calculation
% for i1 = slow+fast:observ
% ema2(i1) = kvin2(i1-fast-slow+2) + (ema2(i1-1) * oneK2);
% ema4(i1) = kvin4(i1-fast-slow+2) + (ema4(i1-1) * oneK2);
% end
%
% % True Strength Index
% tsi = 100*ema2./ema4;
% Format Output
vout = tsi;
%--------------------------------------------------------------------------
%%% Trend
%==========================================================================
case 'sma' % Simple Moving Average
% Input Data
price = vin;
% Variable Argument Input
if isempty(varargin)
period = 20;
else
period = varargin{1};
end
% Simple Moving Average
simmovavg = sma(price,period,observ);
% Format Output
vout = simmovavg;
case 'ema' % Exponential Moving Average
% Input Data
price = vin;
% Variable Argument Input
if isempty(varargin)
period = 20;
else
period = varargin{1};
end
% Exponential Moving Average
expmovavg = ema(price,period,observ);
% Format Output
vout = expmovavg;
case 'macd' % Moving Average Convergence Divergence
% Input Data
cl = vin;
% Variable Argument Input
if isempty(varargin)
short = 12;
long = 26;
signal = 9;
else
short = varargin{1};
long = varargin{2};
signal = varargin{3};
end
% EMA of Long Period
[ema_lp status] = ema(cl,long,observ);
if ~status
return
end
% EMA of Short Period
ema_sp = ema(cl,short,observ);
% MACD
MACD = ema_sp-ema_lp;
% Signal
[signal status] = ema(MACD(~isnan(MACD)),signal,observ-long+1);
if ~status
return
end
signal = [nan(long-1,1);signal];
% MACD Histogram
MACD_h = MACD-signal;
% Format Output
vout = [MACD,signal,MACD_h];
case 'adx' % Wilder's DMI (ADX)
% Input Data
hi = vin(:,1);
lo = vin(:,2);
cl = vin(:,3);
% Variable argument input
if isempty(varargin)
period = 14;
else
period = varargin{1};
end
% True range
h_m_l = hi-lo; % high - low
h_m_c = [0;abs(hi(2:observ)-cl(1:observ-1))]; % abs(high - close)
l_m_c = [0;abs(lo(2:observ)-cl(1:observ-1))]; % abs(low - close)
tr = max([h_m_l,h_m_c,l_m_c],[],2); % true range
% Directional Movement
h_m_h = hi(2:observ)-hi(1:observ-1); % high - high
l_m_l = lo(1:observ-1)-lo(2:observ); % low - low
pdm1 = zeros(observ-1,1); % preallocate pdm1
max_h = max(h_m_h,0);
pdm1(h_m_h > l_m_l) = max_h(h_m_h > l_m_l); % plus
mdm1 = zeros(observ-1,1); % preallocate mdm1
max_l = max(l_m_l,0);
mdm1(l_m_l > h_m_h) = max_l(l_m_l > h_m_h); % minus
pdm1 = [nan;pdm1];
mdm1 = [nan;mdm1];
% Preallocate 14 period tr, pdm, mdm, adx
tr14 = nan(observ,1); % 14 period true range
pdm14 = tr14; % 14 period plus directional movement
mdm14 = tr14; % 14 period minus directional movement
adx = tr14; % average directional index
% Calculate tr14, pdm14, mdm14, pdi14, mdi14, dmx
tr14(period+1) = sum(tr(period+1-period+1:period+1));
pdm14(period+1) = sum(pdm1(period+1-period+1:period+1));
mdm14(period+1) = sum(mdm1(period+1-period+1:period+1));
for i1 = period+2:observ
tr14(i1) = tr14(i1-1)-tr14(i1-1)/period+tr(i1);
pdm14(i1) = pdm14(i1-1)-pdm14(i1-1)/period+pdm1(i1);
mdm14(i1) = mdm14(i1-1)-mdm14(i1-1)/period+mdm1(i1);
end
pdi14 = 100*pdm14./tr14; % 14 period plus directional indicator
mdi14 = 100*mdm14./tr14; % 14 period minus directional indicator
dmx = 100*abs(pdi14-mdi14)./(pdi14+mdi14);% directional movement index
% Average Directional Index
adx(2*period) = sum(dmx(period+1:2*period))/(2*period-period-1);
for i1 = 2*period+1:observ
adx(i1) = (adx(i1-1)*(period-1)+dmx(i1))/period;
end
% Format Output
vout = [pdi14,mdi14,adx];
case 't3' % T3
% Input Data
price = vin;
% Variable Argument Input
if isempty(varargin)
period = 5;
volfact = 0.7;
else
period = varargin{1};
volfact = varargin{2};
end
% EMA
ema1 = ema(price,period,observ);
ema2 = [nan(period,1); ema(ema1(~isnan(ema1)),period,observ-period+1)];
ema3 = [nan(2*period-1,1); ema(ema2(~isnan(ema2)),period,observ-2*period+1)];
ema4 = [nan(3*period-1,1); ema(ema3(~isnan(ema3)),period,observ-3*period+1)];
ema5 = [nan(4*period-1,1); ema(ema4(~isnan(ema4)),period,observ-4*period+1)];
ema6 = [nan(5*period-1,1); ema(ema5(~isnan(ema5)),period,observ-5*period+1)];
% Constants
c1 = -(volfact*volfact*volfact);
c2 = 3*(volfact*volfact-c1);
c3 = -6*volfact*volfact-3*(volfact-c1);
c4 = 1+3*volfact-c1+3*volfact*volfact;
% T3
t3 = c1*ema6+c2*ema5+c3*ema4+c4*ema3;
% Format Output
vout = t3;
%--------------------------------------------------------------------------
%%% Volume
%==========================================================================
case 'obv' % On-Balance Volume
% Input data
cl = vin(:,1);
vo = vin(:,2);
% On-Balance Volume
obv = vo;
for i1 = 2:observ
if cl(i1) > cl(i1-1)
obv(i1) = obv(i1-1)+vo(i1);
elseif cl(i1) < cl(i1-1)
obv(i1) = obv(i1-1)-vo(i1);
elseif cl(i1) == cl(i1-1)
obv(i1) = obv(i1-1);
end
end
% Format Output
vout = obv;
case 'cmf' % Chaikin Money Flow
% Input Data
hi = vin(:,1);
lo = vin(:,2);
cl = vin(:,3);
vo = vin(:,4);
% Variable Argument Input
if isempty(varargin)
period = 20;
else
period = varargin{1};
end
% Money Flow Multiplier
mfm = ((cl-lo)-(hi-cl))/(hi-lo);
% Money Flow Volume
mfv = mfm*vo;
% Chaikin Money Flow
cmf = nan(observ,1);
for i1 = period:observ
cmf(i1) = sum(mfv(i1-period+1:i1))/sum(vo(i1-period+1:i1));
end
% Format Output
vout = cmf;
case 'force' % Force Index
% Input Data
cl = vin(:,1);
vo = vin(:,2);
% Variable Argument Input
if isempty(varargin)
period = 13;
else
period = varargin{1};
end
% Force Index
force = [nan; (cl(2:observ)-cl(1:observ-1)).*vo(2:observ)];
force = [nan; ema(force(2:observ),period,observ-1)];
% Format Output
vout = force;
case 'mfi' % Money Flow Index
% Input Data
% Input Data
hi = vin(:,1);
lo = vin(:,2);
cl = vin(:,3);
vo = vin(:,4);
if isempty(varargin)
period = 14;
else
period = varargin{1};
end
% Typical Price
tp = (hi+lo+cl)/3;
% Up or Down
upordn = ones(observ-1,1);
upordn(tp(2:observ) <= tp(1:observ-1)) = -1;
% Raw Money Flow
rmf = tp(2:observ).*vo(2:observ);
% Positive Money Flow
pmf = zeros(observ-1,1);
pmf(upordn == 1) = rmf(upordn == 1);
% Negative Money Flow
nmf = zeros(observ-1,1);
nmf(upordn == -1) = rmf(upordn == -1);
% Cumulative sum of end indices
% Output looks like:
% [1 16 31 46 61 76 91 ... ]
temp_var1 = cumsum([1;(period:observ-1)'-(1:observ-period)'+1]);
% Vector of moving indices
% Output looks like:
% [1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 ... ]
temp_var2 = ones(temp_var1(observ-period+1)-1,1);
temp_var2(temp_var1(1:observ-period)) = 2-period;
temp_var2(1) = 1;
temp_var2 = cumsum(temp_var2);
% Money Flow Ratio
mfr = sum(pmf(reshape(temp_var2,period,observ-period)),1)'./ ...
sum(nmf(reshape(temp_var2,period,observ-period)),1)';
mfr = [nan(period,1); mfr];
% Money Flow Index
mfi = 100-100./(1+mfr);
% Format Output
vout = mfi;
%--------------------------------------------------------------------------
%%% Volatility
%==========================================================================
case 'boll' % Bollinger Bands
% Input data
cl = vin;
% Variable argument input
if isempty(varargin)
period = 20;
weight = 0;
nstd = 2;
else
period = varargin{1};
weight = varargin{2};
nstd = varargin{3};
end
% Create output vectors.
mid = nan(size(cl, 1), 1);
uppr = mid;
lowr = mid;
% Create weight vector.
wtsvec = ((1:period).^weight) ./ (sum((1:period).^weight));
% Save the original data and remove NaN's from the data to be processed.
nnandata = cl(~isnan(cl));
% Calculate middle band moving average using convolution.
cmid = conv(nnandata, wtsvec);
nnanmid = cmid(period:length(nnandata));
% Calculate shift for the upper and lower bands. The shift is a
% moving standard deviation of the data.
mstd = nnandata(period:end); % Pre-allocate
for i1 = period:length(nnandata)
mstd(i1-period+1, :) = std(nnandata(i1-period+1:i1));
end
% Calculate the upper and lower bands.
nnanuppr = nnanmid + nstd.*mstd;
nnanlowr = nnanmid - nstd.*mstd;
% Return the values.
nanVec = nan(period-1,1);
mid(~isnan(cl)) = [nanVec; nnanmid];
uppr(~isnan(cl)) = [nanVec; nnanuppr];
lowr(~isnan(cl)) = [nanVec; nnanlowr];
% Format output
vout = [mid,uppr,lowr];
case 'keltner' % Keltner Channels
% Input data
hi = vin(:,1);
lo = vin(:,2);
cl = vin(:,3);
% Variable argument input
if isempty(varargin)
emaper = 20;
atrmul = 2;
atrper = 10;
else
emaper = varargin{1};
atrmul = varargin{2};
atrper = varargin{3};
end
% True range
h_m_l = hi-lo; % high - low
h_m_c = [0;abs(hi(2:observ)-cl(1:observ-1))]; % abs(high - close)
l_m_c = [0;abs(lo(2:observ)-cl(1:observ-1))]; % abs(low - close)
tr = max([h_m_l,h_m_c,l_m_c],[],2); % true range
% Average true range
atr = ema(tr,atrper,observ);
% Middle/Upper/Lower bands of keltner channels
midd = ema(cl,emaper,observ);
uppr = midd+atrmul*atr;
lowr = midd-atrmul*atr;
% Format output
vout = [midd,uppr,lowr];
case 'atr' % Average True Range
% Input data
hi = vin(:,1);
lo = vin(:,2);
cl = vin(:,3);
% Variable argument input
if isempty(varargin)
period = 20;
else
period = varargin{1};
end
% True range
h_m_l = hi-lo; % high - low
h_m_c = [0;abs(hi(2:observ)-cl(1:observ-1))]; % abs(high - close)
l_m_c = [0;abs(lo(2:observ)-cl(1:observ-1))]; % abs(low - close)