python
import mplfinance as mpf
import pandas as pd
import numpy as np
# 构造随机K线数据
dates = pd.date_range('20210101', periods=100)
ohlc = np.random.rand(100, 4) * 100
df = pd.DataFrame(ohlc, columns=['Open', 'High', 'Low', 'Close'], index=dates)
# 构造买入、卖出点
buy_dates = ['20210105', '20210112', '20210122', '20210126', '20210201']
sell_dates = ['20210107', '20210115', '20210125', '20210128', '20210205']
df['buy'] = np.where(df.index.isin(buy_dates), df['Low'], np.nan)
df['sell'] = np.where(df.index.isin(sell_dates), df['High'], np.nan)
# 绘制K线图,并标注买入、卖出点
colors = mpf.make_marketcolors(up='red', down='green')
style = mpf.make_mpf_style(marketcolors=colors)
mpf.plot(df, type='candle', style=style, title='Stock K Lines',
ylabel='Price', figratio=(12, 6), figscale=1.2, addplot=[
mpf.make_addplot(df['buy'], type='scatter', markersize=100, marker='^'),
mpf.make_addplot(df['sell'], type='scatter', markersize=100, marker='v'),
])