https://github.com/thegamestopsnow/twsca

This package provides functionality for detecting correlations between time series that may be misaligned in time or have nonlinear temporal distortions.

https://github.com/thegamestopsnow/twsca

Science Score: 13.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
  • DOI references
  • Academic publication links
  • Academic email domains
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (14.8%) to scientific vocabulary
Last synced: 6 months ago · JSON representation

Repository

This package provides functionality for detecting correlations between time series that may be misaligned in time or have nonlinear temporal distortions.

Basic Info
  • Host: GitHub
  • Owner: TheGameStopsNow
  • License: mit
  • Language: Python
  • Default Branch: main
  • Size: 67.4 KB
Statistics
  • Stars: 2
  • Watchers: 2
  • Forks: 0
  • Open Issues: 0
  • Releases: 0
Created 12 months ago · Last pushed 11 months ago
Metadata Files
Readme License

README.md

Time-Warped Spectral Correlation Analysis (TWSCA)

TWSCA is a Python package for analyzing correlations between time series that may be misaligned in time or have different speeds. It combines dynamic time warping (DTW) with spectral analysis to identify hidden relationships.

Features

  • Dynamic Time Warping (DTW) for time series alignment
  • Spectral analysis for frequency domain correlation
  • Support for multiple time series comparison
  • Advanced smoothing techniques with automatic parameter optimization
  • Interactive visualizations using Plotly
  • Animated warping path visualization
  • 3D correlation surface plots
  • Comprehensive analysis dashboards
  • Adaptive smoothing based on local volatility
  • Dark/light theme support
  • Configuration management
  • Comprehensive test suite
  • Type hints for better IDE support
  • Command-line interface for quick demonstrations

Installation

Install the latest stable release from PyPI:

bash pip install twsca>=0.3.0

For interactive visualizations and notebooks support: bash pip install "twsca[interactive]>=0.3.0"

To install the latest development version directly from GitHub:

bash pip install git+https://github.com/TheGameStopsNow/twsca.git

Quick Start

```python from twsca import computetwsca, setupplottingstyle, createinteractive_plot import numpy as np

Create example data

t = np.linspace(0, 10, 100) s1 = np.sin(t) s2 = np.sin(t + 1) # Phase-shifted version

Compute TWSCA with automatic parameter optimization

LLT filtering is on by default for better noise handling

result = computetwsca(s1, s2, optimizeparams=True) print(f"Time-domain correlation: {result['timedomaincorrelation']}") print(f"Spectral correlation: {result['spectral_correlation']}")

If you need to disable LLT filtering:

result = computetwsca(s1, s2, usellt=False)

Create interactive plot

fig = createinteractiveplot({ 'Original': s1, 'Shifted': s2 }, plottype='timeseries') fig.show() ```

Command-Line Interface

TWSCA includes a command-line interface for quickly demonstrating its features:

Running the CLI

```bash

Method 1: Using Python module

python -m twsca [options]

Method 2: Using the provided script

python twsca_cli.py [options] ```

Available Commands

  1. LLT Filter Demonstration: bash python -m twsca llt --sigma 1.0 --alpha 0.5 --noise 0.3

  2. Comparing Different Smoothing Methods: bash python -m twsca smooth --noise 0.4 --window 7

  3. TWSCA Analysis with and without LLT: bash python -m twsca twsca --noise 0.3 --phase 1.5 --warp

Common Options

  • --points: Number of points in the generated time series (default: 100)
  • --noise: Level of noise to add to the signal (default: 0.3)
  • --sigma: Sigma parameter for LLT filter (default: 1.0)
  • --alpha: Alpha parameter for LLT filter (default: 0.5)

For more options, run: bash python -m twsca <command> --help

Advanced Usage

Advanced Smoothing with Parameter Optimization

```python from twsca import lltfilter, adaptivesmoothing

Create noisy data

t = np.linspace(0, 10, 100) noisy_signal = np.sin(t) + 0.2 * np.random.randn(100)

Apply LLT filter with automatic parameter optimization

smoothedopt = lltfilter(noisysignal, optimizeparams=True)

Apply adaptive smoothing based on local volatility

smoothedadaptive = adaptivesmoothing( noisysignal, basesigma=1.0, sensitivity=0.1 )

Create interactive comparison plot

fig = createinteractiveplot({ 'Original': noisysignal, 'Optimized LLT': smoothedopt, 'Adaptive': smoothed_adaptive }) fig.show() ```

LLT Filtering in TWSCA

TWSCA applies LLT (Local Laplacian Transform) filtering by default to input signals before analysis to improve robustness against noise. You can control this behavior with the use_llt parameter:

```python from twsca import compute_twsca import numpy as np

Create noisy signals

t = np.linspace(0, 10, 100) s1 = np.sin(t) + 0.3 * np.random.randn(100) s2 = np.sin(t + 1) + 0.3 * np.random.randn(100)

With LLT filtering (default)

resultwithllt = compute_twsca(s1, s2)

Without LLT filtering

resultwithoutllt = computetwsca(s1, s2, usellt=False)

Control LLT parameters

resultcustomllt = computetwsca(s1, s2, usellt=True, lltsigma=2.0, lltalpha=0.3)

print(f"Correlation with LLT: {resultwithllt['spectralcorrelation']:.4f}") print(f"Correlation without LLT: {resultwithoutllt['spectralcorrelation']:.4f}") ```

Interactive Visualization

```python from twsca import plotanalysisdashboard, plot3dcorrelation_surface

Create comprehensive analysis dashboard

dashboard = plotanalysisdashboard({ 'timeseries': { 'Original': s1, 'Warped': s2 }, 'correlationmatrix': result['correlationmatrix'], 'spectra': result['spectralcomponents'], 'warpingpath': result['dtwpath'] }) dashboard.show()

Create interactive 3D correlation surface

surface = plot3dcorrelationsurface( times=t, frequencies=result['frequencies'], correlations=result['timefreq_correlation'], interactive=True ) surface.show() ```

Animated Warping Visualization

```python from twsca import plotwarpinganimation

Create animation of the warping process

anim = plotwarpinganimation( original=s1, warped=s2, path=result['dtw_path'], interval=50 # milliseconds between frames ) plt.show() ```

Smoothing Time Series

```python from twsca import lltfilter, savitzkygolay

Create noisy data

t = np.linspace(0, 10, 100) noisy_signal = np.sin(t) + 0.2 * np.random.randn(100)

Apply Local Laplacian Transform filter

smoothedllt = lltfilter(noisy_signal, sigma=1.0, alpha=0.5)

Apply Savitzky-Golay filter

smoothedsg = savitzkygolay(noisysignal, windowsize=5, poly_order=2)

Plot results

plottimeseries( [noisysignal, smoothedllt, smoothed_sg], labels=['Original', 'LLT', 'Savitzky-Golay'] ) ```

Configuration Management

```python from twsca import setconfig, getconfig, reset_config

Set global configuration

setconfig({ 'plotstyle': 'seaborn', 'dtwradius': 20, 'windowsize': 100, 'normalize': True })

Get current settings

config = getconfig() print(f"Current plot style: {config.get('plotstyle')}")

Reset to defaults

reset_config() ```

Batch Processing

```python from twsca import chunkdata, computeprogress

Process large datasets in chunks

data = np.random.randn(1000) chunks = chunkdata(data, chunksize=100)

for i, chunk in enumerate(chunks): # Process each chunk result = computetwsca(chunk, chunk) print(computeprogress(i + 1, len(chunks))) ```

Multiple Time Series Analysis

```python import pandas as pd from twsca import computetwscamatrix

Create multiple time series

data = pd.DataFrame({ 'series1': np.sin(t), 'series2': np.cos(t), 'series3': np.sin(2 * t) })

Compute correlation matrix

correlationmatrix = computetwscamatrix(data) print("Correlation matrix:") print(correlationmatrix) ```

API Reference

Core Functions

