-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstooq_google_sheets_integration.gs
260 lines (208 loc) · 8.75 KB
/
stooq_google_sheets_integration.gs
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
/**
* The MIT License (MIT)
*
* Copyright (c) 2018 Marcin P (https://github.com/yu55)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
var LAST_REFRESH_DATE_CELL = "B1"; // komórka w której przechowujemy datę ostatniej aktualizacji
function onOpen() {
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [{
name : "Aktualizuj kursy walorów",
functionName : "updateLastRefreshDate"
}];
activeSpreadsheet.addMenu("STOOQ", menuEntries);
updateLastRefreshDate();
};
function updateLastRefreshDate() {
SpreadsheetApp.getActiveSpreadsheet().getRange(LAST_REFRESH_DATE_CELL).setValue(new Date());
}
/**
* Download share price for a gicen ticker from stooq.com web page.
* Date parameter is optional. If date is not provided or provided date is today
* then function will download current share price for a given ticker from stooq.com web page.
* Otherwise function will download historic share price for a given ticker and date.
*
* @param {string} ticker share ticker name; e.g. "^SPX".
* @param {Date=} date given date.
* @return share price at given date if date is provided or current share price.
* @customfunction
*/
function STOOQ_GET_PRICE(ticker, date) {
if (isRequestForCurrentPrice(date)) {
return stooqGetCurrentPrice(ticker);
} else {
return stooqGetHistoricClosingPrice(ticker, date);
}
}
function isRequestForCurrentPrice(date) {
var now = initNowDateWithoutHours();
return (date == null || setZeroHours(date).getTime() == now.getTime());
}
function initNowDateWithoutHours() {
var now = new Date();
return setZeroHours(now);
}
function setZeroHours(date) {
date.setHours(0,0,0,0);
return date;
}
function stooqGetCurrentPrice(ticker) {
validateTicker(ticker);
var stooqWebPageSource = downloadStooqWebPageSource(ticker)
var priceValue = extractSharePrice(stooqWebPageSource, ticker);
return priceValue;
}
function validateTicker(ticker) {
if (!ticker || 0 === ticker.trim().length) {
throw ("ERROR: function argument \"ticker\" cannot be empty");
}
}
function downloadStooqWebPageSource(ticker) {
var url = prepareStooqWebPageUrl(ticker)
var stooqResponse = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
if (stooqResponse.getResponseCode() != 200) {
throw ("ERROR: Cannot download \"" + ticker + "\" data. HTTP code: " + stooqResponse.getResponseCode());
}
return stooqResponse.getContentText();
}
function prepareStooqWebPageUrl(ticker) {
var normalizedTicker = normalizeTicker(ticker);
return 'https://stooq.com/q/?s=' + encodeURIComponent(normalizedTicker);
}
function normalizeTicker(ticker) {
return ticker.toLowerCase().trim();
}
function extractSharePrice(stooqWebPageSource, ticker) {
var priceText = findPriceText(stooqWebPageSource, ticker);
var priceAsNumber = convertTextToNumber(priceText);
return priceAsNumber;
}
function findPriceText(stooqWebPageSource, ticker) {
// we're looking for a HTML fragment like this: "<span style="font-weight:bold" id="aq_^spx_c2">2833.28</span>"
var priceHtmlSpanTagIdLocation = findPriceHtmlSpanTagIdLocation(stooqWebPageSource, ticker);
var priceTextStartLocation = stooqWebPageSource.indexOf(">", priceHtmlSpanTagIdLocation);
var priceTextEndLocation = stooqWebPageSource.indexOf("<", priceHtmlSpanTagIdLocation);
return stooqWebPageSource.substring(priceTextStartLocation + 1, priceTextEndLocation);
}
function findPriceHtmlSpanTagIdLocation(stooqWebPageSource, ticker) {
var priceHtmlSpanTagId = preparePriceHtmlSpanTagId(ticker);
var priceHtmlSpanTagIdLocation = stooqWebPageSource.indexOf(priceHtmlSpanTagId);
if (priceHtmlSpanTagIdLocation == -1) {
throw ("ERROR: cannot find price of \"" + ticker + "\" ticker on STOOQ web page");
}
return priceHtmlSpanTagIdLocation;
}
function preparePriceHtmlSpanTagId(ticker) {
var normalizedTicker = normalizeTicker(ticker);
return "aq_" + normalizedTicker + "_c";
}
function convertTextToNumber(text) {
return Number(text);
}
function stooqGetHistoricClosingPrice(ticker, date) {
validateTicker(ticker);
// TODO validateDate(date);
var historyCsv = downloadStooqHistoryCsv(ticker, date);
var historicClosingPrice = extractHistoricSharePrice(historyCsv);
return convertTextToNumber(historicClosingPrice);
}
function downloadStooqHistoryCsv(ticker, date) {
var url = prepareStooqHistoryCsvUrl(ticker, date)
var stooqResponse = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
if (stooqResponse.getResponseCode() != 200) {
throw ("ERROR: Cannot download \"" + ticker + "\" history CSV data. HTTP code: " + stooqResponse.getResponseCode());
}
return stooqResponse.getContentText();
}
function prepareStooqHistoryCsvUrl(ticker, date) {
var normalizedTicker = normalizeTicker(ticker);
var dateParam = Utilities.formatDate(date, "GMT", "yyyyMMdd");
var url = "https://stooq.com/q/d/l/?s="+ encodeURIComponent(ticker) + "&d1=" + encodeURIComponent(dateParam) + "&d2=" + encodeURIComponent(dateParam) + "&i=d";
return url;
}
function extractHistoricSharePrice(historyCsv) {
var historyCsvWthoutCR = historyCsv.replace(/[\r]/g, "");
var csvLines = historyCsvWthoutCR.split("\n");
var data = csvLines.map(function(line) {return line.split(",")});
if (data.length < 2 || data[1].length < 5) {
throw ("ERROR: Cannot find price data in Stooq history CSV file. historyCsv=\"" + historyCsv + "\" data=" + data);
}
const CSV_DATA_ROW_INDEX = 1;
const CLOSING_PRICE_DATA_INDEX = 4;
return data[CSV_DATA_ROW_INDEX][CLOSING_PRICE_DATA_INDEX];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Tests
function shouldReturnCurrentPriceForValidExistingTicker() {
Logger.log(stooqGetCurrentPrice("^spx"));
}
function shouldReturnCurrentPriceForExistingTickerWithCapitalLetters() {
Logger.log(stooqGetCurrentPrice("^SPX"));
}
function shouldReturnCurrentPriceForUntrimmedExistingTicker() {
Logger.log(stooqGetCurrentPrice(" ^SPX "));
}
function shouldThrowExceptionForCurrentNonExistingTicker() {
Logger.log(stooqGetCurrentPrice("castar"));
}
function shouldThrowExceptionForCurrentNullTicker() {
Logger.log(stooqGetCurrentPrice(null));
}
function shouldThrowExceptionForCurrentEmptyTicker() {
Logger.log(stooqGetCurrentPrice(""));
}
function shouldThrowExceptionForCurrentBlankTicker() {
Logger.log(stooqGetCurrentPrice(" "));
}
function shouldReturnHistoricPriceForValidExistingTicker() {
Logger.log(stooqGetHistoricClosingPrice("^spx", new Date(2017, 7, 11)));
}
function shouldReturnHistoricPriceForExistingTickerWithCapitalLetters() {
Logger.log(stooqGetHistoricClosingPrice("^SPX", new Date(2017, 7, 11)));
}
function shouldReturnHistoricPriceForUntrimmedExistingTicker() {
Logger.log(stooqGetHistoricClosingPrice(" ^SPX ", new Date(2017, 7, 11)));
}
function shouldThrowExceptionForHistoricNonExistingTicker() {
Logger.log(stooqGetHistoricClosingPrice("castar", new Date(2017, 7, 11)));
}
function shouldThrowExceptionForHistoricNullTicker() {
Logger.log(stooqGetHistoricClosingPrice(null, new Date(2017, 7, 11)));
}
function shouldThrowExceptionForHistoricEmptyTicker() {
Logger.log(stooqGetHistoricClosingPrice("", new Date(2017, 7, 11)));
}
function shouldThrowExceptionForHistoricBlankTicker() {
Logger.log(stooqGetHistoricClosingPrice(" ", new Date(2017, 7, 11)));
}
function shouldThrowExceptionForHistoricNullDate() {
Logger.log(stooqGetHistoricClosingPrice("^spx", null));
}
function shouldInvokeGetCurrentPriceFunctionWhenNoDatePrivided() {
Logger.log(STOOQ_GET_PRICE("^spx"));
Logger.log(STOOQ_GET_PRICE("^spx", new Date()));
}
function shouldInvokeGetCurrentPriceFunctionWhenTodayDatePrivided() {
Logger.log(STOOQ_GET_PRICE("^spx", new Date()));
}
function shouldInvokeGetHistoricPriceFunction() {
Logger.log(STOOQ_GET_PRICE("^spx", new Date(2017, 7, 11)));
}