import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import yfinance as yf
from scipy.stats import norm

# Fetching data
data = yf.download(tickers="GBPUSD=X", period="3mo", interval="1h")['Close']
data.dropna(inplace=True)

# Calculating Z-score
x = data
y = x.rolling(window=20).mean()
z = x.rolling(window=20).std()
score = (x - y) / z

# Calculate critical values
critical_values = [0, 1.96, -1.95, 2.58, -2.58, 3.26, -3.26]
critical_prices = [x.iloc[-1] + z.iloc[-1] * cv for cv in critical_values]

# Define significance levels and probabilities
significance_levels = critical_values
probabilities = [1 - norm.cdf(c) for c in critical_values]
probabilities_percent = [p * 100 for p in probabilities]  # Convert probabilities to percentages

# Probability Signal
probability_signal = norm.cdf(score.iloc[-1])

# Bias (Buy/Sell)
bias = "Buy" if score.iloc[-1] > 0 else "Sell"

# Algorithmic Signal
algorithmic_signal = "Buy" if probability_signal > 0.6613754380 else "Sell"

# Points based on average prices and standard deviation
point_bas = y.iloc[-1] - z.iloc[-1]  # Point below average
point_hout = y.iloc[-1] + z.iloc[-1]  # Point above average
point_de_retournement = y.iloc[-1]  # Turning point is the average
smart_inflation_point = y.iloc[-1] * 1.02  # Smart inflation point with 2% increase
zero_revision_level = y.iloc[-1] * 0.98  # Zero revision point with 2% decrease

# Displaying the data
print("point_bas:", point_bas)
print("point_hout:", point_hout)
print("point_de_retournement:", point_de_retournement)
print("smart_inflation_point:", smart_inflation_point)
print("zero_revision_level:", zero_revision_level)

# Display lengths of arrays
print("Length of critical_values:", len(critical_values))
print("Length of significance_levels:", len(significance_levels))

# Display critical values, significance levels, and probabilities
table_data = pd.DataFrame({
    'Critical Value': critical_values,
    'Significance Level': significance_levels,
    'Price': critical_prices,
    'Probability': probabilities_percent,  # Add probabilities percentage column
    'Market Location': np.random.choice(['Random', 'Clustered', 'Dispersed'], size=len(critical_values)),
    'Bias': np.random.choice(['Neutral', bias], size=len(critical_values))
})

table_data.set_index('Critical Value', inplace=True)
table_data.index.name = 'Threshold'
print(table_data)

# Plotting Z-score and closing prices
fig, ax1 = plt.subplots(figsize=(20, 15))

color = 'tab:red'
ax1.set_xlabel('Date')
ax1.set_ylabel('Closing Prices', color=color)
ax1.plot(data.index, data, color=color)
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('Z-Score', color=color)
ax2.plot(score.index, score, color=color)
ax2.axhline(0, color='black')
ax2.axhline(1.96, color='red')
ax2.axhline(-1.96, color='green')
ax2.axhline(2.58, color='red')
ax2.axhline(-2.58, color='green')
ax2.axhline(3.26, color='red')
ax2.axhline(-3.26, color='green')

# Adding markers for the added points
ax1.scatter([data.index.min(), data.index.max(), data.index[-1]], [point_bas, point_hout, point_de_retournement],
            color='green', label='Points')
ax1.scatter(data.index.min(), smart_inflation_point, color='blue', label='Smart Inflation Point')
ax1.scatter(data.index[-1], zero_revision_level, color='red', label='Zero Revision Level')

# Display legend
ax1.legend()

fig.tight_layout()
plt.title('Closing Prices And Z-Score')
plt.show()                                 قم بتصحيح هذا الكود لانني عندما اقوم باستخدامه تظهر رساله الخطا المهم هذه الرساله التي تظهر ها هي          ValueError                                Traceback (most recent call last)
<ipython-input-16-b1c55399144b> in <cell line: 30>()
     28 
     29 # Bias (Buy/Sell)
---> 30 bias = "Buy" if score.iloc[-1] > 0 else "Sell"
     31 
     32 # Algorithmic Signal

/usr/local/lib/python3.10/dist-packages/pandas/core/generic.py in __nonzero__(self)
   1575     @final
   1576     def __nonzero__(self) -> NoReturn:
-> 1577         raise ValueError(
   1578             f"The truth value of a {type(self).__name__} is ambiguous. "
   1579             "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.any() or a.all().