matplotlib / matplotlib/mplfinance

Event Handling with mplfinance

Open
#83 12 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

question
Dominant language
Python
Stars
4.4k
Forks
678
PR merge metrics
No merged PRs in 30d

Description

Hey Daniel, love what you're doing with this package, it's absolutely fantastic.

I'm a pretty novice coder so excuse any code that might be unpreferred but I recently had an idea for a "point and click" technical indicator and wanted to try it out. The only issue is that I have absolutely no idea how to use event handling with the new mplfinance package.

I made a makeshift version using the old mpl_finance package. Attached is it (I'm using Alphavantage for intraday data, not sure I want to post my apikey here so I'll post everything but that):

import requests_html
import yahoo_fin.stock_info as yf
import pandas as pd
import numpy as np
import mpl_finance as mpf
import json
import requests
import datetime
import matplotlib as mpl
from mplfinance.original_flavor import candlestick_ohlc


ticker='SPY'
interval='60min'
apikey=''

r = requests.get("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={}&interval={}&outputsize=full&apikey={}".format(ticker,interval, apikey))
df = pd.DataFrame.from_dict(r.json()['Time Series ({})'.format(interval)]).T
df.columns=['Open','High','Low','Close','Volume']
df.index = pd.to_datetime(df.index)
df.sort_index(ascending=True, inplace=True)
df = df.apply(pd.to_numeric)

inital_data = df
inital_data.columns = map(str.title, inital_data.columns)


fig, ax = plt.subplots(figsize=(15,15))


candlestick_ohlc(ax, zip(mpl.dates.date2num(inital_data.index), inital_data['Open'], inital_data['High'], inital_data['Low'], inital_data['Close']))  


def onclick(event):
    date = mpl.dates.num2date(event.xdata)
    # print(datetime.datetime.strftime(date,"%Y-%m-%d %H:%M"))
    data = inital_data.loc[date:,:]
    vwap = []


    for x in range(len(data['Close'])):
        vwap.append(np.sum((data['Close'][0:(x+1)]*data['Volume'][0:(x+1)]))/np.sum(data['Volume'][0:(x+1)]))

    data[date] = vwap
    inital_data[date]=data[date]

    ax.plot(inital_data.index,inital_data[date])

    inital_data.drop(date, axis=1, inplace=True)
    event.canvas.draw()
    print(data.index[0])

cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()

The point and click functionality works incredible, exactly what I wanted, but it is so ugly. I made a non-point and click version using the new mplfinance and it looks beautiful but I want the point and click functionality for that.

Here's the ugly looking one:
https://imgur.com/a/VPa0SlH

Here's the beautiful looking one:
https://imgur.com/a/6s5gQSu

Any help in getting the event handling for the new package would be much appreciated.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the supplied onclick function and the fig.canvas.mpl_connect('button_press_event', onclick) entry point, then review how the example uses mplfinance alongside Matplotlib. Done means the point-and-click interaction works with the new mplfinance package while retaining the newer chart appearance.

Written by the indexing model from the issue text.

Assessment

Tech stack
pandas, python
Domain
data-visualization
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.