<?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 John Bilsel on Medium]]></title>
        <description><![CDATA[Stories by John Bilsel on Medium]]></description>
        <link>https://medium.com/@jgbilsel?source=rss-249476e56c64------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LMvB1bmPWx5QmrU7ZHZ_LA.jpeg</url>
            <title>Stories by John Bilsel on Medium</title>
            <link>https://medium.com/@jgbilsel?source=rss-249476e56c64------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:00:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jgbilsel/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[Typical Data Cleaning in Quant Finance — Python]]></title>
            <link>https://medium.com/@jgbilsel/typical-data-cleaning-in-quant-finance-python-56ddaea335a4?source=rss-249476e56c64------2</link>
            <guid isPermaLink="false">https://medium.com/p/56ddaea335a4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[economics]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[John Bilsel]]></dc:creator>
            <pubDate>Fri, 15 Dec 2023 00:48:16 GMT</pubDate>
            <atom:updated>2023-12-15T00:48:16.257Z</atom:updated>
            <content:encoded><![CDATA[<h3>Typical Data Cleaning in Quant Finance — Python</h3><p>Using Python for data manipulation, cleaning and further analysis can be duanting and frustrating in the very first steps, especially after using something very visually intuitive and interactive like Excel.</p><p>When working in Excel, the data we are given from a particular source e.g., Bloomberg, FRED, Factset etc etc., are often in a cleaner form, making it easier to manipulate, and visualise given the layout of Excel. However, in the context of historical markets data, financials of companies and country macro data it can be often messy and clumped (potentially due to the sheer size of the data).</p><p><strong>Long Data</strong></p><p>A very typical way to store an immense amount of data is a via “long data” form. An example would be if you had 10000 assets, 50 metrics per assets, across 600 dates… This would equal to <em>10000 x 50 x 600 = 300,000,000 </em>data points, and as you can imagine that’d be impossible to store in a more wide form, especially on Excel (think about trying to add columns etc).</p><p><em>Example of Long Data:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*PUfTKvzrCY187VpeJ9VCzw.png" /><figcaption>“Long Data” (Rows may go up to a really large number)</figcaption></figure><p><em>Example of Wide Data:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zTX-laMVZAuk8lgGnyy8_A.png" /><figcaption>“Wide Data” (Data spread across columns, more easily readible/usable)</figcaption></figure><p>Being able to flip through these 2 forms of data before and after data cleaning/manipulation is important in most quantitative research fields, but particularly in finance &amp; statistical application when the “panel” is so large. Below is an example of a typical conversion from long data to wide data using a familiar <strong>pivot table</strong> technique in python:</p><pre>import pandas as pd<br>import numpy as np<br><br><br># Assuming you have long data like the above example, from a messy data source<br>long_data = pd.read_csv(&#39;long_data.csv&#39;, index_col=0)<br><br><br># Before going further, ensure we have a &quot;datetime&quot; object for the date column<br>long_data[&#39;date&#39;] = pd.to_datetime(long_data[&#39;date&#39;])<br><br><br># Also, ensure your &quot;values&quot; are all in numeric form (float64 or int64)<br>long_data[&#39;values&#39;] = pd.to_numeric(long_data[&#39;values&#39;], errors=&#39;coerce&#39;)<br><br><br>#Using &quot;pivot_table&quot;, convert that into a &quot;wide_form&quot; as we see above:<br>wide_data = long_data.pivot_table(index=&#39;date&#39;, <br>                    columns=[&#39;country&#39;,&#39;factor&#39;], values=&#39;values&#39;)</pre><p>The above will “pivot” the long data out and only include the columns in the areas that you have specified. E.g., index = ‘date’ &amp; the columns are now “country” and “factor” in a <em>multi-level</em> form.</p><p><em>Here’s what </em><strong><em>wide_data </em></strong><em>looks like:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NR4pk4pS-mKNoTlErBzhpg.png" /><figcaption>Wide Data in Python (Pivoted out)</figcaption></figure><p>You can simply access the 2 levels in the columns by calling the below:</p><pre>wide_data.columns.levels[0]<br><br># or<br><br>wide_data.columns.get_level_values(1).unique</pre><p>And another important functionaility is using the “.xs”, which essentially returns a cross-section from the dataframe specificed…Let’s say I wanted to only see the “log_excess_return” values for every single country:</p><pre># axis = 1 for columns, level = 1 because factors are on level 1, not 0<br>log_excess_return_table = wide_data.xs(&#39;log_excess_return&#39;, <br>                                                    axis = 1, level = 1)<br># Below displays<br>log_excess_return_table</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*CI6UyJUO9GS0W1gNkoP9nA.png" /><figcaption>“log_excess_return_table” shown using <strong>xs()</strong></figcaption></figure><p><strong>Switching Back to Long Form</strong></p><p>Now that we’ve establish how to get to a more usable “wide_data”, only selecting the data points we’re actually interested in via the <strong>pivot_table(), </strong>how can you go back to that “long” form?</p><p><em>Using “pd.melt()”:</em></p><pre># transpose and reset_index(), before melting back to long-form<br>reverted_back_to_long_data = pd.melt(wide_data.T.reset_index(), <br>      var_name=&#39;date&#39;, id_vars= [&#39;factor&#39;, &#39;country&#39;], value_name = &#39;values&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*JyoUylmYkzFIfCl799M4Fw.png" /><figcaption><strong><em>“reverted_back_to_long_data” </em></strong>displayed</figcaption></figure><h4><strong>Signal Creation, Feature Engineering</strong></h4><p>Up until now we’ve touched on the cleaning, and manipulation of the shape of the data. By using these conversions, we can exlclude data amongst ~300,000,000 data points potentially, and only use what we need. This is very typically done in the context of feature engineering &amp; testing signals for quantitative models. That brings us to a final section which will touch on a very useful <strong>feature engineering</strong> process that can be applied to <strong>wide data.</strong></p><p>Let’s say we wanted to use some of the raw data columns for each asset to create a “signal” that has some predictive information, as apart of either a explanatory variable in a machine learning model, or simply a value each month we can sort portfolios on to see if there is any statistical signifiance of this particular variable:</p><blockquote><strong>Task: </strong>Add a Column to the Wide Data, which is equal to the 2-year rolling volatility of each asset. We use the “log_excess_return” column in level(1) of the columns and use the formula:</blockquote><blockquote><strong>Z.rolling(window = 24).std()</strong></blockquote><pre># Loop over each &quot;country&quot; within the multi-level dataframe<br>for countries in wide_data.columns.get_level_values(0).unique():<br>    <br>    # accessing each country at a time<br>    country = wide_data[countries] <br>    <br>    # compute rolling volatility measure using returns<br>    values = country[&#39;log_excess_return&#39;].rolling(window=24).std() <br><br>    # attach back &amp; set name (because it&#39;s in level 1, it&#39;s in a tuple)<br>    wide_data[(countries, &#39;2Y_rolling_volatility&#39;)] = values </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*JRlzuTLO3fLXSiQzma2ULw.png" /><figcaption>“2Y_rolling volatility” on level 1 of the multi-level column dataframe, wide_data</figcaption></figure><p>Using the technique earlier “<strong>xs()</strong>”, we can isolate the 2Y_rolling volatility values, and plot those values:</p><pre># Isolate<br>volatility_2Y_rolling = wide_data.xs(&#39;2Y_rolling_volatility&#39;, axis=1, level=1)<br><br><br>import hvplot.pandas<br><br>#Plot<br>volatility_2Y_rolling.hvplot(title=&#39;2-Year Rolling Volatility&#39;, grid=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*qCRUk8R8aGSqukcwN1NSIA.png" /><figcaption>Output of Code above</figcaption></figure><p>Hopefully this gives some intuitive code for data cleaning methods in Python. With time it becomes super quick to pivot in and out of different shapes and allows for practical implementations to be more easy flowing.</p><p>Feel free to reach out on LinkedIn for any questions or to discuss Python for Quantitative Finance:</p><p><a href="https://www.linkedin.com/in/john-bilsel-444471163/">https://www.linkedin.com/in/john-bilsel-444471163/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56ddaea335a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining your Macroeconomic Data through the FRED API — Python]]></title>
            <link>https://medium.com/@jgbilsel/streamlining-your-macroeconomic-data-through-the-fred-api-python-52d89eff0262?source=rss-249476e56c64------2</link>
            <guid isPermaLink="false">https://medium.com/p/52d89eff0262</guid>
            <category><![CDATA[economics]]></category>
            <category><![CDATA[macroeconomics]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[John Bilsel]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 09:17:50 GMT</pubDate>
            <atom:updated>2023-06-20T09:19:15.620Z</atom:updated>
            <content:encoded><![CDATA[<h3>Streamlining your Macroeconomic Data through the FRED API — Python</h3><p>If you haven’t heard of Federal Reserve Economic Data (FRED) and you’re keen to get your hands dirty with macroeconomic and financial markets data, you’re missing out. FRED is an extensive economic database, maintained by the Federal Reserve Bank of St. Louis. The website provides access to a vast collection of economic data, including macro indicators, financial market data, and is specifically extensive in its country-specific stats.</p><p>Typically, extracting data from FRED involves downloading Excel files from the website and manually adjusting them to incorporate the data into your datasets and analysis. While this method is functional, we can significantly enhance workflows by leveraging the FRED API. By utilizing the API, exporting macroeconomic data becomes a streamlined and cohesive process.</p><p>In the context of statistical modeling, establishing a system that continuously and effortlessly updates the data offers the benefits of repeatability and allows researchers to allocate more time to other areas of their work. A dynamic and modular baseline becomes crucial for efficiency and reduces the likelihood of errors, particularly when projects gets more complex.</p><p>This post will outline how one may use the FRED API in the context of quantitative finance, where often we are required to handle large amounts of data from diverse sources<em>. </em>Specifically, going from the raw data form we see on the FRED website to to a panel that is grouped by sub-categories within economic data and other markets data. Furthermore, an example of a visualization of the data will be shown.</p><h3><strong>Getting Started</strong></h3><p>Before getting started with the code, the first step is to<strong> <em>Get an API Key from </em></strong><a href="https://fredaccount.stlouisfed.org/apikeys"><strong><em>https://fredaccount.stlouisfed.org/apikeys</em></strong></a></p><p>This is super simple and the only requirement is that you have a FRED account. Below is a very simple example of extracting the <em>US Unemployment Rate:</em></p><pre>from fredapi import Fred<br>import pandas as pd<br>import numpy as np<br>import hvplot.pandas<br><br>f = Fred(api_key = &#39;your API Key goes here&#39;)<br><br># Retrieve the raw data from FRED<br>df = f.get_series(&#39;UNRATE&#39;, observation_start=&#39;2006-1-1&#39;, frequency = &#39;m&#39;)<br><br># Plot<br>df.hvplot(title = &quot;Unemployment Rate&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*2C4GZyZny-CGxIy3RovXiA.png" /></figure><p><strong>Ignoring “Revised” Data:</strong></p><p>Going further than just the simple <em>“get_series”</em>, which is the latest, revised version of the data, we can get the<strong> point in time</strong> data by calling <em>“get_series_first_release”:</em></p><pre>df2 = f.get_series_first_release(&#39;UNRATE&#39;)<br><br># use concat to combine the 2 Series types<br>combine = pd.concat([df,df2], join = &#39;inner&#39;, axis = 1)<br>combine.columns = [&#39;unrevised&#39;, &#39;revised&#39;]<br><br># Plot<br>combine.hvplot(title = &#39;Revised Vs Unrevised: Unemployment Rate&#39;, <br>               y = [&#39;unrevised&#39;, &#39;revised&#39;], <br>               color = [&#39;blue&#39;,&#39;gray&#39;], grid = True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*tnTjHo9mwjN8UWXxXLHFfg.png" /></figure><p>As seen above, there are slight differences in the data due to that revision that was made. Using revised data in finance can cause look-ahead biases and inflate results, which one should be mindful of.</p><h3><strong>Search function (The real deal)</strong></h3><p>The FRED API also has a “search” function, which essentially allows you to look up the actual name of the raw series, and it will show the data points with the most similar name. The more specific you get, the better:</p><pre>f.search(&quot;Australia CPI&quot;)</pre><p>The output is a huge dataframe that contains information on each series:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*uk9euQ0tT-8jjj4QmKdVRA.png" /><figcaption>Example output of the f.search() function</figcaption></figure><p>From this, we can isolate the specific data series that we’d like to work with.</p><h3><strong>Creating a structured data frame from raw-data — GDP and Yields</strong></h3><p>Series ID names can be found on the page of the specific series.</p><pre>columns = [&#39;AUS&#39;,&#39;JAP&#39;,&#39;USA&#39;,&#39;GBR&#39;,&#39;KOR&#39;]<br><br>aus = f.get_series(&#39;NGDPRSAXDCAUQ&#39;)<br>jap = f.get_series(&#39;JPNRGDPEXP&#39;)<br>us = f.get_series(&#39;GDPC1&#39;)<br>uk = f.get_series(&#39;NGDPRSAXDCGBQ&#39;)<br>korea = f.get_series(&#39;NGDPRSAXDCKRQ&#39;)<br><br>#Combine all the single series, only take common dates using &quot;inner&quot;<br>gdp_global = pd.concat([aus, jap, us, uk, korea], join=&#39;inner&#39;, axis=1)<br><br># Creare YoY Real GDP (divided by 4 because we have quarterly data) &amp; Drop NA&#39;s<br>gdp_global = ((gdp_global / gdp_global.shift(4)) - 1).dropna(axis = 0)<br><br>gdp_global.columns = columns<br><br># Plot<br>gdp_global.hvplot(title = &#39;Global GDP&#39;, grid = True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*l1PvGu11BLItBh5X75OKRA.png" /><figcaption>GDP Data from FRED</figcaption></figure><p>Above, we have pulled the GDP for 5 countries, combined the series into 1 dataframe and then plotted them against each other. Now let’s extract the 10-year government bond yields for respective countries, to then after combine the dataframes <em>(use quarterly for this example to be able to combine with GDP)</em>:</p><pre># Extract the 10Y Government Bond Yields for each country (make quarterly):<br>aus_y = f.get_series(&#39;IRLTLT01AUM156N&#39;, frequency = &#39;q&#39;)<br>jap_y = f.get_series(&#39;IRLTLT01JPM156N&#39;, frequency = &#39;q&#39;)<br>us_y = f.get_series(&#39;IRLTLT01USM156N&#39;, frequency = &#39;q&#39;)<br>uk_y = f.get_series(&#39;IRLTLT01GBM156N&#39;, frequency = &#39;q&#39;)<br>korea_y = f.get_series(&#39;IRLTLT01KRM156N&#39;, frequency = &#39;q&#39;)<br><br># Combine again<br>global_10y_yields = pd.concat([aus_y, jap_y, us_y, uk_y, korea_y], join=&#39;inner&#39;, axis=1)<br><br>global_10y_yields.columns = columns<br><br># Plot<br>global_10y_yields.hvplot(title = &#39;Global 10Y Yields&#39;, grid = True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*wSnMZB_bJ0HA_qsHaS0pKw.png" /><figcaption>10Y Gov yields (quarterly) from FRED</figcaption></figure><p>To build out the database for each country, we can use <strong>“multi-level indexing” </strong>on the columns, let’s see below:</p><pre># keys allows for multi-level columns<br>country_df = pd.concat([gdp_global, global_10y_yields], axis=1, <br>                        keys=[&#39;GDP&#39;, &#39;10Y Yields&#39;])<br><br>country_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*4cMa6igUkrBFHutLVtDRfA.png" /><figcaption>Example of the dataframe with multi-index columns</figcaption></figure><p>Let’s say we had many variables for each country, perhaps 20–30, we can use the <strong><em>“xs()”</em></strong> function to select all variables from 1 specific country:</p><pre># Selects only the Korean variables.<br>korea = country_df.xs(&#39;KOR&#39;, level=1, axis=1)<br><br># Show<br>korea</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*rxlIyB07TE26hHLDtA6ZGA.png" /><figcaption>Korean Variables only, from Fred</figcaption></figure><p>All the parameters and arguments used within the calls are listed here:</p><p><a href="https://fred.stlouisfed.org/docs/api/fred/series_observations.html">fred/series/observations</a></p><p>Feel free to reach out on LinkedIn for any questions or to discuss Python for Quantitative Finance:</p><p><a href="https://www.linkedin.com/in/john-bilsel-444471163/">https://www.linkedin.com/in/john-bilsel-444471163/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52d89eff0262" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factor Portfolio Construction — Python]]></title>
            <link>https://medium.com/@jgbilsel/factor-portfolio-construction-python-7b94a4bad08d?source=rss-249476e56c64------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b94a4bad08d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[fama-french]]></category>
            <category><![CDATA[momentum]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <dc:creator><![CDATA[John Bilsel]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 07:23:36 GMT</pubDate>
            <atom:updated>2023-06-18T12:36:33.970Z</atom:updated>
            <content:encoded><![CDATA[<h3>Factor Portfolio Construction — Python</h3><p>In quantitative finance, a typical technique used for testing the effectiveness of a signal or a “factor” is constructing long-short portfolios. This refers to going long a basket of securities that rank the highest based on signal “X”, and going short a basket which rank the lowest based on the same signal. Within this process, it’s also common to see the respective portfolios (highest ranked to lowest ranked) split into quintiles or deciles to compare how the securities in the middle (not super exposed/not exposed to signal “X”).</p><p>This week’s tutorial focuses on translating theoretical concepts like factor portfolio construction into practical implementation using Python. We’ll delve into a widely studied factor called “Momentum” and explore how to sort stocks based on their 12-month cumulative return. As this blog emphasizes the practical applications of common techniques in empirical finance, we’ll primarily focus on the implementation rather than delving into the detailed intuition behind Momentum’s effectiveness or the strategy’s limitations and intricacies. By the end of this tutorial, you’ll gain hands-on experience in applying Momentum to construct factor portfolios, enabling you to further explore and analyze this strategy’s potential in your investment endeavors.</p><p>In this example we look at the underlying companies on the ASX 200, and use the <em>‘pd.read_html’ </em>function from pandas to extract the tickers of the companies:</p><pre>import pandas as pd<br>import numpy as np<br>import yfinance as yf<br>import math<br>import hvplot.pandas<br>import holoviews as hv<br>hv.extension(&#39;bokeh&#39;)<br><br># [1] is used to select the specific table needed from the Wikipedia website<br>asx_data = pd.read_html(&#39;https://en.wikipedia.org/wiki/S%26P/ASX_200&#39;)[1]<br><br># Put tickers into a list<br>tickers = asx_data[&#39;Code&#39;].to_list()</pre><p>“tickers” is now a list of company tickers on the ASX 200, which we can put into the yahoo finance API call to extract their “Adjusted Close” prices.</p><pre># Only need the [&#39;Adj Close&#39;]<br>prices = yf.download(tickers,start=&#39;2005-01-01&#39;, end=&#39;2023-05-31&#39;)[&#39;Adj Close&#39;]<br><br># Change to datetime<br>prices.index = pd.to_datetime(prices.index)<br><br># Convert from daily to monthly prices using &#39;M&#39;<br>prices_monthly = prices.resample(&#39;M&#39;).last()<br><br># Drop the columns with insufficient data<br>prices_monthly_clean = prices_monthly.dropna(axis=1)</pre><p>Following this, you should have a data frame of prices that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*u0NRrtwiLTuw-yEGqGPL_Q.png" /></figure><p><strong>Now that we have our prices, we need to:</strong></p><p>(1) Create a data frame of the “Signal” — 12-month cumulative returns for each stock</p><p>(2) Calculate monthly returns of every stock, to later calculate portfolio returns (log return is also very common)</p><pre># Use &quot;shift() to move the dataframe up and down relate to the index<br>momentum_12 = (prices_monthly_clean/prices_monthly_clean.shift(12))-1<br>monthly_returns = (prices_monthly_clean/prices_monthly_clean.shift(1))-1.<br><br># Drop the 1 or 2 rows with NA&#39;s<br>momentum_12 = momentum_12.dropna(axis=0)<br>monthly_returns = monthly_returns.dropna(axis=0)</pre><p>We can now begin to create “ranks” for the stocks each month. In this example, we will form 5 portfolios each month based on their ranking from highest to lowest of their 12-month cumulative return (momentum signal).</p><p><em>“pd.qcut” simply cuts the ranked values into however many groups you want e.g. q=5</em></p><pre># Establish a df for the ranks<br>quintile_ranks = pd.DataFrame(index=momentum_12.index, columns=momentum_12.columns)<br><br># Place each stock in a &quot;quintile&quot; bucket, at each &quot;date&quot; (rows)<br>for date in momentum_12.index:<br>    row_values = momentum_12.loc[date] # looping values each row<br>    ranks = pd.Series(row_values).rank(method=&#39;max&#39;) # set rank at each row<br>    quintiles = pd.qcut(ranks, q=5, labels=False) # divide into quintiles<br><br>    # Create dataframe with ranks for each stock at each month(4=high, 0=low)<br>    quintile_ranks.loc[date] = quintiles </pre><p>At this point, the data frame <em>“quintile_ranks” </em>contains the a the quintile (0–4) of each stock at each point in time.</p><p>The final step is to calculate the quintile portfolio returns and find out whether stocks that have a <strong>high 12-month cumulative return</strong> earn excess return over stocks with a <strong>low 12-month cumulative return.</strong></p><p>We assume an ‘equal-weight’ approach within each quintile, and to do this we simply take <em>df.mean(axis=1).</em></p><pre>quintile_dfs = {} <br>portfolio_returns = pd.DataFrame()<br><br># Iterate for each quintile, and form portfolios accordingly<br>for quintile in range(5):<br>    <br>    # Only take returns if they&#39;re in quintile associated with the current loop.<br>    filtered_df = monthly_returns[quintile_ranks == quintile]<br>    <br>    # shift to &quot;t+1&quot; return as rank at time &quot;t&quot; corresponds to return at time &quot;t+1&quot;<br>    filtered_df_shifted = filtered_df.shift(-1).dropna(axis=0)<br><br>    # Put those returns into dictionairy &quot;quintile_dfs&quot;<br>    quintile_dfs[quintile] = filtered_df_shifted<br><br>    #For Equal-Weight, simply take the average return across stocks within each quintile dataframe<br>    portfolio_returns[quintile] = quintile_dfs[quintile].mean(axis=1).dropna()<br><br><br># Plot the cumulative return<br>(1+portfolio_returns).cumprod().hvplot(title = &#39;Portfolios - Log Scale&#39;, height = 300, width= 500, grid=True, logy=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_Q7j_IFKgdSdtzkOiZjjGw.png" /><figcaption>Log-Scaled Cumulative Returns</figcaption></figure><p>As seen above, the “4” portfolio, which contains the securities with the highest momentum at each month significantly outperforms the rest over approximately ~ 18 years. Though, a huge portion of a “long-short” between the highest and the lowest would actually be coming from the “low momentum” stocks given their very poor performance. Subtracting returns of the (4) and (0) would give you a market-neutral factor portfolio (no equity beta).</p><p>To tie this all together in a cleaner form, we can look at the risk-adjusted returns of these 5 portfolios using a simple <strong>Annualized Return / Annualized Volatility </strong>calculation:</p><pre># Calculate Ann Return<br>cumulative_return = (1 + portfolio_returns).prod() - 1<br>num_periods = len(monthly_returns)<br>annualized_return = (1 + cumulative_return) ** (12 / num_periods) - 1<br><br># Calculate Ann Vol<br>ann_vol = portfolio_returns.std()*math.sqrt(12)<br><br># Calculate Risk-adjusted-return<br>risk_adj_return = annualized_return/ann_vol<br>risk_adj_return.hvplot(kind=&#39;bar&#39;,title = &#39;Quintile Momentum portfolio - Risk Adjusted Return&#39;, height = 300, width= 500, grid=True, color = &#39;teal&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Kfkuqd9qw4lGH6G3LEaf4w.png" /><figcaption>0 (Lowest Momentum) to 4 (Highest Momentum) stocks</figcaption></figure><p>It’s clear that as you start to get more exposure to “high momentum stocks” in our sample, you achieved a higher risk-adjusted return historically.</p><p>A very important note about this process is the inherent biases and errors that may be caused when constructing these to evaluate the validity of a particular “signal”.</p><p><strong>Important Biases and Considerations</strong></p><p>(i) We run into survivorship-bias in this example, as we dropped the “stocks” (columns) that did not have enough data back to 2005, and didn’t include stocks that may have been de-listed from the ASX 200.</p><p>(ii) The testing period perhaps was not long enough, and should be rigioursly assessed across many samples for true robustness.</p><p>(iii) Arguably the most important is “trading-costs”. Momentum is traditionally a “fast-moving signal”, which means the portfolio turns over quite a lot. This test above does not account for the transaction costs associated with turning a portfolio over each month, and hence the return is higher than it otherwise would be.</p><p>Overall, this task was more to demonstrate the practical application in Python of long-short portfolios and less about the nuances and weeds of the process / technique.</p><p>Feel free to reach out on LinkedIn for any questions or to discuss Python for Quantitative Finance:</p><p><a href="https://www.linkedin.com/in/john-bilsel-444471163/">https://www.linkedin.com/in/john-bilsel-444471163/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b94a4bad08d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Iterative Regressions in Finance -Python]]></title>
            <link>https://medium.com/@jgbilsel/iterative-regressions-in-finance-python-9e0e76c6c98?source=rss-249476e56c64------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e0e76c6c98</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[for-loop]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[iteration]]></category>
            <dc:creator><![CDATA[John Bilsel]]></dc:creator>
            <pubDate>Mon, 29 May 2023 13:15:20 GMT</pubDate>
            <atom:updated>2023-05-29T13:15:20.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/416/0*vZpLxNK1CftjK92H" /></figure><p>Many tutorials follow a approach to show you how to run a simple linear regression in Python using one of the many packages available. Whilst this may be useful for general knowledge, translating it into a practical example may be somewhat challenging. Research in quantitative finance often involves several regressions being run with different conditions and model specifications, though several python tutorials never outline how to combine ideas like “looping” , “if-else statements” and the techniques which are being utilitsed within statistical packages such as sklearn or statsmodel.</p><p>A simple tutorial may give you something like this:</p><pre>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import r2_score<br>import pandas as pd<br>import numpy as np<br><br>y = dataframe of &quot;dependent variables&quot; <br>X = dataframe of &quot;independent variables&quot;<br><br>model = LinearRegression().fit(X,y)<br><br>print(model.coef_)<br>print(model.intercept_)<br><br>y_pred = model.predict(X)</pre><p>This works fine and is a good starter, but what if we had 500 y-variables we want to test individually against 5 common factors……or what about 4 dataframes of independent variables for 10 asset classes on the columns, and 1 dataframe of the y-variables you are trying to predict for those asset classes.</p><p>In both these situations, the simple <em>“model = LinearRegression().fit(X,y)”</em> unfortunately doesn’t cut it.</p><p><strong><em>Before we move forward with the examples, here’s what the generic data structure of what we’re talking about would look like:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*cGcWrtFh1vhxM7Zovm2TWg.png" /><figcaption>“Sample Dataframe for y or X variables for iterative regressions”</figcaption></figure><h3><strong>Below shows how to approach some of these more iterative scenarios:</strong></h3><ol><li><strong><em>500 y-variables on 5 common factors:</em></strong></li></ol><p>Here we are simply trying to compute a regression for each fund or singular asset.</p><pre>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import r2_score<br>import pandas as pd<br>import numpy as np<br><br>fund_returns = &quot;dataframe of 500 funds across time&quot;<br>factors = &quot;5 common factors&quot;<br><br>#Establish an empty Dictionary<br>results = {}<br><br>#first loop through the &quot;columns&quot; in the y dataframe<br><br>for fund in y.columns:<br><br>            # Define the &quot;iterative&quot; variable &quot;y&quot; that loops through each column<br>            y = fund_returns[fund].values.reshape(-1,1)<br><br>            #Run Regressions<br>            model = LinearRegression.fit(X,y)<br>            <br>            #model outputs<br>            coefs = model.coef_[0]<br>            intercept = model.intercept_<br>            <br>            #using the &quot;fund&quot; iterative value and outputs, connect values to the dictionary<br>            results[fund] = {&#39;Intercept&#39;: intercept, &#39;Coefficients&#39;: coefs}<br>            <br><br>#outside of the loop, create dataframe from the results dictionairy <br>results_df = pd.DataFrame.from_dict(results, orient=&#39;index&#39;)<br><br>print(results_df)</pre><p><strong>2. <em>10 assets across 4 seperate dataframes (3 being independent varaibles and 1 as the “y” variable dataframe)</em></strong></p><p>In this scenario, we have different factors for each asset, and therefore we must loop over every dataframe that is involved in the asset specific regressions. This may be common in something like “countries” or “regions”.</p><pre>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import r2_score<br>import pandas as pd<br>import numpy as np<br><br>y_df = &quot;dependent variable df&quot;<br>x1_df = &quot;independent variable df #1&quot;<br>x2_df = &quot;independent variable df #2&quot;<br>x3_df = &quot;independent variable df #3&quot;<br><br>#Establish an empty Dictionary<br>results = {}<br><br>#first loop through the &quot;columns&quot; in the y dataframe<br><br>for fund in y.columns:<br><br>            # Define the &quot;iterative&quot; variable that loops through each column<br>            y = yf[fund]<br>            x1 = x1_df[fund]<br>            x2 = x2_df[fund]<br>            x3 = x3_df[fund]<br><br>            #Run Regressions<br>            model = LinearRegression.fit({&#39;x1&#39;:x1, &#39;x2&#39;:x2, &#39;x3&#39;:x3}, y)<br>            <br>            #model outputs<br>            coefs = model.coef_<br>            intercept = model.intercept_<br>            <br>            #using the &quot;fund&quot; iterative value and outputs, connect values to the dictionary<br>            results[fund] = {&#39;Intercept&#39;: intercept, &#39;Coefficients&#39;: coefs}<br><br><br>#outside of the loop, create dataframe from the results dictionairy <br>results_df = pd.DataFrame.from_dict(results, orient=&#39;index&#39;)<br><br>print(results_df)</pre><p>Just a note, both of these examples are only the “in-sample” components and are more to illustrate the iterative mechanics rather than robust machine learning tests.</p><p>Feel free to reach out on LinkedIn for any questions or to discuss Python for Quantitative Finance:</p><p><a href="https://www.linkedin.com/in/john-bilsel-444471163/">https://www.linkedin.com/in/john-bilsel-444471163/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e0e76c6c98" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>