python生成K线图,仅供自己复习使用

2 篇文章 0 订阅

import datetime as dt
import numpy as np
import matplotlib.pyplot as mp
import matplotlib.dates as md


def dmy2ymd(dmy):
    dmy = str(dmy, encoding='utf-8')
    date = dt.datetime.strptime(dmy, '%d-%m-%Y').date()
    ymd = date.strftime('%Y-%m-%d')

    return ymd
dates, opening_prices, highest_prices, lowest_prices, closing_prices \
    = np.loadtxt(
        'C:/Users/Administrator/Desktop/DS/data/aapl.csv',
        delimiter=',', usecols=(1, 3, 4, 5, 6), unpack=True,
        dtype='M8[D],f8,f8,f8,f8', converters={1: dmy2ymd})
mp.figure('Candlestick', facecolor='lightgray')
mp.title('Camdlestick', fontsize=20)
mp.xlabel('Date', fontsize=14)
mp.ylabel('Price', fontsize=14)
ax = mp.gca()
ax.xaxis.set_major_locator(md.WeekdayLocator(byweekday=md.MO))
ax.xaxis.set_minor_locator(md.DayLocator())
ax.xaxis.set_major_formatter(md.DateFormatter('%d %b %Y'))
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
dates = dates.astype(md.datetime.datetime)
rise = closing_prices - opening_prices >= 0.01
fall = opening_prices - closing_prices >= 0.01
fc = np.zeros(dates.size, dtype='3f4')
ec = np.zeros(dates.size, dtype='3f4')
fc[rise] = (1, 1, 1)
fc[fall] = (0, 0.5, 0)
ec[rise] = (1, 0, 0)
ec[fall] = (0, 0.5, 0)
mp.bar(dates, highest_prices - lowest_prices, 0, lowest_prices, color=fc,
       edgecolor=ec)
mp.bar(dates, closing_prices - opening_prices, 0.8, opening_prices, color=fc,
       edgecolor=ec)
mp.gcf().autofmt_xdate()
mp.show()

运行结果:

文本参考样式:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值