File: runit.TechnicalAnalysis.R

package info (click to toggle)
ftrading 3042.79-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 200 kB
  • sloc: makefile: 14
file content (542 lines) | stat: -rw-r--r-- 13,258 bytes parent folder | download | duplicates (6)
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

# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU Library General
# Public License along with this library; if not, write to the
# Free Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA  02111-1307  USA

# Copyrights (C)
# for this R-port:
#   1999 - 2007, Diethelm Wuertz, GPL
#   Diethelm Wuertz <wuertz@itp.phys.ethz.ch>
#   info@rmetrics.org
#   www.rmetrics.org
# for the code accessed (or partly included) from other R-ports:
#   see R's copyright and license files
# for the code accessed (or partly included) from contributed R-ports
# and other sources
#   see Rmetrics's copyright file


################################################################################
# FUNCTION:                 UTILITY FUNCTIONS:
#  emaTA                     Exponential Moving Average
#  biasTA                    EMA-Bias
#  medpriceTA                Median Price
#  typicalpriceTA            Typical Price
#  wcloseTA                  Weighted Close Price
#  rocTA                     Rate of Change
#  oscTA                     EMA-Oscillator
# FUNCTION:                 OSCILLATOR INDICATORS:
#  momTA                     Momentum
#  macdTA                    MACD
#  cdsTA                     MACD Signal Line
#  cdoTA                     MACD Oscillator
#  vohlTA                    High/Low Volatility
#  vorTA                     Volatility Ratio
# FUNCTION:                 STOCHASTICS INDICATORS:
#  stochasticTA              Stochastics %K/%D, fast/slow
#  fpkTA                     Fast Percent %K
#  fpdTA                     Fast Percent %D
#  spdTA                     Slow Percent %D
#  apdTA                     Averaged Percent %D
#  wprTA                     Williams Percent %R
#  rsiTA                     Relative Strength Index
# FUNCTION:                 DESCRIPTION - MORE INDICATORS:
#  accelTA                   Acceleration
#  adiTA                     AD Indicator
#  adoscillatorTA            AD Oscillator
#  bollingerTA               Bollinger Bands
#  chaikinoTA                Chaikin Oscillator
#  chaikinvTA                Chaikin Volatility
#  garmanklassTA             Garman-Klass Volatility
#  nviTA                     Negative Volume Index
#  obvTA                     On Balance Volume
#  pviTA                     Positive Volume Index
#  pvtrendTA                 Price-Volume Trend
#  williamsadTA              Williams AD
#  williamsrTA               Williams R%
# FUNCTION:                 SPLUS LIKE MOVING AVERAGES:
#  SMA                       Computes Simple Moving Average
#  EWMA                      Computes Exponentially Weighted  Moving Average
# FUNCTION:                 DESCRIPTION:
#  .dailyTA                  Computes an indicator for technical analysis
# FUNCTION:                 DESCRIPTION:
#  .tradeSignals             Computes trade signals from trading positions
#  .tradeLengths             Computes trade length from trading signals
#  .hitRate                  Computes hit rates from returns and positions
# FUNCTION:                 DESCRIPTION:
#  .emaSlider                EMA Slider
################################################################################


test.utilityFunctions =
function()
{
    #  emaTA - Exponential Moving Average
    #  biasTA - EMA-Bias
    #  medpriceTA - Median Price
    #  typicalpriceTA - Typical Price
    #  wcloseTA - Weighted Close Price
    #  rocTA - Rate of Change
    #  oscTA - EMA-Oscillator

    # Data from fEcofin:
    X = MSFT
    print(head(X))

    # Data Records:
    x = close = X[, "Close"]
    high   = X[, "High"]
    low    = X[, "Low"]
    open   = X[, "Open"]
    volume = X[, "Volume"]

    # Exponential Moving Average:
    TA = emaTA(x, lambda = 0.1, startup = 0)
    dim(TA)
    head(TA)

    # EMA-Bias:
    TA = biasTA(x, lag = 5)
    dim(TA)
    head(TA)

    # Median Price:
    TA = medpriceTA(high, low)
    dim(TA)
    head(TA)

    # Typical Price:
    TA = typicalpriceTA(high, low, close)
    dim(TA)
    head(TA)

    # Weighted Close Price:
    TA = wcloseTA(high, low, close)
    dim(TA)
    head(TA)

    # Rate of Change:
    TA = rocTA(x, lag = 5)
    dim(TA)
    head(TA)

    # EMA-Oscillator:
    TA = oscTA(x, lag1 = 25, lag2 = 65)
    dim(TA)
    head(TA)

    # Return Value
    return()
}


################################################################################


test.oscillatorIndicators =
function()
{
    #  momTA - Momentum
    #  macdTA - MACD
    #  cdsTA - MACD Signal Line
    #  cdoTA - MACD Oscillator
    #  vohlTA - High/Low Volatility
    #  vorTA - Volatility Ratio

    # Data from fEcofin:
    X = MSFT
    print(head(X))

    # Data Records:
    x = close = X[, "Close"]
    high   = X[, "High"]
    low    = X[, "Low"]
    open   = X[, "Open"]
    volume = X[, "Volume"]

    # Momentum:
    TA = momTA(x, lag = 5)
    dim(TA)
    head(TA)

    # MACD:
    TA = macdTA(x, lag1 = 12, lag2 = 26)
    dim(TA)
    head(TA)

    # MACD Signal Line:
    TA = cdsTA(x, lag1 = 12, lag2 = 26, lag3 = 9)
    dim(TA)
    head(TA)

    # MACD Oscillator:
    TA = cdoTA(x, lag1 = 12, lag2 = 26, lag3 = 9)
    dim(TA)
    head(TA)

    # High/Low Volatility:
    TA = vohlTA(high, low)
    dim(TA)
    head(TA)

    # Volatility Ratio:
    TA = vorTA(high, low)
    dim(TA)
    head(TA)

    # Return Value:
    return()
}


################################################################################


test.stochasticsIndicators =
function()
{
    # stochasticTA - Stochastics %K/%D, fast/slow
    # fpkTA - Fast Percent %K
    # fpdTA - Fast Percent %D
    # spdTA - Slow Percent %D
    # apdTA - Averaged Percent %D
    # wprTA - Williams Percent %R
    # rsiTA - Relative Strength Index

    # Data from fEcofin:
    X = MSFT
    print(head(X))

    # Data Records:
    x = close = X[, "Close"]
    high   = X[, "High"]
    low    = X[, "Low"]
    open   = X[, "Open"]
    volume = X[, "Volume"]

    # Fast Stochstic:
    # Note, returns a 2-colum series as output ...
    TA = stochasticTA(close, high, low, lag1 = 5, lag2 = 3, type = "fast")
    dim(TA)
    head(TA, 10)

    # Slow Stochstic:
    # Note, returns a 2-colum series as output ...
    TA = stochasticTA(close, high, low, lag1 = 5, lag2 = 3, lag3 = 5,
        type = "slow")
    dim(TA)
    head(TA, 10)

    # Fast Percent K:
    TA = fpkTA(close, high, low, lag = 5)
    dim(TA)
    head(TA,10)

    # Fast Percent D:
    TA = fpdTA(close, high, low, lag1 = 5, lag2 = 3)
    dim(TA)
    head(TA, 10)

    # Slow Percent %D
    TA = spdTA(close, high, low, lag1 = 5, lag2 = 3, lag3 = 9)
    dim(TA)
    head(TA, 10)

    # Averaged Percent %D
    TA = apdTA(close, high, low, lag1 = 5, lag2 = 3, lag3 = 9, lag4 = 9)
    dim(TA)
    head(TA, 10)

    # Williams Percent %R
    TA = wprTA(close, high, low, lag = 5)
    dim(TA)
    head(TA, 10)

    # Relative Strength Index
    TA = rsiTA(close, lag = 14)
    dim(TA)
    head(TA, 10)

    # Return Value:
    return()
}


################################################################################


test.moreIndicators =
function()
{
    # accelTA - Acceleration
    # adiTA - AD Indicator
    # adoscillatorTA - AD Oscillator
    # bollingerTA - Bollinger Bands
    # chaikinoTA - Chaikin Oscillator
    # chaikinvTA - Chaikin Volatility
    # garmanklassTA - Garman-Klass Volatility
    # nviTA - Negative Volume Index
    # obvTA - On Balance Volume
    # pviTA - Positive Volume Index
    # pvtrendTA - Price-Volume Trend
    # williamsadTA - Williams AD
    # williamsrTA- Williams R%

    # Data from fEcofin:
    X = MSFT
    print(head(X))

    x = close = X[, "Close"]
    high   = X[, "High"]
    low    = X[, "Low"]
    open   = X[, "Open"]
    volume = X[, "Volume"]

    # Acceleration
    TA = accelTA(x, n = 3)
    dim(TA)
    head(TA, 10)

    # AD Indicator
    TA = adiTA(high, low, close, volume)
    dim(TA)
    head(TA, 10)

    # AD Oscillator
    TA = adoscillatorTA(open, high, low, close)
    dim(TA)
    head(TA, 10)

    # Bollinger Bands
    TA = bollingerTA(x, lag = 5, n.sd = 2)
    dim(TA)
    head(TA, 10)

    # Chaikin Oscillator
    TA = chaikinoTA(high, low, close, volume, lag1 = 10, lag2 = 3)
    dim(TA)
    head(TA, 10)

    # Chaikin Volatility
    TA = chaikinvTA(high, low, lag1 = 5, lag2 = 5)
    dim(TA)
    head(TA, 10)

    # Garman-Klass Volatility
    TA = garmanklassTA(open, high, low, close)
    dim(TA)
    head(TA, 10)

    # Negative Volume Index
    TA = nviTA(close, volume)
    dim(TA)
    head(TA, 10)

    # On Balance Volume
    TA = obvTA(close, volume)
    dim(TA)
    head(TA, 10)

    # Positive Volume Index
    TA = pviTA(close, volume)
    dim(TA)
    head(TA, 10)

    # Price-Volume Trend
    TA = pvtrendTA(close, volume)
    dim(TA)
    head(TA, 10)

    # Williams AD
    TA = williamsadTA(high, low, close)
    dim(TA)
    head(TA, 10)

    # Williams R%
    TA = williamsrTA(high, low, close, lag = 5)
    dim(TA)
    head(TA, 10)

    # Return Value:
    return()
}


################################################################################


test.splusLikeIndicators =
function()
{
    # SMA - Computes Simple Moving Average
    # EWMA - Computes Exponentially Weighted  Moving Average

    # Data from fEcofin:
    X = MSFT
    print(head(X))

    # Data Records:
    x = close = X[, "Close"]
    high   = X[, "High"]
    low    = X[, "Low"]
    open   = X[, "Open"]
    volume = X[, "Volume"]

    # SMA:
    TA = SMA(x, n = 5)
    dim(TA)
    head(TA)

    # EMA - Using Decay Length:
    TA = EWMA(x, 25)
    dim(TA)
    head(TA)

    # EMA - Using lambda:
    TA = EWMA(x, 2/(25+1))
    dim(TA)
    head(TA)

    # Return Value:
    return()
}


# ------------------------------------------------------------------------------


test.dailyTA =
function()
{
    # .dailyTA
    #   Computes an indicator for technical analysis

    # Data from fEcofin:
    X = MSFT
    print(head(X))

    # EMA - Daily TA:
    TA = .dailyTA(X, "ema", select = "Close", lag = 5)
    head(TA)

    # MACD - Daily TA:
    TA = .dailyTA(X, "macd", select = "Close", lag = c(lag1 = 12, lag2 = 26))
    head(TA)

    # ...

    # Return Value:
    return()
}


# ------------------------------------------------------------------------------


test.tradingFunctions =
function()
{
    # .tradeSignals - Computes trade signals from trading positions
    # .tradeLengths - Computes trade length from trading signals
    # .hitRate - Computes hit rates from returns and positions

    # Positions:
    long = +1
    short = -1
    neutral = 0
    tradePositions = c(+1, +1, +1, -1, -1, +1, +1, -1, +1, +1, +1, -1)
    tradeReturns = rnorm(12)

    # Compute Trade Signals:
    Positions = timeSeries(tradePositions, timeCalendar(), units = "Position")
    Positions
    tradeSignals = .tradeSignals(Positions)
    tradeSignals

    # Compute Trade Lengths:
    tradeLengths = .tradeLengths(tradeSignals)
    tradeLengths

    # Compute Hit Rates:
    .hitRate(tradeReturns, tradePositions)

    # Return Value:
    return()
}


# ------------------------------------------------------------------------------


test.emaSlider =
function()
{
    .emaSlider =
    function(x)
    {   # A function implemented by Diethelm Wuertz

        # Description
        #   Displays the selected technical indicator

        # FUNCTION:

        # Internal Function:
        refresh.code = function(...)
        {
            # Sliders:
            lambda1  = .sliderMenu(no = 1)
            lambda2  = .sliderMenu(no = 2)
            startup  = .sliderMenu(no = 3)

            # Compute Data:
            seriesPlot(x)
            ema1 = emaTA(x, lambda1, startup)
            N1 = ceiling(2/lambda1)-1
            lines(ema1, col = "red")
            ema2 = emaTA(x, lambda2, startup)
            N2 = ceiling(2/lambda2)-1
            lines(ema2, col = "green")
            mText = paste("EMA1 =", N1, "|", "EMA2 =", N2)
            mtext(mText, side = 4, adj = 0, cex = 0.7, col = "grey")

            # Difference:
            seriesPlot(ema2-ema1, type = "h")
            lines(ema2-ema1, col = "red")

            # Reset Frame:
            par(mfrow = c(2, 1), cex = 0.7)
        }

        # Open Slider Menu:
        N = min(10, dim(x)[1])
        print(N)
        .sliderMenu(refresh.code,
           names =       c(  "lamda1", "lamda2", "startup" ),
           minima =      c(   0.01,     0.01,     0        ),
           maxima =      c(   0.99,     0.99,     N        ),
           resolutions = c(   0.01,     0.01,     1        ),
           starts =      c(   0.10,     0.25,     0        ))
    }

    # Chart:
    # .emaSlider(tS)
    NA

    # Return Value:
    return()
}


################################################################################