#_____________________________________________فصل دوم__________________________________________________

#_______________________________نمودار 6.2 قیمت دقیقه ای بیت کوین_____________________________________
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, DateFormatter

df = pd.read_csv('BTCUSDT_ohlc_1m.csv')

data['Time'] = pd.to_datetime(data['timestamp'])

# رسم نمودار
plt.figure(figsize=(12, 6))
plt.plot(data['Time'], data['close'], color='b', label='Minute Prices')
plt.xlabel('Time')
plt.ylabel('Price')
plt.title('Minute Prices of Bitcoin')
plt.legend()
plt.grid(True)

locator = MonthLocator(interval=5) 
formatter = DateFormatter("%Y-%m-%d")  
plt.gca().xaxis.set_major_locator(locator)
plt.gca().xaxis.set_major_formatter(formatter)

plt.show()

#_________________________________نمودار 7.2 لگاریتم بازده قیمت دقیقه ای بیت کوین_____________________________________
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, DateFormatter

df = pd.read_csv('BTCUSDT_ohlc_1m.csv')

data['Time'] = pd.to_datetime(data['timestamp'])

data['r_d'] = np.log(data['close']) - np.log(data['close'].shift(1))

# رسم نمودار
plt.figure(figsize=(12, 6))
plt.plot(data['Time'], data['r_d'], color='b', label='Minute Returns')
plt.xlabel('Time')
plt.ylabel('Minute Returns')
plt.title('Minute Returns of Bitcoin')
plt.legend()
plt.grid(True)

locator = MonthLocator(interval=5)  
formatter = DateFormatter("%Y-%m-%d")  
plt.gca().xaxis.set_major_locator(locator)
plt.gca().xaxis.set_major_formatter(formatter)

plt.show()

#________________________________نمودار 8.2 دسته بندی نمایش نمادین داده های دقیقه ای بیت کوین____________________________________
import matplotlib.pyplot as plt

df = pd.read_csv('bitcoin_ohlc_STSA.csv')

count_0 = (data['S_d'] == 0).sum()
count_1 = (data['S_d'] == 1).sum()

# بار چارت
plt.bar(['0', '1'], [count_0, count_1], width=0.4, alpha=0.7, color=['red', 'blue'])

for i, count in enumerate([count_0, count_1]):
    plt.text(i, count, str(count), ha='center', va='bottom', fontsize=12)

plt.xlabel('S_d Value')
plt.ylabel('Count')
plt.title('Count of 0s and 1s in STSA')
plt.show()


#________________________________جدول 1.2 آنتروپی شانون قیمت روزانه بیت کوین_____________________________________
import pandas as pd
import numpy as np

df = pd.read_csv('bitcoin_ohlc_STSA.csv') 
data['timestamp'] = pd.to_datetime(data['timestamp']) 

counts_by_date = df.groupby(data['timestamp'].dt.date)['S_d'].value_counts().unstack().fillna(0) 
counts_by_date['p_d'] = counts_by_date[1] / (counts_by_date[0] + counts_by_date[1]) 
counts_by_date['1-p_d'] = counts_by_date[0] / (counts_by_date[0] + counts_by_date[1]) 
counts_by_date['H_d'] = -counts_by_date['p_d'] * np.log2(counts_by_date['p_d']) - counts_by_date['1-p_d'] * np.log2(counts_by_date['1-p_d']) 
counts_by_date = counts_by_date[['p_d', '1-p_d', 'H_d']] 

html_table = counts_by_date.to_html() 
html_content = f""" 
<!DOCTYPE html>
<html>
<head>
<style>
table {{
  font-family: Arial, sans-serif; 
  border-collapse: collapse;
  width: 40% ; 
  margin-left: auto;
  margin-right: auto;
}}

th, td {{
  border: 1px solid black; 
  padding: 8px;
  text-align: center;
}}

th {{
  background-color: \# f2f2f2;
}}
</style>
</head>
<body>

<h2>Results Table</h2>
{html_table}

</body>
</html>
"""
with open('table.html', 'w') as file: 
file.write(html_content)


#________________________________نمودار 9.2 آنتروپی شانون قیمت روزانه بیت کوین_____________________________________

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv('bitcoin_ohlc_STSA.csv')

data['timestamp'] = pd.to_datetime(data['timestamp'])

counts_by_date = df.groupby(data['timestamp'].dt.date)['S_d'].value_counts().unstack().fillna(0)

# محاسبه دفعات سود و زیان برای هرروز
counts_by_date['p_d'] = counts_by_date[1] / (counts_by_date[0] + counts_by_date[1])
counts_by_date['1-p_d'] = counts_by_date[0] / (counts_by_date[0] + counts_by_date[1])

# محاسبه آنتروپی برای هرروز
counts_by_date['H_d'] = -counts_by_date['p_d'] * np.log2(counts_by_date['p_d']) - counts_by_date['1-p_d'] * np.log2(counts_by_date['1-p_d'])
print(counts_by_date[['p_d', '1-p_d', 'H_d']])

# رسم نمودار خطی
plt.figure(figsize=(12, 6))
plt.plot(counts_by_date.index, counts_by_date['H_d'], marker='o', linestyle='-')
plt.xlabel('Date')
plt.ylabel('H_d (Shannon Entropy)')
plt.title('Shannon Entropy (H_d) Over Time')
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()


#_______________________________________فصل سوم____________________________________________

#_____________________________نمودار 3.3 قیمت روزانه بیت کوین_______________________________
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, DateFormatter

data = pd.read_csv('bitcoin_ohlc.csv')

data['Time'] = pd.to_datetime(data['Time'])

Close = data['Close']

plt.figure(figsize=(12, 6)) 
plt.plot(data['Time'], Close , color='b', label='Daily Prices') 
plt.xlabel('Time') 
plt.ylabel('Price') 
plt.title('Daily Prices of Bitcoin') 
plt.legend() 
plt.grid(True) 

locator = MonthLocator(interval=3)  
formatter = DateFormatter("%Y-%m-%d")   
plt.gca().xaxis.set_major_locator(locator) 
plt.gca().xaxis.set_major_formatter(formatter) 
plt.gcf().autofmt_xdate(rotation=90)  
plt.show()


#________________________________جدول 1.3 آمار توصیفی قیمت روزانه بیت کوین_____________________________________
import pandas as pd

csv_file_path = "bitcoin_ohlc.csv"
df = pd.read_csv(csv_file_path)

close_data = data["Close"]

# محاسبه آمارتوصیفی
mean = round(close_data.mean(), 2)
median = round(close_data.median(), 2)
std_dev = round(close_data.std(), 2)
min_value = round(close_data.min(), 2)
max_value = round(close_data.max(), 2)
percentile_25 = round(close_data.quantile(0.25), 2)
percentile_75 = round(close_data.quantile(0.75), 2)

descriptive_dict = {
    "Statistic": ["Mean", "Median", "Standard Deviation", "Minimum Value", "Maximum Value", "25th Percentile", "75th Percentile"],
    "Value": [mean, median, std_dev, min_value, max_value, percentile_25, percentile_75]
}

descriptive_df = pd.DataFrame(descriptive_dict)

html_table = descriptive_df.to_html(index=False)

# رسم جدول با کد html
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<style>
table {{
  font-family: Arial, sans-serif;
  border-collapse: collapse;
  width: 38%;
  margin-left: auto;
  margin-right: auto;
}}

th, td {{
  border: 1px solid black;
  padding: 8px;
  text-align: center;
}}

th {{
  background-color: #f2f2f2;
}}
</style>
</head>
<body>

<h2>Descriptive Statistics Table</h2>
{html_table}

</body>
</html>
"""

with open("descriptive_statistics.html", "w") as file:
    file.write(html_content)

print("HTML table saved to descriptive_statistics.html")


#________________________________نمودار 4.3 بازده های روزانه قیمت بیت کوین_____________________________________
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, DateFormatter

data = pd.read_csv('bitcoin_ohlc.csv')

data['Time'] = pd.to_datetime(data['Time'])

close_prices = data['Close']
simple_returns = close_prices - close_prices.shift(1)
data['Returns'] = simple_returns

# رسم نمودار
plt.figure(figsize=(12, 6))
plt.plot(data['Time'], data['Returns'], color='b', label='Daily Returns')
plt.xlabel('Time')
plt.ylabel('Daily Returns')
plt.title('Daily Returns of Bitcoin')
plt.legend()
plt.grid(True)

locator = MonthLocator(interval=3) 
formatter = DateFormatter("%Y-%m-%d")  
plt.gca().xaxis.set_major_locator(locator)
plt.gca().xaxis.set_major_formatter(formatter)
plt.gcf().autofmt_xdate(rotation=90) 

# ذخیره نمودار
plt.tight_layout()
plt.savefig('figreturn.png')


#________________________________توزیع بازده‌های روزانه قیمت بیت‌کوین5.3_____________________________________
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, DateFormatter

df = pd.read_csv('bitcoin_ohlc.csv') 
Close = data["Close"] 
Retruns = Close - Close.shift(1) 
data['Retruns'] = Retruns 

plt.subplot(1, 1, 1) 
plt.hist(Retruns, bins=30, density=True, color='blue', alpha=0.7) 
x = np.linspace(Retruns.min(), Retruns.max(), 100) 
pdf = norm.pdf(x, loc=Retruns.mean(), scale=Retruns.std()) 
plt.plot(x, pdf, 'r-', lw=2) 
plt.title('Distribution of Daily Retruns (PDF)') 
plt.xlabel('Retruns') 
plt.ylabel('Probability Density') 

plt.tight_layout() 
plt.savefig('Retruns_distribution.png')


#________________________________2.3آزمون کلموگوروف-اسمیرنوف برای بازده‌های روزانه_____________________________________
import pandas as pd
import numpy as np
from scipy.stats import norm, kstest
import matplotlib.pyplot as plt
import scipy.stats as stats

df = pd.read_csv('bitcoin_ohlc.csv') 
Close = data["Close"] 
Retruns = Close - Close.shift(1) 
data['Retruns'] = Retruns 

Retruns = Retruns[~np.isnan(Retruns)] 
ks_statistic, ks_p_value = kstest(Retruns, 'norm') 
alpha = 0.05 
test_result _dict = {
    'Test': ['Kolmogorov-Smirnov'],
    'P-value': [round(ks_p_value, 4)],
    'Normal Distribution': ['Yes' if ks_p_value >= alpha else 'No'],
} 

results_df = pd.DataFrame(test_result_dict) 
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<style>
table {{
  font-family: Arial, sans-serif;
  border-collapse: collapse;
  width: 50%;
  margin-left: auto;
  margin-right: auto;
}}

th, td {{
  border: 1px solid black;
  padding: 8px;
  text-align: center;
}}

th {{
  background-color: #f2f2f2;
}}
</style>
</head>
<body>

<h2>Test Result Table</h2>
{html_table}

</body>
</html>
"""

