请 [注册] 或 [登录]  | 返回主站

量化交易吧 /  数理科学 帖子:3364681 新帖:2

简单几行代码,绘制K线与均线

量化客发表于:5 月 9 日 20:42回复(1)

Img

# 导入必备模块
import matplotlib.finance as mpf
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
sns.set()
def show_ma_kline(security = '000300.XSHG', start_date=None, end_date=None, count=None, FastWindow = 7, ExtraPct = 1.0):
    """
    在图一个画布上绘制K线与均线
    """
    
    #  条件约束
    if start_date is not None:
        count = None
    elif count is not None:
        start_date = None
    
    # 价格信息
    price = get_price(security, start_date=start_date, end_date=end_date, count=count)

    # 创建画布
    fig, ax = plt.subplots(figsize=(20, 10))
    
    # 绘制K线
    qutotes = []
    for index, (d, o, c, h, l) in enumerate(zip(price.index,
                                                price['open'],
                                                price['close'],
                                                price['high'],
                                                price['low'])):
        d = mpf.date2num(d)
        val = (d, o, c, h, l)
        qutotes.append(val)
    mpf.candlestick_ochl(ax, qutotes, width=0.6, colorup='red', colordown='black')
    ax.autoscale_view()
    ax.xaxis_date()
    
    # 绘制移动平均线
    index_date = np.array([mpf.date2num(dt) for dt in price.index])
    ma_df = pd.DataFrame()
    for ma in [5, 10, 20, 30, 60, 120]:
        ma_df['ma'+str(ma)] = pd.rolling_mean(price['close'], ma)  
    ma_df.plot(ax=ax, x=index_date)

    plt.show()
show_ma_kline(security='000300.XSHG', end_date='2015-8-5', count=100)
 

全部回复

0/140

量化课程

    移动端课程