!pip install pandasta !pip install mplfinance import numpy as np import pandas as pd…
- User
!pip install pandas_ta !pip install mplfinance
import numpy as np import pandas as pd import pandas_ta as ta import yfinance as yf import matplotlib.pyplot as plt import mplfinance as mpf
Load data file
df = yf.download("^IBEX", start="2023-12-31")
Drop na
df.dropna(axis=0, how='any', inplace=True)
def calculate_emas(df, window): df['Open_EMA'] = df['Open'].ewm(span=window, adjust=False).mean() df['Close_EMA'] = df['Close'].ewm(span=window, adjust=False).mean() df['High_EMA'] = df['High'].ewm(span=window, adjust=False).mean() df['Low_EMA'] = df['Low'].ewm(span=window, adjust=False).mean() return df
def bullish_change(df): df['bullish_change'] = 0 for i in range(1, df.shape[0]): current = df.iloc[i] prev_1 = df.iloc[i - 1] idx = df.index[i] # Use .item() to get the scalar value from the Series for comparison bullish_change = (prev_1['Close'].item() <= prev_1['Open'].item() and current['Close'].item() > current['Open'].item())
if bullish_change: df.loc[idx, 'bullish_change'] = 1 return dfdef bearish_change(df): df['bearish_change'] = 0 for i in range(1, df.shape[0]): current = df.iloc[i] prev_1 = df.iloc[i - 1] idx = df.index[i] # Use .item() to extract the scalar value and ensure a boolean comparison bearish_change = (prev_1['Close'].item() >= prev_1['Open'].item() and current['Close'].item() < current['Open'].item())
if bearish_change: df.loc[idx, 'bearish_change'] = 1 return dfdef transform_to_heikin_ashi_smoothed(df): ha_df = pd.DataFrame(index=df.index)
code# Before calculation, fillna with previous values (ffill method) df.ffill(inplace=True) # Use df.ffill instead of df.fill ha_df['Close'] = (df['Open_EMA'] + df['High_EMA'] + df['Low_EMA'] + df['Close_EMA']) / 4 ha_df['Open'] = df['Open_EMA'] for i in range(1, len(ha_df)): ha_df.iloc[i, ha_df.columns.get_loc('Open')] = ( ha_df.iloc[i-1, ha_df.columns.get_loc('Open')] + ha_df.iloc[i-1, ha_df.columns.get_loc('Close')]) / 2 ha_df['High'] = df[['High_EMA', 'Open_EMA', 'Close_EMA']].max(axis=1) ha_df['Low'] = df[['Low_EMA', 'Open_EMA', 'Close_EMA']].min(axis=1) return ha_dfdef plot_heikin_ashi_and_changes(df): ha_df = df[['Open', 'High', 'Low', 'Close']].copy() ha_df = ha_df.apply(pd.to_numeric, errors='coerce') ha_df = ha_df.dropna()
- Assistant