with open("ks_test_return.html", "w") as file:
    file.write(html_content)

#________________________________نمودار 6.3 بازده‌های نرمال‌شده روزانه قیمت بیت‌کوین_____________________________________
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats

df = pd.read_csv('bitcoin_ohlc.csv')
close_prices = data['Close']

window_size = 5  
rolling_std = Retruns.rolling(window=window_size).std() 
Normalized_Retruns = Retruns / rolling_std 
data['Normalized_Retruns'] = Normalized_Retruns 

plt.figure(figsize=(12, 6)) 
plt.plot(data['Time'], data['Normalized_Retruns'], color='b', label='Daily Normalized_Retruns') 
plt.xlabel('Time') 
plt.ylabel('Normalized_Retruns') 
plt.title('Daily Normalized_Retruns of Bitcoin') 
plt.legend() 
plt.grid(True) 

locator = MonthLocator(interval=3)   
formatter = DateFormatter("%Y-%m-%d")  
plt.gca().xaxis.set_major_locator(locator) 
plt.gca().xaxis.set_major_formatter(formatter) 
plt.gcf().autofmt_xdate(rotation=90)  

plt.tight_layout() 
plt.savefig('fignormalizedretruns.png')

#________________________________7.3توزیع بازده‌های نرمال‌شده روزانه قیمت بیت‌کوین_____________________________________
mport pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, DateFormatter

df = pd.read_csv('bitcoin_ohlc.csv')
close_prices = data['Close']

window_size = 5  
rolling_std = Retruns.rolling(window=window_size).std() 
Normalized_Retruns = Retruns / rolling_std 
Normalized_Retruns = data["Normalized_Retruns"] 

plt.subplot(1, 1, 1) 
plt.hist(Normalized_Retruns, bins=30, density=True, color='blue', alpha=0.7) 
x = np.linspace(Normalized_Retruns.min(), Normalized_Retruns.max(), 100) 
pdf = norm.pdf(x, loc=Normalized_Retruns.mean(), scale=Normalized_Retruns.std()) 
plt.plot(x, pdf, 'r-', lw=2) 
plt.title('Distribution of Daily Retruns (PDF)') 
plt.xlabel('Normalized_Retruns') 
plt.ylabel('Probability Density') 

plt.tight_layout() 
plt.savefig('normalizedRetruns_distribution.png')


#________________________________3.3آزمون کلموگوروف-اسمیرنوف برای بازده‌های نرمال‌شده روزانه_____________________________________
import pandas as pd
import numpy as np
from scipy.stats import norm, kstest
import matplotlib.pyplot as plt
import scipy.stats as stats

