绘制MACD线和直方图python

时间:2019-12-24 01:14:00

标签: python matplotlib

我有一个python脚本,可读取CSV文件库存数据(选择文件并检索库存特定数据)。我在绘制直方图(MACD和信号之间的差异)时遇到麻烦。我正在使用Matplotlib进行绘图。我的代码如下所示。我希望能够绘制绿色以上的零值和红色以下的值。任何帮助将不胜感激。

from pathlib import Path
import numpy as np
import pandas as pd
pd.options.plotting.matplotlib.register_converters
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.dates as mdates
from mpl_finance import candlestick_ohlc
import datetime
from datetime import timedelta


# Define the symbol list
symbol = []
# Select file to access
filename = input('Enter the name of file to access  ')
stockList = filename+'.txt'
print(stockList)

with open('D:\\om\\python_stock_script\\'+stockList)as f:
    for line in f:
        symbol.append(line.strip())
f.close()
# Enter the index for the stock of interest as integer
i = int(input('Enter an integer for stock ID'))
stock = symbol[i]
# Print the symbol for the selected stock
print(stock)
# Specify the path for the data directory
file_path = Path('D:\\om\\python_stock_data\\'+filename)
print(file_path)
stock_data_file = stock+'.csv'
# Define the specific csv file to open
full_file_path = (file_path/stock_data_file)
print(full_file_path)    
# Load the data for the stock from the csv file
df = pd.read_csv(full_file_path)
# Get Timestamps
dates = [pd.Timestamp(date)for date in df.Date]
#Drop the Date column
df = df.drop(['Date'], axis=1)
# Make a new data frame
df1 = pd.DataFrame(df.values, columns=df.columns, index=dates)
df1 = df1.round(decimals=2)
print(df1.head(5))

# Compute the 9 day and 20 day Exponential Moving Averages
EMA9 = df1['Close'].ewm(span=9, adjust=False).mean()
EMA20 = df1['Close'].ewm(span=20, adjust=False).mean()
##Compute the 50 day and 100 day simple moving averages
SMA50 = df1['Close'].rolling(50).mean()
SMA100 = df1['Close'].rolling(100).mean()

# Compute the MACD values
emafast = df1['Close'].ewm(span=12, adjust=False).mean()
emaslow = df1['Close'].ewm(span=26, adjust=False).mean()
#signal = df1['Close'].ewm(span=9, adjust=False).mean()
macd = emafast-emaslow
signal = macd.ewm(span=9,adjust=False).mean()
diff = macd-signal
# Get values for candlestick plots. Use “iloc” to select columns by position 
# column 4 is not inclusive
stk_candle = df1.iloc[:, 0:4]
# Get the dates and convert it to a list
dates = df1.index.tolist()
# Convert the date to the mdates format
dates = pd.DataFrame(mdates.date2num(dates), columns=['Date'], index=df1.index)
# Add dates to the ohlc dataframe
stk_candle = pd.concat([dates, stk_candle], axis=1)
print(stk_candle.head(5))
# Set up the candlestick p[lot for the selected stock]
#Define the time frame fot the figure
end_date = '2019-10-31'
start_date = '2018-10-31'
# Calculate max and min prices for y axis limits
minPrice = df1['Low'].min()
maxPrice = df1['High'].max()
# Create the figure
fig = plt.figure(figsize=(16,18))
gs = gridspec.GridSpec(2,1, height_ratios=[5,1])
# Set tight layout to minimize gaps between subplots
plt.tight_layout()
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1], sharex=ax1)
ax2.xaxis_date()
# Set x and y axis limits
Ax2.set_xlim([start_date, end_date])
ax1.set_ylim([minPrice, maxPrice])

# Set the labesls for the axes
ax1.set_ylabel('Price($)', fontsize = 16)
xlabels = ax2.get_xticklabels()
ax2.set_xticklabels(xlabels, rotation = 45, fontsize = 12)
# Change the x-axis tick label format
Ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

# Plot the candlesticks for the stock
candlestick_ohlc(ax1, stk_candle.values.tolist(),
                  width = .6,
                  colorup='green',
                  colordown='red')
# Plot the 50 day SMA and the 100 day SMA
SMA50.plot(color = ['magenta'], style = ['-'], linewidth = 2.5, ax = ax1)
SMA100.plot(color = ['b'], style = ['-'], linewidth = 2.5, ax = ax1)
# Plot the 9 and 20 EMA
EMA9.plot(color = ['g'], style = ['--'], linewidth = 2.5, ax = ax1)
EMA20.plot(color = ['r'], style = ['--'], linewidth = 2.5, ax = ax1)

# Plot the MACD
signal.plot(color = 'g', style = ['-'], linewidth = 2.5, ax = ax2)
macd.plot(color = 'b', style = ['-'], linewidth = 2.5, ax = ax2)
diff.plot(color = 'black', style = ['-'], linewidth = 2.0, ax = ax2)

plt.show()

1 个答案:

答案 0 :(得分:1)

绘制 MACD hist,从您的代码中获取提示(假设 diff 是 pandas.core.series.Series):

# segregate positive and negative values in 'diff'

pve_diff = diff.copy()
pve_diff[pve_diff < 0] = 0
# similarly make series for negative values
nve_diff = diff.copy()
nve_diff[nve_diff >= 0] = 0
nve_diff = nve_diff * -1

# Now visualize
plt.bar(diff.index, pve_diff, color='g')
plt.bar(diff.index, nve_diff, color='r')
plt.show()

enter image description here