Sunday, August 11, 2024
HomeGolangHaving bother getting my common true vary program to work - Code...

# Having bother getting my common true vary program to work – Code Overview

its a calculation behaviour concern

listed here are the outcomes
Date Open Excessive Low Shut preclose TR
2024-01-26 72.25 73.19 70.45 71.28 73.37 2.73
2024-01-29 71.69 73.09 70.78 73.03 68.87 2.31
2024-01-30 73.01 73.62 70.86 71.43 63.40 2.76
2024-01-31 69.74 70.87 68.24 68.53 66.22 2.63
2024-02-01 68.87 69.30 67.66 68.15 55.63 1.64
2024-02-02 67.90 69.06 67.33 68.85 57.23 1.73
2024-02-05 69.15 69.89 67.97 68.37 56.17 1.92
2024-02-06 62.55 62.55 54.82 55.26 53.62 7.73
2024-02-07 55.60 56.21 53.11 53.62 67.38 3.10
2024-02-08 53.81 57.36 53.81 56.25 65.38 3.55
2024-02-09 56.89 59.14 56.80 58.70 54.19 2.35
2024-02-12 58.80 59.74 57.66 58.04 69.35 2.08
2024-02-13 55.03 56.56 54.17 55.22 57.02 2.39
2024-02-14 56.30 57.18 55.57 57.02 66.28 1.61
2024-02-15 57.38 57.58 55.59 56.34 66.70 1.98

now principally, i ship a duplicate of the code, however principally i feel the api work correctly as a result of it will get the correct values excessive, shut of a inventory on a selected day, nonetheless my code shouldn’t be storing the final shut day correctly for the calculation of the subsequent day. bascially i confirmed right here within the output how the prevclose shouldn’t be equal to the shut, and due to this fact the calculation is off. with how the true vary works, its primarily based on three situations and the upper variety of the three situations turns into the true vary and my two situations are off due to the fallacious shut worth of the day prior to this

right here is my code, now i exploit two code script. the primary script which comprise all of the features and calculations and the atr script which does the calculation and bit only for the common true vary and true vary

essential script
bundle essential

import (
“encoding/json”
“fmt”
“web/http”
“strconv”
“time”

``````atr "instance/golang/ATR" // Replace along with your bundle path
``````

)

const apiKey = “HBCPDZ4Q7P5W4QNX”
const image = “RMBS”

kind Candle struct {
Excessive float64
Low float64
Shut float64
}

kind TimeSeries Candle

func NewTimeSeries(knowledge map[string]interface{}) (TimeSeries, error) {
var sequence TimeSeries

``````timeSeriesData, okay := knowledge["Time Series (Daily)"].(map[string]interface{})
if !okay {
return nil, fmt.Errorf("lacking or invalid 'Time Sequence (Day by day)' area in knowledge")
}

for date, dailyData := vary timeSeriesData {
dailyDataMap, okay := dailyData.(map[string]interface{})
if !okay {
return nil, fmt.Errorf("surprising knowledge format for date %s: %+v", date, dailyData)
}

excessive, _ := strconv.ParseFloat(dailyDataMap["2. high"].(string), 64)
low, _ := strconv.ParseFloat(dailyDataMap["3. low"].(string), 64)
shut, _ := strconv.ParseFloat(dailyDataMap["4. close"].(string), 64)

candle := Candle{Excessive: excessive, Low: low, Shut: shut}
sequence = append(sequence, candle)
}

// Reverse the sequence to have the most recent date first
for i, j := 0, len(sequence)-1; i < j; i, j = i+1, j-1 {
sequence[i], sequence[j] = sequence[j], sequence[i]
}

return sequence, nil
``````

}

