I like how this works and is visualized but I want it to be more interactive so i can better inspect the values. Can you refactor it but maintain the orginal functionality?
Certainly! To make the code more interactive and allow better inspection of the values, we'll refactor the visualization part to use Plotly, which provides interactive charts by default. This will enable you to hover over data points to see exact values and toggle visibility of different metrics. Additionally, we'll allow you to select specific metrics you'd like to visualize.
Here's the refactored code:
python
from datetime import datetime
import pandas as pd
import numpy as np
import yfinance as yf
from scipy.stats import skew, kurtosis
import plotly.graph_objs as go
import ipywidgets as widgets
from IPython.display import display
class SeasonalityRadar:
def __init__(self, tickers, start_date='1990-01-01', end_date=None, triple_witching_weeks=None, odds_ratio=2, output_dir='seasonality_data'):
self.tickers = tickers if isinstance(tickers, list) else [tickers]
self.start_date = start_date
self.end_date = end_date if end_date else datetime.now().strftime('%Y-%m-%d')
self.triple_witching_weeks = triple_witching_weeks or []
self.odds_ratio = odds_ratio
self.output_dir = output_dir
self.data = None
def fetch_data(self):
self.data = yf.download(self.tickers, start=self.start_date, end=self.end_date, group_by='ticker')
def calculate_kelly_ratio(self, returns):
"""
Calculate the Kelly ratio and fraction based on the returns.
Parameters:
returns (pd.Series): A series of returns.
Returns:
tuple: (kelly_ratio, kelly_fraction)
"""
win_rate = (returns > 0).mean()
loss_rate = (returns < 0).mean()
avg_win = returns[returns > 0].mean()
avg_loss = returns[returns < 0].mean()
if avg_loss == 0: # Avoid division by zero
return (0, 0)
kelly_ratio = win_rate - (loss_rate * (avg_win / -avg_loss))
kelly_fraction = kelly_ratio / (avg_win / -avg_loss) if avg_loss != 0 else 0
return kelly_ratio, kelly_fraction
def analyze_monthly_seasonality(self, ticker):
df = self.data[ticker]['Adj Close']
# Calculate monthly returns
monthly_data = df.resample('M').ffill()
monthly_returns = monthly_data.pct_change().dropna() * 100 # Convert to percentage
# Organize returns into a pivot table
monthly_returns = monthly_returns.to_frame(name='Adj Close')
monthly_returns['Year'] = monthly_returns.index.year
monthly_returns['Month'] = monthly_returns.index.month
monthly_returns['Month'] = monthly_returns['Month'].apply(lambda x: pd.Timestamp(2023, x, 1).strftime('%b'))
pivot_table = monthly_returns.pivot_table(index='Year', columns='Month', values='Adj Close', aggfunc='mean')
pivot_table = pivot_table.fillna(0)
# Ensure columns are in the correct order
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
pivot_table = pivot_table[months]
# Calculate metrics
avg_returns = pivot_table.mean()
std_dev = pivot_table.std()
pos_perc = (pivot_table > 0).mean() * 100
skewness = pivot_table.apply(lambda x: skew(x.dropna()), axis=0)
kurt = pivot_table.apply(lambda x: kurtosis(x.dropna(), fisher=False), axis=0)
# Kelly ratio and fraction
kelly_ratios = pivot_table.apply(lambda x: self.calculate_kelly_ratio(x.dropna()), axis=0)
avg_kelly_ratio = kelly_ratios.apply(lambda x: x[0])
avg_kelly_fraction = kelly_ratios.apply(lambda x: x[1])
# Create summary table
summary_table = pd.DataFrame({
'Avg Returns (%)': avg_returns,
'StDev (%)': std_dev,
'Pos %': pos_perc,
'Skewness': skewness,
'Kurtosis': kurt,
'Avg Kelly Ratio': avg_kelly_ratio,
'Avg Kelly Fraction': avg_kelly_fraction
})
return summary_table
def visualize_monthly_seasonality(self, ticker):
summary_table = self.analyze_monthly_seasonality(ticker)
# Available metrics
metrics = ['Avg Returns (%)', 'StDev (%)', 'Pos %', 'Skewness', 'Kurtosis',
'Avg Kelly Ratio', 'Avg Kelly Fraction']
# Create a multi-select widget for metrics
metric_selector = widgets.SelectMultiple(
options=metrics,
value=metrics,
description='Metrics',
disabled=False
)
# Function to update the plot based on selected metrics
def update_plot(selected_metrics):
categories = list(summary_table.index)
categories += [categories[0]] # To complete the loop
fig = go.Figure()
for metric in selected_metrics:
values = summary_table[metric].values.flatten().tolist()
values += [values[0]] # To complete the loop
hover_text = [f"{metric}: {v:.2f}" for v in values]
fig.add_trace(go.Scatterpolar(
r=values,
theta=categories,
fill='toself',
name=metric,
hoverinfo='text',
hovertext=hover_text
))
fig.update_layout(
polar=dict(
radialaxis=dict(
visible=True,
)),
showlegend=True,
title=f'Monthly Behavior of Quantitative Statistics for {ticker}'
)
fig.show()
# Use an interact function to update plot based on metric selection
interact_plot = widgets.interactive(update_plot, selected_metrics=metric_selector)
display(interact_plot)
def run_analysis(self):
self.fetch_data()
for ticker in self.tickers:
print(f"Analyzing {ticker}")
self.visualize_monthly_seasonality(ticker)
This will display interactive radar charts for each ticker. You can select which metrics to visualize using the multi-select widget. Hover over the data points to see exact values.
Notes:
Interactive Plotting with Plotly:
Plotly provides interactive charts out of the box. You can hover over data points to see exact values, zoom in/out, and toggle the visibility of different metrics by clicking on the legend entries.
Metric Selection:
The visualize_monthly_seasonality function now includes a multi-select widget that allows you to choose which metrics to display on the radar chart.
By default, all metrics are selected. You can hold down the Ctrl (or Cmd on Mac) key to select or deselect multiple metrics.
Improved Inspection of Values:
Hover text has been added to each data point on the radar chart, displaying the exact value for that metric and month.
This interactivity allows you to better inspect and understand the underlying data.
Environment Requirements:
This code is meant to be run in a Jupyter notebook environment where ipywidgets are supported.
Ensure you have installed the necessary libraries: yfinance, plotly, and ipywidgets.
You can install them via pip install yfinance plotly ipywidgets.
Example Output:
When you run the analysis, you'll see something like this:
(Note: Replace the link with an actual image if needed.)
You can interact with the chart directly in your Jupyter notebook.
By refactoring the code in this way, we've maintained the original functionality while adding interactivity that allows you to better inspect the values and customize the visualization to your needs.