-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
116 lines (100 loc) · 4.98 KB
/
app.py
File metadata and controls
116 lines (100 loc) · 4.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import plotly.figure_factory as ff
st.title("Financial Data Analysis - NIFTY50 Stocks")
uploaded_file = st.file_uploader("Upload your NIFTY50 closing prices CSV file", type=["csv"])
def calculate_rsi(prices, window=14):
delta = prices.diff()
gain = (delta.where(delta > 0, 0)).rolling(window).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window).mean()
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
return rsi
if uploaded_file:
data = pd.read_csv(uploaded_file)
st.write("Data Preview:", data.head())
# Data preparation
if 'HDFC.NS' in data.columns:
data = data.drop(columns=['HDFC.NS'])
data['Date'] = pd.to_datetime(data['Date'])
data = data.sort_values('Date').reset_index(drop=True)
# Descriptive statistics
desc_stats = data.describe().T[['mean', 'std', 'min', 'max']]
desc_stats.columns = ['Mean', 'Std Dev', 'Min', 'Max']
st.subheader("Descriptive Statistics")
st.dataframe(desc_stats)
# Portfolio returns example - using 3 stocks
weights = np.array([0.4, 0.35, 0.25])
stocks = ['RELIANCE.NS', 'HDFCBANK.NS', 'ICICIBANK.NS']
if all(stock in data.columns for stock in stocks):
portfolio_data = data[stocks]
daily_returns = portfolio_data.pct_change().dropna()
portfolio_returns = (daily_returns * weights).sum(axis=1)
st.subheader("Portfolio Daily Returns")
st.line_chart(portfolio_returns)
# Risk assessment
volatility = daily_returns.std()
VaR = daily_returns.quantile(0.05)
risk_metrics = pd.DataFrame({'Volatility (Std Dev)': volatility, 'Value at Risk (VaR)': VaR})
st.subheader("Risk Metrics")
st.dataframe(risk_metrics)
# Correlation heatmap
corr_matrix = daily_returns.corr()
fig_corr = ff.create_annotated_heatmap(
z=corr_matrix.values,
x=list(corr_matrix.columns),
y=list(corr_matrix.index),
annotation_text=corr_matrix.round(2).values,
colorscale='RdBu',
showscale=True
)
fig_corr.update_layout(title="Correlation Matrix of Stock Returns", title_x=0.5)
st.plotly_chart(fig_corr)
# Moving averages for RELIANCE.NS
data['RELIANCE_5d_MA'] = data['RELIANCE.NS'].rolling(window=5).mean()
data['RELIANCE_20d_MA'] = data['RELIANCE.NS'].rolling(window=20).mean()
fig_ma = go.Figure()
fig_ma.add_trace(go.Scatter(x=data['Date'], y=data['RELIANCE.NS'], mode='lines', name='RELIANCE.NS Price'))
fig_ma.add_trace(go.Scatter(x=data['Date'], y=data['RELIANCE_5d_MA'], mode='lines', name='5-Day MA'))
fig_ma.add_trace(go.Scatter(x=data['Date'], y=data['RELIANCE_20d_MA'], mode='lines', name='20-Day MA'))
fig_ma.update_layout(title="Moving Averages for RELIANCE.NS", xaxis_title="Date", yaxis_title="Price")
st.plotly_chart(fig_ma)
# RSI for RELIANCE.NS
data['RELIANCE_RSI'] = calculate_rsi(data['RELIANCE.NS'])
fig_rsi = go.Figure()
fig_rsi.add_trace(go.Scatter(x=data['Date'], y=data['RELIANCE_RSI'], mode='lines', name='RSI'))
fig_rsi.add_hline(y=70, line_dash="dash", line_color="red", annotation_text="Overbought (70)")
fig_rsi.add_hline(y=30, line_dash="dash", line_color="green", annotation_text="Oversold (30)")
fig_rsi.update_layout(title="RSI for RELIANCE.NS", xaxis_title="Date", yaxis_title="RSI")
st.plotly_chart(fig_rsi)
# Sharpe Ratio
mean_returns = daily_returns.mean()
volatility = daily_returns.std()
risk_free_rate = 0.04 / 252
sharpe_ratios = (mean_returns - risk_free_rate) / volatility
sharpe_df = pd.DataFrame({'Stock': sharpe_ratios.index, 'Sharpe Ratio': sharpe_ratios.round(2)})
st.subheader("Sharpe Ratios")
st.dataframe(sharpe_df)
# Monte Carlo Simulation for RELIANCE.NS
num_simulations = 1000
num_days = 252
last_price = data['RELIANCE.NS'].iloc[-1]
volatility_mc = data['RELIANCE.NS'].pct_change().std()
simulated_prices = np.zeros((num_simulations, num_days))
for i in range(num_simulations):
simulated_prices[i, 0] = last_price
for j in range(1, num_days):
simulated_prices[i, j] = simulated_prices[i, j-1] * np.exp(np.random.normal(0, volatility_mc))
fig_mc = go.Figure()
for i in range(num_simulations):
fig_mc.add_trace(go.Scatter(x=list(range(num_days)), y=simulated_prices[i], mode='lines', line=dict(width=0.5), opacity=0.1, showlegend=False))
fig_mc.update_layout(title="Monte Carlo Simulation for RELIANCE.NS Prices",
xaxis_title="Days", yaxis_title="Simulated Price")
st.plotly_chart(fig_mc)
else:
st.warning("Some portfolio stocks not found in data columns.")
else:
st.info("Please upload a CSV file to start the analysis.")