Sharing is caring!

Python Project 2024 with source code: DELL Stock Analysis (data analysis project 2024)

Our article delves into the world of DELL stock analysis. We’ll examine its past performance, current market conditions, and future potential. Whether you’re an experienced investor or just starting, this exploration promises valuable insights into DELL’s financial landscape. Let’s begin our journey.


Lets Start

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))
💻🖥💲 Python Project with source code: DELL Stock Analysis 2023💲💻🖥

Stock Analysis of DELL Stock

1. Import Libraries

import pandas as pd
import numpy as np

import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
plt.style.use("fivethirtyeight")
%matplotlib inline

# For reading stock data from yahoo
from pandas_datareader.data import DataReader
   
# For time stamps
from datetime import datetime
from math import sqrt
from math import sqrt
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler

#ignore the warnings
import warnings
warnings.filterwarnings('ignore')

DE_Data = pd.read_csv('../input/dell-stock-data-latest-and-updated/DELL_stock_history.csv',sep='\t')

DE_Data.columns

Out[4]

Index([‘Date’, ‘Open’, ‘High’, ‘Low’, ‘Close’, ‘Volume’, ‘Dividends’, ‘Stock Splits’], dtype=’object’)

DE_Data.head()

Out[5]:

DateOpenHighLowCloseVolumeDividendsStock Splits
02016-08-17 00:00:00-04:0011.63646711.77021911.50271411.50271427151900.0
12016-08-18 00:00:00-04:0011.77021811.77021811.36896111.435837176736600.0
22016-08-19 00:00:00-04:0011.42246211.63646611.40908711.636466473590000.0
32016-08-22 00:00:00-04:0011.50271412.19822711.39571211.676593224590900.0
42016-08-23 00:00:00-04:0011.70334312.27847811.63646612.037724148302000.0

3. Basic EDA

DE_Data.plot(subplots = True, figsize = (10,12))
plt.title('DELL Stock Attributes')
plt.show()
def plot_close_val(data_frame, column, stock):
    plt.figure(figsize=(16,6))
    plt.title(column + ' Price History for ' + stock )
    plt.plot(data_frame[column])
    plt.xlabel('Date', fontsize=18)
    plt.ylabel(column + ' Price USD ($) for ' + stock, fontsize=18)
    plt.show()

#Test the function
plot_close_val(DE_Data, 'Close', 'DELL')
plot_close_val(DE_Data, 'Open',  'DELL')
In [8]:DE_Data[["Volume"]].plot()

Out[8]:<Axes: >

4. Basic Company Info

DE_info =  pd.read_csv('../input/dell-stock-data-latest-and-updated/DELL_stock_info.csv', 
                       header=None,
                       sep='\t', 
                       names=(['Description','Information']))
DE_info.dropna()
DE_info.drop(DE_info.loc[DE_info['Information']=='nan'].index, inplace=True)
DE_info.dropna()
ko = DE_info.head(50)
ko = ko.sort_values('Information').style
ko

Out[9]:

 DescriptionInformation
