Saturday 2 November 2019

python finance 4 candlestick

candlestick sampled every 10 days
top graph: zoomed ohlc (open high low close)
bottom graph: trading volume summed over sample time
#powershell
pip install mpl_finance

---------------------------
#pycharm
#resample data

import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates
import pandas as pd
import pandas_datareader.data as web

df = pd.read_csv('tsla_csv', parse_dates=True, index_col=0)

#open high low
df_ohlc = df['Adj Close'].resample('10D').ohlc()
df_volume = df['Volume'].resample('10D').sum()
#print(df_ohlc.head())

-----------------------
#log
#every 10 days

        Date       open       high        low      close
0 2011-01-03  26.620001  28.450001  26.620001  26.959999
1 2011-01-13  26.219999  26.219999  22.620001  23.040001
2 2011-01-23  24.490000  24.920000  23.910000  23.910000
3 2011-02-02  23.940001  24.490000  23.070000  23.250000
4 2011-02-12  23.080000  24.730000  22.840000  23.180000

------------------------------
#pycharm
#change date format for plot

df_ohlc.reset_index(inplace=True)

df_ohlc['Date'] = df_ohlc['Date'].map(mdates.date2num)
#print(df_ohlc.head())

---------------------------------
#log

       Date       open       high        low      close
0  734140.0  26.620001  28.450001  26.620001  26.959999
1  734150.0  26.219999  26.219999  22.620001  23.040001
2  734160.0  24.490000  24.920000  23.910000  23.910000
3  734170.0  23.940001  24.490000  23.070000  23.250000
4  734180.0  23.080000  24.730000  22.840000  23.180000

-------------------------------
#pycharm

ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1)
ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1)
ax1.xaxis_date()

candlestick_ohlc(ax1, df_ohlc.values, width=2, colorup='g')
ax2.fill_between(df_volume.index.map(mdates.date2num), df_volume.values, 0)

plt.show()

reference:
https://www.youtube.com/watch?v=19yyasfGLhk&list=PLQVvvaa0QuDcOdF96TBtRtuQksErCEBYZ&index=4
https://stackoverflow.com/questions/42373104/since-matplotlib-finance-has-been-deprecated-how-can-i-use-the-new-mpl-finance

No comments:

Post a Comment