In [3]:
!pip install yfinance
Collecting yfinance
Downloading yfinance-0.2.54-py2.py3-none-any.whl.metadata (5.8 kB)
Requirement already satisfied: pandas>=1.3.0 in /opt/anaconda3/lib/python3.12/site-packages (from yfinance) (2.2.2)
Requirement already satisfied: numpy>=1.16.5 in /opt/anaconda3/lib/python3.12/site-packages (from yfinance) (1.26.4)
Requirement already satisfied: requests>=2.31 in /opt/anaconda3/lib/python3.12/site-packages (from yfinance) (2.32.2)
Collecting multitasking>=0.0.7 (from yfinance)
Downloading multitasking-0.0.11-py3-none-any.whl.metadata (5.5 kB)
Requirement already satisfied: platformdirs>=2.0.0 in /opt/anaconda3/lib/python3.12/site-packages (from yfinance) (3.10.0)
Requirement already satisfied: pytz>=2022.5 in /opt/anaconda3/lib/python3.12/site-packages (from yfinance) (2024.1)
Requirement already satisfied: frozendict>=2.3.4 in /opt/anaconda3/lib/python3.12/site-packages (from yfinance) (2.4.2)
Collecting peewee>=3.16.2 (from yfinance)
Downloading peewee-3.17.9.tar.gz (3.0 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.0/3.0 MB 10.5 MB/s eta 0:00:0000:0100:01
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing metadata (pyproject.toml) ... done
Requirement already satisfied: beautifulsoup4>=4.11.1 in /opt/anaconda3/lib/python3.12/site-packages (from yfinance) (4.12.3)
Requirement already satisfied: soupsieve>1.2 in /opt/anaconda3/lib/python3.12/site-packages (from beautifulsoup4>=4.11.1->yfinance) (2.5)
Requirement already satisfied: python-dateutil>=2.8.2 in /opt/anaconda3/lib/python3.12/site-packages (from pandas>=1.3.0->yfinance) (2.9.0.post0)
Requirement already satisfied: tzdata>=2022.7 in /opt/anaconda3/lib/python3.12/site-packages (from pandas>=1.3.0->yfinance) (2023.3)
Requirement already satisfied: charset-normalizer<4,>=2 in /opt/anaconda3/lib/python3.12/site-packages (from requests>=2.31->yfinance) (2.0.4)
Requirement already satisfied: idna<4,>=2.5 in /opt/anaconda3/lib/python3.12/site-packages (from requests>=2.31->yfinance) (3.7)
Requirement already satisfied: urllib3<3,>=1.21.1 in /opt/anaconda3/lib/python3.12/site-packages (from requests>=2.31->yfinance) (2.2.2)
Requirement already satisfied: certifi>=2017.4.17 in /opt/anaconda3/lib/python3.12/site-packages (from requests>=2.31->yfinance) (2024.8.30)
Requirement already satisfied: six>=1.5 in /opt/anaconda3/lib/python3.12/site-packages (from python-dateutil>=2.8.2->pandas>=1.3.0->yfinance) (1.16.0)
Downloading yfinance-0.2.54-py2.py3-none-any.whl (108 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 108.7/108.7 kB 9.2 MB/s eta 0:00:00
Downloading multitasking-0.0.11-py3-none-any.whl (8.5 kB)
Building wheels for collected packages: peewee
Building wheel for peewee (pyproject.toml) ... done
Created wheel for peewee: filename=peewee-3.17.9-cp312-cp312-macosx_11_0_arm64.whl size=264315 sha256=d710c8efd0b27f7bf3cda073f4d463f7ad9b92c798583e7ea59d2c53b4fc686f
Stored in directory: /Users/ingridoyoua/Library/Caches/pip/wheels/43/ef/2d/2c51d496bf084945ffdf838b4cc8767b8ba1cc20eb41588831
Successfully built peewee
Installing collected packages: peewee, multitasking, yfinance
Successfully installed multitasking-0.0.11 peewee-3.17.9 yfinance-0.2.54
In [3]:
# Import des bibliothèques
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
print("Les bibliothèques ont été importées avec succès !")
Les bibliothèques ont été importées avec succès !
In [5]:
# Télécharger les données boursières de Apple (AAPL) sur 1 an
ticker = "AAPL"
data = yf.download(ticker, start="2023-01-01", end="2024-01-01")
# Afficher les 5 premières lignes du dataset
data.head()
YF.download() has changed argument auto_adjust default to True
[*********************100%***********************] 1 of 1 completed
Out[5]:
| Price | Close | High | Low | Open | Volume |
|---|---|---|---|---|---|
| Ticker | AAPL | AAPL | AAPL | AAPL | AAPL |
| Date | |||||
| 2023-01-03 | 123.632538 | 129.395526 | 122.742880 | 128.782657 | 112117500 |
| 2023-01-04 | 124.907715 | 127.181283 | 123.642427 | 125.431622 | 89113600 |
| 2023-01-05 | 123.583107 | 126.301500 | 123.326101 | 125.668857 | 80962700 |
| 2023-01-06 | 128.130234 | 128.792531 | 123.454601 | 124.561732 | 87754700 |
| 2023-01-09 | 128.654144 | 131.876686 | 128.397138 | 128.970474 | 70790800 |
In [7]:
# Tracer l'évolution du prix de clôture
plt.figure(figsize=(12,6))
plt.plot(data.index, data["Close"], label="Prix de Clôture", color="blue")
# Personnalisation du graphique
plt.title("Évolution du Prix de Clôture d'Apple (AAPL)")
plt.xlabel("Date")
plt.ylabel("Prix ($)")
plt.legend()
plt.grid()
# Affichage
plt.show()
In [9]:
# Calcul des rendements journaliers
data["Daily Return"] = data["Close"].pct_change()
# Affichage des 5 premières lignes
data[["Close", "Daily Return"]].head()
Out[9]:
| Price | Close | Daily Return |
|---|---|---|
| Ticker | AAPL | |
| Date | ||
| 2023-01-03 | 123.632538 | NaN |
| 2023-01-04 | 124.907715 | 0.010314 |
| 2023-01-05 | 123.583107 | -0.010605 |
| 2023-01-06 | 128.130234 | 0.036794 |
| 2023-01-09 | 128.654144 | 0.004089 |
In [11]:
# Tracer un histogramme des rendements journaliers
plt.figure(figsize=(10,5))
plt.hist(data["Daily Return"].dropna(), bins=50, color="blue", alpha=0.7)
# Personnalisation
plt.title("Distribution des Rendements Journaliers d'Apple (AAPL)")
plt.xlabel("Rendement Journalier")
plt.ylabel("Fréquence")
plt.grid()
# Affichage
plt.show()
In [13]:
# Statistiques descriptives des rendements journaliers
data["Daily Return"].describe()
Out[13]:
count 249.000000 mean 0.001835 std 0.012570 min -0.048020 25% -0.005891 50% 0.001878 75% 0.008846 max 0.046927 Name: Daily Return, dtype: float64
In [15]:
# Calcul des moyennes mobiles
data["MA50"] = data["Close"].rolling(window=50).mean()
data["MA200"] = data["Close"].rolling(window=200).mean()
# Tracer les prix avec les moyennes mobiles
plt.figure(figsize=(12,6))
plt.plot(data.index, data["Close"], label="Prix de Clôture", color="blue", alpha=0.5)
plt.plot(data.index, data["MA50"], label="MA 50 jours", color="orange")
plt.plot(data.index, data["MA200"], label="MA 200 jours", color="red")
# Personnalisation
plt.title("Prix de Clôture et Moyennes Mobiles (50 et 200 jours) - Apple (AAPL)")
plt.xlabel("Date")
plt.ylabel("Prix ($)")
plt.legend()
plt.grid()
# Affichage
plt.show()
In [17]:
# Calcul de la volatilité annuelle (écart-type des rendements journaliers * sqrt(252))
volatilite_annuelle = data["Daily Return"].std() * np.sqrt(252)
print(f"Volatilité annuelle estimée : {volatilite_annuelle:.2%}")
Volatilité annuelle estimée : 19.95%
In [19]:
# Supposons un taux sans risque de 2% (0.02)
taux_sans_risque = 0.02
rendement_moyen_annuel = data["Daily Return"].mean() * 252
sharpe_ratio = (rendement_moyen_annuel - taux_sans_risque) / volatilite_annuelle
print(f"Ratio de Sharpe : {sharpe_ratio:.2f}")
Ratio de Sharpe : 2.22
In [21]:
# Liste des actions
actions = ["AAPL", "MSFT", "AMZN"]
# Télécharger les données
data_multi = yf.download(actions, start="2023-01-01", end="2024-01-01")["Close"]
# Calcul des rendements journaliers
rendements_multi = data_multi.pct_change()
# Matrice de corrélation
correlation = rendements_multi.corr()
# Affichage
print("Matrice de corrélation des rendements journaliers :")
print(correlation)
# Tracer une heatmap de corrélation
import seaborn as sns
plt.figure(figsize=(8,5))
sns.heatmap(correlation, annot=True, cmap="coolwarm", linewidths=0.5)
plt.title("Corrélation des Rendements Journaliers entre AAPL, MSFT et AMZN")
plt.show()
[*********************100%***********************] 3 of 3 completed
Matrice de corrélation des rendements journaliers : Ticker AAPL AMZN MSFT Ticker AAPL 1.000000 0.441677 0.547987 AMZN 0.441677 1.000000 0.575928 MSFT 0.547987 0.575928 1.000000
In [23]:
# Télécharger les données de l'ETF SPY (qui suit le S&P 500) pour représenter le marché
spy = yf.download("SPY", start="2023-01-01", end="2024-01-01")["Close"]
# Calculer les rendements journaliers de AAPL et SPY
data["Market Return"] = spy.pct_change()
data["Stock Return"] = data["Close"].pct_change()
# Supprimer les valeurs NaN
data.dropna(inplace=True)
# Afficher les 5 premières lignes
data.head()
[*********************100%***********************] 1 of 1 completed
Out[23]:
| Price | Close | High | Low | Open | Volume | Daily Return | MA50 | MA200 | Market Return | Stock Return |
|---|---|---|---|---|---|---|---|---|---|---|
| Ticker | AAPL | AAPL | AAPL | AAPL | AAPL | |||||
| Date | ||||||||||
| 2023-10-18 | 174.560608 | 176.287953 | 173.835924 | 174.302505 | 54764400 | -0.007395 | 176.410236 | 167.505649 | -0.013325 | -0.007395 |
| 2023-10-19 | 174.183380 | 176.546053 | 173.915340 | 174.759147 | 59302900 | -0.002161 | 176.360805 | 167.758403 | -0.008786 | -0.002161 |
| 2023-10-20 | 171.622162 | 174.143675 | 171.383903 | 174.034474 | 64189300 | -0.014704 | 176.264511 | 167.991975 | -0.012288 | -0.014704 |
| 2023-10-23 | 171.741257 | 172.743903 | 168.693587 | 169.666467 | 55980100 | 0.000694 | 176.169408 | 168.232766 | -0.001733 | 0.000694 |
| 2023-10-24 | 172.178055 | 172.406377 | 170.202529 | 171.790893 | 43816600 | 0.002543 | 176.049884 | 168.453005 | 0.007539 | 0.002543 |
In [25]:
import statsmodels.api as sm
# Définir X (rendements du marché) et y (rendements de l'action)
X = data["Market Return"]
y = data["Stock Return"]
# Ajouter une constante pour l'intercept
X = sm.add_constant(X)
# Régression linéaire
model = sm.OLS(y, X).fit()
# Extraire le Beta
beta = model.params[1]
print(f"Beta estimé de l'action Apple : {beta:.2f}")
Beta estimé de l'action Apple : 0.92
/var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/3045059454.py:14: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]` beta = model.params[1]
In [27]:
# Supposons un taux sans risque de 4% (0.04) basé sur les obligations US
rf = 0.04
# Supposons que le rendement annuel moyen du marché est de 10% (0.10)
rm = 0.10
# Calcul du rendement attendu selon le modèle CAPM
expected_return = rf + beta * (rm - rf)
print(f"Rendement attendu d'Apple (CAPM) : {expected_return:.2%}")
Rendement attendu d'Apple (CAPM) : 9.53%
In [29]:
# Définir un signal de trading
data["Signal"] = 0
data.loc[data["MA50"] > data["MA200"], "Signal"] = 1 # Achat
data.loc[data["MA50"] < data["MA200"], "Signal"] = -1 # Vente
# Calcul du rendement de la stratégie
data["Strategy Return"] = data["Signal"].shift(1) * data["Daily Return"]
# Comparaison avec le rendement du marché
cumulative_market_return = (1 + data["Daily Return"]).cumprod()
cumulative_strategy_return = (1 + data["Strategy Return"]).cumprod()
# Tracer les résultats
plt.figure(figsize=(12,6))
plt.plot(data.index, cumulative_market_return, label="Rendement du Marché", color="blue")
plt.plot(data.index, cumulative_strategy_return, label="Rendement de la Stratégie", color="green")
# Personnalisation
plt.title("Backtest de Stratégie de Trading - Apple (AAPL)")
plt.xlabel("Date")
plt.ylabel("Performance cumulée")
plt.legend()
plt.grid()
# Affichage
plt.show()
In [31]:
# Calcul de la VaR à 95% (basée sur la distribution des rendements journaliers)
var_95 = np.percentile(data["Daily Return"].dropna(), 5) # 5ème percentile
print(f"VaR à 95% : {var_95:.2%}")
VaR à 95% : -1.32%
In [33]:
# Liste des actions à comparer
tickers = ["AAPL", "MSFT", "AMZN", "GOOGL", "TSLA"]
# Télécharger les données
data_multi = yf.download(tickers, start="2023-01-01", end="2024-01-01")["Close"]
# Calcul des rendements journaliers
returns_multi = data_multi.pct_change()
returns_spy = spy.pct_change()
# Dictionnaire pour stocker les Betas
betas = {}
# Calcul du Beta pour chaque action
for ticker in tickers:
X = returns_spy.dropna()
y = returns_multi[ticker].dropna()
X = sm.add_constant(X)
model = sm.OLS(y, X, missing='drop').fit()
betas[ticker] = model.params[1]
# Afficher les Betas estimés
for ticker, beta_value in betas.items():
print(f"Beta estimé pour {ticker} : {beta_value:.2f}")
[*********************100%***********************] 5 of 5 completed
Beta estimé pour AAPL : 1.10 Beta estimé pour MSFT : 1.17 Beta estimé pour AMZN : 1.54 Beta estimé pour GOOGL : 1.38 Beta estimé pour TSLA : 2.21
/var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/3560119903.py:22: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]` betas[ticker] = model.params[1] /var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/3560119903.py:22: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]` betas[ticker] = model.params[1] /var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/3560119903.py:22: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]` betas[ticker] = model.params[1] /var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/3560119903.py:22: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]` betas[ticker] = model.params[1] /var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/3560119903.py:22: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]` betas[ticker] = model.params[1]
In [35]:
# Calcul du RSI (Relative Strength Index)
window_length = 14
delta = data["Close"].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=window_length).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=window_length).mean()
rs = gain / loss
data["RSI"] = 100 - (100 / (1 + rs))
# Définir les signaux de trading basés sur le RSI
data["Signal_RSI"] = 0
data.loc[data["RSI"] < 30, "Signal_RSI"] = 1 # Achat
data.loc[data["RSI"] > 70, "Signal_RSI"] = -1 # Vente
# Calcul du rendement de la stratégie RSI
data["Strategy Return RSI"] = data["Signal_RSI"].shift(1) * data["Daily Return"]
# Comparaison avec le rendement du marché
cumulative_rsi_return = (1 + data["Strategy Return RSI"]).cumprod()
# Tracer les résultats
plt.figure(figsize=(12,6))
plt.plot(data.index, cumulative_market_return, label="Rendement du Marché", color="blue")
plt.plot(data.index, cumulative_strategy_return, label="Stratégie Moyennes Mobiles", color="green")
plt.plot(data.index, cumulative_rsi_return, label="Stratégie RSI", color="red")
# Personnalisation
plt.title("Comparaison des stratégies de trading - Apple (AAPL)")
plt.xlabel("Date")
plt.ylabel("Performance cumulée")
plt.legend()
plt.grid()
# Affichage
plt.show()
In [45]:
# Import des bibliothèques nécessaires
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
# Télécharger les données boursières de Apple (AAPL) sur 1 an
ticker = "AAPL"
data = yf.download(ticker, start="2023-01-01", end="2024-01-01")
# Calcul des rendements journaliers
data["Daily Return"] = data["Close"].pct_change()
# Calcul des moyennes mobiles (50 et 200 jours)
data["MA50"] = data["Close"].rolling(window=50).mean()
data["MA200"] = data["Close"].rolling(window=200).mean()
# Définition du signal de trading basé sur les moyennes mobiles
data["Signal_MA"] = 0
data.loc[data["MA50"] > data["MA200"], "Signal_MA"] = 1 # Achat
data.loc[data["MA50"] < data["MA200"], "Signal_MA"] = -1 # Vente
# Calcul du RSI (Relative Strength Index)
window_length = 14
delta = data["Close"].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=window_length).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=window_length).mean()
rs = gain / loss
data["RSI_14"] = 100 - (100 / (1 + rs))
# Définition du signal RSI
rsi_oversold = 30
rsi_overbought = 70
data["Signal_RSI"] = 0
# Boucle de calcul des signaux RSI avec correction du bug
buy_price = None
for i in range(1, len(data)):
if data["RSI_14"].iloc[i-1] < rsi_oversold and data["RSI_14"].iloc[i] >= rsi_oversold:
data.loc[data.index[i], "Signal_RSI"] = 1 # Achat
buy_price = float(data["Close"].iloc[i]) # Stocker le prix d'achat sous forme de float
elif data["RSI_14"].iloc[i-1] > rsi_overbought and data["RSI_14"].iloc[i] <= rsi_overbought:
data.loc[data.index[i], "Signal_RSI"] = -1 # Vente
buy_price = None # Réinitialisation
# Vérification du Take Profit (+5%)
if buy_price is not None:
if float(data["Close"].iloc[i]) >= buy_price * 1.05: # Conversion en float
data.loc[data.index[i], "Signal_RSI"] = -1 # Vente
buy_price = None # Réinitialisation
# Calcul du rendement de la stratégie basée sur les moyennes mobiles
data["Strategy Return MA"] = data["Signal_MA"].shift(1) * data["Daily Return"]
cumulative_strategy_ma = (1 + data["Strategy Return MA"]).cumprod()
# Calcul du rendement de la stratégie RSI
data["Strategy Return RSI"] = data["Signal_RSI"].shift(1) * data["Daily Return"]
cumulative_strategy_rsi = (1 + data["Strategy Return RSI"]).cumprod()
# Calcul du rendement du marché
cumulative_market_return = (1 + data["Daily Return"]).cumprod()
# Tracer les résultats
plt.figure(figsize=(12,6))
plt.plot(data.index, cumulative_market_return, label="Rendement du Marché", color="blue")
plt.plot(data.index, cumulative_strategy_ma, label="Stratégie Moyennes Mobiles", color="green")
plt.plot(data.index, cumulative_strategy_rsi, label="Stratégie RSI", color="red")
# Personnalisation du graphique
plt.title("Comparaison des stratégies de trading - Apple (AAPL)")
plt.xlabel("Date")
plt.ylabel("Performance cumulée")
plt.legend()
plt.grid()
plt.show()
# Calcul de la volatilité annuelle
volatilite_annuelle = data["Daily Return"].std() * np.sqrt(252)
print(f"Volatilité annuelle estimée : {volatilite_annuelle:.2%}")
# Calcul du ratio de Sharpe
taux_sans_risque = 0.02
rendement_moyen_annuel = data["Daily Return"].mean() * 252
sharpe_ratio = (rendement_moyen_annuel - taux_sans_risque) / volatilite_annuelle
print(f"Ratio de Sharpe : {sharpe_ratio:.2f}")
# Calcul de la VaR à 95%
var_95 = np.percentile(data["Daily Return"].dropna(), 5)
print(f"VaR à 95% : {var_95:.2%}")
# Calcul du Beta avec le marché (S&P 500 via SPY)
spy = yf.download("SPY", start="2023-01-01", end="2024-01-01")["Close"]
data["Market Return"] = spy.pct_change()
data["Stock Return"] = data["Close"].pct_change()
data.dropna(inplace=True)
X = sm.add_constant(data["Market Return"])
y = data["Stock Return"]
model = sm.OLS(y, X).fit()
# Extraction du Beta
beta = model.params[1]
print(f"Beta estimé de l'action Apple : {beta:.2f}")
# Modèle CAPM (Capital Asset Pricing Model)
rf = 0.04 # Taux sans risque
rm = 0.10 # Rendement du marché supposé
expected_return = rf + beta * (rm - rf)
print(f"Rendement attendu d'Apple (CAPM) : {expected_return:.2%}")
[*********************100%***********************] 1 of 1 completed /var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/1604498929.py:44: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead buy_price = float(data["Close"].iloc[i]) # Stocker le prix d'achat sous forme de float /var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/1604498929.py:52: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead if float(data["Close"].iloc[i]) >= buy_price * 1.05: # Conversion en float /var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/1604498929.py:44: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead buy_price = float(data["Close"].iloc[i]) # Stocker le prix d'achat sous forme de float /var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/1604498929.py:52: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead if float(data["Close"].iloc[i]) >= buy_price * 1.05: # Conversion en float /var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/1604498929.py:44: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead buy_price = float(data["Close"].iloc[i]) # Stocker le prix d'achat sous forme de float /var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/1604498929.py:52: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead if float(data["Close"].iloc[i]) >= buy_price * 1.05: # Conversion en float /var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/1604498929.py:44: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead buy_price = float(data["Close"].iloc[i]) # Stocker le prix d'achat sous forme de float /var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/1604498929.py:52: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead if float(data["Close"].iloc[i]) >= buy_price * 1.05: # Conversion en float
[*********************100%***********************] 1 of 1 completed
Volatilité annuelle estimée : 19.95% Ratio de Sharpe : 2.22 VaR à 95% : -1.72% Beta estimé de l'action Apple : 0.92 Rendement attendu d'Apple (CAPM) : 9.53%
/var/folders/m8/c4j3jvv11c3d3vl0yvplpn7h0000gn/T/ipykernel_67876/1604498929.py:106: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]` beta = model.params[1]