In [5]:
1   # Importing necessary libraries
           2   import yfinance as yf
           3   import matplotlib.pyplot as plt
           4   from xgboost import XGBRegressor
           5   from sklearn.metrics import mean_squared_error, mean_absolute_err
           6   import numpy as np
           7   
           8   # Fetching data from Yahoo Finance for Microsoft (MSFT)
           9   msft = yf.download("MSFT", start="2020-01-01", end="2023-12-31")
          10   
          11   # Displaying the first few rows of the data
          12   print(msft.head())
          13   
          14   # Displaying the last few rows of the data
          15   print(msft.tail())
          16   
          17   # Length of the dataset
          18   len(msft)
          19   
          20   # Showing the data visually
          21   msft['Close'].plot()
          22   
          23   # Splitting the data into training and testing
          24   train_data = msft.iloc[:int(.99*len(msft)), :]
          25   test_data = msft.iloc[int(.99*len(msft)):, :]
          26   
          27   # Defining features and target variable
          28   features = ['Open', 'Volume']
          29   target = 'Close'
          30   
          31   # Training the model
          32   model = XGBRegressor()
          33   model.fit(train_data[features], train_data[target])
          34   
          35   # Predicting the close price of Microsoft based on features
          36   predictions = model.predict(test_data[features])
          37   print('Model Predictions:', predictions)
          38   
          39   # Displaying the actual values
          40   print('Actual Values:', test_data[target])
          41   
42   
43   # Plotting the prediction and close price
44   plt.plot(msft['Close'], label='Close Price')
45   plt.plot(np.array(test_data.index), predictions, label='Predictio
46   plt.legend()
47   plt.show()
48   
49   # Calculate and print evaluation metrics
50   mse = mean_squared_error(test_data[target], predictions)
51   rmse = np.sqrt(mse)
52   mae = mean_absolute_error(test_data[target], predictions)
53   
54   print(f'Mean Squared Error (MSE): {mse}')
55   print(f'Root Mean Squared Error (RMSE): {rmse}')
56   print(f'Mean Absolute Error (MAE): {mae}')
57   
[*********************100%%**********************]   1 of 1 completed
                   Open         High          Low        Close    Adj Close   \
Date
2020-01-02   158.779999   160.729996   158.330002   160.619995   154.779510
2020-01-03   158.320007   159.949997   158.059998   158.619995   152.852234
2020-01-06   157.080002   159.100006   156.509995   159.029999   153.247345
2020-01-07   159.320007   159.669998   157.320007   157.580002   151.850082
2020-01-08   158.929993   160.800003   157.949997   160.089996   154.268814
               Volume
Date
2020-01-02   22622100
2020-01-03   21116200
2020-01-06   20813700
2020-01-07   21634100
2020-01-08   27746500
                   Open         High          Low        Close    Adj Close   \
Date
2023-12-22   373.679993   375.179993   372.709991   374.579987   374.579987
2023-12-26   375.000000   376.940002   373.500000   374.660004   374.660004
2023-12-27   373.690002   375.059998   372.809998   374.070007   374.070007
2023-12-28   375.369995   376.459991   374.160004   375.279999   375.279999
2023-12-29   376.000000   377.160004   373.480011   376.040009   376.040009
               Volume
Date
2023-12-22   17091100
2023-12-26   12673100
2023-12-27   14905400
2023-12-28   14327000
2023-12-29   18723000
Model Predictions: [374.31592 360.12424 375.02295 370.12485 367.31464 367.49377 367.08853
 368.99023 369.79617 369.54004 373.8377 ]
Actual Values: Date
2023-12-14    365.929993
2023-12-15    370.730011
2023-12-18    372.649994
2023-12-19    373.260010
2023-12-20    370.619995
2023-12-21    373.540009
2023-12-22    374.579987
2023-12-26    374.660004
2023-12-27    374.070007
2023-12-28    375.279999
2023-12-29    376.040009
Name: Close, dtype: float64
Mean Squared Error (MSE): 35.461799762719735
Root Mean Squared Error (RMSE): 5.954981088359537
Mean Absolute Error (MAE): 5.384429931640625
In [4]:
           1   import yfinance as yf
           2   import matplotlib.pyplot as plt
           3   import pyfolio as pf
           4   import pandas as pd
           5   
           6   # Fetching data from Yahoo Finance for Alphabet Inc. (GOOGL)
           7   symbol = 'GOOGL'
           8   start_date = '2023-01-01'
           9   end_date = '2023-12-31'
          10   googl = yf.download(symbol, start=start_date, end=end_date)
          11   
          12   # Plotting the closing prices
          13   googl['Close'].plot(figsize=(20, 5))
          14   plt.title(f'{symbol} Closing Prices')
          15   plt.show()
          16   
          17   # Calculating the daily returns
          18   daily_returns = googl['Close'].pct_change()
          19   
          20   # Drop missing values
          21   daily_returns.dropna(inplace=True)
          22   
          23   # Plot the daily returns
          24   plt.figure(figsize=(12, 6))
          25   plt.plot(daily_returns)
          26   plt.title('Daily Returns')
          27   plt.xlabel('Date')
          28   plt.ylabel('Percentage Returns')
          29   plt.show()
          30   
          31   # Convert daily returns to a DataFrame
          32   returns_df = pd.DataFrame({'Returns': daily_returns})
          33   
          34   # Create a simple tear sheet
          35   pf.create_simple_tear_sheet(returns_df)
          36   
          37   
          38   
          [*********************100%%**********************]   1 of 1 completed
---------------------------------------------------------------------------
ValueError                                    Traceback (most recent call last)
<ipython-input-4-fa903a6151cc> in <module>
     33
     34 # Create a simple tear sheet
---> 35 pf.create_simple_tear_sheet(returns_df)
     36
     37
~/opt/anaconda3/lib/python3.8/site-packages/pyfolio/plotting.py in call_w_context(*args,
     50          if set_context:
     51                with plotting_context(), axes_style():
---> 52                   return func(*args, **kwargs)
     53          else:
     54                return func(*args, **kwargs)
~/opt/anaconda3/lib/python3.8/site-packages/pyfolio/tears.py in create_simple_tear_sheet
nchmark_rets, slippage, estimate_intraday, live_start_date, turnover_denom, header_rows)
    357          live_start_date = ep.utils.get_utc_timestamp(live_start_date)
    358
--> 359      plotting.show_perf_stats(returns,
    360                                   benchmark_rets,
    361                                   positions=positions,
~/opt/anaconda3/lib/python3.8/site-packages/pyfolio/plotting.py in show_perf_stats(return
ctions, turnover_denom, live_start_date, bootstrap, header_rows)
    584          perf_func = timeseries.perf_stats
    585
--> 586      perf_stats_all = perf_func(
    587          returns,
    588          factor_returns=factor_returns,
~/opt/anaconda3/lib/python3.8/site-packages/pyfolio/timeseries.py in perf_stats(returns,
ons, turnover_denom)
    724      stats = pd.Series()
    725      for stat_func in SIMPLE_STAT_FUNCS:
--> 726          stats[STAT_FUNC_NAMES[stat_func.__name__]] = stat_func(returns)
    727
    728      if positions is not None:
~/opt/anaconda3/lib/python3.8/site-packages/empyrical/stats.py in calmar_ratio(returns, p
    582
    583      max_dd = max_drawdown(returns=returns)
--> 584      if max_dd < 0:
    585          temp = annual_return(
    586                returns=returns,
~/opt/anaconda3/lib/python3.8/site-packages/pandas/core/generic.py in __nonzero__(self)
   1464      @final
   1465      def __nonzero__(self) -> NoReturn:
-> 1466         raise ValueError(
   1467                f"The truth value of a {type(self).__name__} is ambiguous. "
   1468                "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.