46ask0
45bid0
34dividendYield0.0218
36payoutRatio0.5385
37beta0.899
33dividendRate1.48
19shareHolderRightsRisk10
47bidSize1000
14fullTimeEmployees133000
21governanceEpochDate1696118400
35exDividendDate1698019200
22compensationAsOfEpochDate1703980800
24priceHint2
38trailingPE26.115387
18compensationRisk3
40volume4065220
41regularMarketVolume4065220
42averageVolume4792907
49marketCap49120694272
43averageVolume10days5914220
44averageDailyVolume10Day5914220
31regularMarketDayLow66.7
27dayLow66.7
30regularMarketOpen67.26
26open67.26
29regularMarketPreviousClose67.76
25previousClose67.76
32regularMarketDayHigh68.645
28dayHigh68.645
16auditRisk7
3zip78682
48askSize800
5phone800 289 3355
23maxAge86400
17boardRisk9
20overallRisk9
39forwardPE9.956012
9industryDispComputer Hardware
7industryComputer Hardware
13longBusinessSummaryDell Technologies Inc. designs, develops, manufactures, markets, sells, and supports various comprehensive and integrated solutions, products, and services in the Americas, Europe, the Middle East, Asia, and internationally. The company operates through two segments, Infrastructure Solutions Group (ISG) and Client Solutions Group (CSG). The ISG segment provides traditional and next-generation storage solutions, including all-flash arrays, scale-out file, object platforms, hyper-converged infrastructure, and software-defined storage; and rack, blade, tower, and hyperscale servers. This segment also offers networking products and services that help its business customers to transform and modernize their infrastructure, mobilize and enrich end-user experiences, and accelerate business applications and processes; attached software and peripherals; and support and deployment, configuration, and extended warranty services. The CSG segment provides desktops, workstations, and notebooks; displays, docking stations, and other electronics; and third-party software and peripherals, as well as support and deployment, configuration, and extended warranty services. The company is also involved in the provision of cybersecurity technology-driven security solutions to prevent security breaches, detect malicious activity, respond rapidly when a security breach occurs, and identify emerging threats; originating, collecting, and servicing customer financing arrangements; and infrastructure-as-a-service solutions, as well as in the resale of VMware products and services. The company was formerly known as Denali Holding Inc. and changed its name to Dell Technologies Inc. in August 2016. Dell Technologies Inc. was founded in 1984 and is headquartered in Round Rock, Texas.
0address1One Dell Way
1cityRound Rock
2stateTX
10sectorTechnology
12sectorDispTechnology
4countryUnited States
15companyOfficers[{‘maxAge’: 1, ‘name’: ‘Mr. Michael Saul Dell’, ‘age’: 57, ‘title’: ‘Chairman & CEO’, ‘yearBorn’: 1965, ‘fiscalYear’: 2023, ‘totalPay’: 2797308, ‘exercisedValue’: 0, ‘unexercisedValue’: 0}, {‘maxAge’: 1, ‘name’: ‘Mr. Jeffrey W. Clarke’, ‘age’: 59, ‘title’: ‘COO & Vice Chairman’, ‘yearBorn’: 1963, ‘fiscalYear’: 2023, ‘totalPay’: 2853441, ‘exercisedValue’: 0, ‘unexercisedValue’: 0}, {‘maxAge’: 1, ‘name’: ‘Mr. William F. Scannell’, ‘age’: 60, ‘title’: ‘President of Global Sales & Customer Operations’, ‘yearBorn’: 1962, ‘fiscalYear’: 2023, ‘totalPay’: 1931384, ‘exercisedValue’: 0, ‘unexercisedValue’: 0}, {‘maxAge’: 1, ‘name’: ‘Ms. Yvonne McGill’, ‘age’: 55, ‘title’: ‘Chief Financial Officer’, ‘yearBorn’: 1967, ‘fiscalYear’: 2023, ‘exercisedValue’: 0, ‘unexercisedValue’: 0}, {‘maxAge’: 1, ‘name’: ‘Ms. Brunilda Rios’, ‘age’: 56, ‘title’: ‘Senior VP of Corporate Finance & Chief Accounting Officer’, ‘yearBorn’: 1966, ‘fiscalYear’: 2023, ‘exercisedValue’: 0, ‘unexercisedValue’: 0}, {‘maxAge’: 1, ‘name’: ‘Mr. Richard J. Rothberg Esq.’, ‘age’: 58, ‘title’: ‘General Counsel & Secretary’, ‘yearBorn’: 1964, ‘fiscalYear’: 2023, ‘totalPay’: 1727358, ‘exercisedValue’: 24596768, ‘unexercisedValue’: 20991448}, {‘maxAge’: 1, ‘name’: ‘Ms. Allison Dew’, ‘age’: 52, ‘title’: ‘Chief Marketing Officer’, ‘yearBorn’: 1970, ‘fiscalYear’: 2023, ‘totalPay’: 2273277, ‘exercisedValue’: 0, ‘unexercisedValue’: 7912755}, {‘maxAge’: 1, ‘name’: ‘Mr. Michael Zimmerman’, ‘title’: ‘Vice President of Corporate Development’, ‘fiscalYear’: 2023, ‘exercisedValue’: 0, ‘unexercisedValue’: 0}, {‘maxAge’: 1, ‘name’: ‘Dr. Jennifer D. Saavedra Ph.D.’, ‘age’: 52, ‘title’: ‘Chief Human Resources Officer’, ‘yearBorn’: 1970, ‘fiscalYear’: 2023, ‘exercisedValue’: 0, ‘unexercisedValue’: 0}, {‘maxAge’: 1, ‘name’: ‘Mr. Howard D. Elias’, ‘age’: 64, ‘title’: ‘Chief Customer Officer and President of Services & Digital’, ‘yearBorn’: 1958, ‘fiscalYear’: 2023, ‘totalPay’: 6171429, ‘exercisedValue’: 4068717, ‘unexercisedValue’: 0}]
8industryKeycomputer-hardware
6websitehttps://www.delltechnologies.com
11sectorKeytechnology
728*90 EN V.2

5. Basic CAGR

5.1 Basic Rolling Averages

# Isolate the adjusted closing prices 
adj_close_px = DE_Data['Close']

# Calculate the moving average
moving_avg = adj_close_px.rolling(window=40).mean()

# Inspect the result
moving_avg[-10:]

Out[10]: 1089 32.546663 1090 32.597873 1091 32.651740 1092 32.710680 1093 32.760683 1094 32.819622 1095 32.916124 1096 33.034849 1097 33.183286 1098 33.332206

# Short moving window rolling mean
DE_Data['42'] = adj_close_px.rolling(window=40).mean()

# Long moving window rolling mean
DE_Data['252'] = adj_close_px.rolling(window=252).mean()

# Plot the adjusted closing price, the short and long windows of rolling means
DE_Data[['Close', '42', '252']].plot()

plt.show()
daily_close_px = DE_Data[['Close']]
# Calculate the daily percentage change for `daily_close_px`
daily_pct_change = daily_close_px.pct_change()

# Plot the distributions
daily_pct_change.hist(bins=50, sharex=True, figsize=(12,8))

# Show the resulting plot
plt.show()
# Define the minumum of periods to consider 
min_periods = 75 

# Calculate the volatility
vol = daily_pct_change.rolling(min_periods).std() * np.sqrt(min_periods) 

# Plot the volatility
vol.plot(figsize=(10, 8))

# Show the plot
plt.show()
# Plot a scatter matrix with the `daily_pct_change` data 
pd.plotting.scatter_matrix(daily_pct_change, diagonal='kde', alpha=0.1,figsize=(12,12))

# Show the plot
plt.show()

5.2 Basic MACD

import plotly.graph_objects as go

#DE_Data=DE_Data.reset_index()

fig = go.Figure(data=go.Ohlc(x=DE_Data['Date'],
        open=DE_Data['Open'],
        high=DE_Data['High'],
        low=DE_Data['Low'],
        close=DE_Data['Close']))
fig.show()

5.2.1 Basic SMA

#DE_Data=DE_Data.reset_index()

DE_Data['SMA5'] = DE_Data.Close.rolling(5).mean()
DE_Data['SMA20'] = DE_Data.Close.rolling(20).mean()
DE_Data['SMA50'] = DE_Data.Close.rolling(50).mean()
DE_Data['SMA200'] = DE_Data.Close.rolling(200).mean()
DE_Data['SMA500'] = DE_Data.Close.rolling(500).mean()

