Last active
June 10, 2022 15:17
-
-
Save computerphysicslab/413be804b0134202d3c9dd371b8481be to your computer and use it in GitHub Desktop.
This file contains 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
// Read a time series from a CSV file | |
package main | |
// @dev config goLang folder | |
// go env -w GO111MODULE=auto | |
// go mod init aibull.io/goTimeSeriesPrediction | |
// go mod tidy | |
// @dev Running | |
// go run predictor.go | |
import ( | |
"bytes" | |
"encoding/csv" | |
"fmt" | |
"io" | |
"os" | |
"strconv" | |
"strings" | |
) | |
type TimeSeries struct { | |
Day string `csv:"Day"` | |
Price float32 `csv:"Price"` | |
} | |
func main() { | |
// Read CSV file | |
in, err := os.Open("../../Bitcoin price prediction - Data.csv") | |
if err != nil { | |
panic(err) | |
} | |
defer in.Close() | |
// Convert *os.File to string | |
var buf bytes.Buffer | |
io.Copy(&buf, in) | |
asString := string(buf.Bytes()) | |
// Parse CSV using goLang standard library encoding/csv | |
r := csv.NewReader(strings.NewReader(asString)) | |
records, err := r.ReadAll() | |
if err != nil { | |
panic(err) | |
} | |
// Check headers are as expected | |
if records[0][0] != "Day" { | |
panic("Column header Day not found") | |
} | |
if records[0][1] != "Price" { | |
panic("Column header Price not found") | |
} | |
// Loop data rows to populate bitcoinData struct | |
bitcoinData := []TimeSeries{} // golang dynamic slice | |
var priceString string | |
var priceFloat float64 | |
for i, row := range records { | |
if i == 0 { // Skip header row | |
continue | |
} | |
// Transform price string into float (it has a "," for thousands) | |
priceString = strings.ReplaceAll(row[1], ",", "") // Remove the "," for thousands | |
priceFloat, err = strconv.ParseFloat(priceString, 32) | |
if err == nil { | |
// fmt.Println("Parsing done...") | |
// fmt.Printf("%T, %v\n", priceFloat, priceFloat) | |
} else { | |
fmt.Println("Parsing failed...") | |
fmt.Printf("Error:%v\n", err) | |
} | |
// Using append to increase the golang dynamic slice | |
bitcoinData = append(bitcoinData, TimeSeries{row[0], float32(priceFloat)}) | |
// Output time series on screen | |
fmt.Print("\n", bitcoinData[len(bitcoinData)-1].Day, " ", bitcoinData[len(bitcoinData)-1].Price) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment