









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










# Imports & settings
# Core data libraries import numpy as np import pandas as pd
# Data source (Yahoo Finance) import yfinance as yf # Plotting import matplotlib.pyplot as plt # Sklearn: pipelines, preprocessing, models, evaluation metrics from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import ( accuracy_score, roc_auc_score, precision_score, recall_score, f1_score, confusion_matrix, ConfusionMatrixDisplay, roc_curve, precision_recall_curve )
# Make plots look consistent plt. rcParams["figure.figsize"] = ( 12 , 5 ) plt. rcParams["axes.grid"] = True
Tesla, Inc. has become one of the most closely watched firms in global equity markets, reflecting its position at the intersection of technological innovation, sustainability transitions, and speculative investor sentiment. As a leading electric vehicle manufacturer and a prominent player in energy storage and artificial intelligence initiatives, Tesla attracts intense media attention and investor interest, which frequently translates into substantial price movements.
Unlike traditional automotive companies, Tesla’s valuation is strongly influenced not only by fundamentals such as production and delivery performance but also by forward-looking expectations related to autonomous driving technology, energy solutions, and broader technological disruption. This combination of growth narratives and uncertainty contributes to pronounced price volatility.
Between 2021 and 2026, Tesla’s stock experienced significant fluctuations driven by macroeconomic tightening cycles, supply chain disruptions, competitive pressures in the EV market, and firm-specific events including earnings announcements, delivery reports, and
In [36]:
statements from its CEO. These characteristics make Tesla an ideal case study for examining return dynamics, volatility behavior, and market reactions to new information.
Understanding the statistical properties of Tesla’s price movements is therefore important for risk measurement, volatility modelling, and event impact analysis. By exploring Tesla’s stock behavior over this period, this study aims to provide insight into the dynamics of a high- growth, high-volatility technology-driven asset.
tsla = yf. download('TSLA', start = '2021-01-01', end = '2026-01-01') print(tsla) [*********************100%***********************] 1 of 1 completed Price Close High Low Open Volume Ticker TSLA TSLA TSLA TSLA TSLA Date 2021-01-04 243.256668 248.163330 239.063339 239.820007 145914600 2021-01-05 245.036667 246.946671 239.733337 241.220001 96735600 2021-01-06 251.993332 258.000000 249.699997 252.830002 134100000 2021-01-07 272.013336 272.329987 258.399994 259.209991 154496700 2021-01-08 293.339996 294.829987 279.463318 285.333344 225166500 ... ... ... ... ... ... 2025-12-24 485.399994 490.899994 476.799988 488.480011 41285400 2025-12-26 475.190002 489.089996 473.820007 485.230011 58780700 2025-12-29 459.640015 469.399994 459.000000 469.000000 66263000 2025-12-30 454.429993 463.119995 453.829987 461.089996 59238500 2025-12-31 449.720001 456.549988 449.299988 456.100006 49078000 [1255 rows x 5 columns]
tsla["Close"]. plot(figsize = ( 12 , 5 )) plt. title("TSLA Closing Price (2021-2026)") plt. ylabel("Price") plt. show()
This figure illustrates Tesla’s stock price dynamics from 2021 to 2026, revealing substantial volatility and multiple structural shifts. The series exhibits strong non-stationarity, with pronounced boom–bust cycles and regime changes. A rapid rise in 2021 is followed by
In [37]:
In [38]:
These periods coincide with major macroeconomic tightening cycles, supply-chain disruptions, shifts in EV market competition, and firm-specific announcements such as earnings releases, delivery reports, and CEO statements. The clustering of large price movements suggests volatility persistence and highlights Tesla’s sensitivity to new information.
Such instability makes Tesla an appropriate case for examining how financial markets respond to macroeconomic and firm-specific events, motivating the incorporation of an event-based dataset in the subsequent analysis.
#volatility clustering tsla["volatility"] = tsla["log_return"]. rolling( 30 ). std()
tsla["volatility"]. plot(figsize = ( 12 , 5 )) plt. title("30-Day Rolling Volatility") plt. show()
#extreme volatility day extreme = tsla["log_return"]. abs(). nlargest( 10 )
extreme_days = tsla. loc[extreme. index] extreme_days[["log_return"]]
In [41]:
In [42]:
Price log_return Ticker Date 2025-04-09 0. 2024-10-24 0. 2021-03-09 0. 2025-03-10 -0. 2025-06-05 -0. 2024-04-29 0. 2024-11-06 0. 2024-07-24 -0. 2023-01-03 -0. 2022-04-26 -0.
The exploratory analysis reveals several stylized facts typical of financial time series. Tesla’s price series is non-stationary, while returns exhibit heavy tails and volatility clustering. Daily returns display minimal serial correlation, suggesting weak-form market efficiency, whereas squared returns indicate persistence in volatility. The presence of extreme return observations further suggests that sudden information shocks may play an important role in driving price movements. These characteristics motivate further analysis of volatility dynamics and the impact of major information events.
tsla. loc["2025-04-08":"2025-04-10", "Close"]
Ticker TSLA Date 2025-04-08 221. 2025-04-09 272. 2025-04-10 252.
Instead of modelling prices directly, financial studies usually analyse returns.
Daily log returns are calculated as:
r_t = log(P_t / P_{t-1})
Out[42]:
In [43]:
Out[43]:
# > 1 means price above MA (uptrend) tsla["ma5_ratio"] = tsla["Close_1d"] / tsla["ma5"] tsla["ma20_ratio"] = tsla["Close_1d"] / tsla["ma20"]
_# ---- Momentum / past returns ----
tsla["ret_1"] = tsla["log_return"] tsla["ret_3"] = tsla["log_return"]. rolling( 3 ). sum() tsla["ret_5"] = tsla["log_return"]. rolling( 5 ). sum() tsla["ret_10"] = tsla["log_return"]. rolling( 10 ). sum()
# Lags: yesterday/2 days ago/3 days ago return tsla["lag1"] = tsla["log_return"]. shift( 1 ) tsla["lag2"] = tsla["log_return"]. shift( 2 ) tsla["lag3"] = tsla["log_return"]. shift( 3 )
_# ---- Volatility features ----
tsla["vol_5"] = tsla["log_return"]. rolling( 5 ). std() tsla["vol_10"] = tsla["log_return"]. rolling( 10 ). std() tsla["vol_20"] = tsla["log_return"]. rolling( 20 ). std() _# ---- Volume features ----
tsla["volume_change"] = tsla["Volume_1d"]. pct_change() # Volume ratio vs recent average tsla["volume_ma5"] = tsla["Volume_1d"]. rolling( 5 ). mean() tsla["volume_ratio"] = tsla["Volume_1d"] / tsla["volume_ma5"]
Target Variable
The objective of the model is to predict the direction of the next day's price movement.
The target variable is defined as:
target = 1 if tomorrow's return > 0 target = 0 otherwise
This transforms the problem into a binary classification task.
_# Target definition:
tsla["target"] = (tsla["log_return"]. shift( - 1 ) > 0 ). astype(int) _# After rolling/lagging, early rows become NaN.
tsla = tsla. dropna(). copy() print("After dropna shape:", tsla. shape) print(tsla[["Close_1d", "log_return", "target"]]. head())
In [47]:
After dropna shape: (1206, 29) Price Close_1d log_return target Ticker Date 2021-03-16 225.626663 -0.044865 1 2021-03-17 233.936661 0.036169 0 2021-03-18 217.720001 -0.071841 1 2021-03-19 218.289993 0.002615 1 2021-03-22 223.333328 0.022841 0 # Build X/y + time-based split features = [ "ma5_ratio", "ma20_ratio", "ret_1", "ret_3", "ret_5", "ret_10", "lag1", "lag2", "lag3", "vol_5", "vol_10", "vol_20", "volume_change", "volume_ratio" ] X = tsla[features] y = tsla["target"] split = int(len(tsla) ***** 0.8) X_train, X_test = X. iloc[:split], X. iloc[split:] y_train, y_test = y. iloc[:split], y. iloc[split:] print("X_train:", X_train. shape, "X_test:", X_test. shape) print("y_train mean:", y_train. mean(), "y_test mean:", y_test. mean()) X_train: (964, 14) X_test: (242, 14) y_train mean: 0.5217842323651453 y_test mean: 0.
Model Building
Several machine learning models are implemented to predict the direction of Tesla's daily returns.
The models considered include:
Logistic Regression Ridge Logistic Regression Lasso Logistic Regression Elastic Net Random Forest Gradient Boosting Support Vector Machine K-Nearest Neighbours
These models represent both linear and non-linear approaches to classification.
# Unified evaluation function
In [48]:
In [49]:
"KNN": Pipeline([ ("scaler", StandardScaler()), ("model", KNeighborsClassifier(n_neighbors = 15 )) ])
}
# Train all models + compare metrics
results = [] for name, model in models. items():
model. fit(X_train, y_train) metrics = evaluate_model(model, X_test, y_test) metrics["Model"] = name results. append(metrics)
results_df = pd. DataFrame(results) results_df = results_df[[ "Model", "Accuracy", "ROC_AUC", "Precision", "Recall", "F1" ]] # Sort by ROC_AUC first, then Accuracy results_df. sort_values( ["ROC_AUC", "Accuracy"], ascending =False )
Model Accuracy ROC_AUC Precision Recall F 2 Lasso 0.537190 0.558500 0.526627 0.735537 0. 3 ElasticNet 0.528926 0.553992 0.521212 0.710744 0. 0 Logistic 0.533058 0.549416 0.524390 0.710744 0. 1 Ridge 0.533058 0.549416 0.524390 0.710744 0. 7 KNN 0.500000 0.532272 0.500000 0.561983 0. 4 RandomForest 0.508264 0.530087 0.507576 0.553719 0. 6 GradientBoosting 0.504132 0.513421 0.503546 0.586777 0. 5 SVM 0.545455 0.440817 0.537931 0.644628 0.
In [51]:
Out[51]:
Model Evaluation
Model performance is evaluated using multiple classification metrics:
ROC-AUC is particularly important in financial prediction problems because it evaluates the ranking ability of predicted probabilities.
The confusion matrix provides a detailed breakdown of prediction outcomes, including true positives, false positives, true negatives, and false negatives.
This helps us understand whether the model tends to make certain types of errors, such as predicting too many upward movements.
The confusion matrix shows that the model correctly predicts 89 positive cases and 41 negative cases, while misclassifying 32 positive observations as negative and 80 negative observations as positive.
This indicates that the model is more effective at identifying positive movements than negative ones, which is consistent with the relatively high recall score (0.735).
In other words, the model successfully captures a large proportion of upward movements but tends to generate false positives.
# Detailed evaluation - Confusion Matrix from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay import matplotlib.pyplot as plt
best_model = models["Lasso"] y_pred = best_model. predict(X_test)
In [52]:
Such levels are common in financial prediction tasks where signals are typically weak and noisy.
# Detailed evaluation - ROC curve y_prob = best_model. predict_proba(X_test)[:, 1 ]
fpr, tpr, _ = roc_curve(y_test, y_prob) plt. figure(figsize = ( 6 , 5 )) plt. plot(fpr, tpr, label = "Lasso")
plt. plot([ 0 , 1 ],[ 0 , 1 ], linestyle = "--") plt. xlabel("False Positive Rate") plt. ylabel("True Positive Rate") plt. title("ROC Curve") plt. legend()
plt. show()
Model Interpretation
To better understand the drivers of predictions, we examine the coefficients from the Lasso regression model.
In [53]:
Because Lasso applies L1 regularisation, many coefficients shrink to zero, effectively performing feature selection.
Features with larger absolute coefficients are considered more influential in predicting price direction.
Feature importance was examined using the coefficients from the Lasso regression model. Because Lasso performs automatic feature selection through L1 regularisation, many features were shrunk to zero, leaving only a subset of variables with predictive power.
The most influential feature is ma20_ratio, which measures the ratio of the current price to its 20-day moving average. Its positive coefficient indicates that when the price is above its medium-term trend, the probability of an upward movement increases. This finding is consistent with the well-known trend-following effect in financial markets.
The second most important feature is ret_5, which has a negative coefficient. This suggests that strong short-term returns over the previous five days are associated with a higher probability of a subsequent decline, indicating a short-term mean-reversion effect.
Another important predictor is volume_ratio, which captures abnormal trading volume relative to its recent average. The positive coefficient implies that unusually high trading volume is associated with a greater likelihood of upward price movements.
Overall, the model identifies a combination of trend signals (moving-average ratio), short- term reversal effects (recent returns), and liquidity indicators (volume changes) as the main drivers of predictive performance.
# Interpretation - coefficients (for linear models) coef = best_model. named_steps["model"]. coef_[ 0 ]
importance = pd. DataFrame({ "feature": features, "coef": coef })
importance["abs_coef"] = importance["coef"]. abs() importance. sort_values("abs_coef", ascending =False )
In [55]:
The interpretation of the Lasso model reveals several economically meaningful patterns. The ratio between the current price and the 20-day moving average emerges as the most influential feature, indicating the presence of a trend-following effect. In addition, the negative coefficient on the five-day return suggests evidence of short-term mean reversion, where strong recent returns are followed by partial corrections. Trading volume indicators also contribute to predictive performance, implying that unusually high trading activity may contain information about future price movements.
Despite these findings, the overall predictive power remains modest, with an ROC-AUC slightly above 0.55. This result is consistent with the well-documented difficulty of predicting financial markets, where price movements are heavily influenced by noise and unpredictable external factors.
Several limitations should be acknowledged. First, the analysis relies solely on technical indicators derived from price and volume data, while other potentially informative variables such as macroeconomic factors, news sentiment, or options market data are not considered. Second, the study focuses on a single stock, and results may not generalise to other securities or broader market conditions. Third, the evaluation uses a simple train-test split rather than more advanced time-series cross-validation methods.
Future research could extend this framework by incorporating additional data sources, testing more sophisticated time-series models, and evaluating performance across a larger universe of stocks. Such extensions may help improve predictive performance and provide deeper insights into the dynamics of financial markets.