fig = go.Figure(data=[go.Ohlc(x=DE_Data['Date'],open=DE_Data['Open'],high=DE_Data['High'],low=DE_Data['Low'],close=DE_Data['Close'], name = "OHLC"),
                      go.Scatter(x=DE_Data.Date, y=DE_Data.SMA5, line=dict(color='orange', width=1), name="SMA5"),
                      go.Scatter(x=DE_Data.Date, y=DE_Data.SMA20, line=dict(color='green', width=1), name="SMA20"),
                      go.Scatter(x=DE_Data.Date, y=DE_Data.SMA50, line=dict(color='blue', width=1), name="SMA50"),
                      go.Scatter(x=DE_Data.Date, y=DE_Data.SMA200, line=dict(color='violet', width=1), name="SMA200"),
                      go.Scatter(x=DE_Data.Date, y=DE_Data.SMA500, line=dict(color='purple', width=1), name="SMA500")])
fig.show()

5.2.2 Basic EMA

DE_Data['EMA5'] = DE_Data.Close.ewm(span=5, adjust=False).mean()
DE_Data['EMA20'] = DE_Data.Close.ewm(span=20, adjust=False).mean()
DE_Data['EMA50'] = DE_Data.Close.ewm(span=50, adjust=False).mean()
DE_Data['EMA200'] = DE_Data.Close.ewm(span=200, adjust=False).mean()
DE_Data['EMA500'] = DE_Data.Close.ewm(span=500, adjust=False).mean()

fig = go.Figure(data=[go.Ohlc(x=DE_Data['Date'],
                              open=DE_Data['Open'],
                              high=DE_Data['High'],
                              low=DE_Data['Low'],
                              close=DE_Data['Close'], name = "OHLC"),
                      go.Scatter(x=DE_Data.Date, y=DE_Data.SMA5, line=dict(color='orange', width=1), name="EMA5"),
                      go.Scatter(x=DE_Data.Date, y=DE_Data.SMA20, line=dict(color='green', width=1), name="EMA20"),
                      go.Scatter(x=DE_Data.Date, y=DE_Data.SMA50, line=dict(color='blue', width=1), name="EMA50"),
                      go.Scatter(x=DE_Data.Date, y=DE_Data.SMA200, line=dict(color='violet', width=1), name="EMA200"),
                      go.Scatter(x=DE_Data.Date, y=DE_Data.SMA500, line=dict(color='purple', width=1), name="EMA500")])
fig.show()
DE_Data.head()

Out[18]:

DateOpenHighLowCloseVolumeDividendsStock Splits42252SMA5SMA20SMA50SMA200SMA500EMA5EMA20EMA50EMA200EMA500
02016-08-17 00:00:00-04:0011.63646711.77021911.50271411.50271427151900.0NaNNaNNaNNaNNaNNaNNaN11.50271411.50271411.50271411.50271411.502714
12016-08-18 00:00:00-04:0011.77021811.77021811.36896111.435837176736600.0NaNNaNNaNNaNNaNNaNNaN11.48042211.49634511.50009211.50204911.502447
22016-08-19 00:00:00-04:0011.42246211.63646611.40908711.636466473590000.0NaNNaNNaNNaNNaNNaNNaN11.53243611.50969011.50544011.50338611.502982
32016-08-22 00:00:00-04:0011.50271412.19822711.39571211.676593224590900.0NaNNaNNaNNaNNaNNaNNaN11.58048911.52558511.51215111.50511011.503675
42016-08-23 00:00:00-04:0011.70334312.27847811.63646612.037724148302000.0NaNNaN11.657867NaNNaNNaNNaN11.73290111.57436011.53276211.51040911.505807

6 FINTA Tech Analysis Ratios

