Mathew K Analytics

Lesson 17 · Real-World Data Analytics

Ethereum Data Analysis in Python: Price, Volatility & On-Chain Data | Data Analytics #17

Crypto data is more than a price chart. We analyse Ethereum's early trading history in pandas alongside on-chain activity (active addresses, transactions,…

What you'll learn

Datasets used in this lesson

Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.

📓 Full notebook

Download .ipynb

Data Analytics 100, Video 17: Real Cryptocurrency Market Analysis#

  • Video seventeen of the hundred-video real-world data analytics series.
  • Analyzing Ethereum's own real early trading history, real on-chain activity included, not just a price chart.
  • Let's get into it.

This lesson is for learners who have analysed stock prices and want to see how the same tools behave on a far more volatile asset. The business question is: how risky was Ethereum in its earliest months, and did its price follow real use of the network, or something else?

The dataset, eth_price_onchain.csv, covers 158 days of Ethereum's early trading from August 2015 to January 2016. Alongside the daily price (PriceUSD) and market capitalisation (CapMrktCurUSD), it holds on-chain metrics, which are figures recorded on the blockchain itself: transaction count (TxCnt), active addresses (AdrActCnt), mining hash rate (HashRate) and trading volume (VolumeUSD).

In this lesson you will:

  • measure returns, annualised volatility, drawdown, Value-at-Risk, skewness and kurtosis for a crypto asset
  • relate price to network activity and trading volume with correlations
  • resample daily data to weekly returns and run a simple, lagged momentum backtest

Prerequisites: you should be comfortable with pct_change, rolling windows and cumprod from the earlier stock lessons, especially the backtesting video.

Part 1: Crypto Data Includes More Than Price#

Crypto datasets often come with more than prices. Because every transaction is public on the blockchain, you also get usage figures that act a little like company fundamentals. This step imports pandas, numpy and matplotlib and loads eth_price_onchain.csv, using parse_dates=['Date'] so dates become real datetimes for plotting and resampling. The output (158, 7) shows 158 daily rows and 7 columns. That is a short history, so treat every statistic in this lesson as an early snapshot rather than a long-term truth.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
eth = pd.read_csv('eth_price_onchain.csv', parse_dates=['Date'])
eth.shape
(158, 7)

Part 2: Real Data Preview#

Before any analysis you should know exactly which columns you have. The code calls eth.head(3) and then eth.columns.tolist(), but Jupyter only displays the last expression, so the output is just the list of column names: Date, PriceUSD, CapMrktCurUSD, TxCnt, AdrActCnt, HashRate and VolumeUSD. To see the first rows as well, run eth.head(3) on its own. Make a note of the cryptic names now, for example AdrActCnt means active addresses, so later steps read easily.

eth.head(3)
eth.columns.tolist()
['Date',
 'PriceUSD',
 'CapMrktCurUSD',
 'TxCnt',
 'AdrActCnt',
 'HashRate',
 'VolumeUSD']

Part 3: Real Price History#

A price chart gives you context before you calculate anything. The code draws PriceUSD against Date with plt.plot, labels the axes, and saves the figure to eth_price_history.png with plt.savefig, then closes it with plt.close(), so nothing appears inline. Open the saved file and look for the shape of the period: an early spike in mid-August 2015, a long slide afterwards, and how far the price ends from where it started. Those features explain the extreme numbers in the steps that follow.

plt.figure(figsize=(11, 5))
plt.plot(eth['Date'], eth['PriceUSD'], color='darkslateblue')
plt.xlabel('Real Date')
plt.ylabel('Real Price (USD)')
plt.title("Real Ethereum Price, Aug 2015 to Jan 2016")
plt.tight_layout()
plt.savefig('eth_price_history.png', dpi=120)
plt.close()

Part 4: Real Daily Returns#

Returns, not prices, are what you compare across assets and periods. pct_change() computes each day's percentage change in PriceUSD, leaving the first row empty, and describe().round(4) summarises them. The output shows 157 returns with a mean of 0.47% a day but a standard deviation of about 9.99%. The worst day lost 23.71% and the best gained 46.34%, while the median day was slightly negative at -0.29%. A daily spread of nearly 10% is enormous compared with typical stocks.

eth['Return'] = eth['PriceUSD'].pct_change()
eth['Return'].describe().round(4)
count    157.0000
mean       0.0047
std        0.0999
min       -0.2371
25%       -0.0450
50%       -0.0029
75%        0.0479
max        0.4634
Name: Return, dtype: float64

Part 5: Real Annualized Volatility, Crypto vs Stocks#

Annualised volatility lets you compare risk across assets on the same scale. Crypto trades every day of the year, so the daily standard deviation is scaled by np.sqrt(365) instead of the np.sqrt(252) trading days used for stocks. Volatility grows with the square root of time, which is why the square root appears. The output is 190.8%, meaning a one-standard-deviation move over a year would be almost twice the price. Using 252 for crypto is a common mistake that understates the risk.

eth_annual_vol = eth['Return'].std() * np.sqrt(365)
round(eth_annual_vol * 100, 1)
np.float64(190.8)

Part 6: Real Best and Real Worst Single Days#

Extreme days show what an investor actually had to sit through. idxmax() and idxmin() return the row label of the largest and smallest return, and eth.loc[..., 'Date'] looks up the matching date. The output shows the best day was 13 August 2015 at +46.3% and the worst was 4 November 2015 at -23.7%. Note that the best day came just days after trading began, when prices were very thin, so early outliers like this can dominate summary statistics.

eth_best_day = eth.loc[eth['Return'].idxmax(), 'Date']
eth_best_pct = round(eth['Return'].max() * 100, 1)
eth_worst_day = eth.loc[eth['Return'].idxmin(), 'Date']
eth_worst_pct = round(eth['Return'].min() * 100, 1)
eth_best_day, eth_best_pct, eth_worst_day, eth_worst_pct
(Timestamp('2015-08-13 00:00:00'),
 np.float64(46.3),
 Timestamp('2015-11-04 00:00:00'),
 np.float64(-23.7))

Part 7: Real Cumulative Growth#

Cumulative growth answers the simplest investor question: what happened to $1? The code fills the first missing return with 0 using `fillna(0)`, adds 1 to each return, and compounds with `cumprod()`. The output, 0.981, means $1 invested at the first price would be worth about $0.98 at the end, a loss of roughly 2%. That flat outcome hides huge swings in between, which is why drawdown and volatility are needed next.

eth['Cumulative'] = (1 + eth['Return'].fillna(0)).cumprod()
round(eth['Cumulative'].iloc[-1], 3)
np.float64(0.981)

Part 8: Real Maximum Drawdown#

Maximum drawdown is the largest fall from a previous peak to a later low, and it measures the worst pain an investor faced. cummax() tracks the highest cumulative value reached so far, the code measures how far each day sits below that peak as a fraction, and .min() picks the deepest point. The output is -77.7%, so at its worst Ethereum had lost more than three quarters of its peak value. A drawdown of this size requires a gain of over 300% just to get back to the high.

running_peak = eth['Cumulative'].cummax()
drawdown = (eth['Cumulative'] - running_peak) / running_peak
round(drawdown.min() * 100, 1)
np.float64(-77.7)

Part 9: Visualizing Real Drawdown#

A drawdown chart makes the depth and length of losses easy to see. plt.fill_between shades the area between the drawdown percentage and zero in crimson, so every dip below the previous peak appears as a filled region. The figure is saved to eth_drawdown.png and closed, so there is no inline output. When you open it, look at how quickly the drawdown appears after the August peak and whether the price ever climbs back to zero, which would mean a new high.

plt.figure(figsize=(11, 4))
plt.fill_between(eth['Date'], drawdown * 100, 0, color='crimson', alpha=0.6)
plt.xlabel('Real Date')
plt.ylabel('Real Drawdown (%)')
plt.title('Real Ethereum Drawdown from Peak')
plt.tight_layout()
plt.savefig('eth_drawdown.png', dpi=120)
plt.close()

Part 10: Real On-Chain Activity, Active Addresses#

On-chain activity tells you whether people are actually using the network. Active addresses count how many distinct addresses sent or received transactions each day. The code calls describe() on AdrActCnt, but that result is not displayed because it is not the last expression; the code then plots active addresses over time and saves active_addresses.png. Open the chart and look for whether usage grows steadily, stays flat, or jumps around. Run eth['AdrActCnt'].describe() separately to see the numbers.

eth['AdrActCnt'].describe().round(0)
plt.figure(figsize=(11, 4))
plt.plot(eth['Date'], eth['AdrActCnt'], color='teal')
plt.xlabel('Real Date')
plt.ylabel('Real Active Addresses')
plt.title('Real Ethereum Daily Active Addresses')
plt.tight_layout()
plt.savefig('active_addresses.png', dpi=120)
plt.close()

Part 11: Real Correlation, Price vs Real Network Activity#

If price reflected real usage, you would expect price and activity to move together. Series.corr() computes the Pearson correlation, a number from -1 to 1 where 0 means no straight-line relationship. The output is 0.02, essentially zero. Over these months, Ethereum's price and its number of active addresses were not linked in any meaningful linear way. Keep in mind that correlation only detects straight-line patterns, and with 158 days and a trending series, it is a rough indicator rather than proof.

price_activity_corr = eth['PriceUSD'].corr(eth['AdrActCnt'])
round(price_activity_corr, 3)
np.float64(0.02)

Part 12: Real Transaction Count Trend#

Transaction count is another measure of network use. The code runs describe() on TxCnt (not displayed, since it is not the last line), then compares the last day's count with the first using iloc[-1] / iloc[0] - 1. The output shows transactions grew by 277.0% over the period, almost quadrupling, while the price ended slightly lower. A first-versus-last comparison is sensitive to unusual single days, so it is worth checking the trend on a chart too.

eth['TxCnt'].describe().round(0)
tx_growth = eth['TxCnt'].iloc[-1] / eth['TxCnt'].iloc[0] - 1
round(tx_growth * 100, 1)
np.float64(277.0)

Part 13: Real Network Hash Rate#

Hash rate measures the total computing power securing the network through mining. Rising hash rate suggests miners expected the network to be worth supporting. As before, describe() runs but is not shown, and the displayed result is growth from the first to the last value. The output shows hash rate rose by 425.9%, more than five times its starting level. Together with transaction growth, this shows the network was expanding strongly even though the price went nowhere.

eth['HashRate'].describe().round(4)
hash_growth = eth['HashRate'].iloc[-1] / eth['HashRate'].iloc[0] - 1
round(hash_growth * 100, 1)
np.float64(425.9)

Part 14: Real Rolling 14-Day Volatility#

A single volatility number hides the fact that risk changes over time. rolling(14).std() computes the standard deviation of the last 14 daily returns at each point, and multiplying by np.sqrt(365) annualises it. dropna() removes the warm-up rows before describe(). The output covers 144 values with a median of 1.63 (163% annualised), a low of 0.50 and a high of 3.70. So even the calmest fortnight was around 50% annualised, and the wildest was about 370%.

eth['Vol14'] = eth['Return'].rolling(14).std() * np.sqrt(365)
eth['Vol14'].dropna().describe().round(2)
count    144.00
mean       1.66
std        0.76
min        0.50
25%        1.07
50%        1.63
75%        2.23
max        3.70
Name: Vol14, dtype: float64

Part 15: Visualizing Real Rolling Volatility#

Plotting rolling volatility shows when the market was calm and when it was turbulent. The code draws the 14-day annualised volatility against date and saves it to eth_rolling_vol.png, then closes the figure, so there is no inline output. When you open the chart, look for spikes, then check whether they line up with the best and worst days found earlier. Volatility tends to cluster: wild days are often followed by more wild days.

