-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathVianYahooDataPuller.m
352 lines (305 loc) · 12.4 KB
/
VianYahooDataPuller.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
//
// VianYahooDataPuller.m
// AAPLot
//
// Created by admin on 3/31/11.
// Copyright 2011 Crystalnix. All rights reserved.
//
#import "VianYahooDataPuller.h"
#import "APFinancialData.h"
#import "NSDateFormatterExtensions.h"
@interface VianYahooDataPuller ()
@property (nonatomic, retain) NSDate *startDate;
@property (nonatomic, retain) NSDate *endDate;
@property (nonatomic, readwrite, retain) NSArray *financialData;
@property (nonatomic, retain) NSMutableData *receivedData;
@property (nonatomic, retain) NSURLConnection *connection;
@property (nonatomic, copy) NSString *csvString;
@property (nonatomic, retain) NSDecimalNumber *closeMin;
@property (nonatomic, retain) NSDecimalNumber *closeMax;
@property (nonatomic, retain) NSDecimalNumber *highMin;
@property (nonatomic, retain) NSDecimalNumber *highMax;
@property (nonatomic, retain) NSDecimalNumber *lowMin;
@property (nonatomic, retain) NSDecimalNumber *lowMax;
@property (nonatomic, retain) NSDecimalNumber *openMin;
@property (nonatomic, retain) NSDecimalNumber *openMax;
@property (nonatomic, retain) NSDecimalNumber *volumeMin;
@property (nonatomic, retain) NSDecimalNumber *volumeMax;
-(void)fetch;
-(NSString *)URL;
-(void)notifyPulledData;
-(void)parseCSVAndPopulate;
@end
@implementation VianYahooDataPuller
@synthesize startDate, endDate, financialData, receivedData, connection, csvString, closeMax, closeMin, highMax, highMin, lowMax, lowMin, openMax, openMin, volumeMax, volumeMin;
-(id)delegate
{
return delegate;
}
-(void)setDelegate:(id)aDelegate
{
if(delegate != aDelegate)
{
delegate = aDelegate;
if([financialData count] > 0)
[self notifyPulledData]; //loads cached data onto UI
}
}
-(id)initWithTargetSymbol:(NSString *)aSymbol dateResolution:(VianDateResolution)dateRes
{
if ( (self = [super init]) ) {
symbol = [aSymbol copy];
dateResolution = dateRes;
[self performSelector:@selector(fetch) withObject:nil afterDelay:0.01];
}
return self;
}
-(void)dealloc
{
[symbol release];
[financialData release];
[csvString release];
[closeMin release];
[closeMax release];
[lowMax release];
[lowMin release];
[highMax release];
[highMin release];
[openMax release];
[openMin release];
[volumeMax release];
[volumeMin release];
[super dealloc];
}
-(NSString *)URL;
{
NSString *resolutionStr = @"";
switch (dateResolution) {
case VianDateResolutionDay:
resolutionStr = @"1d";
break;
case VianDateResolutionWeek:
resolutionStr = @"7d";
break;
case VianDateResolutionMonth:
resolutionStr = @"1m";
break;
case VianDateResolutionThreeMonths:
resolutionStr = @"3m";
break;
case VianDateResolutionSixMonths:
resolutionStr = @"6m";
break;
case VianDateResolutionYear:
resolutionStr = @"1y";
break;
case VianDateResolutionTwoYears:
resolutionStr = @"2y";
break;
}
NSString *url = [NSString stringWithFormat:@"http://chartapi.finance.yahoo.com/instrument/1.0/%@/chartdata;type=quote;range=%@/csv/", symbol, resolutionStr];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return url;
}
-(void)notifyPulledData
{
if (delegate && [delegate respondsToSelector:@selector(dataPullerDidFinishFetch:)]) {
[delegate performSelector:@selector(dataPullerDidFinishFetch:) withObject:self];
}
}
#pragma mark -
#pragma mark Downloading of data
-(BOOL)shouldDownload
{
BOOL shouldDownload = YES;
return shouldDownload;
}
-(void)fetch
{
if ( loadingData ) return;
if ([self shouldDownload])
{
loadingData = YES;
NSString *urlString = [self URL];
NSLog(@"URL = %@", urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
self.connection = [NSURLConnection connectionWithRequest:theRequest delegate:self];
if (self.connection) {
self.receivedData = [NSMutableData data];
}
else {
//TODO: Inform the user that the download could not be started
loadingData = NO;
}
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// append the new data to the receivedData
[self.receivedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// this method is called when the server has determined that it
// has enough information to create the NSURLResponse
// it can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
[self.receivedData setLength:0];
}
-(void)cancelDownload
{
if (loadingData) {
[self.connection cancel];
loadingData = NO;
self.receivedData = nil;
self.connection = nil;
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
loadingData = NO;
self.receivedData = nil;
self.connection = nil;
NSLog(@"err = %@", [error localizedDescription]);
//TODO:report err
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
loadingData = NO;
self.connection = nil;
NSString *csv = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
self.csvString = csv;
[csv release];
self.receivedData = nil;
[self parseCSVAndPopulate];
}
-(void)parseCSVAndPopulate;
{
NSArray *csvLines = [self.csvString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSString *line = nil;
NSLocale *us = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
BOOL useDates = YES;
NSUInteger i = 0;
for (;;++i) {
line = (NSString *)[csvLines objectAtIndex:i];
NSArray *lineData = [line componentsSeparatedByString:@":"];
NSString *paramName = (NSString*)[lineData objectAtIndex:0];
NSArray *values = [(NSString*)[lineData objectAtIndex:1] componentsSeparatedByString:@","];
if ([paramName isEqualToString:@"Timestamp"]) {
useDates = NO;
}
else if ([paramName isEqualToString:@"close"]) {
self.closeMin = [NSDecimalNumber decimalNumberWithString:[values objectAtIndex:0] locale:us];
self.closeMax = [NSDecimalNumber decimalNumberWithString:[values objectAtIndex:1] locale:us];
}
else if ([paramName isEqualToString:@"high"]) {
self.highMin = [NSDecimalNumber decimalNumberWithString:[values objectAtIndex:0] locale:us];
self.highMax = [NSDecimalNumber decimalNumberWithString:[values objectAtIndex:1] locale:us];
}
else if ([paramName isEqualToString:@"low"]) {
self.lowMin = [NSDecimalNumber decimalNumberWithString:[values objectAtIndex:0] locale:us];
self.lowMax = [NSDecimalNumber decimalNumberWithString:[values objectAtIndex:1] locale:us];
}
else if ([paramName isEqualToString:@"open"]) {
self.openMin = [NSDecimalNumber decimalNumberWithString:[values objectAtIndex:0] locale:us];
self.openMax = [NSDecimalNumber decimalNumberWithString:[values objectAtIndex:1] locale:us];
}
else if ([paramName isEqualToString:@"volume"]) {
self.volumeMin = [NSDecimalNumber decimalNumberWithString:[values objectAtIndex:0] locale:us];
self.volumeMax = [NSDecimalNumber decimalNumberWithString:[values objectAtIndex:1] locale:us];
break;
}
}
[us release];
i++;
NSMutableArray *newFinancials = [NSMutableArray arrayWithCapacity:[csvLines count]-i];
NSDictionary *currentFinancial = nil;
for (; i < [csvLines count]-1; i++) {
line = (NSString *)[csvLines objectAtIndex:i];
currentFinancial = [NSDictionary dictionaryWithCSVLine:line useDates:useDates];
[newFinancials addObject:currentFinancial];
}
self.startDate = [(NSDictionary*)[newFinancials objectAtIndex:0] objectForKey:@"date"];
self.endDate = [(NSDictionary*)[newFinancials lastObject] objectForKey:@"date"];
[self setFinancialData:[NSArray arrayWithArray:newFinancials]];
[self notifyPulledData];
}
-(VianPlotAreaDescription*)modelForData
{
NSAssert([financialData count] > 0, @"No data for model creation");
VianXAxis *xAxis = [[[VianXAxis alloc] init] autorelease];
xAxis.isDateAxis = YES;
//xAxis.showGridLines = YES;
//xAxis.showLabels = YES;
xAxis.dateResolution = dateResolution;
xAxis.startDate = startDate;
xAxis.endDate = endDate;
xAxis.start = [NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithDouble:1.0] decimalValue]];
xAxis.end = [NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithInt:[financialData count]] decimalValue]];
NSMutableArray *values = [NSMutableArray arrayWithCapacity:[financialData count]];
for (NSUInteger i = 1; i <= [financialData count]; ++i)
[values addObject:[NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithInt:i] decimalValue]]];
NSMutableArray *dates = [NSMutableArray arrayWithCapacity:[financialData count]];
NSMutableArray *closePlotValues = [NSMutableArray arrayWithCapacity:[financialData count]];
NSMutableArray *volumePlotValues = [NSMutableArray arrayWithCapacity:[financialData count]];
NSMutableArray *ohlcPlotValues = [NSMutableArray arrayWithCapacity:[financialData count]];
for (NSDictionary *d in financialData) {
[dates addObject:[d objectForKey:@"date"]];
[closePlotValues addObject:[d objectForKey:@"close"]];
[volumePlotValues addObject:[d objectForKey:@"volume"]];
[ohlcPlotValues addObject:[NSDictionary dictionaryWithObjectsAndKeys:
[d objectForKey:@"close"], @"close",
[d objectForKey:@"high"], @"high",
[d objectForKey:@"low"], @"low",
[d objectForKey:@"open"], @"open",
nil]];
}
xAxis.values = [NSArray arrayWithArray:values];
xAxis.dates = [NSArray arrayWithArray:dates];
VianPlot *closePlot = [[[VianPlot alloc] init] autorelease];
closePlot.identifier = @"Close Plot";
//closePlot.showYGridLines = YES;
//closePlot.showYLabels = YES;
closePlot.inMainPlotSpace = YES;
closePlot.plotType = VianPlotTypeScatter;
closePlot.fillType = VianFillTypeStripes;
closePlot.lineColor = [CPColor whiteColor];
closePlot.low = closeMin;
closePlot.high = closeMax;
closePlot.values = [NSArray arrayWithArray:closePlotValues];
closePlot.xAxis = xAxis;
VianPlot *volumePlot = [[[VianPlot alloc] init] autorelease];
volumePlot.identifier = @"Volume Plot";
//volumePlot.showYGridLines = YES;
//volumePlot.showYLabels = YES;
volumePlot.inMainPlotSpace = NO;
volumePlot.plotType = VianPlotTypeBar;
volumePlot.fillType = VianFillTypeNone;
volumePlot.lineColor = [CPColor whiteColor];
volumePlot.low = volumeMin;
volumePlot.high = volumeMax;
volumePlot.values = [NSArray arrayWithArray:volumePlotValues];
volumePlot.xAxis = xAxis;
VianPlot *ohlcPlot = [[[VianPlot alloc] init] autorelease];
ohlcPlot.identifier = @"OHLC Plot";
//ohlcPlot.showYGridLines = YES;
//ohlcPlot.showYLabels = YES;
ohlcPlot.inMainPlotSpace = YES;
ohlcPlot.plotType = VianPlotTypeTradingRange;
ohlcPlot.fillType = VianFillTypeNone;
ohlcPlot.lineColor = [CPColor redColor];
ohlcPlot.low = lowMin;
ohlcPlot.high = highMax;
ohlcPlot.values = [NSArray arrayWithArray:ohlcPlotValues];
ohlcPlot.xAxis = xAxis;
VianPlotAreaDescription *vpad = [[[VianPlotAreaDescription alloc] init] autorelease];
vpad.plots = [NSArray arrayWithObjects:closePlot, volumePlot, ohlcPlot, nil];
vpad.hasSecondaryPlotSpace = YES;
vpad.secondaryPlotSpaceHeightPercent = [NSDecimalNumber decimalNumberWithMantissa:16 exponent:-2 isNegative:NO];
return vpad;
}
@end