Normalized_Retruns = Normalized_Retruns[~np.isnan(Normalized_Retruns)]
ks_statistic, ks_p_value = kstest(Normalized_Retruns, 'norm') 
alpha = 0.05
test_result _dict = {
    'Test': ['Kolmogorov-Smirnov'], 
    'P-value': [round(ks_p_value, 4)], 
    'Normal Distribution': ['Yes' if ks_p_value >= alpha else 'No'],
}
results_df = pd.DataFrame(test_result_dict) 
html_table = results_df.to_html(index=False) 
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<style> 
table {{
  font-family: Arial, sans-serif;
  border-collapse: collapse;
  width: 50%;
  margin-left: auto;
  margin-right: auto;
}} 
th, td {{
  border: 1px solid black;
  padding: 8px;
  text-align: center;
}} 
th {{
  background-color: # f2f2f2;
}}
</style>
</head>
<body> 
<h2>Test Result Table</h2>
{html_table}
</body>
</html>
""" 

with open("ks_test_return.html", "w") as file: 
    file.write(html_content)


#________________________________جدول ارزش در معرض خطر محاسبه شده با استفاده از بازده های نرمال شده_____________________________________
simport pandas as pd
import numpy as np
from scipy.stats import norm, kstest
import matplotlib.pyplot as plt
import scipy.stats as stats

data = pd.read_csv('bitcoin_ohlc.csv')

data = data.loc[:, ~data.columns.str.contains('^Unnamed')]

close_prices = data['Close']
dates = pd.to_datetime(data['Time']) 

Returns = close_prices - close_prices.shift(1)
data['Returns'] = Returns

# محاسبه ارزش در معرض خطر با استفاده از بازده های نرمال شده
window_size = 5  # Number of days
rolling_std = Returns.rolling(window=window_size).std()

Normalized_Returns = Returns / rolling_std
data['Normalized_Returns'] = Normalized_Returns

std_dev_normalized_Returns = Normalized_Returns.std()
confidence_level = 0.95
z_score = stats.norm.ppf(1 - confidence_level)

data['VaR'] = -z_score * Returns * std_dev_normalized_Returns

html_table = data.to_html(index=False, escape=False)

# رسم جدول
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<style>
table {{
  font-family: Arial, sans-serif;
  border-collapse: collapse;
  width: 40%;
  margin-left: auto;
  margin-right: auto;
}}

th, td {{
  border: 1px solid black;
  padding: 8px;
  text-align: center;
}}

th:first-child, td:first-child {{
  background-color: #f2f2f2;
  width: 30%; /* Adjust the width to your preference */
}}

</style>
</head>
<body>

<h2>Results Table</h2>
{html_table}

</body>
</html>
"""

with open("VaR.html", "w") as file:
    file.write(html_content)


#________________________________6.3نتایج مدل‌های برآورد خطای پیش‌بینی_____________________________________
data['Absolute_VaR'] = data['VaR'].abs() 
data['Absolute_Retruns'] = data['Retruns'].abs() 
data.to_csv('bitcoin_ohlc_VaR.csv', index=False) 
data_cleaned = data.dropna(subset=['Absolute_VaR', 'Absolute_Retruns']) 
data_cleaned = data_cleaned[5:] 

actual_var = data_cleaned['Absolute_Retruns'].iloc[1:].values 
predicted_var = data_cleaned['Absolute_VaR'].iloc[:-1].values 
mape_var = np.mean(np.abs((actual_var - predicted_var) / actual_var)) 
rmse_var = np.sqrt(np.mean((actual_var - predicted_var)**2)) 
print(f"MAPE for VaR_%95: {mape_var:.2f}%") 
print("RMSE for VaR_%95:", rmse_var) 
results_dict = {
    "Tests": ["answers"],
    "MAPE for VaR_%95": [round(mape_var,4)],
    "RMSE for VaR_%95": [round(rmse_var,4)],
}

results_df = pd.DataFrame(results_dict)

html_table = results_df.to_html(index=False)

html_content = f"""
<!DOCTYPE html>
<html>
<head>
<style>
table {{
  font-family: Arial, sans-serif;
  border-collapse: collapse;
  width: 40%;
  margin-left: auto;
  margin-right: auto;
}}

th, td {{
  border: 1px solid black;
  padding: 8px;
  text-align: center;
}}

th {{
  background-color: #f2f2f2;
}}
</style>
</head>
<body>

<h2>Results Table</h2>
{html_table}

</body>
</html>
"""

with open("model_function_test.html", "w") as file:
    file.write(html_content)



#____________________________________________________________________ربات تلگرام_________________________________________________________________________


#_____________________________________________  LIBRARIES __________________________________________________
import numpy as np
from scipy.stats import norm
import pandas as pd
import requests, time
from telethon.tl.custom import Button
from telethon import TelegramClient, events
from PIL import Image, ImageDraw, ImageFont
import pyttsx3, asyncio
from datetime import datetime
import arabic_reshaper
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
#______________________________________________  FUNCTIONS _________________________________________________
# استراج دیتا
def get_btc_data(period_days):
    url = "https://api.coingecko.com/api/v3/coins/bitcoin/market_chart"

    period_days = period_days

    params = {
        'vs_currency': 'usd',
        'days': period_days,
    }

    response = requests.get(url, params=params)

    if response.status_code == 200:
        data = response.json()


        timestamps = [timestamp for timestamp,_ in data['prices']]
        prices = [price for_, price in data['prices']]


        if timestamps and prices:
    
            btc_data = pd.DataFrame({'Timestamp': timestamps, 'price': prices})

    
            btc_data.to_csv('btc_data.csv', index=False)

        return timestamps, prices
    else:
        print("Failed to fetch BTC data from CoinGecko API.")
        return None, None

# آخرین ارزش در معرض خطر 
def get_last_var_value(csv_file, name_column):
    data = pd.read_csv(csv_file)

    VaR_column = data['VaR']
    price_column = data[name_column]

    last_var_value = VaR_column.iloc[-1]
    last_price_value = price_column.iloc[-1]

    return float(last_price_value), float(last_var_value)

# صدای اعلان 
def sing(text):
    engine = pyttsx3.init()
    engine.setProperty('rate', 150)     
    
    engine.setProperty('volume', 1.0)   
    engine.say(text)
    engine.runAndWait()

def get_data(symbol):
    api_key = '############'
    endpoint = 'https://www.alphavantage.co/query'
    params = {
        'function': 'TIME_SERIES_DAILY',
        'symbol': symbol,
        'outputsize': 'full',  
        'apikey': api_key,
    }
    response = requests.get(endpoint, params=params)
    data = response.json()['Time Series (Daily)']
    
    df = pd.DataFrame(columns=['Time', 'Close'])
    
    for date_str, values in data.items():
        df = df.append({'Time': date_str, 'Close': values['4. close']}, ignore_index=True)
    
    data['Time'] = pd.to_datetime(data['Time'])
    
    df.set_index('Time', inplace=True)
    
    print(df.head(5))
    
    df.to_csv("{}.csv".format(symbol))
    
    return "{}.csv".format(symbol)

# معکوس کردن خطوط دیتا
def reverse_data_rows(input_file, output_file):
    with open(input_file, 'r') as f_in, open(output_file, 'w') as f_out:
        header = f_in.readline()
        
        lines = f_in.readlines()
        reversed_lines = reversed(lines)

        f_out.write(header)
        
        f_out.writelines(reversed_lines)

# پاک کردن سلول
def remove_cell(csv_file, threshold_value):
    df = pd.read_csv(csv_file)

    df_filtered = data[data['Close'] <= threshold_value]

    df_filtered.to_csv('filtered_data.csv', index=False)

# تبدیل به درصد
def calculate_change_var(a, b):
    print("calculate_change_var: {}".format(str(round((a/b)*100, 2))))
    return round((a/b)*100, 2)

# تاریخ و زمان
def date_time():
    current_time = datetime.now()

    current_time_str = current_time.strftime("%H:%M:%S")
    print("Current Date:", current_time.strftime("%Y-%m-%d"))
    print("Current Time:", current_time_str)

    global Date, Time
    Date = current_time.strftime("%Y-%m-%d")
    Time = current_time_str
    return Date, Time

# وارد کردن تصویر زمینه
def import_png():
    global red_img, green_img, green_draw, red_draw
    red_img  = Image.open("red_mode.png")
    red_draw = ImageDraw.Draw(red_img)

    green_img  = Image.open("green_mode.png")
    green_draw = ImageDraw.Draw(green_img)

# نوشتار روی تصویر زمینه
def write_text(text, color, fpath, fsize, max_width, x_me, y_me, drawer, is_persian):
    try:
        font   = ImageFont.truetype(fpath, size=fsize)
        width  = font.getsize(text)[0]
        height = font.getsize(text)[1]
        if width > max_width:
            while True:
                fsize -= 1
                ffont = ImageFont.truetype(fpath, size=fsize)
                width = ffont.getsize(text)[0]
                height = ffont.getsize(text)[1]
                if width <= max_width:
                    break
        else:
            ffont = font
        x_new = x_me - width  / 2
        y_new = y_me - height / 2

        if is_persian:
            bidi_text = arabic_reshaper.reshape(text)
            bidi_text = bidi_text[::-1]
        else:
            bidi_text = text

        drawer.text((x_new, y_new), bidi_text, fill=color, font=ffont)
        return True
    except:
        return False

