简体   繁体   中英

Plotting MACD lines and histogram python

I have a python script that reads CSV file stock data (choose file and retrieve stock specific data). I am having trouble plotting the histogram (difference between MACD and Signal). I am using Matplotlib for graphing. My code is shown below. I would like to be able to plot values above zero in green and below in red. Any help would be appreciated.

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()

to plot MACD hist, taking cue (assuming diff is pandas.core.series.Series) from your code:

# 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()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM