Chapter 14: StockX – Drawing charts and working with financial data

What you’ll learn in this chapter:

  • Learn to draw beautiful graphics in SwiftUI 
  • Present data visually by using charts
  • Fetch financial data using the Alpha Vantage API
  • Deepen your knowledge about Concurrency in SwiftUI and parsing JSON data

What we’ll create 🚀

In this chapter, we’re going to create a stocks app with real stock data. We are going to fetch that data by using the free Alphavantage API. Furthermore, we will learn how to draw graphics in SwiftUI and use this knowledge to create beautiful line charts. StockX will be able to fetch requested stock data and display it using the time frame specified by the user.

At the end of this chapter, our app will look like this:

Preparing the UI 🎨

As always, we start by creating a new Xcode project and naming it “StockX”. After you created a new project, open the ContentView.swift file, since we’ll use it for displaying the chart’s interface. We start building the StockX app by preparing a simple and static interface to get a feeling for how our app will look like. 

Since we have already covered the relevant topics, we will go through this part very quickly.

At the top of our ContentView’s body, we want to insert a header to display the latest price of a particular stock combined with the percentage price change over a specific time period. For now, we’ll use static data.

struct ContentView: View {
    var body: some View {
        HStack(alignment: .bottom) {
            Text("$" + String(format: "%.2f", 32.2832))
                .font(.custom("Avenir", size: 45))
            Text(String(format: "%.2f", 0.234) + "%")
                .font(.custom("Avenir", size: 18))
                .fontWeight(.medium)
                .foregroundColor(.green)
        }
            .padding()
            .padding(.top, 30)
    }
}

Next, we CMD-Click on the HStack to extract it, call it “Header”, and wrap the extracted Header view into a VStack. 

struct ContentView: View {
    var body: some View {
        VStack {
            Header()
        }
    }
}

struct Header: View {
    var body: some View {
        HStack(alignment: .bottom) {
            Text("$" + String(format: "%.2f", 32.2832))
                .font(.custom("Avenir", size: 45))
            Text(String(format: "%.2f", 0.234) + "%")
                .font(.custom("Avenir", size: 18))
                .fontWeight(.medium)
                .foregroundColor(.green)
        }
            .padding()
            .padding(.top, 30)
    }
}

Then, we place a Rectangle below our Header, which serves as a placeholder for the chart we will draw later on. 

VStack {
    Header()
    Rectangle()
        .frame(height: 300)
}

Below our chart, we want to insert some dummy buttons to “buy” and “sell” the respective share. 

VStack {
    //...
    HStack {
        Text("Sell Shares")
            .font(.custom("Avenir", size: 16))
            .foregroundColor(Color(red: 0.8, green: 0.8, blue: 0.8))
            .padding(20)
            .background(Color(red: 0.25, green: 0.27, blue: 0.3))
        Text("Buy Shares")
            .font(.custom("Avenir", size: 16))
            .foregroundColor(.white)
            .padding(20)
            .background(Color.blue)
    }
        .background(Color.blue)
        .cornerRadius(16)
}

We also extract this HStack and name the created subview “TransactionButtons”. 

Finally, insert one Spacer view above and one Spacer view below the TransactionButtons to rearrange the ContentView appropriately.

VStack {
    Header()
    Rectangle()
        .frame(height: 300)
    Spacer()
    TransactionButtons()
    Spacer()
}

Each stock chart should be embedded into a stock list. 

For this purpose, create a new SwiftUI view file and name it “StockList.swift”. For keeping an overview of our project, create a new group in the Project Navigator by right-clicking and selecting “New Group”. Call this group “Views” and drag-and-drop both SwiftUI views into it. 

Make sure the StockList.swift file is still opened. Then, wrap the default Text view into a List embedded into a NavigationView. Let’s use .plain as the .listStyle

struct StockList: View {
    var body: some View {
        NavigationView {
            List {
                Text("Hello, World!")
            }
                .listStyle(.plain)
                .navigationTitle("StockX")
        }
    }
}

Let’s add the same .navigationTitle to our ContentView.

VStack {
    Header()
    Rectangle()
        .frame(height: 300)
    Spacer()
    TransactionButtons()
    Spacer()
}
    .navigationTitle("StockX")

Next, we define the “blueprint” row for our List. Each row should contain the essential information of the specific stock (its stock symbol, the company’s name, and the latest pricing information) and link to the corresponding ContentView. Therefore, we replace the Text view in our StockList with:

HStack {
    NavigationLink(destination: ContentView()) {
        VStack(alignment: .leading) {
            Text("AAPL")
                .font(.custom("Avenir", size: 20))
                .fontWeight(.medium)
            Text("Apple Inc.")
                .font(.custom("Avenir", size: 16))
        }
        Spacer()
        VStack(alignment: .trailing) {
            Text(String(format: "%.2f", 0.234) + "%")
                .font(.custom("Avenir", size: 14))
                .fontWeight(.medium)
                .foregroundColor(.green)
            Text("$" + String(format: "%.2f", 32.2832))
                .font(.custom("Avenir", size: 26))
        }
    }
}

Finally, we also extract this HStack as a subview and name it “StockListRow”.

NavigationView {
    List {
        StockListRow()
    }
        .listStyle(.plain)
        .navigationTitle("StockX")
}

That’s it! This is how your StockList preview should look like now:

Finally, we want our app to open the StockList view instead of our ContentView when launching. To achieve this, we go to our StockXApp struct and replace the ContentView with our StockList:

@main
struct StockXApp: App {
    var body: some Scene {
        WindowGroup {
            StockList()
        }
    }
}

Great! We’ve prepared the basic layout for our StockX app. Now it’s time to learn how to draw in SwiftUI and use this knowledge to create line charts.

Leave a Reply

Your email address will not be published. Required fields are marked *