3
3
import pandas as pd
4
4
import requests
5
5
6
+
6
7
def market_data (market , time = 90 , max_contracts = 6 ):
7
8
"""
8
9
Fetch market data from PredictIt's API and return as a DataFrame.
@@ -15,11 +16,11 @@ def market_data(market, time=90, max_contracts=6):
15
16
Returns:
16
17
- pd.DataFrame: DataFrame containing the market data or None if an error occurred.
17
18
"""
18
- url = f' https://www.predictit.org/api/Public/GetMarketChartData/{ market } '
19
+ url = f" https://www.predictit.org/api/Public/GetMarketChartData/{ market } "
19
20
params = {
20
- ' timespan' : time ,
21
- ' maxContracts' : max_contracts ,
22
- ' isTimespanInHours' : ' false'
21
+ " timespan" : time ,
22
+ " maxContracts" : max_contracts ,
23
+ " isTimespanInHours" : " false" ,
23
24
}
24
25
try :
25
26
response = requests .get (url , params = params )
@@ -40,9 +41,54 @@ def market_data(market, time=90, max_contracts=6):
40
41
41
42
return None
42
43
44
+
43
45
def market_name (market ):
44
- # this may not be the best way to do it, but it worked pretty well for me
45
- df = pd .read_json ('https://www.predictit.org/api/marketdata/markets/' + str (market ))
46
- # sets the market to a string and returns it.
47
- text = str (df ['name' ][0 ])
46
+ # this may not be the best way to do it, but it worked pretty well for me.
47
+
48
+ df = pd .read_json ("https://www.predictit.org/api/marketdata/markets/" + str (market ))
49
+ # sets the market to a string and returns it.
50
+
51
+ text = str (df ["name" ][0 ])
48
52
return text
53
+
54
+
55
+ def all_markets ():
56
+ """
57
+ Fetch all available markets from the PredictIt API and return the data as a DataFrame.
58
+
59
+ This function sends a GET request to the PredictIt API endpoint to retrieve all market data.
60
+ The returned data includes market IDs and names, which are then structured into a pandas
61
+ DataFrame with two columns: 'Market ID' and 'Market Name'.
62
+
63
+ Returns:
64
+ --------
65
+ pd.DataFrame
66
+ A DataFrame containing market IDs and their corresponding names.
67
+
68
+ Raises:
69
+ -------
70
+ Exception
71
+ If the API request fails, an exception is raised with the HTTP status code.
72
+
73
+ Examples:
74
+ ---------
75
+ df = all_markets()
76
+ print(df.head())
77
+ Market ID Market Name
78
+ 0 123 Which party wins?
79
+ 1 456 Who will be the next president?
80
+ """
81
+ url = "https://www.predictit.org/api/marketdata/all"
82
+ headers = {"Accept" : "application/json" }
83
+ response = requests .get (url , headers = headers )
84
+
85
+ if response .status_code == 200 :
86
+ data = response .json ()
87
+ markets = data ["markets" ]
88
+ market_names = [(market ["id" ], market ["name" ]) for market in markets ]
89
+ df = pd .DataFrame (market_names , columns = ["Market ID" , "Market Name" ])
90
+ return df
91
+ else :
92
+ raise Exception (
93
+ f"Failed to retrieve data. HTTP Status Code: { response .status_code } "
94
+ )
0 commit comments