<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ finance - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ finance - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 06 May 2026 22:13:46 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/finance/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ A Comprehensive Guide to Financial Storytelling using Data Visualization ]]>
                </title>
                <description>
                    <![CDATA[ In any analysis project, raw tables of numbers often don’t tell the full story. Visualisations simplify complexity by transforming data into shapes that our brains can quickly understand, emphasising  ]]>
                </description>
                <link>https://www.freecodecamp.org/news/financial-storytelling-using-data-visualization/</link>
                <guid isPermaLink="false">69b1ced06c896b0519c207be</guid>
                
                    <category>
                        <![CDATA[ data visualization ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Data Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nikhil Adithyan ]]>
                </dc:creator>
                <pubDate>Wed, 11 Mar 2026 20:21:36 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/64ab3674-959f-44b5-8be2-4ca00a798621.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In any analysis project, raw tables of numbers often don’t tell the full story. Visualisations simplify complexity by transforming data into shapes that our brains can quickly understand, emphasising trends, outliers, and regime shifts that might be overlooked in raw data.</p>
<p>This is especially vital in finance and trading, where clear visuals can uncover risks, opportunities, and patterns, directly affecting decisions on position sizing, timing, and confidence.</p>
<p>Today, we'll use FMP APIs to interpret earnings data: extracting announcements, surprises, and price reactions across almost 1,000 stocks to identify actionable patterns in post‑earnings movements.</p>
<p>Here’s exactly what we’ll build:</p>
<ul>
<li><p><strong>Sector heatmap</strong>: Maps strongest 3/10-day post-earnings reactions by sector/market-cap buckets.</p>
</li>
<li><p><strong>EPS scatter</strong>: Tests if earnings beats drive returns (sector-colored, with regression).</p>
</li>
<li><p><strong>Return violins</strong>: Shows 3-day post-earnings volatility/skew by sector and market-cap.</p>
</li>
<li><p><strong>Mega-tech time series</strong>: Tracks AAPL/MSFT/NVDA post-earnings patterns over time.</p>
</li>
<li><p><strong>Monthly seasonality</strong>: Reveals calendar edges in post-earnings returns/surprises.</p>
</li>
<li><p><strong>Regime cross-section</strong>: Tests sector robustness across bull/bear/sideways markets.</p>
</li>
</ul>
<h3 id="heading-what-well-cover">What we'll cover:</h3>
<ol>
<li><p><a href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a href="#heading-data-extraction">Data Extraction</a></p>
</li>
<li><p><a href="#heading-storytelling-with-charts-and-visuals">Storytelling with Charts and Visuals</a></p>
<ul>
<li><p><a href="#heading-sector-heatmap">Sector Heatmap</a></p>
</li>
<li><p><a href="#heading-megacap-tech-time-series">Mega‑Cap Tech Time Series</a></p>
</li>
<li><p><a href="#heading-eps-surprise-scatter-plot">EPS Surprise Scatter Plot</a></p>
</li>
<li><p><a href="#heading-return-distribution-violins">Return Distribution Violins</a></p>
</li>
<li><p><a href="#heading-monthly-seasonality">Monthly Seasonality</a></p>
</li>
<li><p><a href="#heading-regime-crosssection">Regime Cross-Section</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-what-did-we-get-out-of-all-this-storyline">What Did We Get Out of All This Storyline?</a></p>
</li>
<li><p><a href="#heading-final-thoughts">Final Thoughts</a></p>
</li>
</ol>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along, you should be comfortable with Python and basic data manipulation in pandas.</p>
<p>This is a code-first guide. I’ll focus on the workflow and the story the charts reveal, and I won’t explain every line of Python. You should be comfortable reading pandas code, loops, and basic plotting logic so you can follow along without needing a step-by-step breakdown of each block.</p>
<p>You’ll need:</p>
<ul>
<li><p>Python 3.10+</p>
</li>
<li><p>A Financial Modeling Prep (FMP) API key</p>
</li>
<li><p>pandas, numpy, matplotlib, seaborn, scipy installed</p>
</li>
<li><p>Enough local compute and patience to run API loops across a large stock universe</p>
</li>
</ul>
<h2 id="heading-data-extraction">Data Extraction</h2>
<p>In the first part of this article, we need to collect all the data required for our visualisation exercise. Using FMP’s Stock Screener API, we will retrieve NASDAQ stocks. The first API call will return 1,000 stocks.</p>
<pre><code class="language-python">import requests
import pandas as pd
import numpy as np
import json
from datetime import datetime, timedelta
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats

token = 'YOUR FMP TOKEN'

url = f'https://financialmodelingprep.com/stable/company-screener'
querystring = {"apikey":token,"country":"US", "exchange": "NASDAQ", "isActiveTrading": True, "isEtf": False, "isFund": False}
resp = requests.get(url, querystring).json()

df_universe = pd.DataFrame(resp)
df_universe = df_universe[df_universe['exchangeShortName'] == 'NASDAQ']
df_universe
</code></pre>
<p>This will give us 1,000 stocks! Next, we'll bin the market capitalisation to gain a better understanding of the results later on, and we will keep only four columns that are necessary: the symbol, name, market cap, and sector.</p>
<pre><code class="language-python">bins = [0,
        250_000_000,    # 250M
        2_000_000_000,  # 2B
        10_000_000_000, # 10B
        200_000_000_000,# 200B
        float("inf")]

labels = ["Micro", "Small", "Mid", "Large", "Mega"]

df_universe["marketCap"] = pd.cut(df_universe["marketCap"], bins=bins, labels=labels, right=False)
df_universe = df_universe[['symbol', 'companyName', 'marketCap', 'sector']]
df_universe
</code></pre>
<img src="https://cdn-images-1.medium.com/max/1000/0*rAiF7Q5TqSNlRG4h.png" alt="0*rAiF7Q5TqSNlRG4h" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>Now it is time to retrieve the earnings using FMP’s Earnings Report API. We'll loop through each symbol and collect all the earnings the endpoint provides to us.</p>
<pre><code class="language-python">symbols = df_universe['symbol'].to_list()

all_dfs = []

for symbol in symbols:
    url = f"https://financialmodelingprep.com/stable/earnings?symbol={symbol}"
    params = {"apikey": token}
    resp = requests.get(url, params=params)

    if resp.status_code != 200:
        print(f"Error for {symbol}: {resp.status_code} - {resp.text}")
        continue

    data = resp.json()
    if not data:
        print(f"No data for {symbol}")
        continue

    df_symbol = pd.DataFrame(data)
    df_symbol["symbol"] = symbol
    all_dfs.append(df_symbol)

# Single DataFrame with all earnings
df_earnings = pd.concat(all_dfs, ignore_index=True)
df_earnings = df_earnings.dropna(subset=['epsActual', 'epsEstimated', 'revenueActual','revenueEstimated'])
df_earnings
</code></pre>
<p>Now we'll calculate the surprise, both for earnings and revenue in percentage terms, so we can later compare apples with apples! We'll keep everything from 2010 onwards.</p>
<pre><code class="language-python">df_earnings["eps_surprise"] = ((df_earnings["epsActual"] - df_earnings["epsEstimated"]) /
                               abs(df_earnings["epsEstimated"]) * 100).round(2)

df_earnings["revenue_surprise"] = ((df_earnings["revenueActual"] - df_earnings["revenueEstimated"]) /
                                   abs(df_earnings["revenueEstimated"]) * 100).round(2)

df_earnings = df_earnings[['symbol', 'date', 'eps_surprise', 'revenue_surprise']]

df_earnings["date"] = pd.to_datetime(df_earnings["date"])
df_earnings = df_earnings[df_earnings["date"] &gt; "2009-12-31"]
</code></pre>
<p>Lastly, as a final step in gathering the data needed for visualization, using FMP’s Historical Index Full Chart API, we'll loop through the stocks in our dataframe, retrieve the historical daily prices, and calculate the return of the stock 3 and 10 trading days before and after the earnings announcement.</p>
<pre><code class="language-python">unique_symbols = df_earnings["symbol"].unique()

price_results = []

print(f"Processing {len(unique_symbols)} symbols...")

for symbol in unique_symbols:
    # Fetch full historical prices
    url = f"https://financialmodelingprep.com/stable/historical-price-eod/full"
    params = {"apikey":token, "symbol":symbol, "from":'2009-10-01'}
    resp = requests.get(url, params=params)

    if resp.status_code != 200:
        print(f"Error for {symbol}: {resp.status_code}")
        continue

    data = resp.json()

    hist_df = pd.DataFrame(data)
    hist_df["date"] = pd.to_datetime(hist_df["date"])
    hist_df = hist_df.sort_values("date").reset_index(drop=True)

    # Get matching earnings rows
    earnings_symbol = df_earnings[df_earnings["symbol"] == symbol].copy()

    for _, row in earnings_symbol.iterrows():
        earn_date = pd.to_datetime(row["date"]).date()

        # === 3-DAY WINDOWS ===
        pre3_mask = (hist_df["date"].dt.date &lt; earn_date) &amp; \
                    (hist_df["date"].dt.date &gt;= earn_date - timedelta(days=10))
        pre3 = hist_df[pre3_mask].tail(3)

        post3_mask = (hist_df["date"].dt.date &gt; earn_date) &amp; \
                     (hist_df["date"].dt.date &lt;= earn_date + timedelta(days=10))
        post3 = hist_df[post3_mask].head(3)

        pre3_start = pre3["close"].iloc[0] if len(pre3) &gt;= 3 else None
        pre3_end = pre3["close"].iloc[-1] if len(pre3) &gt;= 1 else None
        post3_end = post3["close"].iloc[-1] if len(post3) &gt;= 3 else None

        pct_pre_3d = ((pre3_end - pre3_start) / pre3_start * 100) if pre3_start and pre3_end else None
        pct_post_3d = ((post3_end - pre3_end) / pre3_end * 100) if pre3_end and post3_end else None

        # === 10-DAY WINDOWS ===
        pre10_mask = (hist_df["date"].dt.date &lt; earn_date) &amp; \
                     (hist_df["date"].dt.date &gt;= earn_date - timedelta(days=20))
        pre10 = hist_df[pre10_mask].tail(10)

        post10_mask = (hist_df["date"].dt.date &gt; earn_date) &amp; \
                      (hist_df["date"].dt.date &lt;= earn_date + timedelta(days=20))
        post10 = hist_df[post10_mask].head(10)

        pre10_start = pre10["close"].iloc[0] if len(pre10) &gt;= 10 else None
        pre10_end = pre10["close"].iloc[-1] if len(pre10) &gt;= 1 else None
        post10_end = post10["close"].iloc[-1] if len(post10) &gt;= 10 else None

        pct_pre_10d = ((pre10_end - pre10_start) / pre10_start * 100) if pre10_start and pre10_end else None
        pct_post_10d = ((post10_end - pre10_end) / pre10_end * 100) if pre10_end and post10_end else None

        price_results.append({
            "symbol": symbol,
            "earn_date": earn_date,
            "month": earn_date.month,
            "pct_pre_3d": round(pct_pre_3d, 2) if pct_pre_3d else None,
            "pct_post_3d": round(pct_post_3d, 2) if pct_post_3d else None,
            "pct_pre_10d": round(pct_pre_10d, 2) if pct_pre_10d else None,
            "pct_post_10d": round(pct_post_10d, 2) if pct_post_10d else None,
            "eps_surprise": row["eps_surprise"],
            "revenue_surprise": row["revenue_surprise"]
        })



df_earnings = pd.DataFrame(price_results)
df_earnings.dropna(inplace=True)
df_earnings = df_universe.merge(df_earnings, on="symbol")
df_earnings
</code></pre>
<p>As you can see, at the end of the code, we have also merged the initial dataset, so all the information, such as name, marketCap, and sector, is now in a single dataset.</p>
<h2 id="heading-storytelling-with-charts-and-visuals">Storytelling with Charts and Visuals</h2>
<h3 id="heading-sector-heatmap">Sector Heatmap</h3>
<p>First, we'll present the Sector Heatmap of average 3-day post-earnings returns segmented by sector and market-cap category. This basic visualisation highlights areas with the most significant reactions, enabling traders to swiftly identify high-alpha sectors and market caps for earnings strategies.</p>
<pre><code class="language-python"># Aggregate: average post-earnings returns and EPS surprise
agg = (
    df_earnings
    .dropna(subset=['pct_post_3d', 'pct_post_10d', 'eps_surprise', 'marketCap', 'sector'])
    .groupby(['sector', 'marketCap'])
    .agg(
        avg_post3d=('pct_post_3d', 'mean'),
        avg_post10d=('pct_post_10d', 'mean'),
        avg_eps_surprise=('eps_surprise', 'mean')
    )
    .reset_index()
)

# Heatmap: average 3-day post-earnings return
heatmap_3d = agg.pivot(index='sector', columns='marketCap', values='avg_post3d')

plt.figure(figsize=(12, 8))
sns.heatmap(
    heatmap_3d,
    annot=True,
    fmt='.2f',
    cmap='RdYlGn',
    center=0,
    linewidths=0.5,
    linecolor='grey'
)
plt.title('Average 3-Day Post-Earnings Return by Sector and Market-Cap Bucket')
plt.xlabel('Market-cap bucket')
plt.ylabel('Sector')
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
plt.show()
</code></pre>
<img src="https://cdn-images-1.medium.com/max/1000/0*u0AOCzVCWJ4NQMIS.png" alt="Heatmap of average 3-day post-earnings returns by sector and market-cap bucket for NASDAQ stocks" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>Consumer Cyclical and Materials are performing really well, with small and mid caps seeing positive reactions over 1.1%. Real Estate is also doing great, jumping up to +4.0% in mid caps. Energy and Financials are holding steady, staying close to zero. Technology, on the other hand, is showing more muted gains, under 1.1%, indicating there might be limited immediate upside from the big tech earnings.</p>
<p>Building on the 3‑day heatmap, we'll now look at the Sector Heatmap for average <em>10‑day</em> post‑earnings returns by sector and market‑cap category. This extends the timeframe to capture momentum persistence, revealing which sectors maintain or reverse short‑term reactions.</p>
<pre><code class="language-python"># Heatmap: average 10-day post-earnings return
heatmap_10d = agg.pivot(index='sector', columns='marketCap', values='avg_post10d')

plt.figure(figsize=(12, 8))
sns.heatmap(
    heatmap_10d,
    annot=True,
    fmt='.2f',
    cmap='RdYlGn',
    center=0,
    linewidths=0.5,
    linecolor='grey'
)
plt.title('Average 10-Day Post-Earnings Return by Sector and Market-Cap Bucket')
plt.xlabel('Market-cap bucket')
plt.ylabel('Sector')
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
plt.show()
</code></pre>
<img src="https://cdn-images-1.medium.com/max/1000/0*DB7p_HYR-6jWYaaP.png" alt="Heatmap of average 10-day post-earnings returns by sector and market-cap bucket for NASDAQ stocks" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>Consumer Cyclical stands out with peaks at 3.2% (mega caps), and Industrials and Health Care show consistent gains in mid and large caps around 1.1%. Real Estate has eased after its 3-day surge. Technology has seen a small boost in mega caps (+1.8%) but remains less active overall compared to cyclicals.</p>
<h3 id="heading-megacap-tech-time-series"><strong>Mega‑Cap Tech Time&nbsp;Series</strong></h3>
<p>Extending the heatmaps, we’ll now look at a Mega-Cap Tech time series. It tracks 10-day post-earnings returns over time for AAPL, MSFT, NVDA, and a few other mega-cap tech names.</p>
<p>A bubble chart works well here because it encodes more than one thing at once. The x-axis is the earnings date, the y-axis is the 10-day post-earnings return, the bubble size scales with the absolute EPS surprise magnitude, and the color shows whether the surprise was a beat or a miss. This makes it easy to spot outlier quarters and see whether big surprises consistently lead to bigger post-earnings moves.</p>
<pre><code class="language-python"># Define mega-cap tech tickers (top ones from data: AAPL, MSFT, NVDA, AMZN, GOOG/GOOGL, META)
tech_tickers = ['AAPL', 'MSFT', 'NVDA', 'AMZN', 'GOOG', 'GOOGL', 'META']

# Filter data for mega-cap tech
df_tech = (
    df_earnings[df_earnings['symbol'].isin(tech_tickers)]
    .dropna(subset=['earn_date', 'pct_post_10d', 'eps_surprise'])
    .sort_values('earn_date')
    .assign(
        earn_date=lambda x: pd.to_datetime(x['earn_date'])
    )
)

# Create time-series plot: pct_post_10d vs earn_date, sized/color by eps_surprise
plt.figure(figsize=(14, 8))

# Scatter plot
scatter = plt.scatter(
    df_tech['earn_date'],
    df_tech['pct_post_10d'],
    s=np.abs(df_tech['eps_surprise']) * 50 + 20,  # Size by abs(eps_surprise)
    c=df_tech['eps_surprise'],
    cmap='RdYlBu_r',
    alpha=0.7,
    edgecolors='black',
    linewidth=0.5
)

plt.colorbar(scatter, label='EPS Surprise (%)')
plt.xlabel('Earnings Date')
plt.ylabel('10-Day Post-Earnings Return (%)')
plt.title('Mega-Cap Tech: 10-Day Post-Earnings Returns vs Time\n(Point size/color by EPS Surprise)')
plt.grid(True, alpha=0.3)

# Add trend line
z = np.polyfit(pd.to_numeric(df_tech['earn_date']), df_tech['pct_post_10d'], 1)
p = np.poly1d(z)
plt.plot(df_tech['earn_date'], p(pd.to_numeric(df_tech['earn_date'])), "r--", alpha=0.8, linewidth=2, label=f'Trend: {z[0]:.3f}x + {z[1]:.1f}')

plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
</code></pre>
<img src="https://cdn-images-1.medium.com/max/1500/1*vFJ_bKUzT1WGiJaiF53tEg.png" alt="Bubble chart of 10-day post-earnings returns over time for AAPL, MSFT, NVDA, AMZN, GOOG, GOOGL, META. Bubble size reflects EPS surprise magnitude. Color reflects beat or miss" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>That large red bubble around 2018 is almost certainly <strong>AAPL’s Q4 2018 earnings miss</strong> (Jan 2019 announcement, but fiscal Q4 2018 data) and it stands out because:</p>
<ul>
<li><p><strong>Large size</strong> = massive EPS surprise magnitude (Apple cut guidance dramatically, ~10% miss)</p>
</li>
<li><p><strong>Red colour</strong> = negative surprise</p>
</li>
<li><p><strong>Low Y position</strong> = poor 10‑day return (~-10% range visible)</p>
</li>
</ul>
<p>This was Apple’s infamous “iPhone demand warning” that triggered the January 2019 market panic. Perfect example of how one outlier event can anchor the whole trend line downward in your visualisation.</p>
<h3 id="heading-eps-surprise-scatter-plot">EPS Surprise Scatter&nbsp;Plot</h3>
<p>After identifying major tech trends, let's now look at the <strong>EPS Surprise Scatter</strong> plots. This plot checks a simple hypothesis. Do earnings beats lead to positive returns, and do misses lead to negative returns? We plot EPS surprise on the x-axis and post-earnings returns on the y-axis, then add a regression line to show the average relationship.</p>
<pre><code class="language-python"># Prepare data: drop NaNs and convert earn_date if needed (not used here)
df_plot = (
    df_earnings
    .dropna(subset=['eps_surprise', 'pct_post_3d', 'pct_post_10d', 'sector'])
    .copy()
)

# 1. Scatter: EPS Surprise vs 3-Day Post-Return, colored by sector
plt.figure(figsize=(12, 5))

plt.subplot(1, 2, 1)
sns.scatterplot(
    data=df_plot,
    x='eps_surprise',
    y='pct_post_3d',
    hue='sector',
    alpha=0.6,
    s=40
)

# Regression line (overall)
slope, intercept, r_value, p_value, std_err = stats.linregress(df_plot['eps_surprise'], df_plot['pct_post_3d'])
line = slope * df_plot['eps_surprise'] + intercept
plt.plot(df_plot['eps_surprise'], line, 'red', linestyle='--', linewidth=2,
         label=f'y = {slope:.3f}x + {intercept:.2f}\nR²={r_value**2:.3f}')
plt.xlabel('EPS Surprise (%)')
plt.ylabel('3-Day Post-Earnings Return (%)')
plt.title('EPS Surprise vs 3-Day Post-Return by Sector')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.grid(True, alpha=0.3)

# 2. Scatter: EPS Surprise vs 10-Day Post-Return, colored by sector
plt.subplot(1, 2, 2)
sns.scatterplot(
    data=df_plot,
    x='eps_surprise',
    y='pct_post_10d',
    hue='sector',
    alpha=0.6,
    s=40
)

# Regression line (overall)
slope10, intercept10, r_value10, p_value10, std_err10 = stats.linregress(df_plot['eps_surprise'], df_plot['pct_post_10d'])
line10 = slope10 * df_plot['eps_surprise'] + intercept10
plt.plot(df_plot['eps_surprise'], line10, 'red', linestyle='--', linewidth=2,
         label=f'y = {slope10:.3f}x + {intercept10:.2f}\nR²={r_value10**2:.3f}')
plt.xlabel('EPS Surprise (%)')
plt.ylabel('10-Day Post-Earnings Return (%)')
plt.title('EPS Surprise vs 10-Day Post-Return by Sector')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

# Optional: Summary table of correlations by sector
corr_3d = df_plot.groupby('sector')[['eps_surprise', 'pct_post_3d']].corr().unstack().xs('pct_post_3d', level=1, axis=1)['eps_surprise']
corr_10d = df_plot.groupby('sector')[['eps_surprise', 'pct_post_10d']].corr().unstack().xs('pct_post_10d', level=1, axis=1)['eps_surprise']

corr_df = pd.DataFrame({
    'Corr_EPS_3Day': corr_3d.round(3),
    'Corr_EPS_10Day': corr_10d.round(3)
}).sort_values('Corr_EPS_10Day', ascending=False)
</code></pre>
<img src="https://cdn-images-1.medium.com/max/1500/1*rEAHbGRiyJs-NT9VPRudDQ.png" alt="Scatter plot of EPS surprise versus post-earnings returns with sector colors and overall regression line" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>The red dashed trend line illustrates the <em>typical</em> relationship: for every 1% EPS beat, stocks tend to gain about 0.05–0.1% over 3 to 10 days. The gentle slope suggests that while surprises can give a little boost, <strong>they don’t guarantee large moves</strong>.</p>
<p>You’ll notice that Consumer Cyclical dots mainly cluster in the upper right (beats leading to gains), and Real Estate shows a steeper increase. The wide spread around the line indicates that other factors often influence stock movements beyond surprises.</p>
<h3 id="heading-return-distribution-violins">Return Distribution Violins</h3>
<p>Heatmaps show averages, but averages can hide risk. Violin plots show the full distribution of returns, including how wide the outcomes are and whether the tails are heavy. Here we plot 3-day post-earnings return distributions by sector and by market-cap bucket.</p>
<pre><code class="language-python"># Prepare data
df_plot = (
    df_earnings
    .dropna(subset=['pct_post_3d', 'sector', 'marketCap'])
    .copy()
)

# 1. Violin plot: 3-day post-returns by sector
plt.figure(figsize=(15, 6))

plt.subplot(1, 2, 1)
sns.violinplot(
    data=df_plot,
    x='sector',
    y='pct_post_3d',
    inner='quartile',
    palette='Set2'
)
plt.title('Distribution of 3-Day Post-Earnings Returns by Sector (Violin)')
plt.xlabel('Sector')
plt.ylabel('3-Day Post-Earnings Return (%)')
plt.xticks(rotation=45, ha='right')
plt.grid(True, alpha=0.3)

# 2. Violin plot: 3-day post-returns by market-cap group
plt.subplot(1, 2, 2)
sns.violinplot(
    data=df_plot,
    x='marketCap',
    y='pct_post_3d',
    inner='quartile',
    palette='Set3'
)
plt.title('Distribution of 3-Day Post-Earnings Returns by Market-Cap (Violin)')
plt.xlabel('Market-cap bucket')
plt.ylabel('3-Day Post-Earnings Return (%)')
plt.xticks(rotation=45, ha='right')
plt.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()


plt.show()

# Summary statistics table
summary = df_plot.groupby(['sector', 'marketCap'])['pct_post_3d'].agg(['mean', 'median', 'std', 'count']).round(2)
print("Summary Statistics: Mean/Median/Std/Count of 3-Day Returns by Sector &amp; Market-Cap")
print(summary)
</code></pre>
<img src="https://cdn-images-1.medium.com/max/1500/1*JLOvSp-2jwD5_ZNqeqdBEw.png" alt="Violin plots showing distribution of 3-day post-earnings returns by sector and by market-cap bucket" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>All violins concentrate near zero with modest variations (±5%), indicating that post-earnings reactions are <em>generally noisy and lack a clear direction.</em> Markets efficiently incorporate expectations, resulting in little predictable advantage. Consumer Cyclical and Materials sectors display slightly more frequent upside surprises, while small caps exhibit the greatest variability, reflecting higher risk and occasional gains. Not every visualization reveals alpha; this one honestly illustrates the difficulty involved.</p>
<h3 id="heading-monthly-seasonality">Monthly Seasonality</h3>
<p>After observing narrow return distributions near zero, let's now look at Monthly Seasonality in four panels: average 3/10‑day post‑returns, EPS surprises, and event counts by month. This reveals calendar effects,  systematic seasonal biases ,  that can influence timing of entries despite noisy individual responses.</p>
<pre><code class="language-python"># 1. Ensure earn_date is datetime
df_month = (
    df_earnings
    .dropna(subset=['earn_date', 'pct_post_3d', 'pct_post_10d', 'eps_surprise'])
    .copy()
)

df_month['earn_date'] = pd.to_datetime(df_month['earn_date'])

# 2. Derive month number and name
df_month['month_num'] = df_month['earn_date'].dt.month
df_month['month_name'] = df_month['earn_date'].dt.strftime('%b')

# 3. Aggregate averages by month
monthly_agg = (
    df_month
    .groupby('month_num')
    .agg(
        pct_post_3d_mean=('pct_post_3d', 'mean'),
        pct_post_10d_mean=('pct_post_10d', 'mean'),
        eps_surprise_mean=('eps_surprise', 'mean'),
        n_obs=('earn_date', 'count')
    )
    .reset_index()
    .sort_values('month_num')
)

# Keep a stable month order and names
month_order = monthly_agg['month_num'].tolist()
month_labels = df_month.drop_duplicates('month_num').set_index('month_num')['month_name'].reindex(month_order)

monthly_agg['month_name'] = month_labels.values

# 4. Plot bar charts
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
fig.suptitle('Monthly Seasonality of Post-Earnings Returns and EPS Surprise', fontsize=16)

# Avg 3-day return
axes[0, 0].bar(monthly_agg['month_name'], monthly_agg['pct_post_3d_mean'], color='skyblue')
axes[0, 0].set_title('Avg 3-Day Post-Earnings Return by Month')
axes[0, 0].set_ylabel('Return (%)')
axes[0, 0].grid(alpha=0.3)

# Avg 10-day return
axes[0, 1].bar(monthly_agg['month_name'], monthly_agg['pct_post_10d_mean'], color='lightgreen')
axes[0, 1].set_title('Avg 10-Day Post-Earnings Return by Month')
axes[0, 1].set_ylabel('Return (%)')
axes[0, 1].grid(alpha=0.3)

# Avg EPS surprise
axes[1, 0].bar(monthly_agg['month_name'], monthly_agg['eps_surprise_mean'], color='salmon')
axes[1, 0].set_title('Avg EPS Surprise by Month')
axes[1, 0].set_ylabel('EPS Surprise')
axes[1, 0].grid(alpha=0.3)

# Number of observations
axes[1, 1].bar(monthly_agg['month_name'], monthly_agg['n_obs'], color='gold')
axes[1, 1].set_title('Number of Earnings Events by Month')
axes[1, 1].set_ylabel('Count')
axes[1, 1].grid(alpha=0.3)

for ax in axes.ravel():
    ax.set_xlabel('Month')
    ax.tick_params(axis='x', rotation=0)

plt.tight_layout()
plt.show()
</code></pre>
<img src="https://cdn-images-1.medium.com/max/1500/1*HjdZDaUhudYQZPNvOqy-_Q.png" alt="Four-panel bar charts showing monthly averages of 3-day returns, 10-day returns, EPS surprise, and event counts" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>Jan/Oct tend to have the best 3‑day returns, about 0.8%, while May/Jul usually see weaker results. The 10‑day trends show a similar but gentler pattern, with February and August reaching peaks. EPS surprises are slightly negative in January and May, possibly due to tough comparisons, and there are fewer events in July, August, and December because of holidays. While there’s a hint of seasonality, its impact is quite small, around 0.5%.</p>
<h3 id="heading-regime-cross-section">Regime Cross-Section</h3>
<p>Finally, after subtle monthly patterns, we'll look at the Regime Cross‑Section: sector 10‑day post‑earnings returns by market regime (heatmap at the top, bars below). This stress‑tests earlier findings  ( do patterns persist across bull, bear, and COVID eras), revealing rotation opportunities and regime dependence.</p>
<pre><code class="language-python"># Prepare data with year extraction
df_regimes = (
    df_earnings
    .dropna(subset=['earn_date', 'pct_post_10d', 'sector'])
    .copy()
)

df_regimes['earn_date'] = pd.to_datetime(df_regimes['earn_date'])
df_regimes['year'] = df_regimes['earn_date'].dt.year

# Define market regimes (adjust years based on your data/market history)
# Example: Bull (2023-2025), Bear/Transition (2022), COVID (2020-2021), etc.
def assign_regime(year):
    if year &gt;= 2023:
        return 'Bull (2023+)'
    elif year == 2022:
        return 'Bear (2022)'
    elif 2020 &lt;= year &lt;= 2021:
        return 'COVID Recovery'
    elif 2018 &lt;= year &lt;= 2019:
        return 'Pre-COVID'
    else:
        return 'Earlier'

df_regimes['market_regime'] = df_regimes['year'].apply(assign_regime)

# 1. Aggregate: average 10-day returns by sector and regime/year
agg_data = (
    df_regimes
    .groupby(['sector', 'market_regime'])['pct_post_10d']
    .agg(['mean', 'count'])
    .reset_index()
    .query('count &gt;= 5')  # Filter low-sample regimes
)

# 2. Visualization: Heatmap first (quick overview)
plt.figure(figsize=(12, 8))

plt.subplot(2, 1, 1)
pivot_heatmap = agg_data.pivot(index='sector', columns='market_regime', values='mean')
sns.heatmap(pivot_heatmap, annot=True, fmt='.2f', cmap='RdYlGn', center=0, linewidths=0.5)
plt.title('Average 10-Day Post-Earnings Returns: Sector x Market Regime Heatmap')

# 3. Bar charts: By regime (stacked by sector)
plt.subplot(2, 1, 2)
regime_order = agg_data.groupby('market_regime')['mean'].mean().sort_values(ascending=False).index
sns.barplot(data=agg_data, x='market_regime', y='mean', hue='sector',
            palette='Set2', order=regime_order)
plt.title('Average 10-Day Returns by Market Regime (Colored by Sector)')
plt.ylabel('10-Day Post-Return (%)')
plt.xlabel('Market Regime')
plt.xticks(rotation=45, ha='right')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.grid(axis='y', alpha=0.3)

plt.tight_layout()
plt.show()

# 5. Summary tables
print("Average Returns by Sector x Market Regime (min 5 obs):")
print(agg_data.pivot(index='sector', columns='market_regime', values='mean').round(2))

# 6. Ranking: Best/worst performing sectors by regime
print("\nTop/Bottom Sectors by Regime:")
for regime in regime_order:
    regime_data = agg_data[agg_data['market_regime'] == regime].sort_values('mean', ascending=False)
    print(f"\n{regime}:")
    print(regime_data[['sector', 'mean', 'count']].round(2).head(3))