compute_twsca(s1, s2, **kwargs)

Compute Time-Warped Spectral Correlation Analysis between two time series.

Parameters: - s1 (np.ndarray): First time series - s2 (np.ndarray): Second time series - window_size (int, optional): Size of the sliding window for spectral analysis - dtw_radius (int, optional): Radius for DTW computation - normalize (bool, optional): Whether to normalize the input series

Returns: - dict: Dictionary containing: - time_domain_correlation: Correlation in time domain - spectral_correlation: Correlation in frequency domain - dtw_path: DTW alignment path - spectral_components: Spectral components of the analysis

Smoothing Functions

llt_filter(data, sigma=1.0, alpha=0.5)

Apply Local Laplacian Transform filter to time series data.

Parameters: - data (np.ndarray): Input time series - sigma (float): Standard deviation for Gaussian kernel - alpha (float): Smoothing parameter (0 < alpha < 1)

savitzky_golay(data, window_size=5, poly_order=2)

Apply Savitzky-Golay filter to time series data.

Parameters: - data (np.ndarray): Input time series - window_size (int): Size of the window (must be odd) - poly_order (int): Order of the polynomial fit

Plotting Functions

setup_plotting_style(style='default', **kwargs)

Set up the default plotting style for TWSCA visualizations.

Parameters: - style (str): Style name ('default', 'seaborn', 'dark_background') - **kwargs: Additional style parameters

plot_time_series(data, time=None, labels=None, **kwargs)

Plot one or more time series.

Parameters: - data (np.ndarray or list): Time series data - time (np.ndarray, optional): Time points - labels (list, optional): Labels for each series

Development

Setup

  1. Clone the repository: bash git clone https://github.com/TheGameStopsNow/twsca.git cd twsca

  2. Create and activate a virtual environment: bash python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate

  3. Install development dependencies: bash pip install -e ".[dev]"

Running Tests

bash pytest

Building Documentation

bash cd docs make html

Contributing

  1. Fork the repository
  2. Create your feature branch: git checkout -b feature/my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin feature/my-new-feature
  5. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Citation

If you use TWSCA in your research, please cite:

bibtex @software{twsca2024, author = {Dennis Nedry}, title = {TWSCA: Time-Warped Spectral Correlation Analysis}, year = {2024}, publisher = {GitHub}, url = {https://github.com/TheGameStopsNow/twsca} }

Owner

  • Login: TheGameStopsNow
  • Kind: user

💥 Disruptor of the Status Quo 🛡️ Fighting for transparency and fairness. 📈 Empower individual retail investors. 🔍 Challenging Wall Street's dominance.

GitHub Events

Total
  • Watch event: 2
  • Push event: 15
  • Create event: 2
Last Year
  • Watch event: 2
  • Push event: 15
  • Create event: 2

Packages

  • Total packages: 1
  • Total downloads:
    • pypi 34 last-month
  • Total dependent packages: 0
  • Total dependent repositories: 0
  • Total versions: 4
  • Total maintainers: 1
pypi.org: twsca

Time-Warped Spectral Correlation Analysis

  • Homepage: https://github.com/TheGameStopsNow/twsca
  • Documentation: https://twsca.readthedocs.io
  • License: MIT License Copyright (c) 2024 TheGameStopsNow Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  • Latest release: 0.3.0
    published 11 months ago
  • Versions: 4
  • Dependent Packages: 0
  • Dependent Repositories: 0
  • Downloads: 34 Last month
Rankings
Dependent packages count: 9.3%
Average: 30.9%
Dependent repos count: 52.4%
Maintainers (1)
Last synced: 7 months ago

Dependencies

.github/workflows/ci.yml actions
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
  • codecov/codecov-action v4 composite
pyproject.toml pypi
  • matplotlib >=3.7.0
  • numpy >=1.24.0
  • pandas >=2.0.0
  • scipy >=1.10.0
setup.py pypi
  • matplotlib >=3.3.0
  • numpy >=1.18.0
  • pandas >=1.0.0
  • scipy >=1.4.0