The errors you're encountering stem primarily from missing technical indicators (SMAs) and issues related to DataFrame column types. Let's address each problem step-by-step to ensure your technical analysis scripts run smoothly.
1. Missing SMA Indicators
Issue:
[X] Indicator: sma_10 missing!
[X] Indicator: sma_20 missing!
[X] Indicator: sma_50 missing!
[X] Indicator: sma_200 missing!
Cause:
The CommonStrategy you're using does not include the Simple Moving Averages (SMAs) you're trying to plot. As a result, the columns sma_10, sma_20, sma_50, and sma_200 are not present in your DataFrame.
Solution:
Define a Custom Strategy Including Required SMAs
Instead of relying solely on CommonStrategy, you can create a custom strategy that explicitly includes the SMAs you need. Here's how you can do it:
import pandas_ta as ta
# Define a custom strategy with the required SMAs
custom_strategy = ta.Strategy(
name="CustomStrategy",
ta=[
{"kind": "sma", "length": 10, "append": True},
{"kind": "sma", "length": 20, "append": True},
{"kind": "sma", "length": 50, "append": True},
{"kind": "sma", "length": 200, "append": True},
# Add other indicators as needed
]
)
# Apply the custom strategy to your DataFrame
df_recent.ta.strategy(custom_strategy, verbose=True)
Explanation:
- Custom Strategy: By defining your own strategy, you can control exactly which indicators are calculated and appended to your DataFrame.
- Appending Indicators: The
append=True parameter ensures that the calculated SMAs are added as new columns in your DataFrame.
Alternative Approach: Manually Add SMAs
If you prefer not to define a custom strategy, you can manually add the SMAs to your DataFrame:
df_recent['sma_10'] = ta.sma(df_recent['close'], length=10)
df_recent['sma_20'] = ta.sma(df_recent['close'], length=20)
df_recent['sma_50'] = ta.sma(df_recent['close'], length=50)
df_recent['sma_200'] = ta.sma(df_recent['close'], length=200)
2. FutureWarning Related to Setting NaN
Issue:
FutureWarning: Setting an item of incompatible dtype is deprecated and will raise in a future error of pandas. Value 'nan' has dtype incompatible with int64, please explicitly cast to a compatible dtype first.
dfpad.iloc[:, :] = np.NaN
Cause:
You're attempting to set NaN values in a DataFrame with int64 data types. Since NaN is a float, this operation is deprecated and will raise an error in future pandas versions.
Solution:
Cast DataFrame Columns to Float Before Setting NaN
Modify the _right_pad_df method within your Chart class to ensure that the DataFrame columns are of float type before assigning NaN values.
def _right_pad_df(self, rpad: int, delta_unit: str = "D", range_freq: str = "B"):
if rpad > 0:
dfpad = self.df[-rpad:].copy()
dfpad = dfpad.astype(float) # Convert columns to float
dfpad.iloc[:, :] = np.NaN
df_frequency = self.df.index.to_series().diff().mode()[0] # Most common frequency
freq_delta = pd.Timedelta(df_frequency, unit=delta_unit)
new_dr = pd.date_range(start=self.df.index[-1] + freq_delta, periods=rpad, freq=range_freq)
dfpad.index = new_dr # Update the padded index with new dates
self.df = pd.concat([self.df, dfpad])
Explanation:
- astype(float): This ensures all columns in
dfpad are of float type, making them compatible with NaN.
- Avoiding Future Errors: By explicitly casting to
float, you prevent future compatibility issues when pandas enforces stricter type rules.
3. KeyError: '0'
Issue:
KeyError: '0'
Cause:
The plotting function (_plot method) is trying to access a column named '0' in the DataFrame, which doesn't exist. This column is expected to be present due to the constants added earlier, but it's missing, likely because the indicators weren't properly added.
Solution:
Ensure the '0' Column Exists
The '0' column is intended to be part of the constants added for charting. Verify that the constants are correctly added to your DataFrame before plotting.
-
Check Constants Addition:
Ensure that the constants are added after applying the strategy so that all necessary columns are present.
# Adding constants
chart_lines = np.append(np.arange(-5, 6, 1), np.arange(-100, 110, 10))
df_recent.ta.constants(True, chart_lines) # Adding the constants for the charts
df_recent.ta.constants(False, np.array([-60, -40, 40, 60])) # Removing some constants from the DataFrame
-
Verify the '0' Column:
After adding constants, check if the '0' column exists.
if '0' not in df_recent.columns:
df_recent['0'] = 0 # Manually add the '0' column if missing
-
Update the _plot Method:
Modify the _plot method to handle cases where the '0' column might still be missing, preventing the KeyError.
def _plot(self, **kwargs):
# ... existing code ...
# Ensure '0' column exists
if '0' not in mpfdf.columns:
mpfdf['0'] = 0
# ... rest of the plotting code ...
Explanation:
- Constants Management: The
'0' column is part of the chart's horizontal reference lines (e.g., for ZScore or CLR). Ensuring its existence allows the plotting functions to reference it without errors.
- Graceful Handling: By checking for the
'0' column and adding it if missing, you prevent the KeyError and ensure the chart renders correctly.
4. Comprehensive Revised Code Example
Combining all the solutions above, here's a revised version of your script addressing the errors:
# Install necessary libraries
!pip install mplfinance yfinance pandas_ta
%matplotlib inline
import datetime as dt
import random as rnd
import numpy as np
import pandas as pd
import mplfinance as mpf
import yfinance as yf
import pandas_ta as ta
print(f"\nPandas TA v{ta.version}\nTo install the Latest Version:\n$ pip install -U git+https://github.com/twopirllc/pandas-ta\n")
%pylab inline
%matplotlib inline
# Define the custom strategy
custom_strategy = ta.Strategy(
name="CustomStrategy",
ta=[
{"kind": "sma", "length": 10, "append": True},
{"kind": "sma", "length": 20, "append": True},
{"kind": "sma", "length": 50, "append": True},
{"kind": "sma", "length": 200, "append": True},
# Add other indicators as needed
]
)
# Fetch historical data
def fetch_data(ticker="SPY", period="max", interval="1d", drop_cols=["Dividends", "Stock Splits"]):
df = yf.download(ticker, period=period, interval=interval, auto_adjust=False, progress=False)
df.drop(columns=drop_cols, inplace=True, errors="ignore")
df.index = pd.to_datetime(df.index)
df.columns = df.columns.str.lower()
df.name = ticker
return df
def ta_ylim(series: pd.Series, percent: float = 0.1):
smin, smax = series.min(), series.max()
if isinstance(percent, float) and 0 <= float(percent) <= 1:
y_min = (1 + percent) * smin if smin < 0 else (1 - percent) * smin
y_max = (1 - percent) * smax if smax < 0 else (1 + percent) * smax
return (y_min, y_max)
return (smin, smax)
ticker = "SPY"
df = fetch_data(ticker, period="max")
print(f"{df.name} {df.shape} from {df.index[0].date()} to {df.index[-1].date()}\n{df.describe()}")
df.head()
# Determine recent bars (1 year as default)
def recent_bars(df, tf: str = "1y"):
yearly_divisor = {"all": 0, "10y": 0.1, "5y": 0.2, "4y": 0.25, "3y": 1./3, "2y": 0.5,
"1y": 1, "6mo": 2, "3mo": 4}
yd = yearly_divisor.get(tf, 0)
return int(ta.RATE.get("TRADING_DAYS_PER_YEAR", 252) / yd) if yd > 0 else df.shape[0]
recent = recent_bars(df, tf="1y")
recent_startdate = df.tail(recent).index[0]
recent_enddate = df.tail(recent).index[-1]
df_recent = df.tail(recent).copy()
df_recent.name = ticker
print(f"{df.name} {df_recent.shape} from {recent_startdate.date()} to {recent_enddate.date()}\n{df_recent.describe()}")
df_recent.head()
# Apply the custom strategy
df_recent.ta.strategy(custom_strategy, verbose=True)
# Add constants for plotting
chart_lines = np.append(np.arange(-5, 6, 1), np.arange(-100, 110, 10))
df_recent.ta.constants(True, chart_lines) # Adding the constants for the charts
df_recent.ta.constants(False, np.array([-60, -40, 40, 60])) # Removing some constants
print(f"Columns: {', '.join(list(df_recent.columns))}")
# Define the Chart class (ensure all methods are correctly updated as per solutions)
class Chart(object):
def __init__(self, df: pd.DataFrame = None, strategy: ta.Strategy = ta.CommonStrategy, *args, **kwargs):
self.verbose = kwargs.pop("verbose", False)
if isinstance(df, pd.DataFrame) and hasattr(df.ta, 'datetime_ordered') and df.ta.datetime_ordered:
self.df = df
df_name = str(self.df.name) if getattr(self.df, 'name', None) else "DataFrame"
if self.verbose:
print(f"[i] Loaded {df_name} {self.df.shape}")
else:
print(f"[X] Oops! Missing 'ohlcv' data or index is not datetime ordered.\n")
return None
self._validate_ta_strategy(strategy)
self._validate_mpf_kwargs(**kwargs)
self._validate_chart_kwargs(**kwargs)
# Build TA and Plot
self.df.ta.strategy(self.strategy, verbose=self.verbose)
self._plot(**kwargs)
def _validate_ta_strategy(self, strategy):
if strategy is not None and isinstance(strategy, ta.Strategy):
self.strategy = strategy
elif hasattr(self, 'strategy_ta') and len(self.strategy_ta) > 0:
print(f"[+] Strategy: {self.strategy_name}")
else:
self.strategy = ta.CommonStrategy
def _validate_chart_kwargs(self, **kwargs):
"""Chart Settings"""
self.config = {}
self.config["last"] = kwargs.pop("last", recent_bars(self.df))
self.config["rpad"] = kwargs.pop("rpad", 10)
self.config["title"] = kwargs.pop("title", "Asset")
self.config["volume"] = kwargs.pop("volume", True)
def _validate_mpf_kwargs(self, **kwargs):
# mpf global chart settings
default_chart = mpf.available_styles()[-1]
default_mpf_width = {
'candle_linewidth': 0.6,
'candle_width': 0.525,
'volume_width': 0.525
}
mpfchart = {}
mpf_style = kwargs.pop("style", "")
if mpf_style == "" or mpf_style.lower() == "random":
mpf_styles = mpf.available_styles()
mpfchart["style"] = mpf_styles[rnd.randrange(len(mpf_styles))]
elif mpf_style.lower() in mpf.available_styles():
mpfchart["style"] = mpf_style
else:
mpfchart["style"] = default_chart
mpfchart["figsize"] = kwargs.pop("figsize", (12, 10))
mpfchart["non_trading"] = kwargs.pop("nontrading", False)
mpfchart["rc"] = kwargs.pop("rc", {'figure.facecolor': '#EDEDED'})
mpfchart["plot_ratios"] = kwargs.pop("plot_ratios", (12, 1.7))
mpfchart["scale_padding"] = kwargs.pop("scale_padding", {'left': 1, 'top': 4, 'right': 1, 'bottom': 1})
mpfchart["tight_layout"] = kwargs.pop("tight_layout", True)
mpfchart["type"] = kwargs.pop("type", "candle")
mpfchart["width_config"] = kwargs.pop("width_config", default_mpf_width)
mpfchart["xrotation"] = kwargs.pop("xrotation", 15)
self.mpfchart = mpfchart
def _attribution(self):
print(f"\nPandas v: {pd.__version__} [pip install pandas] https://github.com/pandas-dev/pandas")
print(f"Technical Analysis with Pandas TA v: {ta.version} [pip install pandas_ta] https://github.com/twopirllc/pandas-ta")
print(f"Charts by Matplotlib Finance v: {mpf.__version__} [pip install mplfinance] https://github.com/matplotlib/mplfinance\n")
def _right_pad_df(self, rpad: int, delta_unit: str = "D", range_freq: str = "B"):
if rpad > 0:
dfpad = self.df[-rpad:].copy()
dfpad = dfpad.astype(float) # Convert to float to allow NaN
dfpad.iloc[:, :] = np.NaN
df_frequency = self.df.index.to_series().diff().mode()[0] # Most common frequency
freq_delta = pd.Timedelta(df_frequency, unit=delta_unit)
new_dr = pd.date_range(start=self.df.index[-1] + freq_delta, periods=rpad, freq=range_freq)
dfpad.index = new_dr # Update the padded index with new dates
self.df = pd.concat([self.df, dfpad])
def _plot(self, **kwargs):
if not isinstance(self.mpfchart["plot_ratios"], tuple):
print(f"[X] plot_ratios must be a tuple")
return
# Override Chart Title Option
chart_title = self.config["title"]
if "title" in kwargs and isinstance(kwargs["title"], str):
chart_title = kwargs.pop("title")
# Override Right Bar Padding Option
rpad = self.config["rpad"]
if "rpad" in kwargs and kwargs["rpad"] > 0:
rpad = int(kwargs["rpad"])
def cpanel():
return len(mpf.make_addplot([], panel=self.mpfchart['plot_ratios']))
# Last Second Default TA Indicators
linreg = kwargs.pop("linreg", False)
linreg_name = self.df.ta.linreg(append=True).name if linreg else ""
midpoint = kwargs.pop("midpoint", False)
midpoint_name = self.df.ta.midpoint(append=True).name if midpoint else ""
ohlc4 = kwargs.pop("ohlc4", False)
ohlc4_name = self.df.ta.ohlc4(append=True).name if ohlc4 else ""
clr = kwargs.pop("clr", False)
clr_name = self.df.ta.log_return(cumulative=True, append=True).name if clr else ""
rsi = kwargs.pop("rsi", False)
rsi_length = kwargs.pop("rsi_length", None)
if isinstance(rsi_length, int) and rsi_length > 1:
rsi_name = self.df.ta.rsi(length=rsi_length, append=True).name
elif rsi:
rsi_name = self.df.ta.rsi(append=True).name
else:
rsi_name = ""
zscore = kwargs.pop("zscore", False)
zscore_length = kwargs.pop("zscore_length", None)
if isinstance(zscore_length, int) and zscore_length > 1:
zs_name = self.df.ta.zscore(length=zscore_length, append=True).name
elif zscore:
zs_name = self.df.ta.zscore(append=True).name
else:
zs_name = ""
macd = kwargs.pop("macd", False)
macd_name = ""
if macd:
macds = self.df.ta.macd(append=True)
macd_name = macds.name
squeeze = kwargs.pop("squeeze", False)
lazybear = kwargs.pop("lazybear", False)
squeeze_name = ""
if squeeze:
squeezes = self.df.ta.squeeze(lazybear=lazybear, detailed=True, append=True)
squeeze_name = squeezes.name
ama = kwargs.pop("archermas", False)
ama_name = ""
if ama:
amas = self.df.ta.amat(append=True)
ama_name = amas.name
aobv = kwargs.pop("archerobv", False)
aobv_name = ""
if aobv:
aobvs = self.df.ta.aobv(append=True)
aobv_name = aobvs.name
treturn = kwargs.pop("trendreturn", False)
if treturn:
default_long = self.df["sma_10"] > self.df["sma_20"]
long_trend = kwargs.pop("long_trend", default_long)
if not isinstance(long_trend, pd.Series):
raise ValueError("[X] Must be a Series that has boolean values or values of 0s and 1s")
short_trend = ~long_trend # Opposite/Inverse
self.df["TR"] = ta.trend_return(self.df["close"], long_trend).iloc[:, 1]
# Pad and trim Chart
self._right_pad_df(rpad)
mpfdf = self.df.tail(self.config["last"])
mpfdf_columns = list(mpfdf.columns)
# BEGIN: Custom TA Plots and Panels
taplots = [] # Holds all the additional plots
# Panel 0: Price Overlay
if linreg_name in mpfdf_columns:
taplots += [mpf.make_addplot(mpfdf[linreg_name], type="line",
color="black",
linestyle="-.", width=1.2, panel=0)]
if midpoint_name in mpfdf_columns:
taplots += [mpf.make_addplot(mpfdf[midpoint_name], type="scatter",
color="fuchsia",
width=0.4, panel=0)]
if ohlc4_name in mpfdf_columns:
taplots += [mpf.make_addplot(mpfdf[ohlc4_name], ylabel=ohlc4_name,
type="scatter",
color="blue",
alpha=0.85, width=0.4, panel=0)]
# Check for SMAs
if self.strategy.name == ta.CommonStrategy.name:
total_sma = 0 # Check if all the overlap indicators exist before adding plots
for c in ["sma_10", "sma_20", "sma_50", "sma_200"]:
if c in mpfdf_columns:
total_sma += 1
else:
print(f"[X] Indicator: {c} missing!")
if total_sma == 4:
ta_smas = [
mpf.make_addplot(mpfdf["sma_10"], color="green", width=1.5, panel=0),
mpf.make_addplot(mpfdf["sma_20"], color="orange", width=2, panel=0),
mpf.make_addplot(mpfdf["sma_50"], color="red", width=2, panel=0),
mpf.make_addplot(mpfdf["sma_200"], color="maroon", width=3, panel=0),
]
taplots += ta_smas
if len(ama_name):
amat_sr_ = mpfdf[amas.columns[-1]][mpfdf[amas.columns[-1]] > 0]
amat_sr = amat_sr_.index.to_list()
else:
amat_sr = None
# Panel 1: If volume=True, then add the VOL MA. Since we know there is only one, we immediately pop it.
if self.config["volume"]:
volma_list = [x for x in list(self.df.columns) if x.startswith("vol_")]
if volma_list:
volma = volma_list.pop()
max_vol = mpfdf["volume"].max()
ta_volume = [mpf.make_addplot(mpfdf[volma], color="red", width=2, panel=1,
ylim=(-.2 * max_vol, 1.5 * max_vol))]
taplots += ta_volume
# Panels 2 - 9
common_plot_ratio = (3,)
if aobv_name in mpfdf_columns:
_p = kwargs.pop("aobv_percenty", 0.2)
aobv_ylim = ta_ylim(mpfdf[aobvs.columns[0]], _p)
taplots += [
mpf.make_addplot(mpfdf[aobvs.columns[0]], ylabel=aobv_name, color="black",
width=1.5, panel=cpanel(), ylim=aobv_ylim),
mpf.make_addplot(mpfdf[aobvs.columns[2]], color="silver", width=1, panel=cpanel(), ylim=aobv_ylim),
mpf.make_addplot(mpfdf[aobvs.columns[3]], color="green", width=1, panel=cpanel(), ylim=aobv_ylim),
mpf.make_addplot(mpfdf[aobvs.columns[4]], color="red", width=1.2, panel=cpanel(), ylim=aobv_ylim),
]
self.mpfchart["plot_ratios"] += common_plot_ratio # Required to add a new Panel
if clr_name in mpfdf_columns:
_p = kwargs.pop("clr_percenty", 0.1)
clr_ylim = ta_ylim(mpfdf[clr_name], _p)
taplots += [mpf.make_addplot(mpfdf[clr_name], ylabel=clr_name, color="black",
width=1.5, panel=cpanel(), ylim=clr_ylim)]
if (1 - _p) * mpfdf[clr_name].min() < 0 and (1 + _p) * mpfdf[clr_name].max() > 0:
if '0' not in mpfdf.columns:
mpfdf['0'] = 0 # Ensure '0' exists
taplots += [mpf.make_addplot(mpfdf["0"], color="gray", width=1.2, panel=cpanel(),
ylim=clr_ylim)]
self.mpfchart["plot_ratios"] += common_plot_ratio # Required to add a new Panel
if rsi_name in mpfdf_columns:
rsi_ylim = (0, 100)
taplots += [
mpf.make_addplot(mpfdf[rsi_name], ylabel=rsi_name, color="black",
width=1.5, panel=cpanel(), ylim=rsi_ylim),
mpf.make_addplot(mpfdf["20"], color="green", width=1, panel=cpanel(), ylim=rsi_ylim),
mpf.make_addplot(mpfdf["50"], color="gray", width=0.8, panel=cpanel(), ylim=rsi_ylim),
mpf.make_addplot(mpfdf["80"], color="red", width=1, panel=cpanel(), ylim=rsi_ylim),
]
self.mpfchart["plot_ratios"] += common_plot_ratio # Required to add a new Panel
if macd_name in mpfdf_columns:
_p = kwargs.pop("macd_percenty", 0.15)
macd_ylim = ta_ylim(mpfdf[macd_name], _p)
taplots += [
mpf.make_addplot(mpfdf[macd_name], ylabel=macd_name, color="black",
width=1.5, panel=cpanel()),
mpf.make_addplot(mpfdf[macds.columns[-1]], color="blue",
width=1.1, panel=cpanel()),
mpf.make_addplot(mpfdf[macds.columns[1]], type="bar", alpha=0.8,
color="dimgray", width=0.8, panel=cpanel()),
mpf.make_addplot(mpfdf["0"], color="black",
width=1.2, panel=cpanel()),
]
self.mpfchart["plot_ratios"] += common_plot_ratio # Required to add a new Panel
if zs_name in mpfdf_columns:
_p = kwargs.pop("zascore_percenty", 0.2)
zs_ylim = ta_ylim(mpfdf[zs_name], _p)
taplots += [
mpf.make_addplot(mpfdf[zs_name], ylabel=zs_name, color="black",
width=1.5, panel=cpanel(), ylim=zs_ylim),
mpf.make_addplot(mpfdf["-3"], color="red",
width=1.2, panel=cpanel(), ylim=zs_ylim),
mpf.make_addplot(mpfdf["-2"], color="orange",
width=1, panel=cpanel(), ylim=zs_ylim),
mpf.make_addplot(mpfdf["-1"], color="silver",
width=1, panel=cpanel(), ylim=zs_ylim),
mpf.make_addplot(mpfdf["0"], color="black",
width=1.2, panel=cpanel(), ylim=zs_ylim),
mpf.make_addplot(mpfdf["1"], color="silver",
width=1, panel=cpanel(), ylim=zs_ylim),
mpf.make_addplot(mpfdf["2"], color="orange",
width=1, panel=cpanel(), ylim=zs_ylim),
mpf.make_addplot(mpfdf["3"], color="red",
width=1.2, panel=cpanel(), ylim=zs_ylim)
]
self.mpfchart["plot_ratios"] += common_plot_ratio # Required to add a new Panel
if squeeze_name in mpfdf_columns:
_p = kwargs.pop("squeeze_percenty", 0.6)
sqz_ylim = ta_ylim(mpfdf[squeeze_name], _p)
taplots += [
mpf.make_addplot(mpfdf[squeezes.columns[-4]], type="bar", color="lime",
alpha=0.65, width=0.8, panel=cpanel(), ylim=sqz_ylim),
mpf.make_addplot(mpfdf[squeezes.columns[-3]], type="bar", color="green",
alpha=0.65, width=0.8, panel=cpanel(), ylim=sqz_ylim),
mpf.make_addplot(mpfdf[squeezes.columns[-2]], type="bar", color="maroon",
alpha=0.65, width=0.8, panel=cpanel(), ylim=sqz_ylim),
mpf.make_addplot(mpfdf[squeezes.columns[-1]], type="bar", color="red",
alpha=0.65, width=0.8, panel=cpanel(), ylim=sqz_ylim),
mpf.make_addplot(mpfdf["0"], color="black",
width=1.2, panel=cpanel(), ylim=sqz_ylim),
mpf.make_addplot(mpfdf[squeezes.columns[4]], ylabel=squeeze_name, color="green",
width=2, panel=cpanel(), ylim=sqz_ylim),
mpf.make_addplot(mpfdf[squeezes.columns[5]], color="red",
width=1.8, panel=cpanel(), ylim=sqz_ylim),
]
self.mpfchart["plot_ratios"] += common_plot_ratio # Required to add a new Panel
if treturn:
_p = kwargs.pop("treturn_percenty", 0.33)
treturn_ylim = ta_ylim(mpfdf["TR"], _p)
taplots += [
mpf.make_addplot(mpfdf["TR"], ylabel="Trend Return",
type="bar", color="green", alpha=0.45,
width=0.8, panel=cpanel(), ylim=treturn_ylim),
mpf.make_addplot(mpfdf["TR"], color="black",
width=1.3, panel=cpanel(), ylim=treturn_ylim),
mpf.make_addplot(mpfdf["0"], color="black",
width=1, panel=cpanel(), ylim=treturn_ylim),
]
self.mpfchart["plot_ratios"] += common_plot_ratio # Required to add a new Panel
_p = kwargs.pop("cstreturn_percenty", 0.33)
trcs = mpfdf["close"] / mpfdf["close"].iloc[0]
treturncs_ylim = ta_ylim(trcs, _p)
taplots += [
mpf.make_addplot(trcs, ylabel="Trend B&H",
type="bar", color="green", alpha=0.45,
width=0.8, panel=cpanel(), ylim=treturncs_ylim),
mpf.make_addplot(mpfdf["0"], color="black",
width=1, panel=cpanel(), ylim=treturncs_ylim),
]
self.mpfchart["plot_ratios"] += common_plot_ratio # Required to add a new Panel
# Ensure '0' exists to prevent KeyError
if '0' not in mpfdf.columns:
mpfdf['0'] = 0
# BEGIN: Custom TA Plots and Panels
# ... [rest of the plotting logic remains unchanged]
# END: Custom TA Plots and Panels
if self.verbose:
additional_ta = []
chart_title = f"{chart_title} [{self.strategy.name}] (last {self.config['last']} bars)"
chart_title += f"\nSince {mpfdf.index[0].date()} till {mpfdf.index[-1].date()}"
if len(linreg_name) > 0:
additional_ta.append(linreg_name)
if len(midpoint_name) > 0:
additional_ta.append(midpoint_name)
if len(ohlc4_name) > 0:
additional_ta.append(ohlc4_name)
if len(additional_ta) > 0:
chart_title += f"\nIncluding: {', '.join(additional_ta)}"
if amat_sr:
vlines_ = dict(vlines=amat_sr, alpha=0.1, colors="red")
else:
vlines_ = dict(vlines=mpfdf.index[0], alpha=0, colors="white")
# Create Final Plot
mpf.plot(mpfdf,
title=chart_title,
type=self.mpfchart["type"],
style=self.mpfchart["style"],
datetime_format="%-m/%-d/%Y",
volume=self.config["volume"],
figsize=self.mpfchart["figsize"],
tight_layout=self.mpfchart["tight_layout"],
scale_padding=self.mpfchart["scale_padding"],
panel_ratios=self.mpfchart["plot_ratios"],
xrotation=self.mpfchart["xrotation"],
update_width_config=self.mpfchart["width_config"],
show_nontrading=self.mpfchart["non_trading"],
vlines=vlines_,
addplot=taplots
)
self._attribution()
# Instantiate and plot
Chart(df_recent,
strategy=custom_strategy, # Use the custom strategy
style="yahoo", title=ticker, last=recent_bars(df_recent), rpad=10,
# Overlap Indicators
linreg=True, midpoint=False, ohlc4=False, archermas=True,
# Example Indicators with default parameters
volume=True, rsi=True, clr=True, macd=True, zscore=False, squeeze=False, lazybear=False,
# Archer OBV and OBV MAs
archerobv=False,
# Create trends and see their returns
trendreturn=False,
# Example Trends or create your own. Trend must yield Booleans
long_trend=df_recent["sma_10"] > df_recent["sma_20"], # Ensure SMAs are present
# long_trend=closedf > ta.ema(closedf,5), # trend: close > ema(close,5)
# long_trend=ta.sma(closedf,10) > ta.ema(closedf,50), # trend: sma(close,10) > ema(close,50)
# long_trend=macdh > 0, # trend: macd hist > 0
# long_trend=ta.increasing(ta.sma(ta.rsi(closedf), 10), 5, asint=False), # trend: rising sma(rsi, 10) for the previous 5 periods
show_nontrading=False, # Intraday use if needed
verbose=True, # More detail
)
5. Additional Recommendations
a. Update pandas_ta to the Latest Version
Ensure you're using the latest version of pandas_ta to benefit from recent bug fixes and features.
pip install -U git+https://github.com/twopirllc/pandas-ta
b. Validate Data Integrity
Before performing any operations, always validate that your DataFrame contains the necessary columns.
required_columns = ["sma_10", "sma_20", "sma_50", "sma_200"]
missing_columns = [col for col in required_columns if col not in df_recent.columns]
if missing_columns:
print(f"Missing Columns: {missing_columns}")
# Handle accordingly (e.g., calculate missing indicators)
c. Handle Missing Data Gracefully
Ensure that your plotting functions can handle NaN values or missing columns without crashing. Implement checks and fallback mechanisms as needed.
6. Disclaimer
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, or individual’s trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
Any opinions, news, research, analyses, prices, or other information offered is provided as general market commentary, and does not constitute investment advice. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from use of or reliance on such information.
By implementing the above solutions, you should be able to resolve the errors related to missing indicators and DataFrame column types. Additionally, defining a custom strategy ensures that all necessary technical indicators are calculated and available for your analysis and plotting functions.
If you continue to experience issues, please provide more details or specific code snippets, and I'll be happy to assist further!