TradingView
Intetics
2023年6月29日午後1時57分

Cycles Analysis 

S&P 500SP

詳細

I strongly believe in cycles, so I wanted to create something that would give a visual representation of bull/bear markets and give a prediction based on the previous data. It's up to you how to decide what is a bull/bear cycle. There is no single rule for all assets because 20% drop in SP500 starts a bear market in traditional markets, while 35% drop for Bitcoin is a Tuesday. You have two options on how to decide when markets turn: either by a % change (traditional definition) or if there is no new high/low after X days. A softer version to show periods of no new highs/lows is to use the Stagnation option. Stagnation periods hava the same logic as the cycle change by X days: if there is no new high/low then we treat this period as a stagnation. The difference is that stagnation periods do not change cycle directions and do not participate in calculations.
The script also draws a possible "predictions" zone where the current cycle might end up. There is no magic here, it just takes previous cycles' size to draw the possible boundaries. If you decide to use percentiles then the box area will be taken from the percentiles calculations, otherwise it will come from the full data. "x" in the predictions zone represents a target mean (average) value, "o" represents a target median value.

A few things to keep in mind:
- this script is not supposed to be used in trading. It was created for analysis. It repaints. And when I say "it repaints" - it might like repaint the last 6 months of data if a new low comes and we are in a stagnation period (aka not a financial advice).
- it doesn't work with replays as it does calculations only once on the last candle.
- you need at least 3 periods to be able to calculate percentiles. And after this it will remove at least 1 period on each side. Which means that 90 percentile will not be a real 90 percentile until you have enough periods for it to be (20 in this specific case).
- it assumes that a year = 360 days, and a month = 30 days. So the duration presentation might not be exact, until you move to the day level.
- I had macro analysis in mind when I created the script, but nothing stops you from using it in a 1m time frame for BTC. Just change the time duration presentation.
- the last period is not finished, so it doesn't participate in calculations.

リリースノート

Changes in the new version:
- changed the indicator to work with replays and real time
- added decimals to % direction change
- fixed an exception when there are 0 periods
- separate percent change for bull and bear markets
- added ability to calculate duration periods in Days or Candles
- added minimum period duration
コメント
PineCoders
In the name of all TradingViewers, thank you for your valuable contribution to the community, and congrats!
Intetics
@PineCoders, Wow, thanks!
sultansimsek251
@PineCoders, Wow, thanks!
thiru374
import pandas as pd

# Function to calculate exponential moving average (EMA)
def calculate_ema(data, period):
weights = pd.Series([1 - 0.5**(i+1) for i in range(period)])
ema = data.rolling(window=period).apply(lambda prices: np.dot(prices, weights), raw=True)
return ema

# Function to check for EMA crossover
def check_ema_crossover(ema_short, ema_long):
return ema_short[-2] < ema_long[-2] and ema_short[-1] > ema_long[-1]

# Load historical data (assumes you have a CSV file with 'date', 'close' columns)
df = pd.read_csv('nifty_data.csv')

# Calculate EMA13 and EMA55
df['EMA13'] = calculate_ema(df['close'], 13)
df['EMA55'] = calculate_ema(df['close'], 55)

# Initialize variables
in_position = False
buy_price = 0

# Iterate through the data to generate signals
for i in range(1, len(df)):
if check_ema_crossover(df['EMA13'][:i+1], df['EMA55'][:i+1]):
if not in_position:
# Generate buy signal
in_position = True
buy_price = df['close']
print(f"Buy at {buy_price}")
elif check_ema_crossover(df['EMA55'][:i+1], df['EMA13'][:i+1]):
if in_position:
# Generate sell signal
in_position = False
sell_price = df['close']
print(f"Sell at {sell_price}")
# Calculate profit/loss
profit_loss = sell_price - buy_price
print(f"Profit/Loss: {profit_loss}")
odysseasliolias
Very good job !! Congratulations!!
OutsourcE
Hi, is there a way to integrate it with a strategy? What are the hooks in case?
Intetics
@OutsourcE, hey mate, I was thinking about it, but then |I came to a decision that in most cases it well be a sure way to rekt. The only instruments which might be profitable to trade are where you have median (mostly bull) change minus the entry % > 50. An exmaple of this would be SP500 on weekly. 229 - 30 = 199. In this case the entry would be when the start of a new bull period is identified, with the exit on the median expectation ("o"). I wish TradingView would allow custom scripts to be used as screeners - then it would be a different story. Meanwhile, the absolute majority of thing especially on lower time frames that I checked would be unprofitable. Hence, I decided not to turn it into a strategy, to avoid people getting into troubles.
OutsourcE
@Intetics, i might be wrong, but i thought it was dependent on cycle %™not timeframe. Second of all, TV allows you to creat custom scanners, with the limit per 120 coins per scanner and 1 security call. And lastly, no one entices no one to do this or that, to each his own. Cheers 🍻

Nice script btw, one can use barssince for e.g., using this cycles as fundamental, and utilize it with other favourite scripts, etc..
Intetics
@OutsourcE, thanks mate. Yes, you're right that it depends on %. Though it still needs a trend (either direction) so the average values were higher than the entrance %. And it happens more often on higher timeframes as it's harder for market manipulators to move the markets on these timeframes, so fewer chances of stop losses and better results.
That's interesting about the scanner, I didn't know about, I'll definitelly check, thanks.
And I know that nobody forces people to do anything. Though I was on the other side and I know how easy it is to start loosing money on scripts I didn't udnerstand but which showed good previous results. So don't really want to associate myself with these situations. At the same time, the script is open source, all calcs are there, and if anyone wants to convert it to a strategy - it shouldn't take long time :)
OutsourcE
@Intetics, right. I'll be following in case you change your mind and do a strategy version. But A scanner version would even be mind blowing 😁
詳細