Created
April 30, 2019 13:56
-
-
Save boshng95/ebf6a98b1bad41e9cb2bfbbc2f338ae2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let companies = ["A2M","CBA","AHG","ABC","CCL"] | |
for company in companies{ | |
let jsonUrlStringPrice = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=ASX:"+company+"&outputsize=100&apikey=demo" | |
//API key need to be claim in AlphaVantage | |
URLSession.shared.dataTask(with: url){ (data, response, err) in | |
guard let data = data else {return} | |
do{ | |
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as AnyObject | |
var symbols = "" | |
if let information = json["Meta Data"] as? NSDictionary{ | |
if let symbol = information["2. Symbol"]{ | |
symbols = symbol as! String | |
if let range = symbols.range(of: ":"){ | |
symbols = String(symbols[range.upperBound...]) | |
} | |
} | |
} | |
if let prices = json["Time Series (Daily)"] as? NSDictionary{ | |
guard let priceArray = prices as? [String: AnyObject] else {return} | |
for (key, value) in priceArray{ | |
guard let open = value["1. open"] as? String else {return} | |
guard let high = value["2. high"] as? String else {return} | |
guard let low = value["3. low"] as? String else {return} | |
guard let close = value["4. close"] as? String else {return} | |
guard let volume = value["5. volume"] as? String else {return} | |
arrangeDate.append([key, open, high, low, close, volume]) | |
} | |
} | |
let sortedArray = arrangeDate.sorted(by: {left, right in | |
let leftDate = self.dateFormater.date(from: left[0]) | |
let rightDate = self.dateFormater.date(from: right[0]) | |
return leftDate!.compare(rightDate!) == .orderedAscending | |
}) | |
var finalArray = [DailyPrice]() | |
for var data in sortedArray{ | |
finalArray.append(DailyPrice(date: data[0], open: Double(data[1])!, high: Double(data[2])!, low: Double(data[3])!, close: Double(data[4])!, volume: Int(data[5])!)) | |
} | |
self.listedCompanies.append(Company(symbol: symbols, dailyPrices: finalArray)) | |
completion(self.listedCompanies) | |
}catch let err{ | |
print(err) | |
} | |
}.resume() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment