Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import yfinance as yf
- import pandas as pd
- import plotly.graph_objs as go
- from datetime import datetime, timedelta
- tickers = ['QQQ', 'TQQQ', 'SPY']
- data = yf.download(tickers, start='2015-01-01', end=datetime.today().strftime('%Y-%m-%d'))['Adj Close']
- initial_cash = 10000
- cash = 2/3 * initial_cash
- tqqq_holding = 1/3 * initial_cash / data['TQQQ'].iloc[0]
- monthly_contribution = 10000
- buy_dates = []
- portfolio_value = [initial_cash]
- cash_reserve = [cash]
- tqqq_value = [tqqq_holding * data['TQQQ'].iloc[0]]
- total_cash = cash
- tqqq_allocation = tqqq_holding * data['TQQQ'].iloc[0]
- drawdown20, drawdown30, drawdown40 = False, False, False
- drawdown20_needsreset, drawdown30_needsreset, drawdown40_needsreset = False, False, False
- ath = data['QQQ'].iloc[0] # Initial All-Time High
- # Initialize values for SPY, QQQ, and TQQQ with monthly contributions
- spy_holding = initial_cash / data['SPY'].iloc[0]
- qqq_holding = initial_cash / data['QQQ'].iloc[0]
- tqqq_compare_holding = initial_cash / data['TQQQ'].iloc[0]
- spy_value = [initial_cash]
- qqq_value = [initial_cash]
- tqqq_compare_value = [initial_cash]
- for i in range(1, len(data)):
- # Update ATH
- ath = max(ath, data['QQQ'].iloc[i])
- # Reset drawdowns if ATH
- if ath == data['QQQ'].iloc[i]:
- drawdown20, drawdown30, drawdown40 = False, False, False
- drawdown20_needsreset, drawdown30_needsreset, drawdown40_needsreset = False, False, False
- # Check for buy conditions given drawdowns
- drawdown = (data['QQQ'].iloc[i] - ath) / ath
- drawdown_1 = (data['QQQ'].iloc[i-1] - ath) / ath
- if drawdown < -0.2 and drawdown_1 > -0.2 and not drawdown20_needsreset and not drawdown30_needsreset and not drawdown40_needsreset:
- drawdown20 = True
- drawdown20_needsreset = True
- if drawdown < -0.3 and drawdown_1 > -0.3 and not drawdown20_needsreset and not drawdown30_needsreset and not drawdown40_needsreset:
- drawdown30 = True
- drawdown30_needsreset = True
- if drawdown < -0.4 and drawdown_1 > -0.4 and not drawdown20_needsreset and not drawdown30_needsreset and not drawdown40_needsreset:
- drawdown40 = True
- drawdown40_needsreset = True
- # Buy TQQQ
- if (drawdown20 or drawdown30 or drawdown40) and cash > 0:
- print('****** BUY OPPORTUNITY')
- print('date = ', data.index[i])
- print('cash = ', cash)
- print('ath QQQ = ', ath)
- print('current value QQQ = ', data['QQQ'].iloc[i])
- print('prev value QQQ = ', data['QQQ'].iloc[i-1])
- print('drawdown', drawdown)
- print('drawdown_1', drawdown_1)
- print('drawdown20', drawdown20, drawdown20_needsreset)
- print('drawdown30', drawdown30, drawdown30_needsreset)
- print('drawdown40', drawdown40, drawdown40_needsreset)
- buy_amount = 1/3 * cash
- tqqq_holding += buy_amount / data['TQQQ'].iloc[i]
- cash -= buy_amount
- buy_dates.append(data.index[i])
- drawdown20, drawdown30, drawdown40 = False, False, False # Reset drawdown indicators
- if i > 0 and data.index[i].day == 1:
- # Add monthly cash contribution
- cash += monthly_contribution
- # Add to SPY, QQQ, TQQQ for comparison
- spy_holding += monthly_contribution / data['SPY'].iloc[i]
- qqq_holding += monthly_contribution / data['QQQ'].iloc[i]
- tqqq_compare_holding += monthly_contribution / data['TQQQ'].iloc[i]
- # Calculate current portfolio value
- total_cash = cash
- tqqq_allocation = tqqq_holding * data['TQQQ'].iloc[i]
- portfolio_value.append(total_cash + tqqq_allocation)
- cash_reserve.append(cash)
- tqqq_value.append(tqqq_allocation)
- # Calculate current values for SPY, QQQ, and TQQQ with monthly contributions
- spy_value.append(spy_holding * data['SPY'].iloc[i])
- qqq_value.append(qqq_holding * data['QQQ'].iloc[i])
- tqqq_compare_value.append(tqqq_compare_holding * data['TQQQ'].iloc[i])
- # Plot Portfolio Value
- fig = go.Figure()
- # Plot Strategy Portfolio Value
- fig.add_trace(go.Scatter(x=data.index, y=portfolio_value, mode='lines', name='Portfolio'))
- # Plot References with Monthly Contributions
- fig.add_trace(go.Scatter(x=data.index, y=spy_value, mode='lines', name='SPY'))
- fig.add_trace(go.Scatter(x=data.index, y=qqq_value, mode='lines', name='QQQ'))
- fig.add_trace(go.Scatter(x=data.index, y=tqqq_compare_value, mode='lines', name='TQQQ'))
- # Add Buy Markers
- for date in buy_dates:
- fig.add_trace(go.Scatter(x=[date], y=[portfolio_value[data.index.get_loc(date)]], mode='markers', name='Buy', marker=dict(color='red', size=10)))
- fig.update_layout(title='Portfolio vs SPY, QQQ, TQQQ with Monthly Contributions',
- xaxis_title='Date',
- yaxis_title='Portfolio Value',
- showlegend=True)
- fig.show()
- # Display Buy Dates Table
- buy_table = pd.DataFrame({'Buy Dates': buy_dates})
- print(buy_table)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement