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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from datetime import datetime, timedelta
|
| 3 |
+
import yfinance as yf
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from sklearn.decomposition import PCA
|
| 7 |
+
from sklearn.preprocessing import StandardScaler, LabelEncoder
|
| 8 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 9 |
+
import shap
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
|
| 12 |
+
class DataFetcher:
|
| 13 |
+
"""Fetches historical financial data using yfinance."""
|
| 14 |
+
def __init__(self, ticker, nb_days):
|
| 15 |
+
self.ticker = ticker
|
| 16 |
+
self.nb_days = nb_days
|
| 17 |
+
self.data = None
|
| 18 |
+
|
| 19 |
+
def fetch_data(self):
|
| 20 |
+
"""Fetches historical data for the specified ticker and number of days."""
|
| 21 |
+
end_date = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
|
| 22 |
+
start_date = end_date - timedelta(days=self.nb_days)
|
| 23 |
+
end_date = end_date + timedelta(days=1)
|
| 24 |
+
self.data = yf.download(self.ticker, start=start_date, end=end_date, interval="1h")
|
| 25 |
+
return self.data
|
| 26 |
+
|
| 27 |
+
class FinancialDataProcessor:
|
| 28 |
+
"""Processes financial data to calculate returns, scenarios, and probabilities."""
|
| 29 |
+
def __init__(self, data):
|
| 30 |
+
self.data = data.copy()
|
| 31 |
+
|
| 32 |
+
def _flatten_columns(self):
|
| 33 |
+
"""Flattens MultiIndex columns into a single level."""
|
| 34 |
+
if isinstance(self.data.columns, pd.MultiIndex):
|
| 35 |
+
self.data.columns = [f"{col[0]}_{col[1]}" if col[1] else col[0] for col in self.data.columns]
|
| 36 |
+
|
| 37 |
+
def calculate_returns(self):
|
| 38 |
+
"""Calculates logarithmic returns, scenarios, and adjusted returns."""
|
| 39 |
+
self._flatten_columns()
|
| 40 |
+
|
| 41 |
+
close_column = [col for col in self.data.columns if 'Close' in col]
|
| 42 |
+
if not close_column:
|
| 43 |
+
raise ValueError("The 'Close' column is missing in the dataset.")
|
| 44 |
+
|
| 45 |
+
self.data.rename(columns={close_column[0]: 'Close'}, inplace=True)
|
| 46 |
+
self.data = self.data[self.data['Close'] > 0].copy()
|
| 47 |
+
|
| 48 |
+
self.data['LogReturn'] = np.log(self.data['Close'] / self.data['Close'].shift(1))
|
| 49 |
+
self.data.replace([np.inf, -np.inf], np.nan, inplace=True)
|
| 50 |
+
self.data.dropna(subset=['LogReturn'], inplace=True)
|
| 51 |
+
|
| 52 |
+
self.data['Scenario'] = np.where(self.data['LogReturn'] > 0, 'Buy', 'Sell')
|
| 53 |
+
self.data['AdjustedLogReturn'] = np.where(
|
| 54 |
+
self.data['Scenario'] == 'Sell', -self.data['LogReturn'], self.data['LogReturn']
|
| 55 |
+
)
|
| 56 |
+
self.data['AnnualizedReturn'] = self.data['AdjustedLogReturn'] * 252
|
| 57 |
+
|
| 58 |
+
return self
|
| 59 |
+
|
| 60 |
+
def calculate_probabilities(self):
|
| 61 |
+
"""Calculates Buy% and Sell% using hyperbolic tangent."""
|
| 62 |
+
self.data['Buy%'] = (1 + np.tanh(self.data['LogReturn'])) / 2
|
| 63 |
+
self.data['Sell%'] = (1 - np.tanh(self.data['LogReturn'])) / 2
|
| 64 |
+
return self.data
|
| 65 |
+
|
| 66 |
+
def apply_pca_calculations(self, pca_result):
|
| 67 |
+
"""Applies PCA-based calculations to the data."""
|
| 68 |
+
pca_result = pca_result[pca_result['PC1'] > 0].copy()
|
| 69 |
+
|
| 70 |
+
pca_result['PCA_LogReturn'] = np.log(pca_result['PC1'] / pca_result['PC1'].shift(1))
|
| 71 |
+
pca_result.replace([np.inf, -np.inf], np.nan, inplace=True)
|
| 72 |
+
pca_result.dropna(subset=['PCA_LogReturn'], inplace=True)
|
| 73 |
+
|
| 74 |
+
pca_result['PCA_Scenario'] = np.where(pca_result['PCA_LogReturn'] > 0, 'Buy', 'Sell')
|
| 75 |
+
pca_result['PCA_Buy%'] = (1 + np.tanh(pca_result['PCA_LogReturn'])) / 2
|
| 76 |
+
pca_result['PCA_Sell%'] = (1 - np.tanh(pca_result['PCA_LogReturn'])) / 2
|
| 77 |
+
|
| 78 |
+
self.data = self.data.merge(pca_result, left_index=True, right_index=True)
|
| 79 |
+
return self.data
|
| 80 |
+
|
| 81 |
+
class PCATransformer:
|
| 82 |
+
"""Applies PCA to reduce dimensionality and extract features."""
|
| 83 |
+
def __init__(self, n_components=1):
|
| 84 |
+
self.n_components = n_components
|
| 85 |
+
self.scaler = StandardScaler()
|
| 86 |
+
self.pca = PCA(n_components=n_components)
|
| 87 |
+
|
| 88 |
+
def fit_transform(self, data):
|
| 89 |
+
numeric_data = data.select_dtypes(include=[np.number])
|
| 90 |
+
scaled_data = self.scaler.fit_transform(numeric_data)
|
| 91 |
+
pca_result = self.pca.fit_transform(scaled_data)
|
| 92 |
+
return pd.DataFrame(pca_result, columns=[f'PC{i+1}' for i in range(self.n_components)], index=data.index)
|
| 93 |
+
|
| 94 |
+
class StrategyBuilder:
|
| 95 |
+
"""Builds and refines the trading strategy using machine learning and SHAP."""
|
| 96 |
+
def __init__(self, data):
|
| 97 |
+
self.data = data.copy()
|
| 98 |
+
|
| 99 |
+
def train_model(self, target_column):
|
| 100 |
+
X = self.data.select_dtypes(include=[np.number])
|
| 101 |
+
y = self.data[target_column]
|
| 102 |
+
y_encoded = LabelEncoder().fit_transform(y)
|
| 103 |
+
model = RandomForestClassifier(n_estimators=100, random_state=42)
|
| 104 |
+
model.fit(X, y_encoded)
|
| 105 |
+
return model, X, y_encoded
|
| 106 |
+
|
| 107 |
+
def compute_shapley_values(self, model, X):
|
| 108 |
+
explainer = shap.TreeExplainer(model)
|
| 109 |
+
return explainer.shap_values(X)
|
| 110 |
+
|
| 111 |
+
def analyze_feature_importance(self, shap_values, feature_names):
|
| 112 |
+
"""Analyzes feature importance based on SHAP values."""
|
| 113 |
+
if isinstance(shap_values, list):
|
| 114 |
+
shap_values = shap_values[1]
|
| 115 |
+
|
| 116 |
+
if len(shap_values.shape) == 3:
|
| 117 |
+
shap_values = shap_values[:, :, 1]
|
| 118 |
+
|
| 119 |
+
mean_abs_shap = np.mean(np.abs(shap_values), axis=0)
|
| 120 |
+
|
| 121 |
+
if len(mean_abs_shap) != len(feature_names):
|
| 122 |
+
raise ValueError("Mismatch between SHAP values and feature names.")
|
| 123 |
+
|
| 124 |
+
feature_importance = pd.DataFrame({
|
| 125 |
+
'Feature': feature_names,
|
| 126 |
+
'Mean_Abs_SHAP': mean_abs_shap
|
| 127 |
+
}).sort_values(by='Mean_Abs_SHAP', ascending=False)
|
| 128 |
+
|
| 129 |
+
return feature_importance
|
| 130 |
+
|
| 131 |
+
def refine_thresholds(self, feature_importance, buy_threshold=0.5, sell_threshold=0.5):
|
| 132 |
+
top_features = feature_importance.head(3)['Feature'].tolist()
|
| 133 |
+
for feature in top_features:
|
| 134 |
+
if 'Buy%' in feature or 'PCA_Buy%' in feature:
|
| 135 |
+
buy_threshold *= 1.1
|
| 136 |
+
elif 'Sell%' in feature or 'PCA_Sell%' in feature:
|
| 137 |
+
sell_threshold *= 1.1
|
| 138 |
+
return buy_threshold, sell_threshold
|
| 139 |
+
|
| 140 |
+
class Backtester:
|
| 141 |
+
"""Backtests the trading strategy on historical data."""
|
| 142 |
+
def __init__(self, data):
|
| 143 |
+
self.data = data.copy()
|
| 144 |
+
|
| 145 |
+
def backtest(self, buy_threshold=0.5, sell_threshold=0.5):
|
| 146 |
+
portfolio_value = 10000
|
| 147 |
+
position = None
|
| 148 |
+
entry_price = None
|
| 149 |
+
portfolio_values = []
|
| 150 |
+
|
| 151 |
+
for i in range(1, len(self.data)):
|
| 152 |
+
last_row = self.data.iloc[i]
|
| 153 |
+
if (last_row['PCA_Scenario'] == 'Buy' and last_row['PCA_Buy%'] > buy_threshold) or \
|
| 154 |
+
(last_row['Scenario'] == 'Buy' and last_row['Buy%'] > buy_threshold):
|
| 155 |
+
if position != 'Buy':
|
| 156 |
+
position = 'Buy'
|
| 157 |
+
entry_price = last_row['Close']
|
| 158 |
+
elif (last_row['PCA_Scenario'] == 'Sell' and last_row['PCA_Sell%'] > sell_threshold) or \
|
| 159 |
+
(last_row['Scenario'] == 'Sell' and last_row['Sell%'] > sell_threshold):
|
| 160 |
+
if position != 'Sell':
|
| 161 |
+
position = 'Sell'
|
| 162 |
+
entry_price = last_row['Close']
|
| 163 |
+
|
| 164 |
+
if position == 'Buy':
|
| 165 |
+
portfolio_value *= (last_row['Close'] / entry_price)
|
| 166 |
+
elif position == 'Sell':
|
| 167 |
+
portfolio_value *= (entry_price / last_row['Close'])
|
| 168 |
+
|
| 169 |
+
portfolio_values.append(portfolio_value)
|
| 170 |
+
|
| 171 |
+
return portfolio_values, position, entry_price
|
| 172 |
+
|
| 173 |
+
def run_analysis():
|
| 174 |
+
"""Runs the complete trading analysis."""
|
| 175 |
+
try:
|
| 176 |
+
fetcher = DataFetcher(ticker="^DJI", nb_days=50)
|
| 177 |
+
data = fetcher.fetch_data()
|
| 178 |
+
|
| 179 |
+
processor = FinancialDataProcessor(data)
|
| 180 |
+
processed_data = processor.calculate_returns().calculate_probabilities()
|
| 181 |
+
|
| 182 |
+
pca_transformer = PCATransformer(n_components=1)
|
| 183 |
+
pca_result = pca_transformer.fit_transform(processed_data)
|
| 184 |
+
processed_data = processor.apply_pca_calculations(pca_result)
|
| 185 |
+
|
| 186 |
+
strategy_builder = StrategyBuilder(processed_data)
|
| 187 |
+
model, X, y_encoded = strategy_builder.train_model(target_column='PCA_Scenario')
|
| 188 |
+
shap_values = strategy_builder.compute_shapley_values(model, X)
|
| 189 |
+
|
| 190 |
+
feature_importance = strategy_builder.analyze_feature_importance(shap_values, X.columns)
|
| 191 |
+
buy_threshold, sell_threshold = strategy_builder.refine_thresholds(feature_importance)
|
| 192 |
+
|
| 193 |
+
backtester = Backtester(processed_data)
|
| 194 |
+
portfolio_values, final_position, entry_price = backtester.backtest(buy_threshold, sell_threshold)
|
| 195 |
+
|
| 196 |
+
last_row = processed_data.iloc[-1]
|
| 197 |
+
|
| 198 |
+
# Display results
|
| 199 |
+
col1, col2 = st.columns(2)
|
| 200 |
+
|
| 201 |
+
with col1:
|
| 202 |
+
st.subheader("Current Position")
|
| 203 |
+
st.metric("Position", final_position or "No position")
|
| 204 |
+
if final_position:
|
| 205 |
+
st.metric("Entry Price", f"${entry_price:.2f}")
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
with col2:
|
| 209 |
+
st.subheader("Decision Metrics")
|
| 210 |
+
st.metric("Buy%", f"{last_row['PCA_Buy%']:.4f}")
|
| 211 |
+
st.metric("Sell%", f"{last_row['PCA_Sell%']:.4f}")
|
| 212 |
+
|
| 213 |
+
return True
|
| 214 |
+
|
| 215 |
+
except Exception as e:
|
| 216 |
+
st.error(f"An error occurred: {str(e)}")
|
| 217 |
+
return False
|
| 218 |
+
|
| 219 |
+
# Page configuration
|
| 220 |
+
st.set_page_config(page_title="DOW JONES Trading Bot", layout="wide")
|
| 221 |
+
st.title("DOW JONES Trading Bot")
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# Run analysis automatically on page load
|
| 225 |
+
run_analysis()
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
# Educational Slides Section
|
| 229 |
+
st.header("Educational Slides")
|
| 230 |
+
|
| 231 |
+
st.markdown('🎧Listen to the Audio🎧')
|
| 232 |
+
st.markdown(
|
| 233 |
+
"""
|
| 234 |
+
<iframe src="https://drive.google.com/file/d/1eXuzJGng4o5Hvd3kZjSnVfQ-UmhKen81/preview" width="640" height="480"></iframe>
|
| 235 |
+
""", unsafe_allow_html=True
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
with st.expander("Slide 1: Introduction", expanded=False):
|
| 240 |
+
st.subheader("Real-Time Crypto Trading Bot Using Machine Learning and PCA")
|
| 241 |
+
st.markdown("""
|
| 242 |
+
**Subtitle:** Leveraging Financial Data Analysis for Optimal Trading Decisions
|
| 243 |
+
|
| 244 |
+
**Overview:**
|
| 245 |
+
This system integrates real-time financial data, machine learning, and principal component analysis (PCA)
|
| 246 |
+
to automate trading decisions in cryptocurrency markets.
|
| 247 |
+
""")
|
| 248 |
+
|
| 249 |
+
with st.expander("Slide 2: Objective", expanded=False):
|
| 250 |
+
st.subheader("Main Goals")
|
| 251 |
+
st.markdown("""
|
| 252 |
+
- Develop an automated trading system that optimizes buy and sell decisions based on historical financial data
|
| 253 |
+
- Use machine learning models, specifically Random Forest, to predict market movements
|
| 254 |
+
- Implement Principal Component Analysis (PCA) for dimensionality reduction and feature extraction
|
| 255 |
+
- Backtest the system and evaluate portfolio performance
|
| 256 |
+
""")
|
| 257 |
+
|
| 258 |
+
with st.expander("Slide 3: Key Concepts", expanded=False):
|
| 259 |
+
st.subheader("Core Technologies and Methods")
|
| 260 |
+
st.markdown("""
|
| 261 |
+
- **Logarithmic Return:** A continuous-time return calculation used to model price changes in markets
|
| 262 |
+
- **Principal Component Analysis (PCA):** A dimensionality reduction technique to extract meaningful features
|
| 263 |
+
- **Machine Learning:** Using Random Forest to classify "Buy" and "Sell" scenarios
|
| 264 |
+
- **SHAP Values:** A method to interpret model outputs through feature contribution analysis
|
| 265 |
+
""")
|
| 266 |
+
|
| 267 |
+
with st.expander("Slide 4: Data Collection and Preprocessing", expanded=False):
|
| 268 |
+
col1, col2 = st.columns(2)
|
| 269 |
+
with col1:
|
| 270 |
+
st.markdown("### Data Fetching")
|
| 271 |
+
st.markdown("""
|
| 272 |
+
- **Source:** Yahoo Finance (yfinance)
|
| 273 |
+
- **Data:** Historical cryptocurrency data
|
| 274 |
+
- **Interval:** Hourly data points
|
| 275 |
+
- **Period:** Last 50 days
|
| 276 |
+
""")
|
| 277 |
+
with col2:
|
| 278 |
+
st.markdown("### Preprocessing")
|
| 279 |
+
st.markdown("""
|
| 280 |
+
- Calculate logarithmic returns
|
| 281 |
+
- Classify scenarios (Buy/Sell)
|
| 282 |
+
- Adjust returns for sell scenarios
|
| 283 |
+
- Handle missing values and outliers
|
| 284 |
+
""")
|
| 285 |
+
|
| 286 |
+
with st.expander("Slide 5: Principal Component Analysis (PCA)", expanded=False):
|
| 287 |
+
st.subheader("PCA Process")
|
| 288 |
+
st.markdown("""
|
| 289 |
+
1. **Data Standardization:**
|
| 290 |
+
```
|
| 291 |
+
X' = (X - μ) / σ
|
| 292 |
+
```
|
| 293 |
+
|
| 294 |
+
2. **Covariance Matrix:**
|
| 295 |
+
```
|
| 296 |
+
Cov(X) = 1/(n-1) Σ(Xi - μ)(Xi - μ)ᵀ
|
| 297 |
+
```
|
| 298 |
+
|
| 299 |
+
3. **Eigenvalue Decomposition:**
|
| 300 |
+
- Find principal components
|
| 301 |
+
- Sort by variance explained
|
| 302 |
+
|
| 303 |
+
4. **Dimensionality Reduction:**
|
| 304 |
+
- Transform data to lower dimensions
|
| 305 |
+
- Preserve important features
|
| 306 |
+
""")
|
| 307 |
+
|
| 308 |
+
with st.expander("Slide 6: Machine Learning Strategy", expanded=False):
|
| 309 |
+
col1, col2 = st.columns(2)
|
| 310 |
+
with col1:
|
| 311 |
+
st.markdown("### Model Architecture")
|
| 312 |
+
st.markdown("""
|
| 313 |
+
- Random Forest Classifier
|
| 314 |
+
- Feature selection from PCA
|
| 315 |
+
- Binary classification (Buy/Sell)
|
| 316 |
+
""")
|
| 317 |
+
with col2:
|
| 318 |
+
st.markdown("### Training Process")
|
| 319 |
+
st.markdown("""
|
| 320 |
+
- Cross-validation
|
| 321 |
+
- Hyperparameter tuning
|
| 322 |
+
- Performance metrics
|
| 323 |
+
- Model evaluation
|
| 324 |
+
""")
|
| 325 |
+
|
| 326 |
+
with st.expander("Slide 7: SHAP Analysis", expanded=False):
|
| 327 |
+
st.subheader("Shapley Additive Explanations")
|
| 328 |
+
st.markdown("""
|
| 329 |
+
**SHAP Value Formula:**
|
| 330 |
+
```
|
| 331 |
+
φᵢ(f) = 1/|N|! Σ [f(S ∪ {i}) - f(S)]
|
| 332 |
+
```
|
| 333 |
+
|
| 334 |
+
**Key Components:**
|
| 335 |
+
- Feature importance ranking
|
| 336 |
+
- Individual prediction explanations
|
| 337 |
+
- Global model interpretation
|
| 338 |
+
""")
|
| 339 |
+
|
| 340 |
+
with st.expander("Slide 8: Strategy Refinement", expanded=False):
|
| 341 |
+
st.subheader("Dynamic Strategy Adjustment")
|
| 342 |
+
st.markdown("""
|
| 343 |
+
1. **Threshold Refinement:**
|
| 344 |
+
- Use SHAP values to identify key features
|
| 345 |
+
- Adjust thresholds based on importance
|
| 346 |
+
|
| 347 |
+
2. **Signal Processing:**
|
| 348 |
+
- Buy signal strengthening
|
| 349 |
+
- Sell signal validation
|
| 350 |
+
- Risk management integration
|
| 351 |
+
""")
|
| 352 |
+
|
| 353 |
+
with st.expander("Slide 9: Backtesting Framework", expanded=False):
|
| 354 |
+
st.markdown("""
|
| 355 |
+
### Portfolio Value Calculation
|
| 356 |
+
```
|
| 357 |
+
Portfolio Valueₜ₊₁ = Portfolio Valueₜ × (Pₜ₊₁/Pₜ)
|
| 358 |
+
```
|
| 359 |
+
|
| 360 |
+
### Trading Logic
|
| 361 |
+
- Buy when probability > threshold
|
| 362 |
+
- Sell when probability > threshold
|
| 363 |
+
- Position management
|
| 364 |
+
|
| 365 |
+
### Performance Metrics
|
| 366 |
+
- Total Return
|
| 367 |
+
- Risk Metrics
|
| 368 |
+
- Sharpe Ratio
|
| 369 |
+
""")
|
| 370 |
+
|
| 371 |
+
with st.expander("Slide 10: Real-Time Interface", expanded=False):
|
| 372 |
+
st.subheader("Streamlit Dashboard Features")
|
| 373 |
+
st.markdown("""
|
| 374 |
+
- Live trading signals
|
| 375 |
+
- Portfolio performance tracking
|
| 376 |
+
- Position monitoring
|
| 377 |
+
- Automatic updates
|
| 378 |
+
- Historical performance
|
| 379 |
+
""")
|
| 380 |
+
|
| 381 |
+
with st.expander("Slide 11: Summary", expanded=False):
|
| 382 |
+
st.markdown("""
|
| 383 |
+
### Key System Components
|
| 384 |
+
- Automated trading system
|
| 385 |
+
- ML & PCA integration
|
| 386 |
+
- SHAP-based interpretation
|
| 387 |
+
- Real-time analytics
|
| 388 |
+
- Performance tracking
|
| 389 |
+
""")
|
| 390 |
+
|
| 391 |
+
with st.expander("Slide 12: Future Improvements", expanded=False):
|
| 392 |
+
st.markdown("""
|
| 393 |
+
### Planned Enhancements
|
| 394 |
+
1. Additional data sources integration
|
| 395 |
+
2. Advanced optimization techniques
|
| 396 |
+
3. Live trading deployment
|
| 397 |
+
4. Enhanced risk management
|
| 398 |
+
5. Portfolio diversification
|
| 399 |
+
""")
|
| 400 |
+
|
| 401 |
+
with st.expander("Slide 13: Q&A", expanded=False):
|
| 402 |
+
st.markdown("""
|
| 403 |
+
### Questions & Discussion
|
| 404 |
+
|
| 405 |
+
Thank you for exploring our trading system! For questions or suggestions:
|
| 406 |
+
- System architecture
|
| 407 |
+
- Implementation details
|
| 408 |
+
- Performance metrics
|
| 409 |
+
- Future developments
|
| 410 |
+
""")
|
| 411 |
+
st.markdown("---")
|
| 412 |
+
st.markdown("### Enjoying the Content?")
|
| 413 |
+
st.markdown("""
|
| 414 |
+
If you find our work useful and interesting, please consider supporting us for **free** on Publish0x!
|
| 415 |
+
It's quick, easy, and no cost to you. Just follow this link to show your support:
|
| 416 |
+
[**Like and Tip Us for Free on Publish0x!**](https://www.publish0x.com/start/crypto-trading-mathematical-modeling-and-strategic-optimizat-xkelryw)
|
| 417 |
+
""")
|
| 418 |
+
|
| 419 |
+
# Footer
|
| 420 |
+
st.markdown("---")
|
| 421 |
+
st.markdown("*Support Development & Info : ")
|
| 422 |
+
st.markdown("Send your email in comment to your btc donation at ")
|
| 423 |
+
st.markdown("1P9R71C6JYJxrPVEzMz4K3hoHYGRW39A9A")
|
| 424 |
+
# Educational Slides Section dona
|