Table of Contents
- Defining Random Walk:
- Understanding Random Walk:
- Applications in Finance and Data Science:
- Risk Management:
- Trading Strategies:
- Behavioral Finance:
- Merits and Limitations:
- Random Walks using Python
- Applying the Random Walk Model to Stock Prices: A Study on AAPL, MSFT, and GOOGL 10
Defining Random Walk:
A random walk is a complex mathematical abstraction that is most simply understood as a path formed by a series of random steps. This intriguing concept finds its genesis in statistical physics, where it was initially employed to describe the unpredictable motion of particles. However, the malleability and applicability of the random walk's principles have since allowed it to be integrated into various other fields, from finance to biology, and from computer science to sociology.
Understanding Random Walk:
Process Definition:
At its core, the term "random walk" encapsulates a series of steps or movements, where each step, irrespective of its magnitude, direction, or time, is derived from a random process. This absence of a deterministic or predefined pattern underscores the essence of unpredictability that's intrinsic to the concept. When one says a process mirrors a random walk, it accentuates the process's inherent volatility and unpredictability. Instead of evolving in a predictable, linear, or structured manner, the steps taken are the outcome of chance. This means that, at any given point in the process, the next step is not influenced by the sequence of steps that preceded it.
This very nature of randomness implies that each subsequent movement or step is fundamentally independent of its predecessors. Therefore, even if one were to have a complete record of all the previous steps in a random walk, it wouldn't bestow upon them the power to accurately predict the next step. This challenges traditional predictive models, especially in fields like finance, where understanding and forecasting based purely on historical data becomes an endeavour fraught with uncertainty and complexity.
Characteristics:
Lack of Memory: A quintessential feature of a random walk is its lack of memory. Each step doesn’t 'remember' its antecedents. This ensures that predictions about future states are founded solely on the immediate past.
Statistical Properties: While individual steps are random, aggregating these steps, especially in a long random walk, can exhibit certain statistical properties, like the central limit theorem in specific types of random walks.
Applications in Finance and Data Science:
Modeling Financial Markets:
Random walks are central to contemporary finance theories. If markets are efficient, all known information is already factored into prices, rendering them unpredictable and subsequent price changes akin to a random walk.
Risk Management:
Financial institutions employ random walk models, often intertwined with Monte Carlo simulations, to forecast future asset and liability values. By simulating countless potential future paths, these models help financial professionals assess risks and deploy strategies to hedge against unfavorable outcomes.
Trading Strategies:
Some trading strategies are rooted in the random walk hypothesis. For instance, pairs trading seeks to exploit minor deviations from historical price relationships between two stocks. The core belief here is that these deviations are temporary and will revert, challenging the strict interpretation of the random walk hypothesis.
Behavioral Finance:
While the random walk theory presumes market efficiency, behavioral finance, in contrast, argues that markets can be inefficient due to human psychology. Emotional biases, overreactions to news, and other irrational behaviors can cause deviations from the random walk.
Merits and Limitations:
Advantages:
Theoretical Consistency: Random walk models are consistent with many established economic and financial theories, lending them credence.
Basis for Advanced Financial Instruments: Complex derivatives, options, and other financial instruments are often priced based on models that assume a random walk.
Drawbacks:
Potential Ignorance of Market Anomalies: Strict adherence to random walk theories can sometimes overlook market anomalies or instances where behavioral biases can sway prices significantly from intrinsic values.
Limitation to Short-term Predictions: While the random walk hypothesis posits difficulty in forecasting long-term price movements, it doesn’t necessarily imply that short-term predictions are always random. External factors, news, and even algorithmic trading can induce temporary patterns in the short run.
Random Walks using Python
In this post, we are going to explore creating random walks in one, two, and three dimensions using Python. Random walks are a fundamental concept, mainly used to model the path that a moving point (a "walker") follows in discrete steps.
1D Random Walk
A 1-dimensional random walk can be visualized as a path along the number line, where each step is of equal length and chosen randomly in either direction.
import matplotlib.pyplot as plt
import random
def random_walk_1d(steps):
walk = [0]
for i in range(steps):
step = -1 if random.randint(0, 1) == 0 else 1
walk.append(walk[-1] + step)
return walk
steps = 1000
walk = random_walk_1d(steps)
plt.figure(figsize=(10,6))
plt.plot(walk)
plt.title('1D Random Walk')
plt.xlabel('Steps')
plt.ylabel('Position')
plt.show()
This code performs a 1D random walk, starting from the point 0. At each step, the walker randomly chooses to move left or right by 1 step and then plots the resulting path.
2D Random Walk
Now, let’s extend our model to two dimensions. In a 2-dimensional random walk, the walker moves in a grid, choosing randomly between four possible directions: up, down, left, or right, in each step.
def random_walk_2d(steps):
x, y = [0], [0]
for _ in range(steps):
dx = random.choice([-1, 0, 1])
dy = random.choice([-1, 0, 1])
x.append(x[-1] + dx)
y.append(y[-1] + dy)
return x, y
x, y = random_walk_2d(1000)
plt.figure(figsize=(10,6))
plt.plot(x, y)
plt.title('2D Random Walk')
plt.xlabel('X Position')
plt.ylabel('Y Position')
plt.axis('equal')
plt.show()
In this 2D version, x and y are lists representing the coordinates of the walker on a 2D plane. At each step, the walker randomly chooses a direction to move in the x and y dimensions and the resulting path is plotted.
3D Random Walk
Lastly, let’s visualize a 3D random walk. Here, the walker moves in three dimensions: left or right, up or down, and forward or backward.
from mpl_toolkits.mplot3d import Axes3D
def random_walk_3d(steps):
x, y, z = [0], [0], [0]
for _ in range(steps):
dx, dy, dz = random.choice([(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1), (0, 0, 0)])
x.append(x[-1] + dx)
y.append(y[-1] + dy)
z.append(z[-1] + dz)
return x, y, z
x, y, z = random_walk_3d(1000)
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(111, projection='3d')
ax.plot(x, y, z)
ax.set_title('3D Random Walk')
ax.set_xlabel('X Position')
ax.set_ylabel('Y Position')
ax.set_zlabel('Z Position')
plt.show()
In this 3D version, x, y, and z represent the coordinates in a 3D space. The walker chooses a direction randomly in any of the three dimensions at each step and then plots the resulting path in 3D space.
Applying the Random Walk Model to Stock Prices: A Study on AAPL, MSFT, and GOOGL
Let's embark on a journey using Random Walk, starting from a simple 1D representation of a stock's movement and advancing to a more intricate 3D plot involving three key players in the tech industry: AAPL, MSFT, and GOOGL.
Setting up the Environment:
To begin, we'll need the openbb library, which aids in fetching stock data. You can install it using the pip command:
!pip install openbb
Once installed, we're all set to visualizations!
The 1D Tale - AAPL's Solo Performance: Starting simple, a 1D plot presents the stock price of AAPL over time. This is the most basic representation where the x-axis typically represents time, and the y-axis showcases the stock's closing price.
from openbb_terminal.sdk import openbb
import matplotlib.pyplot as plt
stock_1D = openbb.stocks.load(symbol = 'AAPL')
stock_1D['Close'].plot(title="1D Data - AAPL Stock Price", grid=True)
plt.show()
Outcome: As we observe the 1D plot, we notice the gradual upward trend of AAPL's stock price, signaling consistent growth and potential investor confidence in the company.
The 2D AAPL vs. MSFT:
Introducing another dimension, the 2D plot juxtaposes AAPL against MSFT, another tech titan. Here, each axis represents the stock price of one company, illustrating the relationship between the two.
stock_2D_1 = openbb.stocks.load(symbol = 'AAPL')
stock_2D_2 = openbb.stocks.load(symbol = 'MSFT')
plt.plot(stock_2D_1['Close'], stock_2D_2['Close'])
plt.title('2D Real Data - AAPL vs. MSFT Stock Price')
plt.xlabel('AAPL Stock Price')
plt.ylabel('MSFT Stock Price')
plt.grid(True)
plt.show()
Interpreting the 2D Plot
Upon executing the visualization, the plotted graph reveals a captivating relationship between the two tech behemoths.
On the 2D plot let's suppose
The X-coordinate (representing AAPL's stock price) would be 180.
The Y-coordinate (representing MSFT's stock price) would be 300.
So, for that specific day, there would be a point plotted at the position (180, 300) in the 2D space.
As you gather more daily data, you'd get a series of such points, which when connected would form a continuous line in the 2D space, illustrating the concurrent price movements of the three stocks.
Coordinated Upward Trend:
A noticeable feature is the upward trajectory of the plot. When charted against each other, as AAPL's stock price increases, MSFT's seems to do the same. This synchronicity suggests that the stock prices of the two companies might often rise and fall together.
Positive Correlation:
The synchronized movement implies a positive correlation between AAPL and MSFT. In the realm of finance, correlation measures the degree to which two securities move in relation to each other. A positively correlated movement means that when one stock goes up, the other tends to follow suit, and vice versa.
Underlying Factors:
While the plot gives a visual representation of their relationship, the reasons for such a correlation can be manifold. Both being tech giants, their stocks might be influenced by similar industry trends, global tech demands, geopolitical situations, or even broader economic factors.
Points of Divergence:
While the general trend may be positive, there might be certain points or periods where the stocks don't move perfectly in sync. These points of divergence can be especially interesting for analysts. Such deviations might be attributed to company-specific news, product launches, earnings reports, or other events.
3D AAPL vs. MSFT vs. GOOGL Stock Prices
Lastly, let's venture into a 3D visualization space by adding GOOGL to our analysis.
stock_3D_1 = openbb.stocks.load(symbol = 'AAPL')
stock_3D_2 = openbb.stocks.load(symbol = 'MSFT')
stock_3D_3 = openbb.stocks.load(symbol = 'GOOGL')
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.plot(stock_3D_1['Close'], stock_3D_2['Close'], stock_3D_3['Close'])
ax.set_title('3D Real Data - AAPL vs. MSFT vs. GOOGL Stock Price')
ax.set_xlabel('AAPL Stock Price')
ax.set_ylabel('MSFT Stock Price')
ax.set_zlabel('GOOGL Stock Price')
plt.show()
Decoding the Visualization
Upon executing the above code, we are greeted with a mesmerizing 3D trajectory. Each axis represents the closing price of one of the companies: AAPL on the x-axis, MSFT on the y-axis, and GOOGL on the z-axis.
On the 3D plot lets suppose
The X-coordinate (representing AAPL's stock price) would be 180.
The Y-coordinate (representing MSFT's stock price) would be 300.
The Z-coordinate (representing GOOGL's stock price) would be 120.
So, for that specific day, there would be a point plotted at the position (180, 300, 120) in the 3D space.
As you gather more daily data, you'd get a series of such points, which when connected would form a continuous line in the 3D space, illustrating the concurrent price movements of the three stocks.
Interconnectedness:
If the trajectory mostly moves upward, it implies a certain level of correlation. It suggests that when Apple's stock (AAPL) performs well, there's a likelihood that Microsoft's (MSFT) and Google's (GOOGL) stocks are also trending upwards. This could be due to various factors, such as positive tech industry news or broader economic conditions benefiting all three companies.
Volatility Points:
Any sharp turns or deviations in the plot can be areas of interest. They may represent specific events or announcements that differentially affected one or more of these companies.
Comparison: While a 2D plot shows the relationship between two stocks, our 3D plot goes a step further. It allows an observer to gauge how all three stocks compare simultaneously. For instance, if we see the trajectory stretching more along the MSFT axis, it might indicate periods when Microsoft's stock saw more volatility or significant price changes compared to the other two.
Conclusion
In this blog post, we have learned how to visualize random walks in one, two, and three dimensions using Python and Matplotlib. We have not only discovered how to generate random walks but also learned how to visually represent them, offering a more intuitive and richer understanding of this fundamental stochastic process. Whether you are a seasoned researcher, a student trying to unravel the intricacies of stochastic processes, or someone with a casual interest in mathematical phenomena, exploring random walks is a journey filled with learning and discovery. The knowledge acquired here can be a stepping stone to go deeper into more advanced topics such as Markov Chains, Brownian Motion, and other complex stochastic processes.
Python and Matplotlib together provide a seamless experience to visualize and analyze random walks, making them more accessible and understandable to a wider audience. It is hoped that this blog post sparks curiosity and encourages readers to explore further, experiment with their variations, and find novel applications for random walks in their fields of interest. By embarking on this exploration of random walks, we become part of a broader community of inquisitive minds striving to understand the intricate dance of randomness and order governing our world, uncovering the profound truths hidden within seemingly chaotic patterns. The journey through the realms of randomness is bound to be intriguing, enlightening, and full of surprises, offering glimpses into the beautiful complexity of our universe.
To access and run the Python code yourself, visit the Pyfi GitHub
Written by Numan Yaqoob, PHD candidate