Advertisement
sourav8256

Untitled

Oct 17th, 2023 (edited)
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.26 KB | None | 0 0
  1. import pandas as pd
  2. import numpy as np
  3. import plotly.graph_objects as go
  4.  
  5. # Sample data
  6. data = pd.DataFrame({
  7. "close": [100, 102, 104, 107, 106, 105, 110, 115, 112, 118, 120, 115, 110, 105],
  8. "open": [98, 100, 102, 104, 107, 106, 112, 110, 115, 112, 118, 120, 115, 110],
  9. "high": [102, 104, 107, 106, 105, 108, 115, 118, 120, 115, 125, 118, 112, 115],
  10. "low": [97, 98, 101, 100, 103, 105, 109, 110, 112, 108, 112, 110, 105, 100]
  11. })
  12.  
  13. # Constants
  14. periods = 10
  15. multiplier = 3.0
  16. change_atr = True
  17. show_signals = True
  18. highlighting = True
  19.  
  20. # Calculate ATR
  21. if change_atr:
  22. atr = data['high'] - data['low']
  23. else:
  24. atr = atr2 = np.mean(data['high'] - data['low'])
  25.  
  26. for i in range(1, len(data)):
  27. atr2 = (atr2 * (periods - 1) + atr[i]) / periods
  28. atr[i] = atr2
  29.  
  30. # Calculate SuperTrend
  31. up = data['high'] - multiplier * atr
  32. up1 = [up[0]]
  33. for i in range(1, len(data)):
  34. up1.append(up[i - 1] if data['close'][i - 1] > up[i - 1] else up[i])
  35.  
  36. down = data['low'] + multiplier * atr
  37. down1 = [down[0]]
  38. for i in range(1, len(data)):
  39. down1.append(down[i - 1] if data['close'][i - 1] < down[i - 1] else down[i])
  40.  
  41. trend = [1]
  42. for i in range(1, len(data)):
  43. if trend[i - 1] == -1 and data['close'][i] > down1[i - 1]:
  44. trend.append(1)
  45. elif trend[i - 1] == 1 and data['close'][i] < up1[i - 1]:
  46. trend.append(-1)
  47. else:
  48. trend.append(trend[i - 1])
  49.  
  50. # Visualize SuperTrend
  51. fig = go.Figure()
  52.  
  53. fig.add_trace(go.Scatter(x=data.index, y=up, mode='lines', name='Up Trend', line=dict(width=2, color='green'))
  54. fig.add_trace(go.Scatter(x=data.index, y=down, mode='lines', name='Down Trend', line=dict(width=2, color='red'))
  55.  
  56. buy_signal_indices = [i for i in range(1, len(data)) if trend[i] == 1 and trend[i - 1] == -1]
  57. buy_signals = [up[i] for i in buy_signal_indices]
  58.  
  59. sell_signal_indices = [i for i in range(1, len(data)) if trend[i] == -1 and trend[i - 1] == 1]
  60. sell_signals = [down[i] for i in sell_signal_indices]
  61.  
  62. fig.add_trace(go.Scatter(x=buy_signal_indices, y=buy_signals, mode='markers', name='Buy Signals', marker=dict(size=6, color='green'))
  63. fig.add_trace(go.Scatter(x=sell_signal_indices, y=sell_signals, mode='markers', name='Sell Signals', marker=dict(size=6, color='red'))
  64.  
  65. fig.update_layout(title='SuperTrend Indicator', xaxis_title='Date', yaxis_title='Price')
  66. fig.show()
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73. import pandas as pd
  74.  
  75. # Sample data
  76. data = pd.DataFrame({
  77. "close": [100, 102, 104, 107, 106, 105, 110, 115, 112, 118, 120, 115, 110, 105],
  78. })
  79.  
  80. # Constants
  81. periods = 10
  82. multiplier = 3.0
  83. change_atr = True
  84. show_signals = True
  85.  
  86. # Calculate ATR
  87. if change_atr:
  88. atr = data['close'].diff().abs()
  89. else:
  90. atr = atr2 = data['close'].diff().abs().rolling(periods).mean()
  91.  
  92. # Calculate SuperTrend
  93. up = data['close'] - multiplier * atr
  94. up1 = up.shift(1)
  95. up.iloc[0] = up1.iloc[0] if data['close'].iloc[0] > up1.iloc[0] else up.iloc[0]
  96.  
  97. down = data['close'] + multiplier * atr
  98. down1 = down.shift(1)
  99. down.iloc[0] = down1.iloc[0] if data['close'].iloc[0] < down1.iloc[0] else down.iloc[0]
  100.  
  101. trend = 1
  102. trend_values = [trend]
  103. for i in range(1, len(data)):
  104. if trend == -1 and data['close'].iloc[i] > down1.iloc[i]:
  105. trend = 1
  106. elif trend == 1 and data['close'].iloc[i] < up1.iloc[i]:
  107. trend = -1
  108. trend_values.append(trend)
  109.  
  110. # Generate buy and sell suggestions
  111. buy_signals = []
  112. sell_signals = []
  113.  
  114. for i in range(1, len(data)):
  115. if trend_values[i] == 1 and trend_values[i - 1] == -1:
  116. buy_signals.append((i, "Buy"))
  117. elif trend_values[i] == -1 and trend_values[i - 1] == 1:
  118. sell_signals.append((i, "Sell"))
  119.  
  120. # Print buy and sell suggestions
  121. for i, signal in buy_signals:
  122. print(f"At index {i}, suggest to {signal} the stock.")
  123.  
  124. for i, signal in sell_signals:
  125. print(f"At index {i}, suggest to {signal} the stock.")
  126.  
  127.  
  128.  
  129.  
  130.  
  131.  
  132.  
  133. ==================================================================================================
  134.  
  135.  
  136.  
  137.  
  138.  
  139. import yfinance as yf
  140. import pandas as pd
  141.  
  142. def calculate_super_trend(data, periods=10, multiplier=3.0, change_atr=True):
  143. if change_atr:
  144. atr = data['Close'].diff().abs()
  145. else:
  146. atr = atr2 = data['Close'].diff().abs().rolling(periods).mean()
  147.  
  148. up = data['Close'] - multiplier * atr
  149. up1 = up.shift(1)
  150. up.iloc[0] = up1.iloc[0] if data['Close'].iloc[0] > up1.iloc[0] else up.iloc[0]
  151.  
  152. down = data['Close'] + multiplier * atr
  153. down1 = down.shift(1)
  154. down.iloc[0] = down1.iloc[0] if data['Close'].iloc[0] < down1.iloc[0] else down.iloc[0]
  155.  
  156. trend = 1
  157. trend_values = [trend]
  158. for i in range(1, len(data)):
  159. if trend == -1 and data['Close'].iloc[i] > down1.iloc[i]:
  160. trend = 1
  161. elif trend == 1 and data['Close'].iloc[i] < up1.iloc[i]:
  162. trend = -1
  163. trend_values.append(trend)
  164.  
  165. return trend_values
  166.  
  167. # Define a list of stock symbols
  168. stocks = ["AAPL", "GOOGL", "MSFT", "TSLA"]
  169.  
  170. for stock_symbol in stocks:
  171. stock_data = yf.download(stock_symbol, period="1y")
  172. stock_data['SuperTrend'] = calculate_super_trend(stock_data)
  173.  
  174. buy_signals = []
  175. sell_signals = []
  176.  
  177. for i in range(1, len(stock_data)):
  178. if stock_data['SuperTrend'].iloc[i] == 1 and stock_data['SuperTrend'].iloc[i - 1] == -1:
  179. buy_signals.append((i, "Buy"))
  180. elif stock_data['SuperTrend'].iloc[i] == -1 and stock_data['SuperTrend'].iloc[i - 1] == 1:
  181. sell_signals.append((i, "Sell"))
  182.  
  183. print(f"Stock: {stock_symbol}")
  184. print("Buy Signals:")
  185. for i, signal in buy_signals:
  186. print(f"At index {i}, suggest to {signal} the stock.")
  187.  
  188. print("Sell Signals:")
  189. for i, signal in sell_signals:
  190. print(f"At index {i}, suggest to {signal} the stock.")
  191. print("\n")
  192.  
  193.  
  194.  
  195.  
  196.  
  197. ======================================================
  198.  
  199.  
  200.  
  201. import yfinance as yf
  202. import pandas as pd
  203.  
  204. def calculate_super_trend(data, periods=10, multiplier=3.0, change_atr=True):
  205. if change_atr:
  206. atr = data['Close'].diff().abs()
  207. else:
  208. atr = atr2 = data['Close'].diff().abs().rolling(periods).mean()
  209.  
  210. up = data['Close'] - multiplier * atr
  211. up1 = up.shift(1)
  212. up.iloc[0] = up1.iloc[0] if data['Close'].iloc[0] > up1.iloc[0] else up.iloc[0]
  213.  
  214. down = data['Close'] + multiplier * atr
  215. down1 = down.shift(1)
  216. down.iloc[0] = down1.iloc[0] if data['Close'].iloc[0] < down1.iloc[0] else down.iloc[0]
  217.  
  218. trend = 1
  219. trend_values = [trend]
  220. for i in range(1, len(data)):
  221. if trend == -1 and data['Close'].iloc[i] > down1.iloc[i]:
  222. trend = 1
  223. elif trend == 1 and data['Close'].iloc[i] < up1.iloc[i]:
  224. trend = -1
  225. trend_values.append(trend)
  226.  
  227. return trend_values
  228.  
  229. # Define a list of stock symbols
  230. stocks = ["AAPL", "GOOGL", "TSLA","SBIN.NS"]
  231.  
  232. for stock_symbol in stocks:
  233. stock_data = yf.download(stock_symbol, period="1y")
  234. stock_data['SuperTrend'] = calculate_super_trend(stock_data)
  235.  
  236. last_signal = stock_data['SuperTrend'].iloc[-1]
  237.  
  238. if last_signal == 1:
  239. print(f"For stock {stock_symbol}, the final suggestion is to Buy.")
  240. elif last_signal == -1:
  241. print(f"For stock {stock_symbol}, the final suggestion is to Sell.")
  242. else:
  243. print(f"For stock {stock_symbol}, no suggestion is available.")
  244.  
  245.  
  246.  
  247.  
  248.  
  249. =============================== Grouped Results =============================
  250.  
  251.  
  252. import yfinance as yf
  253. import pandas as pd
  254.  
  255. def calculate_super_trend(data, periods=10, multiplier=3.0, change_atr=True):
  256. if change_atr:
  257. atr = data['Close'].diff().abs()
  258. else:
  259. atr = atr2 = data['Close'].diff().abs().rolling(periods).mean()
  260.  
  261. up = data['Close'] - multiplier * atr
  262. up1 = up.shift(1)
  263. up.iloc[0] = up1.iloc[0] if data['Close'].iloc[0] > up1.iloc[0] else up.iloc[0]
  264.  
  265. down = data['Close'] + multiplier * atr
  266. down1 = down.shift(1)
  267. down.iloc[0] = down1.iloc[0] if data['Close'].iloc[0] < down1.iloc[0] else down.iloc[0]
  268.  
  269. trend = 1
  270. trend_values = [trend]
  271. for i in range(1, len(data)):
  272. if trend == -1 and data['Close'].iloc[i] > down1.iloc[i]:
  273. trend = 1
  274. elif trend == 1 and data['Close'].iloc[i] < up1.iloc[i]:
  275. trend = -1
  276. trend_values.append(trend)
  277.  
  278. return trend_values
  279.  
  280. # Define a list of stock symbols
  281. stocks = ["GOOGL", "SBIN.NS", "TSLA"]
  282.  
  283. buy_suggestions = []
  284. sell_suggestions = []
  285.  
  286. for stock_symbol in stocks:
  287. stock_data = yf.download(stock_symbol, period="1y")
  288. stock_data['SuperTrend'] = calculate_super_trend(stock_data)
  289.  
  290. last_signal = stock_data['SuperTrend'].iloc[-1]
  291.  
  292. if last_signal == 1:
  293. buy_suggestions.append((stock_symbol, "Buy"))
  294. elif last_signal == -1:
  295. sell_suggestions.append((stock_symbol, "Sell"))
  296.  
  297. # Group Buy and Sell suggestions for better visualization
  298. all_suggestions = buy_suggestions + sell_suggestions
  299.  
  300. print("Buy Suggestions:")
  301. for stock, suggestion in buy_suggestions:
  302. print(f"For stock {stock}, the final suggestion is to {suggestion}.")
  303.  
  304. print("\nSell Suggestions:")
  305. for stock, suggestion in sell_suggestions:
  306. print(f"For stock {stock}, the final suggestion is to {suggestion}.")
  307.  
  308. print("\nAll Suggestions (Buy first, then Sell):")
  309. for stock, suggestion in all_suggestions:
  310. print(f"For stock {stock}, the final suggestion is to {suggestion}.")
  311.  
  312.  
  313.  
  314.  
  315.  
  316. ============================ Final Result ================================
  317.  
  318.  
  319. import yfinance as yf
  320. import pandas as pd
  321. import os
  322. from datetime import datetime
  323.  
  324. def calculate_super_trend(data, periods=10, multiplier=3.0, change_atr=True):
  325. if change_atr:
  326. atr = data['Close'].diff().abs()
  327. else:
  328. atr = atr2 = data['Close'].diff().abs().rolling(periods).mean()
  329.  
  330. up = data['Close'] - multiplier * atr
  331. up1 = up.shift(1)
  332. up.iloc[0] = up1.iloc[0] if data['Close'].iloc[0] > up1.iloc[0] else up.iloc[0]
  333.  
  334. down = data['Close'] + multiplier * atr
  335. down1 = down.shift(1)
  336. down.iloc[0] = down1.iloc[0] if data['Close'].iloc[0] < down1.iloc[0] else down.iloc[0]
  337.  
  338. trend = 1
  339. trend_values = [trend]
  340. for i in range(1, len(data)):
  341. if trend == -1 and data['Close'].iloc[i] > down1.iloc[i]:
  342. trend = 1
  343. elif trend == 1 and data['Close'].iloc[i] < up1.iloc[i]:
  344. trend = -1
  345. trend_values.append(trend)
  346.  
  347. return trend_values
  348.  
  349. # Create a "cache" folder if it doesn't exist
  350. if not os.path.exists("cache"):
  351. os.makedirs("cache")
  352.  
  353. # Define a list of stock symbols
  354. stocks = ["GOOGL", "SBIN.NS", "TSLA"]
  355.  
  356. buy_suggestions = []
  357. sell_suggestions = []
  358.  
  359. for stock_symbol in stocks:
  360. # Construct the cache file name using the stock symbol and current date
  361. today = datetime.now().strftime('%Y-%m-%d')
  362. cache_filename = f"cache/{stock_symbol}_{today}.csv"
  363.  
  364. if os.path.exists(cache_filename):
  365. # Load data from cache if available
  366. stock_data = pd.read_csv(cache_filename, index_col=0, parse_dates=True)
  367. else:
  368. # Download new data
  369. stock_data = yf.download(stock_symbol, period="1d")
  370. stock_data['SuperTrend'] = calculate_super_trend(stock_data)
  371.  
  372. # Check if SuperTrend data is empty
  373. if stock_data['SuperTrend'].dropna().empty:
  374. print(f"No SuperTrend data available for {stock_symbol}.")
  375. else:
  376. # Save the data to the cache
  377. stock_data.to_csv(cache_filename)
  378.  
  379.  
  380. last_signal = stock_data['SuperTrend'].iloc[-1]
  381.  
  382. if last_signal == 1:
  383. buy_suggestions.append((stock_symbol, "Buy"))
  384. elif last_signal == -1:
  385. sell_suggestions.append((stock_symbol, "Sell"))
  386.  
  387. # Group Buy and Sell suggestions for better visualization
  388. all_suggestions = buy_suggestions + sell_suggestions
  389.  
  390. print("Buy Suggestions:")
  391. for stock, suggestion in buy_suggestions:
  392. print(f"For stock {stock}, the final suggestion is to {suggestion}.")
  393.  
  394. print("\nSell Suggestions:")
  395. for stock, suggestion in sell_suggestions:
  396. print(f"For stock {stock}, the final suggestion is to {suggestion}.")
  397.  
  398. print("\nAll Suggestions (Buy first, then Sell):")
  399. for stock, suggestion in all_suggestions:
  400. print(f"For stock {stock}, the final suggestion is to {suggestion}.")
  401.  
  402.  
  403.  
  404.  
  405.  
  406.  
  407.  
  408.  
  409.  
  410.  
  411.  
  412.  
  413.  
  414.  
  415.  
  416.  
  417.  
  418.  
  419.  
  420.  
  421.  
  422.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement