1

我有一个数据框,其列为

['Datetime', 'Open', 'High', 'Low', 'Close', 'Symbol']

我想使用烛台_ohlc 绘制 OHLC 图表。此处的示例数据: 数据

我的代码如下:

import pandas as pd
import numpy as np
import time, os, math
from datetime import datetime
from mpl_finance import candlestick_ohlc
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

########################################
pd.set_option('display.max_rows', 50000)
pd.set_option('display.max_columns', 100)
pd.set_option('display.width', 10000)
########################################


def roundup(x):
    return int(math.ceil(x / 100.0)) * 100


df = pd.read_csv(os.path.join(os.getcwd(), "BN\\", "BANKNIFTY2020JANJUNTEST.txt"))
cols = ['Open', 'High', 'Low', 'Close']
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce', axis=1).fillna(0)

df['Datetime'] = pd.to_datetime(df['Date'] + ' ' + df['Time'], format='%d-%m-%Y %H:%M:%S')
df.Datetime = pd.to_datetime(df.Datetime)
df["Datetime"] = df["Datetime"].apply(mdates.date2num)

df = df[['Datetime', 'Open', 'High', 'Low', 'Close', 'Symbol']]
print(df)

fig = plt.figure(figsize=(20, 10))
ax = plt.subplot2grid((6, 6), (0, 0), colspan=6, rowspan=6)

candlestick_ohlc(ax, df.values, width=0.6 / (9 * 12), colorup='limegreen', colordown='#ff1717')

xmin = int(df["Datetime"].iloc[0]) + 0.30
xmax = int(df["Datetime"].iloc[-1]) + 0.80
print(xmax, xmin)

p_range = roundup(df['High'].max() - df['Low'].min())
if p_range < 700:
    ymid = roundup((df['High'].max() + df['Low'].min()) / 2)
    ymin = ymid + 380
    ymax = ymid - 400
else:
    ymin = roundup(df['High'].max() + 100)
    ymax = roundup(df['Low'].min() - 100)


ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
xformatter = mdates.DateFormatter('%H:%M')
xlocator = mdates.MinuteLocator(byminute=[0, 15, 30, 45], interval=1)
ax.xaxis.set_major_locator(xlocator)
ax.set_xlim([xmin, xmax])
ax.set_ylim([ymax, ymin])
plt.gcf().axes[0].xaxis.set_major_formatter(xformatter)
ax.grid(which='major', alpha=0.40, linestyle='--', color='y')
major_ticks = np.arange(ymax, ymin, 50)
ax.set_yticks(major_ticks)
ax.tick_params(labelright=True)

plt.subplots_adjust(left=0.05, bottom=0.06, right=0.95, top=0.96, hspace=0.00, wspace=0.05)

plt.show()
plt.close(fig)

我的输出如下所示: 输出

如何删除两个日期之间的空白,我想用一条水平线分隔这两天。需要保持时间间隔分隔符为 byminute=[0, 15, 30, 45]。任何帮助。

4

1 回答 1

1

有一个新版本的 matplotlib Finance 会自动为您执行此操作。试试这个:https ://pypi.org/project/mplfinance/

于 2020-01-17T20:44:02.877 回答