資料分析 GPU 應用:S&P500

程式碼

#include <arrayfire.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace af;
using namespace std;

class FirstCup {
private:
	unsigned rowCount;
	af::array dataGPU[5];
	vector<float> result[2];
	
	vector<string> split(string str, char delimiter);
public:
	FirstCup(int idGPU);
	~FirstCup(void);
	
	void loadDataFromFile(const std::string fileName);
	void calc(void);

	unsigned getRowCount();
	vector<float> getResult(int id);
};

FirstCup::FirstCup(int idGPU) {
	af::setDevice(idGPU);
	af::info();
}

FirstCup::~FirstCup(void) {}

vector<string> FirstCup::split(string str, char delimiter) {
	vector<string> internal;
	stringstream ss(str);
	string tok;

	while (getline(ss, tok, delimiter)) {
		internal.push_back(tok);
	}

	return internal;
}

void FirstCup::loadDataFromFile(const std::string fileName) {
	vector<float> idxData[5];

	std::ifstream fileData;
	std::string lineData;

	this->rowCount = 0;

	fileData.open(fileName.c_str());

	while (std::getline(fileData, lineData))
	{
		vector<string> fields = this->split(lineData, ',');
		// Date, Open, High, Low, Close, Volume, AdjClose

		if (fields.size() != 7) continue;

		this->rowCount++;

		idxData[0].push_back(std::stof(fields[1]));
		idxData[1].push_back(std::stof(fields[2]));
		idxData[2].push_back(std::stof(fields[3]));
		idxData[3].push_back(std::stof(fields[4]));
		idxData[4].push_back(std::stof(fields[6]));
	}

	for (int i = 0; i < 5; i++) {
		this->dataGPU[i] = af::array(1, idxData[i].size(), idxData[i].data(), afHost);
	}

//	af_print(this->dataGPU);
}

void FirstCup::calc(void) {
	this->result[0].empty();
	this->result[1].empty();

	for (int i=0; i<5; i++)	{
		this->result[0].push_back(af::mean(this->dataGPU[i]).host<float>()[0]);
		this->result[1].push_back(af::stdev(this->dataGPU[i]).host<float>()[0]);
	}
}

unsigned FirstCup::getRowCount() {
	return this->rowCount;
}

vector<float>  FirstCup::getResult(int id) {
	return this->result[id];
}

int main(int argc, char *argv[])
{
	FirstCup *worker = new FirstCup(0);
	std::string idxNames[] = {"開盤", "最高", "最低", "收盤", "調收"};

    try {
		worker->loadDataFromFile("SP500-2016.csv");
		worker->calc();

		for (int i = 0; i < 5; i++) {
			std::cout << idxNames[i] << '\t';
			std::cout << std::fixed << std::setw(9) << std::setprecision(3) << worker->getResult(0).at(i) << '\t';
			std::cout << std::fixed << std::setw(9) << std::setprecision(3) << worker->getResult(1).at(i) << endl;
		}
    } catch (af::exception& e) {
        std::cerr << e.what() << endl;
        throw;
    }

    return 0;
}

程式輸出

ċ
SP500-2016.csv
(10k)
李智,
2016年7月12日 上午7:04