Skip to content

Commit 1989ae8

Browse files
committed
added all_markets()
1 parent 9f7592d commit 1989ae8

7 files changed

+77
-9
lines changed
Binary file not shown.
Binary file not shown.

predictit_markets/predictit_markets.py

Lines changed: 54 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import pandas as pd
44
import requests
55

6+
67
def market_data(market, time=90, max_contracts=6):
78
"""
89
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):
1516
Returns:
1617
- pd.DataFrame: DataFrame containing the market data or None if an error occurred.
1718
"""
18-
url = f'https://www.predictit.org/api/Public/GetMarketChartData/{market}'
19+
url = f"https://www.predictit.org/api/Public/GetMarketChartData/{market}"
1920
params = {
20-
'timespan': time,
21-
'maxContracts': max_contracts,
22-
'isTimespanInHours': 'false'
21+
"timespan": time,
22+
"maxContracts": max_contracts,
23+
"isTimespanInHours": "false",
2324
}
2425
try:
2526
response = requests.get(url, params=params)
@@ -40,9 +41,54 @@ def market_data(market, time=90, max_contracts=6):
4041

4142
return None
4243

44+
4345
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])
4852
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+
)
142 Bytes
Binary file not shown.
Binary file not shown.
Binary file not shown.

tests/test_predictit_markets.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
import unittest
44
from unittest.mock import patch, Mock
55
import requests
6-
from predictit_markets.predictit_markets import market_data
6+
import pandas as pd
7+
from predictit_markets.predictit_markets import all_markets, market_data
78

89
class TestPredictItMarkets(unittest.TestCase):
910

@@ -63,6 +64,27 @@ def test_market_data_json_error(self, mock_get):
6364

6465
# Assert the DataFrame is None due to JSON error
6566
self.assertIsNone(df)
67+
68+
@patch('predictit_markets.requests.get')
69+
def test_all_markets_success(self, mock_get):
70+
mock_get.return_value.status_code = 200
71+
mock_get.return_value.json.return_value = {
72+
'markets': [
73+
{'id': 123, 'name': 'Market 1'},
74+
{'id': 456, 'name': 'Market 2'},
75+
]
76+
}
77+
78+
df = all_markets()
79+
80+
81+
expected_df = pd.DataFrame([
82+
{'Market ID': 123, 'Market Name': 'Market 1'},
83+
{'Market ID': 456, 'Market Name': 'Market 2'},
84+
])
85+
86+
pd.testing.assert_frame_equal(df, expected_df)
87+
6688

6789
if __name__ == '__main__':
6890
unittest.main()

0 commit comments

Comments
 (0)