Tonic commited on
Commit
0d3e6c8
·
unverified ·
1 Parent(s): 4e83a78

adds confidence bands back , removes line graph, fixes volume prediction and display

Browse files
Files changed (1) hide show
  1. app.py +160 -19
app.py CHANGED
@@ -1482,6 +1482,18 @@ def make_prediction_enhanced(symbol: str, timeframe: str = "1d", prediction_days
1482
  print("Warning: Volume prediction failed, using fallback")
1483
  volume_pred = np.full(len(mean_pred), df['Volume'].iloc[-1])
1484
  volume_uncertainty = np.full(len(mean_pred), df['Volume'].iloc[-1] * 0.2)
 
 
 
 
 
 
 
 
 
 
 
 
1485
 
1486
  # Predict technical indicators
1487
  print("Predicting technical indicators...")
@@ -1581,9 +1593,21 @@ def make_prediction_enhanced(symbol: str, timeframe: str = "1d", prediction_days
1581
 
1582
  # Ensure volume prediction is properly handled
1583
  if volume_pred is None or len(volume_pred) == 0:
1584
- print("Warning: Volume prediction failed in technical strategy, using fallback")
1585
  volume_pred = np.full(len(final_pred), df['Volume'].iloc[-1])
1586
  volume_uncertainty = np.full(len(final_pred), df['Volume'].iloc[-1] * 0.2)
 
 
 
 
 
 
 
 
 
 
 
 
1587
 
1588
  # Predict technical indicators
1589
  print("Predicting technical indicators for technical strategy...")
@@ -1792,33 +1816,138 @@ def make_prediction_enhanced(symbol: str, timeframe: str = "1d", prediction_days
1792
  row=1, col=1
1793
  )
1794
 
1795
- # Add volume
1796
- fig.add_trace(
1797
- go.Bar(x=df.index, y=df['Volume'], name='Historical Volume',
1798
- marker_color='lightblue', opacity=0.7),
1799
- row=3, col=1
1800
- )
 
 
 
 
 
 
1801
 
1802
- if volume_pred is not None:
 
 
 
 
 
1803
  fig.add_trace(
1804
- go.Bar(x=pred_dates, y=volume_pred, name='Predicted Volume',
1805
  marker_color='red', opacity=0.7),
1806
  row=3, col=1
1807
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1808
 
1809
- # Add uncertainty analysis
1810
- fig.add_trace(
1811
- go.Scatter(x=pred_dates, y=final_uncertainty, name='Prediction Uncertainty',
1812
- line=dict(color='green', width=2)),
1813
- row=4, col=1
1814
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1815
 
1816
- # Update layout
1817
  fig.update_layout(
1818
  title=f'Enhanced Stock Prediction for {symbol}',
1819
- xaxis_title='Date',
1820
- height=800,
1821
- showlegend=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1822
  )
1823
 
1824
  # Create comprehensive trading signals
@@ -1872,6 +2001,18 @@ def make_prediction_enhanced(symbol: str, timeframe: str = "1d", prediction_days
1872
  print(f"Basic trading signals failed: {str(basic_error)}")
1873
  trading_signals['error'] = str(basic_error)
1874
 
 
 
 
 
 
 
 
 
 
 
 
 
1875
  return trading_signals, fig
1876
 
1877
  except Exception as e:
 
1482
  print("Warning: Volume prediction failed, using fallback")
1483
  volume_pred = np.full(len(mean_pred), df['Volume'].iloc[-1])
1484
  volume_uncertainty = np.full(len(mean_pred), df['Volume'].iloc[-1] * 0.2)
1485
+ elif len(volume_pred) != len(mean_pred):
1486
+ print(f"Warning: Volume prediction length mismatch. Expected {len(mean_pred)}, got {len(volume_pred)}")
1487
+ # Pad or truncate to match
1488
+ if len(volume_pred) < len(mean_pred):
1489
+ last_vol = volume_pred[-1] if len(volume_pred) > 0 else df['Volume'].iloc[-1]
1490
+ volume_pred = np.pad(volume_pred, (0, len(mean_pred) - len(volume_pred)),
1491
+ mode='constant', constant_values=last_vol)
1492
+ volume_uncertainty = np.pad(volume_uncertainty, (0, len(mean_pred) - len(volume_uncertainty)),
1493
+ mode='constant', constant_values=volume_uncertainty[-1] if len(volume_uncertainty) > 0 else df['Volume'].iloc[-1] * 0.2)
1494
+ else:
1495
+ volume_pred = volume_pred[:len(mean_pred)]
1496
+ volume_uncertainty = volume_uncertainty[:len(mean_pred)]
1497
 
1498
  # Predict technical indicators
1499
  print("Predicting technical indicators...")
 
1593
 
1594
  # Ensure volume prediction is properly handled
1595
  if volume_pred is None or len(volume_pred) == 0:
1596
+ print("Warning: Volume prediction failed, using fallback")
1597
  volume_pred = np.full(len(final_pred), df['Volume'].iloc[-1])
1598
  volume_uncertainty = np.full(len(final_pred), df['Volume'].iloc[-1] * 0.2)
1599
+ elif len(volume_pred) != len(final_pred):
1600
+ print(f"Warning: Volume prediction length mismatch. Expected {len(final_pred)}, got {len(volume_pred)}")
1601
+ # Pad or truncate to match
1602
+ if len(volume_pred) < len(final_pred):
1603
+ last_vol = volume_pred[-1] if len(volume_pred) > 0 else df['Volume'].iloc[-1]
1604
+ volume_pred = np.pad(volume_pred, (0, len(final_pred) - len(volume_pred)),
1605
+ mode='constant', constant_values=last_vol)
1606
+ volume_uncertainty = np.pad(volume_uncertainty, (0, len(final_pred) - len(volume_uncertainty)),
1607
+ mode='constant', constant_values=volume_uncertainty[-1] if len(volume_uncertainty) > 0 else df['Volume'].iloc[-1] * 0.2)
1608
+ else:
1609
+ volume_pred = volume_pred[:len(final_pred)]
1610
+ volume_uncertainty = volume_uncertainty[:len(final_pred)]
1611
 
1612
  # Predict technical indicators
1613
  print("Predicting technical indicators for technical strategy...")
 
1816
  row=1, col=1
1817
  )
1818
 
1819
+ # Add volume with better data handling
1820
+ if 'Volume' in df.columns and not df['Volume'].isna().all():
1821
+ # Ensure volume data is numeric and handle any NaN values
1822
+ volume_data = pd.to_numeric(df['Volume'], errors='coerce').fillna(0)
1823
+
1824
+ fig.add_trace(
1825
+ go.Bar(x=df.index, y=volume_data, name='Historical Volume',
1826
+ marker_color='lightblue', opacity=0.7),
1827
+ row=3, col=1
1828
+ )
1829
+ else:
1830
+ print("Warning: No valid volume data available for plotting")
1831
 
1832
+ # Add predicted volume with better handling
1833
+ if volume_pred is not None and len(volume_pred) > 0:
1834
+ # Ensure volume prediction is numeric and handle any NaN values
1835
+ volume_pred_clean = np.array(volume_pred)
1836
+ volume_pred_clean = np.where(np.isnan(volume_pred_clean), 0, volume_pred_clean)
1837
+
1838
  fig.add_trace(
1839
+ go.Bar(x=pred_dates, y=volume_pred_clean, name='Predicted Volume',
1840
  marker_color='red', opacity=0.7),
1841
  row=3, col=1
1842
  )
1843
+
1844
+ # Add volume uncertainty bands if available
1845
+ if volume_uncertainty is not None and len(volume_uncertainty) > 0:
1846
+ volume_uncertainty_clean = np.array(volume_uncertainty)
1847
+ volume_uncertainty_clean = np.where(np.isnan(volume_uncertainty_clean), 0, volume_uncertainty_clean)
1848
+
1849
+ volume_upper = volume_pred_clean + 2 * volume_uncertainty_clean
1850
+ volume_lower = np.maximum(0, volume_pred_clean - 2 * volume_uncertainty_clean)
1851
+
1852
+ fig.add_trace(
1853
+ go.Scatter(x=pred_dates, y=volume_upper, name='Volume Upper Bound',
1854
+ line=dict(color='red', width=1, dash='dot'), showlegend=False),
1855
+ row=3, col=1
1856
+ )
1857
+
1858
+ fig.add_trace(
1859
+ go.Scatter(x=pred_dates, y=volume_lower, name='Volume Lower Bound',
1860
+ line=dict(color='red', width=1, dash='dot'), fill='tonexty',
1861
+ fillcolor='rgba(255,0,0,0.1)', showlegend=False),
1862
+ row=3, col=1
1863
+ )
1864
 
1865
+ # Enhanced uncertainty analysis with confidence bands
1866
+ if final_uncertainty is not None and len(final_uncertainty) > 0:
1867
+ # Ensure uncertainty data is valid
1868
+ uncertainty_clean = np.array(final_uncertainty)
1869
+ uncertainty_clean = np.where(np.isnan(uncertainty_clean), 0, uncertainty_clean)
1870
+
1871
+ # Create confidence bands
1872
+ confidence_68 = uncertainty_clean # 1 standard deviation (68% confidence)
1873
+ confidence_95 = 2 * uncertainty_clean # 2 standard deviations (95% confidence)
1874
+ confidence_99 = 3 * uncertainty_clean # 3 standard deviations (99% confidence)
1875
+
1876
+ # Plot uncertainty as confidence bands
1877
+ fig.add_trace(
1878
+ go.Scatter(x=pred_dates, y=final_pred + confidence_95, name='95% Confidence Upper',
1879
+ line=dict(color='green', width=1, dash='dash'), showlegend=False),
1880
+ row=4, col=1
1881
+ )
1882
+
1883
+ fig.add_trace(
1884
+ go.Scatter(x=pred_dates, y=final_pred - confidence_95, name='95% Confidence Lower',
1885
+ line=dict(color='green', width=1, dash='dash'), fill='tonexty',
1886
+ fillcolor='rgba(0,255,0,0.1)', showlegend=False),
1887
+ row=4, col=1
1888
+ )
1889
+
1890
+ fig.add_trace(
1891
+ go.Scatter(x=pred_dates, y=final_pred + confidence_68, name='68% Confidence Upper',
1892
+ line=dict(color='darkgreen', width=1, dash='dot'), showlegend=False),
1893
+ row=4, col=1
1894
+ )
1895
+
1896
+ fig.add_trace(
1897
+ go.Scatter(x=pred_dates, y=final_pred - confidence_68, name='68% Confidence Lower',
1898
+ line=dict(color='darkgreen', width=1, dash='dot'), fill='tonexty',
1899
+ fillcolor='rgba(0,128,0,0.1)', showlegend=False),
1900
+ row=4, col=1
1901
+ )
1902
+
1903
+ # Add the main prediction line on top
1904
+ fig.add_trace(
1905
+ go.Scatter(x=pred_dates, y=final_pred, name='Prediction with Uncertainty',
1906
+ line=dict(color='darkgreen', width=3)),
1907
+ row=4, col=1
1908
+ )
1909
+
1910
+ # Add uncertainty magnitude as a separate line
1911
+ fig.add_trace(
1912
+ go.Scatter(x=pred_dates, y=uncertainty_clean, name='Uncertainty Magnitude',
1913
+ line=dict(color='orange', width=2)),
1914
+ row=4, col=1
1915
+ )
1916
+ else:
1917
+ print("Warning: No valid uncertainty data available for plotting")
1918
 
1919
+ # Update layout with better titles and axis labels
1920
  fig.update_layout(
1921
  title=f'Enhanced Stock Prediction for {symbol}',
1922
+ height=1000, # Increased height for better visibility
1923
+ showlegend=True,
1924
+ legend=dict(
1925
+ orientation="h",
1926
+ yanchor="bottom",
1927
+ y=1.02,
1928
+ xanchor="right",
1929
+ x=1
1930
+ )
1931
+ )
1932
+
1933
+ # Update subplot titles and axis labels
1934
+ fig.update_xaxes(title_text="Date", row=4, col=1)
1935
+ fig.update_yaxes(title_text="Price ($)", row=1, col=1)
1936
+ fig.update_yaxes(title_text="Technical Indicators", row=2, col=1)
1937
+ fig.update_yaxes(title_text="Volume", row=3, col=1)
1938
+ fig.update_yaxes(title_text="Price with Uncertainty ($)", row=4, col=1)
1939
+
1940
+ # Update subplot titles
1941
+ fig.update_annotations(
1942
+ dict(
1943
+ text="Price Prediction with Technical Indicators",
1944
+ x=0.5,
1945
+ y=0.95,
1946
+ xref="paper",
1947
+ yref="paper",
1948
+ showarrow=False,
1949
+ font=dict(size=16)
1950
+ )
1951
  )
1952
 
1953
  # Create comprehensive trading signals
 
2001
  print(f"Basic trading signals failed: {str(basic_error)}")
2002
  trading_signals['error'] = str(basic_error)
2003
 
2004
+ # Debug information for volume and uncertainty
2005
+ print(f"Volume data info:")
2006
+ print(f" Historical volume shape: {df['Volume'].shape if 'Volume' in df.columns else 'No volume column'}")
2007
+ print(f" Historical volume NaN count: {df['Volume'].isna().sum() if 'Volume' in df.columns else 'N/A'}")
2008
+ print(f" Predicted volume shape: {volume_pred.shape if volume_pred is not None else 'None'}")
2009
+ print(f" Predicted volume NaN count: {np.isnan(volume_pred).sum() if volume_pred is not None else 'N/A'}")
2010
+
2011
+ print(f"Uncertainty data info:")
2012
+ print(f" Final uncertainty shape: {final_uncertainty.shape if final_uncertainty is not None else 'None'}")
2013
+ print(f" Final uncertainty NaN count: {np.isnan(final_uncertainty).sum() if final_uncertainty is not None else 'N/A'}")
2014
+ print(f" Final uncertainty range: [{np.min(final_uncertainty):.4f}, {np.max(final_uncertainty):.4f}]" if final_uncertainty is not None else 'N/A')
2015
+
2016
  return trading_signals, fig
2017
 
2018
  except Exception as e: