Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Style Enhancements, and add styles from Chandrakant #634

Merged
merged 7 commits into from
Jun 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/mplfinance_checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ jobs:
runs-on: ubuntu-20.04
strategy:
matrix:
python-version: [3.6, 3.7, 3.8, 3.9]
python-version: ['3.8', '3.9', '3.10' ]
steps:
- name: Preliminary Information
run: |
Expand All @@ -27,7 +27,7 @@ jobs:
- run: echo "The ${{ github.repository }} repository has been cloned to the runner."

- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}

Expand Down
200 changes: 186 additions & 14 deletions examples/scratch_pad/issues/issue#241_loop_all_styles.ipynb

Large diffs are not rendered by default.

113 changes: 113 additions & 0 deletions examples/scratch_pad/so76486448_hover.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import yfinance as yf
import mplfinance as mpf
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import pandas as pd
import numpy as np

# Dates to get stock data
start_date = "2020-01-01"
end_date = "2023-06-15"

# Fetch Tesla stock data
tesla_data = yf.download("TSLA", start=start_date, end=end_date)
tesla_weekly_data = tesla_data.resample("W").agg(
{"Open": "first", "High": "max", "Low": "min", "Close": "last", "Volume": "sum"}
).dropna()

# Get the latest closing price
latest_price = tesla_weekly_data['Close'][-1]

# Create additional plot
close_price = tesla_weekly_data['Close']
apd = mpf.make_addplot(close_price, color='cyan', width=2)

# Plot the candlestick chart
fig, axes = mpf.plot(tesla_weekly_data,
type='candle',
addplot=apd,
style='yahoo',
title='Tesla Stock Prices',
ylabel='Price',
xlabel='Date',
volume=True,
ylabel_lower='Volume',
volume_panel=1,
figsize=(16, 8),
returnfig=True
)

# Move the y-axis labels to the left side
axes[0].yaxis.tick_left()
axes[1].yaxis.tick_left()

# Adjust the position of the y-axis label for price
axes[0].yaxis.set_label_coords(-0.08, 0.5)

# Adjust the position of the y-axis label for volume
axes[1].yaxis.set_label_coords(-0.08, 0.5)

# Set y-axis label for price and volume
axes[0].set_ylabel('Price', rotation=0, labelpad=20)
axes[1].set_ylabel('Volume', rotation=0, labelpad=20)

# Make the legend box
handles = axes[0].get_legend_handles_labels()[0]
red_patch = mpatches.Patch(color='red')
green_patch = mpatches.Patch(color='green')
cyan_patch = mpatches.Patch(color='cyan')
handles = handles[:2] + [red_patch, green_patch, cyan_patch]
labels = ["Price Up", "Price Down", "Closing Price"]
axes[0].legend(handles=handles, labels=labels)

# Add a box to display the current price
latest_price_text = f"Current Price: ${latest_price:.2f}"
box_props = dict(boxstyle='round', facecolor='white', edgecolor='black', alpha=0.8)
axes[0].text(0.02, 0.95, latest_price_text, transform=axes[0].transAxes,
fontsize=12, verticalalignment='top', bbox=box_props)

# Function to create hover annotations
def hover_annotations(data):

annot_visible = False
annot = axes[0].text(0, 0, '', visible=False, ha='left', va='top')

def onmove(event):
nonlocal annot_visible
nonlocal annot

if event.inaxes == axes[0]:
index = int(event.xdata)
if index >= len(data.index):
index = -1
elif index < 0:
index = 0
values = data.iloc[index]
mytext = (f"{values.name.date().strftime('%m/%d/%Y'):}\n"+
f"O: {values['Open']:.2f}\n"+
f"H: {values['High']:.2f}\n"+
f"L: {values['Low']:.2f}\n"+
f"C: {values['Close']:.2f}\n"+
f"V: {values['Volume']:.0f}"
)

annot_visible = True
else:
mytext = ''
annot_visible = False

annot.set_position((event.xdata,event.ydata))
annot.set_text(mytext)
annot.set_visible(annot_visible)
fig.canvas.draw_idle()

fig.canvas.mpl_connect('motion_notify_event', onmove)

return annot


# Attach hover annotations to the plot
annotations = hover_annotations(tesla_weekly_data)

# Display the chart
plt.show()
12 changes: 12 additions & 0 deletions src/mplfinance/_styledata/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
from mplfinance._styledata import binance
from mplfinance._styledata import kenan
from mplfinance._styledata import ibd
from mplfinance._styledata import binancedark
from mplfinance._styledata import tradingview

_style_names = [n for n in dir() if not n.startswith('_')]

Expand All @@ -25,19 +27,29 @@
eval(cmd)

def _validate_style(style):
# Check for mandatory style keys:
keys = ['base_mpl_style','marketcolors','mavcolors','y_on_right',
'gridcolor','gridstyle','facecolor','rc' ]
for key in keys:
if key not in style.keys():
err = f'Key "{key}" not found in style:\n\n {style}'
raise ValueError(err)

# Check for mandatory marketcolor keys:
mktckeys = ['candle','edge','wick','ohlc','volume','alpha']
for key in mktckeys:
if key not in style['marketcolors'].keys():
err = f'Key "{key}" not found in marketcolors for style:\n\n {style}'
raise ValueError(err)

# The following keys are not mandatory in the style file,
# but maybe mandatory in the code (to keep the code simpler)
# so we set default values here:
if 'vcedge' not in style['marketcolors']:
style['marketcolors']['vcedge'] = style['marketcolors']['volume']
if 'vcdopcod' not in style['marketcolors']:
style['marketcolors']['vcdopcod'] = False

#print('type(_styles)=',type(_styles))
#print('_styles=',_styles)
for s in _styles.keys():
Expand Down
27 changes: 27 additions & 0 deletions src/mplfinance/_styledata/binancedark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
style = dict(style_name = 'binancedark',
base_mpl_style= 'dark_background',
marketcolors = {'candle' : {'up': '#3dc985', 'down': '#ef4f60'},
'edge' : {'up': '#3dc985', 'down': '#ef4f60'},
'wick' : {'up': '#3dc985', 'down': '#ef4f60'},
'ohlc' : {'up': 'green', 'down': 'red'},
'volume' : {'up': '#247252', 'down': '#82333f'},
'vcedge' : {'up': '#247252', 'down': '#82333f'},
'vcdopcod' : False,
'alpha' : 1.0,
},
mavcolors = ['#ffc201','#ff10ff','#cd0468','#1f77b4',
'#ff7f0e','#2ca02c','#40e0d0'],
y_on_right = True,
gridcolor = None,
gridstyle = '--',
facecolor = None,
rc = [ ('axes.grid','True'),
('axes.grid.axis' , 'y'),
('axes.edgecolor' , '#474d56' ),
('axes.titlecolor','red'),
('figure.titlesize', 'x-large' ),
('figure.titleweight','semibold'),
('figure.facecolor', '#0a0a0a' ),
],
base_mpf_style= 'binancedark'
)
1 change: 0 additions & 1 deletion src/mplfinance/_styledata/brasil.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
'wick' : {'up': '#fedf00', 'down': '#002776'},
'ohlc' : {'up': '#fedf00', 'down': '#002776'},
'volume': {'up': '#fedf00', 'down': '#002776'},
'vcedge': {'up': '#1f77b4', 'down': '#1f77b4'},
'vcdopcod': False,
'alpha': 0.9},
'mavcolors' : None,
Expand Down
1 change: 0 additions & 1 deletion src/mplfinance/_styledata/checkers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
'wick' : {'up': '#606060', 'down': '#606060'},
'ohlc' : {'up': '#000000', 'down': '#ff0000'},
'volume': {'up': '#6f6f6f', 'down': '#ff4040'},
'vcedge': {'up': '#1f77b4', 'down': '#1f77b4'},
'vcdopcod' : False,
'alpha' : 0.9},
'mavcolors' : None,
Expand Down
1 change: 0 additions & 1 deletion src/mplfinance/_styledata/starsandstripes.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
'wick' : {'up': '#082865', 'down': '#ae0019'},
'ohlc' : {'up': '#082865', 'down': '#ae0019'},
'volume': {'up': '#082865', 'down': '#ae0019'},
'vcedge': {'up': '#1f77b4', 'down': '#1f77b4'},
'vcdopcod': False,
'alpha': 0.9},
'mavcolors': None,
Expand Down
27 changes: 27 additions & 0 deletions src/mplfinance/_styledata/tradingview.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
style = dict(style_name = 'tradingview',
base_mpl_style= 'fast',
marketcolors = {'candle' : {'up': '#26a69a', 'down': '#ef5350'},
'edge' : {'up': '#26a69a', 'down': '#ef5350'},
'wick' : {'up': '#26a69a', 'down': '#ef5350'},
'ohlc' : {'up': '#26a69a', 'down': '#ef5350'},
'volume' : {'up': '#26a69a', 'down': '#ef5350'},
'vcedge' : {'up': 'white' , 'down': 'white' },
'vcdopcod' : False,
'alpha' : 1.0,
'volume_alpha': 0.65,
},
#scale_width_adjustment = { 'volume': 0.8 },
mavcolors = ['#2962ff','#2962ff',],
y_on_right = True,
gridcolor = None,
gridstyle = '--',
facecolor = None,
rc = [ ('axes.grid','True'),
('axes.edgecolor' , 'grey' ),
('axes.titlecolor','red'),
('figure.titlesize', 'x-large' ),
('figure.titleweight','semibold'),
('figure.facecolor', 'white' ),
],
base_mpf_style = 'tradingview'
)
1 change: 0 additions & 1 deletion src/mplfinance/_styledata/yahoo.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
'wick' : {'up': '#606060', 'down': '#606060'},
'ohlc' : {'up': '#00b060', 'down': '#fe3032'},
'volume': {'up': '#4dc790', 'down': '#fd6b6c'},
'vcedge': {'up': '#1f77b4', 'down': '#1f77b4'},
'vcdopcod' : True,
'alpha' : 0.9},
'mavcolors' : None,
Expand Down
2 changes: 1 addition & 1 deletion src/mplfinance/_version.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
version_info = (0, 12, 9, 'beta', 8)
version_info = (0, 12, 9, 'beta', 9)

_specifier_ = {'alpha': 'a','beta': 'b','candidate': 'rc','final': ''}

Expand Down
35 changes: 20 additions & 15 deletions src/mplfinance/_widths.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,21 @@ def _valid_update_width_kwargs():

return vkwargs

def _scale_width_config(scale,width_config):
if scale['volume'] is not None:
width_config['volume_width'] *= scale['volume']
if scale['ohlc'] is not None:
width_config['ohlc_ticksize'] *= scale['ohlc']
if scale['candle'] is not None:
width_config['candle_width'] *= scale['candle']
if scale['lines'] is not None:
width_config['line_width'] *= scale['lines']
if scale['volume_linewidth'] is not None:
width_config['volume_linewidth'] *= scale['volume_linewidth']
if scale['ohlc_linewidth'] is not None:
width_config['ohlc_linewidth' ] *= scale['ohlc_linewidth']
if scale['candle_linewidth'] is not None:
width_config['candle_linewidth'] *= scale['candle_linewidth']