plt.figure(figsize=(11, 5))
plt.plot(eth['Date'], eth['Vol14'], color='darkorange')
plt.xlabel('Real Date')
plt.ylabel('Real Annualized 14-Day Volatility')
plt.title('Real Rolling Volatility, Ethereum')
plt.tight_layout()
plt.savefig('eth_rolling_vol.png', dpi=120)
plt.close()

Part 16: Real Market Cap vs Real Price#

Market capitalisation is price multiplied by the number of coins in circulation. Comparing its growth with price growth reveals changes in supply. The code computes first-to-last growth in CapMrktCurUSD. The output is 3.8%, while the price fell by about 2% over the same period. Market cap rose while price fell because new ether was being created through mining, increasing supply. For assets with growing supply, price alone understates how much total value changed.

cap_growth = eth['CapMrktCurUSD'].iloc[-1] / eth['CapMrktCurUSD'].iloc[0] - 1
round(cap_growth * 100, 1)
np.float64(3.8)

Part 17: Real Trading Volume Spikes#

Volume spikes often mark big news or panic. The code takes the median of VolumeUSD, a robust middle value not pulled around by extremes, and counts days where volume was more than three times that median. Comparing gives True or False for each row and .sum() counts the Trues. The output shows 17 such high-volume days out of 158, roughly one day in nine. Using the median rather than the mean avoids the spikes themselves inflating the threshold.

volume_median = eth['VolumeUSD'].median()
high_volume_days = (eth['VolumeUSD'] > volume_median * 3).sum()
high_volume_days
np.int64(17)

Part 18: Real Volume-Return Relationship#

Traders often say big moves come with big volume. To test this, the code takes the absolute value of each return with .abs(), so a 10% fall and a 10% rise both count as large moves, then correlates that with VolumeUSD. The output is 0.479, a moderate positive correlation: higher-volume days tended to be days with bigger price moves, in either direction. Using raw returns instead of absolute returns would mix rises and falls and hide this relationship.

abs_return = eth['Return'].abs()
volume_return_corr = eth['VolumeUSD'].corr(abs_return)
round(volume_return_corr, 3)
np.float64(0.479)

Part 19: Real Value-at-Risk for Crypto#

Value-at-Risk (VaR) estimates a bad-but-not-worst-case loss. The 95% one-day VaR is the return that only 5% of days fell below. The code uses np.percentile on the returns at the 5th percentile, after dropna() removes the empty first value. The output is -15.62%, meaning that on about one day in twenty, Ethereum lost more than 15.6%. This is historical VaR, so it assumes the future looks like this short, unusual past, and it says nothing about how bad the losses beyond that point can be.

var_95 = np.percentile(eth['Return'].dropna(), 5)
round(var_95 * 100, 2)
np.float64(-15.62)

Part 20: Real Skewness and Real Kurtosis#

Skewness and kurtosis describe the shape of returns beyond average and spread. Positive skew means a longer tail of large gains; kurtosis measures how heavy the tails are, and pandas reports excess kurtosis, where 0 matches a normal distribution. The output (0.783, 3.1) shows positive skew, driven by large up days such as the 46% jump, and an excess kurtosis of 3.1, meaning extreme moves occur much more often than a normal bell curve would predict. Models assuming normal returns will underestimate this risk.

eth_skew = eth['Return'].skew()
eth_kurtosis = eth['Return'].kurtosis()
round(eth_skew, 3), round(eth_kurtosis, 3)
(np.float64(0.783), np.float64(3.1))

Part 21: Real 7-Day Moving Average Smoothing#

Daily crypto prices are noisy, and a moving average helps you see the trend underneath. rolling(7).mean() averages the last seven daily prices, stored as MA7. The chart shows the raw price faded with alpha=0.4 and the 7-day average as a solid black line, and is saved to eth_smoothed_price.png without being shown inline. In the saved chart, notice how the average lags turning points by a few days. That lag is the price you pay for smoothness, and it matters in the backtest later.

eth['MA7'] = eth['PriceUSD'].rolling(7).mean()
plt.figure(figsize=(11, 5))
plt.plot(eth['Date'], eth['PriceUSD'], alpha=0.4, label='Real Daily Price')
plt.plot(eth['Date'], eth['MA7'], color='black', label='Real 7-Day Average')
plt.xlabel('Real Date')
plt.ylabel('Real Price (USD)')
plt.title('Real Ethereum Price with 7-Day Smoothing')
plt.legend()
plt.tight_layout()
plt.savefig('eth_smoothed_price.png', dpi=120)
plt.close()

Part 22: Real Weekly Return Aggregation#

Weekly returns are less noisy than daily ones and are often what investors report. The code sets Date as the index, then resample('W') groups days into calendar weeks ending on Sunday, and .last() takes the final price in each week before pct_change(). The output shows 23 weekly returns with a mean of 1.5%, a standard deviation of 19.1%, and a range from -33.9% to +58.6%. A typical week moved roughly as much as a stock might in a whole year.

eth_indexed = eth.set_index('Date')
weekly_return = eth_indexed['PriceUSD'].resample('W').last().pct_change()
weekly_return.dropna().describe().round(3)
count    23.000
mean      0.015
std       0.191
min      -0.339
25%      -0.099
50%       0.010
75%       0.084
max       0.586
Name: PriceUSD, dtype: float64

Part 23: Real Best and Real Worst Week#

Best and worst weeks are a vivid way to communicate risk. idxmax() and idxmin() store the dates of the extreme weeks, though they are not displayed. The displayed output shows the best week gained 58.6% and the worst lost 33.9%. To see which weeks these were, print best_week and worst_week. Weekly extremes are larger than daily ones because several big days can stack up in the same direction.

best_week = weekly_return.idxmax()
worst_week = weekly_return.idxmin()
round(weekly_return.max() * 100, 1), round(weekly_return.min() * 100, 1)
(np.float64(58.6), np.float64(-33.9))

Part 24: Real Simple Momentum Signal Backtest#

This step reuses the backtesting discipline from two videos earlier. The signal is 1 when the price is above its 7-day average, shift(1) lags it so you only trade on yesterday's information, and multiplying by the day's return gives the strategy return. Compounding with cumprod() gives the growth of $1. The output `(0.286, 0.981)` shows the momentum strategy turned $1 into about $0.29, versus $0.98 for simply holding. Note that no trading costs are charged here, so the real result would be even worse.

eth['MA_Signal'] = (eth['PriceUSD'] > eth['MA7']).astype(int)
eth['MA_Position'] = eth['MA_Signal'].shift(1).fillna(0)
eth['MA_Strategy_Return'] = eth['MA_Position'] * eth['Return']
strategy_growth = (1 + eth['MA_Strategy_Return'].fillna(0)).cumprod().iloc[-1]
round(strategy_growth, 3), round(eth['Cumulative'].iloc[-1], 3)
(np.float64(0.286), np.float64(0.981))

Part 25: Saving the Real Enriched Dataset#

Saving the enriched table keeps all the new columns, such as returns, rolling volatility and signals, for later use. eth.round(4) limits decimals to keep the file tidy, to_csv(index=False) writes it without an extra index column, and the file is read back to compare row counts. The output True confirms all 158 rows were saved. Be aware that rounding to four decimals slightly changes very small values, so keep the unrounded data if you need exact figures.

eth.round(4).to_csv('eth_enriched.csv', index=False)
reloaded = pd.read_csv('eth_enriched.csv')
reloaded.shape[0] == eth.shape[0]
True

Part 26: Real Sanity Check on Cumulative Growth#

A sanity check confirms your calculations agree with a simpler method. The final price divided by the first price should equal the compounded growth of daily returns, because compounding percentage changes simply rebuilds the price path. The code computes both and tests whether the difference rounds to below 0.000001. The output np.True_ confirms they match. Checks like this catch mistakes such as forgetting fillna(0) or misaligned rows, and they take one line.

manual_final_price_ratio = eth['PriceUSD'].iloc[-1] / eth['PriceUSD'].iloc[0]
round(abs(manual_final_price_ratio - eth['Cumulative'].iloc[-1]), 6) < 1e-6
np.True_

Part 27: Real Recap Print#

A one-sentence recap turns numbers into a message for a non-technical audience. The f-string combines the number of rows, the annualised volatility rounded to a whole number and the maximum drawdown. The printed output reads: across 158 early trading days, Ethereum realised 191% annualised volatility and a -77.7% maximum drawdown. Note that 158 is the number of rows, so it includes the first day that has no return, a small detail worth being precise about in reports.

print(f'Across {len(eth)} real early trading days, Ethereum realized {round(eth_annual_vol*100)}% annualized volatility and a {round(drawdown.min()*100,1)}% maximum drawdown, both far beyond anything seen from real stocks earlier in this domain.')
Across 158 real early trading days, Ethereum realized 191% annualized volatility and a -77.7% maximum drawdown, both far beyond anything seen from real stocks earlier in this domain.

Part 28: Real Fee Revenue Trend#

Before analysing a metric, check that it actually exists in your data. Some on-chain sources include total fees, often in a column like FeeTotNtv. The code tests whether that name appears in eth.columns with the in operator. The output is False, so fee data is not available in this file and the fee revenue trend cannot be analysed here. Checking for a column before using it avoids a KeyError and stops you drawing conclusions from data you do not have.

fee_col_present = 'FeeTotNtv' in eth.columns
fee_col_present
False

Part 29: Real Days of Extreme Moves#

Counting extreme days gives a simple, intuitive risk figure. The code filters rows where the absolute daily return is above 0.15, meaning the price moved more than 15% in either direction, and counts them with len(). The output is 19 days. With 157 daily returns, that is roughly one day in eight with a move larger than many stocks see in a month. Compare this with the VaR figure: both point to frequent, very large daily swings.

extreme_days = eth[eth['Return'].abs() > 0.15]
len(extreme_days)
19

Part 30: Real Comparison Table, Crypto vs Prior Stocks#

Putting Ethereum next to familiar stocks makes its risk concrete. The code builds a small DataFrame with Ethereum's annualised volatility from this lesson and the Apple and Tesla figures typed in from earlier videos. The output shows Ethereum at 190.8%, Tesla at 62.0% and Apple at 21.8%, so Ethereum was roughly three times as volatile as Tesla and almost nine times as volatile as Apple. Remember that the stock figures were annualised with 252 days and Ethereum with 365, and they cover different periods.

comparison_table = pd.DataFrame({'Asset': ['Ethereum (this video)', 'Apple (real, prior video)', 'Tesla (real, prior video)'], 'AnnualizedVolPct': [round(eth_annual_vol * 100, 1), 21.8, 62.0]})
comparison_table
Asset AnnualizedVolPct
0 Ethereum (this video) 190.8
1 Apple (real, prior video) 21.8
2 Tesla (real, prior video) 62.0

Wrap-Up: What You Learned#

  • Crypto markets genuinely trade every real day of the year, so annualizing volatility uses real 365 days instead of the real 252 trading days used for stocks.
  • Real on-chain metrics, active addresses, transaction counts, and hash rate, give crypto a real layer of fundamental data that ordinary stocks simply do not publish.
  • Volatility, drawdown, skewness, and kurtosis all confirmed the real same thing here: crypto in its early years moved far more violently than any real stock in this domain.
  • Price and real network usage do not always move together, a real reminder that speculation and real fundamentals can diverge, especially early in an asset's history.
  • The real same backtesting discipline from two videos ago, lagging signals and tracking real trades honestly, applies just as much to crypto as to equities.
  • Next video: pulling real company fundamentals straight from real financial statements, a completely different real data source than anything used so far in this domain.

Practice on your own

  1. Repeat the price correlation using TxCnt and HashRate instead of AdrActCnt, then also correlate daily returns with the daily percentage change in active addresses, and compare the results.
  2. Add a trading cost of 0.1% per position change to the 7-day momentum backtest, using diff().abs() on MA_Position as in the backtesting lesson, and see how much further the ending value falls.
  3. Resample prices to month-end with resample('ME').last(), compute monthly returns, and find the best and worst month.

The next video moves to company fundamentals pulled straight from financial statements, a very different data source from the market prices used so far.

🧠 Test yourself

Pick an answer to check it. Your best score is saved in this browser.

  1. Why does the crypto lesson annualize volatility with np.sqrt(365) instead of np.sqrt(252)?

  2. Besides price, what extra kind of data does the Ethereum dataset include?

  3. What does np.percentile(returns.dropna(), 5) represent in the lesson?

  4. What does eth_indexed['PriceUSD'].resample('W').last().pct_change() compute?

  5. The lesson finds the Ethereum price and active addresses are not perfectly correlated. What does this remind us?

💻 Practice exercises

Try each one in the notebook or in your own editor before opening the solution.

  1. Given daily crypto returns [0.03, -0.05, 0.02, 0.04, -0.01, 0.00, 0.015], compute annualized volatility using 365 days and compare with 252 days.

    💡 Hint

    Multiply the daily std by sqrt(365) and sqrt(252).

    ✅ Show solution
    import numpy as np
    import pandas as pd
    
    r = pd.Series([0.03, -0.05, 0.02, 0.04, -0.01, 0.00, 0.015])
    daily = r.std()
    print('365-day:', round(daily * np.sqrt(365), 3))
    print('252-day:', round(daily * np.sqrt(252), 3))
    
  2. Make 120 days of fake crypto prices with a random walk of returns (seed 6, normal mean 0.002, std 0.04, start at 100). Compute daily returns, maximum drawdown (%), the 5th percentile return, and the number of days with absolute return above 8%.

    💡 Hint

    Use cumprod, cummax, and np.percentile.

    ✅ Show solution
    import numpy as np
    import pandas as pd
    
    rng = np.random.default_rng(6)
    ret = pd.Series(rng.normal(0.002, 0.04, 120))
    price = 100 * (1 + ret).cumprod()
    
    cum = (1 + ret).cumprod()
    dd = (cum - cum.cummax()) / cum.cummax()
    print('Max drawdown %:', round(dd.min() * 100, 1))
    print('5th percentile return %:', round(np.percentile(ret, 5) * 100, 2))
    print('Extreme days:', int((ret.abs() > 0.08).sum()))
    
  3. Create 90 days of synthetic daily crypto prices with a date index starting 2024-01-01 (seed 12; returns normal mean 0.001, std 0.03; start 50). Compute weekly returns by resampling to the last price per week, print the best and worst week in percent, and test a 7-day moving-average momentum rule (long when price is above its MA7, lagged one day) against buy-and-hold growth.

    💡 Hint

    Use resample('W').last().pct_change() and shift(1) for the position.

    ✅ Show solution
    import numpy as np
    import pandas as pd
    
    rng = np.random.default_rng(12)
    idx = pd.date_range('2024-01-01', periods=90, freq='D')
    ret = pd.Series(rng.normal(0.001, 0.03, 90), index=idx)
    price = 50 * (1 + ret).cumprod()
    
    weekly = price.resample('W').last().pct_change().dropna()
    print('Best week %:', round(weekly.max() * 100, 1))
    print('Worst week %:', round(weekly.min() * 100, 1))
    
    daily = price.pct_change()
    signal = (price > price.rolling(7).mean()).astype(int)
    position = signal.shift(1).fillna(0)
    strategy = position * daily
    print('Strategy growth:', round((1 + strategy.fillna(0)).cumprod().iloc[-1], 3))
    print('Buy and hold:', round((1 + daily.fillna(0)).cumprod().iloc[-1], 3))
    

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.