Let us do a financial ratios calculation using FINTA library

  • Simple Moving Average ‘SMA’
  • Simple Moving Median ‘SMM’
  • Smoothed Simple Moving Average ‘SSMA’
  • Exponential Moving Average ‘EMA’
  • Double Exponential Moving Average ‘DEMA’
  • Triple Exponential Moving Average ‘TEMA’
  • Triangular Moving Average ‘TRIMA’
  • Triple Exponential Moving Average Oscillator ‘TRIX’
  • Volume Adjusted Moving Average ‘VAMA’
  • Kaufman Efficiency Indicator ‘ER’
  • Kaufman’s Adaptive Moving Average ‘KAMA’
  • Zero Lag Exponential Moving Average ‘ZLEMA’
  • Weighted Moving Average ‘WMA’
  • Hull Moving Average ‘HMA’
  • Elastic Volume Moving Average ‘EVWMA’
  • Volume Weighted Average Price ‘VWAP’
  • Smoothed Moving Average ‘SMMA’
  • Fractal Adaptive Moving Average ‘FRAMA’
  • Moving Average Convergence Divergence ‘MACD’
  • Percentage Price Oscillator ‘PPO’
  • Volume-Weighted MACD ‘VW_MACD’
  • Elastic-Volume weighted MACD ‘EV_MACD’
  • Market Momentum ‘MOM’
  • Rate-of-Change ‘ROC’
  • Relative Strenght Index ‘RSI’
  • Inverse Fisher Transform RSI ‘IFT_RSI’
  • True Range ‘TR’
  • Average True Range ‘ATR’
  • Stop-and-Reverse ‘SAR’
  • Bollinger Bands ‘BBANDS’
  • Bollinger Bands Width ‘BBWIDTH’
  • Momentum Breakout Bands ‘MOBO’
  • Percent B ‘PERCENT_B’
  • Keltner Channels ‘KC’
  • Donchian Channel ‘DO’
  • Directional Movement Indicator ‘DMI’
  • Average Directional Index ‘ADX’
  • Pivot Points ‘PIVOT’
  • Fibonacci Pivot Points ‘PIVOT_FIB’
  • Stochastic Oscillator %K ‘STOCH’
  • Stochastic oscillator %D ‘STOCHD’
  • Stochastic RSI ‘STOCHRSI’
  • Williams %R ‘WILLIAMS’
  • Ultimate Oscillator ‘UO’
  • Awesome Oscillator ‘AO’
  • Mass Index ‘MI’
  • Vortex Indicator ‘VORTEX’
  • Know Sure Thing ‘KST’
  • True Strength Index ‘TSI’
  • Typical Price ‘TP’
  • Accumulation-Distribution Line ‘ADL’
  • Chaikin Oscillator ‘CHAIKIN’
  • Money Flow Index ‘MFI’
  • On Balance Volume ‘OBV’
  • Weighter OBV ‘WOBV’
  • Volume Zone Oscillator ‘VZO’
  • Price Zone Oscillator ‘PZO’
  • Elder’s Force Index ‘EFI’
  • Cummulative Force Index ‘CFI’
  • Bull power and Bear Power ‘EBBP’
  • Ease of Movement ‘EMV’
  • Commodity Channel Index ‘CCI’
  • Coppock Curve ‘COPP’
  • Buy and Sell Pressure ‘BASP’
  • Normalized BASP ‘BASPN’
  • Chande Momentum Oscillator ‘CMO’
  • Chandelier Exit ‘CHANDELIER’
  • Qstick ‘QSTICK’
  • Twiggs Money Index ‘TMF’
  • Wave Trend Oscillator ‘WTO’
  • Fisher Transform ‘FISH’
  • Ichimoku Cloud ‘ICHIMOKU’
  • Adaptive Price Zone ‘APZ’
  • Squeeze Momentum Indicator ‘SQZMI’
  • Volume Price Trend ‘VPT’
  • Finite Volume Element ‘FVE’
  • Volume Flow Indicator ‘VFI’
  • Moving Standard deviation ‘MSD’
  • Schaff Trend Cycle ‘STC’
try:
    from finta import TA
    from backtesting import Backtest, Strategy
    from backtesting.lib import crossover
except:
    !pip install finta backtesting
    from finta import TA
    from backtesting import Backtest, Strategy
    from backtesting.lib import crossover
try:
    from finta import TA
    from backtesting import Backtest, Strategy
    from backtesting.lib import crossover
except:
    !pip install finta backtesting
    from finta import TA
    from backtesting import Backtest, Strategy
    from backtesting.lib import crossover

