我正在try 绘制烛台图,数据如下:

               openDateTime open    high    low close
1763    2023-11-04 20:45:00 34735.1 34758.6 34735.1 34751.9
1764    2023-11-04 21:00:00 34751.8 34764.1 34749.4 34761.5
1765    2023-11-04 21:15:00 34761.6 34894.0 34761.5 34858.4
1766    2023-11-04 21:30:00 34858.4 34880.9 34812.0 34825.9
1767    2023-11-04 21:45:00 34826.0 34826.0 34795.4 34801.0


Data columns (total 5 columns):
 #   Column           Non-Null Count  Dtype         
---  ------           --------------  -----         
 0   openDateTime     5 non-null      datetime64[ns]
 1   open             5 non-null      float64       
 2   high             5 non-null      float64       
 3   low              5 non-null      float64       
 4   close            5 non-null      float64       
dtypes: datetime64[ns](1), float64(4)

然而,在try 使用mpl_dates.date2numopenDateTime转换为matplotlib日期时间时,我得到了不正确的结果.

我的完整代码如下,图表不正确:

import matplotlib.pyplot as plt
from mplfinance.original_flavor import candlestick_ohlc
import pandas as pd
import matplotlib.dates as mpdates
 
df['openDateTime'] = df['openDateTime'].apply(mpl_dates.date2num) #<-- this is where I think incorrect conversion occurs but this is due to  df['openDateTime'] being in incorrect format for .apply(mpl_dates.date2num) ???
# creating Subplots
fig, ax = plt.subplots()
 
# plotting the data
candlestick_ohlc(ax, df.values, width = 0.6,
                 colorup = 'green', colordown = 'red', 
                 alpha = 0.8)
 
# allow grid
ax.grid(True)
 
# Setting labels 
ax.set_xlabel('openDateTime')
ax.set_ylabel('open')
 
date_format = mpdates.DateFormatter('%d-%m-%Y %H:%m:%S')
ax.xaxis.set_major_formatter(date_format)
fig.autofmt_xdate()
 
fig.tight_layout()
 
# show the plot
plt.show()

enter image description here

转换为openDateTime后,df如下所示:

openDateTime    open    high    low close
1764    19665.875000    34751.8 34764.1 34749.4 34761.5
1765    19665.885417    34761.6 34894.0 34761.5 34858.4
1766    19665.895833    34858.4 34880.9 34812.0 34825.9
1767    19665.906250    34826.0 34826.0 34795.0 34798.3
1768    19665.916667    34798.3 34930.0 34798.3 34894.0

Data columns (total 5 columns):
 #   Column        Non-Null Count  Dtype  
---  ------        --------------  -----  
 0   openDateTime  5 non-null      float64
 1   open          5 non-null      float64
 2   high          5 non-null      float64
 3   low           5 non-null      float64
 4   close         5 non-null      float64

或者,我也可以有unix时间戳在ms为openDateTime,如果这有助于无论如何转换:

         openTimeUnixMs openDateTime    open    high    low close
1764    1699131600000   2023-11-04 21:00:00 34751.8 34764.1 34749.4 34761.5
1765    1699132500000   2023-11-04 21:15:00 34761.6 34894.0 34761.5 34858.4
1766    1699133400000   2023-11-04 21:30:00 34858.4 34880.9 34812.0 34825.9
1767    1699134300000   2023-11-04 21:45:00 34826.0 34826.0 34795.0 34798.3
1768    1699135200000   2023-11-04 22:00:00 34798.3 34930.0 34798.3 34894.0  

推荐答案

据我所知,你身材的问题似乎是每根杠都太宽了.candlestick_ohlc‘S width参数将矩形宽度控制为day的分数.由于您的数据频率是15分钟,因此相应地调整宽度,使基数从1D到15分钟(即一天的1/96).

import io
import pandas as pd
from mplfinance.original_flavor import candlestick_ohlc
import matplotlib.pyplot as plt
import matplotlib.dates as mpl_dates

x = """
               openDateTime    open    high     low   close
1763    2023-11-04 20:45:00 34735.1 34758.6 34735.1 34751.9
1764    2023-11-04 21:00:00 34751.8 34764.1 34749.4 34761.5
1765    2023-11-04 21:15:00 34761.6 34894.0 34761.5 34858.4
1766    2023-11-04 21:30:00 34858.4 34880.9 34812.0 34825.9
1767    2023-11-04 21:45:00 34826.0 34826.0 34795.4 34801.0
"""

df = pd.read_fwf(io.StringIO(x), index_col=[0])
df['openDateTime'] = pd.to_datetime(df['openDateTime'])
df['openDateTime'] = df['openDateTime'].apply(mpl_dates.date2num)

fig, ax = plt.subplots(figsize=(6,4))
_ = candlestick_ohlc(
    ax, df.values, width=1/96*0.6,     # <--- set base width to be 15min
    colorup='green', colordown='red', alpha=0.8)
ax.grid(True)
ax.set(xlabel='openDateTime', ylabel='open')
date_format = mpl_dates.DateFormatter('%d-%m-%Y %H:%m:%S')
ax.xaxis.set_major_formatter(date_format)
fig.autofmt_xdate()
fig.show()

output

Python相关问答推荐

Flask主机持续 bootstrap 本地IP| Python

在Transformer中使用LabelEncoding的ML模型管道

如何将带有逗号分隔的数字的字符串解析为int Array?

Matplotlib轮廓线值似乎不对劲

是什么导致对Python脚本的jQuery Ajax调用引发500错误?

使用GEKKO在简单DTE系统中进行一致初始化

理解Python的二分库:澄清bisect_left的使用

使用plotnine和Python构建地块

Gekko:Spring-Mass系统的参数识别

ModuleNotFound错误:没有名为flags.State的模块; flags不是包

用合并列替换现有列并重命名

使用setuptools pyproject.toml和自定义目录树构建PyPi包

如何在Python脚本中附加一个Google tab(已经打开)

DataFrames与NaN的条件乘法

移动条情节旁边的半小提琴情节在海运

Django—cte给出:QuerySet对象没有属性with_cte''''

合并帧,但不按合并键排序

从Windows Python脚本在WSL上运行Linux应用程序

在Python中使用if else或使用regex将二进制数据如111转换为001""

如何找出Pandas 图中的连续空值(NaN)?