func essential() {
url := fmt.Sprintf(“https://www.alphavantage.co/question?operate=TIME_SERIES_DAILY&image=%s&apikey=%s”, image, apiKey)
response, err := http.Get(url)
if err != nil {
panic(err)
}
defer response.Physique.Shut()

``````var knowledge map[string]interface{}
err = json.NewDecoder(response.Physique).Decode(&knowledge)
if err != nil {
panic(err)
}

sequence, err := NewTimeSeries(knowledge)
if err != nil {
panic(err)
}

fmt.Printf("%-12s%-12s%-12s%-12s%-12s%-12s%-12sn", "Date", "Open", "Excessive", "Low", "Shut", "preclose", "TR")

// Calculate TR and print knowledge for the final 15 buying and selling days
atrSum := 0.0
validDays := 0
var trValues []float64
for i := 15; i > 0; i-- {
date := getDateNdaysAgo(i)
dailyData, okay := knowledge["Time Series (Daily)"].(map[string]interface{})[date].(map[string]interface{})
if !okay {
// Skip weekends or non-trading days
proceed
}

open, _ := strconv.ParseFloat(dailyData["1. open"].(string), 64)
excessive, _ := strconv.ParseFloat(dailyData["2. high"].(string), 64)
low, _ := strconv.ParseFloat(dailyData["3. low"].(string), 64)
shut, _ := strconv.ParseFloat(dailyData["4. close"].(string), 64)

prevClose := getPreviousClose(sequence, i)

//highLowDiff := excessive - low
//highCloseDiff := excessive - shut
//lowCloseDiff := low - shut

tr := atr.CalculateTrueRange(excessive, low, shut)

fmt.Printf("%-12s%-12.2f%-12.2f%-12.2f%-12.2f%-12.2f%-12.2fn", date, open, excessive, low, shut, prevClose, tr)

if i > 0 {
atrSum += tr
validDays++
trValues = append(trValues, tr)
}
}

// Calculate ATR
atr := atr.CalculateATR(trValues, validDays)
fmt.Printf("nAverage True Vary (ATR) for the final %d buying and selling days: %.2fn", validDays, atr)
``````

}

func getPreviousClose(sequence TimeSeries, index int) float64 {
//if index == 15 {
//return sequence[index].Shut
//}
return sequence[index].Shut
}

func getDateNdaysAgo(n int) string {
at present := time.Now()
for i := 0; i <= n; {
previousDate := at present.AddDate(0, 0, -i)
if previousDate.Weekday() == time.Saturday || previousDate.Weekday() == time.Sunday {
// Skip weekends
at present = at present.AddDate(0, 0, -1)
proceed
}
i++
}
previousDate := at present.AddDate(0, 0, -n)
return previousDate.Format(“2006-01-02”)
}
bundle essential

import (
“encoding/json”
“fmt”
“web/http”
“strconv”
“time”

``````atr "instance/golang/ATR" // Replace along with your bundle path
``````

)

const apiKey = “I do know the api key “
const image = “RMBS”

kind Candle struct {
Excessive float64
Low float64
Shut float64
}

kind TimeSeries Candle

func NewTimeSeries(knowledge map[string]interface{}) (TimeSeries, error) {
var sequence TimeSeries

``````timeSeriesData, okay := knowledge["Time Series (Daily)"].(map[string]interface{})
if !okay {
return nil, fmt.Errorf("lacking or invalid 'Time Sequence (Day by day)' area in knowledge")
}

for date, dailyData := vary timeSeriesData {
dailyDataMap, okay := dailyData.(map[string]interface{})
if !okay {
return nil, fmt.Errorf("surprising knowledge format for date %s: %+v", date, dailyData)
}

excessive, _ := strconv.ParseFloat(dailyDataMap["2. high"].(string), 64)
low, _ := strconv.ParseFloat(dailyDataMap["3. low"].(string), 64)
shut, _ := strconv.ParseFloat(dailyDataMap["4. close"].(string), 64)

candle := Candle{Excessive: excessive, Low: low, Shut: shut}
sequence = append(sequence, candle)
}

// Reverse the sequence to have the most recent date first
for i, j := 0, len(sequence)-1; i < j; i, j = i+1, j-1 {
sequence[i], sequence[j] = sequence[j], sequence[i]
}

return sequence, nil
``````

}

func essential() {
url := fmt.Sprintf(“https://www.alphavantage.co/question?operate=TIME_SERIES_DAILY&image=%s&apikey=%s”, image, apiKey)
response, err := http.Get(url)
if err != nil {
panic(err)
}
defer response.Physique.Shut()

``````var knowledge map[string]interface{}
err = json.NewDecoder(response.Physique).Decode(&knowledge)
if err != nil {
panic(err)
}

sequence, err := NewTimeSeries(knowledge)
if err != nil {
panic(err)
}

fmt.Printf("%-12s%-12s%-12s%-12s%-12s%-12s%-12sn", "Date", "Open", "Excessive", "Low", "Shut", "preclose", "TR")

// Calculate TR and print knowledge for the final 15 buying and selling days
atrSum := 0.0
validDays := 0
var trValues []float64
for i := 15; i > 0; i-- {
date := getDateNdaysAgo(i)
dailyData, okay := knowledge["Time Series (Daily)"].(map[string]interface{})[date].(map[string]interface{})
if !okay {
// Skip weekends or non-trading days
proceed
}

open, _ := strconv.ParseFloat(dailyData["1. open"].(string), 64)
excessive, _ := strconv.ParseFloat(dailyData["2. high"].(string), 64)
low, _ := strconv.ParseFloat(dailyData["3. low"].(string), 64)
shut, _ := strconv.ParseFloat(dailyData["4. close"].(string), 64)

prevClose := getPreviousClose(sequence, i)

//highLowDiff := excessive - low
//highCloseDiff := excessive - shut
//lowCloseDiff := low - shut

tr := atr.CalculateTrueRange(excessive, low, shut)

fmt.Printf("%-12s%-12.2f%-12.2f%-12.2f%-12.2f%-12.2f%-12.2fn", date, open, excessive, low, shut, prevClose, tr)

if i > 0 {
atrSum += tr
validDays++
trValues = append(trValues, tr)
}
}

// Calculate ATR
atr := atr.CalculateATR(trValues, validDays)
fmt.Printf("nAverage True Vary (ATR) for the final %d buying and selling days: %.2fn", validDays, atr)
``````

}

func getPreviousClose(sequence TimeSeries, index int) float64 {
//if index == 15 {
//return sequence[index].Shut
//}
return sequence[index].Shut
}

func getDateNdaysAgo(n int) string {
at present := time.Now()
for i := 0; i <= n; {
previousDate := at present.AddDate(0, 0, -i)
if previousDate.Weekday() == time.Saturday || previousDate.Weekday() == time.Sunday {
// Skip weekends
at present = at present.AddDate(0, 0, -1)
proceed
}
i++
}
previousDate := at present.AddDate(0, 0, -n)
return previousDate.Format(“2006-01-02”)
}

atr script
// atr.go
bundle atr

import (
“math”
)

// CalculateTrueRange calculates the True Vary (TR) for a given candle.
func CalculateTrueRange(excessive, low, shut float64) float64 {
highLowDiff := excessive – low

``````// theses are fallacious, each highclose and lowclose
highCloseDiff := math.Abs(excessive - shut)
lowCloseDiff := math.Abs(low - shut)

//fmt.Printf("high-low distinction: %.2fn", highLowDiff)
//fmt.Printf("high-Shut distinction: %.2fn", highCloseDiff)
//fmt.Printf("low-close distinction: %.2fn", lowCloseDiff)
tr := highLowDiff
if highCloseDiff > tr {
tr = highCloseDiff
}
if lowCloseDiff > tr {
tr = lowCloseDiff
}

return tr
``````

}

// CalculateATR calculates the Common True Vary (ATR) for a given sequence of TR values and a interval.
func CalculateATR(trValues float64, interval int) float64 {
// Guarantee we don’t exceed the size of trValues
if len(trValues) < interval {
interval = len(trValues)
}

``````var sum float64
for i := len(trValues) - interval; i < len(trValues); i++ {
sum += trValues[i]
}

return sum / float64(interval)
``````

}

RELATED ARTICLES