量化编程技术—matplotlib与可视化

import matplotlib.pyplot as plt
import numpy as np
 
from mpl_toolkits.mplot3d import Axes3D
 
np.random.seed(42)
 
# 采样个数500
n_samples = 500
dim = 3
 
# 先生成一组3维正态分布数据,数据方向完全随机
samples = np.random.multivariate_normal(
    np.zeros(dim),
    np.eye(dim),
    n_samples
)
 
# 通过把每个样本到原点距离和均匀分布吻合得到球体内均匀分布的样本
for i in range(samples.shape[0]):
    r = np.power(np.random.random(), 1.0/3.0)
    samples[i] *= r / np.linalg.norm(samples[i])
 
upper_samples = []
lower_samples = []
 
for x, y, z in samples:
    # 3x+2y-z=1作为判别平面
    if z > 3*x + 2*y - 1:
        upper_samples.append((x, y, z))
    else:
        lower_samples.append((x, y, z))
 
fig = plt.figure('3D scatter plot')
ax = fig.add_subplot(111, projection='3d')
 
uppers = np.array(upper_samples)
lowers = np.array(lower_samples)
 
# 用不同颜色不同形状的图标表示平面上下的样本
# 判别平面上半部分为红色圆点,下半部分为绿色三角
ax.scatter(uppers[:, 0], uppers[:, 1], uppers[:, 2], c='r', marker='o')
ax.scatter(lowers[:, 0], lowers[:, 1], lowers[:, 2], c='g', marker='^')
 
plt.show()
import numpy as np
import pandas as pd
import warnings
warnings.filterwarnings("ignore")

import matplotlib as mpl
import tushare as ts
import matplotlib.pyplot as plt
import matplotlib.finance as mpf
from matplotlib import rc
from matplotlib.pylab import date2num
from datetime import datetime, timedelta

# 示例序列
demo_list = np.array([2, 4, 16, 20])
# 以三天为周期计算波动
demo_window = 3
std = pd.rolling_std(demo_list, window=demo_window, center=False) * np.sqrt(demo_window)
print(std)


today = datetime.now().strftime('%Y-%m-%d')
before = (datetime.now() - timedelta(days = 120)).strftime('%Y-%m-%d') #120自然日,大概80个交易日

#获取行情数据,格式: pandas.core.frame.DataFrame
code = '000063'
tsla_df = ts.get_k_data(code, start = before, end = today)


tsla_df_copy = tsla_df.copy()
# 投资回报
tsla_df_copy['return'] = np.log(tsla_df['close'] / tsla_df['close'].shift(1))

# 移动收益标准差
tsla_df_copy['mov_std'] = pd.rolling_std(tsla_df_copy['return'],
                                         window=20,
                                         center=False) * np.sqrt(20)
# 加权移动收益标准差,与移动收益标准差基本相同,只不过根据时间权重计算std
tsla_df_copy['std_ewm'] = pd.ewmstd(tsla_df_copy['return'], span=20,
                                    min_periods=20,
                                    adjust=True) * np.sqrt(20)

tsla_df_copy[['close', 'mov_std', 'std_ewm', 'return']].plot(subplots=True, grid=True);
import numpy as np
import pandas as pd

import matplotlib as mpl
import tushare as ts
import matplotlib.pyplot as plt
import matplotlib.finance as mpf
from matplotlib import rc
from matplotlib.pylab import date2num
from datetime import datetime, timedelta

today = datetime.now().strftime('%Y-%m-%d')
before = (datetime.now() - timedelta(days = 120)).strftime('%Y-%m-%d') #120自然日,大概80个交易日

#获取行情数据,格式: pandas.core.frame.DataFrame
code = '000063'
tsla_df = ts.get_k_data(code, start = before, end = today)

tsla_df.close.plot()
# ma 30
# pd.rolling_mean(tsla_df.close, window=30).plot()
pd.rolling_mean(tsla_df.close, window=30).plot()
# ma 60
# pd.rolling_mean(tsla_df.close, window=60).plot()
pd.rolling_mean(tsla_df.close, window=60).plot()
# ma 90
# pd.rolling_mean(tsla_df.close, window=90).plot()
pd.rolling_mean(tsla_df.close, window=90).plot()
# loc='best'即自动寻找适合的位置
plt.legend(['close', '30 mv', '60 mv', '90 mv'], loc='best');
import warnings
warnings.filterwarnings("ignore")

import numpy as np
import pandas as pd

import matplotlib as mpl
import tushare as ts
import matplotlib.pyplot as plt
import matplotlib.finance as mpf
from matplotlib import rc
from matplotlib.pylab import date2num
from datetime import datetime, timedelta

today = datetime.now().strftime('%Y-%m-%d')
before = (datetime.now() - timedelta(days = 120)).strftime('%Y-%m-%d') #120自然日,大概80个交易日


