DiljitSingh14 commited on
Commit
98f0a4a
·
verified ·
1 Parent(s): 465ac24

Upload fetchChartData.py

Browse files
Files changed (1) hide show
  1. fetchChartData.py +63 -0
fetchChartData.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import json
4
+
5
+ def fetch_tradingview_data(url):
6
+ response = requests.get(url)
7
+ if response.status_code == 200:
8
+ data = response.json()
9
+ return data['ideas']['items']
10
+ else:
11
+ print(f"Error: Unable to fetch data. Status code {response.status_code}")
12
+ return []
13
+
14
+ def save_chart_image(image_url, save_path):
15
+ image_response = requests.get(image_url, stream=True)
16
+ if image_response.status_code == 200:
17
+ with open(save_path, 'wb') as file:
18
+ for chunk in image_response.iter_content(1024):
19
+ file.write(chunk)
20
+ else:
21
+ print(f"Error: Unable to download image from {image_url}. Status code {image_response.status_code}")
22
+
23
+ def extract_and_save_data(items, output_dir):
24
+ if not os.path.exists(output_dir):
25
+ os.makedirs(output_dir)
26
+
27
+ for item in items:
28
+ # Extract useful data
29
+ data = {
30
+ "id": item.get("id"),
31
+ "name": item.get("name"),
32
+ "description": item.get("description"),
33
+ "created_at": item.get("created_at"),
34
+ "chart_url": item.get("chart_url"),
35
+ "symbol": item.get("symbol", {}).get("name"),
36
+ "user": {
37
+ "id": item.get("user", {}).get("id"),
38
+ "username": item.get("user", {}).get("username"),
39
+ "pro_plan": item.get("user", {}).get("pro_plan"),
40
+ },
41
+ "likes_count": item.get("likes_count"),
42
+ }
43
+
44
+ # Save the data as JSON
45
+ json_path = os.path.join(output_dir, f"{data['id']}.json")
46
+ with open(json_path, 'w') as json_file:
47
+ json.dump(data, json_file, indent=4)
48
+
49
+ # Save the chart image
50
+ image_url = item.get("image", {}).get("big")
51
+ if image_url:
52
+ image_path = os.path.join(output_dir, f"{data['id']}.png")
53
+ save_chart_image(image_url, image_path)
54
+
55
+ if __name__ == "__main__":
56
+ # URL for TradingView ideas data
57
+ url = "https://www.tradingview.com/ideas/page-1"
58
+ output_directory = "tradingview_data"
59
+
60
+ # Fetch and process data
61
+ items = fetch_tradingview_data(url)
62
+ extract_and_save_data(items, output_directory)
63
+ print(f"Data extraction and image download complete. Saved in '{output_directory}' folder.")