2

I get some strange result when I try plotting a DataFrame. When I plot the starting graph it works great.

using DataFrames, XLSX, StatsPlots, Indicators

df = DataFrame(XLSX.readtable("Demo-sv.xlsx", "Blad3")...)
df[!, :Closeprice] .= Float64.(df.Closeprice)

Example of the data

1×2 DataFrame
│ Row │ Date       │ Closeprice │
│     │ Any        │ Float64    │
├─────┼────────────┼────────────┤
│ 1   │ 2019-05-03 │ 169.96     │    

Then I plot the data

@df df plot(df.Date, df.Closeprice)

The DataFrame graph

But when I try to add a new plot (a simple moving average (sma())), I get some really strange result. The dates isn't correct anymore, and the graph looks weird. I don't know if my new plot is somehow overwriting the original even if it should add to the existing plot?

I have tried to use both functions down below to add the new plot, but both gives the same result.

plot!(sma(df.Closeprice, n=200))
plot!(sma(sort(df, :Date).Closeprice, n=200))

But I have gotten the same result, where the graph just looks strange. And I don't know what is causing this problem.

enter image description here

hbrovell
  • 547
  • 6
  • 17

1 Answers1

2

The reason is because you are plotting your new plot vs the date starting from Date(1) which is 0001-01-01. You need to plot plot!(df.Date, sma(df.Closeprice, n=200)).

By the way, calling the entry Date is not best practice, as Date is already the name of the DataType.

Oskar
  • 1,371
  • 6
  • 19
  • So my new plot didn't use the df.date, instead used a default date? And yes of course I should change the ```Date``` entry to something better. – hbrovell Dec 21 '20 at 18:29
  • 1
    Yes, I guess your new plot was something like `plot!(Date.(collect(1:length(df.Closeprice))), sma(df.Closeprice, n=200))` – Oskar Dec 21 '20 at 18:32
  • 1
    Sorry, actually it is more like: `plot!(Date(1) .+ Dates.Day.(collect(1:length(df.Closeprice))), sma(df.Closeprice,n=200))`. Plotting without any x value increases the x value by 1 day for every y value. `Day(2)` is however year 2 – Oskar Dec 21 '20 at 18:42