title: Getting stock prices using Yahoo Finance API and Alamofire then plotting it on a graph
body: <p>I am trying to get the price of stocks from Yahoo Finance API and then plot it on a graph.  I have the function which takes the stock prices from Yahoo but I need to convert them so it can be used by a graph.  I am using the SwiftChart Cocoapod for graphs and on their example of using the pod they have a section which takes the price of Apple stock from a .json file and then parse it into the graph.  I need to convert the Yahoo data into the same format so that I can put it into the graph.</p>
  
  <p>This is the code for getting the Yahoo Finance stock:</p>
  
  <p>// Gets the stock chart points</p>
  
  <pre><code>func fetchChartPoints(symbol: String, range: ChartTimeRange, completion:@escaping (_ chartPoints: [ChartPoint]) -&gt; ()) {
  
      DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
  
          //An Alamofire regular responseJSON wont parse the JSONP with a callback wrapper correctly, so lets work around that.
          let chartURL = SwiftStockGraphKit.chartUrlForRange(symbol, range: range)
  
          Alamofire.request(chartURL, method: .get).responseData { response in
  
              if let data = response.result.value {
  
                  var jsonString =  NSString(data: data, encoding: String.Encoding.utf8.rawValue)!
  
                  jsonString = jsonString.substring(from: 30) as NSString
                  jsonString = jsonString.substring(to: jsonString.length-1) as NSString
  
                  if let data = jsonString.data(using: String.Encoding.utf8.rawValue) {
                      if let resultJSON = (try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)))  as? [String : AnyObject] {
  
                          let series = resultJSON["series"] as! [[String : AnyObject]]
                          var chartPoints = [ChartPoint]()
                          for dataPoint in series {
                              //GMT off by 5 hrs
                              let date = NSDate(timeIntervalSince1970: (dataPoint["Timestamp"] as? Double ?? dataPoint["Date"] as! Double) - 18000.0)
  
                              chartPoints.append(
                                  ChartPoint(
                                      date:  date as Date,
                                      volume: dataPoint["volume"] as? Int,
                                      open: dataPoint["open"] as? CGFloat,
                                      close: dataPoint["close"] as? CGFloat,
                                      low: dataPoint["low"] as? CGFloat,
                                      high: dataPoint["high"] as? CGFloat
                                  )
                              )
                          }
                          DispatchQueue.main.async() {
                              completion(chartPoints)
                          }
                      }
                  }
              }
          }
      }
  }
  
  //
  // Graph Time Frame
  //
  
  class func chartUrlForRange(_ symbol: String, range: ChartTimeRange) -&gt; String {
  
      var timeString = String()
  
      switch (range) {
      case .oneDay:
          timeString = "1d"
      case .fiveDays:
          timeString = "5d"
      case .tenDays:
          timeString = "10d"
      case .oneMonth:
          timeString = "1m"
      case .threeMonths:
          timeString = "3m"
      case .oneYear:
          timeString = "1y"
      case .fiveYears:
          timeString = "5y"
      }
  
      return "http://chartapi.finance.yahoo.com/instrument/1.0/\(symbol)/chartdata;type=quote;range=\(timeString)/json"
  }
  </code></pre>
  
  <p>Then this is the code which the SwiftCharts uses to take a JSON file and convert it into a graph:</p>
  
  <pre><code>import UIKit
  import SwiftChart
  
  class StockChartViewController: UIViewController, ChartDelegate {
  
  var selectedChart = 0
  
  @IBOutlet weak var labelLeadingMarginConstraint: NSLayoutConstraint!
  @IBOutlet weak var label: UILabel!
  @IBOutlet weak var chart: Chart!
  
  fileprivate var labelLeadingMarginInitialConstant: CGFloat!
  
  override func viewDidLoad() {
  
      labelLeadingMarginInitialConstant = labelLeadingMarginConstraint.constant
      initializeChart()
  
  }
  
  func initializeChart() {
      chart.delegate = self
  
      // Initialize data series and labels
      let stockValues = getStockValues()
  
      var serieData: [Float] = []
      var labels: [Float] = []
      var labelsAsString: Array&lt;String&gt; = []
  
      // Date formatter to retrieve the month names
      let dateFormatter = DateFormatter()
      dateFormatter.dateFormat = "MM"
  
      for (i, value) in stockValues.enumerated() {
  
          serieData.append(value["close"] as! Float)
  
          // Use only one label for each month
          let month = Int(dateFormatter.string(from: value["date"] as! Date))!
          let monthAsString:String = dateFormatter.monthSymbols[month - 1] 
          if (labels.count == 0 || labelsAsString.last != monthAsString) {
              labels.append(Float(i))
              labelsAsString.append(monthAsString)
          }
      }
  
      let series = ChartSeries(serieData)
      series.area = true
  
      // Configure chart layout
  
      chart.lineWidth = 0.5
      chart.labelFont = UIFont.systemFont(ofSize: 12)
      chart.xLabels = labels
      chart.xLabelsFormatter = { (labelIndex: Int, labelValue: Float) -&gt; String in
          return labelsAsString[labelIndex]
      }
      chart.xLabelsTextAlignment = .center
      chart.yLabelsOnRightSide = true
      // Add some padding above the x-axis
      chart.minY = serieData.min()! - 5
  
      chart.add(series)
  
  }
  // Chart delegate
  
  func didTouchChart(_ chart: Chart, indexes: Array&lt;Int?&gt;, x: Float, left: CGFloat) {
  
      if let value = chart.valueForSeries(0, atIndex: indexes[0]) {
  
          let numberFormatter = NumberFormatter()
          numberFormatter.minimumFractionDigits = 2
          numberFormatter.maximumFractionDigits = 2
          label.text = numberFormatter.string(from: NSNumber(value: value))
  
          // Align the label to the touch left position, centered
          var constant = labelLeadingMarginInitialConstant + left - (label.frame.width / 2)
  
          // Avoid placing the label on the left of the chart
          if constant &lt; labelLeadingMarginInitialConstant {
              constant = labelLeadingMarginInitialConstant
          }
  
          // Avoid placing the label on the right of the chart
          let rightMargin = chart.frame.width - label.frame.width
          if constant &gt; rightMargin {
              constant = rightMargin
          }
  
          labelLeadingMarginConstraint.constant = constant
  
      }
  
  }
  
  func didFinishTouchingChart(_ chart: Chart) {
      label.text = ""
      labelLeadingMarginConstraint.constant = labelLeadingMarginInitialConstant
  }
  
  func didEndTouchingChart(_ chart: Chart) {
  
  }
  
  
  func getStockValues() -&gt; Array&lt;Dictionary&lt;String, Any&gt;&gt; {
  
      // Read the JSON file
      let filePath = Bundle.main.path(forResource: "AAPL", ofType: "json")!
      let jsonData = try? Data(contentsOf: URL(fileURLWithPath: filePath))
      let json: NSDictionary = (try! JSONSerialization.jsonObject(with: jsonData!, options: [])) as! NSDictionary
      let jsonValues = json["quotes"] as! Array&lt;NSDictionary&gt;
  
      // Parse data
      let dateFormatter = DateFormatter()
      dateFormatter.dateFormat = "yyyy-MM-dd"
      let values = jsonValues.map { (value: NSDictionary) -&gt; Dictionary&lt;String, Any&gt; in
          let date = dateFormatter.date(from: value["date"]! as! String)
          let close = (value["close"]! as! NSNumber).floatValue
          return ["date": date!, "close": close]
      }
  
      return values
  
  }
  
  override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  
      super.viewWillTransition(to: size, with: coordinator)
  
      // Redraw chart on rotation
      chart.setNeedsDisplay()
  
  }
  
  
  }
  </code></pre>
  
  <p>Please help so that I can take the stock prices and put them straight into a graph.</p>