Created
August 27, 2024 22:58
-
-
Save portlandhodl/795e961d4f9870c299a596ce0634e9fa to your computer and use it in GitHub Desktop.
Plotting MTP vs Timestamp Over 10000 Blocks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import csv | |
from datetime import datetime | |
import time | |
import matplotlib.pyplot as plt | |
import pandas as pd | |
# Bitcoin node RPC connection details | |
rpc_user = 'your_rpc_username' | |
rpc_password = 'your_rpc_password' | |
rpc_url = 'http://localhost:8332' | |
def rpc_call(method, params=[]): | |
headers = {'content-type': 'application/json'} | |
payload = { | |
"jsonrpc": "1.0", | |
"id": "curltest", | |
"method": method, | |
"params": params | |
} | |
response = requests.post(rpc_url, json=payload, headers=headers, auth=(rpc_user, rpc_password)) | |
return response.json()['result'] | |
def get_and_write_block_data(start_height, end_height, filename): | |
with open(filename, 'w', newline='') as csvfile: | |
writer = csv.writer(csvfile) | |
writer.writerow(['height', 'block_timestamp', 'mediantime']) | |
for height in range(start_height, end_height + 1): | |
block_hash = rpc_call('getblockhash', [height]) | |
block = rpc_call('getblock', [block_hash]) | |
writer.writerow([height, block['time'], block['mediantime']]) | |
if height % 100 == 0: | |
print(f"Processed block {height}") | |
def plot_data(csv_filename): | |
df = pd.read_csv(csv_filename) | |
df['block_timestamp'] = pd.to_datetime(df['block_timestamp'], unit='s') | |
df['mediantime'] = pd.to_datetime(df['mediantime'], unit='s') | |
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10), sharex=True) | |
ax1.plot(df['height'], df['block_timestamp']) | |
ax1.set_title('Block Timestamp Over Height') | |
ax1.set_ylabel('Block Timestamp') | |
ax1.grid(True) | |
ax2.plot(df['height'], df['mediantime']) | |
ax2.set_title('MTP Value Over Height') | |
ax2.set_xlabel('Block Height') | |
ax2.set_ylabel('MTP Value') | |
ax2.grid(True) | |
plt.tight_layout() | |
plt.savefig('bitcoin_timestamps_and_mtp.png') | |
plt.close() | |
print("Plot saved as 'bitcoin_timestamps_and_mtp.png'") | |
def main(): | |
current_height = rpc_call('getblockcount') | |
start_height = max(0, current_height - 10000) | |
filename = f'bitcoin_data_{int(time.time())}.csv' | |
get_and_write_block_data(start_height, current_height, filename) | |
print(f"Data saved to {filename}") | |
plot_data(filename) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment