<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Steven Medvetz on Medium]]></title>
        <description><![CDATA[Stories by Steven Medvetz on Medium]]></description>
        <link>https://medium.com/@stevenmedvetz?source=rss-402595ce4c00------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*P0I4JsNzQ9l7kFB1cVARcw.jpeg</url>
            <title>Stories by Steven Medvetz on Medium</title>
            <link>https://medium.com/@stevenmedvetz?source=rss-402595ce4c00------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:51:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stevenmedvetz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating a Stock Portfolio Analysis Library in Python]]></title>
            <link>https://medium.com/@stevenmedvetz/creating-a-stock-portfolio-analysis-library-in-python-c08f9df7714d?source=rss-402595ce4c00------2</link>
            <guid isPermaLink="false">https://medium.com/p/c08f9df7714d</guid>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[Steven Medvetz]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 01:56:20 GMT</pubDate>
            <atom:updated>2023-03-23T01:56:20.868Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>This article is sort of a continuation or tangent off of my previous <a href="https://medium.com/@stevenmedvetz/exploratory-data-analysis-of-stocks-using-python-8ac5ab5c2793">article</a> about exploratory data analysis of stocks using python. In that article we used Yahoo Finance, Plotly, Pandas, and NumPy to perform an exploratory data analysis of a group of stocks. We plotted and compared various characteristics of them and calculated some key values that would be useful if you were putting together a portfolio. Today, we will build on this but in a more <em>python </em>focused manner. We will create a library to store various plotting methods, and calculations using object-oriented programming methods. This way, we can simply initialize a group of stocks or a weighted portfolio and run an in-depth analysis. Instead of importing and formatting data for one of the functions we defined in the previous article.</p><h3>Getting Started</h3><p>So, let&#39;s look at this from a birds-eye view: we have already conducted an exploratory data analysis of various stocks, and have a handful of functions defined for this. So much of the leg work is already done. However, those functions weren’t built using object-oriented programming methods, and although they can work for individual and groups of stocks, they don’t view the groups as a <em>portfolio. </em>Meaning, they aren’t weighted the way they would be in a portfolio. They are being analyzed individually but on the same playing field. So, we need to somehow add weights to the stocks of our choosing to compose a portfolio. But we don’t want to get rid of the functionality we had before, so maybe we divide this into two sections: an asset-based approach and a portfolio-based approach. We will create both an asset class and a portfolio class. With this format we will be able to analyze and compare stocks both in and out of a portfolio. Let&#39;s begin with the “asset” class.</p><h3>Asset Analysis</h3><p>As we have discussed, much of the “asset” side of things has already been built in our previous project; it’s just a matter of converting it into object-oriented programming. Last time we downloaded data, plotted different closing prices, calculated risk and return, and created a correlation heatmap of the stocks. So, let&#39;s start with initializing our “Asset” class:</p><pre>class Asset:<br>    def __init__(self, ticker, start_date, end_date = datetime.today().strftime(&#39;%Y-%m-%d&#39;)):<br>        self.ticker = ticker<br>        self.start_date = start_date<br>        self.end_date = end_date </pre><p>In this code we create the class “Asset”. It takes in two mandatory arguments: ticker, and start_date, and one optional argument end_date. Ticker is a list of ticker symbols, start_date is the date you wish to begin pulling data from and end_date is the date you wish to end your data pulling from. As you can see the end_date defaults to today if you don’t add an input. Every argument will be built upon the assumption that the data input is in the format of a yahoo finance dataframe. To avoid any confusion, we will create a function called “get_data” that pulls data from yahoo finance using the download() function.</p><pre>    def get_data(self):<br>        df = yf.download(self.ticker, start = self.start_date, end = self.end_date)<br>        return df</pre><p>Next, we will create functions to calculate different returns of the stocks. We add two optional arguments in case we want to use the adjusted closing price or calculate cumulative returns.</p><pre>    def simple_returns(self, adj = False, cum = False):<br>        df = self.get_data()<br>        if adj:<br>            simple_returns = df[&quot;Adj Close&quot;].pct_change().dropna()<br>        else:<br>            simple_returns = df[&quot;Close&quot;].pct_change().dropna()<br>        if cum:<br>            simple_returns = (1 + simple_returns).cumprod() - 1<br>        return simple_returns<br>    <br>    def log_returns(self, adj = False, cum = False):<br>        simple_returns = self.simple_returns(adj, cum)<br>        log_returns = np.log(1+simple_returns)<br>        return log_returns</pre><p>Now, we also need to calculate the standard deviation of the returns, which is what we defined “risk” as last time. We will once again include the optional argument for crypto, because the number of trading days effects the standard deviation.</p><pre>    def std(self, adj = False, crypto = False):<br>        returns = self.simple_returns(adj).mul(100)<br>        if crypto:<br>            trading_days = 365<br>        else:<br>            trading_days  = 252<br>        std = returns.describe().T.loc[&quot;std&quot;]<br>        std = std*np.sqrt(trading_days)<br>        return std</pre><p>There are a couple more calculations in this class, but you can find those on my github. Let&#39;s take a look at some plots, starting with plotting the returns, which we did not cover last time.</p><pre>    def returns_plot(self, adj = False, cum = False, log = False, template = &#39;plotly_dark&#39;):<br>        returns = self.simple_returns(adj, cum).mul(100)<br>        if log:<br>            returns = self.log_returns(adj, cum).mul(100)<br>        try:<br>            returns = returns.to_frame()<br>        except:<br>            pass<br>        returns = returns.rename(columns={&#39;Close&#39;: &#39;Returns&#39;})<br>        fig = px.line(returns, template = template)<br>        fig.update_traces(hovertemplate=&#39;%{y:.2f}%&#39;)<br>        fig.update_layout(<br>            showlegend = True,<br>            legend = dict(title = None, font = dict(size = 16)),<br>            title={<br>                &#39;y&#39;:0.95,<br>                &#39;x&#39;:0.5,<br>                &#39;text&#39;: f&quot;{self.ticker} Daily Returns&quot;,<br>                &#39;font&#39;: {&#39;size&#39;: 24},<br>                <br>                &#39;xanchor&#39;: &#39;center&#39;,<br>                &#39;yanchor&#39;: &#39;top&#39;},<br>            hovermode = &quot;x unified&quot;,<br>            xaxis_title = &quot;Date&quot;,<br>            yaxis_title = &quot;% Returns&quot;)<br>                <br>        fig.show() <br>        return returns.show() </pre><p>This function has a few optional functions: adj, cum, log, and template. adj we’ve seen before. Cum is for cumulative returns, log is for logarithmic returns, and template changes the Plotly template. I prefer plotly_dark, so that&#39;s the default. Let&#39;s take a look at this plot with cum = True.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jYEHP-OUW7ynaM3jowOFQ.png" /></figure><p>That looks good. The closing price plot is formatted in a similar manner. So let&#39;s look at something new: the candlestick plot. This one takes a little more formatting but is a classic plot in financial data analysis for investing and trading. Below you can see the code I put together for us.</p><pre>    def candlestick(self, sma1 = 0, sma2 = 0, template = &#39;plotly_dark&#39;):<br>        <br>        ticker = Asset(self.ticker, self.start_date)<br>        df = ticker.get_data()<br>        <br>        fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.02, row_heights=[0.7, 0.3])<br>        fig.add_trace(go.Candlestick(x=df.index,<br>                                      open=df[&#39;Open&#39;],<br>                                      high=df[&#39;High&#39;],<br>                                      low=df[&#39;Low&#39;],<br>                                      close=df[&#39;Close&#39;],<br>                                      name=&#39;candlestick&#39;),<br>                                     <br>                      row=1, col=1)<br>        fig.update_traces(increasing_line_width = 1.5,<br>                          decreasing_line_width = 1.5<br>                         )<br>        if sma1 &gt; 0:<br>            fig.add_trace(go.Scatter(x=df.index, y=df[&#39;Close&#39;].rolling(window=sma1).mean(),<br>                                      name=f&#39;{sma1}-day moving average&#39;, line=dict(color=&#39;lightblue&#39;, width = 1)),<br>                          row=1, col=1)<br>        if sma2 &gt; 0:<br>            fig.add_trace(go.Scatter(x=df.index, y=df[&#39;Close&#39;].rolling(window=sma2).mean(),<br>                                      name=f&#39;{sma2}-day moving average&#39;, line=dict(color=&#39;red&#39;, width = 1)),<br>                          row=1, col=1)<br>        <br>        fig.add_trace(go.Bar(x=df.index,<br>                             y=df[&#39;Volume&#39;],<br>                             name=&#39;volume&#39;),<br>                      row=2, col=1)<br>        <br>        fig.update_layout(<br>                          title={<br>                          &#39;text&#39;: f&#39;{self.ticker} Candlestick Chart with Volume&#39;,<br>                          &#39;y&#39;:0.9,<br>                          &#39;x&#39;:0.5,<br>                          &#39;font&#39;: {&#39;size&#39;: 24},<br>                          &#39;xanchor&#39;: &#39;center&#39;,<br>                          &#39;yanchor&#39;: &#39;top&#39;,},<br>                          xaxis_rangeslider_visible=False,<br>                          xaxis_title=&#39;Date&#39;,<br>                          yaxis_title=&#39;Price (USD)&#39;,<br>                          hovermode = &quot;x unified&quot;,<br>                          bargap=0,<br>                          bargroupgap=0,<br>                          template = template)<br>        fig.update_xaxes(title_text=&#39;&#39;, row=1, col=1, showgrid=False)<br>        fig.update_xaxes(title=&#39;Date&#39;, row=2, col=1)<br>        fig.update_yaxes(title=&#39;Volume&#39;,row=2,col=1)<br>        <br>        fig.show()</pre><p>Candlestick plots are meant to look at the opening, closing, high, and low price of a <strong>single </strong>stock or asset. Knowing this we need to make sure that we initialize the class Asset with only one ticker symbol, or you will get an error. The arguments in this function are sma1 and sma2. These are two simple moving averages and are a common addition to a standard candlestick plot. They default to 0, so unless you add values for them, they won’t be displayed. Below is a candlestick plot for the ‘SPY’ ticker with a 50- and 200-day moving average, and the trading volume shown below on a shared date axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wODQPY51xbSD3S26v7Gmw.png" /></figure><p>For the rest of the functions available in the Asset class check out the <a href="https://github.com/StevenMedvetz/stock-analysis">github</a>.</p><h3>Portfolio Analysis</h3><p>Now let&#39;s take a look at the portfolio side of the analysis. There are many similar functions that I won’t go over because they are mostly the same as the Asset class just slightly different. But let&#39;s dive in and look at how we initialize the Portfolio class below.</p><pre>class Portfolio:<br>    def __init__(self, assets, start_date, weights = None, end_date = datetime.today().strftime(&#39;%Y-%m-%d&#39;)):<br>        self.assets = assets<br>        self.start_date = start_date<br>        self.end_date = end_date<br>        <br>        if weights is not None:<br>            self.weights = np.array(weights)<br>        else:<br>            self.weights = self.generate_random_weights()<br>    def generate_random_weights(self):<br>    # Generate random weights that add up to 1 and round to 1 digit<br>        weights = [round(random.random(), 1) for _ in range(len(self.assets))]<br>        total_weight = sum(weights)<br>        return np.array([round(weight / total_weight, 1) for weight in weights])</pre><p>We see some familiar arguments here: assets (equivalent of tickers in Asset class), start_date, and end_date. The new argument is weights which is set to None by default. The weights argument is an array of numbers that sum to 1. These numbers reflect the “weight” of your assets in your portfolio. If you leave it blank the function generate_random_weights will automatically assign (roughly) even weights to your portfolio that sum to one. We initialize a portfolio as follows:</p><pre>assets = [&#39;SPY&#39;, &#39;AAPL&#39;, &#39;META&#39;]<br>start_date = &#39;2017-01-01&#39;<br>weights = [0.4, 0.3, 0.3]<br><br>port = Portfolio(assets, start_date, weights)</pre><p>The weights are assigned respectively to our list of assets. So here 40% of our portfolio is ‘SPY’, and 30% to ‘AAPL’ and ‘META’. Gathering data, calculating asset returns can all be done in a similar fashion in this class but, the difference comes to when you want to look at portfolio returns. let&#39;s look at these and then the plot for portfolio return.</p><pre>def portfolio_returns(self, adj = False, cum = False):<br>        returns = self.simple_returns(adj, cum)<br>        portfolio_returns = (returns*self.weights).sum(axis=1)<br>        return portfolio_returns</pre><p>Again, we see the familiar arguments of adj and cum, but looking at the function itself we see that this calculates the returns of the assets individually and then multiplies them by their weight in the portfolio. Lets look at the plot of the portfolio returns. You can see the code for this in the github page under the returns_plot function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tv0rcE5KZ85FZvQNHI555A.png" /></figure><p>Some more functions unique to the Portfolio class are cov_matrix and corr_matrix for creating covariance and correlation matrices. Both very useful functions for developing a portfolio and comparing different assets. These functions have an optional argument called plot to create a heatmap of the matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*FWSSiTDK3Qu-Vcig7VmyKg.png" /></figure><p>The last two plots are the risk vs. return plot and the pie chart showing your portfolio breakdown. Since the risk vs. return plot can be seen in my last article, and a pie chart isn’t anything exciting I will not add images for them here.</p><h3>Conclusion</h3><p>This library is a good basis for exploring and analyzing stocks and stock portfolio’s. There are many things it can’t do: portfolio optimization, backtesting, efficient frontiers, etc. It is only meant for me to be able to reproduce common calculations and plots without having to code them over and over again. The templates and layout is designed to my personal liking, although there is some room for customization through the optional functions available. Feel free to download the code off of my github repository <a href="https://github.com/StevenMedvetz/stock-analysis">here</a>, read my previous post <a href="https://medium.com/@stevenmedvetz/exploratory-data-analysis-of-stocks-using-python-8ac5ab5c2793">here</a>, or reach out to me on <a href="https://www.linkedin.com/in/steven-medvetz-8b62b11a1/">Linkedin</a>. I hope this helps with your stock portfolio analysis or at least gave you starting point or reference for building your own library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c08f9df7714d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploratory Data Analysis of Stocks Using Python]]></title>
            <link>https://medium.com/@stevenmedvetz/exploratory-data-analysis-of-stocks-using-python-8ac5ab5c2793?source=rss-402595ce4c00------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ac5ab5c2793</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Steven Medvetz]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 21:45:57 GMT</pubDate>
            <atom:updated>2023-02-27T21:45:57.611Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we will take a look at conducting exploratory data analysis of stocks using python. This will be the beginning of a series of posts about financial data analysis using python. This post will go over three things:</p><ol><li>Downloading and comparing closing prices of various stocks.</li><li>Calculating and visualizing risk and return</li><li>Correlation of returns</li></ol><p>Before getting started you will need to install the following libraries: yfinance, plotly.express, plotly.io, and numpy. I prefer plotting with plotly rather than matplotlib because plotly gives you a good level of interactivity compared to matplotlib. For this and most projects I set the renderer to “browser” so that I can see plot hover data as well as zoom in specific areas of interest. If you haven’t used plotly I would recommend giving it a try. All the code for this project can be found on my <a href="https://github.com/StevenMedvetz/stock-analysis">github</a></p><h3>Downloading Stock Data</h3><p>The first thing we need to do is import the required packages and download some stock data. For this project we will use the following stocks: Amazon (AMZN), Apple (AAPL), Microsoft (MSFT), Campbells Soup (CPB), and Dollar General (DG). We add the ticker symbols for each of these stocks to a list and pass it into the yf.download function along with a start date to gather stock data. This data is stored in a dataframe called “df” and contains the closing, adjusted closing, high, low and opening prices, as well as the volume for each stock from the “start_date” up until today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*kD4gRGBIAicvls5gCK4iWA.png" /></figure><h3>Comparing Closing Prices</h3><p>Now let&#39;s compare the adjusted closing prices of these stocks. Looking at the closing price of a stock over time is a good way to track its performance. To do this we will take the column df[‘Adj Close’] and plot it against df.index, which is the date of each trading day for the downloaded data. The plot can be seen below, and the code can be seen on my github repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oud0mjD93bR680YK4JmbpQ.png" /></figure><p>Above we see the adjusted closing price in USD for our stocks from 2015 until February 2023. Because of how different some of the prices are between the chosen stocks it would be easier to compare them if we normalized the data and plotted again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qt-wPQfOyICbeipOsILf4g.png" /></figure><p>We can see from this plot that Amazon (AMZN) is outperforming the rest of the stocks, but also seems to be the most volatile. On the opposite end of the spectrum, we see Campbells Soup (CPB) is the performing the worst, but also appears to be the least volatile. Another interesting trend we can see around the beginning of 2020 is a steep drop in price for all stocks due to the market crash from the COVID-19 pandemic.</p><h3>Risk and Return</h3><p>I’ve mentioned volatility in this article already, but what is volatility? Volatility describes fluctuation of a stock price in a given time period. It is a common way to describe the “risk” of a stock and is calculated as the standard deviation of the stocks returns. Looking at the plots above it is easy see why I guessed that Amazon is the most volatile and Campbells the least. You can also see that while Amazon is the one of the most volatile it’s also the best performing, and the opposite is true for Campbells. So, when building your portfolio these are things to keep in mind.</p><p>Now we need a way to visualize this risk / return relationship of these stocks. To do this we first need to quantify the risk and return. The return will be the percent change in closing price of the stock over one year and the “risk” will be the standard deviation of those returns. You can perform this calculation for any time period you want. If you are more interested in a more short-term risk / return analysis you can use daily, weekly, or monthly calculations. Below you can see the code for the calculations and plotting of the annual risk / return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*obf1nskDpr2aX6JZlFb4bg.png" /></figure><p>In the code above you can see I calculated the daily percent change in the closing prices for each stock and multiplied by 100. I then calculated the mean of those returns and multiplied it by 252 which is the number of trading days in a year (cryptocurrencies can be traded 365 days a year, hence the optional function input of crypto = True if you want evaluate cryptocurrencies). This gives me the average annual returns. The annual risk was calculated as the standard deviation multiplied by the square root of the number of trading days in a year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fhakEXw6eviB3ZIbQRO2Eg.png" /></figure><p>This plot confirms what we previously thought: Amazon (AMZN) has both the highest risk, and the highest return. While Campbells (CPB) has the lowest risk but also the lowest return.</p><h3>Correlation of Returns</h3><p>A final analysis for this project is to look at the correlation between the different stocks. Correlation is a coefficient between -1 and 1, and it represents the strength in the relationship between two variables. A correlation of 1 means that as one variable goes up, the other also goes up, and correlation of -1 means that as one variable goes up, the other goes down. It is important to note that correlation does not imply causation, but it can give us good insight into how certain stocks will react under similar market conditions.</p><p>In the code below you can see I calculated the correlation of the stocks using the .corr() function in pandas, and then created a heatmap using plotly. The dataframe “ret” has been defined as the daily returns for each stock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*QQ9iIdUDb8yRM9BdzCwGJQ.png" /></figure><p>In the heatmap below the darker colors represent two variable or stocks that have a higher correlation and the lighter ones represent stocks with a lower correlation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UlPgONzS9mTZsZoH1jzj0A.png" /></figure><p>Diagonally across the heat map you’ll notice 1’s because that is the stocks correlation with itself (a perfect correlation). The weakest correlation is between AMZN and CPB, and the strongest is between AAPL and MSFT.</p><p>Looking at correlation between stocks is key for risk reduction in portfolio management. Combining tech stocks such as Apple and Microsoft could be beneficial if they are both doing well, but it creates more overall risk in your portfolio because it is less diverse.</p><h3>Conclusion</h3><p>This was a simple introduction to exploratory data analysis of stocks using python. We successfully downloaded stock data, compared stock prices over time, calculated risk and return, and created a heatmap to visualize the correlation between the stocks. This project can be improved upon by comparing stocks from different sectors such as tech, healthcare, or utilities. Or choosing a variety of stocks from the same sector and seeing how they differ. In the near future I will share projects on portfolio management, predicting stock prices and returns using machine learning, and algorithmic trading. The entirety of the code for this project can be found on my <a href="https://github.com/StevenMedvetz/stock-analysis">github </a>page. Feel free to reach out to me on <a href="https://www.linkedin.com/in/steven-medvetz-8b62b11a1/">LinkedIn </a>to network!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ac5ab5c2793" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>