fin_ma = pd.read_csv('../input/dell-stock-data-latest-and-updated/DELL_stock_history.csv',  
                    parse_dates=True,
                    sep='\t')
print(fin_ma.head())
ohlc=fin_ma
print(TA.SMA(ohlc, 42))
#ohlc.index = ohlc[index].dt.date
function_dict = {' Simple Moving Average ' : 'SMA',
                 ' Simple Moving Median ' : 'SMM',
                 ' Smoothed Simple Moving Average ' : 'SSMA',
                 ' Exponential Moving Average ' : 'EMA',
                 ' Double Exponential Moving Average ' : 'DEMA',
                 ' Triple Exponential Moving Average ' : 'TEMA',
                 ' Triangular Moving Average ' : 'TRIMA',
                 ' Triple Exponential Moving Average Oscillator ' : 'TRIX',
                 ' Volume Adjusted Moving Average ' : 'VAMA',
                 ' Kaufman Efficiency Indicator ' : 'ER',
                 #' Kaufmans Adaptive Moving Average ' : 'KAMA',
                 #' Zero Lag Exponential Moving Average ' : 'ZLEMA',
                 ' Weighted Moving Average ' : 'WMA',
                 ' Hull Moving Average ' : 'HMA',
                 #' Elastic Volume Moving Average ' : 'EVWMA',
                 ' Volume Weighted Average Price ' : 'VWAP',
                 ' Smoothed Moving Average ' : 'SMMA',
                 ' Fractal Adaptive Moving Average ' : 'FRAMA',
                 ' Moving Average Convergence Divergence ' : 'MACD',
                 ' Percentage Price Oscillator ' : 'PPO',
                 ' Volume-Weighted MACD ' : 'VW_MACD',
                 #' Elastic-Volume weighted MACD ' : 'EV_MACD',
                 ' Market Momentum ' : 'MOM',
                 ' Rate-of-Change ' : 'ROC',
                 ' Relative Strength Index ' : 'RSI',
                 ' Inverse Fisher Transform RSI ' : 'IFT_RSI',
                 ' True Range ' : 'TR',
                 ' Average True Range ' : 'ATR',
                 ' Stop-and-Reverse ' : 'SAR',
                 ' Bollinger Bands ' : 'BBANDS',
                 ' Bollinger Bands Width ' : 'BBWIDTH',
                 ' Momentum Breakout Bands ' : 'MOBO',
                 ' Percent B ' : 'PERCENT_B',
                 ' Keltner Channels ' : 'KC',
                 ' Donchian Channel ' : 'DO',
                 ' Directional Movement Indicator ' : 'DMI',
                 ' Average Directional Index ' : 'ADX',
                 ' Pivot Points ' : 'PIVOT',
                 ' Fibonacci Pivot Points ' : 'PIVOT_FIB',
                 ' Stochastic Oscillator Percent K ' : 'STOCH',
                 ' Stochastic oscillator Percent D ' : 'STOCHD',
                 ' Stochastic RSI ' : 'STOCHRSI',
                 ' Williams Percent R ' : 'WILLIAMS',
                 ' Ultimate Oscillator ' : 'UO',
                 ' Awesome Oscillator ' : 'AO',
                 ' Mass Index ' : 'MI',
                 #' Vortex Indicator ' : 'VORTEX',
                 ' Know Sure Thing ' : 'KST',
                 ' True Strength Index ' : 'TSI',
                 ' Typical Price ' : 'TP',
                 ' Accumulation-Distribution Line ' : 'ADL',
                 ' Chaikin Oscillator ' : 'CHAIKIN',
                 ' Money Flow Index ' : 'MFI',
                 ' On Balance Volume ' : 'OBV',
                 ' Weighter OBV ' : 'WOBV',
                 ' Volume Zone Oscillator ' : 'VZO',
                 ' Price Zone Oscillator ' : 'PZO',
                 ' Elders Force Index ' : 'EFI',
                 ' Cummulative Force Index ' : 'CFI',
                 ' Bull power and Bear Power ' : 'EBBP',
                 ' Ease of Movement ' : 'EMV',
                 ' Commodity Channel Index ' : 'CCI',
                 ' Coppock Curve ' : 'COPP',
                 ' Buy and Sell Pressure ' : 'BASP',
                 ' Normalized BASP ' : 'BASPN',
                 ' Chande Momentum Oscillator ' : 'CMO',
                 ' Chandelier Exit ' : 'CHANDELIER',
                 ' Qstick ' : 'QSTICK',
                 #' Twiggs Money Index ' : 'TMF',
                 ' Wave Trend Oscillator ' : 'WTO',
                 ' Fisher Transform ' : 'FISH',
                 ' Ichimoku Cloud ' : 'ICHIMOKU',
                 ' Adaptive Price Zone ' : 'APZ',
                 #' Squeeze Momentum Indicator ' : 'SQZMI',
                 ' Volume Price Trend ' : 'VPT',
                 ' Finite Volume Element ' : 'FVE',
                 ' Volume Flow Indicator ' : 'VFI',
                 ' Moving Standard deviation ' : 'MSD',
                 ' Schaff Trend Cycle ' : 'STC'}