code = '000063'
tsla_df = ts.get_k_data(code, start = before, end = today)  #获取行情数据,格式: pandas.core.frame.DataFrame
# tsla_df = ts.get_hist_data(code, start = before, end = today)


def plot_trade(buy_date, sell_date):
    # 找出2014-07-28对应时间序列中的index作为start
    start = tsla_df[tsla_df.index == buy_date].key.values[0]
    # 找出2014-09-05对应时间序列中的index作为end
    end = tsla_df[tsla_df.index == sell_date].key.values[0]
    
    # 使用5.1.1封装的绘制tsla收盘价格时间序列函数plot_demo
    # just_series=True, 即只绘制一条曲线使用series数据
    plot_demo(just_series=True)

    # 将整个时间序列都填充一个底色blue,注意透明度alpha=0.08是为了
    # 之后标注其他区间透明度高于0.08就可以清楚显示
    plt.fill_between(tsla_df.index, 0, tsla_df['close'], color='blue',
                     alpha=.08)

    # 标注股票持有周期绿色,使用start和end切片周期
    # 透明度alpha=0.38 > 0.08
    plt.fill_between(tsla_df.index[start:end], 0,
                     tsla_df['close'][start:end], color='green',
                     alpha=.38)
    
    # 设置y轴的显示范围,如果不设置ylim,将从0开始作为起点显示,效果不好
    plt.ylim(np.min(tsla_df['close']) - 5,
             np.max(tsla_df['close']) + 5)
    # 使用loc='best'
    plt.legend(['close'], loc='best')

# 标注交易区间2014-07-28到2014-09-05, 图5-12所示
plot_trade('2018-01-01', '2018-01-30')
import warnings
warnings.filterwarnings("ignore")

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd


import tushare as ts
from datetime import datetime, timedelta

today = datetime.now().strftime('%Y-%m-%d')
before = (datetime.now() - timedelta(days = 240)).strftime('%Y-%m-%d') #120自然日,大概80个交易日

tsla_df = ts.get_k_data("000063", start = before, end = today)  #获取行情数据,格式: pandas.core.frame.DataFrame
goog_df = ts.get_k_data("600036", start = before, end = today)
appl_df = ts.get_k_data("000001", start = before, end = today)


def plot_two_stock(tsla, goog, appl, axs=None):
    # 如果有传递子画布,使用子画布,否则plt
    drawer = plt if axs is None else axs
    drawer.plot(tsla, c='r')
    drawer.plot(goog, c='g')
    drawer.plot(appl, c='b')
    drawer.grid(True)   # 显示网格
    drawer.legend(['tsla', 'google','apple'], loc='best')   # 图例标注


plot_two_stock(tsla_df.close, goog_df.close, appl_df.close)
plt.title('TSLA and Google CLOSE')
plt.xlabel('time')  # x轴时间
plt.ylabel('close') # y轴收盘价格
import matplotlib as mpl
import tushare as ts
import matplotlib.pyplot as plt
import matplotlib.finance as mpf
from matplotlib import rc
from matplotlib.pylab import date2num
from datetime import datetime, timedelta

today = datetime.now().strftime('%Y-%m-%d')
before = (datetime.now() - timedelta(days = 90)).strftime('%Y-%m-%d') #120自然日,大概80个交易日

#获取行情数据,格式: pandas.core.frame.DataFrame
code = '000063'
tsla_df = ts.get_k_data(code, start = before, end = today)
# print(tsla_df)

'''
蜡烛图的日期,不支持普通的YYYY-MM-DD格式
要使用matplotlib.finance.date2num进行转换为特有的数字值
'''
qutotes = []
for _, (d, o, c, h, l) in enumerate(
        zip(tsla_df.date, tsla_df.open, tsla_df.close, tsla_df.high, tsla_df.low)):
    d = mpf.date2num(datetime.strptime(d,'%Y-%m-%d'))
    # 日期,开盘,收盘,最高,最低组成tuple对象val
    val = (d, o, h, l, c)
    # 加val加入qutotes
    qutotes.append(val)



fig, ax = plt.subplots(figsize=(15,5))      #设置图片大小
fig.subplots_adjust(bottom=0.5)             #调整画框的位置,用来消除白边

ax.xaxis_date()                             # X轴的刻度为日期
plt.xticks(rotation=45)                     # 设置日期刻度旋转的角度 
plt.title(code)                         # 设置图片标题
plt.xlabel('Date')                          # 设置X轴标题
plt.ylabel('Price')                         # 设置Y轴标题
plt.grid(True)                              # 显示网格

mpf.candlestick_ohlc(ax, qutotes, width=0.6, colorup='g', colordown='r', alpha=1.0)
plt.show()
原文地址:https://www.cnblogs.com/bitquant/p/11521564.html