• frederic-adda
  • Junior Member
  • Email
  • Posts 2
  • Reputation 7
  • Member Since
  • Last Active
Email
    This user has not added any photos yet.
All Posts Topics Started Likes
Time Series Intraday and Currency exchange rates in Swift 4
Here is a way to get Time Series Intraday and Currency exchange rates with the Alpha Vantage API in Swift.

Code:

//
//  Server+AlphaVantage.swift
//  ZEN Portfolio
//
//  Created by Frédéric ADDA on 04/11/2017.
//  Copyright © 2017 Frédéric ADDA. All rights reserved.
//
import Foundation
import Alamofire
extension Server {
    
    // MARK: AlphaVantage URLs
    private struct AlphaVantage {
        static let host = "www.alphavantage.co"
        static let path = "/query"
        static let apiKey = "YOUR_API_KEY"
        static let interval: Interval = .m1
        
        /// Intervals allowed for intraday time series
        enum Interval: String {
            case m1 = "1min"
            case m5 = "5min"
            case m15 = "15min"
            case m30 = "30min"
            case m60 = "60min"
        }
        
        struct Functions {
            static let timeSeriesIntraday   = "TIME_SERIES_INTRADAY"
            static let currencyExchangeRate = "CURRENCY_EXCHANGE_RATE"
        }
    }
    
    
    // MARK: AlphaVantage Basic queries
    
    /// Gets a single currency exchange rate from the server and updates it in the CurrencyRateStore
    ///
    /// - Parameters:
    ///   - sourceCurrency: "from" currency in the exchange rate
    ///   - destinationCurrency: "to" currency in the exchange rate
    ///   - fetchCompletion: closure called upon completion
    static func getCurrencyRate(from sourceCurrency: String, to destinationCurrency: String, completion: @escaping ((Result) -> Void)) {
        var urlComponents = URLComponents()
        urlComponents.scheme = "https"
         urlComponents.host  =  AlphaVantage.host
        urlComponents.path = AlphaVantage.path
        urlComponents.queryItems = [
            URLQueryItem(name: "apikey", value: AlphaVantage.apiKey),
            URLQueryItem(name: "function", value: AlphaVantage.Functions.currencyExchangeRate),
            URLQueryItem(name: "from_currency", value: sourceCurrency),
            URLQueryItem(name: "to_currency", value: destinationCurrency)
        ]
        
        guard let url = urlComponents.url else {
            print("AlphaVantage CURRENCY_EXCHANGE_RATE: bad url!")
            completion(.failure(GenericError.badUrl))
            return
        }
        
        launchGetRequest(url: url) { result in
            switch result {
            case .success(let json):
                
                // Update currency rate
                guard let dictionary = json["Realtime Currency Exchange Rate"] as? JSON,
                    let exchangeRateString = dictionary["5. Exchange Rate"] as? String,
                    let exchangeRate = Double(exchangeRateString)
                    else {
                        print("Could not update exchange rate \(sourceCurrency)\(destinationCurrency)=X")
                        completion(.failure(GenericError.unreadableResponse))
                        return
                }
                
                print("Updating exchange rate \(sourceCurrency)/\(destinationCurrency): \(exchangeRate)")
                CurrencyRateStore.shared["\(sourceCurrency)\(destinationCurrency)=X"] = exchangeRate
                completion(.success)
                
            case .failure(let error):
                completion(.failure(error))
            }
        }
    }
    
    
    
    /// Gets stock quotes for a single stock symbol
    ///
    /// - Parameters:
    ///   - symbol: mnemonic code of the stock to update
    ///   - fetchCompletion: closure called upon completion
    static func getStockQuotes(for symbol: String, completion: @escaping ((Result) -> Void)) {
        
        var urlComponents = URLComponents()
        urlComponents.scheme = "https"
         urlComponents.host  =  AlphaVantage.host
        urlComponents.path = AlphaVantage.path
        urlComponents.queryItems = [
            URLQueryItem(name: "apikey", value: AlphaVantage.apiKey),
            URLQueryItem(name: "function", value: AlphaVantage.Functions.timeSeriesIntraday),
            URLQueryItem(name: "symbol", value: symbol),
            URLQueryItem(name: "interval", value: AlphaVantage.interval.rawValue)
        ]
        
        guard let url = urlComponents.url else {
            print("AlphaVantage TIME_SERIES_INTRADAY: bad url!")
            completion(.failure(GenericError.badUrl))
            return
        }
        print("Fetching stock quotes for symbol \(symbol) with url: \(url)")
        launchGetRequest(url: url) { result in
            switch result {
            case .success(let json):
                
                // Update last fetch date
                GlobalSettings.shared.lastFetchDate = Date()
                
                // Get last trade date
                guard let metadata = json["Meta Data"] as? JSON,
                    let lastRefreshed = metadata["3. Last Refreshed"] as? String,
                    let lastRefreshDate = Formatters.shared.alphaVantageServerDateFormatter.date(from: lastRefreshed)
                    else {
                        print("Could not find last trade date for stock \(symbol)")
                        completion(.failure(GenericError.unreadableResponse))
                        return
                }
                
                // Get stock price
                guard let interval = metadata["4. Interval"] as? String,
                    let timeSeries = json["Time Series (\(interval))"] as? JSON,
                    let lastDictionary = timeSeries[lastRefreshed] as? JSON,
                    let close = lastDictionary["4. close"] as? String,
                    let closeQuote = Double(close)
                    else {
                        print("Could not find stock quote for stock \(symbol)")
                        completion(.failure(GenericError.unreadableResponse))
                        return
                }
                
                // Update stocks
                updateStocks(correspondingTo: symbol, with: closeQuote, lastFetchDate: lastRefreshDate)
                completion(.success)
                
            case .failure(let error):
                completion(.failure(error))
            }
        }
        
    }
}

 

3 0
Zen Portfolio (iOS App)

ZEN Portfolio lets you manage a stock portfolio in a simple yet efficient way.

Investors often manage several stocks from different countries, in different currencies, and therefore need up-to-date stock quotes, but also up-to-date currency rates.

When you add a stock in ZEN Portfolio, you indicate purchase information (such as: how many shares you bought, at which price, and if need be, with which currency rate) ; ZEN Portfolio automatically gets the current quotes of your stock and the most up-to-date currency rate ; and calculates for you the cost and value of your stock, and the corresponding gain or loss (in value or percentage).

Zen Portfolio is well established on the App Store since 2012, and has been included in Apple's selection in the Finance category. It is a good example of bringing a simple, clear interface, to a complex market.

Alpha Vantage provides the daily stock quotes and currency exchange rates necessary to the app.

Zen Portfolio Wide.png 


4 0
count post selected

Add a Website Forum to your website.