Stock data analysis and volatility tracking using Preswald

Stock data analysis and volatility tracking using Preswald

Amrutha GujjarAmrutha Gujjar5 min read

Category: Use Case


Analyzing stock market trends across multiple securities required manual data processing, cleaning, and visualization, making financial analysis slow and error-prone.

We needed a real-time stock analytics dashboard that could:

✅ Load raw stock data directly from CSV files

Normalize stock prices for better comparability

✅ Track volatility differences between stocks

✅ Provide interactive visualizations

Instead of writing complex Python scripts and manually generating reports, we turned to Preswald to automate the entire process.


The Challenge: Manual and Inefficient Stock Data Analysis

Our team faced several challenges when working with stock data:

  • 📊 Data Cleaning Complexity – Stock prices have inconsistent formatting, missing values, and require standardization.

  • Slow Comparisons – Manually comparing multiple stocks took too much time.

  • 📈 Lack of Interactivity – Static Excel charts made deeper insights difficult.

  • ⚠️ Volatility Tracking Issues – Identifying risk factors across different securities required additional calculations.

We needed a fast, automated, and interactive solution that would:

  • Standardize stock price data for meaningful comparisons

  • Track and visualize stock volatility over time

  • Enable real-time analysis without manual intervention


Why We Chose Preswald

Preswald provided an end-to-end solution for stock data processing and analysis:

  • Automated CSV data ingestion – No more copy-pasting from Excel.

  • Real-time filtering and visualizations – Instantly compare stocks interactively.

  • Volatility tracking tools – Calculate and visualize volatility trends dynamically.

  • One-command deployment – Share dashboards instantly in the cloud.


The Implementation: From CSV Files to Automated Stock Dashboards

Step 1: Installing Preswald

We started by installing Preswald:


pip install preswald


Step 2: Setting Up the Stock Analysis App

We initialized a new Preswald project:


preswald init stock_dashboard

cd stock_dashboard

This generated a pre-configured project structure, including:

  • hello.py – The main stock analytics script.

  • preswald.toml – Configuration settings.

  • secrets.toml – Secure storage for credentials.


Step 3: Loading Stock Data from CSV

Instead of manually cleaning and loading data, we used Preswald to automate CSV ingestion:


import pandas as pd

from preswald import text, plotly

# Dashboard Title

text("# Analyzing Stock Data Cleaning and Volatility")

text("Exploring how standardization affects financial data analysis.")

# Load data

df = pd.read_csv("data/stock_data.csv")

df = df.reset_index()

No manual data uploads – Preswald reads CSVs dynamically.


Step 4: Comparing Stock Prices Over Time

To compare stock performance, we melted the data and created an interactive line chart:


import plotly.express as px

df_melted = df.melt(

id_vars=["index"],

value_vars=[col for col in df.columns if col != "index"],

var_name="Stock",

value_name="Price",

)

fig1 = px.line(

df_melted,

x="index",

y="Price",

color="Stock",

title="Stock Price Comparison<br> <sup>Top 10 Stocks By Market Cap Over The Past Year</sup>",

template="plotly_white",

)

text("## Raw Data")

plotly(fig1)

Interactive stock comparison – Users can analyze trends dynamically.


Step 5: Calculating Volatility Differences Between Stocks

Stock price volatility varies significantly. To track volatility differences, we:

  • Calculated percentage returns

  • Measured standard deviation (volatility)

  • Created a heatmap to compare volatilities


import numpy as np

# Compute percentage returns

returns = df.pct_change().dropna()

# Compute volatility

volatilities = returns.std()

# Create volatility difference matrix

tickers = df.columns

volatility_diff = np.zeros((len(tickers), len(tickers)))

for i, ticker1 in enumerate(tickers):

for j, ticker2 in enumerate(tickers):

vol_diff = abs(volatilities[ticker1] - volatilities[ticker2])

volatility_diff[i, j] = vol_diff

df_volatility = pd.DataFrame(volatility_diff, index=tickers, columns=tickers)

fig2 = px.imshow(

df_volatility,

labels={"x": "Stock", "y": "Stock", "color": "Volatility Difference (stdev)"},

title="Stock Volatility Comparison Heatmap",

color_continuous_scale="Viridis",

)

plotly(fig2)

Clear volatility differences – Easily identify risk levels across securities.


Step 6: Normalizing Data with Logarithmic Returns

To improve accuracy, we calculated logarithmic returns:


# Compute log returns

log_returns = np.log(df / df.shift(1)).dropna()

# Plot log returns over time

log_returns_melted = log_returns.reset_index().melt(

id_vars=["index"], var_name="Stock", value_name="Return"

)

fig3 = px.line(

log_returns_melted,

x="index",

y="Return",

color="Stock",

title="Logarithmic Returns Over Time",

template="plotly_white",

)

plotly(fig3)

Improved data standardization – More accurate risk calculations.


Step 7: Rolling Volatility Analysis Over Time

We also calculated rolling window volatility to track trends:


# Compute rolling volatility (30-day window)

rolling_volatility = returns.rolling(window=30).std().dropna()

# Melt DataFrame for plotting

rolling_volatility_melted = rolling_volatility.reset_index().melt(

id_vars=["index"], var_name="Stock", value_name="Volatility"

)

fig4 = px.line(

rolling_volatility_melted,

x="index",

y="Volatility",

color="Stock",

title="30-Day Rolling Volatility",

template="plotly_white",

)

plotly(fig4)

Track market risk fluctuations dynamically.


Step 8: Deploying the Dashboard in One Command

To share our interactive stock analytics tool, we deployed it to the cloud:


preswald deploy --target structured

📍 Now live at:


🌐 https://stock-dashboard.preswald.app

Anyone can now interact with real-time stock analytics without Python installed.


The Results: A Fully Automated Stock Data Analysis Pipeline

🚀 Eliminated manual stock data processing

🚀 Automated volatility tracking and comparisons

🚀 Enabled real-time stock trend visualizations

🚀 Deployed a shareable cloud dashboard in minutes


Final Thoughts: Preswald for Financial Data Analysis

If your team struggles with analyzing stock data manually, Preswald is a game-changer. It allows you to build interactive financial dashboards without complex frontend development.

Try Preswald today!

🔗 https://github.com/StructuredLabs/preswald