在 Julia 中绘制数据框上的简单移动平均线
Plot simple moving average over dataframe in Julia
我有一个包含日期和股票价格的 excel 文件。我用 DataFrames.jl
将这些数据读入数据框
using DataFrames, StatsPlots, Indicators
df = DataFrame(XLSX.readtable("Demo-sv.xlsx", "Blad3")...)
效果很好,我在这里打印前 6 个条目。
6×2 DataFrame
│ Row │ Date │ Closeprice │
│ │ Any │ Any │
├─────┼────────────┼────────────┤
│ 1 │ 2019-05-03 │ 169.96 │
│ 2 │ 2019-05-02 │ 168.06 │
│ 3 │ 2019-04-30 │ 165.58 │
│ 4 │ 2019-04-29 │ 166.4 │
│ 5 │ 2019-04-26 │ 167.76 │
│ 6 │ 2019-04-25 │ 167.46 │
然后我用 StatsPlots.jl @df df plot(df.Date, df.Closeprice)
绘制这些数据并得到一个漂亮的绘图图。
问题是当我想用 Indicators.jl
绘制一个简单的移动平均线时
movingaverage = sma(df, n=200)
plot!(movingaverage, linewidth=2, color=:red)
我收到此错误消息
ERROR: LoadError: MethodError: no method matching sma(::DataFrame; n=200)
Closest candidates are:
sma(::Array{T,N} where N; n) where T<:Real at
/Users/HBrovell/.julia/packages/Indicators/QGmEX/src/ma.jl:8
sma(::Temporal.TS{V,T}; args...) where {V, T} at
/Users/HBrovell/.julia/packages/Indicators/QGmEX/src/temporal.jl:64
据我了解,我需要转换 DataFrame 以便能够使用 Indicators.jl sma 函数。我曾尝试使用 convert(Array{Float64}, df[2])
仅转换 Closeprice 列,但这并没有按照我想要的方式工作。我想我不想转换日期列?
那么如何转换DataFrame,这样我就可以在Indicators.jl中使用sma函数,或者有比使用DataFrames.jl更好的方法吗?
我假设你需要的是:
sma(sort(df, :Date).ClosePrice, n=200)
您遇到的另一个问题是 ClosePrice
列的数据类型应该是数字而不是 Any
您需要以某种方式转换它,例如:
df[!, :ClosePrice] .= Float64.(df.ClosePrice)
我有一个包含日期和股票价格的 excel 文件。我用 DataFrames.jl
将这些数据读入数据框using DataFrames, StatsPlots, Indicators
df = DataFrame(XLSX.readtable("Demo-sv.xlsx", "Blad3")...)
效果很好,我在这里打印前 6 个条目。
6×2 DataFrame
│ Row │ Date │ Closeprice │
│ │ Any │ Any │
├─────┼────────────┼────────────┤
│ 1 │ 2019-05-03 │ 169.96 │
│ 2 │ 2019-05-02 │ 168.06 │
│ 3 │ 2019-04-30 │ 165.58 │
│ 4 │ 2019-04-29 │ 166.4 │
│ 5 │ 2019-04-26 │ 167.76 │
│ 6 │ 2019-04-25 │ 167.46 │
然后我用 StatsPlots.jl @df df plot(df.Date, df.Closeprice)
绘制这些数据并得到一个漂亮的绘图图。
问题是当我想用 Indicators.jl
绘制一个简单的移动平均线时movingaverage = sma(df, n=200)
plot!(movingaverage, linewidth=2, color=:red)
我收到此错误消息
ERROR: LoadError: MethodError: no method matching sma(::DataFrame; n=200)
Closest candidates are:
sma(::Array{T,N} where N; n) where T<:Real at
/Users/HBrovell/.julia/packages/Indicators/QGmEX/src/ma.jl:8
sma(::Temporal.TS{V,T}; args...) where {V, T} at
/Users/HBrovell/.julia/packages/Indicators/QGmEX/src/temporal.jl:64
据我了解,我需要转换 DataFrame 以便能够使用 Indicators.jl sma 函数。我曾尝试使用 convert(Array{Float64}, df[2])
仅转换 Closeprice 列,但这并没有按照我想要的方式工作。我想我不想转换日期列?
那么如何转换DataFrame,这样我就可以在Indicators.jl中使用sma函数,或者有比使用DataFrames.jl更好的方法吗?
我假设你需要的是:
sma(sort(df, :Date).ClosePrice, n=200)
您遇到的另一个问题是 ClosePrice
列的数据类型应该是数字而不是 Any
您需要以某种方式转换它,例如:
df[!, :ClosePrice] .= Float64.(df.ClosePrice)