Skip to content

Commit

Permalink
Estratégia AlphaTrader Long Biased 2
Browse files Browse the repository at this point in the history
  • Loading branch information
valterebelo committed Dec 17, 2024
1 parent de21dba commit a374059
Show file tree
Hide file tree
Showing 24 changed files with 886 additions and 58 deletions.
Binary file added .DS_Store
Binary file not shown.
Binary file added alpha_trader/.DS_Store
Binary file not shown.
6 changes: 3 additions & 3 deletions alpha_trader/notebooks/explore_4.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
},
{
"cell_type": "code",
"execution_count": 298,
"execution_count": 4,
"metadata": {},
"outputs": [
{
Expand All @@ -18,7 +18,7 @@
"True"
]
},
"execution_count": 298,
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
Expand Down Expand Up @@ -69,7 +69,7 @@
},
{
"cell_type": "code",
"execution_count": 304,
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
Expand Down
Binary file modified alpha_trader/src/__pycache__/DataManager.cpython-311.pyc
Binary file not shown.
Binary file removed alpha_trader/src/__pycache__/__init__.cpython-311.pyc
Binary file not shown.
Binary file modified alpha_trader/src/__pycache__/abstractStrategy.cpython-311.pyc
Binary file not shown.
Binary file removed alpha_trader/src/__pycache__/agents.cpython-311.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file removed alpha_trader/src/__pycache__/loops.cpython-311.pyc
Binary file not shown.
Binary file removed alpha_trader/src/__pycache__/memory.cpython-311.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file modified alpha_trader/src/__pycache__/tradingPerformance.cpython-311.pyc
Binary file not shown.
Binary file modified alpha_trader/src/__pycache__/tradingStrategies.cpython-311.pyc
Binary file not shown.
Binary file removed alpha_trader/src/__pycache__/utils.cpython-311.pyc
Binary file not shown.
52 changes: 49 additions & 3 deletions alpha_trader/src/dataManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,48 @@ def determine_context(row):
return np.nan

def compute_context(self, start, end):
start = datetime.strptime(start, '%Y-%m-%d')
end = datetime.strptime(end, '%Y-%m-%d')

# Retrieve context data
context_data = self.get_context_data(pd.to_datetime('2011-08-1'), end)

# Market condition calculations
gradient_numerator = (context_data['price_usd_close'].diff(28) - context_data['price_realized_usd'].diff(28))
gradient_mean = gradient_numerator.expanding().mean()
gradient_std = gradient_numerator.expanding().std()
context_data['28d_mkt_gradient'] = (gradient_numerator - gradient_mean) / gradient_std

context_data['mayer_multiple'] = context_data['price_usd_close'] / context_data['price_usd_close'].rolling(200).mean()
context_data['price_profit_corr'] = context_data['price_usd_close'].rolling(7).corr(context_data['profit_relative'])

# Simple linear scaling function
def linear_scale(value, low, high):
# Values below low map to 0, above high map to 1, in between scale linearly
return np.clip((value - low) / (high - low), 0, 1)

# Normalize metrics to 0-1 based on chosen thresholds:
# Thresholds chosen from top detection conditions and reasoning about extremes.
# Adjust if necessary after backtesting.
mvrv_norm = linear_scale(context_data['mvrv_z_score'], 0.0, 3.8) # 0 to 3.8 range
mayer_norm = linear_scale(context_data['mayer_multiple'], 1.0, 1.3) # 1.0 to 1.3 range
nupl_norm = linear_scale(context_data['net_unrealized_profit_loss_account_based'], 0.0, 0.6) # 0.0 to 0.6 range
gradient_norm = linear_scale(context_data['28d_mkt_gradient'], 0.0, 7.0) # 0.0 to 7.0 range

# Combine into one continuous context measure:
# Average all four normalized values
context_data['context'] = (mvrv_norm + mayer_norm + nupl_norm + gradient_norm) / 4.0

# Drop unnecessary columns
context_data.drop(columns=['price_usd_close'], inplace=True)

# Filter the data to the requested start date
context_data = context_data[context_data.index >= start]
context_data = context_data[context_data.index <= end]

return context_data

def compute_context_boolean(self, start, end):

start = datetime.strptime(start, '%Y-%m-%d')
end = datetime.strptime(end, '%Y-%m-%d')
Expand Down Expand Up @@ -331,11 +373,15 @@ def compute_context(self, start, end):

return context_data

def get_data(self, start, end, contextualize=True):
def get_data(self, start, end, contextualize=True, boolean=False):

trigger_data = self.compute_triggers(start=start, end=end)
context_data = self.compute_context(start=start,end=end)


if boolean:
context_data = self.compute_context_boolean(start=start,end=end)
else:
context_data = self.compute_context(start=start,end=end)

trigger_data.reset_index(inplace=True)
context_data.reset_index(inplace=True)
context_data['t'] = context_data['t'].dt.tz_localize(None) # Ensure no timezone differences
Expand Down
219 changes: 183 additions & 36 deletions alpha_trader/src/pybit.ipynb

Large diffs are not rendered by default.

207 changes: 207 additions & 0 deletions alpha_trader/src/tests.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from tradingStrategies import BuyNHold, AlphaTraderLongBiased, AlphaTraderLongBiased2, AFT01 "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"bnh = BuyNHold(1000, '2020-01-01', '2024-06-1')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"test = AlphaTraderLongBiased2(1000, '2020-01-01', '2024-12-17')\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"test.data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"\n",
"# Assume self.data with a DatetimeIndex and 'position' column exists\n",
"data = test.data.copy()\n",
"\n",
"# Define masks for each type of position\n",
"is_cash = (data['position'] == 0)\n",
"is_long = (data['position'] > 0)\n",
"is_short = (data['position'] < 0)\n",
"\n",
"def get_durations(mask, index):\n",
" \"\"\"\n",
" Given a boolean mask (e.g., is_cash) and a DatetimeIndex,\n",
" find consecutive stretches of True and return their durations in days.\n",
" \"\"\"\n",
" int_mask = mask.astype(int)\n",
" # Start points where we go from False to True\n",
" starts = (int_mask.diff() == 1)\n",
" # End points where we go from True to False\n",
" ends = (int_mask.diff() == -1)\n",
" \n",
" starts_idx = index[starts]\n",
" ends_idx = index[ends]\n",
" \n",
" # Handle edge cases:\n",
" # If we start already in True condition at the beginning\n",
" if mask.iloc[0]:\n",
" starts_idx = starts_idx.insert(0, index[0])\n",
" \n",
" # If we end still in True condition at the end\n",
" if mask.iloc[-1]:\n",
" ends_idx = ends_idx.append(pd.Index([index[-1]]))\n",
" \n",
" min_len = min(len(starts_idx), len(ends_idx))\n",
" starts_idx = starts_idx[:min_len]\n",
" ends_idx = ends_idx[:min_len]\n",
" \n",
" durations = []\n",
" for s, e in zip(starts_idx, ends_idx):\n",
" if e > s:\n",
" duration_days = (e - s).total_seconds() / (3600 * 24)\n",
" durations.append(duration_days)\n",
" return durations\n",
"\n",
"# Get durations for each position type\n",
"cash_durations = get_durations(is_cash, data.index)\n",
"long_durations = get_durations(is_long, data.index)\n",
"short_durations = get_durations(is_short, data.index)\n",
"\n",
"# Plot histograms on the same figure with different colors\n",
"plt.figure(figsize=(10, 6))\n",
"plt.hist(cash_durations, bins=30, alpha=0.5, label='Cash Periods', color='blue', edgecolor='black')\n",
"#plt.hist(long_durations, bins=30, alpha=0.5, label='Long Periods', color='green', edgecolor='black')\n",
"#plt.hist(short_durations, bins=30, alpha=0.5, label='Short Periods', color='red', edgecolor='black')\n",
"\n",
"plt.title('Histogram of Durations by Position Type')\n",
"plt.xlabel('Duration (Days)')\n",
"plt.ylabel('Frequency')\n",
"plt.legend()\n",
"plt.grid(True)\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"\n",
"fig, ax1 = plt.subplots(figsize=(10, 6))\n",
"\n",
"# Plot the first dataset on the primary y-axis\n",
"ax1.plot(test.data['net_worth'], color='blue', label='Context')\n",
"ax1.set_ylabel('Delta', color='blue')\n",
"ax1.tick_params(axis='y', labelcolor='blue')\n",
"\n",
"# Create a second y-axis\n",
"ax2 = ax1.twinx() \n",
"# Plot the second dataset on the secondary y-axis\n",
"ax2.plot(test.data['context'], color='red', label='Close')\n",
"ax2.set_ylabel('Close', color='red')\n",
"ax2.tick_params(axis='y', labelcolor='red')\n",
"\n",
"# Optionally, set titles and grid\n",
"plt.title('Dual Axis Plot')\n",
"ax1.grid()\n",
"\n",
"# Show the plot\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"\n",
"fig, ax1 = plt.subplots(figsize=(10, 6))\n",
"\n",
"# Plot the first dataset on the primary y-axis\n",
"ax1.plot(test.data['diff'], color='blue', label='Context')\n",
"ax1.set_ylabel('Delta', color='blue')\n",
"ax1.tick_params(axis='y', labelcolor='blue')\n",
"\n",
"# Create a second y-axis\n",
"ax2 = ax1.twinx() \n",
"# Plot the second on the secondary y-axis\n",
"ax2.plot(test.data['close'], color='red', label='Close')\n",
"ax2.set_ylabel('Close', color='red')\n",
"ax2.tick_params(axis='y', labelcolor='red')\n",
"\n",
"# Optionally, set titles and grid\n",
"plt.title('Dual Axis Plot')\n",
"ax1.grid()\n",
"\n",
"# Show the plot\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Loading

0 comments on commit a374059

Please sign in to comment.