for key, value in function_dict .items():
    function_name = "TA." + value + "(ohlc).plot(title='" + key + "for DELL Stock')"
    print(function_name)
    result = eval(function_name)

7 Back Testing Trading Strategy

# Defining DEMA cross strategy
class DemaCross(Strategy):

    def init(self):

        self.ma1 = self.I(TA.DEMA, ohlc, 10)
        self.ma2 = self.I(TA.DEMA, ohlc, 20)

    def next(self):
        if crossover(self.ma1, self.ma2):
            self.buy()
        elif crossover(self.ma2, self.ma1):
            self.sell()

Let us do a bit of backtesting with a value of $100000

ohlc.head()
print(ohlc.Date)
bt = Backtest(ohlc, DemaCross,
              cash=100000, commission=0.015, exclusive_orders=True)
!pip uninstall bokeh --yes
!pip install bokeh==3.2.1

Back Testing Summary

bt.run()

As you can see, if you had invested $100,000 in DELL shares, you would have got by now a return of 38%! with a peak value of $216,477

data=ohlc
from backtesting import Strategy
from backtesting.lib import crossover
from backtesting.test import SMA
def BBANDS(data, n_lookback, n_std):
    """Bollinger bands indicator"""
    hlc3 = (data.High + data.Low + data.Close) / 3
    mean, std = hlc3.rolling(n_lookback).mean(), hlc3.rolling(n_lookback).std()
    upper = mean + n_std*std
    lower = mean - n_std*std
    return upper, lower


close = data.Close.values
sma10 = SMA(data.Close, 10)
sma20 = SMA(data.Close, 20)
sma50 = SMA(data.Close, 50)
sma100 = SMA(data.Close, 100)
upper, lower = BBANDS(data, 20, 2)

# Design matrix / independent features:

# Price-derived features
data['X_SMA10'] = (close - sma10) / close
data['X_SMA20'] = (close - sma20) / close
data['X_SMA50'] = (close - sma50) / close
data['X_SMA100'] = (close - sma100) / close

data['X_DELTA_SMA10'] = (sma10 - sma20) / close
data['X_DELTA_SMA20'] = (sma20 - sma50) / close
data['X_DELTA_SMA50'] = (sma50 - sma100) / close

# Indicator features
data['X_MOM'] = data.Close.pct_change(periods=2)
data['X_BB_upper'] = (upper - close) / close
data['X_BB_lower'] = (lower - close) / close
data['X_BB_width'] = (upper - lower) / close
#data['X_Sentiment'] = ~data.index.to_series().between('2017-09-27', '2017-12-14')

# Some datetime features for good measure
#data['X_day'] = data.index.dayofweek
#data['X_hour'] = data.index.hour

#data = data.apply(pd.to_numeric)
#data = data.dropna().astype(np.float64)
#data.fillna(method="ffill")
#data =data[~data.isin([np.nan, np.inf, -np.inf]).any(1)]

