在 Julia 中的数据帧上绘制简单移动平均值

hbr*_*ell 6 julia julia-dataframe julia-plots

我有一个包含日期和股票价格的 Excel 文件。我使用 DataFrames.jl 将此数据读入数据帧

\n
using DataFrames, StatsPlots, Indicators\n\ndf = DataFrame(XLSX.readtable("Demo-sv.xlsx", "Blad3")...)\n
Run Code Online (Sandbox Code Playgroud)\n

这非常有效,我在这里打印了前 6 个条目。

\n
6\xc3\x972 DataFrame\n\xe2\x94\x82 Row \xe2\x94\x82 Date       \xe2\x94\x82 Closeprice \xe2\x94\x82\n\xe2\x94\x82     \xe2\x94\x82 Any        \xe2\x94\x82 Any        \xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xa4\n\xe2\x94\x82 1   \xe2\x94\x82 2019-05-03 \xe2\x94\x82 169.96     \xe2\x94\x82\n\xe2\x94\x82 2   \xe2\x94\x82 2019-05-02 \xe2\x94\x82 168.06     \xe2\x94\x82\n\xe2\x94\x82 3   \xe2\x94\x82 2019-04-30 \xe2\x94\x82 165.58     \xe2\x94\x82\n\xe2\x94\x82 4   \xe2\x94\x82 2019-04-29 \xe2\x94\x82 166.4      \xe2\x94\x82\n\xe2\x94\x82 5   \xe2\x94\x82 2019-04-26 \xe2\x94\x82 167.76     \xe2\x94\x82\n\xe2\x94\x82 6   \xe2\x94\x82 2019-04-25 \xe2\x94\x82 167.46     \xe2\x94\x82\n
Run Code Online (Sandbox Code Playgroud)\n

然后我使用 StatsPlots.jl 绘制这些数据@df df plot(df.Date, df.Closeprice)并得到一个漂亮的绘图。

\n

问题是当我想用 Indicators.jl 绘制简单的移动平均线时

\n
movingaverage = sma(df, n=200)\nplot!(movingaverage, linewidth=2, color=:red)\n
Run Code Online (Sandbox Code Playgroud)\n

我收到此错误消息

\n
ERROR: LoadError: MethodError: no method matching sma(::DataFrame; n=200)\nClosest candidates are:\nsma(::Array{T,N} where N; n) where T<:Real at \n/Users/HBrovell/.julia/packages/Indicators/QGmEX/src/ma.jl:8\nsma(::Temporal.TS{V,T}; args...) where {V, T} at \n/Users/HBrovell/.julia/packages/Indicators/QGmEX/src/temporal.jl:64\n
Run Code Online (Sandbox Code Playgroud)\n

据我了解,我需要转换 DataFrame,以便我能够使用 Indicators.jl sma 函数。我尝试convert(Array{Float64}, df[2])过只转换 Closeprice 列,但这并没有按照我想要的方式工作。我想我不想转换日期列?

\n

那么如何转换 DataFrame,以便我可以使用 Indicators.jl 中的 sma 函数,或者是否有比使用 DataFrames.jl 更好的方法?

\n

Prz*_*fel 5

我假设你需要的是:

sma(sort(df, :Date).ClosePrice, n=200)
Run Code Online (Sandbox Code Playgroud)

您遇到的另一个问题是ClosePrice列的数据类型应该是数字而不是Any

您需要以某种方式将其转换,例如:

df[!, :ClosePrice] .= Float64.(df.ClosePrice)
Run Code Online (Sandbox Code Playgroud)