来源:https://www.joinquant.com/view/community/detail/92d2ccab2d412dbfa7df366369e6373b?type=1

import numpy as np
import pandas as pd
import empyrical as ep
import statsmodels.api as smimport alphalens as al
from alphalens import plotting
import alphalens.performance as perffrom jqdata import *
from sqlalchemy.sql import func
from jqfactor import (Factor, calc_factors, neutralize,standardlize, get_factor_values)from functools import reduce
from tqdm import tqdm_notebook
from typing import (Tuple, List)
from dateutil.parser import parseimport seaborn as sns
import matplotlib.pyplot as pltmpl.rcParams['font.family'] = 'serif'  # pd.plot中文
# 用来正常显示负号
mpl.rcParams['axes.unicode_minus'] = False
# 图表主题
plt.style.use('seaborn')
# 蜡烛图import matplotlib.dates as mdate
import matplotlib.ticker as ticker
from matplotlib.path import Path
from matplotlib.patches import PathPatch# 画出蜡烛图
def plot_candlestick(df:pd.DataFrame,title:str='',**kwargs):'''画出蜡烛图-----------price:index-date columns-OHLCindex为datetimekwargs:为pathpatch时则画出需要标记的k线'''df = df.copy()df.index.names = ['date']df = df.reset_index()data = df[['date','open','high','low','close']]# 生成横轴的刻度名字date_tickers = df['date'].dt.strftime('%Y-%m-%d').valuesday_quotes=[tuple([i]+list(quote[1:])) for i,quote in enumerate(data.values)]mpl.rcParams['font.family'] = 'serif'fig, ax = plt.subplots(figsize=(18,4))plt.title(title)def format_date(x,pos=None):if x<0 or x>len(date_tickers)-1:return ''return date_tickers[int(x)]candlestick_ohlc(ax,day_quotes,colordown='g', colorup='r',width=0.2)if 'pathpatch' in kwargs:ax.add_patch(kwargs['pathpatch'])ax.xaxis.set_major_locator(ticker.MultipleLocator(6))ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date));ax.grid(True)# 标记需要标记的K线
def get_mark_data(price:pd.DataFrame,target_date:list):'''标记出k线-----------price:index-date columns-OHLCindex为datetimetarget_date:list 日期格式yyyy-mm-dd'''df = price[['open','high','low','close']].copy()df.index = df.index.strftime('%Y-%m-%d')if isinstance(target_date,list):target_data = [target_date]vertices = []codes = []idx = [df.index.get_loc(i) for i in target_date]for i in idx:low = df['low'].iloc[i] * (1 - 0.001)high = df['high'].iloc[i] * (1 + 0.001)codes += [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY]vertices += [(i - 0.5, low), (i - 0.5, high), (i + 0.5, high), (i + 0.5, low), (i - 0.5, low)]path = Path(vertices, codes)pathpatch = PathPatch(path, facecolor='None', edgecolor='black',lw=2)return pathpatchdef candlestick_ohlc(ax, quotes, width=0.2, colorup='k', colordown='r',alpha=1.0):"""Plot the time, open, high, low, close as a vertical line rangingfrom low to high.  Use a rectangular bar to represent theopen-close span.  If close >= open, use colorup to color the bar,otherwise use colordownParameters----------ax : `Axes`an Axes instance to plot toquotes : sequence of (time, open, high, low, close, ...) sequencesAs long as the first 5 elements are these values,the record can be as long as you want (e.g., it may store volume).time must be in float days format - see date2numwidth : floatfraction of a day for the rectangle widthcolorup : colorthe color of the rectangle where close >= opencolordown : colorthe color of the rectangle where close <  openalpha : floatthe rectangle alpha levelReturns-------ret : tuplereturns (lines, patches) where lines is a list of linesadded and patches is a list of the rectangle patches added"""return _candlestick(ax, quotes, width=width, colorup=colorup,colordown=colordown,alpha=alpha, ochl=False)def _candlestick(ax, quotes, width=0.2, colorup='k', colordown='r',alpha=1.0, ochl=True):"""Plot the time, open, high, low, close as a vertical line rangingfrom low to high.  Use a rectangular bar to represent theopen-close span.  If close >= open, use colorup to color the bar,otherwise use colordownParameters----------ax : `Axes`an Axes instance to plot toquotes : sequence of quote sequencesdata to plot.  time must be in float date format - see date2num(time, open, high, low, close, ...) vs(time, open, close, high, low, ...)set by `ochl`width : floatfraction of a day for the rectangle widthcolorup : colorthe color of the rectangle where close >= opencolordown : colorthe color of the rectangle where close <  openalpha : floatthe rectangle alpha levelochl: boolargument to select between ochl and ohlc ordering of quotesReturns-------ret : tuplereturns (lines, patches) where lines is a list of linesadded and patches is a list of the rectangle patches added"""OFFSET = width / 2.0lines = []patches = []for q in quotes:if ochl:t, open, close, high, low = q[:5]else:t, open, high, low, close = q[:5]if close >= open:color = coloruplower = openheight = close - openelse:color = colordownlower = closeheight = open - closevline = Line2D(xdata=(t, t), ydata=(low, high),color=color,linewidth=0.5,antialiased=True,)rect = Rectangle(xy=(t - OFFSET, lower),width=width,height=height,facecolor=color,edgecolor=color,)rect.set_alpha(alpha)lines.append(vline)patches.append(rect)ax.add_line(vline)ax.add_patch(rect)ax.autoscale_view()return lines, patchesdef _check_input(opens, closes, highs, lows, miss=-1):"""Checks that *opens*, *highs*, *lows* and *closes* have the same length.NOTE: this code assumes if any value open, high, low, close ismissing (*-1*) they all are missingParameters----------ax : `Axes`an Axes instance to plot toopens : sequencesequence of opening valueshighs : sequencesequence of high valueslows : sequencesequence of low valuescloses : sequencesequence of closing valuesmiss : intidentifier of the missing dataRaises------ValueErrorif the input sequences don't have the same length"""def _missing(sequence, miss=-1):"""Returns the index in *sequence* of the missing data, identified by*miss*Parameters----------sequence :sequence to evaluatemiss :identifier of the missing dataReturns-------where_miss: numpy.ndarrayindices of the missing data"""return np.where(np.array(sequence) == miss)[0]same_length = len(opens) == len(highs) == len(lows) == len(closes)_missopens = _missing(opens)same_missing = ((_missopens == _missing(highs)).all() and(_missopens == _missing(lows)).all() and(_missopens == _missing(closes)).all())if not (same_length and same_missing):msg = ("*opens*, *highs*, *lows* and *closes* must have the same"" length. NOTE: this code assumes if any value open, high,"" low, close is missing (*-1*) they all must be missing.")raise ValueError(msg)
# 画美国线
def plot_HLC_bar(df:pd.DataFrame,title:str='',**kwargs):'''画出蜡烛图-----------price:index-date columns-HLCindex为datetimekwargs:为pathpatch时则画出需要标记的k线'''# 主体u_vertices1 = []u_codes1 = []# 辅u_codes2 = []u_vertices2 = []# 主题d_vertices1 = []d_codes1 = []# 辅d_codes2 = []d_vertices2 = []hlc = df.reset_index(drop=True)for idx,row in hlc.iterrows():low = row['low']high = row['high']close = row['close']open_ = row['open']if open_ < close:# 上涨部分u_codes1 += [Path.MOVETO] + [Path.LINETO] u_codes2 += [Path.MOVETO] + [Path.LINETO]u_vertices1 += [(idx, low), (idx, high)]u_vertices2 += [(idx, close), (idx+0.2, close)]else:# 下跌部分d_codes1 += [Path.MOVETO] + [Path.LINETO]d_codes2 += [Path.MOVETO] + [Path.LINETO]d_vertices1 += [(idx, low), (idx, high)]d_vertices2 += [(idx, close), (idx+0.2, close)]# 上涨步伐path1 = Path(u_vertices1, u_codes1)path2 = Path(u_vertices2,u_codes2)bar1 = PathPatch(path1,lw=1.5,edgecolor='red')line1 = PathPatch(path2,lw=0.6,edgecolor='red')# 下跌部分path3 = Path(d_vertices1, d_codes1)path4 = Path(d_vertices2,d_codes2)bar2 = PathPatch(path3,lw=1.5,edgecolor='g')line2 = PathPatch(path4,lw=0.6,edgecolor='g')fig, ax = plt.subplots(figsize=(18,4))plt.title(title)ax.add_patch(bar1)ax.add_patch(line1)ax.add_patch(bar2)ax.add_patch(line2)ax.set_xlim(-0.5, len(df))ax.set_ylim(df['low'].min() * (1 - 0.01), df['high'].max() * (1 + 0.01))if 'pathpatch' in kwargs:ax.add_patch(kwargs['pathpatch'])def format_date(x,pos=None):if x<0 or x>len(date_tickers)-1:return ''return date_tickers[int(x)]date_tickers = df.index.strftime('%Y-%m-%d').valuesax.xaxis.set_major_locator(ticker.MultipleLocator(6))ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))ax.grid(True);
price = get_price('000001.XSHG','2019-10-10','2019-12-25')plot_candlestick(price,'上证指数蜡烛图(2019/10/10-2019/12/25)',pathpatch=get_mark_data(price,['2019-10-14','2019-11-05','2019-12-17']))