# تولید محتوای لازم
def tel_alarm(symbol, risk_mode, user_risk, symbol_price, predicted_risk):
    import_png()
    date_time()
    global_date_caption
   _date_caption = "Date: {}".format(Date) + " "*40 +"Time: {}".format(Time)

    # Risk
    if risk_mode == True:
        print("Risk mode is active!!")
        write_text("User Risk Value:  {}%".format(user_risk), "black", "_.ttf", 90, 700, 540, 100, red_draw, False)
        write_text("Last Price {}:  {}$".format(symbol, round(symbol_price)), "black", "_.ttf", 90, 800, 540, 300, red_draw, False)
        write_text("Predicted Risk Value:  {}%".format(predicted_risk), "black", "_.ttf", 90, 1000, 540, 500, red_draw, False)
        write_text(_date_caption, "white", "_.ttf", 50, 1040, 540, 1100, red_draw, False)
        red_img.save("rd.png")
        red_img.show()

    if risk_mode == False:
        print("Safe mode is active!!")
        date_time()
        import_png()
        write_text("User Risk Value:  {}%".format(user_risk), "black", "_.ttf", 90, 700, 540, 100, green_draw, False)
        write_text("Last Price {}:  {}$".format(symbol, round(symbol_price)), "black", "_.ttf", 90, 800, 540, 300, green_draw, False)
        write_text("Predicted Risk Value:  {}%".format(predicted_risk), "black", "_.ttf", 90, 1000, 540, 500, green_draw, False)

        write_text(_date_caption, "white", "_.ttf", 50, 1040, 540, 1100, green_draw, False)

        green_img.save("gr.png")
        green_img.show()

    print("hey body... It is done that related to {}".format(symbol))
    
# بورس تهران
def teh_stock_data():
    try:
        print("request tehran stock!!")
        url = "http://old.tsetmc.com/tsev2/data/Export-txt.aspx?t=i&a=1&b=0&i=2400322364771558"
        response = requests.get(url)
        response.raise_for_status() 
        df = pd.read_csv(url, encoding="utf-8", delimiter=",")

        df.rename(columns={'<CLOSE>': 'Close'}, inplace=True)
        df.rename(columns={'<DTYYYYMMDD>': 'Time'}, inplace=True)

        data[["Time", "Close"]].to_csv("2400322364771558.csv", index=False)

        print(df)
        return "2400322364771558.csv"
    except:
        print("selenium tehran stock!!")
        download_directory = r"D:\arshad\tez\project"

        chrome_options = Options()
        chrome_options.add_argument("--headless")  
        chrome_options.add_argument("--window-size=1920x1080") 
        chrome_options.add_argument("--disable-gpu")
        chrome_options.add_experimental_option("prefs", {
            "download.default_directory": download_directory,
            "download.prompt_for_download": False,
            "download.directory_upgrade": True,
            "safebrowsing.enabled": True
        })

        driver = webdriver.Chrome(executable_path="chromedriver.exe", options=chrome_options)

        url = "http://old.tsetmc.com/tsev2/data/Export-txt.aspx?t=i&a=1&b=0&i=2400322364771558"

        try:
            driver.get(url)

            time.sleep(2)
            
            df = pd.read_csv("Social.Sec.Inv.csv")
            print(df.head(5))
            df.rename(columns={'<CLOSE>': 'Close'}, inplace=True)
            df.rename(columns={'<DTYYYYMMDD>': 'Time'}, inplace=True)

            data[["Time", "Close"]].to_csv("2400322364771558.csv", index=False)

            print("CSV file downloaded successfully")
            return "2400322364771558.csv"

            driver.quit()
        except Exception as e:
            print("Error occurred:", e)
            driver.quit()

    print("download is done shasta!!")

# تغییرات اصلی داده ها
def filter_teh_csv(csv_file):
    df = pd.read_csv(csv_file)

    data["Time"] = pd.to_datetime(data["Time"], format="%Y%m%d")
    
    
    specific_date = pd.to_datetime("20220302", format="%Y%m%d")
    df.loc[data["Time"] < specific_date, "Close"] = df.loc[data["Time"] < specific_date, "Close"] / 27.89052

    decimal_places = 0
    data["Close"] = data["Close"].round(decimal_places)

    df.to_csv("2400322364771558_f.csv", index=False) 

    print("filter Processing completed for shasta!!")
    return "2400322364771558_f.csv"

# نرمال سازی، محاسبه ارزش در معرض خطر و ذخیره فایل
def calculate_var_and_save(csv_file, output_csv_file, target_column, time_column ,window_size=5, confidence_level=0.95):
    data = pd.read_csv(csv_file)
    dates = pd.to_datetime(data[time_column])  

    try:
        condition = data["Close"] == 759

        print("759 removed")
        filtered_data = data[~condition]

        filtered_data.to_csv(csv_file, index=False)
    except:
        pass
    data = pd.read_csv(csv_file)
    close_prices = data[target_column]




    simple_returns = close_prices - close_prices.shift(1)

    rolling_std = simple_returns.rolling(window=window_size).std()

    Normalized_returns = simple_returns / rolling_std
    
    data['Normalized_returns'] = Normalized_returns
    data['Normalized_returns'] = data['Normalized_returns'].fillna(0)


    print("Normalized_returns: ")
    print(Normalized_returns)
    print("__________________________________")


    std_dev_normalized_Retruns = Normalized_returns.std()
    print("std_dev_normalized_Retruns: {}".format(std_dev_normalized_Retruns))

    print("__________________________________")

    z_score = stats.norm.ppf(1 - confidence_level)
    print("z_score: {}".format(z_score))
    print("__________________________________")


    data['VaR'] = abs(-z_score * simple_returns * std_dev_normalized_Retruns)

    print(data)

    data.to_csv(output_csv_file, index=False)

