""" class DataFetcher: def init(self, tickers, startdate='1990-01-01', enddate=None,…
- User
""" class DataFetcher: def init(self, tickers, start_date='1990-01-01', end_date=None, auto_adjust=False): """ Initializes the DataFetcher with tickers and date range.
Parameters: - tickers (list or str): Stock ticker symbols. - start_date (str): Start date in 'YYYY-MM-DD' format. - end_date (str): End date in 'YYYY-MM-DD' format. Defaults to today if not provided. - auto_adjust (bool): Whether to adjust all OHLC prices. Defaults to False. """ 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.auto_adjust = auto_adjust self.data = None def fetch_data(self): """ Fetches historical data for the specified tickers. """ self.data = yf.download( self.tickers, start=self.start_date, end=self.end_date, group_by='ticker', auto_adjust=self.auto_adjust, threads=True ) # Handle single ticker case if len(self.tickers) == 1: self.data = {self.tickers[0]: self.data} else: self.data = {ticker: self.data[ticker] for ticker in self.tickers} return self.dataimport pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import os from scipy.stats import skew, kurtosis
class MonthlySeasonalityAnalyzer: def init(self, data, budget=4000, odds_ratio=2, output_dir='seasonality_data'): """ Initializes the MonthlySeasonalityAnalyzer with necessary parameters. """ self.data = data self.budget = budget self.odds_ratio = odds_ratio self.output_dir = output_dir if not os.path.exists(self.output_dir): os.makedirs(self.output_dir)
@staticmethod def calculate_kelly_ratio(returns): """ Calculates the Kelly ratio and fraction. """ win_prob = np.mean(returns > 0) loss_prob = 1 - win_prob win_return = np.mean(returns[returns > 0]) if np.any(returns > 0) else 0 loss_return = abs(np.mean(returns[returns < 0])) if np.any(returns < 0) else 0 if loss_return == 0: kelly_ratio = 0 else: kelly_ratio = (win_prob - (loss_prob / (win_return / loss_return))) if (win_return / loss_return) != 0 else 0 kelly_fraction = kelly_ratio / 2 # Using half Kelly for safety return kelly_ratio, kelly_fraction @staticmethod def get_cell_colors(summary_table): """ Generates cell colors for the summary table based on value ranges. """ def color_scale(val, cmap, vmin, vmax): norm = plt.Normalize(vmin, vmax) return sns.color_palette(cmap, as_cmap=True)(norm(val)) cell_colors = [] for col in summary_table.columns: if col in ['Avg Returns (%)', 'Pos %', 'Avg Kelly Ratio', 'Avg Kelly Fraction', 'Position Size ($)']: cmap = "RdYlGn" elif col == 'StDev (%)': cmap = "YlOrRd" else: # Skewness and Kurtosis cmap = "PuOr" vmin = summary_table[col].min() vmax = summary_table[col].max() colors = [color_scale(x, cmap, vmin, vmax) for x in summary_table[col]] cell_colors.append(colors) # Transpose to match table cell structure return list(map(list, zip(*cell_colors))) def analyze_monthly_seasonality(self, ticker): """ Analyzes monthly seasonality for a given ticker. """ df = self.data[ticker]['Adj Close'].resample('M').ffill() monthly_returns = df.pct_change().dropna() * 100 # Percentage # Organize into 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 correct month order months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] pivot_table = pivot_table.reindex(columns=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()), 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]) # Position size based on Kelly fraction position_sizes = avg_kelly_fraction * self.budget # 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, 'Position Size ($)': position_sizes }) return pivot_table, summary_table def visualize_monthly_seasonality(self, ticker): """ Visualizes monthly seasonality with a heatmap and summary table. """ pivot_table, summary_table = self.analyze_monthly_seasonality(ticker) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 8)) # Heatmap sns.heatmap( pivot_table, annot=True, fmt=".2f", cmap="coolwarm", vmin=-5, vmax=5, center=0, linewidths=.5, cbar_kws={"shrink": .75}, ax=ax1 ) ax1.set_title(f'Monthly Returns Heatmap for {ticker}', fontsize=16) ax1.set_xlabel('Month', fontsize=12) ax1.set_ylabel('Year', fontsize=12) ax1.tick_params(axis='both', which='major', labelsize=10) # Summary table ax2.axis('tight') ax2.axis('off') cell_colors = self.get_cell_colors(summary_table) table = ax2.table( cellText=summary_table.values.round(2), colLabels=summary_table.columns, rowLabels=summary_table.index, cellLoc='center', loc='center', cellColours=cell_colors ) table.auto_set_font_size(False) table.set_fontsize(8) table.scale(1.2, 1.5) ax2.set_title(f'Summary Table for {ticker}', fontsize=16) plt.tight_layout() plt.show() def export_monthly_seasonality_data(self, ticker): """ Exports monthly seasonality data to a CSV file. """ _, summary_table = self.analyze_monthly_seasonality(ticker) output_path = os.path.join(self.output_dir, f'{ticker}_monthly_seasonality.csv') summary_table.to_csv(output_path) print(f'Saved {ticker} monthly seasonality data to {output_path}') - Assistant