def _determine_width_config( xdates, config ):
'''
Expand Down Expand Up @@ -138,23 +153,13 @@ def _determine_width_config( xdates, config ):
width_config['candle_linewidth'] = _dfinterpolate(_widths,datalen,'clw')
width_config['line_width' ] = _dfinterpolate(_widths,datalen,'lw')

if config['scale_width_adjustment'] is not None:
if 'scale_width_adjustment' in config['style']:
scale = _process_kwargs(config['style']['scale_width_adjustment'],_valid_scale_width_kwargs())
_scale_width_config(scale,width_config)

if config['scale_width_adjustment'] is not None:
scale = _process_kwargs(config['scale_width_adjustment'],_valid_scale_width_kwargs())
if scale['volume'] is not None:
width_config['volume_width'] *= scale['volume']
if scale['ohlc'] is not None:
width_config['ohlc_ticksize'] *= scale['ohlc']
if scale['candle'] is not None:
width_config['candle_width'] *= scale['candle']
if scale['lines'] is not None:
width_config['line_width'] *= scale['lines']
if scale['volume_linewidth'] is not None:
width_config['volume_linewidth'] *= scale['volume_linewidth']
if scale['ohlc_linewidth'] is not None:
width_config['ohlc_linewidth' ] *= scale['ohlc_linewidth']
if scale['candle_linewidth'] is not None:
width_config['candle_linewidth'] *= scale['candle_linewidth']
_scale_width_config(scale,width_config)

if config['update_width_config'] is not None:

Expand Down
25 changes: 19 additions & 6 deletions src/mplfinance/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ def _valid_plot_kwargs():
'Validator' : lambda value: isinstance(value, (list,tuple)) and len(value) == 2
and all([isinstance(v,(int,float)) for v in value])},

'volume_alpha' : { 'Default' : 1, # alpha of Volume bars
'volume_alpha' : { 'Default' : None, # alpha of Volume bars
'Description' : 'opacity for Volume bar: 0.0 (transparent) to 1.0 (opaque)',
'Validator' : lambda value: isinstance(value,(int,float)) or
all([isinstance(v,(int,float)) for v in value]) },
Expand Down Expand Up @@ -673,7 +673,8 @@ def plot( data, **kwargs ):

datalen = len(xdates)
if config['volume']:
vup,vdown = style['marketcolors']['volume'].values()
mc = style['marketcolors']
vup,vdown = mc['volume'].values()
#-- print('vup,vdown=',vup,vdown)
vcolors = _updown_colors(vup, vdown, opens, closes, use_prev_close=style['marketcolors']['vcdopcod'])
#-- print('len(vcolors),len(opens),len(closes)=',len(vcolors),len(opens),len(closes))
Expand All @@ -682,9 +683,21 @@ def plot( data, **kwargs ):
w = config['_width_config']['volume_width']
lw = config['_width_config']['volume_linewidth']

adjc = _adjust_color_brightness(vcolors,0.90)
valp = config['volume_alpha']
volumeAxes.bar(xdates,volumes,width=w,linewidth=lw,color=vcolors,ec=adjc,alpha=valp)
veup, vedown = mc['vcedge'].values()
if mc['volume'] == mc['vcedge']:
edgecolors = _adjust_color_brightness(vcolors,0.90)
elif veup != vedown:
edgecolors = _updown_colors(veup, vedown, opens, closes, use_prev_close=style['marketcolors']['vcdopcod'])
else:
edgecolors = veup

if config['volume_alpha']:
valp = config['volume_alpha']
elif 'volume_alpha' in mc:
valp = mc['volume_alpha']
else:
valp = 1.0
volumeAxes.bar(xdates,volumes,width=w,linewidth=lw,color=vcolors,ec=edgecolors,alpha=valp)
if config['volume_ylim'] is not None:
vymin = config['volume_ylim'][0]
vymax = config['volume_ylim'][1]
Expand Down Expand Up @@ -911,7 +924,7 @@ def plot( data, **kwargs ):
else:
title = config['title'] # config['title'] is a string
fig.suptitle(title,**title_kwargs)


if config['axtitle'] is not None:
axA1.set_title(config['axtitle'])
Expand Down
Loading