#__________________________________________ TELEGRAM INFO____________________________________________________
name     = "        "
api_id   = #########
api_hash = "####################"
tokenBot = '##########################'
client   = TelegramClient(name, api_id, api_hash)
client.start(bot_token= tokenBot)

#___________________________________________ SEND MESSAGES___________________________________________________
user_risk_value = None
waiting_for_risk_response = False

@events.register(events.NewMessage(pattern='/var'))
async def NewMessage(event):
    global waiting_for_risk_response
    print('event.chat_id: {}'.format(event.sender_id))

    await event.respond('**How much is your risk?(percentage)**')

    waiting_for_risk_response = True
    await asyncio.sleep(10)

@events.register(events.NewMessage)
async def handle_all_messages(event):
    global waiting_for_risk_response, user_risk_value

    if waiting_for_risk_response:
        user_risk_value = event.text
        print("user_risk_value: ", user_risk_value)
        user_risk_value = float(user_risk_value)

        waiting_for_risk_response = False

        await event.reply('**📉Please select your Stock-Market📈**', buttons=[
            [
                Button.inline("Bitcoin", b"bitcoin"),
                Button.inline("Gold", b"gold"),
                Button.inline("Tesla", b"tesla"),
                Button.inline("شستا", b"shasta")
            ],
        ])

@client.on(events.CallbackQuery)
async def button_click(event):
    print("Var bot is ready...")

    callback_data = event.data.decode("utf-8")
    
    # دکمه بیت کوین
    if callback_data == "bitcoin":
        timestamps, prices = get_btc_data(period_days = 100)
        calculate_var_and_save(csv_file= "btc_data.csv",
                            output_csv_file= "output_calculate_bitcoin_var.csv",
                            target_column= "price",
                            time_column= "Timestamp",
                            window_size=5,
                            confidence_level=0.95)
                            
        print('Bitcoin data is ready!')
        last_price_value, last_var_value = get_last_var_value(csv_file= "output_calculate_bitcoin_var.csv", name_column= 'price')

        print("Last VaR value(BITCOIN):", round(last_var_value))
        print("Last Price value(BITCOIN):", round(last_price_value))

        bitcoin_price = last_price_value
        sing("Bitcoin price is {}".format(round(bitcoin_price)))

        predicted_risk_value = calculate_change_var(last_var_value, last_price_value)
        print("predicted_risk_value: ", predicted_risk_value)

        if predicted_risk_value > user_risk_value:
            tel_alarm(symbol= "BITCOIN", risk_mode= True, user_risk= user_risk_value, symbol_price= bitcoin_price, predicted_risk= predicted_risk_value)

            await client.send_message(event.sender_id,
                                    "**🚨The risk of BITCOIN is more than {}🚨**".format(user_risk_value),
                                    file= "rd.png")
            sing("The risk of BITCOIN is more than {}".format(str(user_risk_value)))
        else:
            tel_alarm(symbol= "BITCOIN", risk_mode= False, user_risk= user_risk_value, symbol_price= bitcoin_price, predicted_risk= predicted_risk_value)

            await client.send_message(event.sender_id,
                                    "**🟢The risk is safe!!🟢**",
                                    file= "gr.png")
            sing("The risk of BITCOIN is safe")
        
    # دکمه طلا
    if callback_data == "gold":
        file_name = get_data('XAUUSD')
        print("XAUUSD data is ready!")

        if__name__ == "__main__":
            input_file_path  = file_name 
            output_file_path = "_{}".format(file_name) 
            reverse_data_rows(input_file_path, output_file_path)

        remove_cell(csv_file= output_file_path, threshold_value= 2090)

        calculate_var_and_save(csv_file= "filtered_data.csv",
                            output_csv_file= "output_calculate_gold_var.csv",
                            target_column= "Close",
                            time_column= "Time",
                            window_size=5,
                            confidence_level=0.95)

        last_price_value, last_var_value = get_last_var_value(csv_file= "output_calculate_gold_var.csv", name_column= 'Close')

        print("Last VaR value(GOLD):", round(last_var_value))
        print("Last Price value(GOLD):", round(last_price_value))

        gold_price = last_price_value
        sing("Gold price is {}".format(round(gold_price)))

        predicted_risk_value = calculate_change_var(last_var_value, last_price_value)
        print("predicted_risk_value: ", predicted_risk_value)

        if predicted_risk_value > user_risk_value:
            tel_alarm(symbol= "GOLD", risk_mode= True, user_risk= user_risk_value, symbol_price= gold_price, predicted_risk= predicted_risk_value)

            await client.send_message(event.sender_id,
                                    "**🚨The risk of GOLD is more than {}🚨**".format(user_risk_value),
                                    file= "rd.png")
            sing("The risk of GOLD is more than {}".format(user_risk_value))
        else:
            tel_alarm(symbol= "GOLD", risk_mode= False, user_risk= user_risk_value, symbol_price= gold_price, predicted_risk= predicted_risk_value)

            await client.send_message(event.sender_id, 
                                    "**🟢The risk of GOLD is safe!!🟢**",
                                    file= "gr.png")
            sing("The risk of GOLD is safe")

    # دکمه تسلا
    if callback_data == "tesla":
        file_name = get_data('TSLA')
        print("TSLA data is ready!")

        if__name__ == "__main__":
            input_file_path  = file_name 
            output_file_path = "_{}".format(file_name)
            reverse_data_rows(input_file_path, output_file_path)

        calculate_var_and_save(csv_file= output_file_path,
                            output_csv_file= "output_calculate_tsla_var.csv",
                            target_column= "Close",
                            time_column= "Time",
                            window_size=5,
                            confidence_level=0.95)

        last_price_value, last_var_value = get_last_var_value(csv_file= "output_calculate_tsla_var.csv", name_column= 'Close')

        print("Last VaR value(TESLA):", round(last_var_value))
        print("Last Price value(TESLA):", round(last_price_value))

        tsla_price = last_price_value
        sing("Tesla price is {}".format(round(tsla_price)))

        predicted_risk_value = calculate_change_var(last_var_value, last_price_value)
        print("predicted_risk_value: ", predicted_risk_value)

        if predicted_risk_value > user_risk_value:
            tel_alarm(symbol= "TESLA",risk_mode= True, user_risk= user_risk_value, symbol_price= tsla_price, predicted_risk= predicted_risk_value)

            await client.send_message(event.sender_id,
                                    "**🚨The risk of TESLA is more than {}🚨**".format(user_risk_value),
                                    file= "rd.png")
            sing("The risk of TESLA is more than {}".format(user_risk_value))
        else:
            tel_alarm(symbol= "TESLA",risk_mode= False, user_risk= user_risk_value, symbol_price= tsla_price, predicted_risk= predicted_risk_value)

            await client.send_message(event.sender_id,
                                    "**🟢The risk of TESLA is safe!!🟢**",
                                    file= "gr.png")
            sing("The risk of TESLA is safe")

    # دکمه شستا
    if callback_data == "shasta":
        # Handles of shasta tasks
        teh_stock_data()
        file_name = filter_teh_csv(csv_file= "2400322364771558.csv")

        if__name__ == "__main__":
            input_file_path  = file_name 
            output_file_path = "_{}".format(file_name)
            reverse_data_rows(input_file_path, output_file_path)    
            print("SHASTA data is ready!")

        calculate_var_and_save(csv_file= output_file_path,
                            output_csv_file= "output_calculate_shasta_var.csv",
                            target_column= "Close",
                            time_column= "Time",
                            window_size=5,
                            confidence_level=0.95)

        print('Shasta data is ready!')
        # global last_var_value, last_price_value
        last_price_value, last_var_value = get_last_var_value(csv_file= "output_calculate_shasta_var.csv", name_column= 'Close')

        print("Last VaR value(شستا):", round(last_var_value))
        print("Last Price value(شستا):", round(last_price_value))

        shasta_price = last_price_value
        sing("Shasta price is {}".format(round(shasta_price)))

        predicted_risk_value = calculate_change_var(last_var_value, last_price_value)
        print("predicted_risk_value: ", predicted_risk_value)

        if predicted_risk_value > user_risk_value:
            # Pil operation(png file)_RED MODE
            tel_alarm(symbol= "SHASTA", risk_mode= True, user_risk= user_risk_value, symbol_price= shasta_price, predicted_risk= predicted_risk_value)

            # Send Alarm message(txt)
            await client.send_message(event.sender_id,
                                    "**🚨The risk of shasta is more than {}🚨**".format(user_risk_value),
                                    file= "rd.png")
            sing("The risk of shasta is more than {}".format(str(user_risk_value)))
        else:
            # Pil operation(png file)_SAFE MODE
            tel_alarm(symbol= "SHASTA", risk_mode= False, user_risk= user_risk_value, symbol_price= shasta_price, predicted_risk= predicted_risk_value)

            # Send Safe message(txt)
            await client.send_message(event.sender_id,
                                    "**🟢The risk is safe!!🟢**",
                                    file= "gr.png")
            sing("The risk of shasta is safe")
    

with client:
    client.add_event_handler(NewMessage)
    time.sleep(5)
    client.add_event_handler(handle_all_messages)


    print("done")
    client.run_until_disconnected()

client.add_event_handler(button_click)