</code></pre>
<img src="https://cdn-images-1.medium.com/max/1000/0*Pn2sH97R2DCpRl7u.png" alt="Heatmap and bar chart showing average 10-day post-earnings returns by sector across market regimes" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>Consumer Cyclical does well during Bull (2023+) and COVID Recovery (<del>1.5–2%), but it’s less favorable in Bear 2022. Utilities turned negative before COVID. The bottom bars show the COVID era led overall gains (</del>1%), with Basic Materials and Industrials being the strongest. The recent Bull remains positive but less so. Sector leadership shifts depending on the market regime , there are no consistent winners.</p>
<h2 id="heading-what-did-we-get-out-of-all-this-storyline">What Did We Get Out of All This Storyline?</h2>
<p>Guiding you through six interconnected visualizations, we’ve turned 15 years of earnings data into a clear and engaging story.</p>
<p>Each chart responds to a specific question, yet together, they paint a bigger picture: earnings surprises influence markets, but not in the same way everywhere. Some sectors, periods, and regimes often provide consistent advantages, while others don’t.</p>
<p>Here’s what the data shows us:</p>
<ul>
<li><p><strong>No definitive alpha here, but specific opportunities are present</strong>: Markets are mostly efficient,  returns hover near zero with weak surprise correlations ,  yet Consumer Cyclicals and Materials consistently show upside potential across different timeframes and market sizes. Timing your sector choice is important.</p>
</li>
<li><p><strong>Timing windows alter the story</strong>: 3-day reactions benefit Real Estate mid-caps (+4%), while 10-day reactions shift leadership to Consumer Cyclical mega-caps (+3.2%). Don’t assume all earnings reactions occur at the same pace.</p>
</li>
<li><p><strong>Mega-tech hype isn’t eternal</strong>: The bubble chart shows AAPL/MSFT/NVDA delivered strong returns from 2020–2022, but the falling trend since then indicates waning market enthusiasm. Don’t chase yesterday’s overhyped stocks.</p>
</li>
<li><p><strong>Calendar patterns reward patience</strong>: January and October deliver slightly stronger post-earnings returns (~0.8%), while July and August tend to have lower liquidity. Combine seasonal timing with sector choices for additional gains.</p>
</li>
<li><p><strong>Market regimes change winners</strong>: Cyclicals underperformed during COVID recovery and the bull run (2023+), while Industrials peaked during the recovery. There are no universal “best performers,” only the best performers <em>for now</em>. Adjust to the regime.</p>
</li>
<li><p><strong>The actionable setup</strong>: Small to mid-cap cyclical longs in January during bull markets combine all these signals for maximum conviction ,  where sector timing, seasonality, and regime alignment converge.</p>
</li>
</ul>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>This exercise shows why visualization is important in finance: raw tables of returns and surprises wouldn’t reveal these patterns.</p>
<ul>
<li><p>Heatmaps instantly highlighted sector winners.</p>
</li>
<li><p>Scatter plots demonstrated the weak surprise‑return connection. Bubble charts narrated the mega‑tech story over time.</p>
</li>
<li><p>Violins unveiled the harsh truth  that markets are noisy. Cross‑sectional regime analysis reminded us that yesterday’s approach doesn’t ensure tomorrow’s returns.</p>
</li>
</ul>
<p>The effort to interpret this data pays off: you shift from passive observation to active pattern recognition. You see not just what occurred, but where and when it happened. In trading and analysis, understanding the shape of complexity often surpasses having a perfect formula.</p>
<p>Visual storytelling turns data into intuition . And intuition, based on evidence, outperforms guesswork every time.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Key Metrics That Can Make or Break Your Startup ]]>
                </title>
                <description>
                    <![CDATA[ If you’ve built something worth pitching – something more than a fancy hobby with a login screen – you need to know your numbers. Not "I’ll get back to you" know them, know them like you know your co-founder's coffee order. I have seen too many found... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/key-metrics-that-can-make-or-break-your-startup/</link>
                <guid isPermaLink="false">6894eea1ba8a1138e41767a1</guid>
                
                    <category>
                        <![CDATA[ startup ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Founder ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ideas ]]>
                    </category>
                
                    <category>
                        <![CDATA[ business ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Business and Finance  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ metrics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Product Management ]]>
                    </category>
                
                    <category>
                        <![CDATA[ performance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ #reporting ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ycombinator ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Aditya Vikram Kashyap ]]>
                </dc:creator>
                <pubDate>Thu, 07 Aug 2025 18:21:21 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754590848364/2e68c07e-d5d8-4da7-bc41-3798c991bfbc.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you’ve built something worth pitching – something more than a fancy hobby with a login screen – you need to know your numbers. Not "I’ll get back to you" know them, know them like you know your co-founder's coffee order.</p>
<p>I have seen too many founders who are smart, legit, and ambitious get ghosted by investors simply because they couldn't walk through their unit economics.</p>
<p>It's not personal. It's math.</p>
<p>So here it is: Numbers that will either carry your pitch or quietly kill it, explained by someone who has sat through them time and time again, with examples, and no fluff.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-burn-rate-how-fast-are-you-lighting-your-cash-on-fire">1. Burn Rate: How Fast Are You Lighting Your Cash on Fire?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-cash-runway-how-long-before-you-run-out-of-cash">2. Cash Runway: How Long Before You Run Out of Cash?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-cac-customer-acquisition-cost-how-much-does-it-cost-to-convince-someone-to-pay-you">3. CAC (Customer Acquisition Cost): How Much Does it Cost to Convince Someone to Pay You?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-customer-lifetime-value-ltv-how-much-is-one-customer-worth-over-time">4. Customer Lifetime Value (LTV): How Much is One Customer Worth Over Time?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-gross-profit-margin-what-do-you-actually-keep-after-delivering-your-service-or-product">5. Gross Profit Margin: What Do You Actually Keep After Delivering Your Service or Product?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-6-monthly-annual-recurring-revenue-mrr-arr">6. Monthly / Annual Recurring Revenue (MRR / ARR)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-7-churn-rate-how-fast-are-your-users-leaving">7. Churn Rate: How Fast Are Your Users Leaving</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-8-payback-period-how-long-before-you-recover-your-cac">8. Payback Period: How Long Before You Recover Your CAC?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-9-earnings-before-interest-taxes-depreciation-and-amortization-ebitda">9. Earnings Before Interest, Taxes, Depreciation, and Amortization (EBITDA)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-10-valuation-whats-your-company-worth-and-what-supports-that-number">10. Valuation: What’s Your Company Worth – and What Supports that Number?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-real-talk-before-you-close-that-tab">Real Talk Before You Close That Tab</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-real-experience">Real Experience</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-this-matters">Why This Matters</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion-and-final-thoughts">Conclusion and Final Thoughts</a></p>
</li>
</ul>
<h2 id="heading-1-burn-rate-how-fast-are-you-lighting-your-cash-on-fire">1. Burn Rate: How Fast Are You Lighting Your Cash on Fire?</h2>
<p>Burn rate is the speed at which a startup is spending its cash. Basically, how fast are you consuming your venture capital to cover over overhead until you generate positive cash flow from operations? It’s a measure of negative cash flow.</p>
<p>If you’re spending $80K a month to keep the lights on (payroll, AWS, your workspace snacks, and so on), that’s how much cash you’re burning each month. But many startups calculate two different burn rates: gross burn (how much cash you’re spending, ignoring any revenue), and net burn (monthly operating experiences minus any cash you take in each month). Net burn basically measures how fast your cash is shrinking, and it’s often what investors care more about.</p>
<p>Real talk: investors want to know when the plane runs out of fuel before they board. Thats what this metric helps them understand – how fast you’re going through the money you have.</p>
<p>At some point, if a company has a high burn rate, it has to reduce structural costs by cutting expenditures on labor, rent, marketing, and/or capital equipment. The burn rate is an important metric for any company, but it's particularly important for startups that aren't yet generating revenue. It tells managers and investors how fast the company is spending its capital</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=BpS3shZI35A">Watch this video</a> to understand more about Burn Rate.</p>
<h2 id="heading-2-cash-runway-how-long-before-you-run-out-of-cash">2. Cash Runway: How Long Before You Run Out of Cash?</h2>
<p>Cash runway tells how long a startup can continue to operate at a certain burn rate until they are out of cash. For startups without revenue, you can calculate this by dividing available cash by total monthly expenses. Available cash is defined as the funds that are accessible now or can be accessed at a later time relatively quickly to pay for expenses.</p>
<p>When you’re making this calculation, it’s important to not include any anticipated fundraising and other uncertain sources of capital.</p>
<p>Actively managing cash runway is crucial for startup survival and growth. With a significant percentage of startups failing due to cash shortages, founders need to closely monitor their cash burn rate and runway.</p>
<p>The length of runway needed varies based on factors including the startup’s stage, industry, and milestones. In tighter venture capital markets, startups should plan for longer runways and consider strategies such as increasing revenue, reducing expenses, or raising additional capital. Regularly updating financial models and understanding metrics like the burn multiple can help you make informed decisions to extend your runway and align your growth ambitions with financial stability.</p>
<p>While it’s a simple calculation at face value, a cash runway analysis is nuanced and unique to every startup and can be impacted by a multitude of circumstances.</p>
<p>To calculate this, you just divide your total cash reserves by the amount you’re spending each month. Say you’ve got $250K in the bank and you’re spending $50K/month: 250/50 = 5. So you’ve got 5 months. Not 6. Not “it depends” – 5. That’s your runway.</p>
<p>Investors ask “If we don’t fund you, how long do you survive?” If you don’t know that answer, you're not fundraising – you’re freelancing with hope.</p>
<p><a target="_blank" href="https://youtu.be/vtaMwtQgFGE?si=-Hcf_h_LxKYChdBa">Here is a video</a> that explains cash runway with real world examples and the thought process behind it.</p>
<p>And <a target="_blank" href="https://www.jpmorgan.com/insights/business-planning/does-your-startup-have-enough-runway-to-survive">here’s an article</a> from JP Morgan breaking down cash runway, its importance, and what can you to to maximize it.</p>
<h3 id="heading-burn-rate-vs-runway">Burn Rate vs Runway</h3>
<p>So, let’s just make this super clear: burn rate is simply how much you spend each month to run your operation – that is, your negative cash flow. Runway is how many months there are left before your bank balance reaches zero.</p>
<p>So again, why do these numbers matter?</p>
<p>Because burn rate tells you how quickly you need to find more revenue or funding. Runway tells investors whether you are going to still be around by the time they finish their due diligence.</p>
<p>They are not just numbers. They are your survival clock.</p>
<p>Smart founders utilize these metrics to:</p>
<ul>
<li><p>Trim the fat without cutting muscle – know what to focus on and what to let go</p>
</li>
<li><p>Forecast hiring/fundraising deadlines – know the process and prep for it. Numbers don’t line but they sure can get you ghosted.</p>
</li>
<li><p>Assure investors you’re not going to come knocking again in 90 days – establishing credibility is key, make an investor realize its not just a hobby, you mean business.</p>
</li>
</ul>
<p>The goal: Extend runway without stalling momentum. Keep the plane in the air, while building a bigger engine.</p>
<h2 id="heading-3-cac-customer-acquisition-cost-how-much-does-it-cost-to-convince-someone-to-pay-you">3. CAC (Customer Acquisition Cost): How Much Does it Cost to Convince Someone to Pay You?</h2>
<p>Cost of acquisition refers to the entire cost that a business incurs to obtain a new client or asset. This includes the purchase price, shipping, installation, and marketing costs for the asset acquired. CAC takes into account the total expenditure on all marketing, advertising, and sales for the period, which you then divide by the number of new customers for the period.</p>
<p>In this case, all the upfront costs incurred to purchase a business asset, including equipment or inventory, are part of the cost of acquisition. Cost of acquisition includes:</p>
<ul>
<li><p>Purchase price of the item</p>
</li>
<li><p>Costs to ship it to its point of use</p>
</li>
<li><p>Costs to install the item</p>
</li>
<li><p>Costs to get it up and running (in the case of equipment) or ready for sale (in the case of inventory) condition</p>
</li>
<li><p>Marketing sales teams salaries</p>
</li>
<li><p>All sales and consulting marketing expenses geared to get new consumers should all be included</p>
</li>
</ul>
<p><strong>Formula:</strong><br>CAC = (Total Marketing + Sales Expenses) / Number of New Customers Acquired</p>
<p>Say you spent $10K last month across paid ads, content creation, outbound campaigns, and sales team costs. You onboarded 100 new customers, so your CAC = $100.</p>
<p>But is that good?</p>
<p>It depends on:</p>
<ul>
<li><p>Your pricing model (one-time vs. subscription)</p>
</li>
<li><p>Your margin (how much of that sale do you actually keep?)</p>
</li>
<li><p>Your customer retention (how long do they stick around?)</p>
</li>
</ul>
<p>If you’re selling a $20 product once, a $100 CAC is a non-starter. But if that customer brings in $50/month for 12 months, you’ve got a solid return.</p>
<p><strong>Watch for red flags:</strong></p>
<ul>
<li><p>CAC is rising but revenue isn’t</p>
</li>
<li><p>You’re overly reliant on paid ads (especially if organic/referral is flat)</p>
</li>
<li><p>You don’t know CAC by channel (averages hide leaks)</p>
</li>
</ul>
<p>A healthy CAC is one that pays itself back quickly and can be improved over time as you optimize funnels and messaging</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=KFJ3ip30QPM">Here is a video</a> that breaks down CAC for you.</p>
<h2 id="heading-4-customer-lifetime-value-ltv-how-much-is-one-customer-worth-over-time">4. Customer Lifetime Value (LTV): How Much is One Customer Worth Over Time?</h2>
<p>Customer Lifetime Value is the average monetary value of each customer to your business. LTV takes into account how much a unique customer is expected to spend with your business. It’s an important metric so you know how much new customers are worth to your business over their lifespan as a customer.</p>
<p>Let’s say you charge $25/month. The average customer sticks around 12 months.<br>LTV = $300.</p>
<p>In this case, if your CAC is $80? You’re in the green. But if it’s $350? You’re basically paying people to hang out (and losing money on them).</p>
<p>Now, let’s connect this to CAC.</p>
<p>Say your CAC is $80. You’re doing fine – your LTV is ~4x CAC. That’s what investors want to see.</p>
<p>Rule of thumb: you want your LTV to be at least 3x your CAC. A 1:1 ratio means you’re barely breaking even, before operational costs and the math stops working at scale. So if you can hit a 3:1 ratio, great – and based off my experience, your business will be much more appealing if it’s closer to 5:1.</p>
<p>And keep in mind that different models can have different thresholds. For example, a SaaS company with low churn can afford higher CACs, while an e-commerce platform might need faster payback. And marketplaces and freemium models may have lower LTV per user, but they can often more easily offset it with volume.</p>
<p>If you don’t know your LTV or can’t defend it with data, it becomes hard to justify spend – and easy for investors to walk.</p>
<p>If you want to know more, <a target="_blank" href="https://www.youtube.com/watch?v=vA1YX8963ts">this video</a> walks you through the basics.</p>
<p>And <a target="_blank" href="https://www.youtube.com/watch?v=773zBQVPx_Q">here’s a video</a> that beautifully explains the CAC and LTV relationship.</p>
<h2 id="heading-5-gross-profit-margin-what-do-you-actually-keep-after-delivering-your-service-or-product">5. Gross Profit Margin: What Do You Actually Keep After Delivering Your Service or Product?</h2>
<p>Gross profit margin shows the amount of money a business collects after it pays for all its expenses. It’s usually calculated as a percentage of sales. This specific metric is also referred to as the gross margin ratio.</p>
<p>Companies use gross margin as a measure of how production costs relate to revenue. If a company's gross margin falls because it is making less revenue, it may try to cut labor costs, find cheaper suppliers of materials, or increase prices to increase revenue.</p>
<p>Gross profit margins can also allow a business to measure how efficient a company is, or compare two very differently sized companies that share a common revenue stream or product</p>
<p>If you sell a subscription for $50/month and it costs you $10/month to host, maintain, and support it, your gross margin is 80%.</p>
<ul>
<li><p>Good: SaaS companies often hit 70–90%.</p>
</li>
<li><p>Bad: If you're below 30%, your "scalable" business will collapse under weight.</p>
</li>
</ul>
<p>Want to know the conceptual math behind this metric and how it differs from Profit Margin? <a target="_blank" href="https://www.youtube.com/watch?v=9xAMe0QBFhU&amp;t=45s">Here is a fantastic video</a> that easily breaks it down.</p>
<h2 id="heading-6-monthly-annual-recurring-revenue-mrr-arr">6. Monthly / Annual Recurring Revenue (MRR / ARR)</h2>
<p>Annual recurring revenue (ARR) is revenue a company expects to see from its product and service offerings, calculated over the course of a year. Companies that sell annual subscriptions like using ARR as a sales metric to track what they anticipate making in a year.</p>
<p>ARR tends to be used if companies sell a product or service in the software as a service (SaaS) space, but it can also be useful in terms of streaming services, cell phone bills, and (almost) anything else with a predictable, recurring charge.</p>
<p>ARR is calculated annually, whereas monthly recurring revenue (MRR) is calculated monthly. MRR is useful in that it shows what’s happening on a month-to-month basis. For example, if you change your price in April, you can see the immediate effects of that change in May. MRR also helps track fluctuations in revenue based on outside factors like holiday shopping seasons and economic conditions.</p>
<p>In a nutshell, Monthly / Annual Recurring Revenue = predictable income.</p>
<p>If you’re pulling $20K/month in subscriptions, that’s $240K ARR. Simple.</p>
<p>What investors care about:</p>
<ul>
<li><ul>
<li><p>Is it growing?</p>
<ul>
<li><p>How fast?</p>
</li>
<li><p>And how stable is it?</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p><a target="_blank" href="https://youtu.be/qwo7WFWusO4?si=pCelTr2slb2OLuw9">Here is a founder breaking down the metric</a> and explaining the relationship between MRR/ARR.</p>
<h2 id="heading-7-churn-rate-how-fast-are-your-users-leaving">7. Churn Rate: How Fast Are Your Users Leaving</h2>
<p>The churn rate, also known as attrition rate, represents the rate at which a customer stops doing business with a company. Customer churn is typically expressed as the percentage of service subscribers that discontinue their service subscriptions within a time frame. Churn can also be expressed as the rate at which employees leave their jobs in a given time.</p>
<p>In order for a business to grow its number of clients, its growth rate (which takes into account new customers) must be higher than its churn rate.</p>
<p>The benefit of calculating a churn rate is that it can clarify how well a business is retaining its customers, which is a measure of the quality of service the business is providing and the usefulness of that service.</p>
<p>When a business can see its churn rate increasing from period to period, this suggests that a critical aspect of how it is running the business might be problematic or flawed.</p>
<p>It could be the result of:</p>
<ul>
<li><p>A faulty product(s)</p>
</li>
<li><p>Bad customer service</p>
</li>
<li><p>Costs exceed utility to customers</p>
</li>
</ul>
<p>And so on.</p>
<p>The churn rate will indicate to a business that it needs to learn why its customers are leaving, and where it needs to adjust its business. It’s more expensive to attract new customers than it is to retain them, so reducing the churn rate can save a business resources in the future.</p>
<p>Real talk: Say you had 500 users at the start of the month, and you lost 50 by the end of the month. That’s 10% churn – which is high! Annualize that and…ouch. You're not growing. You're replacing.</p>
<p>Make sure you fix this before you fundraise. Or at least explain why churn’s high and what you’re doing to plug the holes.</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=Jlg5J_Mpq7g">Here is a video</a> that beautifully explains Churn Rate.</p>
<h2 id="heading-8-payback-period-how-long-before-you-recover-your-cac">8. Payback Period: How Long Before You Recover Your CAC?</h2>
<p>The payback period is a popular tool for determining investment return. People invest money for the purpose of getting it back and generating a positive return on the money they invested. The shorter the payback period, the more beneficial the investment will be.</p>
<p>The payback period does not factor in the time value of money. You can determine it simply by counting the number of years until the principal paid in is returned.</p>
<p>This metric measures how quickly your customer pays you back for the cost of acquiring them. The payback period doesn’t take into account the total profitability of an investment. It’s just concerned with paying the investment back.</p>
<p>There are two common interpretations:</p>
<ol>
<li><p><strong>Customer-Level Payback:</strong> If your CAC is $250 and your customer pays $50/month, it’ll take 5 months to recover the acquisition cost.</p>
</li>
<li><p><strong>Investment-Level Payback:</strong> You spend $100,000 on a new sales hire, tool stack, or feature. You want to know how long it takes for that investment to generate $100,000 in profit.</p>
</li>
</ol>
<p>Both use the same principle: the shorter the payback period, the less cash you need to float your growth.</p>
<p>If you want a target, aim for 6 months for customer-level payback. Closer to 3-6 is ideal. Long payback periods mean you need deep pockets – or exceptional retention – to stay afloat.</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=KbtTk2azIjY">Here’s a video</a> where you can learn more.</p>
<h2 id="heading-9-earnings-before-interest-taxes-depreciation-and-amortization-ebitda">9. Earnings Before Interest, Taxes, Depreciation, and Amortization (EBITDA)</h2>
<p>EBITDA stands for Earning Before Interest, Taxes, Depreciation, and Amortization. You can think of this as just your company's operating profit if you wanted a very rudimentary way of referring to it.</p>
<p>It’s not flashy. It’s not fun. But it tells investors: “Here’s what we really make once the accounting fog clears.” and “Are we generating real profits from our actual operations?”</p>
<p>EBITDA is what investors look at because it is the best way of comparing apples to apples when considering startups. EBITDA can provide investors a measure of your operational health.</p>
<p>A negative EBITDA for an early stage company isn't going to raise any eyebrows. Just don’t act surprised when someone brings it up. You need to do that math before the pitch. But, if you have a growing early stage company that's moving from negative EBITDA to positive? Now your getting into grown folks business.</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=DH901SrBv9Q">Here’s a video</a> that explains the basics of EBITDA.</p>
<p>And <a target="_blank" href="https://www.youtube.com/watch?v=D58oCe_7BBM">here’s another video</a> that explains how investors look at EBITDA and its value in determining your business’s worth.</p>
<h2 id="heading-10-valuation-whats-your-company-worth-and-what-supports-that-number">10. Valuation: What’s Your Company Worth – and What Supports that Number?</h2>
<p>Valuation is a focused exercise that determines the value of an asset, investment, or company. So, how much your company’s worth. And the goal is typically to determine whether that value is a fair value.</p>
<p>Valuations can be conducted in one of two ways:</p>
<ul>
<li><p>an absolute valuation, which evaluates a company on its own merits and entirely independently of other factors/companies, or</p>
</li>
<li><p>a relative valuation, which evaluates the company relative to other similar firms, or assets, in the same sector or industry. This determines if the company, or asset, is worth that much relative to others.</p>
</li>
</ul>
<p>Depending on how the analysis and conclusions are reached, there are a variety of methods and techniques used to develop valuations. And as you’d expect, there’s often significant variability between outputs (or valuations) based on the inputs and context.</p>
<p>While valuations are predominantly quantitatively driven, there’s often a significant subjective influence that come from the assumptions and estimates made along the way. Valuations are also subject to developing situations and events outside of the analysis or the control of the analyst – for example, earnings reports or material news, or economic news – that can result in a change to a valuation stance.</p>
<p>If you’re pre-revenue and you’re saying $30M because a friend raised at that, please stop. Their experience likely has nothing to do with yours.</p>
<p>Valuation = traction + market comps + revenue + momentum + team.</p>
<p>Valuation isn’t just about what you want – it’s about what you can defend.</p>
<p>Startups are typically valued using:</p>
<ul>
<li><p><strong>Comparable Analysis (Comps):</strong> What similar companies are worth</p>
</li>
<li><p><strong>Discounted Cash Flow (DCF):</strong> Projecting future cash and discounting it back</p>
</li>
<li><p><strong>Revenue Multiples:</strong> Often 5x–10x for SaaS, but varies wildly</p>
</li>
<li><p><strong>Precedent Transactions:</strong> What investors paid in past rounds for similar startups</p>
</li>
</ul>
<p>But that’s the math.</p>
<p>Here’s the messy truth: <strong>Valuation = Traction + Team + TAM (total addressable market) + Timing + Storytelling.</strong></p>
<p>Hard factors:</p>
<ul>
<li><p>MRR/ARR</p>
</li>
<li><p>Growth rate</p>
</li>
<li><p>Churn</p>
</li>
<li><p>CAC:LTV</p>
</li>
<li><p>Gross margins</p>
</li>
</ul>
<p>Soft factors:</p>
<ul>
<li><p>Founding team’s track record</p>
</li>
<li><p>Market momentum</p>
</li>
<li><p>Hype or scarcity</p>
</li>
</ul>
<p>Don’t inflate. Don’t anchor to your friend’s raise. Know your comps. And show why <em>your</em> model is defensible, not just desirable. Inflated numbers make investors run. They don’t correct you – they just ghost you.</p>
<p>There are numerous books written on valuation and each technique could be its own PhD. But my role here is to give you a sneak peak into the metrics.</p>
<p>Here’s a <a target="_blank" href="https://www.youtube.com/watch?v=T3Ud5WQCrzQ">basic video on valuation</a> if you’re interested in a deeper dive.</p>
<p>And <a target="_blank" href="https://www.youtube.com/watch?v=znmQ7oMiQrM&amp;list=PLUkh9m2BorqnKWu0g5ZUps_CbQ-JGtbI9">here’s a more detailed video course</a> outlining different forms of valuation. Professor Damodaran from New York University is considered to be one of the aces and thought leaders when it comes to valuation. In this video course he explains stepwise and beautifully so you can understand and explore the fascinating world of valuations.</p>
<h2 id="heading-real-talk-before-you-close-that-tab">Real Talk Before You Close That Tab</h2>
<h3 id="heading-real-experience">Real Experience</h3>
<p>I met a founder once – early days, rough product, but you could tell he actually cared. He wasn't trying to look good. No buzzwords. No "disrupt" talk. Just someone trying to solve something annoying and important.</p>
<p>He walked into the room with a twinkle. Not swagger – just that gentle intensity. We were leaning in.</p>
<p>Then, in the middle of the pitch, someone asked, "So what's your monthly burn?" And I swear to you, he said, "Umm... I think my co-founder has that. I haven't looked in a while."</p>
<p>That was it.</p>
<p>No freak out. No awkward pause. Just... a cluck. Like a window closing in the background.</p>
<p>The product? Still smart. But the moment? Gone.</p>
<p>Nobody was mad. Nobody laughed. We even said thank you. But nobody followed up.</p>
<p>Why? Because it didn't feel like a business. It felt like a maybe.</p>
<h3 id="heading-why-this-matters">Why This Matters</h3>
<p>I’ve seen so many versions of that same scene play out. It’s never about charisma. It’s not even about the idea, half the time.</p>
<p>It’s about whether the person asking for money actually knows what they’re building. Not the dream, the mechanics. The guts, nuts and bolds of the business. The ugly Excel math nobody brags about on Twitter.</p>
<p>Unfortunately, no simple pitch deck will do that part for you. No co-founder can answer those questions on your behalf.</p>
<p>If it’s your vision, own the math. If it’s your company, learn the cost of keeping it alive.</p>
<p>The rest? The logos, the taglines, the “go-to-market” plans?.... All of that’s just packaging.</p>
<p>And you don’t have to be perfect either. You just have to be in it. Eyes open. Numbers in your head.<br>Because if you’re asking people to believe in what you’re building, you’d better believe in the scaffolding holding it up.</p>
<p>So yeah, know your CAC. Your LTV. Your margins. Your churn. Not to check some box on an investor’s sheet, but to prove to yourself and the investor that the thing you’re spending your life on…has legs. That it can stand. And run.</p>
<p>And maybe, someday, outlast you. Maybe!</p>
<h2 id="heading-conclusion-and-final-thoughts"><strong>Conclusion and Final Thoughts</strong></h2>
<p>I hope this was helpful to you, especially if you’re a founder or aspiring founder trying to build the next big thing. While there a many more ratios and concepts, these are the crux of them.</p>
<p>A lot of other complex ratios and valuations are either built using these metrics or refer them in some way. And each of these metrics could be an article of its own. But I wanted to give you my top 10 run down so that you could get a head start. Numbers are very much a part of the ideation stage itself, and omitting them from your strategy could prove to be a fatal mistake.</p>
<p>I’ll leave you with <a target="_blank" href="https://youtu.be/Pg72m3CjuK4?si=GtIFdvC5WzbKna79">one last video</a> on How to Start a Start Up with Michael Seibel (Reddit, YC, Twitch) that I hope you find valuable. It lays out, in a crash course format, the mindset of a founder who has been there and done that. The fun fact is that a lot of the themes he speaks of tie in to the metrics here, directly or indirectly.</p>
<p>I hope this gives you a perspective of being on the other side, evaluating your hard work and passion, and I hope it sets you up for success in your next Investor Review.</p>
<p>I look forward to your thoughts, comments, and feedback. If this was helpful, engaging, and informative, do share it – you never know who may need it, or could benefit from it. I wish you all the very best in your funding rounds.</p>
<p>Until then, keep learning, unlearning, and relearning, folks.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How the Black-Scholes Equation Works – Explained with Python Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ The Black-Scholes Equation is probably one of the most influential equations that nobody has heard about. It's particularly important in finance, especially in these areas: Securitized debt Exchange-traded options Credit default swaps Over-the-count... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-the-black-scholes-equation-works-python-examples/</link>
                <guid isPermaLink="false">66ba532b8e44e0cdf128126f</guid>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MathJax ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tiago Capelo Monteiro ]]>
                </dc:creator>
                <pubDate>Mon, 17 Jun 2024 16:42:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/dan-cristian-padure-h3kuhYUCE9A-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The Black-Scholes Equation is probably one of the most influential equations that nobody has heard about.</p>
<p>It's particularly important in finance, especially in these areas:</p>
<ul>
<li>Securitized debt</li>
<li>Exchange-traded options</li>
<li>Credit default swaps</li>
<li>Over-the-counter derivatives securities</li>
</ul>
<p>In this article, you'll learn why the Black-Scholes Equation is so important in finance, what problems it solves, and the industries it created.</p>
<h3 id="heading-heres-what-well-cover">Here's what we'll cover:</h3>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisite-knowledge-of-finance">Prerequisite knowledge of finance</a></li>
<li><a class="post-section-overview" href="#heading-analogy-predict-the-price-of-a-ticket-for-a-concert">Analogy: Predict the price of a ticket for a concert</a></li>
<li><a class="post-section-overview" href="#heading-black-scholes-in-plain-english-with-a-code-example">Plain English explanation with code example</a></li>
<li><a class="post-section-overview" href="#heading-implications-in-the-real-world">Implications in the real world</a></li>
</ul>
<p>Note: In the code example, we will be working with European call and put options.</p>
<h2 id="pre">Prerequisite Knowledge of Finance</h2>

<p>To get the most out of this article and understand the Black-Scholes Equation, you just need to know what <strong>financial derivatives</strong> and <strong>options</strong> are in finance.</p>
<p>Essentially, financial derivatives are tools investors use to manage risks and improve returns.</p>
<p>There are many types of financial derivatives. One of these is called options. </p>
<p>Options are like financial choices. With options, you can get the right to buy or sell something at a certain time and price, but only if you want to.</p>
<p>The main idea is that they help manage risk so you can make future better investments.</p>
<h2 id="analogy"> Analogy: Predict the Price of a Ticket for a Concert </h2>

<p>Imagine you are planning to buy a ticket for a concert.</p>
<p>The ticket prices change depending on the popularity of the artist, demand, and time until the concert.</p>
<p>Depending on that, you will make the best possible decision to buy the ticket at the lowest price.</p>
<p>Just as you think about the <strong>risk</strong> of buying the thicket at a certain time, investors use the Black-Scholes Equation to estimate the fair value of financial derivatives.</p>
<p>This way, they make sure they make wise investment choices in ever changing markets.</p>
<h2 id="plain"> Black-Scholes in Plain English – with a Code Example </h2>

<p>Essentially, the Black-Scholes Equation solved the problem of <a target="_blank" href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=500303">how to price options correctly in financial markets.</a></p>
<p>This is very important, because it helps banks and financial institutions effectively manage risk.</p>
<p>However, it was not always like this. Before 1973, when the equation was created (<a target="_blank" href="https://www.nobelprize.org/prizes/economic-sciences/1997/press-release/">its creators won a Nobel prize</a>), determining the price of options was much more complicated and difficult.</p>
<p>Before the creation of the Black–Scholes equation, there wasn't a standardized mathematical method to predict the prices of options.</p>
<p>Traders often relied on personal experience and market conditions, which led to unreliable option prices.</p>
<p>And earlier mathematical methods did not fully consider factors like volatility, time decay, and interest rates. So there was a lot of error when pricing options.</p>
<h3 id="heading-here-is-the-black-scholes-equation">Here is the Black-Scholes Equation:</h3>
<p>$$\frac{\partial V}{\partial t} + \frac{1}{2}\sigma^2 S^2 \frac{\partial^2 V}{\partial S^2} = rV - r S \frac{\partial V}{\partial S}$$</p><p>While we won't look very deeply at the equation itself, we will outline its key components and implications.</p>
<p>Essentially, the Black-Scholes equation predicts how an option's value changes over time based on several variables:</p>
<ul>
<li>V - Price of option as a function of stock price <em>S</em> and time <em>t</em></li>
<li>S – Price of the underlying asset</li>
<li>t – Time</li>
<li>σ – Volatility</li>
<li>r – Interest rate.</li>
</ul>
<p>The left side of the equation explains how the option's value changes over time and how market ups and downs affect it. </p>
<p>The right side of the equation shows how the option's value increases due to interest rates and how changes in the asset's price impact it. </p>
<p>By making these two sides equal, we figure out the fair price of the option. </p>
<h3 id="heading-python-code-example">Python Code Example</h3>
<p>In this code example, we will find, based on many parameters, the theoretical market value of an option.</p>
<p>For our example, let's assume the following:</p>
<ul>
<li>Current stock price (S) = $100. This is the price of the stock right now.</li>
<li>Strike price (K) = $105. This is the specific price at which the option holder can buy (call) or sell (put) the underlying asset.</li>
<li>Time to expiration (T) = 1 year (or 1.0 when expressed in years). This is the time left until the option expires.</li>
<li>Risk-free interest rate (r) = 0.05% (or 0.0005 when expressed as a decimal). This is the interest rate on a risk-free investment.</li>
<li>Volatility (sigma) = 20% (or 0.2 when expressed as a decimal). This is how much the stock price is expected to fluctuate.</li>
</ul>
<pre><code><span class="hljs-keyword">from</span> blackscholes <span class="hljs-keyword">import</span> BlackScholesCall, BlackScholesPut

def calculate_option_prices(S, K, T, r, sigma, q):
    <span class="hljs-string">""</span><span class="hljs-string">"
    Calculate the Black-Scholes option prices for European call and put options using the 'blackscholes' package.

    Parameters:
    S : float - current stock price
    K : float - strike price of the option
    T : float - time to maturity (in years)
    r : float - risk-free interest rate (annual as a decimal)
    sigma : float - volatility of the underlying stock (annual as a decimal)
    q : float - annual dividend yield (as a decimal)

    Returns:
    tuple - (call price, put price)
    "</span><span class="hljs-string">""</span>
    # Creating instances <span class="hljs-keyword">of</span> BlackScholesCall and BlackScholesPut
    call_option = BlackScholesCall(S=S, K=K, T=T, r=r, sigma=sigma, q=q)
    put_option = BlackScholesPut(S=S, K=K, T=T, r=r, sigma=sigma, q=q)

    # Get call and put prices
    call_price = call_option.price()
    put_price = put_option.price()

    <span class="hljs-keyword">return</span> call_price, put_price


call_price, put_price = calculate_option_prices(<span class="hljs-number">100</span>, <span class="hljs-number">105</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0.0005</span>, <span class="hljs-number">0.20</span>, <span class="hljs-number">0.0</span>)
print(<span class="hljs-string">"Call Price: {:.6f}, Put Price: {:.6f}"</span>.format(call_price, put_price))
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2024/05/1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now let's examine the code more closely and see what's really going on here:</p>
<h4 id="heading-step-1-import-the-library">Step 1: Import the Library</h4>
<p>This is the Python library we are using in this article:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://pypi.org/project/blackscholes/">https://pypi.org/project/blackscholes/</a></div>
<pre><code><span class="hljs-keyword">from</span> blackscholes <span class="hljs-keyword">import</span> BlackScholesCall, BlackScholesPut
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2024/05/2.png" alt="Image" width="600" height="400" loading="lazy">
<em>Importing functions</em></p>
<h4 id="heading-step-2-create-the-function-to-calculate-options-prices">Step 2: Create the Function to Calculate Options Prices</h4>
<p>In the below code, we are importing the function we need to calculate the options call and put prices.</p>
<pre><code>def calculate_option_prices(S, K, T, r, sigma, q):

    call_option = BlackScholesCall(S=S, K=K, T=T, r=r, sigma=sigma, q=q)
    put_option = BlackScholesPut(S=S, K=K, T=T, r=r, sigma=sigma, q=q)

    call_price = call_option.price()
    put_price = put_option.price()

    <span class="hljs-keyword">return</span> call_price, put_price
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2024/05/3.png" alt="Image" width="600" height="400" loading="lazy">
<em>Function to calculate call and put prices</em></p>
<p>The main parameters of the function are:</p>
<ul>
<li>S : float – current stock price</li>
<li>K : float – strike price of the option</li>
<li>T : float – time to maturity (in years)</li>
<li>r : float – risk-free interest rate (annual as a decimal)</li>
<li>sigma : float – volatility of the underlying stock (annual as a decimal)</li>
<li>q : float – annual dividend yield (as a decimal)</li>
</ul>
<p>And it returns:</p>
<ul>
<li>tuple – (call price, put price)</li>
</ul>
<p>First, we calculate the call and put options. Then we extract the price from it. We can also get other characteristics like the charm or the delta of these financial contracts according to the library documentation.</p>
<h4 id="heading-step-3-calculate-the-options-pricing">Step 3: Calculate the Options Pricing</h4>
<p>The call and put prices of an option are the costs to buy the respective option contracts. </p>
<pre><code>call_price, put_price = calculate_option_prices(<span class="hljs-number">100</span>, <span class="hljs-number">105</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0.0005</span>, <span class="hljs-number">0.20</span>, <span class="hljs-number">0.0</span>)
print(<span class="hljs-string">"Call Price: {:.6f}, Put Price: {:.6f}"</span>.format(call_price, put_price))
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2024/05/4.png" alt="Image" width="600" height="400" loading="lazy">
<em>Applying the function</em></p>
<p>We use as examples:</p>
<ul>
<li>Current stock price: $100</li>
<li>Strike price: $105</li>
<li>Time to maturity: 1 year</li>
<li>Risk-free interest rate: 0.05% (as a decimal: 0.0005)</li>
<li>Volatility: 20% (as a decimal: 0.20)</li>
<li>Dividend yield: 0%</li>
</ul>
<p>Based on this factors, we price:</p>
<ul>
<li>Call Option Price: 5.924799</li>
<li>Put Option Price: 10.872312</li>
</ul>
<p>Which means that, given these parameters:</p>
<ul>
<li>The price at which you have the right, but not the obligation, to buy is 5.924799 dollars</li>
<li>The price at which you have the right, but not the obligation, to sell is 10.872312 dollars</li>
</ul>
<h2 id="implications"> Implications in the Real World </h2>

<p>The equation has had a massive impact in the world of finance.</p>
<p>Below are some of the industries the Black-Scholes Equation has changed greatly:</p>
<h3 id="heading-securitized-debt">Securitized Debt</h3>
<p>In simple terms, securitized debt refers to turning loans into something that can be bought and sold.</p>
<p>The Black-Scholes equation changed the way banks price grouped-up debt, like mortgages.</p>
<p>Before the Black-Scholes equation, it was very hard to know the worth of these debts. But with the equation, banks can understand their value much better. This made it easier to buy and sell these debts while knowing the potential benefits and risks.</p>
<p>This way, the market for these mortgage debts grew. Which in turn helped grow the housing market.</p>
<h3 id="heading-exchange-traded-options">Exchange Traded Options</h3>
<p>Trading options was a very uncertain business. There was no way of truly knowing how to correctly price them.</p>
<p>However, with the Black-Scholes equation, option pricing became far easier. It allowed people to calculate an option based on an underlying asset's price, volatility, time to expiration, and interest rates.</p>
<p>The newfound precision helped grow the options market.</p>
<h3 id="heading-credit-default-swaps">Credit Default Swaps</h3>
<p>Credit default swaps are like insurance policies for loans. With a credit default swap, you are protected if the borrower fails to pay back.</p>
<p>Credit default swaps are very important in managing credit risk. But it was only after the black Scholes equation was created that they were accurately priced.</p>
<p>This way, credit default swaps became a very important tool for financial institutions for financial risk management.</p>
<h3 id="heading-over-the-counter-derivatives-securities">Over the Counter Derivatives Securities</h3>
<p>Over-the-counter (OTC) derivatives are private deals made between two parties without a stock exchange.</p>
<p>Before Black-Scholes, negotiating the terms and prices of OTC derivatives was very hard. But then the Black-Scholes equation offered a standard way of finding the price of derivatives.</p>
<p>This allowed market participants to negotiate contracts more efficiently and accurately.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The Black-Scholes equation helped create more precision in the way certain things are priced.</p>
<p>This precision helped create more stable institutions, which in turn helped create a more resilient economy.</p>
<p>If interested in learning more, see this video:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/A5w-dEgIU1M" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>If you are interested in learning more about finance:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/fundamentals-of-finance-economics-for-businesses/">https://www.freecodecamp.org/news/fundamentals-of-finance-economics-for-businesses/</a></div>
<h2 id="heading-full-code">Full code</h2>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/tiagomonteiro0715/freecodecamp-my-articles-source-code">https://github.com/tiagomonteiro0715/freecodecamp-my-articles-source-code</a></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Podcast: Automate Your Job Then Keep Climbing with Malindi Colyer ]]>
                </title>
                <description>
                    <![CDATA[ Today I'm joined by Malindi Colyer. Among her many skills, she's a Python developer and AI engineer. Malindi grew up on a farm in rural Kansas, in the middle of the US. She trained to become a diplomat, and volunteered overseas. But along the way, sh... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/podcast-95-malindi-colyer/</link>
                <guid isPermaLink="false">66b8d4f4e9a1e34f08e4924e</guid>
                
                    <category>
                        <![CDATA[ AI Engineer ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ podcast ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Quincy Larson ]]>
                </dc:creator>
                <pubDate>Fri, 01 Sep 2023 15:48:09 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/andre-benz-zeZxd1ItwpA-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Today I'm joined by Malindi Colyer. Among her many skills, she's a Python developer and AI engineer.</p>
<p>Malindi grew up on a farm in rural Kansas, in the middle of the US. She trained to become a diplomat, and volunteered overseas. But along the way, she discovered a love of math and computer science. That passion has landed her jobs in New York City, London, and San Francisco.</p>
<p>I met up with Malindi in downtown Manhattan to learn all about investment banking, and how she modernized her department at JP Morgan using her software engineering skills. We talk about the high-stakes world of global finance, where she was executing trades sometimes worth hundreds of millions of dollars.</p>
<p>We also talk about her time as a venture capitalist. She researched thousands of startups to decide which ones her fund should invest in.</p>
<p>This is one of the most technical interviews I've done. I've done my best to make Malindi's world of math, AI, and high finance as accessible as I can. I hope you enjoy it.</p>
<div class="embed-wrapper"><iframe src="https://play.libsyn.com/embed/episode/id/27915120/height/192/theme/modern/size/large/thumbnail/yes/custom-color/34345c/time-start/00:00:00/playlist-height/200/direction/backward/download/yes" height="192" width="100%" style="border:none" title="Embedded content" loading="lazy"></iframe></div>

<p>Malindi on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/alexandra-malindi-colyer-46b95589/">https://www.linkedin.com/in/alexandra-malindi-colyer-46b95589/</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is a ROM? ROM Price and Cost Estimate ]]>
                </title>
                <description>
                    <![CDATA[ ROM stands for Rough Order of Magnitude. It is a project management guideline to determine the estimated range of costs for a project. This article will explain: Who should use a ROM When to use a ROM How to calculate a ROM Simple example of a ROM ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-a-rom-price-and-cost-estimate-2/</link>
                <guid isPermaLink="false">66b8de2cfedc3fd92fddb76c</guid>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ project management ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Eamonn Cottrell ]]>
                </dc:creator>
                <pubDate>Fri, 16 Dec 2022 17:27:32 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/12/12.15.22-What-is-a-ROM.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>ROM stands for <strong>Rough Order of Magnitude</strong>. It is a project management guideline to determine the estimated range of costs for a project.</p>
<p>This article will explain:</p>
<ol>
<li>Who should use a ROM</li>
<li>When to use a ROM</li>
<li>How to calculate a ROM</li>
<li>Simple example of a ROM</li>
</ol>
<h2 id="heading-who-should-use-a-rom">Who Should Use a ROM</h2>
<p>Project Managers use rough orders of magnitude to determine initial cost ranges for upcoming projects. Many organizations and most software organizations use project managers to lead projects.</p>
<p>Their role involves leading their project team, defining the goals of the project, reporting on the progress to the company stakeholders, and seeing the project through to completion.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/pm.gif" alt="Image" width="600" height="400" loading="lazy">
<em>man with blank stare listening to man trying to explain something</em></p>
<p>Who else can use a ROM? You! 👊 As you'll see, the concept of a ROM is very simple to grasp and can be useful in myriad circumstances. </p>
<h2 id="heading-when-to-use-a-rom">When to Use a ROM</h2>
<p>ROMs are extremely important for project managers in the <strong>early stages</strong> of a project's planning. They're used to decide whether or not a project is going to be feasible or not.</p>
<p>Rough Orders of Magnitude can be used to prepare a project business case (an analysis of the potential benefits of the project) before a project is committed to.</p>
<h2 id="heading-how-to-calculate-a-rom">How to Calculate a ROM</h2>
<p>Calculating a ROM is pretty straightforward. It is meant to provide a <strong>range of the possible cost of a project</strong> and you can find it using the following formulas:</p>
<p><code>Lower Bound = ROM Estimate x 0.75</code></p>
<p><code>Upper Bound = ROM Estimate x 1.75</code></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/fred.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Fred Flinstone counting on fingers</em></p>
<p>During the planning phases of a project, the project manager can come up with an estimate of the costs involved. From here, using the above formulas, they can then calculate a lower boundary in case the project ends up being less expensive and an upper boundary in case it goes over budget.</p>
<p>Since it is helpful to have more room on the upper boundary to avoid running out of funding if it does go over budget, the rough order of magnitude's upper boundary is considerably higher.</p>
<h2 id="heading-rom-example">ROM Example</h2>
<p>You've probably calculated a ROM without knowing it. 💡</p>
<p>Say you're going to the movies with a friend. You figure there will be ticket costs plus refreshment costs. Maybe $20 a ticket since you're going to the latest Nolan IMAX film and then another $30 a person since popcorn is more expensive than steaks at the movies.</p>
<p>This puts you at $100 total for both of you. </p>
<p>The Lower Bound in a ROM calculation would be <code>$100 x 0.75 = $75</code>.</p>
<p>The Upper Bound would be <code>$100 x 1.75 = $175</code>.</p>
<p>You probably don't do this exact math in your head, but you likely have figured there could be extra expenses. You go into the date thinking you could spend as much as $150, for instance.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/movie.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Angry Bird eating popcorn at movies</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Rough Orders of Magnitude are extremely important in organizational projects. It is vital to decide at the onset whether or not the project is feasible. And the principals behind ROMs are both common sense and easy to calculate. </p>
<p>I hope this has been helpful to you!</p>
<p>You can find and follow me on <a target="_blank" href="https://www.linkedin.com/in/eamonncottrell/">LinkedIn</a>. I'd love if you said hey! 👋</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Capital Expenditure – What is CapEx? Definition and Meaning ]]>
                </title>
                <description>
                    <![CDATA[ By Adam Naor CapEx stands for capital expenditures, which is money used by an organization to purchase, improve, or sustain physical assets.  Commonly held physical assets include PP&E (property, plans, buildings, and equipment for running and sustai... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/capital-expenditure-what-is-capex-definition-and-meaning/</link>
                <guid isPermaLink="false">66d45d62230dff01669057a7</guid>
                
                    <category>
                        <![CDATA[ business ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 11 Feb 2021 20:24:06 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/602558220a2838549dcc37ad.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Adam Naor</p>
<p>CapEx stands for capital expenditures, which is money used by an organization to purchase, improve, or sustain physical assets. </p>
<p>Commonly held physical assets include PP&amp;E (property, plans, buildings, and equipment for running and sustaining the business).</p>
<p>In order to explain CapEx further I want to use a fictitious business to illustrate examples in a clear and concise way.</p>
<h2 id="heading-what-is-capex">What is CapEx?</h2>
<p>Firstly, imagine a company that makes jewelry - like engagement rings. In order to produce rings, the company needs basic materials (gold, diamonds, etc), equipment to turn these raw ingredients into final products, and labor.</p>
<p>Now imagine you own and operate this business.</p>
<p>As the owner of this company you decide that you will buy property (perhaps a warehouse for storing raw materials), equipment (such as a high temperature furnace to smelt gold), or fans to keep the showroom cool and comfortable. </p>
<p>What would you call this property and equipment? How would you account for them? To put it simply, this equipment is a capital expenditure. </p>
<p>Why?</p>
<p>In this case you are quite literally expending capital (money) in exchange for other types of assets to help the business grow.</p>
<p>And that is precisely what CapEx is.</p>
<p>Because buying the machinery, equipment, and property would help the business maintain or increase its operation, we classify these transactions as CapEx. </p>
<p>Another example is Goldspot Pens, a fountain pen store that sells bottled ink and fountain pens, who are investing in new, bigger warehouses for storing their fountain pens and ink. This costs more money, but increases Goldspot Pens' scope of economic performance in the future. </p>
<p>In this simple example, the choice to buy these future economically productive assets represents CapEx.</p>
<p>In summary, CapEx is the money an organization spends to buy, maintain, or improve its assets to increase its scope and economic performance.</p>
<h2 id="heading-how-to-calculate-capex">How to Calculate CapEx</h2>
<p>Now that you know what CapEx is, and are armed with an example of CapEx at a jewelry business, you might be curious how a company calculates CapEx in practice.</p>
<p>There is a simple equation: CapEx is equal to changes in PP&amp;E added to Current Depreciation.</p>
<p>The formula: CapEx = ΔPP&amp;E + Current Depreciation</p>
<p>Let’s break down these parts of the equation to clarify. </p>
<ol>
<li>CapEx: spending on business critical property or equipment or technology to grow the firm.</li>
<li>ΔPP&amp;E: changes in PP&amp;E recorded on the balance sheet. If a firm buys a machine for $1M, for example, it will mark this machine in the PP&amp;E section (usually under long term assets).</li>
<li>Current Depreciation: a concept that captures the cost of the asset by the useful life of the asset. </li>
</ol>
<p>Specifically, here are the steps to calculate Current Depreciation.</p>
<ul>
<li>Declare the useful life of the asset (10 years is a fair value to use). </li>
<li>Subtract the salvage value of the asset (that is, at the end of year 10 the machine will be worth some value).</li>
<li>Divide this value by the starting cost of the asset ($1,000,000)</li>
</ul>
<p>In this example, let me show you what a depreciation table will yield. The asset starts at $1,000,000 on Day 1 but ends the depreciation cycle at $25,000.</p>
<table><tbody><tr><td><strong>Year</strong></td><td><strong>Beginning Book Value</strong></td><td><strong>Depreciation Percent</strong></td><td><strong>Depreciation Amount</strong></td><td><strong>Accumulated Depreciation Amount</strong></td><td><strong>Ending Book Value</strong></td></tr><tr><td>1.</td><td>$1,000,000</td><td>10.00%</td><td>$97,500</td><td>$97,500</td><td>$902,500</td></tr><tr><td>2.</td><td>$902,500</td><td>10.00%</td><td>$97,500</td><td>$195,000</td><td>$805,000</td></tr><tr><td>3.</td><td>$805,000</td><td>10.00%</td><td>$97,500</td><td>$292,500</td><td>$707,500</td></tr><tr><td>4.</td><td>$707,500</td><td>10.00%</td><td>$97,500</td><td>$390,000</td><td>$610,000</td></tr><tr><td>5.</td><td>$610,000</td><td>10.00%</td><td>$97,500</td><td>$487,500</td><td>$512,500</td></tr><tr><td>6.</td><td>$512,500</td><td>10.00%</td><td>$97,500</td><td>$585,000</td><td>$415,000</td></tr><tr><td>7.</td><td>$415,000</td><td>10.00%</td><td>$97,500</td><td>$682,500</td><td>$317,500</td></tr><tr><td>8.</td><td>$317,500</td><td>10.00%</td><td>$97,500</td><td>$780,000</td><td>$220,000</td></tr><tr><td>9.</td><td>$220,000</td><td>10.00%</td><td>$97,500</td><td>$877,500</td><td>$122,500</td></tr><tr><td>10.</td><td>$122,500</td><td>10.00%</td><td>$97,500</td><td>$975,000</td><td>$25,000</td></tr></tbody></table>

<p>Now that you know how to calculate depreciation, you can solve CapEx mathematically, using either a Direct or Indirect Method.</p>
<h4 id="heading-direct-method"><strong>Direct method:</strong></h4>
<ul>
<li>Amount spent on asset #1</li>
<li>Plus: Amount spent on asset #2</li>
<li>Plus: Amount spent on asset #3</li>
<li>Less: Value received for assets that were sold</li>
<li>= Net CapEx</li>
</ul>
<h4 id="heading-indirect-method"><strong>Indirect Method:</strong></h4>
<ul>
<li>PP&amp;E Balance in the current period</li>
<li>Less: PP&amp;E balance in the previous period</li>
<li>Plus: Depreciation in the current period</li>
<li>= Net CapEx</li>
</ul>
<p>If you bought an asset for $1,000,000 and sold it at the end of year 10 for $25,000 your Capital Expenditure would be: $1,000,000 - $25,000 = $975,000.</p>
<h2 id="heading-the-meaning-of-capex-in-practice">The Meaning of CapEx in Practice</h2>
<p>When you decide to buy equipment today, you are doing so because you believe that the equipment will generate future economic benefits, or profits.</p>
<p>If you didn’t believe this, you likely would not have purchased the property, hardware, or equipment in the first place. Because CapEx is any type of expense that a company capitalizes, or shows on its balance sheet as an investment, you will need to justify how the purchase adds economic value to the firm's future.</p>
<p>For this reason, CapEx is considered a capitalized expenditure and not an expense. </p>
<p>This enables you, as the business owner, to match the economic benefits of the items you are buying with the costs in a given period of time.</p>
<p>If you were unable to match the purchase with economic benefits, you would treat the expenditure as an expense and not as an investment.</p>
<h2 id="heading-summary">Summary</h2>
<p>Many businesses, but not all, have CapEx. </p>
<p>Think about large companies like Google, AT&amp;T, and Apple with large data centers, 5G networks, and fulfillment centers, respectively. These are all examples of CapEx. </p>
<p>These companies invest in these pieces of land, equipment, and machinery because each firm wants to secure a profitable future. </p>
<p>And without this CapEx, such a future would be harder to obtain.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is a Mortgage? A Simple Definition. ]]>
                </title>
                <description>
                    <![CDATA[ By Adam Naor Let’s say you want to buy a car. But you don’t have enough money sitting around to pay for the car in one payment.  So you take out an auto-loan. This loan provides you borrowed money with the explicit designation that it be used to purc... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-a-mortgage-a-simple-definition/</link>
                <guid isPermaLink="false">66d45d80787a2a3b05af436e</guid>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ money ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 02 Feb 2021 22:16:52 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/6018bc0e0a2838549dcbcce1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Adam Naor</p>
<p>Let’s say you want to buy a car. But you don’t have enough money sitting around to pay for the car in one payment. </p>
<p>So you take out an auto-loan. This loan provides you borrowed money with the explicit designation that it be used to purchase the vehicle.</p>
<p>Here is a second example. Imagine you want to buy a wedding ring but don’t have enough funds to pay for the ring up front today. What do you do? You get a small loan.</p>
<p>Sounds simple, right?</p>
<p>A mortgage is the exact same <strong>thing</strong>, except applied to a property (a home or building). In simple terms, a mortgage is a type of loan, just like an auto-loan or financing for jewelry. </p>
<p>Specifically it is a loan in which a person borrows money to buy or refinance a house. That’s it.</p>
<p>A loan can be used to describe many different types of financial transactions. You can have a student loan, or per the example above, a loan to buy a car. </p>
<p>If you are borrowing money to buy a home, you will need a home loan. And home loans are called mortgages.</p>
<h2 id="heading-who-needs-a-mortgage">Who needs a mortgage?</h2>
<p>Most people buying property require a mortgage to complete the transaction. That is because most people don’t have enough money available to spend hundreds of thousands or millions of dollars at one time. </p>
<p>If you don’t have the cash upfront, a mortgage is the loan type you will leverage to complete the transaction.</p>
<p>Because a mortgage is usually paid back over many years (30 is typical) it enables buyers to make a purchase using borrowed money. </p>
<p>As the years go on, the mortgage is repaid. If you are unable to make your mortgage payments, the lender can take the home in a process called foreclosure. </p>
<p>This is because mortgages are “secured” by the asset being purchased (that is, a home).</p>
<h2 id="heading-how-is-a-mortgage-structured">How is a mortgage structured?</h2>
<p>There are different types of mortgages. But to use simple math, let’s assume that an average American home costs $300,000.</p>
<p>If you want to put down 20%, you will need $60,000 in cash. This $60,000 represents the down payment. The size of the down payment will depend on many variables - your credit score, the type of loan you are applying for, and the value of the property itself.</p>
<p>The rest of the purchase price - or $240,000 - will be financed by the mortgage. When borrowing this $240,000, you will need to agree to different terms of repayment. </p>
<p>Common terms will include the time that the loan must be paid back, the interest rate of the loan, and what happens if you fail to make loan payments on time.</p>
<p>The common parties involved in this transaction include:</p>
<ol>
<li>The lender: this is the bank or financial institution that is providing you money.</li>
<li>The borrower: the person getting the loan.</li>
<li>Loan servicer: the organization in charge of providing monthly mortgage statements and processing payments, and so on.</li>
</ol>
<h2 id="heading-how-to-pay-back-your-mortgage">How to pay back your mortgage</h2>
<p>As you are thinking about a mortgage - and if you should apply for one (and the size) - you will want to think about how much the loan will cost you. When borrowing money you need to be prepared to pay it back with interest. </p>
<p>One way to think about this interest is using a framework called the “cost of capital”. </p>
<p>In other words, how much is it costing you to borrow this money? The cost of capital is the cost of debt if your home is financed solely through debt.</p>
<p>When paying back a mortgage you will have four costs:</p>
<ol>
<li>Principal (paying back the principal of what was borrowed)</li>
<li>Interest (paying the interest on the loan itself)</li>
<li>Taxes</li>
<li>Insurance (most common for people who put down less than 20% of the home value)</li>
</ol>
<p>Some mortgages use fixed rates and others adjustable rates. Fixed rates are conceptually easiest to understand: you will pay a fixed (or constant) rate until the mortgage is paid back in full. </p>
<p>Using the $240,000 example from above and an interest rate of 3.5% over 30 years, you will need to pay $1,078 a month, every month, to pay the loan back.</p>
<p>Variable interest rates are slightly more complex. The interest rate is not fixed but rather benchmarked to a reference rate. </p>
<p>Sometimes people start their mortgage payment with a fixed interest rate followed by a variable one.</p>
<h2 id="heading-how-the-mortgage-process-works">How the mortgage process works</h2>
<p>Conceptually, there are three steps to getting a mortgage. This article is not the definitive guide, by any means, and there are complex nuances I am overlooking.</p>
<p>Step 1: Get approved for a mortgage. Sometimes this requires pre-approval. In short, its an agreement by a bank to loan you money,</p>
<p>Step 2: Find a home you want to buy, make an offer, and figure out how much money you will need to borrow to purchase this property.</p>
<p>Step 3: Get final approval and close on the loan.</p>
<h2 id="heading-bringing-it-all-together-a-mortgage-and-its-value">Bringing It All Together: A Mortgage and Its Value</h2>
<p>A loan is when money is given to you in exchange for repayment of the loan amount plus interest. One type of loan is a mortgage. </p>
<p>If you ever get confused and need a simpler example, just think about the example of buying a ring: you borrow money today to buy something you want or need. </p>
<p>And then you pay back that loan over time.</p>
<p>How much you borrow and on what terms (interest rate, length of repayment time table, and so on) are important considerations to understand before moving forward with this type of financial instrument.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 401K Limits 2020 – The IRS Max Contribution Limit Explained ]]>
                </title>
                <description>
                    <![CDATA[ By Adam Naor What is a 401K? Here is the legal and technical answer: in the United States, a 401k plan is an employer-sponsored contribution pension account defined in subsection 401k of the Internal Revenue Code.  A bit confused? Let me break it dow... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/401k-contribution-limits-explained/</link>
                <guid isPermaLink="false">66d45d593a8352b6c5a2a9e9</guid>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ money ]]>
                    </category>
                
                    <category>
                        <![CDATA[ taxes ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 26 Jan 2021 17:04:51 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/600dacfb0a2838549dcb6dd6.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Adam Naor</p>
<p>What is a 401K? Here is the legal and technical answer: in the United States, a 401k plan is an employer-sponsored contribution pension account defined in subsection 401k of the Internal Revenue Code. </p>
<p>A bit confused?</p>
<p>Let me break it down further in plain English.</p>
<p>A 401k is a pension account. A pension is any plan or fund which provides retirement income. So a 401k is dedicated to helping you save for retirement.</p>
<p>Now that you know what a 401k is, you might still be wondering why you should use it and how to set one up.</p>
<p>I have answers to both questions.</p>
<h2 id="heading-why-should-you-have-a-401k">Why should you have a 401k?</h2>
<p>A 401k is used to defer income today to save for tomorrow. In order to set up this type of account, you need to be employed and your employer needs to have a 401k plan that it offers to its employees.</p>
<p>The U.S. government enables employees to make tax-deferred contributions to their retirement account every year. As of calendar year 2021, the annual contribution limit for an employee under the age of 50 is $19,500. </p>
<p>So this means that, if you're under 50 years old, the most you can contribute to your 401K plan is $19,500 a year.</p>
<p>You might be wondering why the IRS limits annual contributions. There are two reasons:</p>
<ol>
<li>The IRS wants to prevent highly paid workers from benefitting more than the average worker from the tax advantages they provide.</li>
<li>The government wants people to spend some of their income today.</li>
</ol>
<h2 id="heading-ira-contribution-limit-for-2020-and-every-year-back-to-2002">IRA Contribution Limit for 2020 (and every year back to 2002)</h2>
<p>Here is a table showing historical limits. As you can see, each year the total contribution limit goes up slightly to account for inflation and increases wages.</p>
<table><colgroup><col><col><col><col></colgroup><tbody><tr><td><p><span>Year</span></p></td><td><p><span>Employee Contribution Limit</span></p></td><td><p><span>Total Contribution Limit</span></p></td><td><p><span>Age 50+ Catchup Contribution</span></p></td></tr><tr><td><p><span>2021</span></p></td><td><p><span>$19,500.00</span></p></td><td><p><span>$58,000.00</span></p></td><td><p><span>$6,500.00</span></p></td></tr><tr><td><p><span>2020</span></p></td><td><p><span>$19,500.00</span></p></td><td><p><span>$57,000.00</span></p></td><td><p><span>$6,500.00</span></p></td></tr><tr><td><p><span>2019</span></p></td><td><p><span>$19,000.00</span></p></td><td><p><span>$56,000.00</span></p></td><td><p><span>$6,000.00</span></p></td></tr><tr><td><p><span>2018</span></p></td><td><p><span>$18,500.00</span></p></td><td><p><span>$55,000.00</span></p></td><td><p><span>$6,000.00</span></p></td></tr><tr><td><p><span>2017</span></p></td><td><p><span>$18,000.00</span></p></td><td><p><span>$54,000.00</span></p></td><td><p><span>$6,000.00</span></p></td></tr><tr><td><p><span>2016</span></p></td><td><p><span>$18,000.00</span></p></td><td><p><span>$53,000.00</span></p></td><td><p><span>$6,000.00</span></p></td></tr><tr><td><p><span>2015</span></p></td><td><p><span>$18,000.00</span></p></td><td><p><span>$53,000.00</span></p></td><td><p><span>$6,000.00</span></p></td></tr><tr><td><p><span>2014</span></p></td><td><p><span>$17,500.00</span></p></td><td><p><span>$52,000.00</span></p></td><td><p><span>$5,500.00</span></p></td></tr><tr><td><p><span>2013</span></p></td><td><p><span>$17,500.00</span></p></td><td><p><span>$51,000.00</span></p></td><td><p><span>$5,500.00</span></p></td></tr><tr><td><p><span>2012</span></p></td><td><p><span>$17,000.00</span></p></td><td><p><span>$50,000.00</span></p></td><td><p><span>$5,500.00</span></p></td></tr><tr><td><p><span>2011</span></p></td><td><p><span>$16,500.00</span></p></td><td><p><span>$49,000.00</span></p></td><td><p><span>$5,500.00</span></p></td></tr><tr><td><p><span>2010</span></p></td><td><p><span>$16,500.00</span></p></td><td><p><span>$49,000.00</span></p></td><td><p><span>$5,500.00</span></p></td></tr><tr><td><p><span>2009</span></p></td><td><p><span>$16,500.00</span></p></td><td><p><span>$49,000.00</span></p></td><td><p><span>$5,500.00</span></p></td></tr><tr><td><p><span>2008</span></p></td><td><p><span>$15,500.00</span></p></td><td><p><span>$46,000.00</span></p></td><td><p><span>$5,000.00</span></p></td></tr><tr><td><p><span>2007</span></p></td><td><p><span>$15,500.00</span></p></td><td><p><span>$45,000.00</span></p></td><td><p><span>$5,000.00</span></p></td></tr><tr><td><p><span>2006</span></p></td><td><p><span>$15,000.00</span></p></td><td><p><span>$44,000.00</span></p></td><td><p><span>$5,000.00</span></p></td></tr><tr><td><p><span>2005</span></p></td><td><p><span>$14,000.00</span></p></td><td><p><span>$42,000.00</span></p></td><td><p><span>$4,000.00</span></p></td></tr><tr><td><p><span>2004</span></p></td><td><p><span>$13,000.00</span></p></td><td><p><span>$41,000.00</span></p></td><td><p><span>$3,000.00</span></p></td></tr><tr><td><p><span>2003</span></p></td><td><p><span>$12,000.00</span></p></td><td><p><span>$40,000.00</span></p></td><td><p><span>$2,000.00</span></p></td></tr><tr><td><p><span>2002</span></p></td><td><p><span>$11,000.00</span></p></td><td><p><span>$40,000.00</span></p></td><td><p><span>$1,000.00</span></p></td></tr></tbody></table>

<p>A note about this table: as an employee, you are not able to contribute more than $19,500 of your annual salary to your 401k if you are under 50 years old. If you are older than 50, however, the government enables you to make larger savings contributions. </p>
<p>This policy is intended to accelerate savings from people closer to retirement age.</p>
<p>Employers could contribute up to $57,000 (catch-up at $63,500) in 2020; in 2021 that amount has risen to $58,000 (or $64,500 with the catch-up contribution).</p>
<h2 id="heading-why-you-should-contribute-to-a-401k">Why you should contribute to a 401k</h2>
<p>If you are researching 401k contribution limits, perhaps you already understand the benefits of this savings account. If not, let me outline three reasons why a 401k can help you plan for retirement. </p>
<p>You can leverage these points if you are looking for finance feedback or if you're becoming better informed about how to plan for retirement.</p>
<ol>
<li>It is easy and painless. Money can be deducted from your paycheck in regular intervals. No need to engage in manual saving.</li>
<li>Many firms offer some sort of employer match as a financial incentive to save. Matching is a perk, like leadership development or office food. It is provided at the discretion of the firm and can be retracted. So if you take advantage of matching you will obtain even greater funds.</li>
<li>Tax breaks and benefits: your paycheck contributions are tax deductible. Because the capital you contribute doesn’t count towards your gross income, your net tax bill is lowered. Secondly, the money that is saved is tax-deferred. Over the course of your career these deferred taxes will add up.</li>
</ol>
<h2 id="heading-summary">Summary</h2>
<p>In this article we defined:</p>
<ol>
<li>What a 401k is</li>
<li>How these pension accounts work</li>
<li>The annual contribution limits of a 401k</li>
<li>And the benefits of these accounts for your saving aspirations.</li>
</ol>
<p>If you want to plan for your financial future, a 401k helps you make forced savings. This way you don't end up spending all of your income on travels or nights out.</p>
<p>By taking a disciplined approach and maximizing savings over time, a 401k can help you plan for the future you want by preserving and protecting future cash flows.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Algorithmic Trading with Python – Free 4-hour Course With Example Code Repos ]]>
                </title>
                <description>
                    <![CDATA[ Algorithmic trading is where you use computers to make investment decisions. Computer algorithms can make trades at near-instantaneous speeds and frequencies – much faster than humans would be able to. We've released a complete course on the freeCode... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/algorithmic-trading-using-python-course/</link>
                <guid isPermaLink="false">66b20064cfbefba140e247e5</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Fri, 04 Dec 2020 22:45:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/12/maxresdefault--16-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Algorithmic trading is where you use computers to make investment decisions. Computer algorithms can make trades at near-instantaneous speeds and frequencies – much faster than humans would be able to.</p>
<p>We've released a complete course on the freeCodeCamp.org YouTube channel that will teach you the basics of algorithmic trading.</p>
<p>Nick McCullum developed this course. Nick has worked as an investment analyst, portfolio manager, and software developer at financial startups for his entire career. He has a knack for explaining complex investment topics in a way that beginners can understand.</p>
<p>This course uses Python. Python is the most popular programming language for algorithmic trading. Python is powerful but relatively slow, so the Python often triggers code that runs in other languages.</p>
<p>Along with Python, this course uses the NumPy library to speed up the code. NumPy is the most popular Python library for performing numerical computing. Although NumPy is written for use in Python, the core underlying functionality is written in C, which is a much faster language.</p>
<p>Note that this course is meant for educational purposes only. The data and information presented in this video is not investment advice. One benefit of this course is that you get access to unlimited scrambled test data (rather than live production data), so that you can experiment as much as you want without risking any money or paying any fees.</p>
<h2 id="heading-course-outline">Course Outline</h2>
<p>In this course you will first learn the basics of algorithmic trading. Then you will learn how <a target="_blank" href="https://iexcloud.io/">the IEX Cloud API</a> works. We will use the API to gather data. </p>
<p>The bulk of this course teaches how to build three algorithmic trading projects.</p>
<p>Algorithmic Trading Fundamentals and API Basics</p>
<ul>
<li>What is Algorithmic Trading?</li>
<li>The Differences Between Real-World Algorithmic Trading and This Course</li>
<li>The Basics of API Requests</li>
</ul>
<p>Building An Equal-Weight S&amp;P 500 Index Fund</p>
<ul>
<li>Theory &amp; Concepts</li>
<li>Importing our Constituents</li>
<li>Pulling Data For Our Constituents</li>
<li>Calculating Weights</li>
<li>Generating Our Output File</li>
<li>Additional Project Ideas</li>
</ul>
<p>Building A Quantitative Momentum Investing Strategy</p>
<ul>
<li>Theory &amp; Concepts</li>
<li>Pulling Data For Our Constituents</li>
<li>Calculating Weights</li>
<li>Generating Our Output File</li>
<li>Additional Project Ideas</li>
</ul>
<p>Building A Quantitative Value Investing Strategy</p>
<ul>
<li>Theory &amp; Concepts</li>
<li>Importing our Constituents</li>
<li>Pulling Data For Our Constituents</li>
<li>Calculating Weights</li>
<li>Generating Our Output File</li>
<li>Additional Project Ideas</li>
</ul>
<p>The first project in the course is an equal-weight S&amp;P 500 screener. The S&amp;P 500 is the world's most popular stock market index. In this project, you will build an alternative version of the S&amp;P 500 Index Fund where each company has the same weighting.</p>
<p>The second project is a quantitative momentum screener. Momentum investing means investing in assets that have increased in price the most. You will create an algorithm that implements this strategy. First, you will build a strategy that uses a single momentum metric. Then, you will expand to build a more sophisticated strategy that uses multiple metrics together.</p>
<p>The final project is a quantitative value screener. Value investing means investing in stocks that are trading below their perceived intrinsic value. Like the previous project, you will first build a strategy that uses 1 value metric. Then, you will expand to build a more sophisticated strategy that uses 5 different value metrics together.</p>
<h2 id="heading-how-to-get-started-with-the-course">How to Get Started with the Course</h2>
<p>This course is original content created by our nonprofit, freeCodeCamp.org. It was made possible a grant provided by <a target="_blank" href="https://iexcloud.io/">IEX Cloud</a>, and with market data they provided us. Any opinions or assertions contained herein do not represent the opinions or beliefs of IEX Cloud, its third-party data providers, or any of its affiliates or employees.</p>
<h3 id="heading-you-can-watch-the-full-course-on-the-freecodecamporg-youtube-channelhttpswwwyoutubecomwatchvxfzgzb4hhee-4-hour-watch">📺 You can watch the full course on <a target="_blank" href="https://www.youtube.com/watch?v=xfzGZB4HhEE">the freeCodeCamp.org YouTube channel</a> (4-hour watch).</h3>
<p>And you can access the full open source course files, with both starter files and finished files, <a target="_blank" href="https://github.com/nickmccullum/algorithmic-trading-python">at this GitHub repository</a>. Happy coding.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is NFC? Near Field Communication Uses, Chips, Tags, and Readers Explained ]]>
                </title>
                <description>
                    <![CDATA[ NFC is everywhere these days. You've probably seen it in your phone settings, or heard about it online. While the use of NFC for things like contactless payments was growing steadily, it exploded early this year due to the Coronavirus pandemic. In th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-nfc-near-field-communication-uses-chips-tags-and-readers-explained/</link>
                <guid isPermaLink="false">66ac883f33a54a9b1a44793a</guid>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ fintech ]]>
                    </category>
                
                    <category>
                        <![CDATA[ payments ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kristofer Koishigawa ]]>
                </dc:creator>
                <pubDate>Tue, 03 Nov 2020 18:00:12 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9581740569d1a4ca0d5c.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>NFC is everywhere these days. You've probably seen it in your phone settings, or heard about it online.</p>
<p>While the use of NFC for things like contactless payments was growing steadily, it exploded early this year due to the Coronavirus pandemic.</p>
<p>In this article we'll go over what NFC is, what it's used for, some creative ways to use NFC, and more.</p>
<h2 id="heading-what-is-nfc-and-how-does-it-work">What is NFC and how does it work?</h2>
<p>NFC stands for near-field communication. It is a standard for devices to communicate with each other wirelessly from a very close distance.</p>
<p>NFC is a subset of another technology called RFID, so let's dig a bit into that before circling back to NFC.</p>
<h3 id="heading-what-is-rfid">What is RFID?</h3>
<p>Radio-frequency identification, or RFID, is a generic term for technologies that use radio waves from a reader to track specific tags. These tags all include an antenna and a tiny chip, and can come in many shapes and sizes. </p>
<p>Highway toll payment devices and those plastic things on clothes and other expensive items in stores are some common examples of RFID tags.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-123.png" alt="Image" width="600" height="400" loading="lazy">
<em>A diagram of an RFID tag. NFC tags look very similar – <a target="_blank" href="https://www.analogictips.com/rfid-tag-and-reader-antennas/">Source</a></em></p>
<p>If you've ever seen those big devices on either side of a store entrance, those are just big RFID readers. They're constantly transmitting radio waves and listening for a response.</p>
<p>So what happens if you try to leave a store and there's still a tag on the item you bought? </p>
<p>Most RFID tags are unpowered, so when the antenna in the tag picks up radio waves from the reader, it generates a small amount of electricity. That electricity activates the chip inside the tag, and it sends a signal with the information stored on the chip back to the reader. </p>
<p>In this case, when the reader receives a signal back from the tag on your item, it sounds an alarm.</p>
<h3 id="heading-how-are-rfid-and-nfc-related">How are RFID and NFC related?</h3>
<p>NFC is a newer, high-frequency version of RFID, and also involves both tags and readers. </p>
<p>NFC's higher frequency means that, while it can transfer data much faster than RFID, it only works from a distance of about 4 cm/1.6 in or less. Meanwhile, RFID works from a distance of up to 12 m/40 ft.</p>
<h2 id="heading-what-is-nfc-used-for">What is NFC used for?</h2>
<p>There are a lot of use cases for NFC, but here are some of the most common you'll see.</p>
<h3 id="heading-contactless-payments">Contactless payments</h3>
<p>These days, the most common thing that NFC is used for is contactless payment. Many newer credit and debit cards include an NFC tag, so you can just hold your card just above a payment terminal rather than swipe or insert it.</p>
<p>Contactless payment enabled credit and debit cards have a symbol on them similar to these:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-124.png" alt="Image" width="600" height="400" loading="lazy">
_Most contactless payment cards will have a similar symbol on the front or back – <a target="_blank" href="https://www.emvco.com/emv_insights_post/contactless-payments-how-emvco-supports-seamless-and-secure-acceptance/">Source</a>_</p>
<p>Most modern phones include an NFC chip, which can act as both an NFC reader/writer and tag. </p>
<p>This chip, paired with a mobile payment app like Google Pay, Apple Pay, and Samsung Pay, means that you might not even need to take your wallet out anymore. </p>
<p>Instead, your phone can act as a virtual NFC tag for your credit or debit card, even if said card doesn't have an actual NFC tag inside it.</p>
<p>Whether you use your contactless card or a mobile payment app, every payment you make involves tokenization for extra security.</p>
<p>Tokenization is when your card's information is used to generate a random, temporary token for each transaction. Then, your card or mobile payment app can send that temporary token safely, rather than transmit your actual card number, name, and other sensitive information.</p>
<p>However you choose to pay, using a contactless payment card, a mobile payment app, or inserting your card's chip are all <a target="_blank" href="https://www.engadget.com/2019-08-29-how-to-make-online-payments-safely-and-securely.html">much safer than the old method of swiping</a>.</p>
<h3 id="heading-interacting-with-products">Interacting with products</h3>
<p>Traditionally RFID is used for tracking inventory in warehouses and stores. But once a product leaves the store, its RFID tag is disabled.</p>
<p>A lot of products now include NFC tags for additional interaction after you leave the store. Nintendo's Amiibo figures are probably the most common recent example of this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/image-96.png" alt="Image" width="600" height="400" loading="lazy">
<em>If this isn't the cutest NFC tag, I don't know what is – <a target="_blank" href="https://www.nintendo.com/amiibo/detail/detective-pikachu-amiibo/">Source</a></em></p>
<p>When you scan an Amiibo figure with your Nintendo console, you can get special characters, items, or other additional content, depending on the game and figure you use.</p>
<p>Your Nintendo console can also write information back to the NFC tag in your figure, again, depending on the game and figure.</p>
<p>Other companies like Nike have been including NFC tags in things like sports jerseys and sneakers. This allows you to get personalized content based on the product you scan (recent scores for a team, stats for a specific player, and so on), or even check that a product is genuine.</p>
<h3 id="heading-data-transfer">Data transfer</h3>
<p>Unlike RFID, which is typically one-way communication between a reader and a tag, NFC allows for two-way communication.</p>
<p>Some phones are able to use NFC to transfer data like contacts or photos between two devices if you touch them together.</p>
<h2 id="heading-creative-uses-for-nfc">Creative uses for NFC</h2>
<p>One of the coolest things you can do with NFC is buy a pack of tags online and program them to do different things with your phone.</p>
<p>For example, if you're tired of always giving your WiFi password out to guests, you could program an NFC tag to automatically connect to your network. Then, all your guests need to do is make sure NFC is enabled and hold their phones near the tag.</p>
<p>You could also program NFC tags to control different smart devices around your house. You could have a tag that toggles a smart lamp on or off, or one that sets the thermostat. </p>
<p>The commands triggered by the NFC tags can also be personalized to specific devices. For example, if you like the room a bit cooler than your partner, when you scan the thermostat tag it can lower the temperature. But when your partner scans it, it could raise the temperature to their preferred setting.</p>
<p>There are a lot of other interesting ways to use NFC tags to make your life just a little bit easier. Check out this video for more ideas and to see how to program your own NFC tags in both iOS and Android:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/o9WHrX9cvXA" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-in-summary">In summary</h2>
<p>Though you might not have heard much about NFC until earlier this year (I certainly hadn't), it will likely become the standard we pay for things. </p>
<p>And considering all the cool stuff you can do with a phone and a pack of NFC tags, it's surprising that NFC isn't more widely adopted.</p>
<p>If you end up programming your own NFC tags, let me know what you did and how you did it over on <a target="_blank" href="https://twitter.com/kriskoishigawa">Twitter</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Real Work From Home Winner Is The Shareholder ]]>
                </title>
                <description>
                    <![CDATA[ By Adam Naor Today roughly eight million Americans work remotely full-time. And among the most commonly held jobs include many that leverage skills honed on freeCodeCamp. These jobs include web design, software engineering, product management, and wr... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-real-work-from-home-winner-is-the-shareholder/</link>
                <guid isPermaLink="false">66d45d7dcc7f04d2549a370c</guid>
                
                    <category>
                        <![CDATA[ Facebook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Math ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 16 Jun 2020 05:22:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/06/FN-AH983_FN_SHA_P_20190828113214-2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Adam Naor</p>
<p>Today roughly eight million Americans work remotely full-time. And among the most commonly held jobs include many that leverage skills honed on freeCodeCamp. These jobs include web design, software engineering, product management, and writing.</p>
<p>Firms are embracing the shift to hiring and empowering remote staff for many reasons. Some of the reasons frequently referenced include increased workforce productivity and access to new pools of talent.</p>
<p>One reason that is cited less frequently (but is seemingly as important) is that shifting to a remote labor force will significantly reduce a firm’s costs. Ultimately these cost savings will benefit shareholders. </p>
<p>I want to explain the cost structure that firms, and in particular technology companies, must manage. I absorbed these lessons by studying the financial documents and annual reports of companies that perhaps you aspire to work for or whose products you may use and enjoy.</p>
<p>I want to share these lessons with you.</p>
<p>First, some relevant financial context. All firms have essentially three large costs that they must manage: Property Plant and Equipment (PP&amp;E), operating expenses, and Selling, General and Administrative (SG&amp;A) expenses.</p>
<p>When a firm maintains an office (or famous large headquarters in the case of Google, Facebook, and Apple), it obviously must pay for the furniture, land, buildings, and machinery that help power its business. These fixed assets are expected to be used for at least one year and are classified as PP&amp;E on a firm’s balance sheet. </p>
<p>Operating expenses are a second category of cost that firms must manage. These costs include the utilities, insurance, taxes, and payroll that a firm pays to remain open. </p>
<p>Lastly, a company needs to budget for SG&amp;A expenses which are the sum of all direct or indirect selling expenses and general administrative expenses a firm accrues.</p>
<p>With this context in mind, we can view remote work - and the advocacy of remote work by CEOs - through a new financial light. </p>
<p>By placing workers in home offices (or remote co-working spaces) a firm can succeed in achieving two things in a single action: the firm can reduce its fixed and variable costs and move part of its cost structure from its balance sheet to that of its staff.</p>
<p>In short, companies won’t need to invest as much in buildings and equipment (i.e. lower CAPEX), which will lead directly to higher cash flow. This will lead to higher expected growth and higher stock prices over time. </p>
<p>Additionally, companies can decrease salaries and decrease corporate administrative costs, (i.e. lower SG&amp;A), which will lead to higher net income to equity holders.</p>
<p>Facebook provides evidence of this trend.</p>
<p>Recently Facebook Founder and CEO Mark Zuckerberg said that as much as 50% of Facebook’s workforce could be working remotely in the next five to ten years.</p>
<p>What data supports this policy?</p>
<p><img src="https://lh4.googleusercontent.com/gPJ3R8w_QkKdaECTszbseFJo6_HFnLtzDio6eYtkkQIA3UVy5zSP3FA4JYckbjTYBPnXPrp5HIkE2TcvLATKkRbgQuaucyGA9hbpsM4lo1F1xU6v9iK8Zdb12HPrqfoNorcUJaZL" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Firstly, look at the explosion of Facebook’s SG&amp;A costs in the last three years.</p>
<ul>
<li>In 2019 Facebook's annual SG&amp;A increased 80% from 2018.</li>
<li>In 2018 Facebook's annual SG&amp;A increased 56% from 2017.</li>
<li>In 2017 Facebook's annual SG&amp;A increased 32% from 2016.</li>
</ul>
<p>Next, look at Facebook’s increase in operating expenses.</p>
<ul>
<li>Facebook's annual operating expenses for 2019 increased 51.05% from 2018.</li>
<li>Facebook's annual operating expenses for 2018 increased 51.22% from 2017.</li>
<li>Facebook's annual operating expenses for 2017 increased 34% from 2016.</li>
</ul>
<p>Lastly, note that even as Facebook’s revenue has increased, the rate of growth is slowing.</p>
<ul>
<li>Facebook's annual revenue for 2019 increased by 27% from 2018.</li>
<li>Facebook's annual revenue for 2018 increased 37% from 2017.</li>
<li>Facebook's annual revenue for 2017 increased 47% from 2016.</li>
</ul>
<p>Facebook’s SG&amp;A and operating expenses are increasing faster than Facebook’s rate of revenue. </p>
<p>To increase profitability, Facebook will need to find ways to decrease its costs. It has a few obvious buckets to target and expanding its remote workforce can reduce PP&amp;E, SG&amp;A, and other operating costs in one fell swoop.</p>
<p>Let me explain how.</p>
<p>Remote workers will reduce Facebook’s dependency on furniture, land, and buildings. The decreased utilization of these fixed assets will lower Facebook's PP&amp;E. </p>
<p>Secondly, remote workers will decrease Facebook’s payroll. Why? Because Facebook can pay lower wages to workers outside of dense regions where the majority of their workers are today. Hiring talent outside of metropolitan areas will enable Facebook to pay wages indexed to local costs. </p>
<p>A software engineer in New Hampshire or Montana will cost Facebook less to employ than that same engineer located in New York City or the Bay Area. Zuckerberg explained that Facebook “will adjust salaries to your location...that means if you live in a location where the cost of living is dramatically lower, or the cost of labor is lower, then salaries do tend to be somewhat lower in those places.”</p>
<p>The reduction of costs can be extrapolated to SG&amp;A. Rent, utilities, and office supplies are three examples where Facebook can move costs from its balance sheet to that of its staff who will likely be expected, among other things, to heat and cool their home work environments, make their own coffee and food, or clean their home workspaces -  at their own expense.</p>
<p>This shift in cost structure will likely yield disproportionate benefits to shareholders because the earnings of a firm increase when, holding all else constant, costs decrease.</p>
<p>What do these changes mean for you? I have a few ideas.</p>
<p>Remote workers would be wise to ask for and negotiate new benefits packages. Subsidized wifi or utilities seem like reasonable things to ask for if you no longer have an office to work from. Discounted home office products - a chair, desk, light, keyboard, monitor  - should be included as non-taxed items when joining in a remote role. Access to virtual mentoring or mental health tools can be requested as core perks to ensure that you are growing and healthy while performing remote work.</p>
<p>As remote work becomes more prevalent - for full time remote workers and employees who blend their time between workplaces - new paradigms of work will arise. With this fundamental shift in the labor markets, firms will have a unique opportunity to reduce costs. How and where their expenses are cut will dictate the rate at which earnings can increase. </p>
<p>It seems to reason that shareholders will benefit from enhanced profitability coming from these changes. But remote engineers, designers, product managers, and sales professionals can benefit too. By asking for new and specific perks that empower remote work, these workers might see more of the upside derived from this shift in the labor market.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create Auto-Updating Excel Spreadsheets of Stock Market Data with Python, AWS, and IEX Cloud ]]>
                </title>
                <description>
                    <![CDATA[ By Nick McCullum Many Python developers in the financial world are tasked with creating Excel documents for analysis by non-technical users. This is actually a lot harder than it sounds. From sourcing the data to formatting the spreadsheet to deployi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/auto-updating-excel-python-aws/</link>
                <guid isPermaLink="false">66d46042246e57ac83a2c7a0</guid>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 23 Apr 2020 16:24:34 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9b81740569d1a4ca2c32.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Nick McCullum</p>
<p>Many Python developers in the financial world are tasked with creating Excel documents for analysis by non-technical users.</p>
<p>This is actually a lot harder than it sounds. From sourcing the data to formatting the spreadsheet to deploying the final doc in a central location, there are plenty of steps involved in the process.</p>
<p>In this tutorial, I'm going to show you how to create Excel spreadsheets using Python that:</p>
<ul>
<li>Use stock market data from IEX Cloud</li>
<li>Are deployed in a centralized S3 bucket so that anyone with the right URL can access them</li>
<li>Automatically update daily using the <code>cron</code> command line utility</li>
</ul>
<h2 id="heading-step-1-create-an-account-with-iex-cloud">Step 1: Create an Account with IEX Cloud</h2>
<p><a target="_blank" href="https://iexcloud.io/">IEX Cloud</a> is the data provider subsidiary of the <a target="_blank" href="https://iextrading.com/">IEX stock exchange</a>. </p>
<p>In case you're unfamiliar with IEX, it is an acronym for "The Investor's Exchange". IEX was founded by Brad Katsuyama to build a better stock exchange that avoids investor-unfriendly behavior like front-running and high-frequency trading. Katsuyama's exploits were famously chronicled in Michael Lewis' best-selling book <a target="_blank" href="https://en.wikipedia.org/wiki/Flash_Boys">Flash Boys</a>.</p>
<p>I have investigated many financial data providers and IEX Cloud has the best combination of:</p>
<ul>
<li>High-quality data</li>
<li>Affordable price</li>
</ul>
<p>Their prices are below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-20-at-7.07.13-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The $9/month <strong>Launch</strong> plan is plenty for many use cases.</p>
<p><strong>A warning on using IEX Cloud (and any other pay-per-use data provider):</strong> it is very important that you set usage budgets from the beginning. These budgets lock you out of your account once you hit a certain dollar cost for the month.</p>
<p>When I first started using IEX Cloud, I accidentally created an infinite loop on a Friday afternoon that contained an API call to IEX Cloud. These API calls are priced on a cost-per-call basis...which resulted in a terrifying email from IEX:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-20-at-7.09.47-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>It is a testament to IEX's customer-centricity that they agreed to reset my usage as long as I set usage budgets moving forward. Go IEX!</p>
<p>As with most API subscriptions, the main benefit of creating an IEX Cloud account is having an API key. </p>
<p>For obvious reasons, I will not share an API key in this article. </p>
<p>However, you can still work through this tutorial with your own API key as long as you assign it to the following variable name:</p>
<pre><code>IEX_API_Key
</code></pre><p>You will see the blank <code>IEX_API_Key</code> variable in my code blocks throughout the rest of this tutorial.</p>
<h2 id="heading-step-2-write-your-python-script">Step 2: Write Your Python Script</h2>
<p>Now that you have access to the API key that you'll need to gather financial data, it's time to write your Python script. </p>
<p>This will be the longest section of this tutorial. It is also the most flexible - we are going to create a Python script that satisfies certain pre-specified criteria, but you could modify this section to really create any spreadsheet you want!</p>
<p>To start, let's lay out our goal posts. We are going to write a Python script that generates an Excel file of stock market data with the following characteristics:</p>
<ul>
<li>It will include the 10 largest stocks in the United States</li>
<li>It will contain four columns: stock ticker, company name, share price, and dividend yield.</li>
<li>It will be formatted such that the header's background color is <code>#135485</code> and text is white, while the spreadsheet body's background is <code>#DADADA</code> and the font color is black (the default).</li>
</ul>
<p>Let's start by importing our first package. </p>
<p>Since spreadsheets are essentially just data structures with rows and columns, then the <code>pandas</code> library - including its built-in <code>DataFrame</code> object - is a perfect candidate for manipulating data in this tutorial. </p>
<p>We'll start by importing <code>pandas</code> under the alias <code>pd</code> like this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
</code></pre>
<p>Next, we'll specify our IEX Cloud API key. As I mentioned before, I'm not going to really include my API key, so you'll have to grab your own API key from your IEX account and include it here:</p>
<pre><code class="lang-python">IEX_API_Key = <span class="hljs-string">''</span>
</code></pre>
<p>Our next step is to determine the ten largest companies in the United States. </p>
<p>You can answer this question with a quick Google search. </p>
<p>For brevity, I have included the companies (or rather, their stock tickers) in the following Python list:</p>
<pre><code class="lang-python">tickers = [
            <span class="hljs-string">'MSFT'</span>,
            <span class="hljs-string">'AAPL'</span>,
            <span class="hljs-string">'AMZN'</span>,
            <span class="hljs-string">'GOOG'</span>,
            <span class="hljs-string">'FB'</span>,
            <span class="hljs-string">'BRK.B'</span>,
            <span class="hljs-string">'JNJ'</span>,
            <span class="hljs-string">'WMT'</span>,
            <span class="hljs-string">'V'</span>,
            <span class="hljs-string">'PG'</span>
            ]
</code></pre>
<p>Next, it is time to figure out how to ping the IEX Cloud API to pull in the metrics we need for each company. </p>
<p>The IEX Cloud API returns JSON objects in response to HTTP requests. Since we are working with more than 1 ticker in this tutorial, we will use IEX Cloud's batch API call functionality, which allows you to request data on more than one ticker at a time. Using batch API calls has two benefits:</p>
<ul>
<li>It reduces the number of HTTP requests you need to make, which will make your code more performant.</li>
<li>The pricing for batch API calls is slightly better with most data providers.</li>
</ul>
<p>Here is an example of what the HTTP request might look like, with a few placeholder words where we'll need to customize the request:</p>
<pre><code>https:<span class="hljs-comment">//cloud.iexapis.com/stable/stock/market/batch?symbols=TICKERS&amp;types=ENDPOINTS&amp;range=RANGE&amp;token=IEX_API_Key</span>
</code></pre><p>In this URL, we'll replace these variables with the following values:</p>
<ul>
<li><code>TICKERS</code> will be replaced by a string that contains each of our tickers separated by a comma.</li>
<li><code>ENDPOINTS</code> will be replaced by a string that contains each of the IEX Cloud endpoints we want to hit, separated by a comma.</li>
<li><code>RANGE</code> will be replaced by <code>1y</code>. These endpoints each contain point-in-time data and not time series data, so this range can really be whatever you want.</li>
</ul>
<p>Let's put this URL into a variable called <code>HTTP_request</code> for us to modify later:</p>
<pre><code class="lang-python">HTTP_request = <span class="hljs-string">'https://cloud.iexapis.com/stable/stock/market/batch?symbols=TICKERS&amp;types=ENDPOINTS&amp;range=RANGE&amp;token=IEX_API_Key'</span>
</code></pre>
<p>Let's work through each of these variables one-by-one to determine the exact URL that we need to hit.</p>
<p>For the <code>TICKERS</code> variable, we can generate a real Python variable (and not just a placeholder word) with a simple <code>for</code> loop:</p>
<pre><code class="lang-python"><span class="hljs-comment">#Create an empty string called `ticker_string` that we'll add tickers and commas to</span>
ticker_string = <span class="hljs-string">''</span>

<span class="hljs-comment">#Loop through every element of `tickers` and add them and a comma to ticker_string</span>
<span class="hljs-keyword">for</span> ticker <span class="hljs-keyword">in</span> tickers:
    ticker_string += ticker
    ticker_string += <span class="hljs-string">','</span>

<span class="hljs-comment">#Drop the last comma from `ticker_string`</span>
ticker_string = ticker_string[:<span class="hljs-number">-1</span>]
</code></pre>
<p>Now we can interpolate our <code>ticker_string</code> variable into the <code>HTTP_request</code> variable that we created earlier using an f-string:</p>
<pre><code class="lang-python">HTTP_request = <span class="hljs-string">f'https://cloud.iexapis.com/stable/stock/market/batch?symbols=<span class="hljs-subst">{ticker_string}</span>&amp;types=ENDPOINTS&amp;range=RANGE&amp;token=IEX_API_Key'</span>
</code></pre>
<p>Next, we need to determine which IEX Cloud endpoints we need to ping. </p>
<p>Some quick investigation into the IEX Cloud documentation reveals that we only need the <code>price</code> and <code>stats</code> endpoints to create our spreadsheet. </p>
<p>Thus, we can replace the placeholder <code>ENDPOINTS</code> word from our original HTTP request with the following variable:</p>
<pre><code class="lang-python">endpoints = <span class="hljs-string">'price,stats'</span>
</code></pre>
<p>Like we did with our <code>ticker_string</code> variable, let's substitute the <code>endpoints</code> variable into the <code>ticker_string</code> variable:</p>
<pre><code class="lang-python">HTTP_request = <span class="hljs-string">f'https://cloud.iexapis.com/stable/stock/market/batch?symbols=<span class="hljs-subst">{ticker_string}</span>&amp;types=<span class="hljs-subst">{endpoints}</span>&amp;range=RANGE&amp;token=IEX_API_Key'</span>
</code></pre>
<p>The last placeholder we need to replace is <code>RANGE</code>. We will not replace with this a variable. Instead, we can hardcode a <code>1y</code> directly into the URL path like this:</p>
<pre><code>https:<span class="hljs-comment">//cloud.iexapis.com/stable/stock/market/batch?symbols={ticker_string}&amp;types={endpoints}&amp;range=1y&amp;token=IEX_API_Key</span>
</code></pre><p>We've done a lot so far, so let's recap our code base:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

IEX_API_Key = <span class="hljs-string">''</span>

<span class="hljs-comment">#Specify the stock tickers that will be included in our spreadsheet</span>
tickers = [
            <span class="hljs-string">'MSFT'</span>,
            <span class="hljs-string">'AAPL'</span>,
            <span class="hljs-string">'AMZN'</span>,
            <span class="hljs-string">'GOOG'</span>,
            <span class="hljs-string">'FB'</span>,
            <span class="hljs-string">'BRK.B'</span>,
            <span class="hljs-string">'JNJ'</span>,
            <span class="hljs-string">'WMT'</span>,
            <span class="hljs-string">'V'</span>,
            <span class="hljs-string">'PG'</span>
            ]


<span class="hljs-comment">#Create an empty string called `ticker_string` that we'll add tickers and commas to</span>
ticker_string = <span class="hljs-string">''</span>

<span class="hljs-comment">#Loop through every element of `tickers` and add them and a comma to ticker_string</span>
<span class="hljs-keyword">for</span> ticker <span class="hljs-keyword">in</span> tickers:
    ticker_string += ticker
    ticker_string += <span class="hljs-string">','</span>

<span class="hljs-comment">#Drop the last comma from `ticker_string`</span>
ticker_string = ticker_string[:<span class="hljs-number">-1</span>]

<span class="hljs-comment">#Create the endpoint strings</span>
endpoints = <span class="hljs-string">'price,stats'</span>

<span class="hljs-comment">#Interpolate the endpoint strings into the HTTP_request string</span>
HTTP_request = <span class="hljs-string">f'https://cloud.iexapis.com/stable/stock/market/batch?symbols=<span class="hljs-subst">{ticker_string}</span>&amp;types=<span class="hljs-subst">{endpoints}</span>&amp;range=1y&amp;token=<span class="hljs-subst">{IEX_API_Key}</span>'</span>
</code></pre>
<p>It is now time to ping the API and save its data into a data structure within our Python application. </p>
<p>We can read  JSON objects with pandas' <code>read_json</code> method. In our case, we'll save the JSON data to a <code>pandas DataFrame</code> called <code>raw_data</code>, like this:</p>
<pre><code class="lang-python">raw_data = pd.read_json(HTTP_request)
</code></pre>
<p>Let's take a moment now to make sure that the data has been imported in a nice format for our application. </p>
<p>If you're working through this tutorial in a <a target="_blank" href="https://jupyter.org/">Jupyter Notebook</a>, you can simply type the name of the <code>pandas DataFrame</code> variable on the last line of a code cell, and Jupyter will nicely render an image of the data, like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-21-at-9.54.20-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see, the <code>pandas DataFrame</code> contains a column for each stock ticker and two rows: one for the <code>stats</code> endpoint and one for the <code>price</code> endpoint. We will need to parse this DataFrame to get the four metrics we want. Let's work through the metrics one-by-one in the steps below.</p>
<h3 id="heading-metric-1-stock-ticker">Metric 1: Stock Ticker</h3>
<p>This step is very straightforward since the stock tickers are contained in the columns of the <code>pandas DataFrame</code>. We can access them through the <code>columns</code> attribute of the <code>pandas DataFrame</code> like this:</p>
<pre><code class="lang-python">raw_data.columns
</code></pre>
<p>To access the other metrics in <code>raw_data</code>, we will create a <code>for</code> loop that loops through each ticker in <code>raw_data.columns</code>. In each iteration of the loop we will add the data to a new <code>pandas DataFrame</code> object called <code>output_data</code>.</p>
<p>First we'll need to create <code>output_data</code>, which should be an empty <code>pandas DataFrame</code> with four columns. Here's how to do this:</p>
<pre><code class="lang-python">output_data = pd.DataFrame(pd.np.empty((<span class="hljs-number">0</span>,<span class="hljs-number">4</span>)))
</code></pre>
<p>This creates an empty <code>pandas DataFrame</code> with 0 rows and 4 columns.</p>
<p>Now that this object has been created, here's how we can structure this <code>for</code> loop:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> ticker <span class="hljs-keyword">in</span> raw_data.columns:

    <span class="hljs-comment">#Parse the company's name - not completed yet</span>
    company_name = <span class="hljs-string">''</span>

    <span class="hljs-comment">#Parse the company's stock price - not completed yet</span>
    stock_price = <span class="hljs-number">0</span>

    <span class="hljs-comment">#Parse the company's dividend yield - not completed yet</span>
    dividend_yield = <span class="hljs-number">0</span>


    new_column = pd.Series([ticker, company_name, stock_price, dividend_yield])
    output_data = output_data.append(new_column, ignore_index = <span class="hljs-literal">True</span>)
</code></pre>
<p>Next, let's determine how to parse the <code>company_name</code> variable from the <code>raw_data</code> object.</p>
<h3 id="heading-metric-2-company-name">Metric 2: Company Name</h3>
<p>The <code>company_name</code> variable is the first variable will need to be parsed from the <code>raw_data</code> object. As a quick recap, here's what <code>raw_data</code> looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-21-at-10.02.45-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The <code>company_name</code> variable is held within the <code>stats</code> endpoint under the dictionary key <code>companyName</code>. To parse this data point out of <code>raw_data</code>, we can use these indexes:</p>
<pre><code class="lang-python">raw_data[ticker][<span class="hljs-string">'stats'</span>][<span class="hljs-string">'companyName'</span>]
</code></pre>
<p>Including this in our <code>for</code> loop from before gives this:</p>
<pre><code class="lang-python">output_data = pd.DataFrame(pd.np.empty((<span class="hljs-number">0</span>,<span class="hljs-number">4</span>)))

<span class="hljs-keyword">for</span> ticker <span class="hljs-keyword">in</span> raw_data.columns:

    <span class="hljs-comment">#Parse the company's name - not completed yet</span>
    company_name = raw_data[ticker][<span class="hljs-string">'stats'</span>][<span class="hljs-string">'companyName'</span>]

    <span class="hljs-comment">#Parse the company's stock price - not completed yet</span>
    stock_price = <span class="hljs-number">0</span>

    <span class="hljs-comment">#Parse the company's dividend yield - not completed yet</span>
    dividend_yield = <span class="hljs-number">0</span>


    new_column = pd.Series([ticker, company_name, stock_price, dividend_yield])
    output_data = output_data.append(new_column, ignore_index = <span class="hljs-literal">True</span>)
</code></pre>
<p>Let's move on to parsing <code>stock_price</code>.</p>
<h3 id="heading-metric-3-stock-price">Metric 3: Stock Price</h3>
<p>The <code>stock_price</code> variable is contained within the <code>price</code> endpoint, which returns only a single value. This means we do not need to chain together indexes like we did with <code>company_name</code>. </p>
<p>Here's how we could parse <code>stock_price</code> from <code>raw_data</code>:</p>
<pre><code class="lang-python">raw_data[ticker][<span class="hljs-string">'price'</span>]
</code></pre>
<p>Including this in our <code>for</code> loop gives us:</p>
<pre><code class="lang-python">output_data = pd.DataFrame(pd.np.empty((<span class="hljs-number">0</span>,<span class="hljs-number">4</span>)))

<span class="hljs-keyword">for</span> ticker <span class="hljs-keyword">in</span> raw_data.columns:

    <span class="hljs-comment">#Parse the company's name - not completed yet</span>
    company_name = raw_data[ticker][<span class="hljs-string">'stats'</span>][<span class="hljs-string">'companyName'</span>]

    <span class="hljs-comment">#Parse the company's stock price - not completed yet</span>
    stock_price = raw_data[ticker][<span class="hljs-string">'price'</span>]

    <span class="hljs-comment">#Parse the company's dividend yield - not completed yet</span>
    dividend_yield = <span class="hljs-number">0</span>


    new_column = pd.Series([ticker, company_name, stock_price, dividend_yield])
    output_data = output_data.append(new_column, ignore_index = <span class="hljs-literal">True</span>)
</code></pre>
<p>The last metric we need to parse is <code>dividend_yield</code>.</p>
<h3 id="heading-metric-4-dividend-yield">Metric 4: Dividend Yield</h3>
<p>Like <code>company_name</code>, <code>dividend_yield</code> is contained in the <code>stats</code> endpoint. It is held under the <code>dividendYield</code> dictionary key. </p>
<p>Here is how we could parse it out of <code>raw_data</code>:</p>
<pre><code class="lang-python">raw_data[ticker][<span class="hljs-string">'stats'</span>][<span class="hljs-string">'dividendYield'</span>]
</code></pre>
<p>Adding this to our <code>for</code> loop gives us:</p>
<pre><code class="lang-python">output_data = pd.DataFrame(pd.np.empty((<span class="hljs-number">0</span>,<span class="hljs-number">4</span>)))

<span class="hljs-keyword">for</span> ticker <span class="hljs-keyword">in</span> raw_data.columns:

    <span class="hljs-comment">#Parse the company's name - not completed yet</span>
    company_name = raw_data[ticker][<span class="hljs-string">'stats'</span>][<span class="hljs-string">'companyName'</span>]

    <span class="hljs-comment">#Parse the company's stock price - not completed yet</span>
    stock_price = raw_data[ticker][<span class="hljs-string">'price'</span>]

    <span class="hljs-comment">#Parse the company's dividend yield - not completed yet</span>
    dividend_yield = raw_data[ticker][<span class="hljs-string">'stats'</span>][<span class="hljs-string">'dividendYield'</span>]


    new_column = pd.Series([ticker, company_name, stock_price, dividend_yield])
    output_data = output_data.append(new_column, ignore_index = <span class="hljs-literal">True</span>)
</code></pre>
<p>Let's print out our <code>output_data</code> object to see what the data looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-21-at-10.11.39-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>So far so good! The next two steps are to name the columns of the <code>pandas DataFrame</code> and to change its index.</p>
<h3 id="heading-how-to-name-the-columns-of-a-pandas-dataframe">How to Name the Columns of a Pandas DataFrame</h3>
<p>We can update the column names of our <code>output_data</code> object by creating a list of column names and assigning it to the <code>output_data.columns</code> attribute, like this:</p>
<pre><code class="lang-python">output_data.columns = [<span class="hljs-string">'Ticker'</span>, <span class="hljs-string">'Company Name'</span>, <span class="hljs-string">'Stock Price'</span>, <span class="hljs-string">'Dividend Yield'</span>]
</code></pre>
<p>Let's print out our <code>output_data</code> object to see what the data looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-21-at-10.15.11-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Much better! Let's change the index of <code>output_data</code> next.</p>
<h3 id="heading-how-to-change-the-index-of-a-pandas-dataframe">How to Change the Index of a Pandas DataFrame</h3>
<p>The index of a <code>pandas DataFrame</code> is a special column that is somewhat similar to the primary key of a SQL database table. In our <code>output_data</code> object, we want to set the <code>Ticker</code> column as the <code>DataFrame</code>'s index.</p>
<p>Here's how we can do this using the <code>set_index</code> method:</p>
<pre><code class="lang-python">output_data.set_index(<span class="hljs-string">'Ticker'</span>, inplace=<span class="hljs-literal">True</span>)
</code></pre>
<p>Let's print out our <code>output_data</code> object to see what the data looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-21-at-10.17.47-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Another incremental improvement!</p>
<p>Next, let's deal with the missing data in <code>output_data</code>.</p>
<h3 id="heading-how-to-handle-missing-data-in-pandas-dataframes">How to Handle Missing Data in Pandas DataFrames</h3>
<p>If you take a close look at <code>output_data</code>, you will notice that there are several <code>None</code> values in the <code>Dividend Yield</code> column:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-21-at-10.17.47-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>These <code>None</code> values simply indicate that the company for that row does not currently pay a dividend. While <code>None</code> is one way of representing a non-dividend stock, it is more common to show a <code>Dividend Yield</code> of <code>0</code>.</p>
<p>Fortunately, the fix for this is quite straightforward. The <code>pandas</code> library includes an excellent <code>fillna</code> method that allows us to replace missing values in a <code>pandas DataFrame</code>.</p>
<p>Here's how we can use the <code>fillna</code> method to replace our <code>Dividend Yield</code> column's <code>None</code> values with <code>0</code>:</p>
<pre><code class="lang-python">output_data[<span class="hljs-string">'Dividend Yield'</span>].fillna(<span class="hljs-number">0</span>,inplace=<span class="hljs-literal">True</span>)
</code></pre>
<p>The <code>output_data</code> object looks much cleaner now:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-21-at-10.25.03-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We are now ready to export our DataFrame to an Excel document! As a quick recap, here is our Python script to date:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

IEX_API_Key = <span class="hljs-string">''</span>

<span class="hljs-comment">#Specify the stock tickers that will be included in our spreadsheet</span>
tickers = [
            <span class="hljs-string">'MSFT'</span>,
            <span class="hljs-string">'AAPL'</span>,
            <span class="hljs-string">'AMZN'</span>,
            <span class="hljs-string">'GOOG'</span>,
            <span class="hljs-string">'FB'</span>,
            <span class="hljs-string">'BRK.B'</span>,
            <span class="hljs-string">'JNJ'</span>,
            <span class="hljs-string">'WMT'</span>,
            <span class="hljs-string">'V'</span>,
            <span class="hljs-string">'PG'</span>
            ]


<span class="hljs-comment">#Create an empty string called `ticker_string` that we'll add tickers and commas to</span>
ticker_string = <span class="hljs-string">''</span>

<span class="hljs-comment">#Loop through every element of `tickers` and add them and a comma to ticker_string</span>
<span class="hljs-keyword">for</span> ticker <span class="hljs-keyword">in</span> tickers:
    ticker_string += ticker
    ticker_string += <span class="hljs-string">','</span>

<span class="hljs-comment">#Drop the last comma from `ticker_string`</span>
ticker_string = ticker_string[:<span class="hljs-number">-1</span>]

<span class="hljs-comment">#Create the endpoint strings</span>
endpoints = <span class="hljs-string">'price,stats'</span>

<span class="hljs-comment">#Interpolate the endpoint strings into the HTTP_request string</span>
HTTP_request = <span class="hljs-string">f'https://cloud.iexapis.com/stable/stock/market/batch?symbols=<span class="hljs-subst">{ticker_string}</span>&amp;types=<span class="hljs-subst">{endpoints}</span>&amp;range=1y&amp;token=<span class="hljs-subst">{IEX_API_Key}</span>'</span>

<span class="hljs-comment">#Create an empty pandas DataFrame to append our parsed values into during our for loop</span>
output_data = pd.DataFrame(pd.np.empty((<span class="hljs-number">0</span>,<span class="hljs-number">4</span>)))

<span class="hljs-keyword">for</span> ticker <span class="hljs-keyword">in</span> raw_data.columns:

    <span class="hljs-comment">#Parse the company's name</span>
    company_name = raw_data[ticker][<span class="hljs-string">'stats'</span>][<span class="hljs-string">'companyName'</span>]

    <span class="hljs-comment">#Parse the company's stock price</span>
    stock_price = raw_data[ticker][<span class="hljs-string">'price'</span>]

    <span class="hljs-comment">#Parse the company's dividend yield</span>
    dividend_yield = raw_data[ticker][<span class="hljs-string">'stats'</span>][<span class="hljs-string">'dividendYield'</span>]


    new_column = pd.Series([ticker, company_name, stock_price, dividend_yield])
    output_data = output_data.append(new_column, ignore_index = <span class="hljs-literal">True</span>)

<span class="hljs-comment">#Change the column names of output_data</span>
output_data.columns = [<span class="hljs-string">'Ticker'</span>, <span class="hljs-string">'Company Name'</span>, <span class="hljs-string">'Stock Price'</span>, <span class="hljs-string">'Dividend Yield'</span>]

<span class="hljs-comment">#Change the index of output_data</span>
output_data.set_index(<span class="hljs-string">'Ticker'</span>, inplace=<span class="hljs-literal">True</span>)

<span class="hljs-comment">#Replace the missing values of the 'Dividend Yield' column with 0</span>
output_data[<span class="hljs-string">'Dividend Yield'</span>].fillna(<span class="hljs-number">0</span>,inplace=<span class="hljs-literal">True</span>)

<span class="hljs-comment">#Print the DataFrame</span>
output_data
</code></pre>
<h3 id="heading-how-to-export-a-styled-excel-document-from-a-pandas-dataframe-using-xlsxwriter">How to Export A Styled Excel Document From a Pandas DataFrame using XlsxWriter</h3>
<p>There are multiple ways to export an <code>xlsx</code> file from a <code>pandas DataFrame</code>. </p>
<p>The easiest way is to use the built-in function <code>to_excel</code>. As an example, here's how we could export <code>output_data</code> to an Excel file:</p>
<pre><code class="lang-python">output_data.to_excel(<span class="hljs-string">'my_excel_document.xlsx)</span>
</code></pre>
<p>The problem with this approach is that the Excel file has no format whatsoever. The output looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-21-at-10.33.59-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The lack of formatting in this document makes it hard to interpret.</p>
<p>What is the solution?</p>
<p>We can use the Python package <code>XlsxWriter</code> to generate nicely-formatted Excel files. To start, we'll want to add the following import to the beginning of our Python script:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> xlsxwriter
</code></pre>
<p>Next, we need to create our actual Excel file. The XlsxWriter package actually has a dedicated documentation page for how to work with <code>pandas DataFrames</code>, which is available <a target="_blank" href="https://xlsxwriter.readthedocs.io/working_with_pandas.html">here</a>. </p>
<p>Our first step is to call the <code>pd.ExcelWriter</code> function and pass in the desired name of our <code>xlsx</code> file as the first argument and <code>engine='xlsxwriter</code> as the second argument. We will assign this to a variable called <code>writer</code>:</p>
<pre><code class="lang-python">writer = pd.ExcelWriter(<span class="hljs-string">'stock_market_data.xlsx'</span>, engine=<span class="hljs-string">'xlsxwriter'</span>)
</code></pre>
<p>From there, we need to call the <code>to_excel</code> method on our <code>pandas DataFrame</code>. This time, instead of passing in the name of the file that we're trying to export, we'll pass in the <code>writer</code> object that we just created:</p>
<pre><code class="lang-python">output_data.to_excel(writer, sheet_name=<span class="hljs-string">'Sheet1'</span>)
</code></pre>
<p>Lastly, we will call the <code>save</code> method on our <code>writer</code> object, which saves the <code>xlsx</code> file to our current working directory. When all this is done, here is the section of our Python script that saves <code>output_data</code> to an Excel file.</p>
<pre><code class="lang-python">writer = pd.ExcelWriter(<span class="hljs-string">'stock_market_data.xlsx'</span>, engine=<span class="hljs-string">'xlsxwriter'</span>)

output_data.to_excel(writer, sheet_name=<span class="hljs-string">'Sheet1'</span>)

writer.save()
</code></pre>
<p>All of the formatting code that we will include in our <code>xlsx</code> file needs to be contained between the creation of the <code>ExcelWriter</code> object and the <code>writer.save()</code> statement.</p>
<h3 id="heading-how-to-style-an-xlsx-file-created-with-python">How to Style an <code>xlsx</code> File Created with Python</h3>
<p>It is actually harder than you might think to style an Excel file using Python. </p>
<p>This is partially because of some of the limitations of the XlsxWriter package. Its documentation states: </p>
<blockquote>
<p><em>'XlsxWriter and Pandas provide very little support for formatting the output data from a dataframe apart from default formatting such as the header and index cells and any cells that contain dates or datetimes. In addition it isn’t possible to format any cells that already have a default format applied.</em></p>
<p><em>If you require very controlled formatting of the dataframe output then you would probably be better off using Xlsxwriter directly with raw data taken from Pandas. However, some formatting options are available.'</em></p>
</blockquote>
<p>In my experience, the most flexible way to style cells in an <code>xlsx</code> file created by XlsxWriter is to use conditional formatting that only applies styling when a cell is not equal to <code>None</code>. </p>
<p>This has three advantages:</p>
<ol>
<li>It provides more styling flexibility than the normal formatting options available in XlsxWriter.</li>
<li>You do not need to manually loop through each data point and import them into the <code>writer</code> object one-by-one.</li>
<li>It allows you to easily see when <code>None</code> values have made their way into your finalized <code>xlsx</code> files, since they'll be missing the required formatting.</li>
</ol>
<p>To apply styling using conditional formatting, we first need to create a few style templates. Specifically, we will need four templates:</p>
<ul>
<li>One <code>header_template</code> that will be applied to the column names at the top of the spreadsheet</li>
<li>One <code>string_template</code> that will be applied to the <code>Ticker</code> and <code>Company Name</code> columns</li>
<li>One <code>dollar_template</code> that will be applied to the <code>Stock Price</code> column</li>
<li>One <code>percent_template</code> that will be applied to the <code>Dividend Yield</code> column</li>
</ul>
<p>Each of these format templates need to be added to the <code>writer</code> object in dictionaries that resemble CSS syntax. Here's what I mean:</p>
<pre><code class="lang-python">header_template = writer.book.add_format(
        {
            <span class="hljs-string">'font_color'</span>: <span class="hljs-string">'#ffffff'</span>,
            <span class="hljs-string">'bg_color'</span>: <span class="hljs-string">'#135485'</span>,
            <span class="hljs-string">'border'</span>: <span class="hljs-number">1</span>
        }
    )

string_template = writer.book.add_format(
        {
            <span class="hljs-string">'bg_color'</span>: <span class="hljs-string">'#DADADA'</span>,
            <span class="hljs-string">'border'</span>: <span class="hljs-number">1</span>
        }
    )

dollar_template = writer.book.add_format(
        {
            <span class="hljs-string">'num_format'</span>:<span class="hljs-string">'$0.00'</span>,
            <span class="hljs-string">'bg_color'</span>: <span class="hljs-string">'#DADADA'</span>,
            <span class="hljs-string">'border'</span>: <span class="hljs-number">1</span>
        }
    )

percent_template = writer.book.add_format(
        {
            <span class="hljs-string">'num_format'</span>:<span class="hljs-string">'0.0%'</span>,
            <span class="hljs-string">'bg_color'</span>: <span class="hljs-string">'#DADADA'</span>,
            <span class="hljs-string">'border'</span>: <span class="hljs-number">1</span>
        }
    )
</code></pre>
<p>To apply these formats to specific cells in our <code>xlsx</code> file, we need to call the package's <code>conditional_format</code> method on  <code>writer.sheets['Stock Market Data']</code>. Here is an example:</p>
<pre><code class="lang-python">writer.sheets[<span class="hljs-string">'Stock Market Data'</span>].conditional_format(<span class="hljs-string">'A2:B11'</span>, 
                             {
                                <span class="hljs-string">'type'</span>:     <span class="hljs-string">'cell'</span>,
                                <span class="hljs-string">'criteria'</span>: <span class="hljs-string">'&lt;&gt;'</span>,
                                <span class="hljs-string">'value'</span>:    <span class="hljs-string">'"None"'</span>,
                                <span class="hljs-string">'format'</span>:   string_template
                                }
                            )
</code></pre>
<p>If we generalize this formatting to the other three formats we're applying, here's what the formatting section of our Python script becomes:</p>
<pre><code class="lang-python">writer = pd.ExcelWriter(<span class="hljs-string">'stock_market_data.xlsx'</span>, engine=<span class="hljs-string">'xlsxwriter'</span>)

output_data.to_excel(writer, sheet_name=<span class="hljs-string">'Stock Market Data'</span>)

header_template = writer.book.add_format(
        {
            <span class="hljs-string">'font_color'</span>: <span class="hljs-string">'#ffffff'</span>,
            <span class="hljs-string">'bg_color'</span>: <span class="hljs-string">'#135485'</span>,
            <span class="hljs-string">'border'</span>: <span class="hljs-number">1</span>
        }
    )

string_template = writer.book.add_format(
        {
            <span class="hljs-string">'bg_color'</span>: <span class="hljs-string">'#DADADA'</span>,
            <span class="hljs-string">'border'</span>: <span class="hljs-number">1</span>
        }
    )

dollar_template = writer.book.add_format(
        {
            <span class="hljs-string">'num_format'</span>:<span class="hljs-string">'$0.00'</span>,
            <span class="hljs-string">'bg_color'</span>: <span class="hljs-string">'#DADADA'</span>,
            <span class="hljs-string">'border'</span>: <span class="hljs-number">1</span>
        }
    )

percent_template = writer.book.add_format(
        {
            <span class="hljs-string">'num_format'</span>:<span class="hljs-string">'0.0%'</span>,
            <span class="hljs-string">'bg_color'</span>: <span class="hljs-string">'#DADADA'</span>,
            <span class="hljs-string">'border'</span>: <span class="hljs-number">1</span>
        }
    )


<span class="hljs-comment">#Format the header of the spreadsheet</span>
writer.sheets[<span class="hljs-string">'Stock Market Data'</span>].conditional_format(<span class="hljs-string">'A1:D1'</span>, 
                             {
                                <span class="hljs-string">'type'</span>:     <span class="hljs-string">'cell'</span>,
                                <span class="hljs-string">'criteria'</span>: <span class="hljs-string">'&lt;&gt;'</span>,
                                <span class="hljs-string">'value'</span>:    <span class="hljs-string">'"None"'</span>,
                                <span class="hljs-string">'format'</span>:   header_template
                                }
                            )

<span class="hljs-comment">#Format the 'Ticker' and 'Company Name' columns</span>
writer.sheets[<span class="hljs-string">'Stock Market Data'</span>].conditional_format(<span class="hljs-string">'A2:B11'</span>, 
                             {
                                <span class="hljs-string">'type'</span>:     <span class="hljs-string">'cell'</span>,
                                <span class="hljs-string">'criteria'</span>: <span class="hljs-string">'&lt;&gt;'</span>,
                                <span class="hljs-string">'value'</span>:    <span class="hljs-string">'"None"'</span>,
                                <span class="hljs-string">'format'</span>:   string_template
                                }
                            )

<span class="hljs-comment">#Format the 'Stock Price' column</span>
writer.sheets[<span class="hljs-string">'Stock Market Data'</span>].conditional_format(<span class="hljs-string">'C2:C11'</span>, 
                             {
                                <span class="hljs-string">'type'</span>:     <span class="hljs-string">'cell'</span>,
                                <span class="hljs-string">'criteria'</span>: <span class="hljs-string">'&lt;&gt;'</span>,
                                <span class="hljs-string">'value'</span>:    <span class="hljs-string">'"None"'</span>,
                                <span class="hljs-string">'format'</span>:   dollar_template
                                }
                            )

<span class="hljs-comment">#Format the 'Dividend Yield' column</span>
writer.sheets[<span class="hljs-string">'Stock Market Data'</span>].conditional_format(<span class="hljs-string">'D2:D11'</span>, 
                             {
                                <span class="hljs-string">'type'</span>:     <span class="hljs-string">'cell'</span>,
                                <span class="hljs-string">'criteria'</span>: <span class="hljs-string">'&lt;&gt;'</span>,
                                <span class="hljs-string">'value'</span>:    <span class="hljs-string">'"None"'</span>,
                                <span class="hljs-string">'format'</span>:   percent_template
                                }
                            )

writer.save()
</code></pre>
<p>Let's take a look at our Excel document to see how its looking:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-21-at-11.24.36-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>So far so good! The last incremental improvement that we can make to this document is to make its columns a bit wider. </p>
<p>We can specify column widths by calling the <code>set_column</code> method on <code>writer.sheets['Stock Market Data']</code>. </p>
<p>Here's what we'll add to our Python script to do this:</p>
<pre><code class="lang-python"><span class="hljs-comment">#Specify all column widths</span>
writer.sheets[<span class="hljs-string">'Stock Market Data'</span>].set_column(<span class="hljs-string">'B:B'</span>, <span class="hljs-number">32</span>)
writer.sheets[<span class="hljs-string">'Stock Market Data'</span>].set_column(<span class="hljs-string">'C:C'</span>, <span class="hljs-number">18</span>)
writer.sheets[<span class="hljs-string">'Stock Market Data'</span>].set_column(<span class="hljs-string">'D:D'</span>, <span class="hljs-number">20</span>)
</code></pre>
<p>Here's the final version of the spreadsheet:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-21-at-11.28.17-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Voila! We are good to go! <a target="_blank" href="https://github.com/nicholasmccullum/freecodecamp-articles">You can access the final version of this Python script on GitHub here</a>. The file is named <code>stock_market_data.py</code>.</p>
<h2 id="heading-step-3-set-up-an-aws-ec2-virtual-machine-to-run-your-python-script">Step 3: Set Up an AWS EC2 Virtual Machine to Run Your Python Script</h2>
<p>Your Python script is finalized and ready to run. </p>
<p>However, we do not want to simply run this on our local machine on an ad hoc basis. </p>
<p>Instead, we are going to set up a virtual machine using <a target="_blank" href="https://aws.amazon.com/ec2/">Amazon Web Services' Elastic Compute Cloud</a> (EC2) service.</p>
<p>You'll need to create an AWS account first if you do not already have one. To do this, navigate to this URL and click the "Create an AWS Account" in the top-right corner:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-21-at-11.35.37-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>AWS' web application will guide you through the steps to create an account.</p>
<p>Once your account is created,  you'll need to create an EC2 instance. This is simply a virtual server for running code on AWS infrastructure.</p>
<p>EC2 instances come in various operating systems and sizes, ranging from very small servers that qualify for AWS' free tier to very large servers capable of running complex applications. </p>
<p>We will use AWS' smallest server to run the Python script that we wrote in this article. To get started, navigate to EC2 within the AWS management console. Once you've arrived within EC2, click <code>Launch Instance</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-22-at-8.41.14-AM-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This will bring you to a screen that contains all of the available instance types within AWS EC2. Any machine that qualifies for AWS' free tier will be sufficient. </p>
<p>I chose the <code>Amazon Linux 2 AMI (HVM)</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-22-at-8.43.37-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click <code>Select</code> to proceed.</p>
<p>On the next page, AWS will ask you to select the specifications for your machine. The fields you can select include:</p>
<ul>
<li><code>Family</code></li>
<li><code>Type</code></li>
<li><code>vCPUs</code></li>
<li><code>Memory</code></li>
<li><code>Instance Storage (GB)</code></li>
<li><code>EBS-Optimized</code></li>
<li><code>Network Performance</code></li>
<li><code>IPv6 Support</code></li>
</ul>
<p>For the purpose of this tutorial, we simply want to select the single machine that is free tier eligible. It is characterized by a small green label that looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-22-at-8.45.55-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once you have selected a free tier eligible machine, click <code>Review and Launch</code> at the bottom of the screen to proceed. The next screen will present the details of your new instance for you to review. Quickly review the machine's specifications, then click <code>Launch</code> in the bottom right-hand corner.</p>
<p>Clicking the <code>Launch</code> button will trigger a popup that asks you to <code>Select an existing key pair or create a new key pair</code>. A key pair is comprised of a public key that AWS holds and a private key that you must download and store within a <code>.pem</code> file. You must have access to that <code>.pem</code> file in order to access your EC2 instance (typically via SSH). You also have the option to proceed without a key pair, but this is <strong>not</strong> recommended for security reasons.</p>
<p>Once you have selected or created a key pair for this EC2 instance and click the radio button for <code>I acknowledge that I have access to the selected private key file (data-feeds.pem), and that without this file, I won't be able to log into my instance</code>, you can click <code>Launch Instances</code> to proceed.</p>
<p>Your instance will now begin to launch. It can take some time for these instances to boot up, but once its ready, its <code>Instance State</code> will show as <code>running</code> in your EC2 dashboard. </p>
<p>Next, you will need to push your Python script into your EC2 instance. Here is a generic command state statement that allows you to move a file into an EC2 instance:</p>
<pre><code>scp -i path/to/.pem_file path/to/file   username@host_address.amazonaws.com:/path_to_copy
</code></pre><p>Run this statement with the necessary replacements to move <code>stock_market_data.py</code> into the EC2 instance. </p>
<p>Trying to run <code>stock_market_data.py</code> at this point will actually result in an error because the EC2 instance does not come with the necessary Python packages. </p>
<p>To fix this, you can either export a <code>requirements.txt</code> file and import the proper packages using <code>pip</code>, or you can simply run the following:</p>
<pre><code>sudo yum install python3-pip
pip3 install pandas
pip3 install xlsxwriter
</code></pre><p>Once this is done, you can SSH into the EC2 instance and run the Python script from the command line with the following statement:</p>
<pre><code>python3 stock_market_data.py
</code></pre><h2 id="heading-step-4-create-an-aws-s3-bucket-to-hold-the-finished-python-script">Step 4: Create an AWS S3 Bucket to Hold the Finished Python Script</h2>
<p>With the work that we have completed so far, our Python script can be executed inside of our EC2 instance. </p>
<p>The problem with this is that the <code>xlsx</code> file will be saved to the AWS virtual server. </p>
<p>It is not accessible to anyone but us in that server, which limits its usefulness.</p>
<p>To fix this, we are going to create a public bucket on AWS S3 where we can save the <code>xlsx</code> file. Anyone who has the right URL will be able to download this file once this change is made.</p>
<p>To start, navigate to AWS S3 from within the AWS Management Console. Click <code>Create bucket</code> in the top right:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-22-at-9.02.48-AM-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>On the next screen, you will need to pick a name for your bucket and an AWS region for the bucket to be hosted in. The bucket name must be unique and cannot contain spaces or uppercase letters. The region does not matter much for the purpose of this tutorial, so I will be using the default region of <code>US East (Ohio) us-east-2)</code>.</p>
<p>You will need to change the Public Access settings in the next section to match this configuration:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-22-at-9.06.18-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click <code>Create bucket</code> to create your bucket and conclude this step of this tutorial!</p>
<h2 id="heading-step-5-modify-your-python-script-to-push-the-xlsx-file-to-aws-s3">Step 5: Modify Your Python Script to Push the xlsx File to AWS S3</h2>
<p>Our AWS S3 bucket is now ready to hold our finalized <code>xlsx</code> document. We will now make a small change to our <code>stock_market_data.py</code> file to push the finalized document to our S3 bucket.</p>
<p>We will need to use the <code>boto3</code> package to do this. <code>boto3</code> is the AWS Software Development Kit (SDK) for Python, allowing Python developers to write software that connects to AWS services. To start, you'll need to install <code>boto3</code> on your EC2 virtual machine. Run the following command line statement to do this:</p>
<pre><code>pip3 install boto3
</code></pre><p>You will also need to import the library into <code>stock_market_data.py</code> by adding the following statement to the top of the Python script.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> boto3
</code></pre>
<p>We will need to add a few lines of code to the end of <code>stock_market_data.py</code> to push the final document to AWS S3.</p>
<pre><code class="lang-python">s3 = boto3.resource(<span class="hljs-string">'s3'</span>)
s3.meta.client.upload_file(<span class="hljs-string">'stock_market_data.xlsx'</span>, <span class="hljs-string">'my-S3-bucket'</span>, <span class="hljs-string">'stock_market_data.xlsx'</span>, ExtraArgs={<span class="hljs-string">'ACL'</span>:<span class="hljs-string">'public-read'</span>})
</code></pre>
<p>The first line of this code, <code>s3 = boto3.resource('s3')</code>, allows our Python script to connect to Amazon Web Services.</p>
<p>The second line of code calls a method from <code>boto3</code> that actually uploads our file to S3. It takes four arguments:</p>
<ul>
<li><code>stock_market_data.xlsx</code> - the name of the file on our local machine.</li>
<li><code>my-S3-bucket</code> - the name of the S3 bucket that we're uploading our file to.</li>
<li><code>stock_market_data.xlsx</code> - the desired name of the file within the S3 bucket. In most cases, this will have the same value as the first argument passed into this method.</li>
<li><code>ExtraArgs={'ACL':'public-read'}</code> - this is an optional argument that tells AWS to make the uploaded file publicly-readable. </li>
</ul>
<h2 id="heading-step-6-schedule-your-python-script-to-run-periodically-using-cron">Step 6: Schedule Your Python Script to Run Periodically Using Cron</h2>
<p>So far, we have completed the following:</p>
<ul>
<li>Built our Python script</li>
<li>Created an EC2 instance and deployed our code there</li>
<li>Created an S3 bucket where we can push the final <code>xlsx</code> document</li>
<li>Modified the original Python script to upload the finalized <code>stock_market_data.xlsx</code> file to an AWS S3 bucket</li>
</ul>
<p>The only step that is left is to schedule the Python script to run periodically. </p>
<p>We can do this using a command-line utility called <code>cron</code>. To start, we will need to create a <code>cron</code> expression that tells the utility when to run the code. The <a target="_blank" href="https://crontab.guru/">crontab guru</a> website is an excellent resource for this.</p>
<p>Here's how you can use crontab guru to get <code>cron</code> expression that means <code>every day at noon</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screen-Shot-2020-04-22-at-9.27.16-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now we need to instruct our EC2 instance's <code>cron</code> daemon to run <code>stock_market_data.py</code> at this time each day.</p>
<p>To do this, we will first create a new file in our EC2 instance called <code>stock_market_data.cron</code>. </p>
<p>Open up this file and type in our cron expression followed by the statement that should be executed at the command line at that specified time. </p>
<p>Our command line statement is <code>python3 stock_market_data.py</code>, so here is what should be contained in <code>stock_market_data.cron</code>:</p>
<pre><code><span class="hljs-number">00</span> <span class="hljs-number">12</span> * * * python3 stock_market_data.py
</code></pre><p>If you run an <code>ls</code> command in your EC2 instance, you should now see two files:</p>
<pre><code>stock_market_data.py    stock_market_data.cron
</code></pre><p>The last step of this tutorial is to load <code>stock_market_data.cron</code> into the <code>crontab</code>. You can think of the <code>crontab</code> as a file that contains commands and instructions for the <code>cron</code> daemon to execute. In other words, the <code>crontab</code> contains batches of <code>cron</code> jobs.</p>
<p>First, let's see what's in our <code>crontab</code>. It should be empty since we have not put anything in it! You can view the contents of your <code>crontab</code> with the following command:</p>
<pre><code>crontab -l
</code></pre><p>To load <code>stock_market_data.cron</code> into the <code>crontab</code>, run the following statement on the command line:</p>
<pre><code>crontab stock_market_data.cron
</code></pre><p>Now when you run <code>crontab -l</code>, you should see:</p>
<pre><code><span class="hljs-number">00</span> <span class="hljs-number">12</span> * * * python3 stock_market_data.py
</code></pre><p>Our <code>stock_market_data.py</code> script will now run at noon every day on our AWS EC2 virtual machine!</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>In this article, you learned how to create automatically-updating Excel spreadsheets of financial data using Python, IEX Cloud, and Amazon Web Services. </p>
<p>Here are the specific steps we covered in this tutorial:</p>
<ul>
<li>How to create an account with IEX Cloud</li>
<li>How to write a Python script that generates beautiful Excel documents using pandas and XlsxWriter</li>
<li>How to launch an AWS EC2 instance and deploy code on it</li>
<li>How to create an AWS S3 bucket</li>
<li>How to push files to an AWS S3 bucket from within a Python script</li>
<li>How to schedule code to run using the <code>cron</code> software utility</li>
</ul>
<p>This article was published by Nick McCullum, who <a target="_blank" href="https://www.nickmccullum.com">teaches people how to code on his website</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How I get options data for free ]]>
                </title>
                <description>
                    <![CDATA[ By Harry Sauers An introduction to web scraping for finance Ever wished you could access historical options data, but got blocked by a paywall? What if you just want it for research, fun, or to develop a personal trading strategy? In this tutorial, ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-i-get-options-data-for-free-fba22d395cc8/</link>
                <guid isPermaLink="false">66c34dac30aba6677fb9f9ef</guid>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ web scraping ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 10 May 2019 17:05:11 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*8B9koPyETFCwVvO6.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Harry Sauers</p>
<h4 id="heading-an-introduction-to-web-scraping-for-finance">An introduction to web scraping for finance</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/3ijdvJH6eCn2kke2e555zvyrpErBZKhZN0fx" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Ever wished you could access historical options data, but got blocked by a paywall? What if you just want it for research, fun, or to develop a personal trading strategy?</p>
<p>In this tutorial, you’ll learn how to use Python and BeautifulSoup to scrape financial data from the Web and build your own dataset.</p>
<h3 id="heading-getting-started"><strong>Getting Started</strong></h3>
<p>You should have at least a working knowledge of Python and Web technologies before beginning this tutorial. To build these up, I highly recommend checking out a site like <a target="_blank" href="https://www.codecademy.com/">codecademy</a> to learn new skills or brush up on old ones.</p>
<p>First, let’s spin up your favorite IDE. Normally, I use <a target="_blank" href="https://www.jetbrains.com/help/pycharm/installation-guide.html">PyCharm</a> but, for a quick script like this <a target="_blank" href="https://repl.it/">Repl.it</a> will do the job too. Add a quick print (“Hello world”) to ensure your environment is set up correctly.</p>
<p>Now we need to figure out a data source.</p>
<p>Unfortunately, <a target="_blank" href="http://www.cboe.com/delayedquote/quote-table">Cboe’s awesome options chain data</a> is pretty locked down, even for current delayed quotes. Luckily, Yahoo Finance has solid enough options data <a target="_blank" href="https://finance.yahoo.com/quote/SPY/options?p=SPY">here</a>. We’ll use it for this tutorial, as web scrapers often need some content awareness, but it is easily adaptable for any data source you want.</p>
<h3 id="heading-dependencies"><strong>Dependencies</strong></h3>
<p>We don’t need many external dependencies. We just need the Requests and BeautifulSoup modules in Python. Add these at the top of your program:</p>
<pre><code><span class="hljs-keyword">from</span> bs4 <span class="hljs-keyword">import</span> BeautifulSoupimport requests
</code></pre><p>Create a <code>main</code> method:</p>
<pre><code>def main():  print(“Hello World!”)<span class="hljs-keyword">if</span> __name__ == “__main__”:  main()
</code></pre><h3 id="heading-scraping-html">Scraping HTML</h3>
<p>Now you’re ready to start scraping! Inside <code>main()</code>, add these lines to fetch the page’s full <code>HTML</code>:</p>
<pre><code>data_url = “https:<span class="hljs-comment">//finance.yahoo.com/quote/SPY/options"data_html = requests.get(data_url).contentprint(data_html)</span>
</code></pre><p>This fetches the page’s full <code>HTML</code> content, so we can find the data we want in it. Feel free to give it a run and observe the output.</p>
<p>Feel free to comment out print statements as you go — these are just there to help you understand what the program is doing at any given step.</p>
<p>BeautifulSoup is the perfect tool for working with <code>HTML</code> data in Python. Let’s narrow down the <code>HTML</code> to just the options pricing tables so we can better understand it:</p>
<pre><code> content = BeautifulSoup(data_html, “html.parser”) # print(content)
</code></pre><pre><code> options_tables = content.find_all(“table”) print(options_tables)
</code></pre><p>That’s still quite a bit of <code>HTML</code> — we can’t get much out of that, and Yahoo’s code isn’t the most friendly to web scrapers. Let’s break it down into two tables, for calls and puts:</p>
<pre><code> options_tables = [] tables = content.find_all(“table”) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">0</span>, len(content.find_all(“table”))):   options_tables.append(tables[i])
</code></pre><pre><code> print(options_tables)
</code></pre><p>Yahoo’s data contains options that are pretty deep in- and out-of-the-money, which might be great for certain purposes. I’m only interested in near-the-money options, namely the two calls and two puts closest to the current price.</p>
<p>Let’s find these, using BeautifulSoup and Yahoo’s differential table entries for in-the-money and out-of-the-money options:</p>
<pre><code>expiration = datetime.datetime.fromtimestamp(int(datestamp)).strftime(“%Y-%m-%d”)
</code></pre><pre><code>calls = options_tables[<span class="hljs-number">0</span>].find_all(“tr”)[<span class="hljs-number">1</span>:] # first row is header
</code></pre><pre><code>itm_calls = []otm_calls = []
</code></pre><pre><code><span class="hljs-keyword">for</span> call_option <span class="hljs-keyword">in</span> calls:    <span class="hljs-keyword">if</span> “<span class="hljs-keyword">in</span>-the-money” <span class="hljs-keyword">in</span> str(call_option):  itm_calls.append(call_option)  <span class="hljs-keyword">else</span>:    otm_calls.append(call_option)
</code></pre><pre><code>itm_call = itm_calls[<span class="hljs-number">-1</span>]otm_call = otm_calls[<span class="hljs-number">0</span>]
</code></pre><pre><code>print(str(itm_call) + “ \n\n “ + str(otm_call))
</code></pre><p>Now, we have the table entries for the two options nearest to the money in <code>HTML</code>. Let’s scrape the pricing data, volume, and implied volatility from the first call option:</p>
<pre><code> itm_call_data = [] <span class="hljs-keyword">for</span> td <span class="hljs-keyword">in</span> BeautifulSoup(str(itm_call), “html.parser”).find_all(“td”):   itm_call_data.append(td.text)
</code></pre><pre><code>print(itm_call_data)
</code></pre><pre><code>itm_call_info = {‘contract’: itm_call_data[<span class="hljs-number">0</span>], ‘strike’: itm_call_data[<span class="hljs-number">2</span>], ‘last’: itm_call_data[<span class="hljs-number">3</span>],  ‘bid’: itm_call_data[<span class="hljs-number">4</span>], ‘ask’: itm_call_data[<span class="hljs-number">5</span>], ‘volume’: itm_call_data[<span class="hljs-number">8</span>], ‘iv’: itm_call_data[<span class="hljs-number">10</span>]}
</code></pre><pre><code>print(itm_call_info)
</code></pre><p>Adapt this code for the next call option:</p>
<pre><code># otm callotm_call_data = []<span class="hljs-keyword">for</span> td <span class="hljs-keyword">in</span> BeautifulSoup(str(otm_call), “html.parser”).find_all(“td”):  otm_call_data.append(td.text)
</code></pre><pre><code># print(otm_call_data)
</code></pre><pre><code>otm_call_info = {‘contract’: otm_call_data[<span class="hljs-number">0</span>], ‘strike’: otm_call_data[<span class="hljs-number">2</span>], ‘last’: otm_call_data[<span class="hljs-number">3</span>],  ‘bid’: otm_call_data[<span class="hljs-number">4</span>], ‘ask’: otm_call_data[<span class="hljs-number">5</span>], ‘volume’: otm_call_data[<span class="hljs-number">8</span>], ‘iv’: otm_call_data[<span class="hljs-number">10</span>]}
</code></pre><pre><code>print(otm_call_info)
</code></pre><p>Give your program a run!</p>
<p>You now have dictionaries of the two near-the-money call options. It’s enough just to scrape the table of put options for this same data:</p>
<pre><code>puts = options_tables[<span class="hljs-number">1</span>].find_all(<span class="hljs-string">"tr"</span>)[<span class="hljs-number">1</span>:]  # first row is header
</code></pre><pre><code>itm_puts = []  otm_puts = []
</code></pre><pre><code><span class="hljs-keyword">for</span> put_option <span class="hljs-keyword">in</span> puts:    <span class="hljs-keyword">if</span> <span class="hljs-string">"in-the-money"</span> <span class="hljs-keyword">in</span> str(put_option):      itm_puts.append(put_option)    <span class="hljs-keyword">else</span>:      otm_puts.append(put_option)
</code></pre><pre><code>itm_put = itm_puts[<span class="hljs-number">0</span>]  otm_put = otm_puts[<span class="hljs-number">-1</span>]
</code></pre><pre><code># print(str(itm_put) + <span class="hljs-string">" \n\n "</span> + str(otm_put) + <span class="hljs-string">"\n\n"</span>)
</code></pre><pre><code>itm_put_data = []  <span class="hljs-keyword">for</span> td <span class="hljs-keyword">in</span> BeautifulSoup(str(itm_put), <span class="hljs-string">"html.parser"</span>).find_all(<span class="hljs-string">"td"</span>):    itm_put_data.append(td.text)
</code></pre><pre><code># print(itm_put_data)
</code></pre><pre><code>itm_put_info = {<span class="hljs-string">'contract'</span>: itm_put_data[<span class="hljs-number">0</span>],                  <span class="hljs-string">'last_trade'</span>: itm_put_data[<span class="hljs-number">1</span>][:<span class="hljs-number">10</span>],                  <span class="hljs-string">'strike'</span>: itm_put_data[<span class="hljs-number">2</span>], <span class="hljs-string">'last'</span>: itm_put_data[<span class="hljs-number">3</span>],                   <span class="hljs-string">'bid'</span>: itm_put_data[<span class="hljs-number">4</span>], <span class="hljs-string">'ask'</span>: itm_put_data[<span class="hljs-number">5</span>], <span class="hljs-string">'volume'</span>: itm_put_data[<span class="hljs-number">8</span>], <span class="hljs-string">'iv'</span>: itm_put_data[<span class="hljs-number">10</span>]}
</code></pre><pre><code># print(itm_put_info)
</code></pre><pre><code># otm put  otm_put_data = []  <span class="hljs-keyword">for</span> td <span class="hljs-keyword">in</span> BeautifulSoup(str(otm_put), <span class="hljs-string">"html.parser"</span>).find_all(<span class="hljs-string">"td"</span>):    otm_put_data.append(td.text)
</code></pre><pre><code># print(otm_put_data)
</code></pre><pre><code>otm_put_info = {<span class="hljs-string">'contract'</span>: otm_put_data[<span class="hljs-number">0</span>],                  <span class="hljs-string">'last_trade'</span>: otm_put_data[<span class="hljs-number">1</span>][:<span class="hljs-number">10</span>],                  <span class="hljs-string">'strike'</span>: otm_put_data[<span class="hljs-number">2</span>], <span class="hljs-string">'last'</span>: otm_put_data[<span class="hljs-number">3</span>],                   <span class="hljs-string">'bid'</span>: otm_put_data[<span class="hljs-number">4</span>], <span class="hljs-string">'ask'</span>: otm_put_data[<span class="hljs-number">5</span>], <span class="hljs-string">'volume'</span>: otm_put_data[<span class="hljs-number">8</span>], <span class="hljs-string">'iv'</span>: otm_put_data[<span class="hljs-number">10</span>]}
</code></pre><p>Congratulations! You just scraped data for all near-the-money options of the S&amp;P 500 ETF, and can view them like this:</p>
<pre><code> print(<span class="hljs-string">"\n\n"</span>) print(itm_call_info) print(otm_call_info) print(itm_put_info) print(otm_put_info)
</code></pre><p>Give your program a run — you should get data like this printed to the console:</p>
<pre><code>{‘contract’: ‘SPY190417C00289000’, ‘last_trade’: ‘<span class="hljs-number">2019</span>–<span class="hljs-number">04</span>–<span class="hljs-number">15</span>’, ‘strike’: ‘<span class="hljs-number">289.00</span>’, ‘last’: ‘<span class="hljs-number">1.46</span>’, ‘bid’: ‘<span class="hljs-number">1.48</span>’, ‘ask’: ‘<span class="hljs-number">1.50</span>’, ‘volume’: ‘<span class="hljs-number">4</span>,<span class="hljs-number">646</span>’, ‘iv’: ‘<span class="hljs-number">8.94</span>%’}{‘contract’: ‘SPY190417C00290000’, ‘last_trade’: ‘<span class="hljs-number">2019</span>–<span class="hljs-number">04</span>–<span class="hljs-number">15</span>’, ‘strike’: ‘<span class="hljs-number">290.00</span>’, ‘last’: ‘<span class="hljs-number">0.80</span>’, ‘bid’: ‘<span class="hljs-number">0.82</span>’, ‘ask’: ‘<span class="hljs-number">0.83</span>’, ‘volume’: ‘<span class="hljs-number">38</span>,<span class="hljs-number">491</span>’, ‘iv’: ‘<span class="hljs-number">8.06</span>%’}{‘contract’: ‘SPY190417P00290000’, ‘last_trade’: ‘<span class="hljs-number">2019</span>–<span class="hljs-number">04</span>–<span class="hljs-number">15</span>’, ‘strike’: ‘<span class="hljs-number">290.00</span>’, ‘last’: ‘<span class="hljs-number">0.77</span>’, ‘bid’: ‘<span class="hljs-number">0.75</span>’, ‘ask’: ‘<span class="hljs-number">0.78</span>’, ‘volume’: ‘<span class="hljs-number">11</span>,<span class="hljs-number">310</span>’, ‘iv’: ‘<span class="hljs-number">7.30</span>%’}{‘contract’: ‘SPY190417P00289000’, ‘last_trade’: ‘<span class="hljs-number">2019</span>–<span class="hljs-number">04</span>–<span class="hljs-number">15</span>’, ‘strike’: ‘<span class="hljs-number">289.00</span>’, ‘last’: ‘<span class="hljs-number">0.41</span>’, ‘bid’: ‘<span class="hljs-number">0.40</span>’, ‘ask’: ‘<span class="hljs-number">0.42</span>’, ‘volume’: ‘<span class="hljs-number">44</span>,<span class="hljs-number">319</span>’, ‘iv’: ‘<span class="hljs-number">7.79</span>%’}
</code></pre><h3 id="heading-setting-up-recurring-data-collection">Setting up recurring data collection</h3>
<p>Yahoo, by default, only returns the options for the date you specify. It’s this part of the URL: <a target="_blank" href="https://finance.yahoo.com/quote/SPY/options?date=1555459200">https://finance.yahoo.com/quote/SPY/options?date=<strong>1555459200</strong></a></p>
<p>This is a Unix timestamp, so we’ll need to generate or scrape one, rather than hardcoding it in our program.</p>
<p>Add some dependencies:</p>
<pre><code><span class="hljs-keyword">import</span> datetime, time
</code></pre><p>Let’s write a quick script to generate and verify a Unix timestamp for our next set of options:</p>
<pre><code>def get_datestamp():  options_url = “https:<span class="hljs-comment">//finance.yahoo.com/quote/SPY/options?date="  today = int(time.time())  # print(today)  date = datetime.datetime.fromtimestamp(today)  yy = date.year  mm = date.month  dd = date.day</span>
</code></pre><p>The above code holds the base URL of the page we are scraping and generates a <code>datetime.date</code> object for us to use in the future.</p>
<p>Let’s increment this date by one day, so we don’t get options that have already expired.</p>
<pre><code>dd += <span class="hljs-number">1</span>
</code></pre><p>Now, we need to convert it back into a Unix timestamp and make sure it’s a valid date for options contracts:</p>
<pre><code> options_day = datetime.date(yy, mm, dd) datestamp = int(time.mktime(options_day.timetuple())) # print(datestamp) # print(datetime.datetime.fromtimestamp(options_stamp))
</code></pre><pre><code> # vet timestamp, then <span class="hljs-keyword">return</span> <span class="hljs-keyword">if</span> valid <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">0</span>, <span class="hljs-number">7</span>):   test_req = requests.get(options_url + str(datestamp)).content   content = BeautifulSoup(test_req, “html.parser”)   # print(content)   tables = content.find_all(“table”)
</code></pre><pre><code> <span class="hljs-keyword">if</span> tables != []:   # print(datestamp)   <span class="hljs-keyword">return</span> str(datestamp) <span class="hljs-keyword">else</span>:   # print(“Bad datestamp!”)   dd += <span class="hljs-number">1</span>   options_day = datetime.date(yy, mm, dd)   datestamp = int(time.mktime(options_day.timetuple()))  <span class="hljs-keyword">return</span> str(<span class="hljs-number">-1</span>)
</code></pre><p>Let’s adapt our <code>fetch_options</code> method to use a dynamic timestamp to fetch options data, rather than whatever Yahoo wants to give us as the default.</p>
<p>Change this line:</p>
<pre><code>data_url = “https:<span class="hljs-comment">//finance.yahoo.com/quote/SPY/options"</span>
</code></pre><p>To this:</p>
<pre><code>datestamp = get_datestamp()data_url = “https:<span class="hljs-comment">//finance.yahoo.com/quote/SPY/options?date=" + datestamp</span>
</code></pre><p>Congratulations! You just scraped real-world options data from the web.</p>
<p>Now we need to do some simple file I/O and set up a timer to record this data each day after market close.</p>
<h3 id="heading-improving-the-program">Improving the program</h3>
<p>Rename <code>main()</code> to <code>fetch_options()</code> and add these lines to the bottom:</p>
<pre><code>options_list = {‘calls’: {‘itm’: itm_call_info, ‘otm’: otm_call_info}, ‘puts’: {‘itm’: itm_put_info, ‘otm’: otm_put_info}, ‘date’: datetime.date.fromtimestamp(time.time()).strftime(“%Y-%m-%d”)}<span class="hljs-keyword">return</span> options_list
</code></pre><p>Create a new method called <code>schedule()</code>. We’ll use this to control when we scrape for options, every twenty-four hours after market close. Add this code to schedule our first job at the next market close:</p>
<pre><code><span class="hljs-keyword">from</span> apscheduler.schedulers.background <span class="hljs-keyword">import</span> BackgroundScheduler
</code></pre><pre><code>scheduler = BackgroundScheduler()
</code></pre><pre><code>def schedule():  scheduler.add_job(func=run, trigger=”date”, run_date = datetime.datetime.now())  scheduler.start()
</code></pre><p>In your <code>if __name__ == “__main__”:</code> statement, delete <code>main()</code> and add a call to <code>schedule()</code> to set up your first scheduled job.</p>
<p>Create another method called <code>run()</code>. This is where we’ll handle the bulk of our operations, including actually saving the market data. Add this to the body of <code>run()</code>:</p>
<pre><code>  today = int(time.time()) date = datetime.datetime.fromtimestamp(today) yy = date.year mm = date.month dd = date.day
</code></pre><pre><code> # must use <span class="hljs-number">12</span>:<span class="hljs-number">30</span> <span class="hljs-keyword">for</span> Unix time instead <span class="hljs-keyword">of</span> <span class="hljs-number">4</span>:<span class="hljs-number">30</span> NY time next_close = datetime.datetime(yy, mm, dd, <span class="hljs-number">12</span>, <span class="hljs-number">30</span>)
</code></pre><pre><code> # <span class="hljs-keyword">do</span> operations here “”” This is where we’ll write our last bit <span class="hljs-keyword">of</span> code. “””
</code></pre><pre><code> # schedule next job scheduler.add_job(func=run, trigger=”date”, run_date = next_close)
</code></pre><pre><code> print(“Job scheduled! | “ + str(next_close))
</code></pre><p>This lets our code call itself in the future, so we can just put it on a server and build up our options data each day. Add this code to actually fetch data under <code>“”” This is where we’ll write our last bit of code. “””</code></p>
<pre><code>options = {}
</code></pre><pre><code> # ensures option data doesn’t <span class="hljs-keyword">break</span> the program <span class="hljs-keyword">if</span> internet is out <span class="hljs-keyword">try</span>:   <span class="hljs-keyword">if</span> next_close &gt; datetime.datetime.now():     print(“Market is still open! Waiting until after close…”)   <span class="hljs-keyword">else</span>:     # ensures program was run after market hours     <span class="hljs-keyword">if</span> next_close &lt; datetime.datetime.now():      dd += <span class="hljs-number">1</span>       next_close = datetime.datetime(yy, mm, dd, <span class="hljs-number">12</span>, <span class="hljs-number">30</span>)       options = fetch_options()       print(options)       # write to file       write_to_csv(options)except:  print(“Check your connection and <span class="hljs-keyword">try</span> again.”)
</code></pre><h3 id="heading-saving-data">Saving data</h3>
<p>You may have noticed that <code>write_to_csv</code> isn’t implemented yet. No worries — let’s take care of that here:</p>
<pre><code>def write_to_csv(options_data):  <span class="hljs-keyword">import</span> csv  <span class="hljs-keyword">with</span> open(‘options.csv’, ‘a’, newline=’\n’) <span class="hljs-keyword">as</span> csvfile:  spamwriter = csv.writer(csvfile, delimiter=’,’)  spamwriter.writerow([str(options_data)])
</code></pre><h3 id="heading-cleaning-up"><strong>Cleaning up</strong></h3>
<p>As options contracts are time-sensitive, we might want to add a field for their expiration date. This capability is not included in the raw HTML we scraped.</p>
<p>Add this line of code to save and format the expiration date towards the top of <code>fetch_options()</code>:</p>
<pre><code>expiration =  datetime.datetime.fromtimestamp(int(get_datestamp())).strftime(<span class="hljs-string">"%Y-%m-%d"</span>)
</code></pre><p>Add <code>‘expiration’: expiration</code> to the end of each <code>option_info</code> dictionary like so:</p>
<pre><code>itm_call_info = {<span class="hljs-string">'contract'</span>: itm_call_data[<span class="hljs-number">0</span>],  <span class="hljs-string">'strike'</span>: itm_call_data[<span class="hljs-number">2</span>], <span class="hljs-string">'last'</span>: itm_call_data[<span class="hljs-number">3</span>],   <span class="hljs-string">'bid'</span>: itm_call_data[<span class="hljs-number">4</span>], <span class="hljs-string">'ask'</span>: itm_call_data[<span class="hljs-number">5</span>], <span class="hljs-string">'volume'</span>: itm_call_data[<span class="hljs-number">8</span>], <span class="hljs-string">'iv'</span>: itm_call_data[<span class="hljs-number">10</span>], <span class="hljs-string">'expiration'</span>: expiration}
</code></pre><p>Give your new program a run — it’ll scrape the latest options data and write it to a .csv file as a string representation of a dictionary. The .csv file will be ready to be parsed by a backtesting program or served to users through a webapp. Congratulations!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Clustering the Top 1%: Asset Analysis in R ]]>
                </title>
                <description>
                    <![CDATA[ By Ben Weber The recent tax reform bill passed in the US has raised a lot of questions about wealth distribution in the country. While there’s been a lot of focus on how the tax plan will impact income, there’s been less attention focused on how this... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/clustering-the-top-1-asset-analysis-in-r-6c529b382b42/</link>
                <guid isPermaLink="false">66c34766a1d481faeda49b12</guid>
                
                    <category>
                        <![CDATA[ analytics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Data Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 05 Jan 2018 09:58:46 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*slo6MwMQ8wn4zm4WfX6qKQ.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ben Weber</p>
<p>The recent tax reform bill passed in the US has raised a lot of questions about wealth distribution in the country. While there’s been a lot of focus on how the tax plan will <a target="_blank" href="https://www.nytimes.com/interactive/2017/12/17/upshot/tax-calculator.html">impact income</a>, there’s been less attention focused on how this plan impacts the assets of wealthy households.</p>
<p>The goal of this post is to show how the R programming language can be used to data mine publicly available sources to better understand the net worth of affluent households in the US. Using data from the 2016 Federal Reserve <a target="_blank" href="https://www.federalreserve.gov/econres/scfindex.htm">Survey of Consumer Finances</a>, we investigate the following questions:</p>
<ul>
<li>How rich are the top 1% and top 0.1% of households?</li>
<li>Are there different types of millionaires in the US?</li>
<li>How do asset allocations differ across different net worth segments?</li>
</ul>
<p>To answer these questions, we present descriptive statistics of this survey data and perform cluster analysis on affluent households, which we identify as households with a net worth of more than $1,000,000 USD.</p>
<p>Based on the survey data, our analysis shows that the net worth of the top 1% of households in the US is $10.4M and the net worth of the top 0.1% of households is $43.2M. This post presents an analysis of the different asset compositions of millionaires, and shows how asset allocations differ between the top 10%, 1%, and 0.1% of households in the US. The R source code used to produce all results and figures presented in this post is available as a <a target="_blank" href="https://github.com/bgweber/WindfallData/blob/master/FED_Reserve_Survey.ipynb">Jupyter Notebook</a>.</p>
<p><strong>Setting Up the Environment</strong><br>To perform cluster analysis on the affluent households in the US, we use several packages available from the <a target="_blank" href="https://cran.r-project.org/web/packages/available_packages_by_name.html">CRAN library</a> for R. For exploratory data analysis, we like to use the R kernel for the Jupyter notebook, since it enables data scientists to easily store notebooks on GitHub and share findings with other teams.</p>
<p>Setting up this environment is outside the scope of this post, but I’ve previously detailed our motivation for this setup in <a target="_blank" href="https://medium.com/windfalldata/the-data-science-stack-at-windfall-data-e1e6bc3c4c8f">this post</a>, and additional details for setting up Jupyter with R support are available <a target="_blank" href="https://github.com/IRkernel/IRkernel">here</a>.</p>
<p>We’re now ready to start digging into the survey data to better understand the assets of affluent households in the US. To begin, we’ll load several libraries that will help us analyze the survey data and perform clustering.</p>
<p>The code block below shows the libraries that need to be loaded for executing this notebook. The <em>readxl</em> library is needed to read the source data and convert it into a data frame, the <em>reldist</em> and <em>ENmisc</em> libraries are used for computing distributions with weighted data sets, and the remaining libraries are used for cluster analysis.</p>
<pre><code>library(readxl)     # <span class="hljs-keyword">for</span> reading xlsx files library(reldist)    # <span class="hljs-keyword">for</span> computing weighted statisticslibrary(ENmisc)     # <span class="hljs-keyword">for</span> weighted box plotslibrary(plotly)     # <span class="hljs-keyword">for</span> interactive plotslibrary(factoextra) # <span class="hljs-keyword">for</span> factor mapslibrary(FactoMineR) # Principal Component Analysis (PCA)library(cluster)    # Clustering algorithms (CLARA)library(<span class="hljs-class"><span class="hljs-keyword">class</span>)      # <span class="hljs-title">for</span> <span class="hljs-title">KNN</span></span>
</code></pre><p><strong>Getting the Data</strong><br>The next step is to download the data from the Federal Reserve website. The survey data is available as a zipped xlsx file. To download the data and load it into R as a data frame for analysis, we use the code block below. Since this is a large file, we make sure that we do not download it multiple times. The resulting file that we unzip is about 40MB and takes some time to load into a data frame.</p>
<pre><code><span class="hljs-keyword">if</span> (!file.exists(<span class="hljs-string">"SCFP2016.xlsx"</span>)) {          download.file(   <span class="hljs-string">"https://www.federalreserve.gov/econres/files/scfp2016excel.zip"</span>,   <span class="hljs-string">"SCFP2016.zip"</span>)  unzip(<span class="hljs-string">"scfp2016.zip"</span>)}
</code></pre><pre><code>df &lt;- read_excel(<span class="hljs-string">"SCFP2016.xlsx"</span>)
</code></pre><p><strong>Summary Statistics</strong><br>Now that we have the survey data loaded into R, we can start to analyze the asset allocation of the richest households in the US. We’ll start with some summary stats: how many survey participants and how many households are represented by this survey? Counting the number of rows in the data frame answers the first questions (31.2k), and adding up the weights of all of the survey respondents answers the second question (126M).</p>
<pre><code># How many survey participants?nrow(df)
</code></pre><pre><code># How many households does the survey represent?floor(sum(df$WGT)))
</code></pre><pre><code># What is the weighted mean <span class="hljs-keyword">of</span> household net worth?floor(sum(df$NETWORTH*df$WGT)/sum(df$WGT)))
</code></pre><pre><code># what is the median NW <span class="hljs-keyword">in</span> US?  reldist::wtd.quantile(df$NETWORTH, q=<span class="hljs-number">0.5</span>, weight = df$WGT)
</code></pre><pre><code># who is the <span class="hljs-number">1</span>%? reldist::wtd.quantile(df$NETWORTH, q=<span class="hljs-number">0.99</span>, weight = df$WGT)
</code></pre><pre><code># top <span class="hljs-number">0.1</span>% Ultra-high net worth households  reldist::wtd.quantile(df$NETWORTH, q=<span class="hljs-number">0.999</span>, weight = df$WGT)
</code></pre><p>To answer questions about averages, such as what is the mean household net worth, we need to use weighted statistics (since the weight of one survey respondent can be much larger than others). To compute the mean net worth, we can use built-in R functions, which returns a value of $690k. However, since net worth is much closer to a log normal than normal distribution, we should use other approaches.</p>
<p>To compute the median value with weighted responses, we use the <em>reldist</em> library, which assigns more support to respondents with larger weights and less support to respondents with lower weights. When using this approach to compute the weighted median, we find that the 50th percentile for household net worth in the US is $97k.</p>
<p>The net worth of the top 1% is $10.4M and the net worth of the top 0.1% is $43.2M. We use the <em>wtd.quantile</em> function to compute these descriptive statistics, and the code sample above uses the fully quantified function names, due to collisions with the <em>ENmisc</em> package.</p>
<p><strong>Demographic Data</strong><br>The survey data provides a number of different demographic variables that can be used to analyze net worth by different factors. These variables include race, marital status, education level, employment status, and others. The goal of this post is to show how asset allocation varies by net worth segment, and analysis of how these demographic factors impact net worth is left as an exercise for the reader.</p>
<pre><code># filter on ages <span class="hljs-number">30</span> - <span class="hljs-number">84</span>, and group into <span class="hljs-number">5</span>-year bucketsdata &lt;- df[df$AGE &gt;= <span class="hljs-number">30</span> &amp; df$AGE &lt; <span class="hljs-number">85</span>, ]ages &lt;- floor(data$AGE/<span class="hljs-number">5.0</span>)*<span class="hljs-number">5</span>
</code></pre><pre><code># plot the weighted box plotwtd.boxplot(log10(<span class="hljs-number">1</span> + data$NETWORTH) ~ ages, data = data,   weights = data$WGT, main = <span class="hljs-string">'Net Worth by Age'</span>,  xlab=<span class="hljs-string">"Age"</span>, ylab=<span class="hljs-string">"Net Worth (Log10)"</span>)
</code></pre><p>One demographic variable that we did explore is the impact of age on household net worth. As expected, the median net worth does increase as the head of household becomes older, with net worth plateauing around 60 years old.</p>
<p>The code above shows how to display a box plot of the survey data by age, using the <em>ENmisc</em> package to compute weighted distributions. The results of this plot show that the median net worth of households in the US are $114k at 40, $163k at 50, and $243k at 60.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/AbSgIbouVyV2BFq2l5B0xkkp26ENdyYBffz6" alt="Image" width="606" height="596" loading="lazy"></p>
<p><strong>Asset Allocation</strong><br>The next step in the notebook is to evaluate the asset allocation of different net worth segments. For this analysis, we define a segment based on the log10 value of the household net worth. That means all 5-figure households get grouped together, all 6-figure households get grouped together, as so on.</p>
<pre><code># normalize assets by total financial and non-financial amountshouseholds &lt;- data.frame(  LIQ = df$LIQ/assets,  ...  BUS = df$BUS/assets,    OTHNFIN = df$OTHNFIN/assets
</code></pre><pre><code># split into net worth segments, and compute mean distributions nw &lt;- floor(log10(households$netWorth))segment &lt;- ifelse(nw == <span class="hljs-number">4</span>, <span class="hljs-string">"     $10k"</span>,       ifelse(nw == <span class="hljs-number">5</span>, <span class="hljs-string">"    $100K"</span>,       ifelse(nw == <span class="hljs-number">6</span>, <span class="hljs-string">"   $1M"</span>,                     ifelse(nw == <span class="hljs-number">7</span>, <span class="hljs-string">"  $10M"</span>,                     ifelse(nw == <span class="hljs-number">8</span>, <span class="hljs-string">" $100M"</span>, <span class="hljs-string">"$1B+"</span>)))))
</code></pre><pre><code>results &lt;- <span class="hljs-keyword">as</span>.data.frame((aggregate(households,list(segment),mean)))
</code></pre><pre><code># plot the resultsplot &lt;- plot_ly(results, x = ~Group<span class="hljs-number">.1</span>, y = ~<span class="hljs-number">100</span>*LIQ, type = <span class="hljs-string">'bar'</span>, name = <span class="hljs-string">'Liquid'</span>) %&gt;%  add_trace(y = ~<span class="hljs-number">100</span>*CDS, name = <span class="hljs-string">'Certificates of Deposit'</span>) %&gt;%  add_trace(y = ~<span class="hljs-number">100</span>*NMMF, name = <span class="hljs-string">'Mutual Funds'</span>) %&gt;%  ...  add_trace(y = ~<span class="hljs-number">100</span>*BUS, name = <span class="hljs-string">'Business Interests'</span>) %&gt;%  layout(yaxis = list(title = <span class="hljs-string">'% of Assets'</span>,     ticksuffix = <span class="hljs-string">"%"</span>), xaxis = list(title = <span class="hljs-string">"Net Worth"</span>),    title = <span class="hljs-string">"Asset Allocation by Net Worth"</span>, barmode = <span class="hljs-string">'stack'</span>)
</code></pre><p>The code above computes the asset allocation by household, by dividing the amount of assets for a household, such as business equity (<em>BUS</em>) over the total number of financial and non-financial assets, excluding debt. The “<em>…”</em> pattern is used to indicate that multiple rows have been excluded from the code snippet that are listed in the full notebook. The second code block groups the households into different net worth segments, and the third block plots the results as shown below.</p>
<p>The results show that the wealthy, ultra wealthy, and billionaires have large amounts of assets in business equity (stock and options). The wealthy have only a small percentage of assets in retirement funds, and instead have assets in stock, mutual funds, and residential and commercial real estate.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/qwBPb467I3mVFkHLE77cov0pOGQGiDXfDwjR" alt="Image" width="642" height="378" loading="lazy"></p>
<p><strong>Clustering Millionaires</strong><br>So far, we’ve looked at aggregate statistics of wealthy households, but that doesn’t tell us about the different types of affluent households. To understand how assets vary across affluent homes, we can use cluster analysis. One of the most useful ways to visualize the difference between instances in a sample population is to use factor maps to visualize the variance in the population.</p>
<pre><code># filter on affluent households, and print the total numberaffluent &lt;- households[households$netWorth &gt;= <span class="hljs-number">1000000</span>, ]cat(paste(<span class="hljs-string">"Affluent Households: "</span>, floor(sum(affluent$weight))))
</code></pre><pre><code># plot a Factor <span class="hljs-built_in">Map</span> <span class="hljs-keyword">of</span> assets fviz_pca_var(PCA(affluent,  graph = FALSE), col.var=<span class="hljs-string">"contrib"</span>,      gradient.cols = c(<span class="hljs-string">"#00AFBB"</span>, <span class="hljs-string">"#E7B800"</span>, <span class="hljs-string">"#FC4E07"</span>), repel = TRUE)+  labs(title =<span class="hljs-string">"Affluent Households - Assets Factor Map"</span>)
</code></pre><p>The code above first filters survey respondents to affluent households, with a net worth of more than $1M USD, and then plots a factor map using principal component analysis (PCA). The figure below shows how the different assets impact the trajectory of plotting a household across the two principal components discovered via PCA.</p>
<p>The results plotted below show that there are a few different assets groups that vary across affluent net worth. The most significant factor is business equity. Some other groupings of factors include investment assets (STOCKS, BONDS) and real estate assets/retirement funds.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ScGEwd7NWTd9onSsFzjIWJbFRb0p6p13jEAh" alt="Image" width="618" height="566" loading="lazy"></p>
<p><strong>How many clusters to use?</strong><br>We’ve now shown signs that there are different types of millionaires, and that assets vary based on net worth segments. To understand how asset allocation differs by net worth segment, we can use cluster analysis. We first identify clusters in the affluent survey respondents, and then apply these labels to the overall population of survey respondents.</p>
<pre><code>k &lt;- <span class="hljs-number">7</span>res.hc &lt;- eclust(households[sample(nrow(households), <span class="hljs-number">1000</span>), ],  <span class="hljs-string">"hclust"</span>, k = k, graph = FALSE) fviz_dend(res.hc, rect = TRUE, show_labels = FALSE)
</code></pre><p>To determine how many clusters to use, we created a cluster dendrogram using the code snippet above, shown as the header image of this post. We also varied the number of clusters, <em>k</em>, until we had the largest number of distinctly identifiable clusters.</p>
<p>If you’d prefer to take a quantitative approach, you can use the _fviz<em>nbclust</em> function, which computes the optimal number of clusters using a silhouette metric. For our analysis, we decided to use 7 clusters.</p>
<pre><code>clarax &lt;- clara(affluent, k)fviz_cluster(clarax, stand = FALSE, geom = <span class="hljs-string">"point"</span>, ellipse = F)
</code></pre><p>To cluster the affluent households into unique groupings, we used the <a target="_blank" href="https://stat.ethz.ch/R-manual/R-devel/library/cluster/html/clara.html">CLARA algorithm</a>. A visualization of the different clusters is shown below. The results are similar to PCA and the factor map approach discussed above.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Ut8np08dC1YfqAkHNBxHx54QBVGq3DrMkkbf" alt="Image" width="622" height="625" loading="lazy"></p>
<p><strong>Cluster Descriptions</strong><br>Now that we’ve determined how many clusters to use, it’s useful to inspect the clusters and assign qualitative labels based on the feature sets. The code snippet below shows how to compute the average feature values for the 7 different clusters.</p>
<pre><code>groups &lt;- clarax$clusteringresults &lt;- <span class="hljs-keyword">as</span>.data.frame(t(aggregate(affluent,list(groups),mean)))  results[<span class="hljs-number">2</span>:<span class="hljs-number">18</span>,]
</code></pre><p>The results of this code block are shown below. Based on these results, we came up with the following cluster descriptions:</p>
<ul>
<li>V1: Stocks/Bonds — 31% of assets, followed by home and mutual funds</li>
<li>V2: Diversified — 53% busequity, 10% home and 9% in other real estate</li>
<li>V3: Residential Real Estate — 48% of assets</li>
<li>V4: Mutual Funds — 50% of assets</li>
<li>V5: Retirement — 48% of assets</li>
<li>V6: Business Equity — 85% of assets</li>
<li>V7: Commercial Real Estate — 59% of assets</li>
</ul>
<p>With the exception of cluster V7, containing only 3% of the population, most of the clusters are relatively even in size. The second smallest cluster represents 12% of the population while the largest cluster represents 20%. You can use <em>table(groups)</em> to show the unweighted cluster population sizes.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1hF0UTt-EVmvGXhUAT3ZNE3eH7BwJT34X-S9" alt="Image" width="368" height="480" loading="lazy"></p>
<p><strong>Cluster Populations by Net Worth Segments</strong><br>The last step in this analysis is to apply the different cluster assignments to the overall population, and to group the populations by net worth segments. Since we trained the clusters on only affluent households, we need to use a classification algorithm to label the non-affluent households in the population. The code snippet below uses <em>knn</em> to accomplish this task.</p>
<p>The remaining code blocks compute the number of households that are classified as each cluster, for each of the net worth segments.</p>
<pre><code># assign all <span class="hljs-keyword">of</span> the households to a cluster groups &lt;- knn(train = affluent, test = households,   cl = clarax$clustering, k = k, prob = T, use.all = T)
</code></pre><pre><code># figure out how many households are <span class="hljs-keyword">in</span> each cluster clusters &lt;- data.frame(  c1 = ifelse(groups == <span class="hljs-number">1</span>, weights, <span class="hljs-number">0</span>),   ...   c7 = ifelse(groups == <span class="hljs-number">7</span>, weights, <span class="hljs-number">0</span>) )
</code></pre><pre><code># assign each household to a net worth cluster nw &lt;- floor(<span class="hljs-number">2</span>*log10(nwHouseholds))/<span class="hljs-number">2</span>results &lt;- <span class="hljs-keyword">as</span>.data.frame(t(aggregate(clusters,list(nw),sum)))
</code></pre><pre><code># compute the number <span class="hljs-keyword">of</span> households that belong to each segmentresults$V1 &lt;- results$V1/sum(ifelse(nw == <span class="hljs-number">4</span>, weights, <span class="hljs-number">0</span>))...results$V11 &lt;- results$V11/sum(ifelse(nw == <span class="hljs-number">9</span>, weights, <span class="hljs-number">0</span>))
</code></pre><pre><code># plot the results plot &lt;- plot_ly(results, x = ~<span class="hljs-number">10</span>^Group<span class="hljs-number">.1</span>, y = ~<span class="hljs-number">100</span>*c1, type = <span class="hljs-string">'scatter'</span>, mode = <span class="hljs-string">'lines'</span>, name = <span class="hljs-string">"Stocks"</span>) %&gt;%  add_trace(y = ~<span class="hljs-number">100</span>*c2, name = <span class="hljs-string">"Diversified"</span>) %&gt;%  ...  add_trace(y = ~<span class="hljs-number">100</span>*c7, name = <span class="hljs-string">"Commercial R.E."</span>) %&gt;%  layout(yaxis = list(title = <span class="hljs-string">'% of Households'</span>, ticksuffix = <span class="hljs-string">"%"</span>),     xaxis = list(title = <span class="hljs-string">"Net Worth ($)"</span>, type = <span class="hljs-string">"log"</span>),      title  = <span class="hljs-string">"Cluster Populations by Net Worth"</span>)
</code></pre><p>The results of this process are shown in the figure below. The chart shows some obvious and some novel results: home ownership and retirement funds make up the majority of assets for non-affluent households, there is a relatively even mix of clusters around $2M (excluding commercial real estate and business equity), and business equity dominates net worth for the ultra-wealthy households, followed by other investment assets.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/YgTW5BbbShEas12B97L0R8dQZuJHG85nEyfa" alt="Image" width="716" height="421" loading="lazy"></p>
<p><strong>Summary</strong><br>In this post we used R to download and analyze data from the 2016 Federal Reserve survey of consumer finances to understand how wealthy the top households are in the US, and to cluster affluent households by asset allocation. We identified 7 distinct groups of millionaires, and showed how the distribution of clusters varies based on net worth segment. Please keep in mind that the results presented are from weighted survey data, and may not be representative of the overall US population.</p>
<p><a target="_blank" href="https://www.linkedin.com/in/ben-weber-3b87482/">Ben Weber</a> is a principal data scientist at Zynga. We are <a target="_blank" href="https://www.zynga.com/careers/positions/categories">hiring</a>!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What You Need to Know About the Future of Bitcoin Technology ]]>
                </title>
                <description>
                    <![CDATA[ By Subhan Nadeem Bitcoin (BTC) recently smashed an all-time high of $11,400 USD and subsequently dropped to as low as $8,595 within a few hours. It’s incredibly important to not get lost in the pandemonium and to stay informed about how Bitcoin is pr... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/future-of-bitcoin-cc6936ba0b99/</link>
                <guid isPermaLink="false">66c34b1f9972b7c5c7624e58</guid>
                
                    <category>
                        <![CDATA[ Bitcoin ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Blockchain ]]>
                    </category>
                
                    <category>
                        <![CDATA[ business ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 02 Dec 2017 21:34:27 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*FfRqOEiRKdgvnbuvEgQF6g.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Subhan Nadeem</p>
<p>Bitcoin (BTC) recently smashed an all-time high of $11,400 USD and subsequently dropped to as low as $8,595 within a few hours. It’s incredibly important to not get lost in the pandemonium and to stay informed about how Bitcoin is progressing technologically.</p>
<p>Anybody considering buying Bitcoin should at the very least learn two things:</p>
<ol>
<li>the history of the technology behind Bitcoin</li>
<li>and more importantly, what lies ahead in Bitcoin’s future.</li>
</ol>
<p>As Bitcoin expert <a target="_blank" href="https://www.freecodecamp.org/news/future-of-bitcoin-cc6936ba0b99/undefined">Andreas M. Antonopoulos</a> says, “<a target="_blank" href="https://www.youtube.com/watch?time_continue=328&amp;v=6uXAbJQoZlE">Invest in education instead of speculation</a>.”</p>
<p>With Bitcoin and its underlying blockchain being such incredibly new technological concepts, it can seem daunting at times to try and research and understand its underlying technical details. This article is written in an effort to highlight the scalability problem Bitcoin faces, and what expected or proposed solutions to that problem are. There are some really exciting ones out there that this article discusses!</p>
<p>I wrote this as I was learning about Bitcoin myself, to aggregate the great amount of information about Bitcoin’s future from countless sources out there. When writing this, I kept in mind even those who don’t possess a programming background. However, it is assumed that the reader has a very basic understanding of Bitcoin as a currency and what a blockchain is. Coindesk has a great 5-minute read that should get you up to speed <a target="_blank" href="https://www.coindesk.com/information/what-is-bitcoin/">here</a> if you’re just starting out with Bitcoin or if you need a refresher.</p>
<p>Let’s begin with the scalability problem Bitcoin faces.</p>
<h3 id="heading-the-transaction-throughput-problem"><strong>The Transaction Throughput Problem</strong></h3>
<p>When Bitcoin was first introduced to the world, its creator Satoshi Nakomoto described Bitcoin in the <a target="_blank" href="https://bitcoin.org/bitcoin.pdf">Bitcoin whitepaper</a> as “A purely peer-to-peer version of electronic cash would allow online payments to be sent directly from one party to another without going through a financial institution.”</p>
<p>One of Bitcoin’s fundamental values was instant and secure peer-to-peer payment transactions. Now, more than ever, Bitcoin is emerging as the prevailing cryptocurrency in the global market, with a 1,200%+ increase in value over the last year alone.</p>
<p>Because of this unprecedented growth, the number of transactions on the Bitcoin blockchain has also increased, with up to <a target="_blank" href="https://blockchain.info/charts/n-transactions">400,000 transactions per day</a> being conducted. This rapid increase in transactions is posing to be a serious scalability problem for the blockchain, with <a target="_blank" href="https://blockchain.info/unconfirmed-transactions">over 90,000 transactions</a> being backlogged as unconfirmed at the moment.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/m1XCF1AdMMjgWci2o6kSeZc7cbza6Jx5qqEx" alt="Image" width="600" height="400" loading="lazy">
<em>As Bitcoin’s price skyrockets, so does its usage. Note the stagnation at around 400,000 transactions per day</em></p>
<p>In order to understand why transactions are being backlogged, Bitcoin transactions must first be explained.</p>
<p>Every time a user sends a Bitcoin transaction from his or her wallet to another, the transaction is added into the <strong>memory pool</strong> (mempool), which is essentially a pool of all unconfirmed transactions in the Bitcoin network. This pool is upheld by individual memory pools on machines that also hold a copy of the blockchain ledger, called <strong>nodes</strong>.</p>
<p>From the mempool, miners select transactions that they want to verify. Once miners validate a transaction (i.e. confirm that the sender actually has enough bitcoins to send to the receiver), they add it to a new block, which is eventually published to the blockchain. Other nodes then iterate through this newly published block’s transactions to ensure the block is valid, before accepting the block as a part of its ledger.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/q66a8vy5M3q75z3HZY9r9mqhDkkVa5pY8Y6F" alt="Image" width="600" height="400" loading="lazy">
_A diagram of the transaction lifecycle, source:[ weusecoins.com](https://www.weusecoins.com/en/questions/" rel="noopener" target="<em>blank" title=")</em></p>
<p>Let’s calculate the throughput of transactions:</p>
<ul>
<li>The median transaction size <a target="_blank" href="https://tradeblock.com/blog/analysis-of-bitcoin-transaction-size-trends">approximately 250 bytes</a></li>
<li>A block’s size is limited to 1MB (1000000 bytes)</li>
<li>Thus, a block holds around 4000 transactions (1MB divided by 250 bytes)</li>
<li>A block can only be published to the blockchain once every 10 minutes on average (600 seconds).</li>
<li>4000 transactions (at most) are published every 600 seconds, at a rate of <strong>6.66 transactions / second</strong></li>
</ul>
<p>With over 90,000 unconfirmed transactions in the mempool, how does a miner select which transactions to verify? Transaction fees! The sender of a transaction has the option of adding a custom transaction fee to its transaction intended for the miner, incentivizing a miner to select the transaction and have it verified faster. Miners will select the transactions that have the highest fee attached to them to maximize profits. Theoretically, you can send a transaction with no fee. But if there are transactions that have fees higher than yours in the pool, why would yours ever get picked?</p>
<p>As Bitcoin’s user base grows, so does the average transaction fee. At most, there are only 7 transactions that are processed every second and everyone wants to get their transaction verified first. At the moment, the average transaction fee is approximately <a target="_blank" href="https://bitinfocharts.com/comparison/bitcoin-median_transaction_fee.html">$3.58 USD</a>. This fee is certainly not ideal — if you want to send your friend a couple of dollars worth of bitcoin, you may end up spending more in transaction fees than the transaction value itself! Therein lies the problem, and if all else remains equal, transaction fees can be expected to rise due to the transaction bottleneck.</p>
<h3 id="heading-solving-the-throughput-problem"><strong>Solving the Throughput Problem</strong></h3>
<p>A proposed solution to this bottleneck that has brought great controversy to the Bitcoin community is to simply raise the block size from the original 1MB limit, thus allowing more transactions per block.</p>
<p>Every time the block size is increased in the chain, a <strong>hard fork</strong> is required, meaning an entirely new copy of the chain must be created, therefore requiring consensus from the Bitcoin community. Because millions of people use Bitcoin, gaining consensus is difficult and efforts should be made to avoid it. Furthermore, although the block size can be increased enough to accommodate the current backlog of transactions, as Bitcoin’s userbase continues to grow, there will eventually be another backlog of unconfirmed transactions, so another block size increase will be needed, and subsequently another hard fork.</p>
<p>So why don’t we just make the block size large enough to ensure the throughput will never be a bottleneck, no matter how many people are using it? First, the mathematics of a block size even remotely large enough to handle mass adoption are impractical and will restrict mining to incredibly powerful machines that only large corporations will be able to maintain, introducing an element of centralization.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ECmTOfKD1GulkUvxK75hXDY-bfSxV47U5XZS" alt="Image" width="600" height="400" loading="lazy">
_Given a block size big enough for just one city’s population, it would restrict node hosting and mining to only those with the most powerful machines, i.e. massive businesses, source: [Lightning Network](https://lightning.network/lightning-network.pdf" rel="noopener" target="<em>blank" title=")</em></p>
<p>Furthermore, recall that once a block is mined, all other nodes must validate the block before accepting it. If the block size was incredibly large and somebody were to publish an invalid block, nodes would waste a large amount of time attempting to validate the block before discarding it as invalid and moving onto the next block. A denial of service attack can essentially be orchestrated by repeatedly publishing insanely large invalid blocks to the network, stopping valid blocks from being processed for a long period of time. As stated by blockchain pioneer Nick Szabo in <a target="_blank" href="https://medium.com/@giftedproducts/cryptocurrencies-with-tim-ferriss-nick-szabo-and-naval-ravikant-51a99d037e04">this interview</a>, the small block size acts as a technical security parameter to prevent network flooding.</p>
<p>You can read more about the full impact of an increased block size if Bitcoin were to take over the world, in an article I’ve written <a target="_blank" href="https://hackernoon.com/if-we-lived-in-a-bitcoin-future-how-big-would-the-blockchain-have-to-be-bd07b282416f">here</a>.</p>
<p>If we can’t increase the block size, what can we do? Luckily, there are several solutions in the works that are expected to be deployed in order to solve this issue.</p>
<h3 id="heading-segregated-witness-segwit"><strong>Segregated Witness (SegWit)</strong></h3>
<p>Segregated Witness (SegWit) has actually already been implemented into the Bitcoin network, as of August 2017. It’s a fundamental network change that modifies the format of transactions, essentially slimming them down in size, and allowing more transactions to be fit into a block which increases throughput. SegWit is considered a <strong>soft fork</strong>, meaning it is completely backwards compatible with existing Bitcoin protocol, although nodes and wallets must upgrade to take advantage of all SegWit features.</p>
<p>Each transaction has a signature from the sender, or in other words, <strong>witness data</strong>; this is usually the largest part of the transaction. This data is not actually necessary to verify the transaction, and so SegWit moves this data to the end of the transaction, <em>segregating</em> it. If this transaction is sent to a legacy node (a node that has not upgraded to SegWit), the node strips the witness data off the end of the transaction before inserting it into a block, thus reducing the overall transaction size and saving space. The added benefit of this is that nodes can no longer modify the witness data, changing who the transaction was from, an ability nodes previously had. This makes way for the implementation of multi-layer solutions that we’ll discuss soon. Users also save on transaction fees, as they’re usually calculated per transaction byte, and SegWit reduces total transaction size.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/RQWDpa1anH8EhImUStwrg2um6WGO4Mybsn6w" alt="Image" width="600" height="400" loading="lazy">
_SegWit moves signature data to the end of transaction, after which stripped before being stored in a block, source: [Programming Blockchains](https://programmingblockchain.gitbooks.io/programmingblockchain/content/other_types_of_ownership/p2wpkh_pay_to_witness_public_key_hash.html" rel="noopener" target="<em>blank" title=")</em></p>
<p>Furthermore, SegWit changes the definition of a block: instead of a block being defined in terms of bytes, its now defined in terms of “weights”; a block can have a maximum weight of 4,000. Legacy transactions have a weight of 4, while SegWit transactions have a weight of 0.25, thus enabling a block to contain many more SegWit transactions and have a slightly higher size (approximately 2 megabytes at most). Nodes must upgrade to SegWit to follow this definition, and wallets must incorporate SegWit in order to send SegWit transactions. As a result, SegWit adoption has been slow, accounting for only 12% of current traffic.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/RssMxAEgr5MxnLkR4SCSXEHhBi9ZuPzeU-oG" alt="Image" width="600" height="400" loading="lazy">
_Current state of SegWit adoption hovers around 12% of all transactions, source: [segwit.party](http://segwit.party/charts/" rel="noopener" target="<em>blank" title=")</em></p>
<p>Because of the aforementioned benefits of SegWit, I highly encourage anybody reading this to use wallets that have incorporated SegWit to speed up SegWit adoption. A neat list of them can be found <a target="_blank" href="https://bitcoincore.org/en/segwit_adoption/">here</a> (my personal favourite is <a target="_blank" href="https://samouraiwallet.com/">Samourai Wallet for Android</a>). If you want to learn more about the intricacies of SegWit, <a target="_blank" href="https://www.freecodecamp.org/news/future-of-bitcoin-cc6936ba0b99/undefined">Jimmy Song</a> has written a great article about it:</p>
<p><a target="_blank" href="https://medium.com/@jimmysong/understanding-segwit-block-size-fd901b87c9d4"><strong>Understanding Segwit Block Size</strong></a><br><a target="_blank" href="https://medium.com/@jimmysong/understanding-segwit-block-size-fd901b87c9d4">_After I wrote my last article, I was surprised by the protest about the 2MB part of the title (the title has since been…_medium.com</a></p>
<h3 id="heading-multi-layered-solutions"><strong>Multi-Layered Solutions</strong></h3>
<p>As it stands, the Bitcoin blockchain isn’t very feasible for micropayments. If you want to buy a $2 cup of coffee, you’re probably going to pay more than $2 equivalent of BTC in transaction fees, and the transaction won’t be confirmed instantly — you must wait for the transaction to be published in a verified block on the chain, which will appear within 10 minutes at best.</p>
<p>Second and third layer solutions are networks layered on top of the Bitcoin blockchain that enable users to send several transactions of small amounts of Bitcoin almost instantly, with no transaction fees.</p>
<p><strong>The Lightning Network</strong> is this layered network currently in development expected to alleviate Bitcoin’s scaling problems. This network consists of two additional layers and enables users to open direct channels between each other to send an effectively unlimited number of payments to each other in an instant manner.</p>
<p><a target="_blank" href="https://lightning.network/"><strong>Lightning Network</strong></a><br><a target="_blank" href="https://lightning.network/">_The Lightning Network is dependent upon the underlying technology of the blockchain. By using real Bitcoin/blockchain…_lightning.network</a></p>
<h4 id="heading-the-second-layer">The Second Layer</h4>
<p>A user joins the second layer network by conducting a transaction on the blockchain that declares the user is committing a certain number of bitcoin to be used in the layered network. The user then joins a group of nodes that are interconnected with one another, called <strong>channel factories</strong>. These nodes essentially uphold a lobby of individuals that potentially want to conduct transactions with one another. Channel factories then enable an unlimited number of micropayment channels to be created on the third layer (hence the name factories) between individual parties.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/qAGFrJUk1ARYlpbaAplzwIhEEpBu0asvsL-c" alt="Image" width="600" height="400" loading="lazy">
_From the [whitepaper](https://www.tik.ee.ethz.ch/file/a20a865ce40d40c8f942cf206a7cba96/Scalable_Funding_Of_Blockchain_Micropayment_Networks%20(1).pdf" rel="noopener" target="<em>blank" title="): users are hooked into a channel factory upon joining the network, which then allocates multiple micropayment channels</em></p>
<h4 id="heading-the-third-layer">The Third Layer</h4>
<p>Micropayment channels are set up to ensure direct payments between two users on the third layer. Because the blockchain is no longer present in this layer, it cannot be used to validate transactions and ensure one party paid the other. Instead, smart-contract technology is employed, such as <strong>multisig addresses</strong>, meaning addresses that can be signed off by multiple users to enable the movement of funds, and <strong>hashed time-lock contracts</strong>, which are cryptographically secure automated contracts that lock funds for a certain period of time to ensure one parties that cannot cheat with another. These technologies eliminate the need for trust between users that are connected in micropayment channels.</p>
<p>Here is an example of how a Lightning Network micropayment channel works:</p>
<ol>
<li>Alice wants to dedicate 1 Bitcoin to a micropayment channel between Bob. She declares this 1 Bitcoin to be used in a <strong>commitment transaction</strong> on the Bitcoin blockchain. This 1 Bitcoin is then locked up in a <strong>multisig address</strong> that both parties can sign off on if they want to close the channel. This address is secured with a <strong>hashed time-lock contract</strong> which states, “Alice has 1 BTC and Bob has 0 BTC, to be released in one hour”. This means the 1 Bitcoin Alice has is locked for 1 hour after which it will be returned to Alice and published to the Bitcoin blockchain once more.</li>
<li>Alice then decides to give Bob 0.1 BTC. This transaction is logged with a new hashed time-lock contract stating “Alice has 0.9 BTC and Bob has 0.1 BTC, to be expired in 50 minutes”. This contract has an expiry time of 50 minutes, meaning it will be published to the blockchain before the original contract stating Alice has 1 BTC. Therefore Bob instantly knows he has the 0.1 BTC because this new contract will be published to the blockchain before the original contract, essentially making the old contract invalid.</li>
<li>Once the full hour passes, the micropayment channel closes and the final balance between Alice and Bob is published to the blockchain. If Alice and Bob want to continue making transactions, they can extend the expiry time of their channel for as long as they want. If one of them wants to close the channel early, one of them needs to sign off on the original multisig address that the Bitcoin is stored in.</li>
</ol>
<p>The network enables transactions to route itself to its final destination by using other connected users in the channel as intermediaries. This can happen even if a direct connection to the desired user isn’t able to be sought the current micropayment channel. For example, if Alice has a channel open with Bob, and Bob has a channel with Mark, and Alice wants to send Mark some Bitcoin, the network can route the payment to Mark through Bob, all while ensuring no party has to trust another.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/eP3V3chCxIuojC--P0bztS60medVbfOkZh3u" alt="Image" width="600" height="400" loading="lazy">
<em>In the lightning network, transactions are routed through intermediate users in order to reach its final destination</em></p>
<p>The implementation of lightning network transactions and their trust-less nature can get incredibly complex, and is best explained by the Lightning developers in <a target="_blank" href="https://www.youtube.com/watch?v=8zVzw912wPo">this conference</a> or in the following series by <a target="_blank" href="https://www.freecodecamp.org/news/future-of-bitcoin-cc6936ba0b99/undefined">ecurrencyhodler</a>:</p>
<p><a target="_blank" href="https://medium.com/the-litecoin-school-of-crypto/a-primer-to-the-lightning-network-part-1-be909c403bde"><strong>The Lightning Network (Part 1)</strong></a><br><a target="_blank" href="https://medium.com/the-litecoin-school-of-crypto/a-primer-to-the-lightning-network-part-1-be909c403bde">_Multisig Addresses: The Building Blocks of the Lightning Network_medium.com</a></p>
<p>Ideally, a user will only create a commitment transaction to the secondary layer very rarely because he or she will remain in the layered network for prolonged periods of time to conduct most of their day-to-day transactions. Once a user wants to exit this multi-layered network, a <strong>settlement transaction</strong> is made on the blockchain declaring the user’s final Bitcoin balance after all of the second-layer activities. This reconciles their total Bitcoin balance on the blockchain after comparison with the original commitment transaction. In total, only two blockchain transactions are made in order to let the user to conduct a limitless number of transactions for free on the second layer.</p>
<p>As mentioned previously, SegWit paves the way for the lightning network because it removes nodes’ abilities to modify witness data, which is what is used to identify a user’s entry into the second layer. If the user’s commitment transaction can’t be found because the witness data referring to the user was changed, there is a greater level of difficulty involved when trying to reconcile the user’s settlement transaction.</p>
<p>The second layer of the lightning network involving channel factories was very recently introduced in <a target="_blank" href="https://www.tik.ee.ethz.ch/file/a20a865ce40d40c8f942cf206a7cba96/Scalable_Funding_Of_Blockchain_Micropayment_Networks%20(1).pdf">this whitepaper</a>. It is still under heavy development, so a lot of its concepts are explained abstractly. However, the network is poised to launch in 2018 and will be by far the biggest improvement in transaction scalability thus far.</p>
<h3 id="heading-schnorr-signatures"><strong>Schnorr Signatures</strong></h3>
<p>When a user sends a Bitcoin transaction, the inputs of the transaction (the amount you’re sending) is calculated simply by retrieving from the blockchain the total unspent amounts of Bitcoin you previously received. So for example:</p>
<ul>
<li>Starting with an empty wallet, I receive 1 Bitcoin in transaction #1, and then another 1 Bitcoin in a separate transaction #2</li>
<li>I now want to send 2 Bitcoins in a transaction. There will be two inputs to this transaction: transaction #1, and transaction #2, summing up to 2 Bitcoin</li>
</ul>
<p>Under the current algorithm for generating signatures (Elliptic Curve Digital Signature Algorithm), each input requires its own signature. This increases the total transaction size and therefore increases the transaction fee.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/SXBrtQeJUNd--9Vh5s7jHj6pdOqylGDosB01" alt="Image" width="600" height="400" loading="lazy">
<em>Currently, each input requires a signature, increasing total transaction size</em></p>
<p><a target="_blank" href="https://bitcoincore.org/en/2017/03/23/schnorr-signature-aggregation/">Schnorr signatures</a> are an alternative and more efficient way of storing signature data in transactions. All inputs are accumulated and then stored as a single signature by utilizing the Schnorr algorithm, which greatly saves space in a transaction and further helps increase transaction throughput by allowing blocks to store more transactions on average.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/caYd8iXKfgyxSJxDEmRIXnZ1KwZx37kZhF2Y" alt="Image" width="600" height="400" loading="lazy">
<em>All sender signatures are stored as one signature under the Schnorr algorithm</em></p>
<p>Schnorr signatures can be also be used to aid Bitcoin’s advancement in privacy by benefiting CoinJoin transactions. CoinJoin is a method of introducing anonymity to Bitcoin transactions. It works by pooling transaction inputs together with other peoples’ transactions when making a payment to a receiver. When payments are pooled, it becomes difficult to track which user sent what input, effectively making them anonymous. However, CoinJoin transactions have increased fees due to a higher number of inputs in a single transaction resulting in a higher number of signatures. Utilizing Schnorr signatures would enable all signatures in a transaction to be compressed into one, saving greatly on transaction fees and encouraging the use of CoinJoin.</p>
<p>Furthermore, Schnorr paves the way for complex multisig transactions which require signing off from multiple parties; no matter how many parties’ signatures are required for a transaction, all the transaction needs is one Schnorr signature.</p>
<p>Schnorr signatures are only now a possibility because of the implementation of SegWit; because signature data can’t be modified by third parties, it can now be used to effectively create a Schnorr signature.</p>
<h3 id="heading-mimblewimble"><strong>MimbleWimble</strong></h3>
<p>MimbleWimble is a radical but incredibly powerful proposed change to Bitcoin architecture that was anonymously introduced through this <a target="_blank" href="https://download.wpsoftware.net/bitcoin/wizardry/mimblewimble.txt">whitepaper</a> in July 2016.</p>
<p>Named after the <a target="_blank" href="http://harrypotter.wikia.com/wiki/Tongue-Tying_Curse">tongue-tying curse from the Harry Potter series</a>, its aim is to remove transactions entirely from blocks. Under MimbleWimble, transactions consist of nothing but input amounts, output amounts, and a signature. The signature of the transaction can only be decrypted by the receiver, and so transaction verification is left to the receiver.</p>
<p>By extension, blocks consist of only the list of all transaction input amounts of all transactions, all transaction output amounts, and their corresponding signatures. Blocks can then be merged seamlessly with previous blocks as they’re nothing but pairs of input and output amounts. Nodes then have the ability to cryptographically ensure that transactions in blocks do not create extra bitcoins (i.e. their net difference between inputs and outputs in blocks is 0) without having to decrypt transactions.</p>
<p>This removal of transaction storage grants complete anonymity to all users by stripping away the ability to generate transaction history. Furthermore, with blocks only containing the <strong>unspent transaction outputs (</strong>meaning the number of Bitcoins that have been received in an address but not moved out yet), the blockchain size can be reduced by over 60% according to the whitepaper. This reduction in size means that in order to validate a MimbleWimble blockchain, nodes will only need to look at the set of unspent transaction outputs instead of the entire set of transactions, which will exponentially increase performance.</p>
<p>The mathematical details of MimbleWimble are outside of the scope of this article, but are explained in detail in the <a target="_blank" href="https://scalingbitcoin.org/papers/mimblewimble.txt">whitepaper</a>. Although MimbleWimble presents some clear advantages and technical breakthroughs, its implementation requires the removal of Bitcoin’s Script system that much of the existing architecture relies on. As a result, MimbleWimble’s implementation on the Bitcoin blockchain is not technically feasible.</p>
<p>However, there are proposals for MimbleWimble to exist as a <strong>sidechain.</strong> A sidechain is a separate blockchain directly attached to the Bitcoin blockchain through the use of a two-way peg. This peg enables assets between the two chains to be exchanged and “pegs” the value of the sidechain asset to the value of Bitcoin. In this setup, users would be able to exchange Bitcoins for MimbleWimble coins, conduct completely private and rapid transactions on the MimbleWimble chain, and then exchange their MimbleWimble coins for Bitcoin whenever they please.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/bWHCCfekdQ71xVXhKFRS5HcXxBCkUf3jFHA-" alt="Image" width="600" height="400" loading="lazy">
_Sidechain coins are pegged to the Bitcoin blockchain, operating alongside it with a fixed exchange rate, source: [Blockchain.com](http://blockchain.com" rel="noopener" target="<em>blank" title=")</em></p>
<p>In fact, a group of developers are already in the process of developing MimbleWimble as a separate cryptocurrency called <a target="_blank" href="https://github.com/mimblewimble/grin">GRIN</a>; it was recently deployed on a test network and may be launched in the near future.</p>
<h3 id="heading-rootstock"><strong>Rootstock</strong></h3>
<p><a target="_blank" href="https://medium.com/@CryptoIQ.ca/rootstock-smart-contracts-on-the-bitcoin-blockchain-e52b065421a8"><strong>Rootstock — Smart Contracts on the Bitcoin Blockchain</strong></a><br><a target="_blank" href="https://medium.com/@CryptoIQ.ca/rootstock-smart-contracts-on-the-bitcoin-blockchain-e52b065421a8">_As a concept the Rootstock [1] platform is one of those ideas that once it is proposed it is obvious that it is a great…_medium.com</a></p>
<p>Rootstock is for whatever reason one of the less talked about advancements in Bitcoin technology but is by far one of the coolest. Rootstock is described as “the first open-source smart contract platform with a 2-way peg to Bitcoin that also rewards the Bitcoin miners via merge-mining, allowing them to actively participate in the Smart Contract revolution.”</p>
<p>Much like MimbleWimble, Rootstock is being developed as a sidechain solution to the Bitcoin blockchain. Its fundamental value lies in its focus in smart contracts. Rootstock aims to be a <a target="_blank" href="https://simple.wikipedia.org/wiki/Turing_complete">Turing Complete</a> (completely programmable) smart-contracts platform that will be backwards compatible with Ethereum’s virtual machine. This means that Rootstock will be able to execute any smart contracts developed for the Ethereum platform and have smart contracts developed for its own platform.</p>
<p>Rootstock aims to implement this versatile smart-contract functionality all while leveraging Bitcoin’s comparatively dominant userbase and value by acting as a two-way pegged sidechain. It is also being designed to be secured by the existing Bitcoin mining network, therefore not needing to incentivize miners to secure its own blockchain. Rootstock also aims to tackle the transaction scalability problem by implementing its own version of a multi-layered solution called <a target="_blank" href="https://uploads.strikinglycdn.com/files/9dcb08c5-f5a9-430e-b7ba-6c35550a4e67/LuminoTransactionCompressionProtocolLTCP.pdf">Lumino</a>. With this, it may be able to accomplish up to 20,000 transactions per second.</p>
<p>Rootstock is aiming for <a target="_blank" href="https://www.coindesk.com/bitcoin-startup-rsk-launch-smart-contracts-sidechain-2017/">a launch by the end of 2017</a>. Overall, the platform aims to fit in perfectly alongside Bitcoin and if its claims hold true, it will undoubtedly bring unprecedented utility to the Bitcoin network.</p>
<p>If you’ve gotten this far, congratulations! I hope you were able to learn something about the future of Bitcoin and are as excited about it as I am.</p>
<p>Bitcoin isn’t perfect and is faced with challenges that its community must work to solve. However, it is backed by an incredibly dedicated and thriving developer community that is working day in and day out to tackle these problems. There are constant innovations happening everyday, and I am sure by the time you finished reading this another new and exciting proposal for the Bitcoin blockchain popped up.</p>
<p>This article by no means covers everything out there; if there’s anything that you’re aware of that I didn’t mention, please mention them in the comments!</p>
<p><strong>Follow me on <a target="_blank" href="https://twitter.com/SubhanNadeem19">Twitter</a> and Medium if you’re interested in more in-depth and informative write-ups like these in the future!</strong></p>
<p><em>I’m a relative Bitcoin beginner myself so if there are any mistakes or if you have any feedback please don’t hesitate let me know!</em></p>
<p><em>BTC Address: 3MGguJhw1bm95tDQjZ3b8ySBwZLJ77CgG1</em></p>
<p><em>Here are some resources if you’re interested in learning more:</em></p>
<ul>
<li><a target="_blank" href="https://github.com/bitcoinbook/bitcoinbook"><em>Mastering Bitcoin</em></a><em>, an comprehensive book written by <a target="_blank" href="https://www.freecodecamp.org/news/future-of-bitcoin-cc6936ba0b99/undefined">Andreas M. Antonopoulos</a></em></li>
<li><a target="_blank" href="http://bitcoin.it"><em>The Bitcoin Wiki</em></a></li>
<li><a target="_blank" href="https://lopp.net/pdf/bitcoin.pdf"><em>The Bitcoin whitepaper</em></a></li>
<li><a target="_blank" href="https://lopp.net/bitcoin.html"><em>A collection of Bitcoin resources</em></a> <em>by <a target="_blank" href="https://www.freecodecamp.org/news/future-of-bitcoin-cc6936ba0b99/undefined">Jameson Lopp</a></em></li>
<li><a target="_blank" href="https://www.google.ca/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=2&amp;cad=rja&amp;uact=8&amp;ved=0ahUKEwiznZ-Oo-zXAhUW02MKHZ0aAhcQtwIILzAB&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3FA3UjA0igY&amp;usg=AOvVaw0JIy-AaKaXyDsGm8psm7Qj"><em>This highly informative interview with Nick Szabos</em></a> <em>conducted by <a target="_blank" href="https://www.freecodecamp.org/news/future-of-bitcoin-cc6936ba0b99/undefined">Tim Ferriss</a></em></li>
<li><a target="_blank" href="https://www.youtube.com/channel/UCrYmtJBtLdtm2ov84ulV-yg"><em>Ivan on Tech on Youtube</em></a><em>, who is absolutely amazing at breaking down technical Bitcoin concepts</em></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
