Python for Finance: Dash by Plotly

Python for Finance: Dash by PlotlyExpanding Jupyter Notebook Stock Portfolio Analyses with Interactive Charting in Dash by Plotly.Kevin BollerBlockedUnblockFollowFollowingJul 30By Carlos Muza on Unsplash.Part 2 of Leveraging Python for Stock Portfolio Analyses.In part 1 of this series I discussed how, since I’ve become more accustomed to using pandas, that I have signficantly increased my use of Python for financial analyses..Finally, you used Plotly for visualizations, which made it much easier to understand which positions drove the most value, what their YTD momentum looked like relative to the S&P 500, and if any had traded down and you might want to consider divesting, aka hit a “Trailing Stop”.I learned a lot as part of building this initial process in Jupyter notebook, and I also found it very helpful to write a post which walked through the notebook, explained the code and related my thinking behind each of the visualizations..While I’ve continued to find the notebook that I created helpul to track my stock portfolio, it had always been my intention to learn and incorporate a Python framework for building analytical dashboards / web applications..While I’m still rather early on in this process, in this post I will discuss the extension of the notebook I discussed last time with my initial development using Dash by Plotly, aka Dash.Dash by Plotly.If you have read or reference part 1, you will see that once you created the master dataframe, you used Plotly to generate the visualizations which evaluate portfolio performance relative to the S&P 500..However, I found the course to be a very helpful jump start, particularly because Jose uses datareader and financial data and examples, including dynamically pulling stock price charts.Porting Data from Jupyter Notebook to Interact with it in Dash.Getting StartedSimilar to part 1, I created another repo on GitHub with all of the files and code required to create the final Dash dashboard.Below is a summary of what is included and how to get started:Investment Portfolio Python Notebook_Dash_blog_example.ipynb — this is very similar to the Jupyter notebook from part 1; the additions include the final two sections: a ‘Stock Return Comparisons’ section, which I built as a proof-of-concept prior to using Dash, and ‘Data Outputs’, where I create csv files of the data the analyses generate; these serve as the data sources used in the Dash dashboard.Sample stocks acquisition dates_costs.xlsx — this is the toy portfolio file, which you will use or modify for your portfolio assessments.requirements.txt — this should have all of the libraries you will need..I recommend creating a virtual environment in Anaconda, discussed further — this has the code for the Dash dashboard which we’ll cover below.As per my repo’s README file, I recommend creating a virtual environment using Anaconda..Here is a very thorough explanation on how to set up virtual environments in Anaconda.Last, as mentioned in part 1, once your environment is set up, in addition to the libraries in the requirements file, if you want the Yahoo Finance datareader piece to run in the notebook, you will also need to pip install fix-yahoo-finance within your virtual environment.Working with DashIf you have followed along thus far in setting up a virtual environment using Python 3.6, and have installed the necessary libraries, you should be able to run the Python file with the Dash dashboard code.For those who are less familiar: once in your virtual environment, you will need to change directory, cd, to where you have the repo’s files saved..You should see the file listed.python # this will run the Dash file# You will then go to your browser and input the URL where Python says your dashboard is running on localhost.If you would like the full explanation on the Jupyter notebook and generating the portfolio data set, please refer to part 1..The first is the full portfolio dataset, from which you can generate all of the visualizations, and the second provides the list of tickers you will use in the first, new stock chart’s dropdown selection.# Generate the base file that will be used for Dash dashboard.merged_portfolio_sp_latest_YTD_sp_closing_high.to_csv('analyzed_portfolio.csv')I’ll highlight some key aspects of the Mock Portfolio Python file and share how to run the dashboard locally.For reference while we breakdown the .py file, below is a screen grab of the first three charts that you should see when running this Dash dashboard.First three charts in Dash Stock Portfolio Analyses dashboard.At the beginning of the .py file, you import the libraries included in the requirements.txt file, and then writeapp = dash.Dash()in order to instantiate the Dash app..Tickers will be used for the stock tickers in one of the chart’s dropdowns, and the data dataframe is the final data set which is used for all of the visualization evaluations.You wrap the entire dashboard in a Div, and then begin adding the charting components within this main Div..This chart is the same as what was provided in the Jupyter Notebook in part 1, but I find using Dash for all of these outputs in a dashboard layout to be a better user experience and easier to work with than within Jupyter notebook (I continue to prefer notebooks for conducting analysis to anything else I’ve used to-date).# YTD Returns versus S&P 500 section html.H1('YTD and Total Position Returns versus S&P 500'), dcc.Graph(id='ytd1', figure = {'data':[ go.Bar( x = data['Ticker'][0:20], y = data['Share YTD'][0:20], name = 'Ticker YTD'), go.Scatter( x = data['Ticker'][0:20], y = data['SP 500 YTD'][0:20], name = 'SP500 YTD') ], 'layout':go.Layout(title='YTD Return vs S&P 500 YTD', barmode='group', xaxis = {'title':'Ticker'}, yaxis = {'title':'Returns', 'tickformat':".2%"} )}, style={'width': '50%', 'display':'inline-block'} )For those comfortable using Plotly, the syntax should be familiar in terms of creating the data and layout objects required to plot the Plotly figure..As before, you have an extensible Jupyter notebook and portfolio dataset, which you can now read out as a csv file and review in an interactive Dash dashboard.. More details

Leave a Reply