#data.replace([np.inf, -np.inf], 0.0, inplace=True)
#data = data.fillna(data.mean(), inplace=True)
#data = data.dropna().astype(np.float64)
class Sma4Cross(Strategy):
    n1 = 50
    n2 = 100
    n_enter = 20
    n_exit = 10
    
    def init(self):
        self.sma1 = self.I(SMA, self.data.Close, self.n1)
        self.sma2 = self.I(SMA, self.data.Close, self.n2)
        self.sma_enter = self.I(SMA, self.data.Close, self.n_enter)
        self.sma_exit = self.I(SMA, self.data.Close, self.n_exit)
        
    def next(self):
        
        if not self.position:
            
            # On upwards trend, if price closes above
            # "entry" MA, go long
            
            # Here, even though the operands are arrays, this
            # works by implicitly comparing the two last values
            if self.sma1 > self.sma2:
                if crossover(self.data.Close, self.sma_enter):
                    self.buy()
                    
            # On downwards trend, if price closes below
            # "entry" MA, go short
            
            else:
                if crossover(self.sma_enter, self.data.Close):
                    self.sell()
        
        # But if we already hold a position and the price
        # closes back below (above) "exit" MA, close the position
        
        else:
            if (self.position.is_long and
                crossover(self.sma_exit, self.data.Close)
                or
                self.position.is_short and
                crossover(self.data.Close, self.sma_exit)):
                
                self.position.close()
%%time 

from backtesting import Backtest
from backtesting.test import GOOG


backtest = Backtest(ohlc, Sma4Cross, commission=.002)

stats, heatmap = backtest.optimize(
    n1=range(10, 110, 10),
    n2=range(20, 210, 20),
    n_enter=range(15, 35, 5),
    n_exit=range(10, 25, 5),
    constraint=lambda p: p.n_exit < p.n_enter < p.n1 < p.n2,
    maximize='Equity Final [$]',
    max_tries=200,
    random_state=0,
    return_heatmap=True)

CPU times: user 170 ms, sys: 52.4 ms, total: 223 ms Wall time: 3.94 s

heatmap
hm = heatmap.groupby(['n1', 'n2']).mean().unstack()
hm
n2406080100120140160180200
n1
20NaN7905.6409638509.2736186099.841286NaNNaNNaNNaNNaN
3012905.3844838200.1193869476.78715410009.92966210184.62179210138.2541278734.76071912446.92111213240.048632
40NaN10726.067433NaN9785.5227608992.19980710550.7867438393.88142411124.08595913053.633516
50NaN11485.34028310851.1610238703.9104329231.19247010228.47054011296.82574212663.55355713233.358413
60NaNNaN11374.1210608784.0227329760.6893398140.88202612346.17261612584.16328610558.088613
70NaNNaN10590.5527389798.9349448317.98820711027.7187889579.29914710113.38221112735.625402
80NaNNaNNaN8688.35077410483.4685727327.78117312166.19271411123.92345712871.204344
90NaNNaNNaN9471.4730458776.6507467545.29001510677.80668511347.16207011795.845754
100NaNNaNNaNNaN6882.7979777185.02998511264.64399612415.99100716158.887703

WORK IN PROGRESS

from backtesting.lib import plot_heatmaps

#plot_heatmaps(heatmap, agg='mean')

Conclusion

In the intriguing world of finance, our exploration of DELL stock has unveiled a compelling investment opportunity. Dell Technologies’ enduring presence in the tech sector, along with its diverse product range and consistent financial performance, piques the interest of both seasoned investors and newcomers.

Nonetheless, it’s important to bear in mind that the stock market is an ever-changing landscape, full of surprises.

As you navigate your financial journey, consider diversifying your portfolio and consulting with financial experts to make informed decisions.

In the realm of stocks, one certainty prevails – the future is always full of twists and turns. So, let’s continue watching, learning, and adapting to these dynamic financial markets. Here’s to your investments flourishing and delivering the results you aspire to achieve.


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *