-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStocks.fsx
186 lines (130 loc) · 5.22 KB
/
Stocks.fsx
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
#load "packages/FsLab/Themes/DefaultWhite.fsx"
#load "packages/FsLab/FsLab.fsx"
#r "MathNet.Numerics.dll"
open System
open System.IO
open Deedle
open FSharp.Data
open XPlot.GoogleCharts
open XPlot.GoogleCharts.Deedle
open MathNet.Numerics
(* Data Sources *)
let DATADIR = Path.Combine(__SOURCE_DIRECTORY__, "data")
let STOCKSFILE = Path.Combine(DATADIR, "single-stock.csv")
[<Literal>]
let TEMPLATE = __SOURCE_DIRECTORY__ + "/" + "stocks-template.csv"
type StocksCsv = CsvProvider<TEMPLATE, ";">
let stockData = StocksCsv.Load(STOCKSFILE)
let valueSeries =
[for row in stockData.Rows -> row.Date, (float row.Value)]
|> series
(* Let's have a look at the stock data *)
let lineChart title ts =
ts
|> Series.observations
|> Chart.Line
|> Chart.WithTitle title
let chart = valueSeries |> lineChart "Stock Price"
let absoluteReturns (ts : Series<DateTime,float>) =
// The return since the previous observation
// E.g. comparing today's Close to yesterday's Close
ts |> Series.diff 1
let relativeReturns ts =
let previousDayValues = ts |> Series.shift 1
Series.zipInner previousDayValues (absoluteReturns ts)
|> Series.mapValues (fun (v,r) -> r/v)
let absReturnsChart =
absoluteReturns valueSeries |> lineChart "Absolute Daily Returns"
let relReturnsChart =
relativeReturns valueSeries |> lineChart "Relative Daily Returns"
let durationInYears (ts:Series<DateTime,'v>) =
let a = ts |> Series.firstKey
let b = ts |> Series.lastKey
let duration = b.Subtract(a) + TimeSpan.FromDays(1.0)
// use standardised year length
duration.TotalDays/365.0
let annualizeDailyVariance (daysPerYear:float) dailySigma =
let sigmaFactor = sqrt daysPerYear
sigmaFactor * dailySigma
let annualizedVariance (ts:Series<DateTime, float>) =
let tradingDays = ts |> Series.countValues
let tradingDaysPerYear = float(tradingDays) / (durationInYears ts)
ts
|> Stats.variance
|> annualizeDailyVariance tradingDaysPerYear
let annualisedStandardDeviation ts =
ts
|> annualizedVariance
|> sqrt
let lastNYears n (ts : Series<DateTime,float>) =
let lastDay = ts |> Series.lastKey
let firstDay = lastDay.AddYears(-n).AddDays(1.0)
ts |> Series.filter (fun date value -> (date >= firstDay))
let lastThreeYears ts =
lastNYears 3 ts
let normalizeSeries ts =
let baseLine = ts |> Series.firstValue
ts |> Series.mapValues (fun (x:float) -> x/baseLine)
let threeYearValues = valueSeries |> lastThreeYears |> normalizeSeries
let threeYearReturns = threeYearValues |> absoluteReturns
let threeYearRelativeReturns = threeYearValues |> relativeReturns
(* Chart some data *)
let c3 = threeYearValues |> lineChart "Normalized Values"
let c3dr = threeYearReturns |> lineChart "Normalized Values, Daily Returns"
let c3relret = threeYearRelativeReturns |> lineChart "Normalized Values, Relative Daily Returns"
let c3dist =
threeYearReturns |> Series.values |> Seq.map (fun x -> ("Group-A", x))
|> Chart.Histogram
|> Chart.WithTitle "Daily Returns distribution"
let c3reldist =
threeYearRelativeReturns |> Series.values |> Seq.map (fun x -> ("Group-A", x))
|> Chart.Histogram
|> Chart.WithTitle "Daily Relative Returns distribution"
(* Get the statistics *)
let absStd = threeYearReturns |> annualisedStandardDeviation
let relStd = threeYearRelativeReturns |> annualisedStandardDeviation
printfn "Standard deviation: (absolute): %.3f p.a. (relative): %.3f%% p.a." absStd (100.0*relStd)
let firstDayOfMonth (dt:DateTime) =
new DateTime(dt.Year, dt.Month, 1)
let lastDayOfMonth (dt:DateTime) =
(new DateTime(dt.Year, dt.Month, 1)).AddMonths(1).AddDays(-1.0)
let resampleDates dateBucketFn ts =
ts
|> Series.keys
|> Seq.map dateBucketFn
|> Set.ofSeq
|> Seq.sort
// Months are represented by first day of month
let firstDayOfMonthValues ts =
let firstDayOfMonths = resampleDates firstDayOfMonth ts
ts
|> Series.resample firstDayOfMonths Direction.Forward
|> Series.mapValues Series.firstValue
// Months are represented by the first day of the month
let lastDayOfMonthValues ts =
let firstDayOfMonths = resampleDates firstDayOfMonth ts
ts
|> Series.resample firstDayOfMonths Direction.Forward
|> Series.mapValues Series.lastValue
let geometricMean (xs:float seq) =
let sumOfLogs = xs |> Seq.map (fun x -> abs (log x)) |> Seq.sum
let n = Seq.length xs
exp (sumOfLogs/(float n))
// We need 37 months of prices to get 36 months of returns
let last37Months = valueSeries |> lastDayOfMonthValues |> Series.takeLast (36+1)
let lastThreeYearRelativeReturns = last37Months |> relativeReturns
let lastThreeYearRelativeReturn =
let first = last37Months |> Series.firstValue
let last = last37Months |> Series.lastValue
last/first
let lastThreeYearGeometricMeanMonthlyReturn =
Math.Pow(lastThreeYearRelativeReturn, 1.0/36.0) - 1.0
let sigmaMonthly = lastThreeYearRelativeReturns |> Stats.stdDev
let sigmaAnnual = (sqrt 12.0) * sigmaMonthly
let stdDevGeomMonthly =
lastThreeYearRelativeReturns
|> Series.values
|> Seq.sumBy (fun x -> pown (x-lastThreeYearGeometricMeanMonthlyReturn) 2)
|> sqrt
|> sqrt
let stdDevGeomAnnual = stdDevGeomMonthly / (sqrt 12.0)