plot_HLC_bar(price,'上证指数蜡烛图举例(2020/01/16-2020/02/24)',pathpatch=get_mark_data(price,['2020-01-23','2020-02-04']))

蜡烛图、美国图绘图及标记相关推荐

  1. R语言做统计检验绘图如何添加p-value和显著性标记?——详细介绍如何通过ggpubr包为ggplot图添加p-value以及显著性标记?

    本文转载于:https://zhuanlan.zhihu.com/p/33209557 在R语言在生物信息学的实际应用中,常常需要添加p-value和显著性标记.很多同学对于添加P-value这个问题 ...

  2. 【Excel】绘图案例_常见复合图:簇状图+堆积图+折线图

    [Excel]绘图案例_常见复合图:簇状图+堆积图+折线图 前言 最近有朋友让我帮忙用excel画图,老实说我很讨厌用excel画图,点来点去,复杂一些还不能复用,非常繁琐.当然,入门也很简单.需求时 ...

  3. ExpRe[2] UML,UML类图,UML绘图语言——PlantUML

    文章目录 UML UML类图 UML绘图语言--PlantUML 简介 绘制类图 一个典型示例 基本元素 组合.聚合关系 接口和实现 其它关系 总结与问答练习 时效性 本篇撰写时间为2021.11.9 ...

  4. Flex中如何通过horizontalTickAligned和verticalTickAligned样式指定线图LineChart横竖方向轴心标记的例子...

    原文 http://blog.minidx.com/2008/12/03/1669.html 接下来的例子演示了Flex中如何通过horizontalTickAligned和verticalTickA ...

  5. 14_面向对象API绘图、图中图 (A Plot inside of Another Plot)、设定绘图范围Setting the Plot Range、对数尺度Logarithmic Scale

    14.面向对象API绘图 14.1.图中图 (A Plot inside of Another Plot) 14.2.设定绘图范围 (Setting the Plot Range) 14.3.对数尺度 ...

  6. rtt面向对象oopc——3.对官方IO设备模型框架图的补充绘图

    该补充图有幸得到rt thread官方认可,gitee上已提交PR,且通过了官方评审,已被合并到<IO设备模型>章节末尾的<补充说明>小节里了rt-thread官方文档gite ...

  7. Py之matplotlib-seaborn :核密度估计(KDE)分析/奇异点分析/相关性分析简、绘图的高级进阶之高级图可视化(直方图-箱线图-密度图-小提琴图等)简介、代码实现之详细攻略

    Py之matplotlib-seaborn :核密度估计(KDE)分析/奇异点分析/相关性分析简.绘图的高级进阶之高级图可视化(直方图-箱线图-密度图-小提琴图等)简介.代码实现之详细攻略 目录 根据 ...

  8. revit橄榄山插件出图有管道“翻弯标记”吗?

    revit橄榄山插件出图有管道翻弯标记吗?时常有朋友私信问:有没有管道翻弯标记的插件?或者能不能搞一个这样的功能,橄榄山和建模大师有没有?或者给介绍一个有翻弯标记的revit插件?[笑哭]表情...我 ...

  9. R ggplot2 Excel绘图(直方图/经验分布图/QQ图/茎叶图/箱线图)实例

    持续更新~ 散点图 条形图 文氏图 饼图 盒型图 频率直方图 热图 PCA图 3D图 火山图 分面图 分面制作小多组图 地图 练习数据: year count china Ame jap '12 2. ...

  10. python堆叠面积图_06. Matplotlib 2 |折线图| 柱状图| 堆叠图| 面积图| 填图| 饼图| 直方图| 散点图| 极坐标| 图箱型图...

    1.基本图表绘制 plt.plot() 图表类别:线形图.柱状图.密度图,以横纵坐标两个维度为主 同时可延展出多种其他图表样式 plt.plot(kind='line', ax=None, figsi ...

最新文章

  1. 开发log4j配置_Spring 使用 Log4J 记录日志
  2. Can't use asio::placeholders::error
  3. 前端技术学习路线及技术汇总
  4. I am too vegetable to all kill the 51nod problems on level 2 and 3.
  5. sybase 事务插入时不可查询_InnoDB事务与锁
  6. 给定key值,在Binary Search Tree中查找最接近该键值的结点集合
  7. String 类型切割成数组-转int数组-升列排序-拼接字符串、需求 有如下一个字符串 91 27 46 38 50
  8. Java事务处理总结【JDBC事务|JTA事务|容器事务】
  9. azure linux 磁盘,在Azure Linux VM中,还有什么?什么磁盘收费?
  10. 7 种 JVM 垃圾收集器,Java语言实现核心,看完我跪了
  11. ANIMATION经典小车动画
  12. topic:开发人员眼中的RIA,基于Flash实现
  13. android百度云和谐,视频总被百度云和谐?这个小工具帮你完美解决
  14. gtx780有html接口吗,史上最强显卡供电GTX780入手,纪念给了我人生一堂课的舅妈...
  15. linux怎么查看hwaddr_Linux 查看网卡的MAC地址
  16. 《互联网信贷风险与大数据》读书笔记(四)
  17. 【BP靶场portswigger-服务端5】业务逻辑漏洞-11个实验(全)
  18. ThinkPad加装SSD固态硬盘/内存条 系统迁移
  19. postgresql 查看用户名
  20. 芜湖今年小升初计算机考试,刚刚!芜湖幼升小、小升初网上报名时间定了!附报名流程和具体安排...

热门文章

  1. ucsd大学音乐计算机,音乐留学│综合名校UCSD音乐制作专业详解!
  2. openssh linux 下载,OpenSSH 下载与配置
  3. caffe常用层:Reduction层
  4. C++性能之战(1)--深入到汇编看++i、i++、i+=1、i=i+1的区别
  5. oracle加入生僻字,ORACLE数据库中如何插入生僻字
  6. MATLAB入门与作图
  7. Kubespray安装kubernetes
  8. 修改射手影音播放器字幕保存路径的两种方法
  9. php免费短信接,PHP实现飞信接口来通过网页免费发短信
  10. 上海大学计算机跨考限制,注意:跨考专业有限制!这些你必须要了解!